{"text":"\/*\n * Copyright 2011 Marco Martin \n * Copyright 2014 Aleix Pol Gonzalez \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2, 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 Library General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"desktopicon.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\nclass ManagedTextureNode : public QSGSimpleTextureNode\n{\nQ_DISABLE_COPY(ManagedTextureNode)\npublic:\n ManagedTextureNode();\n\n void setTexture(QSharedPointer texture);\n\nprivate:\n QSharedPointer m_texture;\n};\n\nManagedTextureNode::ManagedTextureNode()\n{}\n\nvoid ManagedTextureNode::setTexture(QSharedPointer texture)\n{\n m_texture = texture;\n QSGSimpleTextureNode::setTexture(texture.data());\n}\n\ntypedef QHash > > TexturesCache;\n\nstruct ImageTexturesCachePrivate\n{\n TexturesCache cache;\n};\n\nclass ImageTexturesCache\n{\npublic:\n ImageTexturesCache();\n ~ImageTexturesCache();\n\n \/**\n * @returns the texture for a given @p window and @p image.\n *\n * If an @p image id is the same as one already provided before, we won't create\n * a new texture and return a shared pointer to the existing texture.\n *\/\n QSharedPointer loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options);\n\n QSharedPointer loadTexture(QQuickWindow *window, const QImage &image);\n\n\nprivate:\n QScopedPointer d;\n};\n\n\nImageTexturesCache::ImageTexturesCache()\n : d(new ImageTexturesCachePrivate)\n{\n}\n\nImageTexturesCache::~ImageTexturesCache()\n{\n}\n\nQSharedPointer ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options)\n{\n qint64 id = image.cacheKey();\n QSharedPointer texture = d->cache.value(id).value(window).toStrongRef();\n\n if (!texture) {\n auto cleanAndDelete = [this, window, id](QSGTexture* texture) {\n QHash >& textures = (d->cache)[id];\n textures.remove(window);\n if (textures.isEmpty())\n d->cache.remove(id);\n delete texture;\n };\n texture = QSharedPointer(window->createTextureFromImage(image, options), cleanAndDelete);\n (d->cache)[id][window] = texture.toWeakRef();\n }\n\n \/\/if we have a cache in an atlas but our request cannot use an atlassed texture\n \/\/create a new texture and use that\n \/\/don't use removedFromAtlas() as that requires keeping a reference to the non atlased version\n if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) {\n texture = QSharedPointer(window->createTextureFromImage(image, options));\n }\n\n return texture;\n}\n\nQSharedPointer ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image)\n{\n return loadTexture(window, image, 0);\n}\n\nQ_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache)\n\nDesktopIcon::DesktopIcon(QQuickItem *parent)\n : QQuickItem(parent),\n m_smooth(false),\n m_changed(false),\n m_active(false),\n m_selected(false)\n{\n setFlag(ItemHasContents, true);\n connect(qApp, &QGuiApplication::paletteChanged, this, [this]() {\n m_changed = true;\n update();\n });\n}\n\n\nDesktopIcon::~DesktopIcon()\n{\n}\n\nvoid DesktopIcon::setSource(const QVariant &icon)\n{\n if (m_source == icon) {\n return;\n }\n m_source = icon;\n m_changed = true;\n update();\n emit sourceChanged();\n}\n\nQVariant DesktopIcon::source() const\n{\n return m_source;\n}\n\nvoid DesktopIcon::setEnabled(const bool enabled)\n{\n if (enabled == QQuickItem::isEnabled()) {\n return;\n }\n QQuickItem::setEnabled(enabled);\n m_changed = true;\n update();\n emit enabledChanged();\n}\n\n\nvoid DesktopIcon::setActive(const bool active)\n{\n if (active == m_active) {\n return;\n }\n m_active = active;\n m_changed = true;\n update();\n emit activeChanged();\n}\n\nbool DesktopIcon::active() const\n{\n return m_active;\n}\n\nbool DesktopIcon::valid() const\n{\n return !m_source.isNull();\n}\n\nvoid DesktopIcon::setSelected(const bool selected)\n{\n if (selected == m_selected) {\n return;\n }\n m_selected = selected;\n m_changed = true;\n update();\n emit selectedChanged();\n}\n\nbool DesktopIcon::selected() const\n{\n return m_selected;\n}\n\nint DesktopIcon::implicitWidth() const\n{\n return 32;\n}\n\nint DesktopIcon::implicitHeight() const\n{\n return 32;\n}\n\nvoid DesktopIcon::setSmooth(const bool smooth)\n{\n if (smooth == m_smooth) {\n return;\n }\n m_smooth = smooth;\n m_changed = true;\n update();\n emit smoothChanged();\n}\n\nbool DesktopIcon::smooth() const\n{\n return m_smooth;\n}\n\nQSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* \/*data*\/)\n{\n if (m_source.isNull()) {\n delete node;\n return Q_NULLPTR;\n }\n\n if (m_changed || node == 0) {\n QImage img;\n const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio());\n\n switch(m_source.type()){\n case QVariant::Pixmap:\n img = m_source.value().toImage();\n break;\n case QVariant::Image:\n img = m_source.value();\n break;\n case QVariant::Bitmap:\n img = m_source.value().toImage();\n break;\n case QVariant::Icon:\n img = m_source.value().pixmap(size, iconMode(), QIcon::On).toImage();\n break;\n case QVariant::String:\n img = findIcon(size);\n break;\n case QVariant::Brush:\n case QVariant::Color:\n \/\/perhaps fill image instead?\n default:\n break;\n }\n\n if (img.isNull()){\n img = QImage(size, QImage::Format_Alpha8);\n img.fill(Qt::transparent);\n }\n if (img.size() != size){\n img = img.scaled(size, Qt::KeepAspectRatioByExpanding, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation );\n }\n m_changed = false;\n\n ManagedTextureNode* mNode = dynamic_cast(node);\n if (!mNode) {\n delete node;\n mNode = new ManagedTextureNode;\n }\n\n mNode->setTexture(s_iconImageCache->loadTexture(window(), img));\n mNode->setRect(QRect(QPoint(0,0), QSize(width(), height())));\n node = mNode;\n }\n\n return node;\n}\n\nvoid DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)\n{\n if (newGeometry.size() != oldGeometry.size()) {\n m_changed = true;\n update();\n }\n QQuickItem::geometryChanged(newGeometry, oldGeometry);\n}\n\nvoid DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) {\n if (reply->error() == QNetworkReply::NoError) {\n const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();\n if (!possibleRedirectUrl.isEmpty()) {\n const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl);\n if (redirectUrl == reply->url()) {\n \/\/ no infinite redirections thank you very much\n reply->deleteLater();\n return;\n }\n reply->deleteLater();\n QNetworkRequest request(possibleRedirectUrl);\n request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QNetworkReply* newReply = qnam->get(request);\n connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); });\n connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); });\n return;\n }\n }\n}\n\nvoid DesktopIcon::handleReadyRead(QNetworkReply* reply)\n{\n if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) {\n \/\/ We're handing the event loop back while doing network work, and it turns out\n \/\/ this fairly regularly results in things being deleted under us. So, just\n \/\/ handle that and crash less :)\n QPointer me(this);\n QByteArray data;\n do {\n data.append(reply->read(32768));\n \/\/ Because we are in the main thread, this could be potentially very expensive, so let's not block\n qApp->processEvents();\n if(!me) {\n return;\n }\n } while(!reply->atEnd());\n m_loadedImage = QImage::fromData(data);\n if (m_loadedImage.isNull()) {\n \/\/ broken image from data, inform the user of this with some useful broken-image thing...\n const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio());\n m_loadedImage = QIcon::fromTheme(\"unknown\").pixmap(size, iconMode(), QIcon::On).toImage();\n }\n m_changed = true;\n update();\n }\n}\n\nQImage DesktopIcon::findIcon(const QSize &size)\n{\n QImage img;\n QString iconSource = m_source.toString();\n if (iconSource.startsWith(\"image:\/\/\")){\n QUrl iconUrl(iconSource);\n QString iconProviderId = iconUrl.host();\n QString iconId = iconUrl.path();\n QSize actualSize;\n QQuickImageProvider* imageProvider = dynamic_cast(\n qmlEngine(this)->imageProvider(iconProviderId));\n if (!imageProvider)\n return img;\n switch(imageProvider->imageType()){\n case QQmlImageProviderBase::Image:\n img = imageProvider->requestImage(iconId, &actualSize, size);\n break;\n case QQmlImageProviderBase::Pixmap:\n img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage();\n break;\n case QQmlImageProviderBase::Texture:\n case QQmlImageProviderBase::Invalid:\n case QQmlImageProviderBase::ImageResponse:\n \/\/will have to investigate this more\n break;\n }\n } else if(iconSource.startsWith(\"http:\/\/\") || iconSource.startsWith(\"https:\/\/\")) {\n if(!m_loadedImage.isNull()) {\n return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation );\n }\n QQmlEngine* engine = qmlEngine(this);\n QNetworkAccessManager* qnam;\n if (engine && (qnam = qmlEngine(this)->networkAccessManager())) {\n QNetworkRequest request(m_source.toUrl());\n request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QNetworkReply* reply = qnam->get(request);\n connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); });\n connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); });\n }\n \/\/ Temporary icon while we wait for the real image to load...\n img = QIcon::fromTheme(\"image-x-icon\").pixmap(size, iconMode(), QIcon::On).toImage();\n } else {\n if (iconSource.startsWith(\"qrc:\/\")){\n iconSource = iconSource.mid(3);\n }\n QIcon icon(iconSource);\n if (icon.availableSizes().isEmpty()) {\n icon = QIcon::fromTheme(iconSource);\n }\n if (!icon.availableSizes().isEmpty()){\n img = icon.pixmap(size, iconMode(), QIcon::On).toImage();\n }\n }\n return img;\n}\n\nQIcon::Mode DesktopIcon::iconMode() const\n{\n if (!isEnabled()) {\n return QIcon::Disabled;\n } else if (m_selected) {\n return QIcon::Selected;\n } else if (m_active) {\n return QIcon::Active;\n }\n return QIcon::Normal;\n}\nAdd a check for whether the item isn't actually visible\/*\n * Copyright 2011 Marco Martin \n * Copyright 2014 Aleix Pol Gonzalez \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2, 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 Library General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"desktopicon.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\nclass ManagedTextureNode : public QSGSimpleTextureNode\n{\nQ_DISABLE_COPY(ManagedTextureNode)\npublic:\n ManagedTextureNode();\n\n void setTexture(QSharedPointer texture);\n\nprivate:\n QSharedPointer m_texture;\n};\n\nManagedTextureNode::ManagedTextureNode()\n{}\n\nvoid ManagedTextureNode::setTexture(QSharedPointer texture)\n{\n m_texture = texture;\n QSGSimpleTextureNode::setTexture(texture.data());\n}\n\ntypedef QHash > > TexturesCache;\n\nstruct ImageTexturesCachePrivate\n{\n TexturesCache cache;\n};\n\nclass ImageTexturesCache\n{\npublic:\n ImageTexturesCache();\n ~ImageTexturesCache();\n\n \/**\n * @returns the texture for a given @p window and @p image.\n *\n * If an @p image id is the same as one already provided before, we won't create\n * a new texture and return a shared pointer to the existing texture.\n *\/\n QSharedPointer loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options);\n\n QSharedPointer loadTexture(QQuickWindow *window, const QImage &image);\n\n\nprivate:\n QScopedPointer d;\n};\n\n\nImageTexturesCache::ImageTexturesCache()\n : d(new ImageTexturesCachePrivate)\n{\n}\n\nImageTexturesCache::~ImageTexturesCache()\n{\n}\n\nQSharedPointer ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image, QQuickWindow::CreateTextureOptions options)\n{\n qint64 id = image.cacheKey();\n QSharedPointer texture = d->cache.value(id).value(window).toStrongRef();\n\n if (!texture) {\n auto cleanAndDelete = [this, window, id](QSGTexture* texture) {\n QHash >& textures = (d->cache)[id];\n textures.remove(window);\n if (textures.isEmpty())\n d->cache.remove(id);\n delete texture;\n };\n texture = QSharedPointer(window->createTextureFromImage(image, options), cleanAndDelete);\n (d->cache)[id][window] = texture.toWeakRef();\n }\n\n \/\/if we have a cache in an atlas but our request cannot use an atlassed texture\n \/\/create a new texture and use that\n \/\/don't use removedFromAtlas() as that requires keeping a reference to the non atlased version\n if (!(options & QQuickWindow::TextureCanUseAtlas) && texture->isAtlasTexture()) {\n texture = QSharedPointer(window->createTextureFromImage(image, options));\n }\n\n return texture;\n}\n\nQSharedPointer ImageTexturesCache::loadTexture(QQuickWindow *window, const QImage &image)\n{\n return loadTexture(window, image, 0);\n}\n\nQ_GLOBAL_STATIC(ImageTexturesCache, s_iconImageCache)\n\nDesktopIcon::DesktopIcon(QQuickItem *parent)\n : QQuickItem(parent),\n m_smooth(false),\n m_changed(false),\n m_active(false),\n m_selected(false)\n{\n setFlag(ItemHasContents, true);\n connect(qApp, &QGuiApplication::paletteChanged, this, [this]() {\n m_changed = true;\n update();\n });\n}\n\n\nDesktopIcon::~DesktopIcon()\n{\n}\n\nvoid DesktopIcon::setSource(const QVariant &icon)\n{\n if (m_source == icon) {\n return;\n }\n m_source = icon;\n m_changed = true;\n update();\n emit sourceChanged();\n}\n\nQVariant DesktopIcon::source() const\n{\n return m_source;\n}\n\nvoid DesktopIcon::setEnabled(const bool enabled)\n{\n if (enabled == QQuickItem::isEnabled()) {\n return;\n }\n QQuickItem::setEnabled(enabled);\n m_changed = true;\n update();\n emit enabledChanged();\n}\n\n\nvoid DesktopIcon::setActive(const bool active)\n{\n if (active == m_active) {\n return;\n }\n m_active = active;\n m_changed = true;\n update();\n emit activeChanged();\n}\n\nbool DesktopIcon::active() const\n{\n return m_active;\n}\n\nbool DesktopIcon::valid() const\n{\n return !m_source.isNull();\n}\n\nvoid DesktopIcon::setSelected(const bool selected)\n{\n if (selected == m_selected) {\n return;\n }\n m_selected = selected;\n m_changed = true;\n update();\n emit selectedChanged();\n}\n\nbool DesktopIcon::selected() const\n{\n return m_selected;\n}\n\nint DesktopIcon::implicitWidth() const\n{\n return 32;\n}\n\nint DesktopIcon::implicitHeight() const\n{\n return 32;\n}\n\nvoid DesktopIcon::setSmooth(const bool smooth)\n{\n if (smooth == m_smooth) {\n return;\n }\n m_smooth = smooth;\n m_changed = true;\n update();\n emit smoothChanged();\n}\n\nbool DesktopIcon::smooth() const\n{\n return m_smooth;\n}\n\nQSGNode* DesktopIcon::updatePaintNode(QSGNode* node, QQuickItem::UpdatePaintNodeData* \/*data*\/)\n{\n if (m_source.isNull()) {\n delete node;\n return Q_NULLPTR;\n }\n\n if (m_changed || node == 0) {\n QImage img;\n const QSize itemSize(width(), height());\n\n if (itemSize.width() != 0 && itemSize.height() != 0) {\n const QSize size = itemSize * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio());\n\n switch(m_source.type()){\n case QVariant::Pixmap:\n img = m_source.value().toImage();\n break;\n case QVariant::Image:\n img = m_source.value();\n break;\n case QVariant::Bitmap:\n img = m_source.value().toImage();\n break;\n case QVariant::Icon:\n img = m_source.value().pixmap(size, iconMode(), QIcon::On).toImage();\n break;\n case QVariant::String:\n img = findIcon(size);\n break;\n case QVariant::Brush:\n case QVariant::Color:\n \/\/perhaps fill image instead?\n default:\n break;\n }\n\n if (img.isNull()){\n img = QImage(size, QImage::Format_Alpha8);\n img.fill(Qt::transparent);\n }\n if (img.size() != size){\n img = img.scaled(size, Qt::KeepAspectRatioByExpanding, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation );\n }\n }\n m_changed = false;\n\n ManagedTextureNode* mNode = dynamic_cast(node);\n if (!mNode) {\n delete node;\n mNode = new ManagedTextureNode;\n }\n mNode->setTexture(s_iconImageCache->loadTexture(window(), img));\n mNode->setRect(QRect(QPoint(0,0), itemSize));\n node = mNode;\n }\n\n return node;\n}\n\nvoid DesktopIcon::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)\n{\n if (newGeometry.size() != oldGeometry.size()) {\n m_changed = true;\n update();\n }\n QQuickItem::geometryChanged(newGeometry, oldGeometry);\n}\n\nvoid DesktopIcon::handleFinished(QNetworkAccessManager* qnam, QNetworkReply* reply) {\n if (reply->error() == QNetworkReply::NoError) {\n const QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();\n if (!possibleRedirectUrl.isEmpty()) {\n const QUrl redirectUrl = reply->url().resolved(possibleRedirectUrl);\n if (redirectUrl == reply->url()) {\n \/\/ no infinite redirections thank you very much\n reply->deleteLater();\n return;\n }\n reply->deleteLater();\n QNetworkRequest request(possibleRedirectUrl);\n request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QNetworkReply* newReply = qnam->get(request);\n connect(newReply, &QNetworkReply::readyRead, this, [this, newReply](){ handleReadyRead(newReply); });\n connect(newReply, &QNetworkReply::finished, this, [this, qnam, newReply](){ handleFinished(qnam, newReply); });\n return;\n }\n }\n}\n\nvoid DesktopIcon::handleReadyRead(QNetworkReply* reply)\n{\n if (reply->attribute(QNetworkRequest::RedirectionTargetAttribute).isNull()) {\n \/\/ We're handing the event loop back while doing network work, and it turns out\n \/\/ this fairly regularly results in things being deleted under us. So, just\n \/\/ handle that and crash less :)\n QPointer me(this);\n QByteArray data;\n do {\n data.append(reply->read(32768));\n \/\/ Because we are in the main thread, this could be potentially very expensive, so let's not block\n qApp->processEvents();\n if(!me) {\n return;\n }\n } while(!reply->atEnd());\n m_loadedImage = QImage::fromData(data);\n if (m_loadedImage.isNull()) {\n \/\/ broken image from data, inform the user of this with some useful broken-image thing...\n const QSize size = QSize(width(), height()) * (window() ? window()->devicePixelRatio() : qApp->devicePixelRatio());\n m_loadedImage = QIcon::fromTheme(\"unknown\").pixmap(size, iconMode(), QIcon::On).toImage();\n }\n m_changed = true;\n update();\n }\n}\n\nQImage DesktopIcon::findIcon(const QSize &size)\n{\n QImage img;\n QString iconSource = m_source.toString();\n if (iconSource.startsWith(\"image:\/\/\")){\n QUrl iconUrl(iconSource);\n QString iconProviderId = iconUrl.host();\n QString iconId = iconUrl.path();\n QSize actualSize;\n QQuickImageProvider* imageProvider = dynamic_cast(\n qmlEngine(this)->imageProvider(iconProviderId));\n if (!imageProvider)\n return img;\n switch(imageProvider->imageType()){\n case QQmlImageProviderBase::Image:\n img = imageProvider->requestImage(iconId, &actualSize, size);\n break;\n case QQmlImageProviderBase::Pixmap:\n img = imageProvider->requestPixmap(iconId, &actualSize, size).toImage();\n break;\n case QQmlImageProviderBase::Texture:\n case QQmlImageProviderBase::Invalid:\n case QQmlImageProviderBase::ImageResponse:\n \/\/will have to investigate this more\n break;\n }\n } else if(iconSource.startsWith(\"http:\/\/\") || iconSource.startsWith(\"https:\/\/\")) {\n if(!m_loadedImage.isNull()) {\n return m_loadedImage.scaled(size, Qt::KeepAspectRatio, m_smooth ? Qt::SmoothTransformation : Qt::FastTransformation );\n }\n QQmlEngine* engine = qmlEngine(this);\n QNetworkAccessManager* qnam;\n if (engine && (qnam = qmlEngine(this)->networkAccessManager())) {\n QNetworkRequest request(m_source.toUrl());\n request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n QNetworkReply* reply = qnam->get(request);\n connect(reply, &QNetworkReply::readyRead, this, [this, reply](){ handleReadyRead(reply); });\n connect(reply, &QNetworkReply::finished, this, [this, qnam, reply](){ handleFinished(qnam, reply); });\n }\n \/\/ Temporary icon while we wait for the real image to load...\n img = QIcon::fromTheme(\"image-x-icon\").pixmap(size, iconMode(), QIcon::On).toImage();\n } else {\n if (iconSource.startsWith(\"qrc:\/\")){\n iconSource = iconSource.mid(3);\n }\n QIcon icon(iconSource);\n if (icon.availableSizes().isEmpty()) {\n icon = QIcon::fromTheme(iconSource);\n }\n if (!icon.availableSizes().isEmpty()){\n img = icon.pixmap(size, iconMode(), QIcon::On).toImage();\n }\n }\n return img;\n}\n\nQIcon::Mode DesktopIcon::iconMode() const\n{\n if (!isEnabled()) {\n return QIcon::Disabled;\n } else if (m_selected) {\n return QIcon::Selected;\n } else if (m_active) {\n return QIcon::Active;\n }\n return QIcon::Normal;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"TCanvas.h\"\n#include \"TFile.h\"\n#include \"TH2.h\"\n#include \"TStyle.h\"\n\n#include \"core\/utils\/unit.h\"\n#include \"tools\/field_parser.h\"\n\nusing namespace allpix;\nint main(int argc, char** argv) {\n \/\/ Set ROOT params\n gStyle->SetOptStat(0);\n gStyle->SetNumberContours(999);\n\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Read parameters\n std::string file_name;\n std::string output_file_name;\n std::string output_name_log;\n std::string plane = \"yz\";\n std::string units;\n bool flag_cut = false;\n size_t slice_cut = 0;\n bool log_scale = false;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"-f\") == 0 && (i + 1 < argc)) {\n file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n output_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-p\") == 0 && (i + 1 < argc)) {\n plane = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-u\") == 0 && (i + 1 < argc)) {\n units = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n slice_cut = static_cast(std::atoi(argv[++i]));\n flag_cut = true;\n } else if(strcmp(argv[i], \"-l\") == 0) {\n log_scale = true;\n } else {\n std::cout << \"Unrecognized command line argument or missing value\\\"\" << argv[i] << std::endl;\n print_help = true;\n return_code = 1;\n }\n }\n\n if(file_name.empty()) {\n print_help = true;\n return_code = 1;\n }\n\n if(print_help) {\n std::cerr << \"Usage: mesh_plotter -f []\" << std::endl;\n std::cout << \"Required parameters:\" << std::endl;\n std::cout << \"\\t -f name of the interpolated file in INIT or APF format\" << std::endl;\n std::cout << \"Optional parameters:\" << std::endl;\n std::cout << \"\\t -c projection height index (default is mesh_pitch \/ 2)\" << std::endl;\n std::cout << \"\\t -h display this help text\" << std::endl;\n std::cout << \"\\t -l plot with logarithmic scale if set\" << std::endl;\n std::cout << \"\\t -o name of the file to output (default is efield.png)\" << std::endl;\n std::cout << \"\\t -p plane to be ploted. xy, yz or zx (default is yz)\" << std::endl;\n std::cout << \"\\t -u units to interpret the field data in\" << std::endl;\n return return_code;\n }\n\n \/\/ Read file\n std::cout << \"Welcome to the Mesh Plotter Tool of Allpix^2 \" << ALLPIX_PROJECT_VERSION << std::endl;\n std::cout << \"Reading file: \" << file_name;\n\n size_t firstindex = file_name.find_last_of('_');\n size_t lastindex = file_name.find_last_of('.');\n std::string observable = file_name.substr(firstindex + 1, lastindex - (firstindex + 1));\n std::string extension = file_name.substr(lastindex + 1, file_name.size() - lastindex);\n\n \/\/ FIXME this should be done in a more elegant way\n FieldQuantity quantity = (observable == \"ElectricField\" ? FieldQuantity::VECTOR : FieldQuantity::SCALAR);\n FileType type = (extension == \"apf\" ? FileType::APF : FileType::INIT);\n\n FieldParser field_parser(quantity);\n auto field_data = field_parser.get_by_file_name(file_name, type, units);\n size_t xdiv = field_data.getDimensions()[0], ydiv = field_data.getDimensions()[1], zdiv = field_data.getDimensions()[2];\n\n std::cout << \"Number of divisions in x\/y\/z: \" << xdiv << \"\/\" << ydiv << \"\/\" << zdiv << std::endl;\n\n \/\/ Find plotting indices\n int x_bin = 0;\n int y_bin = 0;\n size_t start_x = 0, start_y = 0, start_z = 0;\n size_t stop_x = xdiv, stop_y = ydiv, stop_z = zdiv;\n if(plane == \"xy\") {\n if(!flag_cut) {\n slice_cut = (zdiv + 1) \/ 2;\n }\n\n \/\/ z is the slice:\n start_z = slice_cut;\n stop_z = start_z + 1;\n\n \/\/ scale the plot axes:\n x_bin = static_cast(xdiv);\n y_bin = static_cast(ydiv);\n } else if(plane == \"yz\") {\n if(!flag_cut) {\n slice_cut = (xdiv + 1) \/ 2;\n }\n\n \/\/ x is the slice:\n start_x = slice_cut;\n stop_x = start_x + 1;\n\n x_bin = static_cast(ydiv);\n y_bin = static_cast(zdiv);\n } else {\n if(!flag_cut) {\n slice_cut = (ydiv + 1) \/ 2;\n }\n\n \/\/ y is the slice:\n start_y = slice_cut;\n stop_y = start_y + 1;\n\n x_bin = static_cast(zdiv);\n y_bin = static_cast(xdiv);\n }\n\n \/\/ Create and fill histogram\n auto efield_map =\n new TH2D(Form(\"%s\", observable.c_str()), Form(\"%s\", observable.c_str()), x_bin, 1, x_bin + 1, y_bin, 1, y_bin + 1);\n auto exfield_map = new TH2D(Form(\"%s X component\", observable.c_str()),\n Form(\"%s X component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n auto eyfield_map = new TH2D(Form(\"%s Y component\", observable.c_str()),\n Form(\"%s Y component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n auto ezfield_map = new TH2D(Form(\"%s Z component\", observable.c_str()),\n Form(\"%s Z component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n\n auto c1 = new TCanvas();\n\n if(log_scale) {\n c1->SetLogz();\n output_name_log = \"_log\";\n }\n\n int plot_x, plot_y;\n auto data = field_data.getData();\n for(size_t x = start_x; x < stop_x; x++) {\n for(size_t y = start_y; y < stop_y; y++) {\n for(size_t z = start_z; z < stop_z; z++) {\n \/\/ Select the indices for plotting:\n if(plane == \"xy\") {\n plot_x = static_cast(x);\n plot_y = static_cast(y);\n } else if(plane == \"yz\") {\n plot_x = static_cast(y);\n plot_y = static_cast(z);\n } else {\n plot_x = static_cast(z);\n plot_y = static_cast(x);\n }\n\n if(quantity == FieldQuantity::VECTOR) {\n \/\/ Fill field maps for the individual vector components as well as the magnitude\n auto base = x * ydiv * zdiv * 3 + y * zdiv * 3 + z * 3;\n efield_map->Fill(\n plot_x,\n plot_y,\n sqrt(pow(data->at(base + 0), 2) + pow(data->at(base + 1), 2) + pow(data->at(base + 2), 2)));\n exfield_map->Fill(plot_x, plot_y, data->at(base + 0));\n eyfield_map->Fill(plot_x, plot_y, data->at(base + 1));\n ezfield_map->Fill(plot_x, plot_y, data->at(base + 2));\n\n } else {\n \/\/ Fill one map with the scalar quantity\n efield_map->Fill(plot_x, plot_y, data->at(x * ydiv * zdiv + y * zdiv + z));\n }\n }\n }\n }\n\n if(output_file_name.empty()) {\n output_file_name = file_name.substr(0, lastindex);\n output_file_name = output_file_name + \"_\" + plane + \"_\" + std::to_string(slice_cut) + output_name_log + \".png\";\n }\n\n std::string root_file_name = file_name.substr(0, lastindex);\n root_file_name = root_file_name + \"_Interpolation_plots_\" + plane + \"_\" + std::to_string(slice_cut) + \".root\";\n auto* tf = new TFile(root_file_name.c_str(), \"RECREATE\");\n\n if(quantity == FieldQuantity::VECTOR) {\n exfield_map->Write(Form(\"%s X component\", observable.c_str()));\n eyfield_map->Write(Form(\"%s Y component\", observable.c_str()));\n ezfield_map->Write(Form(\"%s Z component\", observable.c_str()));\n }\n\n efield_map->Write(Form(\"%s Norm\", observable.c_str()));\n c1->cd();\n efield_map->Draw(\"colz\");\n c1->SaveAs(output_file_name.c_str());\n tf->Close();\n return 0;\n}\nMeshPlotter: register units#include \n#include \n#include \n#include \n#include \n#include \n#include \"TCanvas.h\"\n#include \"TFile.h\"\n#include \"TH2.h\"\n#include \"TStyle.h\"\n\n#include \"core\/utils\/unit.h\"\n#include \"tools\/field_parser.h\"\n#include \"tools\/units.h\"\n\nusing namespace allpix;\nint main(int argc, char** argv) {\n\n \/\/ Register the default set of units with this executable:\n allpix::register_units();\n\n \/\/ Set ROOT params\n gStyle->SetOptStat(0);\n gStyle->SetNumberContours(999);\n\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Read parameters\n std::string file_name;\n std::string output_file_name;\n std::string output_name_log;\n std::string plane = \"yz\";\n std::string units;\n bool flag_cut = false;\n size_t slice_cut = 0;\n bool log_scale = false;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"-f\") == 0 && (i + 1 < argc)) {\n file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n output_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-p\") == 0 && (i + 1 < argc)) {\n plane = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-u\") == 0 && (i + 1 < argc)) {\n units = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n slice_cut = static_cast(std::atoi(argv[++i]));\n flag_cut = true;\n } else if(strcmp(argv[i], \"-l\") == 0) {\n log_scale = true;\n } else {\n std::cout << \"Unrecognized command line argument or missing value\\\"\" << argv[i] << std::endl;\n print_help = true;\n return_code = 1;\n }\n }\n\n if(file_name.empty()) {\n print_help = true;\n return_code = 1;\n }\n\n if(print_help) {\n std::cerr << \"Usage: mesh_plotter -f []\" << std::endl;\n std::cout << \"Required parameters:\" << std::endl;\n std::cout << \"\\t -f name of the interpolated file in INIT or APF format\" << std::endl;\n std::cout << \"Optional parameters:\" << std::endl;\n std::cout << \"\\t -c projection height index (default is mesh_pitch \/ 2)\" << std::endl;\n std::cout << \"\\t -h display this help text\" << std::endl;\n std::cout << \"\\t -l plot with logarithmic scale if set\" << std::endl;\n std::cout << \"\\t -o name of the file to output (default is efield.png)\" << std::endl;\n std::cout << \"\\t -p plane to be ploted. xy, yz or zx (default is yz)\" << std::endl;\n std::cout << \"\\t -u units to interpret the field data in\" << std::endl;\n return return_code;\n }\n\n \/\/ Read file\n std::cout << \"Welcome to the Mesh Plotter Tool of Allpix^2 \" << ALLPIX_PROJECT_VERSION << std::endl;\n std::cout << \"Reading file: \" << file_name;\n\n size_t firstindex = file_name.find_last_of('_');\n size_t lastindex = file_name.find_last_of('.');\n std::string observable = file_name.substr(firstindex + 1, lastindex - (firstindex + 1));\n std::string extension = file_name.substr(lastindex + 1, file_name.size() - lastindex);\n\n \/\/ FIXME this should be done in a more elegant way\n FieldQuantity quantity = (observable == \"ElectricField\" ? FieldQuantity::VECTOR : FieldQuantity::SCALAR);\n FileType type = (extension == \"apf\" ? FileType::APF : FileType::INIT);\n\n FieldParser field_parser(quantity);\n auto field_data = field_parser.get_by_file_name(file_name, type, units);\n size_t xdiv = field_data.getDimensions()[0], ydiv = field_data.getDimensions()[1], zdiv = field_data.getDimensions()[2];\n\n std::cout << \"Number of divisions in x\/y\/z: \" << xdiv << \"\/\" << ydiv << \"\/\" << zdiv << std::endl;\n\n \/\/ Find plotting indices\n int x_bin = 0;\n int y_bin = 0;\n size_t start_x = 0, start_y = 0, start_z = 0;\n size_t stop_x = xdiv, stop_y = ydiv, stop_z = zdiv;\n if(plane == \"xy\") {\n if(!flag_cut) {\n slice_cut = (zdiv + 1) \/ 2;\n }\n\n \/\/ z is the slice:\n start_z = slice_cut;\n stop_z = start_z + 1;\n\n \/\/ scale the plot axes:\n x_bin = static_cast(xdiv);\n y_bin = static_cast(ydiv);\n } else if(plane == \"yz\") {\n if(!flag_cut) {\n slice_cut = (xdiv + 1) \/ 2;\n }\n\n \/\/ x is the slice:\n start_x = slice_cut;\n stop_x = start_x + 1;\n\n x_bin = static_cast(ydiv);\n y_bin = static_cast(zdiv);\n } else {\n if(!flag_cut) {\n slice_cut = (ydiv + 1) \/ 2;\n }\n\n \/\/ y is the slice:\n start_y = slice_cut;\n stop_y = start_y + 1;\n\n x_bin = static_cast(zdiv);\n y_bin = static_cast(xdiv);\n }\n\n \/\/ Create and fill histogram\n auto efield_map =\n new TH2D(Form(\"%s\", observable.c_str()), Form(\"%s\", observable.c_str()), x_bin, 1, x_bin + 1, y_bin, 1, y_bin + 1);\n auto exfield_map = new TH2D(Form(\"%s X component\", observable.c_str()),\n Form(\"%s X component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n auto eyfield_map = new TH2D(Form(\"%s Y component\", observable.c_str()),\n Form(\"%s Y component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n auto ezfield_map = new TH2D(Form(\"%s Z component\", observable.c_str()),\n Form(\"%s Z component\", observable.c_str()),\n x_bin + 1,\n 1,\n x_bin + 1,\n y_bin + 1,\n 1,\n y_bin + 1);\n\n auto c1 = new TCanvas();\n\n if(log_scale) {\n c1->SetLogz();\n output_name_log = \"_log\";\n }\n\n int plot_x, plot_y;\n auto data = field_data.getData();\n for(size_t x = start_x; x < stop_x; x++) {\n for(size_t y = start_y; y < stop_y; y++) {\n for(size_t z = start_z; z < stop_z; z++) {\n \/\/ Select the indices for plotting:\n if(plane == \"xy\") {\n plot_x = static_cast(x);\n plot_y = static_cast(y);\n } else if(plane == \"yz\") {\n plot_x = static_cast(y);\n plot_y = static_cast(z);\n } else {\n plot_x = static_cast(z);\n plot_y = static_cast(x);\n }\n\n if(quantity == FieldQuantity::VECTOR) {\n \/\/ Fill field maps for the individual vector components as well as the magnitude\n auto base = x * ydiv * zdiv * 3 + y * zdiv * 3 + z * 3;\n efield_map->Fill(\n plot_x,\n plot_y,\n sqrt(pow(data->at(base + 0), 2) + pow(data->at(base + 1), 2) + pow(data->at(base + 2), 2)));\n exfield_map->Fill(plot_x, plot_y, data->at(base + 0));\n eyfield_map->Fill(plot_x, plot_y, data->at(base + 1));\n ezfield_map->Fill(plot_x, plot_y, data->at(base + 2));\n\n } else {\n \/\/ Fill one map with the scalar quantity\n efield_map->Fill(plot_x, plot_y, data->at(x * ydiv * zdiv + y * zdiv + z));\n }\n }\n }\n }\n\n if(output_file_name.empty()) {\n output_file_name = file_name.substr(0, lastindex);\n output_file_name = output_file_name + \"_\" + plane + \"_\" + std::to_string(slice_cut) + output_name_log + \".png\";\n }\n\n std::string root_file_name = file_name.substr(0, lastindex);\n root_file_name = root_file_name + \"_Interpolation_plots_\" + plane + \"_\" + std::to_string(slice_cut) + \".root\";\n auto* tf = new TFile(root_file_name.c_str(), \"RECREATE\");\n\n if(quantity == FieldQuantity::VECTOR) {\n exfield_map->Write(Form(\"%s X component\", observable.c_str()));\n eyfield_map->Write(Form(\"%s Y component\", observable.c_str()));\n ezfield_map->Write(Form(\"%s Z component\", observable.c_str()));\n }\n\n efield_map->Write(Form(\"%s Norm\", observable.c_str()));\n c1->cd();\n efield_map->Draw(\"colz\");\n c1->SaveAs(output_file_name.c_str());\n tf->Close();\n return 0;\n}\n<|endoftext|>"} {"text":"added informative error dialogs.<|endoftext|>"} {"text":"\/* libs\/graphics\/ports\/SkImageDecoder_Factory.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkMovie.h\"\n#include \"SkStream.h\"\n#include \"SkTRegistry.h\"\n\ntypedef SkTRegistry DecodeReg;\n\ntemplate<> DecodeReg* DecodeReg::gHead;\n\n#ifdef SK_ENABLE_LIBPNG\n extern SkImageDecoder* sk_libpng_dfactory(SkStream*);\n#endif\n\nSkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {\n SkImageDecoder* codec = NULL;\n const DecodeReg* curr = DecodeReg::Head();\n while (curr) {\n codec = curr->factory()(stream);\n \/\/ we rewind here, because we promise later when we call \"decode\", that\n \/\/ the stream will be at its beginning.\n stream->rewind();\n if (codec) {\n return codec;\n }\n curr = curr->next();\n }\n#ifdef SK_ENABLE_LIBPNG\n codec = sk_libpng_dfactory(stream);\n stream->rewind();\n if (codec) {\n return codec;\n }\n#endif\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef SkTRegistry MovieReg;\n\nSkMovie* SkMovie::DecodeStream(SkStream* stream) {\n const MovieReg* curr = MovieReg::Head();\n while (curr) {\n SkMovie* movie = curr->factory()(stream);\n if (movie) {\n return movie;\n }\n \/\/ we must rewind only if we got NULL, since we gave the stream to the\n \/\/ movie, who may have already started reading from it\n stream->rewind();\n curr = curr->next();\n }\n return NULL;\n}\n\nCompile fix for shared library builds.\/* libs\/graphics\/ports\/SkImageDecoder_Factory.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkMovie.h\"\n#include \"SkStream.h\"\n#include \"SkTRegistry.h\"\n\ntypedef SkTRegistry DecodeReg;\n\n\/\/ N.B. You can't use \"DecodeReg::gHead here\" due to complex C++\n\/\/ corner cases.\ntemplate DecodeReg* SkTRegistry::gHead;\n\n#ifdef SK_ENABLE_LIBPNG\n extern SkImageDecoder* sk_libpng_dfactory(SkStream*);\n#endif\n\nSkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {\n SkImageDecoder* codec = NULL;\n const DecodeReg* curr = DecodeReg::Head();\n while (curr) {\n codec = curr->factory()(stream);\n \/\/ we rewind here, because we promise later when we call \"decode\", that\n \/\/ the stream will be at its beginning.\n stream->rewind();\n if (codec) {\n return codec;\n }\n curr = curr->next();\n }\n#ifdef SK_ENABLE_LIBPNG\n codec = sk_libpng_dfactory(stream);\n stream->rewind();\n if (codec) {\n return codec;\n }\n#endif\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef SkTRegistry MovieReg;\n\nSkMovie* SkMovie::DecodeStream(SkStream* stream) {\n const MovieReg* curr = MovieReg::Head();\n while (curr) {\n SkMovie* movie = curr->factory()(stream);\n if (movie) {\n return movie;\n }\n \/\/ we must rewind only if we got NULL, since we gave the stream to the\n \/\/ movie, who may have already started reading from it\n stream->rewind();\n curr = curr->next();\n }\n return NULL;\n}\n\n<|endoftext|>"} {"text":"\n#ifndef __MIRRORED_CACHE_HPP__\n#define __MIRRORED_CACHE_HPP__\n\n#include \"event_queue.hpp\"\n#include \"cpu_context.hpp\"\n#include \"concurrency\/access.hpp\"\n#include \"concurrency\/rwi_lock.hpp\"\n#include \"buffer_cache\/callbacks.hpp\"\n\n\/\/ This cache doesn't actually do any operations itself. Instead, it\n\/\/ provides a framework that collects all components of the cache\n\/\/ (memory allocation, page lookup, page replacement, writeback, etc.)\n\/\/ into a coherent whole. This allows easily experimenting with\n\/\/ various components of the cache to improve performance.\n\n\/* Buffer class. *\/\n\/\/ TODO: make sure we use small object allocator for buf_t\ntemplate \nclass buf : public iocallback_t,\n public config_t::writeback_t::local_buf_t,\n public config_t::concurrency_t::local_buf_t,\n public alloc_mixin_t, buf >\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::transaction_t transaction_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::cache_t cache_t;\n typedef typename config_t::node_t node_t;\n typedef block_available_callback block_available_callback_t;\n\n buf(cache_t *cache, block_id_t block_id);\n ~buf();\n\n void release();\n\n\t\/\/ This function is called by the code that loads the data into the block. Other users, which\n\t\/\/ expect the block to already contain valid data, should call ptr().\n\tvoid *ptr_possibly_uncached() {\n\t\t\/\/ The buf should not be accessed unless it is locked. In fact, pointers to the buf should\n \t\/\/ not exist, except in the page map, unless the block is locked, because any unlocked and\n \t\/\/ non-dirty block is in danger of being swapped out by the page replacement system.\n \tassert(concurrency_t::local_buf_t::lock.locked());\n \treturn data;\n }\n\n \/\/ TODO(NNW) We may want a const version of ptr() as well so the non-const\n \/\/ version can verify that the buf is writable; requires pushing const\n \/\/ through a bunch of other places (such as array_node also, however.\n void *ptr() {\n \tassert(cached);\n \treturn ptr_possibly_uncached();\n }\n\n block_id_t get_block_id() const { return block_id; }\n\n void set_cached(bool _cached) { cached = _cached; }\n bool is_cached() const { return cached; }\n\n void set_dirty() { config_t::writeback_t::local_buf_t::set_dirty(this); }\n\n \/\/ Callback API\n void add_load_callback(block_available_callback_t *callback);\n\n void notify_on_load();\n\n virtual void on_io_complete(event_t *event);\n\nprivate:\n cache_t *cache;\n block_id_t block_id;\n bool cached; \/* Is data valid, or are we waiting for a read? *\/\n void *data;\n \n typedef intrusive_list_t callbacks_t;\n callbacks_t load_callbacks;\n \n \/\/ Incidentally, buf_t holds a redundant pointer to the cache object, because in addition to\n \/\/ the \"cache_t *cache\" declared in buf, writeback_t::local_buf_t declares its own\n \/\/ \"writeback_tmpl_t *writeback\". Each of these pointers will point to a different part of the\n \/\/ same cache object, because mirrored_cache_t is subclassed from writeback_t.\n \n \/\/ It also has a redundant pointer to itself, because concurrency_t::local_buf_t has a field\n \/\/ \"buf_t *gbuf\".\n};\n\n\/* Transaction class. *\/\ntemplate \nclass transaction : public lock_available_callback_t,\n public alloc_mixin_t, transaction >\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::cache_t cache_t;\n typedef typename config_t::buf_t buf_t;\n typedef block_available_callback block_available_callback_t;\n typedef transaction_begin_callback transaction_begin_callback_t;\n typedef transaction_commit_callback transaction_commit_callback_t;\n\n explicit transaction(cache_t *cache, access_t access,\n transaction_begin_callback_t *callback);\n ~transaction();\n\n cache_t *get_cache() const { return cache; }\n access_t get_access() const { return access; }\n\n bool commit(transaction_commit_callback_t *callback);\n\n buf_t *acquire(block_id_t block_id, access_t mode,\n block_available_callback_t *callback);\n buf_t *allocate(block_id_t *new_block_id);\n\n \/* The below function should *only* be called from writeback. *\/\n void committed(transaction_commit_callback_t *callback);\n\nprivate:\n virtual void on_lock_available() { begin_callback->on_txn_begin(this); }\n\n cache_t *cache;\n access_t access;\n transaction_begin_callback_t *begin_callback;\n enum { state_open, state_committing, state_committed } state;\n\npublic:\n#ifndef NDEBUG\n event_queue_t *event_queue; \/\/ For asserts that we haven't changed CPU.\n#endif\n};\n\ntemplate \nstruct mirrored_cache_t : public config_t::serializer_t,\n public config_t::page_map_t,\n public config_t::page_repl_t,\n public config_t::writeback_t,\n public buffer_alloc_t\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::page_repl_t page_repl_t;\n typedef typename config_t::writeback_t writeback_t;\n typedef typename config_t::transaction_t transaction_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::page_map_t page_map_t;\n typedef typename config_t::buf_t buf_t;\n\npublic:\n \/\/ TODO: how do we design communication between cache policies?\n \/\/ Should they all have access to the cache, or should they only\n \/\/ be given access to each other as necessary? The first is more\n \/\/ flexible as anyone can access anyone else, but encourages too\n \/\/ many dependencies. The second is more strict, but might not be\n \/\/ extensible when some policy implementation requires access to\n \/\/ components it wasn't originally given.\n mirrored_cache_t(size_t _block_size, size_t _max_size, bool wait_for_flush,\n unsigned int flush_interval_ms) : \n serializer_t(_block_size),\n page_repl_t(_block_size, _max_size, this, this, this),\n writeback_t(this, wait_for_flush, flush_interval_ms)\n#ifndef NDEBUG\n , n_trans_created(0), n_trans_freed(0),\n n_blocks_acquired(0), n_blocks_released(0)\n#endif\n {}\n ~mirrored_cache_t();\n\n void start() {\n \twriteback_t::start();\n \tpage_repl_t::start();\n }\n void shutdown(sync_callback *cb) {\n \twriteback_t::shutdown(cb);\n \tpage_repl_t::shutdown(cb);\n }\n\n \/\/ Transaction API\n transaction_t *begin_transaction(access_t access,\n transaction_begin_callback *callback);\n\n void aio_complete(buf_t *buf, bool written);\n\n\t\/* do_unload_buf unloads a buf from memory, freeing the buf_t object. It should only be called\n on a buf that is not in use and not dirty. It is called by the cache's destructor and by the\n page replacement policy. *\/\n void do_unload_buf(buf_t *buf);\n\nprivate:\n\t\/\/ TODO: This is boundary-crossing abstraction-breaking treachery. mirrored_cache_t should not\n\t\/\/ mess with the internals of the page map.\n using page_map_t::ft_map;\n\n#ifndef NDEBUG\npublic:\n int n_trans_created, n_trans_freed;\n int n_blocks_acquired, n_blocks_released;\n#endif\n};\n\n#include \"buffer_cache\/mirrored_impl.hpp\"\n\n#endif \/\/ __MIRRORED_CACHE_HPP__\n\nRemoving old todo item\n#ifndef __MIRRORED_CACHE_HPP__\n#define __MIRRORED_CACHE_HPP__\n\n#include \"event_queue.hpp\"\n#include \"cpu_context.hpp\"\n#include \"concurrency\/access.hpp\"\n#include \"concurrency\/rwi_lock.hpp\"\n#include \"buffer_cache\/callbacks.hpp\"\n\n\/\/ This cache doesn't actually do any operations itself. Instead, it\n\/\/ provides a framework that collects all components of the cache\n\/\/ (memory allocation, page lookup, page replacement, writeback, etc.)\n\/\/ into a coherent whole. This allows easily experimenting with\n\/\/ various components of the cache to improve performance.\n\n\/* Buffer class. *\/\ntemplate \nclass buf : public iocallback_t,\n public config_t::writeback_t::local_buf_t,\n public config_t::concurrency_t::local_buf_t,\n public alloc_mixin_t, buf >\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::transaction_t transaction_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::cache_t cache_t;\n typedef typename config_t::node_t node_t;\n typedef block_available_callback block_available_callback_t;\n\n buf(cache_t *cache, block_id_t block_id);\n ~buf();\n\n void release();\n\n\t\/\/ This function is called by the code that loads the data into the block. Other users, which\n\t\/\/ expect the block to already contain valid data, should call ptr().\n\tvoid *ptr_possibly_uncached() {\n\t\t\/\/ The buf should not be accessed unless it is locked. In fact, pointers to the buf should\n \t\/\/ not exist, except in the page map, unless the block is locked, because any unlocked and\n \t\/\/ non-dirty block is in danger of being swapped out by the page replacement system.\n \tassert(concurrency_t::local_buf_t::lock.locked());\n \treturn data;\n }\n\n \/\/ TODO(NNW) We may want a const version of ptr() as well so the non-const\n \/\/ version can verify that the buf is writable; requires pushing const\n \/\/ through a bunch of other places (such as array_node also, however.\n void *ptr() {\n \tassert(cached);\n \treturn ptr_possibly_uncached();\n }\n\n block_id_t get_block_id() const { return block_id; }\n\n void set_cached(bool _cached) { cached = _cached; }\n bool is_cached() const { return cached; }\n\n void set_dirty() { config_t::writeback_t::local_buf_t::set_dirty(this); }\n\n \/\/ Callback API\n void add_load_callback(block_available_callback_t *callback);\n\n void notify_on_load();\n\n virtual void on_io_complete(event_t *event);\n\nprivate:\n cache_t *cache;\n block_id_t block_id;\n bool cached; \/* Is data valid, or are we waiting for a read? *\/\n void *data;\n \n typedef intrusive_list_t callbacks_t;\n callbacks_t load_callbacks;\n \n \/\/ Incidentally, buf_t holds a redundant pointer to the cache object, because in addition to\n \/\/ the \"cache_t *cache\" declared in buf, writeback_t::local_buf_t declares its own\n \/\/ \"writeback_tmpl_t *writeback\". Each of these pointers will point to a different part of the\n \/\/ same cache object, because mirrored_cache_t is subclassed from writeback_t.\n \n \/\/ It also has a redundant pointer to itself, because concurrency_t::local_buf_t has a field\n \/\/ \"buf_t *gbuf\".\n};\n\n\/* Transaction class. *\/\ntemplate \nclass transaction : public lock_available_callback_t,\n public alloc_mixin_t, transaction >\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::cache_t cache_t;\n typedef typename config_t::buf_t buf_t;\n typedef block_available_callback block_available_callback_t;\n typedef transaction_begin_callback transaction_begin_callback_t;\n typedef transaction_commit_callback transaction_commit_callback_t;\n\n explicit transaction(cache_t *cache, access_t access,\n transaction_begin_callback_t *callback);\n ~transaction();\n\n cache_t *get_cache() const { return cache; }\n access_t get_access() const { return access; }\n\n bool commit(transaction_commit_callback_t *callback);\n\n buf_t *acquire(block_id_t block_id, access_t mode,\n block_available_callback_t *callback);\n buf_t *allocate(block_id_t *new_block_id);\n\n \/* The below function should *only* be called from writeback. *\/\n void committed(transaction_commit_callback_t *callback);\n\nprivate:\n virtual void on_lock_available() { begin_callback->on_txn_begin(this); }\n\n cache_t *cache;\n access_t access;\n transaction_begin_callback_t *begin_callback;\n enum { state_open, state_committing, state_committed } state;\n\npublic:\n#ifndef NDEBUG\n event_queue_t *event_queue; \/\/ For asserts that we haven't changed CPU.\n#endif\n};\n\ntemplate \nstruct mirrored_cache_t : public config_t::serializer_t,\n public config_t::page_map_t,\n public config_t::page_repl_t,\n public config_t::writeback_t,\n public buffer_alloc_t\n{\npublic:\n typedef typename config_t::serializer_t serializer_t;\n typedef typename config_t::page_repl_t page_repl_t;\n typedef typename config_t::writeback_t writeback_t;\n typedef typename config_t::transaction_t transaction_t;\n typedef typename config_t::concurrency_t concurrency_t;\n typedef typename config_t::page_map_t page_map_t;\n typedef typename config_t::buf_t buf_t;\n\npublic:\n \/\/ TODO: how do we design communication between cache policies?\n \/\/ Should they all have access to the cache, or should they only\n \/\/ be given access to each other as necessary? The first is more\n \/\/ flexible as anyone can access anyone else, but encourages too\n \/\/ many dependencies. The second is more strict, but might not be\n \/\/ extensible when some policy implementation requires access to\n \/\/ components it wasn't originally given.\n mirrored_cache_t(size_t _block_size, size_t _max_size, bool wait_for_flush,\n unsigned int flush_interval_ms) : \n serializer_t(_block_size),\n page_repl_t(_block_size, _max_size, this, this, this),\n writeback_t(this, wait_for_flush, flush_interval_ms)\n#ifndef NDEBUG\n , n_trans_created(0), n_trans_freed(0),\n n_blocks_acquired(0), n_blocks_released(0)\n#endif\n {}\n ~mirrored_cache_t();\n\n void start() {\n \twriteback_t::start();\n \tpage_repl_t::start();\n }\n void shutdown(sync_callback *cb) {\n \twriteback_t::shutdown(cb);\n \tpage_repl_t::shutdown(cb);\n }\n\n \/\/ Transaction API\n transaction_t *begin_transaction(access_t access,\n transaction_begin_callback *callback);\n\n void aio_complete(buf_t *buf, bool written);\n\n\t\/* do_unload_buf unloads a buf from memory, freeing the buf_t object. It should only be called\n on a buf that is not in use and not dirty. It is called by the cache's destructor and by the\n page replacement policy. *\/\n void do_unload_buf(buf_t *buf);\n\nprivate:\n\t\/\/ TODO: This is boundary-crossing abstraction-breaking treachery. mirrored_cache_t should not\n\t\/\/ mess with the internals of the page map.\n using page_map_t::ft_map;\n\n#ifndef NDEBUG\npublic:\n int n_trans_created, n_trans_freed;\n int n_blocks_acquired, n_blocks_released;\n#endif\n};\n\n#include \"buffer_cache\/mirrored_impl.hpp\"\n\n#endif \/\/ __MIRRORED_CACHE_HPP__\n\n<|endoftext|>"} {"text":"#include \"logger.h\"\n#include \n#include \n#include \n\nnamespace ncv\n{\n logger_t::logger_t(std::ostream& stream, const char* header, bool flush)\n : m_stream(stream), m_flush(flush)\n {\n log_time();\n m_stream << \"[\" << header << \"]\";\n }\n\n logger_t::~logger_t()\n {\n m_flush ? endl() : newl();\n }\n\n logger_t& logger_t::operator<<(const char* str)\n {\n m_stream << str;\n return *this;\n }\n\n logger_t& logger_t::operator<<(std::ostream& (*pf)(std::ostream&))\n {\n (*pf)(m_stream);\n return *this;\n }\n\n logger_t& logger_t::operator<<(logger_t& (*pf)(logger_t&))\n {\n return (*pf)(*this);\n }\n\n logger_t& logger_t::newl()\n {\n m_stream << \"\\n\";\n return *this;\n }\n\n logger_t& logger_t::endl()\n {\n m_stream << std::endl;\n return *this;\n }\n\n logger_t& logger_t::done()\n {\n m_stream << \"<<< program finished correctly >>>\";\n return *this;\n }\n\n logger_t& logger_t::flush()\n {\n m_stream.flush();\n return *this;\n }\n\n void logger_t::log_time()\n {\n std::time_t t = std::time(nullptr);\n {\n \/\/m_stream << \"[\" << std::put_time(std::localtime(&t), \"%c %Z\") << \"] \";\n }\n {\n char buffer[128];\n strftime(buffer, 128, \"%Y:%m:%d %H:%M:%S\", localtime(&t));\n m_stream << \"[\" << buffer << \"]\";\n }\n }\n}\nimprove identation#include \"logger.h\"\n#include \n#include \n#include \n\nnamespace ncv\n{\n logger_t::logger_t(std::ostream& stream, const char* header, bool flush)\n : m_stream(stream), m_flush(flush)\n {\n log_time();\n m_stream << \"[\" << header << \"] \";\n }\n\n logger_t::~logger_t()\n {\n m_flush ? endl() : newl();\n }\n\n logger_t& logger_t::operator<<(const char* str)\n {\n m_stream << str;\n return *this;\n }\n\n logger_t& logger_t::operator<<(std::ostream& (*pf)(std::ostream&))\n {\n (*pf)(m_stream);\n return *this;\n }\n\n logger_t& logger_t::operator<<(logger_t& (*pf)(logger_t&))\n {\n return (*pf)(*this);\n }\n\n logger_t& logger_t::newl()\n {\n m_stream << \"\\n\";\n return *this;\n }\n\n logger_t& logger_t::endl()\n {\n m_stream << std::endl;\n return *this;\n }\n\n logger_t& logger_t::done()\n {\n m_stream << \"<<< program finished correctly >>>\";\n return *this;\n }\n\n logger_t& logger_t::flush()\n {\n m_stream.flush();\n return *this;\n }\n\n void logger_t::log_time()\n {\n std::time_t t = std::time(nullptr);\n {\n \/\/m_stream << \"[\" << std::put_time(std::localtime(&t), \"%c %Z\") << \"] \";\n }\n {\n char buffer[128];\n strftime(buffer, 128, \"%Y:%m:%d %H:%M:%S\", localtime(&t));\n m_stream << \"[\" << buffer << \"]\";\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2010-2014 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\/\/ This is the skeleton for the official flatzinc interpreter. Much\n\/\/ of the funcionnalities are fixed (name of parameters, format of the\n\/\/ input): see http:\/\/www.minizinc.org\/downloads\/doc-1.6\/flatzinc-spec.pdf\n\n#include \/\/ NOLINT\n#include \n#include \n\n#include \"base\/commandlineflags.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/threadpool.h\"\n#include \"base\/timer.h\"\n#include \"flatzinc2\/model.h\"\n#include \"flatzinc2\/parser.h\"\n#include \"flatzinc2\/presolve.h\"\n#include \"flatzinc2\/search.h\"\n#include \"flatzinc2\/solver.h\"\n\nDEFINE_int32(log_period, 10000000, \"Search log period\");\nDEFINE_bool(all, false, \"Search for all solutions\");\nDEFINE_bool(free, false, \"Ignore search annotations\");\nDEFINE_int32(num_solutions, 0, \"Number of solution to search for\");\nDEFINE_int32(time_limit, 0, \"time limit in ms\");\nDEFINE_int32(workers, 0, \"Number of workers\");\nDEFINE_bool(use_impact, false, \"Use impact based search\");\nDEFINE_double(restart_log_size, -1, \"Restart log size for impact search\");\nDEFINE_int32(luby_restart, -1, \"Luby restart factor, <= 0 = no luby\");\nDEFINE_int32(heuristic_period, 100, \"Period to call heuristics in free search\");\nDEFINE_bool(verbose_impact, false, \"Verbose impact\");\nDEFINE_bool(verbose_mt, false, \"Verbose Multi-Thread\");\nDEFINE_bool(presolve, true, \"Use presolve.\");\n\nDECLARE_bool(fz_logging);\nDECLARE_bool(log_prefix);\nDECLARE_bool(use_sat);\n\nusing operations_research::ThreadPool;\n\nnamespace operations_research {\nvoid Run(const std::string& filename, const FzSolverParameters& parameters,\n FzParallelSupportInterface* parallel_support) {\n WallTimer timer;\n timer.Start();\n std::string problem_name(filename);\n problem_name.resize(problem_name.size() - 4);\n size_t found = problem_name.find_last_of(\"\/\\\\\");\n if (found != std::string::npos) {\n problem_name = problem_name.substr(found + 1);\n }\n FzModel model(problem_name);\n CHECK(ParseFlatzincFile(filename, &model));\n FZLOG << \"File \" << filename << \" parsed in \" << timer.GetInMs() << \" ms\"\n << FZENDL;\n FzPresolver presolve;\n presolve.CleanUpModelForTheCpSolver(&model, FLAGS_use_sat);\n if (FLAGS_presolve) {\n FZLOG << \"Presolve model\" << FZENDL;\n timer.Reset();\n timer.Start();\n presolve.Run(&model);\n FZLOG << \" - done in \" << timer.GetInMs() << \" ms\" << FZENDL;\n }\n FzModelStatistics stats(model);\n stats.PrintStatistics();\n FzSolver solver(model);\n CHECK(solver.Extract());\n solver.Solve(parameters, parallel_support);\n}\n\nvoid SequentialRun(const std::string& filename) {\n FzSolverParameters parameters;\n parameters.all_solutions = FLAGS_all;\n parameters.free_search = FLAGS_free;\n parameters.heuristic_period = FLAGS_heuristic_period;\n parameters.ignore_unknown = false;\n parameters.log_period = FLAGS_log_period;\n parameters.luby_restart = FLAGS_luby_restart;\n parameters.num_solutions = FLAGS_num_solutions;\n parameters.restart_log_size = FLAGS_restart_log_size;\n parameters.threads = FLAGS_workers;\n parameters.time_limit_in_ms = FLAGS_time_limit;\n parameters.use_log = FLAGS_fz_logging;\n parameters.verbose_impact = FLAGS_verbose_impact;\n parameters.worker_id = -1;\n parameters.search_type =\n FLAGS_use_impact ? FzSolverParameters::IBS : FzSolverParameters::DEFAULT;\n\n std::unique_ptr parallel_support(\n operations_research::MakeSequentialSupport(parameters.all_solutions,\n parameters.num_solutions));\n Run(filename, parameters, parallel_support.get());\n}\n\nvoid ParallelRun(char* const file, int worker_id,\n FzParallelSupportInterface* parallel_support) {\n FzSolverParameters parameters;\n parameters.all_solutions = FLAGS_all;\n parameters.heuristic_period = FLAGS_heuristic_period;\n parameters.ignore_unknown = false;\n parameters.log_period = 0;\n parameters.luby_restart = -1;\n parameters.num_solutions = FLAGS_num_solutions;\n parameters.random_seed = worker_id * 10;\n parameters.threads = FLAGS_workers;\n parameters.time_limit_in_ms = FLAGS_time_limit;\n parameters.use_log = false;\n parameters.verbose_impact = false;\n parameters.worker_id = worker_id;\n switch (worker_id) {\n case 0: {\n parameters.free_search = false;\n parameters.search_type = operations_research::FzSolverParameters::DEFAULT;\n parameters.restart_log_size = -1.0;\n break;\n }\n case 1: {\n parameters.free_search = true;\n parameters.search_type =\n operations_research::FzSolverParameters::MIN_SIZE;\n parameters.restart_log_size = -1.0;\n break;\n }\n case 2: {\n parameters.free_search = true;\n parameters.search_type = operations_research::FzSolverParameters::IBS;\n parameters.restart_log_size = FLAGS_restart_log_size;\n break;\n }\n case 3: {\n parameters.free_search = true;\n parameters.search_type =\n operations_research::FzSolverParameters::FIRST_UNBOUND;\n parameters.restart_log_size = -1.0;\n parameters.heuristic_period = 10000000;\n break;\n }\n case 4: {\n parameters.free_search = true;\n parameters.search_type = operations_research::FzSolverParameters::DEFAULT;\n parameters.restart_log_size = -1.0;\n parameters.heuristic_period = 30;\n parameters.run_all_heuristics = true;\n break;\n }\n default: {\n parameters.free_search = true;\n parameters.search_type =\n worker_id % 2 == 0\n ? operations_research::FzSolverParameters::RANDOM_MIN\n : operations_research::FzSolverParameters::RANDOM_MAX;\n parameters.restart_log_size = -1.0;\n parameters.luby_restart = 250;\n }\n }\n Run(file, parameters, parallel_support);\n}\n\nvoid FixAndParseParameters(int* argc, char*** argv) {\n FLAGS_log_prefix = false;\n char all_param[] = \"--all\";\n char free_param[] = \"--free\";\n char workers_param[] = \"--workers\";\n char solutions_param[] = \"--num_solutions\";\n char logging_param[] = \"--fz_logging\";\n char verbose_param[] = \"--fz_verbose\";\n char debug_param[] = \"--fz_debug\";\n for (int i = 1; i < *argc; ++i) {\n if (strcmp((*argv)[i], \"-a\") == 0) {\n (*argv)[i] = all_param;\n }\n if (strcmp((*argv)[i], \"-f\") == 0) {\n (*argv)[i] = free_param;\n }\n if (strcmp((*argv)[i], \"-p\") == 0) {\n (*argv)[i] = workers_param;\n }\n if (strcmp((*argv)[i], \"-n\") == 0) {\n (*argv)[i] = solutions_param;\n }\n if (strcmp((*argv)[i], \"-l\") == 0) {\n (*argv)[i] = logging_param;\n }\n if (strcmp((*argv)[i], \"-v\") == 0) {\n (*argv)[i] = verbose_param;\n }\n if (strcmp((*argv)[i], \"-d\") == 0) {\n (*argv)[i] = debug_param;\n }\n }\n google::ParseCommandLineFlags(argc, argv, true);\n \/\/ Fix the number of solutions.\n if (FLAGS_num_solutions == 0) { \/\/ not specified\n FLAGS_num_solutions = FLAGS_all ? kint32max : 1;\n }\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char** argv) {\n operations_research::FixAndParseParameters(&argc, &argv);\n if (argc <= 1) {\n LOG(ERROR) << \"Usage: \" << argv[0] << \" \";\n exit(EXIT_FAILURE);\n }\n if (FLAGS_workers == 0) {\n operations_research::SequentialRun(argv[1]);\n } else {\n std::unique_ptr\n parallel_support(operations_research::MakeMtSupport(\n FLAGS_all, FLAGS_num_solutions, FLAGS_verbose_mt));\n {\n ThreadPool pool(\"Parallel FlatZinc\", FLAGS_workers);\n pool.StartWorkers();\n for (int w = 0; w < FLAGS_workers; ++w) {\n pool.Add(NewCallback(&operations_research::ParallelRun, argv[1], w,\n parallel_support.get()));\n }\n }\n }\n return 0;\n}\nrevisit fz2's implementation of parallelism\/\/ Copyright 2010-2014 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\/\/ This is the skeleton for the official flatzinc interpreter. Much\n\/\/ of the funcionnalities are fixed (name of parameters, format of the\n\/\/ input): see http:\/\/www.minizinc.org\/downloads\/doc-1.6\/flatzinc-spec.pdf\n\n#include \/\/ NOLINT\n#include \n#include \n\n#include \"base\/commandlineflags.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/threadpool.h\"\n#include \"base\/timer.h\"\n#include \"flatzinc2\/model.h\"\n#include \"flatzinc2\/parser.h\"\n#include \"flatzinc2\/presolve.h\"\n#include \"flatzinc2\/search.h\"\n#include \"flatzinc2\/solver.h\"\n\nDEFINE_int32(log_period, 10000000, \"Search log period\");\nDEFINE_bool(all, false, \"Search for all solutions\");\nDEFINE_bool(free, false, \"Ignore search annotations\");\nDEFINE_int32(num_solutions, 0, \"Number of solution to search for\");\nDEFINE_int32(time_limit, 0, \"time limit in ms\");\nDEFINE_int32(workers, 0, \"Number of workers\");\nDEFINE_bool(use_impact, false, \"Use impact based search\");\nDEFINE_double(restart_log_size, -1, \"Restart log size for impact search\");\nDEFINE_int32(luby_restart, -1, \"Luby restart factor, <= 0 = no luby\");\nDEFINE_int32(heuristic_period, 100, \"Period to call heuristics in free search\");\nDEFINE_bool(verbose_impact, false, \"Verbose impact\");\nDEFINE_bool(verbose_mt, false, \"Verbose Multi-Thread\");\nDEFINE_bool(presolve, true, \"Use presolve.\");\n\nDECLARE_bool(fz_logging);\nDECLARE_bool(log_prefix);\nDECLARE_bool(use_sat);\n\nusing operations_research::ThreadPool;\n\nnamespace operations_research {\nvoid Solve(const FzModel* const model, const FzSolverParameters& parameters,\n FzParallelSupportInterface* parallel_support) {\n FzSolver solver(*model);\n CHECK(solver.Extract());\n solver.Solve(parameters, parallel_support);\n}\n\nvoid SequentialRun(const FzModel* model) {\n FzSolverParameters parameters;\n parameters.all_solutions = FLAGS_all;\n parameters.free_search = FLAGS_free;\n parameters.heuristic_period = FLAGS_heuristic_period;\n parameters.ignore_unknown = false;\n parameters.log_period = FLAGS_log_period;\n parameters.luby_restart = FLAGS_luby_restart;\n parameters.num_solutions = FLAGS_num_solutions;\n parameters.restart_log_size = FLAGS_restart_log_size;\n parameters.threads = FLAGS_workers;\n parameters.time_limit_in_ms = FLAGS_time_limit;\n parameters.use_log = FLAGS_fz_logging;\n parameters.verbose_impact = FLAGS_verbose_impact;\n parameters.worker_id = -1;\n parameters.search_type =\n FLAGS_use_impact ? FzSolverParameters::IBS : FzSolverParameters::DEFAULT;\n\n std::unique_ptr parallel_support(\n MakeSequentialSupport(FLAGS_all, FLAGS_num_solutions));\n Solve(model, parameters, parallel_support.get());\n}\n\nvoid ParallelRun(const FzModel* const model, int worker_id,\n FzParallelSupportInterface* parallel_support) {\n FzSolverParameters parameters;\n parameters.all_solutions = FLAGS_all;\n parameters.heuristic_period = FLAGS_heuristic_period;\n parameters.ignore_unknown = false;\n parameters.log_period = 0;\n parameters.luby_restart = -1;\n parameters.num_solutions = FLAGS_num_solutions;\n parameters.random_seed = worker_id * 10;\n parameters.threads = FLAGS_workers;\n parameters.time_limit_in_ms = FLAGS_time_limit;\n parameters.use_log = false;\n parameters.verbose_impact = false;\n parameters.worker_id = worker_id;\n switch (worker_id) {\n case 0: {\n parameters.free_search = false;\n parameters.search_type = operations_research::FzSolverParameters::DEFAULT;\n parameters.restart_log_size = -1.0;\n break;\n }\n case 1: {\n parameters.free_search = true;\n parameters.search_type =\n operations_research::FzSolverParameters::MIN_SIZE;\n parameters.restart_log_size = -1.0;\n break;\n }\n case 2: {\n parameters.free_search = true;\n parameters.search_type = operations_research::FzSolverParameters::IBS;\n parameters.restart_log_size = FLAGS_restart_log_size;\n break;\n }\n case 3: {\n parameters.free_search = true;\n parameters.search_type =\n operations_research::FzSolverParameters::FIRST_UNBOUND;\n parameters.restart_log_size = -1.0;\n parameters.heuristic_period = 10000000;\n break;\n }\n case 4: {\n parameters.free_search = true;\n parameters.search_type = operations_research::FzSolverParameters::DEFAULT;\n parameters.restart_log_size = -1.0;\n parameters.heuristic_period = 30;\n parameters.run_all_heuristics = true;\n break;\n }\n default: {\n parameters.free_search = true;\n parameters.search_type =\n worker_id % 2 == 0\n ? operations_research::FzSolverParameters::RANDOM_MIN\n : operations_research::FzSolverParameters::RANDOM_MAX;\n parameters.restart_log_size = -1.0;\n parameters.luby_restart = 250;\n }\n }\n Solve(model, parameters, parallel_support);\n}\n\nvoid FixAndParseParameters(int* argc, char*** argv) {\n FLAGS_log_prefix = false;\n char all_param[] = \"--all\";\n char free_param[] = \"--free\";\n char workers_param[] = \"--workers\";\n char solutions_param[] = \"--num_solutions\";\n char logging_param[] = \"--fz_logging\";\n char verbose_param[] = \"--fz_verbose\";\n char debug_param[] = \"--fz_debug\";\n for (int i = 1; i < *argc; ++i) {\n if (strcmp((*argv)[i], \"-a\") == 0) {\n (*argv)[i] = all_param;\n }\n if (strcmp((*argv)[i], \"-f\") == 0) {\n (*argv)[i] = free_param;\n }\n if (strcmp((*argv)[i], \"-p\") == 0) {\n (*argv)[i] = workers_param;\n }\n if (strcmp((*argv)[i], \"-n\") == 0) {\n (*argv)[i] = solutions_param;\n }\n if (strcmp((*argv)[i], \"-l\") == 0) {\n (*argv)[i] = logging_param;\n }\n if (strcmp((*argv)[i], \"-v\") == 0) {\n (*argv)[i] = verbose_param;\n }\n if (strcmp((*argv)[i], \"-d\") == 0) {\n (*argv)[i] = debug_param;\n }\n }\n google::ParseCommandLineFlags(argc, argv, true);\n \/\/ Fix the number of solutions.\n if (FLAGS_num_solutions == 0) { \/\/ not specified\n FLAGS_num_solutions = FLAGS_all ? kint32max : 1;\n }\n}\n\nvoid ParseAndRun(const std::string& filename, int num_workers) {\n WallTimer timer;\n timer.Start();\n std::string problem_name(filename);\n problem_name.resize(problem_name.size() - 4);\n size_t found = problem_name.find_last_of(\"\/\\\\\");\n if (found != std::string::npos) {\n problem_name = problem_name.substr(found + 1);\n }\n FzModel model(problem_name);\n CHECK(ParseFlatzincFile(filename, &model));\n FZLOG << \"File \" << filename << \" parsed in \" << timer.GetInMs() << \" ms\"\n << FZENDL;\n FzPresolver presolve;\n presolve.CleanUpModelForTheCpSolver(&model, FLAGS_use_sat);\n if (FLAGS_presolve) {\n FZLOG << \"Presolve model\" << FZENDL;\n timer.Reset();\n timer.Start();\n presolve.Run(&model);\n FZLOG << \" - done in \" << timer.GetInMs() << \" ms\" << FZENDL;\n }\n FzModelStatistics stats(model);\n stats.PrintStatistics();\n\n if (num_workers == 0) {\n operations_research::SequentialRun(&model);\n } else {\n std::unique_ptr\n parallel_support(operations_research::MakeMtSupport(\n FLAGS_all, FLAGS_num_solutions, FLAGS_verbose_mt));\n {\n ThreadPool pool(\"Parallel FlatZinc\", num_workers);\n for (int w = 0; w < num_workers; ++w) {\n pool.Add(NewCallback(ParallelRun, &model, w, parallel_support.get()));\n }\n pool.StartWorkers();\n }\n }\n}\n} \/\/ namespace operations_research\n\nint main(int argc, char** argv) {\n operations_research::FixAndParseParameters(&argc, &argv);\n if (argc <= 1) {\n LOG(ERROR) << \"Usage: \" << argv[0] << \" \";\n exit(EXIT_FAILURE);\n }\n operations_research::ParseAndRun(argv[1], FLAGS_workers);\n return 0;\n}\n<|endoftext|>"} {"text":"Fix a bug about a flag to revert image.<|endoftext|>"} {"text":"#include \n\n#include \"..\/..\/..\/src\/contents.hh\"\n#include \"..\/..\/..\/src\/key_aliases.hh\"\n#include \"..\/..\/..\/src\/show_message.hh\"\n#include \"..\/..\/vick-move\/src\/move.hh\"\n\nstruct cons3_c : public change {\n std::shared_ptr< change > a, b, c;\n cons3_c(change* a, change* b, change* c) : a(a), b(b), c(c) {}\n\n virtual bool is_overriding() override {\n return a->is_overriding() || b->is_overriding() || c->is_overriding();\n }\n virtual void undo(contents& contents) override {\n a->undo(contents);\n b->undo(contents);\n c->undo(contents);\n }\n virtual void redo(contents& contents) override {\n c->redo(contents);\n b->redo(contents);\n a->redo(contents);\n }\n virtual std::shared_ptr< change >\n regenerate(const contents& contents) const override {\n return std::make_shared< cons3_c >(contents, *a, *b, *c);\n }\n cons3_c(const contents& contents, const change& a, const change& b,\n const change& c)\n : a(a.regenerate(contents)), b(b.regenerate(contents)),\n c(c.regenerate(contents)) {}\n};\n\nstruct insert_c : public change {\n unsigned long y, x;\n insert_c() {}\n\n virtual bool is_overriding() override { return true; }\n virtual void undo(contents& contents) override {\n contents.y = y;\n contents.x = x;\n }\n virtual void redo(contents& contents) override {}\n virtual std::shared_ptr< change >\n regenerate(const contents& contents) const override {}\n};\n\nboost::optional< std::shared_ptr< change > >\nenter_insert_mode(contents& contents, boost::optional< int >) {\n char ch;\n show_message(\"--INSERT--\");\n contents.is_inserting = true;\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n while ((ch = getch()) != _escape) {\n auto event = global_insert_map.find(ch);\n if (event != global_insert_map.end()) {\n event->second(contents, 0);\n } else if (contents.x >= contents.cont[contents.y].size()) {\n contents.cont[contents.y].push_back(ch);\n contents.x = contents.cont[contents.y].size();\n } else {\n contents.cont[contents.y][contents.x] = ch;\n contents.x++;\n }\n if (contents.refresh) {\n print_contents(contents);\n show_message(\"--INSERT--\");\n }\n }\n contents.is_inserting = false;\n showing_message = false;\n return boost::none;\n}\nRemove insert_mode2.cc<|endoftext|>"} {"text":"Added point sources to the new interface<|endoftext|>"} {"text":"\/*\n * MobileTest.cpp\n *\n * Created on: Aug 10, 2013\n * Author: TheAnswer\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/templates\/LootGroupTemplate.h\"\n#include \"server\/zone\/managers\/loot\/LootGroupMap.h\"\n#include \"server\/zone\/managers\/creature\/CreatureTemplateManager.h\"\n#include \"server\/zone\/managers\/loot\/lootgroup\/LootGroupCollectionEntry.h\"\n\nclass LuaMobileTest : public ::testing::Test {\npublic:\n\n\tLuaMobileTest() {\n\t\t\/\/ Perform creation setup here.\n\t}\n\n\t~LuaMobileTest() {\n\t}\n\n\tvoid SetUp() {\n\t\t\/\/ Perform setup of common constructs here.\n\t}\n\n\tvoid TearDown() {\n\t\t\/\/ Perform clean up of common constructs here.\n\t}\n\n\tvoid checkLootGroupEntryRecursive(LootGroupMap* lootGroupMap, String& entryName, Vector* parentGroups) {\n\t\tif (entryName.isEmpty())\n\t\t\treturn;\n\n\t\t\/\/Check for infinite recursion\n\t\tfor (int i = 0; i < parentGroups->size(); i++) {\n\t\t\tString parentName = parentGroups->get(i);\n\n\t\t\tEXPECT_FALSE( parentName == entryName ) << \"Loot group \" << std::string(parentName.toCharArray()) << \" failed recursion check.\";\n\n\t\t\tif (parentName == entryName)\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (lootGroupMap->lootGroupExists(entryName)) {\n\n\t\t\tLootGroupTemplate* lootGroupTemplate = lootGroupMap->getLootGroupTemplate(entryName);\n\n\t\t\tfor (int j = 0; j < lootGroupTemplate->size(); j++) {\n\n\t\t\t\tString entry = lootGroupTemplate->getLootGroupEntryAt(j);\n\n\t\t\t\tparentGroups->add(entryName);\n\n\t\t\t\tcheckLootGroupEntryRecursive(lootGroupMap, entry, parentGroups);\n\t\t\t}\n\n\t\t} else {\n\t\t\tReference itemTemplate = lootGroupMap->getLootItemTemplate( entryName );\n\t\t\tEXPECT_TRUE( itemTemplate != NULL ) << \"Item template \" << std::string(entryName.toCharArray()) << \" from \" << std::string(parentGroups->get(parentGroups->size() - 1).toCharArray()) << \" was not found in LootGroupMap\";\n\t\t}\n\t}\n};\n\nTEST_F(LuaMobileTest, LuaMobileTemplatesTest) {\n\tCreatureTemplateManager::DEBUG_MODE = 1;\n\n\t\/\/ Verify that all mobiles load\n\tASSERT_EQ(CreatureTemplateManager::instance()->loadTemplates(), 0);\n\n\t\/\/ Verify loot group map loads\n\tLootGroupMap* lootGroupMap = LootGroupMap::instance();\n\tASSERT_EQ(lootGroupMap->initialize(), 0);\n\n\t\/\/ Load Templates\n\tASSERT_TRUE( TemplateManager::instance() != NULL );\n\tif( TemplateManager::instance()->loadedTemplatesCount == 0 ){\n\t\tTemplateManager::instance()->loadLuaTemplates();\n\t}\n\n\t\/\/ Test Creature Templates\n\tHashTableIterator > creatureIterator = CreatureTemplateManager::instance()->iterator();\n\twhile (creatureIterator.hasNext()) {\n\t\tCreatureTemplate* creature = creatureIterator.next();\n\t\tstd::string templateName( creature->getTemplateName().toCharArray() );\n\n\t\t\/\/ Check configured templates\n\t\tVector objTemps = creature->getTemplates();\n\t\tEXPECT_FALSE( objTemps.isEmpty() ) << \"Mobile \" << templateName << \" does not have any templates configured\";\n\t\tfor( int j=0; j< objTemps.size(); j++ ){\n\t\t\tSharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate(objTemps.get(j).hashCode());\n\t\t\tstd::string objName = objTemps.get(j).toCharArray();\n\t\t\tEXPECT_TRUE( templateData != NULL ) << \"Mobile \" << templateName << \" has invalid template configured: \" << objName;\n\t\t}\n\n\t\t\/\/ Verify loot group percentages\n\t\tLootGroupCollection* groupCollection = creature->getLootGroups();\n\t\tif( groupCollection->count() > 0 ){\n\n\n\t\t\tfor( int i = 0; i < groupCollection->count(); i++ ){\n\n\t\t\t\tLootGroupCollectionEntry* collectionEntry = groupCollection->get(i);\n\t\t\t\tLootGroups* groups = collectionEntry->getLootGroups();\n\t\t\t\tif( groups->count() > 0){\n\n\t\t\t\t\tint totalChance = 0;\n\t\t\t\t\tfor( int j = 0; j < groups->count(); j++ ){\n\n\t\t\t\t\t\tLootGroupEntry* lootGroup = groups->get(j);\n\t\t\t\t\t\ttotalChance += lootGroup->getLootChance();\n\n\t\t\t\t\t\t\/\/ Verify loot group is configured correctly\n\t\t\t\t\t\tLootGroupTemplate* foundGroup = lootGroupMap->getLootGroupTemplate( lootGroup->getLootGroupName() );\n\t\t\t\t\t\tstd::string groupName( lootGroup->getLootGroupName().toCharArray() );\n\t\t\t\t\t\tEXPECT_TRUE( foundGroup != NULL ) << \"Loot group \" << groupName << \" from \" << templateName << \" was not found in LootGroupMap\";\n\n\t\t\t\t\t}\n\n\t\t\t\t\tEXPECT_EQ( 10000000, totalChance ) << \"Loot groups total chance is incorrect \" << templateName;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify weapon groups exist\n\t\tVector weapons = creature->getWeapons();\n\t\tfor (int i = 0; i < weapons.size(); i++) {\n\t\t\tString weaponGroup = weapons.get(i);\n\t\t\tstd::string groupName( weaponGroup.toCharArray() );\n\t\t\tVector group = CreatureTemplateManager::instance()->getWeapons(weaponGroup);\n\t\t\tEXPECT_TRUE( group.size() > 0 ) << \"Weapon group \" << groupName << \" from \" << templateName << \" was not found in weaponMap\";\n\t\t}\n\n\t\t\/\/ Verify conversation template exist, and the mob has converse option bit\n\t\tuint32 convoTemplate = creature->getConversationTemplate();\n\t\tuint32 optionsBitmask = creature->getOptionsBitmask();\n\t\tif (convoTemplate != 0) {\n\t\t\tConversationTemplate* convoTemp = CreatureTemplateManager::instance()->getConversationTemplate(convoTemplate);\n\t\t\tEXPECT_TRUE( convoTemp != NULL ) << \"Conversation template from \" << templateName << \" was not found.\";\n\t\t\tEXPECT_TRUE( optionsBitmask & OptionBitmask::CONVERSE ) << templateName << \" has a convo template but not the CONVERSE options bit.\";\n\t\t}\n\t}\n\n\t\/\/ Test Lair Templates\n\tHashTableIterator > lairIterator = CreatureTemplateManager::instance()->lairTemplateIterator();\n\twhile (lairIterator.hasNext()) {\n\t\tLairTemplate* lair = lairIterator.next();\n\t\tstd::string templateName( lair->getName().toCharArray() );\n\n\t\t\/\/ Verify that mobiles exist and that their weighting is positive\n\t\tVectorMap* mobiles = lair->getMobiles();\n\t\tfor (int i = 0; i < mobiles->size(); i++) {\n\t\t\tint weighting = mobiles->elementAt(i).getValue();\n\t\t\tString mobile = mobiles->elementAt(i).getKey();\n\t\t\tstd::string mobName = mobile.toCharArray();\n\t\t\tEXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(mobile) != NULL ) << \"Mobile \" << mobName << \" in lair template \" << templateName << \" does not exist\";\n\t\t\tEXPECT_TRUE( weighting > 0 ) << \"Mobile \" << mobName << \" in lair template \" << templateName << \" has a non positive weighting\";\n\t\t}\n\n\t\t\/\/ Verify that boss mobiles exist and that their count is positive\n\t\tVectorMap* bossMobiles = lair->getBossMobiles();\n\t\tfor (int i = 0; i < bossMobiles->size(); i++) {\n\t\t\tint count = bossMobiles->elementAt(i).getValue();\n\t\t\tString bossMob = bossMobiles->elementAt(i).getKey();\n\t\t\tstd::string bossName = bossMob.toCharArray();\n\t\t\tEXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(bossMob) != NULL ) << \"Boss mobile \" << bossName << \" in lair template \" << templateName << \" does not exist\";\n\t\t\tEXPECT_TRUE( count > 0 ) << \"Boss mobile \" << bossName << \" in lair template \" << templateName << \" has a non positive spawn count\";\n\t\t}\n\n\t\t\/\/ Verify spawn limit is positive\n\t\tint limit = lair->getSpawnLimit();\n\t\tEXPECT_TRUE( limit > 0 ) << \"Spawn limit in lair template \" << templateName << \" is not positive\";\n\n\t\t\/\/ Verify any configured buildings exist\n\t\tfor(int i=0; i<=4; i++){\n\n\t\t\tVector* buildings = lair->getBuildings( i );\n\t\t\tif( buildings == NULL )\n\t\t\t\tcontinue;\n\n\t\t\tfor( int j=0; j < buildings->size(); j++ ){\n\t\t\t\tString buildingTemplate = buildings->get(j);\n\t\t\t\tstd::string buildingStr = buildingTemplate.toCharArray();\n\t\t\t\tSharedObjectTemplate* templateObject = TemplateManager::instance()->getTemplate(buildingTemplate.hashCode());\n\t\t\t\tEXPECT_TRUE( templateObject != NULL && templateObject->isSharedTangibleObjectTemplate() ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" does not exist\";\n\t\t\t\tif( lair->getBuildingType() == LairTemplate::LAIR ){\n\t\t\t\t\tEXPECT_TRUE( buildingTemplate.beginsWith( \"object\/tangible\/lair\/\") ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" is not a child of object\/tangible\/lair\/\";\n\t\t\t\t}\n\t\t\t\tif( lair->getBuildingType() == LairTemplate::THEATER ){\n\t\t\t\t\tEXPECT_TRUE( buildingTemplate.beginsWith( \"object\/building\/poi\/\") ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" is not a child of object\/building\/poi\/\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ TODO: Add test to enforce LAIRs and THEATERs have at least one building configured\n\n\t}\n\n\t\/\/ Test Spawn Groups\n\tHashTableIterator > spawnIterator = CreatureTemplateManager::instance()->spawnGroupIterator();\n\twhile (spawnIterator.hasNext()) {\n\t\tSpawnGroup* group = spawnIterator.next();\n\t\tstd::string templateName( group->getTemplateName().toCharArray() );\n\n\t\t\/\/ Verify spawn limit is not negative\n\t\tint limit = group->getMaxSpawnLimit();\n\t\tEXPECT_TRUE( limit >= 0 ) << \"Max spawn limit in spawn group \" << templateName << \" is negative\";\n\n\t\t\/\/ Verify spawn list\n\t\tVector >* spawnList = group->getSpawnList();\n\t\tfor (int i = 0; i < spawnList->size(); i++) {\n\t\t\tLairSpawn* spawn = spawnList->get(i);\n\t\t\tstd::string lairName( spawn->getLairTemplateName().toCharArray() );\n\n\t\t\t\/\/ Verify lair template exists\n\t\t\tString lairTemplateName = spawn->getLairTemplateName();\n\t\t\tReference lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());\n\t\t\tEXPECT_TRUE( lairTemplate != NULL ) << \"Lair template \" << lairName << \" in spawn group \" << templateName << \" does not exist.\";\n\n\t\t\t\/\/ Verify spawn limit is at least -1\n\t\t\tfloat spawnLimit = spawn->getSpawnLimit();\n\t\t\tEXPECT_TRUE( spawnLimit >= -1 ) << \"SpawnLimit for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than -1.\";\n\n\t\t\t\/\/ Verify difficulties\n\t\t\tint minDiff = spawn->getMinDifficulty();\n\t\t\tint maxDiff = spawn->getMaxDifficulty();\n\t\t\tEXPECT_TRUE( minDiff > 0 ) << \"MinDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\t\t\tEXPECT_TRUE( maxDiff >= minDiff ) << \"MaxDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than min difficulty.\";\n\n\t\t\t\/\/ Verify number to spawn is not negative\n\t\t\tint numberToSpawn = spawn->getNumberToSpawn();\n\t\t\tEXPECT_TRUE( numberToSpawn >= 0 ) << \"NumberToSpawn for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is negative.\";\n\n\t\t\t\/\/ Verify weighting is positive\n\t\t\tint weighting = spawn->getWeighting();\n\t\t\tEXPECT_TRUE( weighting > 0 ) << \"Weighting for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\n\t\t\t\/\/ Verify size is at least 1\n\t\t\tfloat size = spawn->getSize();\n\t\t\tEXPECT_TRUE( size >= 1 ) << \"Size for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than 1.\";\n\t\t}\n\t}\n\n\t\/\/ Test Destroy Mission Spawn Groups\n\tHashTableIterator > missionIterator = CreatureTemplateManager::instance()->destroyMissionGroupIterator();\n\twhile (missionIterator.hasNext()) {\n\t\tSpawnGroup* group = missionIterator.next();\n\t\tstd::string templateName( group->getTemplateName().toCharArray() );\n\n\t\t\/\/ Verify spawn list\n\t\tVector >* spawnList = group->getSpawnList();\n\t\tfor (int i = 0; i < spawnList->size(); i++) {\n\t\t\tLairSpawn* spawn = spawnList->get(i);\n\t\t\tstd::string lairName( spawn->getLairTemplateName().toCharArray() );\n\n\t\t\t\/\/ Verify lair template exists\n\t\t\tString lairTemplateName = spawn->getLairTemplateName();\n\t\t\tReference lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());\n\t\t\tEXPECT_TRUE( lairTemplate != NULL ) << \"Lair template \" << lairName << \" in spawn group \" << templateName << \" does not exist.\";\n\n\t\t\t\/\/ Verify difficulties\n\t\t\tint minDiff = spawn->getMinDifficulty();\n\t\t\tint maxDiff = spawn->getMaxDifficulty();\n\t\t\tEXPECT_TRUE( minDiff > 0 ) << \"MinDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\t\t\tEXPECT_TRUE( maxDiff >= minDiff ) << \"MaxDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than min difficulty.\";\n\n\t\t\t\/\/ Verify size is at least 1\n\t\t\tfloat size = spawn->getSize();\n\t\t\tEXPECT_TRUE( size >= 1 ) << \"Size for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than 1.\";\n\t\t}\n\t}\n}\n\nTEST_F(LuaMobileTest, LuaLootGroupsTest) {\n\n\tLootGroupMap* lootGroupMap = LootGroupMap::instance();\n\tASSERT_EQ(lootGroupMap->initialize(), 0);\n\n\t\/\/Make sure that no loot items have the same name as a loot group\n\tHashTableIterator > itemIter = lootGroupMap->itemTemplates.iterator();\n\twhile (itemIter.hasNext()) {\n\n\t\tLootItemTemplate* lootItemTemplate = itemIter.next();\n\t\tString itemTemplateName( lootItemTemplate->getTemplateName().toCharArray() );\n\n\t\tEXPECT_FALSE( lootGroupMap->lootGroupExists(itemTemplateName) ) << \"Loot item \" << std::string(itemTemplateName.toCharArray()) << \" has the same name as a loot group.\";\n\t}\n\n\tHashTableIterator > iter = lootGroupMap->groupTemplates.iterator();\n\twhile (iter.hasNext()) {\n\n\t\tLootGroupTemplate* lootGroupTemplate = iter.next();\n\t\tString groupTemplateName( lootGroupTemplate->getTemplateName().toCharArray() );\n\n\t\t\/\/ Check non-empty loot groups to make sure their chances total correctly\n\t\tif( lootGroupTemplate->getLootGroupEntryForRoll(-1).length() > 0 ){\n\t\t\tEXPECT_GT( lootGroupTemplate->getLootGroupEntryForRoll(10000000).length(), 0 ) << \"Item total chance is less than 10000000: \" << std::string(groupTemplateName.toCharArray());\n\t\t\tEXPECT_EQ( lootGroupTemplate->getLootGroupEntryForRoll(10000001).length(), 0 ) << \"Item total chance is greater than 10000000: \" << std::string(groupTemplateName.toCharArray());\n\t\t}\n\n\t\t\/\/ Check that all loot group entries are valid\n\t\tfor( int i = 0; i < lootGroupTemplate->size(); i++ ){\n\n\t\t\tVector parentGroups;\n\t\t\tparentGroups.add(groupTemplateName);\n\n\t\t\tString entryName = lootGroupTemplate->getLootGroupEntryAt(i);\n\n\t\t\tcheckLootGroupEntryRecursive(lootGroupMap, entryName, &parentGroups);\n\t\t}\n\n\t}\n\n}\n[Added] unit test to verify that mobiles' outifts exist\/*\n * MobileTest.cpp\n *\n * Created on: Aug 10, 2013\n * Author: TheAnswer\n *\/\n\n#include \"gtest\/gtest.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/templates\/LootGroupTemplate.h\"\n#include \"server\/zone\/managers\/loot\/LootGroupMap.h\"\n#include \"server\/zone\/managers\/creature\/CreatureTemplateManager.h\"\n#include \"server\/zone\/managers\/loot\/lootgroup\/LootGroupCollectionEntry.h\"\n\nclass LuaMobileTest : public ::testing::Test {\npublic:\n\n\tLuaMobileTest() {\n\t\t\/\/ Perform creation setup here.\n\t}\n\n\t~LuaMobileTest() {\n\t}\n\n\tvoid SetUp() {\n\t\t\/\/ Perform setup of common constructs here.\n\t}\n\n\tvoid TearDown() {\n\t\t\/\/ Perform clean up of common constructs here.\n\t}\n\n\tvoid checkLootGroupEntryRecursive(LootGroupMap* lootGroupMap, String& entryName, Vector* parentGroups) {\n\t\tif (entryName.isEmpty())\n\t\t\treturn;\n\n\t\t\/\/Check for infinite recursion\n\t\tfor (int i = 0; i < parentGroups->size(); i++) {\n\t\t\tString parentName = parentGroups->get(i);\n\n\t\t\tEXPECT_FALSE( parentName == entryName ) << \"Loot group \" << std::string(parentName.toCharArray()) << \" failed recursion check.\";\n\n\t\t\tif (parentName == entryName)\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (lootGroupMap->lootGroupExists(entryName)) {\n\n\t\t\tLootGroupTemplate* lootGroupTemplate = lootGroupMap->getLootGroupTemplate(entryName);\n\n\t\t\tfor (int j = 0; j < lootGroupTemplate->size(); j++) {\n\n\t\t\t\tString entry = lootGroupTemplate->getLootGroupEntryAt(j);\n\n\t\t\t\tparentGroups->add(entryName);\n\n\t\t\t\tcheckLootGroupEntryRecursive(lootGroupMap, entry, parentGroups);\n\t\t\t}\n\n\t\t} else {\n\t\t\tReference itemTemplate = lootGroupMap->getLootItemTemplate( entryName );\n\t\t\tEXPECT_TRUE( itemTemplate != NULL ) << \"Item template \" << std::string(entryName.toCharArray()) << \" from \" << std::string(parentGroups->get(parentGroups->size() - 1).toCharArray()) << \" was not found in LootGroupMap\";\n\t\t}\n\t}\n};\n\nTEST_F(LuaMobileTest, LuaMobileTemplatesTest) {\n\tCreatureTemplateManager::DEBUG_MODE = 1;\n\n\t\/\/ Verify that all mobiles load\n\tASSERT_EQ(CreatureTemplateManager::instance()->loadTemplates(), 0);\n\n\t\/\/ Verify loot group map loads\n\tLootGroupMap* lootGroupMap = LootGroupMap::instance();\n\tASSERT_EQ(lootGroupMap->initialize(), 0);\n\n\t\/\/ Load Templates\n\tASSERT_TRUE( TemplateManager::instance() != NULL );\n\tif( TemplateManager::instance()->loadedTemplatesCount == 0 ){\n\t\tTemplateManager::instance()->loadLuaTemplates();\n\t}\n\n\t\/\/ Test Creature Templates\n\tHashTableIterator > creatureIterator = CreatureTemplateManager::instance()->iterator();\n\twhile (creatureIterator.hasNext()) {\n\t\tCreatureTemplate* creature = creatureIterator.next();\n\t\tstd::string templateName( creature->getTemplateName().toCharArray() );\n\n\t\t\/\/ Check configured templates\n\t\tVector objTemps = creature->getTemplates();\n\t\tEXPECT_FALSE( objTemps.isEmpty() ) << \"Mobile \" << templateName << \" does not have any templates configured\";\n\t\tfor( int j=0; j< objTemps.size(); j++ ){\n\t\t\tSharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate(objTemps.get(j).hashCode());\n\t\t\tstd::string objName = objTemps.get(j).toCharArray();\n\t\t\tEXPECT_TRUE( templateData != NULL ) << \"Mobile \" << templateName << \" has invalid template configured: \" << objName;\n\t\t}\n\n\t\t\/\/ Verify loot group percentages\n\t\tLootGroupCollection* groupCollection = creature->getLootGroups();\n\t\tif( groupCollection->count() > 0 ){\n\n\n\t\t\tfor( int i = 0; i < groupCollection->count(); i++ ){\n\n\t\t\t\tLootGroupCollectionEntry* collectionEntry = groupCollection->get(i);\n\t\t\t\tLootGroups* groups = collectionEntry->getLootGroups();\n\t\t\t\tif( groups->count() > 0){\n\n\t\t\t\t\tint totalChance = 0;\n\t\t\t\t\tfor( int j = 0; j < groups->count(); j++ ){\n\n\t\t\t\t\t\tLootGroupEntry* lootGroup = groups->get(j);\n\t\t\t\t\t\ttotalChance += lootGroup->getLootChance();\n\n\t\t\t\t\t\t\/\/ Verify loot group is configured correctly\n\t\t\t\t\t\tLootGroupTemplate* foundGroup = lootGroupMap->getLootGroupTemplate( lootGroup->getLootGroupName() );\n\t\t\t\t\t\tstd::string groupName( lootGroup->getLootGroupName().toCharArray() );\n\t\t\t\t\t\tEXPECT_TRUE( foundGroup != NULL ) << \"Loot group \" << groupName << \" from \" << templateName << \" was not found in LootGroupMap\";\n\n\t\t\t\t\t}\n\n\t\t\t\t\tEXPECT_EQ( 10000000, totalChance ) << \"Loot groups total chance is incorrect \" << templateName;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify weapon groups exist\n\t\tVector weapons = creature->getWeapons();\n\t\tfor (int i = 0; i < weapons.size(); i++) {\n\t\t\tString weaponGroup = weapons.get(i);\n\t\t\tstd::string groupName( weaponGroup.toCharArray() );\n\t\t\tVector group = CreatureTemplateManager::instance()->getWeapons(weaponGroup);\n\t\t\tEXPECT_TRUE( group.size() > 0 ) << \"Weapon group \" << groupName << \" from \" << templateName << \" was not found in weaponMap\";\n\t\t}\n\n\t\t\/\/ Verify conversation template exist, and the mob has converse option bit\n\t\tuint32 convoTemplate = creature->getConversationTemplate();\n\t\tuint32 optionsBitmask = creature->getOptionsBitmask();\n\t\tif (convoTemplate != 0) {\n\t\t\tConversationTemplate* convoTemp = CreatureTemplateManager::instance()->getConversationTemplate(convoTemplate);\n\t\t\tEXPECT_TRUE( convoTemp != NULL ) << \"Conversation template from \" << templateName << \" was not found.\";\n\t\t\tEXPECT_TRUE( optionsBitmask & OptionBitmask::CONVERSE ) << templateName << \" has a convo template but not the CONVERSE options bit.\";\n\t\t}\n\n\t\t\/\/ Verify that outfits exist\n\t\tString outfit = creature->getOutfit();\n\t\tif (!outfit.isEmpty()) {\n\t\t\tMobileOutfitGroup* outfitGroup = CreatureTemplateManager::instance()->getMobileOutfitGroup(outfit);\n\t\t\tEXPECT_TRUE( outfitGroup != NULL ) << \"Outfit group \" << outfit.toCharArray() << \" from \" << templateName << \" was not found.\";\n\t\t}\n\t}\n\n\t\/\/ Test Lair Templates\n\tHashTableIterator > lairIterator = CreatureTemplateManager::instance()->lairTemplateIterator();\n\twhile (lairIterator.hasNext()) {\n\t\tLairTemplate* lair = lairIterator.next();\n\t\tstd::string templateName( lair->getName().toCharArray() );\n\n\t\t\/\/ Verify that mobiles exist and that their weighting is positive\n\t\tVectorMap* mobiles = lair->getMobiles();\n\t\tfor (int i = 0; i < mobiles->size(); i++) {\n\t\t\tint weighting = mobiles->elementAt(i).getValue();\n\t\t\tString mobile = mobiles->elementAt(i).getKey();\n\t\t\tstd::string mobName = mobile.toCharArray();\n\t\t\tEXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(mobile) != NULL ) << \"Mobile \" << mobName << \" in lair template \" << templateName << \" does not exist\";\n\t\t\tEXPECT_TRUE( weighting > 0 ) << \"Mobile \" << mobName << \" in lair template \" << templateName << \" has a non positive weighting\";\n\t\t}\n\n\t\t\/\/ Verify that boss mobiles exist and that their count is positive\n\t\tVectorMap* bossMobiles = lair->getBossMobiles();\n\t\tfor (int i = 0; i < bossMobiles->size(); i++) {\n\t\t\tint count = bossMobiles->elementAt(i).getValue();\n\t\t\tString bossMob = bossMobiles->elementAt(i).getKey();\n\t\t\tstd::string bossName = bossMob.toCharArray();\n\t\t\tEXPECT_TRUE( CreatureTemplateManager::instance()->getTemplate(bossMob) != NULL ) << \"Boss mobile \" << bossName << \" in lair template \" << templateName << \" does not exist\";\n\t\t\tEXPECT_TRUE( count > 0 ) << \"Boss mobile \" << bossName << \" in lair template \" << templateName << \" has a non positive spawn count\";\n\t\t}\n\n\t\t\/\/ Verify spawn limit is positive\n\t\tint limit = lair->getSpawnLimit();\n\t\tEXPECT_TRUE( limit > 0 ) << \"Spawn limit in lair template \" << templateName << \" is not positive\";\n\n\t\t\/\/ Verify any configured buildings exist\n\t\tfor(int i=0; i<=4; i++){\n\n\t\t\tVector* buildings = lair->getBuildings( i );\n\t\t\tif( buildings == NULL )\n\t\t\t\tcontinue;\n\n\t\t\tfor( int j=0; j < buildings->size(); j++ ){\n\t\t\t\tString buildingTemplate = buildings->get(j);\n\t\t\t\tstd::string buildingStr = buildingTemplate.toCharArray();\n\t\t\t\tSharedObjectTemplate* templateObject = TemplateManager::instance()->getTemplate(buildingTemplate.hashCode());\n\t\t\t\tEXPECT_TRUE( templateObject != NULL && templateObject->isSharedTangibleObjectTemplate() ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" does not exist\";\n\t\t\t\tif( lair->getBuildingType() == LairTemplate::LAIR ){\n\t\t\t\t\tEXPECT_TRUE( buildingTemplate.beginsWith( \"object\/tangible\/lair\/\") ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" is not a child of object\/tangible\/lair\/\";\n\t\t\t\t}\n\t\t\t\tif( lair->getBuildingType() == LairTemplate::THEATER ){\n\t\t\t\t\tEXPECT_TRUE( buildingTemplate.beginsWith( \"object\/building\/poi\/\") ) << \"Building template \" << buildingStr << \" in lair template \" << templateName << \" is not a child of object\/building\/poi\/\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ TODO: Add test to enforce LAIRs and THEATERs have at least one building configured\n\n\t}\n\n\t\/\/ Test Spawn Groups\n\tHashTableIterator > spawnIterator = CreatureTemplateManager::instance()->spawnGroupIterator();\n\twhile (spawnIterator.hasNext()) {\n\t\tSpawnGroup* group = spawnIterator.next();\n\t\tstd::string templateName( group->getTemplateName().toCharArray() );\n\n\t\t\/\/ Verify spawn limit is not negative\n\t\tint limit = group->getMaxSpawnLimit();\n\t\tEXPECT_TRUE( limit >= 0 ) << \"Max spawn limit in spawn group \" << templateName << \" is negative\";\n\n\t\t\/\/ Verify spawn list\n\t\tVector >* spawnList = group->getSpawnList();\n\t\tfor (int i = 0; i < spawnList->size(); i++) {\n\t\t\tLairSpawn* spawn = spawnList->get(i);\n\t\t\tstd::string lairName( spawn->getLairTemplateName().toCharArray() );\n\n\t\t\t\/\/ Verify lair template exists\n\t\t\tString lairTemplateName = spawn->getLairTemplateName();\n\t\t\tReference lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());\n\t\t\tEXPECT_TRUE( lairTemplate != NULL ) << \"Lair template \" << lairName << \" in spawn group \" << templateName << \" does not exist.\";\n\n\t\t\t\/\/ Verify spawn limit is at least -1\n\t\t\tfloat spawnLimit = spawn->getSpawnLimit();\n\t\t\tEXPECT_TRUE( spawnLimit >= -1 ) << \"SpawnLimit for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than -1.\";\n\n\t\t\t\/\/ Verify difficulties\n\t\t\tint minDiff = spawn->getMinDifficulty();\n\t\t\tint maxDiff = spawn->getMaxDifficulty();\n\t\t\tEXPECT_TRUE( minDiff > 0 ) << \"MinDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\t\t\tEXPECT_TRUE( maxDiff >= minDiff ) << \"MaxDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than min difficulty.\";\n\n\t\t\t\/\/ Verify number to spawn is not negative\n\t\t\tint numberToSpawn = spawn->getNumberToSpawn();\n\t\t\tEXPECT_TRUE( numberToSpawn >= 0 ) << \"NumberToSpawn for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is negative.\";\n\n\t\t\t\/\/ Verify weighting is positive\n\t\t\tint weighting = spawn->getWeighting();\n\t\t\tEXPECT_TRUE( weighting > 0 ) << \"Weighting for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\n\t\t\t\/\/ Verify size is at least 1\n\t\t\tfloat size = spawn->getSize();\n\t\t\tEXPECT_TRUE( size >= 1 ) << \"Size for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than 1.\";\n\t\t}\n\t}\n\n\t\/\/ Test Destroy Mission Spawn Groups\n\tHashTableIterator > missionIterator = CreatureTemplateManager::instance()->destroyMissionGroupIterator();\n\twhile (missionIterator.hasNext()) {\n\t\tSpawnGroup* group = missionIterator.next();\n\t\tstd::string templateName( group->getTemplateName().toCharArray() );\n\n\t\t\/\/ Verify spawn list\n\t\tVector >* spawnList = group->getSpawnList();\n\t\tfor (int i = 0; i < spawnList->size(); i++) {\n\t\t\tLairSpawn* spawn = spawnList->get(i);\n\t\t\tstd::string lairName( spawn->getLairTemplateName().toCharArray() );\n\n\t\t\t\/\/ Verify lair template exists\n\t\t\tString lairTemplateName = spawn->getLairTemplateName();\n\t\t\tReference lairTemplate = CreatureTemplateManager::instance()->getLairTemplate(lairTemplateName.hashCode());\n\t\t\tEXPECT_TRUE( lairTemplate != NULL ) << \"Lair template \" << lairName << \" in spawn group \" << templateName << \" does not exist.\";\n\n\t\t\t\/\/ Verify difficulties\n\t\t\tint minDiff = spawn->getMinDifficulty();\n\t\t\tint maxDiff = spawn->getMaxDifficulty();\n\t\t\tEXPECT_TRUE( minDiff > 0 ) << \"MinDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is not positive.\";\n\t\t\tEXPECT_TRUE( maxDiff >= minDiff ) << \"MaxDifficulty for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than min difficulty.\";\n\n\t\t\t\/\/ Verify size is at least 1\n\t\t\tfloat size = spawn->getSize();\n\t\t\tEXPECT_TRUE( size >= 1 ) << \"Size for lairTemplate \" << lairName << \" in spawn group \" << templateName << \" is less than 1.\";\n\t\t}\n\t}\n}\n\nTEST_F(LuaMobileTest, LuaLootGroupsTest) {\n\n\tLootGroupMap* lootGroupMap = LootGroupMap::instance();\n\tASSERT_EQ(lootGroupMap->initialize(), 0);\n\n\t\/\/Make sure that no loot items have the same name as a loot group\n\tHashTableIterator > itemIter = lootGroupMap->itemTemplates.iterator();\n\twhile (itemIter.hasNext()) {\n\n\t\tLootItemTemplate* lootItemTemplate = itemIter.next();\n\t\tString itemTemplateName( lootItemTemplate->getTemplateName().toCharArray() );\n\n\t\tEXPECT_FALSE( lootGroupMap->lootGroupExists(itemTemplateName) ) << \"Loot item \" << std::string(itemTemplateName.toCharArray()) << \" has the same name as a loot group.\";\n\t}\n\n\tHashTableIterator > iter = lootGroupMap->groupTemplates.iterator();\n\twhile (iter.hasNext()) {\n\n\t\tLootGroupTemplate* lootGroupTemplate = iter.next();\n\t\tString groupTemplateName( lootGroupTemplate->getTemplateName().toCharArray() );\n\n\t\t\/\/ Check non-empty loot groups to make sure their chances total correctly\n\t\tif( lootGroupTemplate->getLootGroupEntryForRoll(-1).length() > 0 ){\n\t\t\tEXPECT_GT( lootGroupTemplate->getLootGroupEntryForRoll(10000000).length(), 0 ) << \"Item total chance is less than 10000000: \" << std::string(groupTemplateName.toCharArray());\n\t\t\tEXPECT_EQ( lootGroupTemplate->getLootGroupEntryForRoll(10000001).length(), 0 ) << \"Item total chance is greater than 10000000: \" << std::string(groupTemplateName.toCharArray());\n\t\t}\n\n\t\t\/\/ Check that all loot group entries are valid\n\t\tfor( int i = 0; i < lootGroupTemplate->size(); i++ ){\n\n\t\t\tVector parentGroups;\n\t\t\tparentGroups.add(groupTemplateName);\n\n\t\t\tString entryName = lootGroupTemplate->getLootGroupEntryAt(i);\n\n\t\t\tcheckLootGroupEntryRecursive(lootGroupMap, entryName, &parentGroups);\n\t\t}\n\n\t}\n\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MLOPEN_FLOAT_EQUAL_HPP\n#define GUARD_MLOPEN_FLOAT_EQUAL_HPP\n\n#include \n#include \n#include \n\nnamespace miopen {\n\ntemplate \nusing common_type = typename std::common_type::type;\n\nstruct float_equal_fn\n{\n template \n static bool apply(T x, T y)\n {\n return std::isfinite(x) and std::isfinite(y) and\n std::nextafter(x, std::numeric_limits::lowest()) <= y and\n std::nextafter(x, std::numeric_limits::max()) >= y;\n }\n\n template \n bool operator()(T x, U y) const\n {\n return float_equal_fn::apply>(x, y);\n }\n};\n\nstatic constexpr float_equal_fn float_equal{};\n\n} \/\/ namespace miopen\n\n#endif\nAdd missing header for windows\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MLOPEN_FLOAT_EQUAL_HPP\n#define GUARD_MLOPEN_FLOAT_EQUAL_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace miopen {\n\ntemplate \nusing common_type = typename std::common_type::type;\n\nstruct float_equal_fn\n{\n template \n static bool apply(T x, T y)\n {\n return std::isfinite(x) and std::isfinite(y) and\n std::nextafter(x, std::numeric_limits::lowest()) <= y and\n std::nextafter(x, std::numeric_limits::max()) >= y;\n }\n\n template \n bool operator()(T x, U y) const\n {\n return float_equal_fn::apply>(x, y);\n }\n};\n\nstatic constexpr float_equal_fn float_equal{};\n\n} \/\/ namespace miopen\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * token.cpp\n * openc2e\n *\n * Created by Bryan Donlan on Thu 11 Aug 2005.\n * Copyright (c) 2005 Bryan Donlan. All rights reserved.\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 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 *\/\n\/* vim: set noet: *\/\nRemove token.cpp<|endoftext|>"} {"text":"#include \"DataUnserialiser.h\"\n#include \n#include \n\nnamespace XNet\n{\n\nstatic uint32_t bitswap(uint32_t v)\n{\n\t\/\/ swap odd and even bits\n\tv = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);\n\t\/\/ swap consecutive pairs\n\tv = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);\n\t\/\/ swap nibbles ... \n\tv = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);\n\t\/\/ swap bytes\n\tv = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);\n\t\/\/ swap 2-byte long pairs\n\tv = ( v >> 16 ) | ( v << 16);\n\treturn v;\n}\n\nvoid DataUnserialiser::NextWord()\n{\n\tbitIndex = 0;\n\tif (words.size() == nextWord)\n\t{\n\t\t\/\/ early exit\n\t\tcurrentWord = 0;\n\t\treturn;\n\t}\n\tcurrentWord = bitswap(words[nextWord++]);\n}\n\nvoid DataUnserialiser::Init(const void* data, size_t length)\n{\n\tassert(length % 4 == 0);\n\tconst uint32_t* wordPtr = (const uint32_t*)data;\n\twords.reserve(length \/ 4);\n\tfor (size_t i = 0; i < (length\/4); ++i)\n\t{\n\t\twords.push_back(Big32(wordPtr[i]));\n\t}\n\tnextWord = 0;\n\tNextWord();\n}\n\nstatic uint32_t MaskToLowOrder(uint32_t value, int sigbits)\n{\n\treturn value & ((1 << sigbits)-1);\n}\n\nuint32_t DataUnserialiser::GetWord(int significantBits)\n{\n\tint remaining = 32 - bitIndex;\n\tif (significantBits <= remaining)\n\t{\n\t\t\/\/ simple case\n\t\tbitIndex += significantBits;\n\t\tuint32_t result = MaskToLowOrder(currentWord, significantBits);\n\t\tcurrentWord >>= significantBits;\n\t\tif (bitIndex == 32)\n\t\t{\n\t\t\tNextWord();\n\t\t}\n\t\tresult = bitswap(result);\n\t\tresult >>= 32 - significantBits;\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\t\/\/ complex case\n\t\t\/\/ get high order\n\t\tint highBits = remaining;\n\t\tint lowBits = significantBits - remaining;\n\t\tuint32_t highValue = GetWord(highBits);\n\t\tuint32_t lowValue = GetWord(lowBits);\n\t\tuint32_t result = (highValue << lowBits) | lowValue;\n\t\treturn result;\n\t}\n}\n\nDataUnserialiser::DataUnserialiser(const void* data, size_t length)\n{\n\tInit(data, length);\n}\n\nDataUnserialiser::DataUnserialiser(const std::string& data)\n{\n\tInit(data.data(), data.length());\n}\n\nDataUnserialiser& DataUnserialiser::operator>>(uint64_t& value)\n{\n\tuint64_t result;\n\tuint32_t result32;\n\t*this >> result32;\n\tresult = (uint64_t)result32 << 32;\n\t*this >> result32;\n\tresult |= result32;\n\tvalue = result;\n\treturn *this;\n}\n\nDataUnserialiser& DataUnserialiser::operator>>(std::string& value)\n{\n\tbool isShorthand = GetWord(1);\n\tuint32_t length = GetWord(isShorthand ? 5 : 24);\n\tvalue.resize(length);\n\tfor (uint32_t i = 0; i < length; ++i)\n\t{\n\t\tvalue.at(i) = GetWord(isShorthand ? 7 : 8);\n\t}\n\treturn *this;\n}\n\n}\nAdded some explicit zero-extensions to DataUnserialiser on the 64-bit decoder.#include \"DataUnserialiser.h\"\n#include \n#include \n\nnamespace XNet\n{\n\nstatic uint32_t bitswap(uint32_t v)\n{\n\t\/\/ swap odd and even bits\n\tv = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);\n\t\/\/ swap consecutive pairs\n\tv = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);\n\t\/\/ swap nibbles ... \n\tv = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);\n\t\/\/ swap bytes\n\tv = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);\n\t\/\/ swap 2-byte long pairs\n\tv = ( v >> 16 ) | ( v << 16);\n\treturn v;\n}\n\nvoid DataUnserialiser::NextWord()\n{\n\tbitIndex = 0;\n\tif (words.size() == nextWord)\n\t{\n\t\t\/\/ early exit\n\t\tcurrentWord = 0;\n\t\treturn;\n\t}\n\tcurrentWord = bitswap(words[nextWord++]);\n}\n\nvoid DataUnserialiser::Init(const void* data, size_t length)\n{\n\tassert(length % 4 == 0);\n\tconst uint32_t* wordPtr = (const uint32_t*)data;\n\twords.reserve(length \/ 4);\n\tfor (size_t i = 0; i < (length\/4); ++i)\n\t{\n\t\twords.push_back(Big32(wordPtr[i]));\n\t}\n\tnextWord = 0;\n\tNextWord();\n}\n\nstatic uint32_t MaskToLowOrder(uint32_t value, int sigbits)\n{\n\treturn value & ((1 << sigbits)-1);\n}\n\nuint32_t DataUnserialiser::GetWord(int significantBits)\n{\n\tint remaining = 32 - bitIndex;\n\tif (significantBits <= remaining)\n\t{\n\t\t\/\/ simple case\n\t\tbitIndex += significantBits;\n\t\tuint32_t result = MaskToLowOrder(currentWord, significantBits);\n\t\tcurrentWord >>= significantBits;\n\t\tif (bitIndex == 32)\n\t\t{\n\t\t\tNextWord();\n\t\t}\n\t\tresult = bitswap(result);\n\t\tresult >>= 32 - significantBits;\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\t\/\/ complex case\n\t\t\/\/ get high order\n\t\tint highBits = remaining;\n\t\tint lowBits = significantBits - remaining;\n\t\tuint32_t highValue = GetWord(highBits);\n\t\tuint32_t lowValue = GetWord(lowBits);\n\t\tuint32_t result = (highValue << lowBits) | lowValue;\n\t\treturn result;\n\t}\n}\n\nDataUnserialiser::DataUnserialiser(const void* data, size_t length)\n{\n\tInit(data, length);\n}\n\nDataUnserialiser::DataUnserialiser(const std::string& data)\n{\n\tInit(data.data(), data.length());\n}\n\nDataUnserialiser& DataUnserialiser::operator>>(uint64_t& value)\n{\n\tuint64_t result = 0;\n\tuint32_t result32 = 0;\n\t*this >> result32;\n\tresult = ((uint64_t)result32) << 32ULL;\n\t*this >> result32;\n\tresult |= (uint64_t)result32;\n\tvalue = result;\n\treturn *this;\n}\n\nDataUnserialiser& DataUnserialiser::operator>>(std::string& value)\n{\n\tbool isShorthand = GetWord(1);\n\tuint32_t length = GetWord(isShorthand ? 5 : 24);\n\tvalue.resize(length);\n\tfor (uint32_t i = 0; i < length; ++i)\n\t{\n\t\tvalue.at(i) = GetWord(isShorthand ? 7 : 8);\n\t}\n\treturn *this;\n}\n\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace miopen {\n\n#define MIOPEN_DECLARE_HANDLE_MUTEX(x) \\\n struct x \\\n { \\\n static const char* value() { return \".miopen-\" #x \".lock\"; } \\\n };\n\n#if MIOPEN_GPU_SYNC\nMIOPEN_DECLARE_HANDLE_MUTEX(gpu_handle_mutex)\n#define MIOPEN_HANDLE_LOCK \\\n auto miopen_handle_lock_guard_##__LINE__ = miopen::get_handle_lock(miopen::gpu_handle_mutex{});\n#else\n#define MIOPEN_HANDLE_LOCK\n#endif\n\ninline boost::filesystem::path get_handle_lock_path(const char* name)\n{\n auto p = boost::filesystem::current_path() \/ name;\n if(!boost::filesystem::exists(p))\n {\n auto tmp = boost::filesystem::current_path() \/ boost::filesystem::unique_path();\n boost::filesystem::ofstream{tmp};\n boost::filesystem::rename(tmp, p);\n }\n return p;\n}\n\nstruct handle_mutex\n{\n std::recursive_timed_mutex m;\n boost::interprocess::file_lock flock;\n\n handle_mutex(const char* name) : flock(name) {}\n\n bool try_lock() { return std::try_lock(m, flock); }\n\n void lock() { std::lock(m, flock); }\n\n template \n bool try_lock_for(Duration d)\n {\n return m.try_lock_for(d) &&\n flock.timed_lock(\n boost::posix_time::second_clock::universal_time() +\n boost::posix_time::milliseconds(\n std::chrono::duration_cast(d).count()));\n }\n\n template \n bool try_lock_until(Point p)\n {\n return m.try_lock_for(p - std::chrono::system_clock::now());\n }\n\n void unlock()\n {\n flock.unlock();\n m.unlock();\n }\n};\n\ntemplate \ninline std::unique_lock get_handle_lock(T, int timeout = 60)\n{\n static handle_mutex m{get_handle_lock_path(T::value()).c_str()};\n return {m, std::chrono::seconds{timeout}};\n}\n\n} \/\/ namespace miopen\nAdd missing header for posix time\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace miopen {\n\n#define MIOPEN_DECLARE_HANDLE_MUTEX(x) \\\n struct x \\\n { \\\n static const char* value() { return \".miopen-\" #x \".lock\"; } \\\n };\n\n#if MIOPEN_GPU_SYNC\nMIOPEN_DECLARE_HANDLE_MUTEX(gpu_handle_mutex)\n#define MIOPEN_HANDLE_LOCK \\\n auto miopen_handle_lock_guard_##__LINE__ = miopen::get_handle_lock(miopen::gpu_handle_mutex{});\n#else\n#define MIOPEN_HANDLE_LOCK\n#endif\n\ninline boost::filesystem::path get_handle_lock_path(const char* name)\n{\n auto p = boost::filesystem::current_path() \/ name;\n if(!boost::filesystem::exists(p))\n {\n auto tmp = boost::filesystem::current_path() \/ boost::filesystem::unique_path();\n boost::filesystem::ofstream{tmp};\n boost::filesystem::rename(tmp, p);\n }\n return p;\n}\n\nstruct handle_mutex\n{\n std::recursive_timed_mutex m;\n boost::interprocess::file_lock flock;\n\n handle_mutex(const char* name) : flock(name) {}\n\n bool try_lock() { return std::try_lock(m, flock); }\n\n void lock() { std::lock(m, flock); }\n\n template \n bool try_lock_for(Duration d)\n {\n return m.try_lock_for(d) &&\n flock.timed_lock(\n boost::posix_time::second_clock::universal_time() +\n boost::posix_time::milliseconds(\n std::chrono::duration_cast(d).count()));\n }\n\n template \n bool try_lock_until(Point p)\n {\n return m.try_lock_for(p - std::chrono::system_clock::now());\n }\n\n void unlock()\n {\n flock.unlock();\n m.unlock();\n }\n};\n\ntemplate \ninline std::unique_lock get_handle_lock(T, int timeout = 60)\n{\n static handle_mutex m{get_handle_lock_path(T::value()).c_str()};\n return {m, std::chrono::seconds{timeout}};\n}\n\n} \/\/ namespace miopen\n<|endoftext|>"} {"text":"\/*\n * loader.cpp\n *\n * Copyright (c) 2001, 2002, 2003 Frerich Raabe \n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. For licensing and distribution details, check the\n * accompanying file 'COPYING'.\n *\/\n#include \"loader.h\"\n#include \"document.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace RSS;\n\nDataRetriever::DataRetriever()\n{\n}\n\nDataRetriever::~DataRetriever()\n{\n}\n\nstruct FileRetriever::Private\n{\n Private()\n : buffer(NULL),\n lastError(0), job(NULL)\n {\n }\n\n ~Private()\n {\n delete buffer;\n }\n\n QBuffer *buffer;\n int lastError;\n KIO::Job *job;\n};\n\nFileRetriever::FileRetriever()\n : d(new Private)\n{\n}\n\nFileRetriever::~FileRetriever()\n{\n delete d;\n}\n\nvoid FileRetriever::retrieveData(const KURL &url)\n{\n if (d->buffer)\n return;\n\n d->buffer = new QBuffer;\n d->buffer->open(IO_WriteOnly);\n\n d->job = KIO::get(url, false, false);\n connect(d->job, SIGNAL(data(KIO::Job *, const QByteArray &)),\n SLOT(slotData(KIO::Job *, const QByteArray &)));\n connect(d->job, SIGNAL(result(KIO::Job *)), SLOT(slotResult(KIO::Job *)));\n connect(d->job, SIGNAL(permanentRedirection(KIO::Job *, const KURL &, const KURL &)),\n SLOT(slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &)));\n}\n\nint FileRetriever::errorCode() const\n{\n return d->lastError;\n}\n\nvoid FileRetriever::slotData(KIO::Job *, const QByteArray &data)\n{\n d->buffer->writeBlock(data.data(), data.size());\n}\n\nvoid FileRetriever::slotResult(KIO::Job *job)\n{\n QByteArray data = d->buffer->buffer();\n data.detach();\n\n delete d->buffer;\n d->buffer = NULL;\n\n d->lastError = job->error();\n emit dataRetrieved(data, d->lastError == 0);\n}\n\nvoid FileRetriever::slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &newUrl)\n{\n emit permanentRedirection(newUrl);\n}\n\nvoid FileRetriever::abort()\n{\n\tif (d->job)\n\t{\n\t\td->job->kill(true);\n\t\td->job = NULL;\n\t}\n}\n\nstruct OutputRetriever::Private\n{\n Private() : process(NULL),\n buffer(NULL),\n lastError(0)\n {\n }\n\n ~Private()\n {\n delete process;\n delete buffer;\n }\n\n KShellProcess *process;\n QBuffer *buffer;\n int lastError;\n};\n\nOutputRetriever::OutputRetriever() :\n d(new Private)\n{\n}\n\nOutputRetriever::~OutputRetriever()\n{\n delete d;\n}\n\nvoid OutputRetriever::retrieveData(const KURL &url)\n{\n \/\/ Ignore subsequent calls if we didn't finish the previous job yet.\n if (d->buffer || d->process)\n return;\n\n d->buffer = new QBuffer;\n d->buffer->open(IO_WriteOnly);\n\n d->process = new KShellProcess();\n connect(d->process, SIGNAL(processExited(KProcess *)),\n SLOT(slotExited(KProcess *)));\n connect(d->process, SIGNAL(receivedStdout(KProcess *, char *, int)),\n SLOT(slotOutput(KProcess *, char *, int)));\n *d->process << url.path();\n d->process->start(KProcess::NotifyOnExit, KProcess::Stdout);\n}\n\nint OutputRetriever::errorCode() const\n{\n return d->lastError;\n}\n\nvoid OutputRetriever::slotOutput(KProcess *, char *data, int length)\n{\n d->buffer->writeBlock(data, length);\n}\n\nvoid OutputRetriever::slotExited(KProcess *p)\n{\n if (!p->normalExit())\n d->lastError = p->exitStatus();\n\n QByteArray data = d->buffer->buffer();\n data.detach();\n\n delete d->buffer;\n d->buffer = NULL;\n\n delete d->process;\n d->process = NULL;\n\n emit dataRetrieved(data, p->normalExit() && p->exitStatus() == 0);\n}\n\nstruct Loader::Private\n{\n Private() : retriever(NULL),\n lastError(0)\n {\n }\n\n ~Private()\n {\n delete retriever;\n }\n\n DataRetriever *retriever;\n int lastError;\n KURL discoveredFeedURL;\n KURL url;\n};\n\nLoader *Loader::create()\n{\n return new Loader;\n}\n\nLoader *Loader::create(QObject *object, const char *slot)\n{\n Loader *loader = create();\n connect(loader, SIGNAL(loadingComplete(Loader *, Document, Status)),\n object, slot);\n return loader;\n}\n\nLoader::Loader() : d(new Private)\n{\n}\n\nLoader::~Loader()\n{\n delete d;\n}\n\nvoid Loader::loadFrom(const KURL &url, DataRetriever *retriever)\n{\n if (d->retriever != NULL)\n return;\n\n d->url=url;\n d->retriever = retriever;\n\n connect(d->retriever, SIGNAL(dataRetrieved(const QByteArray &, bool)),\n this, SLOT(slotRetrieverDone(const QByteArray &, bool)));\n\n d->retriever->retrieveData(url);\n}\n\nint Loader::errorCode() const\n{\n return d->lastError;\n}\n\nvoid Loader::abort()\n{\n\tif (d->retriever)\n\t{\n\t\td->retriever->abort();\n\t\td->retriever=NULL;\n\t}\n}\n\nconst KURL &Loader::discoveredFeedURL() const\n{\n return d->discoveredFeedURL;\n}\n\nvoid Loader::slotRetrieverDone(const QByteArray &data, bool success)\n{\n d->lastError = d->retriever->errorCode();\n\n delete d->retriever;\n d->retriever = NULL;\n\n Document rssDoc;\n Status status = Success;\n\n if (success) {\n QDomDocument doc;\n\n \/* Some servers insert whitespace before the declaration.\n * QDom doesn't tolerate that (and it's right, that's invalid XML),\n * so we strip that.\n *\/\n\n const char *charData = data.data();\n int len = data.count();\n\n while (len && QChar(*charData).isSpace()) {\n --len;\n ++charData;\n }\n\n QByteArray tmpData;\n tmpData.setRawData(charData, len);\n\n if (doc.setContent(tmpData))\n {\n rssDoc = Document(doc);\n if (!rssDoc.isValid())\n {\n discoverFeeds(tmpData);\n status = ParseError;\n }\n }\n else\n {\n discoverFeeds(tmpData);\n status = ParseError;\n }\n \n tmpData.resetRawData(charData, len);\n } else\n status = RetrieveError;\n\n emit loadingComplete(this, rssDoc, status);\n\n delete this;\n}\n\nvoid Loader::discoverFeeds(const QByteArray &data)\n{\n QString str, s2;\n QTextStream ts( &str, IO_WriteOnly );\n ts << data.data();\n QRegExp rx( \"(?:REL)[^=]*=[^sAa]*(?:service.feed|ALTERNATE)[\\\\s]*[^s][^s](?:[^>]*)(?:HREF)[^=]*=[^A-Z0-9-_~,.\/$]*([^'\\\">\\\\s]*)\", false);\n if (rx.search(str)!=-1)\n s2=rx.cap(1);\n else{\n \/\/ does not support Atom\/RSS autodiscovery.. try finding feeds by brute force....\n int pos=0;\n QStringList feeds;\n QString host=d->url.host();\n rx.setPattern(\"(?:\\\\s]*)\");\n while ( pos >= 0 ) {\n pos = rx.search( str, pos );\n s2=rx.cap(1);\n if (s2.endsWith(\".rdf\")|s2.endsWith(\".rss\")|s2.endsWith(\".xml\"))\n feeds.append(s2);\n if ( pos >= 0 ) {\n pos += rx.matchedLength();\n }\n }\n\n s2=feeds.first();\n KURL testURL;\n \/\/ loop through, prefer feeds on same host\n for ( QStringList::Iterator it = feeds.begin(); it != feeds.end(); ++it ) {\n testURL=*it;\n if (testURL.host()==host)\n {\n s2=*it;\n break;\n }\n }\n }\n \n if (s2.isNull())\n return;\n\n if (KURL::isRelativeURL(s2))\n {\n if (s2.startsWith(\"\/\/\"))\n {\n s2=s2.prepend(d->url.protocol()+\":\");\n d->discoveredFeedURL=s2;\n }\n else if (s2.startsWith(\"\/\"))\n {\n d->discoveredFeedURL=d->url;\n d->discoveredFeedURL.setPath(s2);\n }\n else\n {\n d->discoveredFeedURL=d->url;\n d->discoveredFeedURL.addPath(s2);\n }\n d->discoveredFeedURL.cleanPath();\n }\n else\n d->discoveredFeedURL=s2;\n \n d->discoveredFeedURL.cleanPath();\n}\n \n#include \"loader.moc\"\n\/\/ vim:noet:ts=4\n* Fix formatting of
 contents.\/*\n * loader.cpp\n *\n * Copyright (c) 2001, 2002, 2003 Frerich Raabe \n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. For licensing and distribution details, check the\n * accompanying file 'COPYING'.\n *\/\n#include \"loader.h\"\n#include \"document.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace RSS;\n\nDataRetriever::DataRetriever()\n{\n}\n\nDataRetriever::~DataRetriever()\n{\n}\n\nstruct FileRetriever::Private\n{\n   Private()\n      : buffer(NULL),\n        lastError(0), job(NULL)\n   {\n   }\n\n   ~Private()\n   {\n      delete buffer;\n   }\n\n   QBuffer *buffer;\n   int lastError;\n   KIO::Job *job;\n};\n\nFileRetriever::FileRetriever()\n   : d(new Private)\n{\n}\n\nFileRetriever::~FileRetriever()\n{\n   delete d;\n}\n\nvoid FileRetriever::retrieveData(const KURL &url)\n{\n   if (d->buffer)\n      return;\n\n   d->buffer = new QBuffer;\n   d->buffer->open(IO_WriteOnly);\n\n   d->job = KIO::get(url, false, false);\n   connect(d->job, SIGNAL(data(KIO::Job *, const QByteArray &)),\n                SLOT(slotData(KIO::Job *, const QByteArray &)));\n   connect(d->job, SIGNAL(result(KIO::Job *)), SLOT(slotResult(KIO::Job *)));\n   connect(d->job, SIGNAL(permanentRedirection(KIO::Job *, const KURL &, const KURL &)),\n                SLOT(slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &)));\n}\n\nint FileRetriever::errorCode() const\n{\n   return d->lastError;\n}\n\nvoid FileRetriever::slotData(KIO::Job *, const QByteArray &data)\n{\n   d->buffer->writeBlock(data.data(), data.size());\n}\n\nvoid FileRetriever::slotResult(KIO::Job *job)\n{\n   QByteArray data = d->buffer->buffer();\n   data.detach();\n\n   delete d->buffer;\n   d->buffer = NULL;\n\n   d->lastError = job->error();\n   emit dataRetrieved(data, d->lastError == 0);\n}\n\nvoid FileRetriever::slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &newUrl)\n{\n   emit permanentRedirection(newUrl);\n}\n\nvoid FileRetriever::abort()\n{\n\tif (d->job)\n\t{\n\t\td->job->kill(true);\n\t\td->job = NULL;\n\t}\n}\n\nstruct OutputRetriever::Private\n{\n   Private() : process(NULL),\n      buffer(NULL),\n      lastError(0)\n   {\n   }\n\n   ~Private()\n   {\n      delete process;\n      delete buffer;\n   }\n\n   KShellProcess *process;\n   QBuffer *buffer;\n   int lastError;\n};\n\nOutputRetriever::OutputRetriever() :\n   d(new Private)\n{\n}\n\nOutputRetriever::~OutputRetriever()\n{\n   delete d;\n}\n\nvoid OutputRetriever::retrieveData(const KURL &url)\n{\n   \/\/ Ignore subsequent calls if we didn't finish the previous job yet.\n   if (d->buffer || d->process)\n      return;\n\n   d->buffer = new QBuffer;\n   d->buffer->open(IO_WriteOnly);\n\n   d->process = new KShellProcess();\n   connect(d->process, SIGNAL(processExited(KProcess *)),\n                       SLOT(slotExited(KProcess *)));\n   connect(d->process, SIGNAL(receivedStdout(KProcess *, char *, int)),\n                       SLOT(slotOutput(KProcess *, char *, int)));\n   *d->process << url.path();\n   d->process->start(KProcess::NotifyOnExit, KProcess::Stdout);\n}\n\nint OutputRetriever::errorCode() const\n{\n   return d->lastError;\n}\n\nvoid OutputRetriever::slotOutput(KProcess *, char *data, int length)\n{\n   d->buffer->writeBlock(data, length);\n}\n\nvoid OutputRetriever::slotExited(KProcess *p)\n{\n   if (!p->normalExit())\n      d->lastError = p->exitStatus();\n\n   QByteArray data = d->buffer->buffer();\n   data.detach();\n\n   delete d->buffer;\n   d->buffer = NULL;\n\n   delete d->process;\n   d->process = NULL;\n\n   emit dataRetrieved(data, p->normalExit() && p->exitStatus() == 0);\n}\n\nstruct Loader::Private\n{\n   Private() : retriever(NULL),\n      lastError(0)\n   {\n   }\n\n   ~Private()\n   {\n      delete retriever;\n   }\n\n   DataRetriever *retriever;\n   int lastError;\n   KURL discoveredFeedURL;\n   KURL url;\n};\n\nLoader *Loader::create()\n{\n   return new Loader;\n}\n\nLoader *Loader::create(QObject *object, const char *slot)\n{\n   Loader *loader = create();\n   connect(loader, SIGNAL(loadingComplete(Loader *, Document, Status)),\n           object, slot);\n   return loader;\n}\n\nLoader::Loader() : d(new Private)\n{\n}\n\nLoader::~Loader()\n{\n   delete d;\n}\n\nvoid Loader::loadFrom(const KURL &url, DataRetriever *retriever)\n{\n   if (d->retriever != NULL)\n      return;\n\n   d->url=url;\n   d->retriever = retriever;\n\n   connect(d->retriever, SIGNAL(dataRetrieved(const QByteArray &, bool)),\n           this, SLOT(slotRetrieverDone(const QByteArray &, bool)));\n\n   d->retriever->retrieveData(url);\n}\n\nint Loader::errorCode() const\n{\n   return d->lastError;\n}\n\nvoid Loader::abort()\n{\n\tif (d->retriever)\n\t{\n\t\td->retriever->abort();\n\t\td->retriever=NULL;\n\t}\n}\n\nconst KURL &Loader::discoveredFeedURL() const\n{\n   return d->discoveredFeedURL;\n}\n\n#include \n\nvoid Loader::slotRetrieverDone(const QByteArray &data, bool success)\n{\n   d->lastError = d->retriever->errorCode();\n\n   delete d->retriever;\n   d->retriever = NULL;\n\n   Document rssDoc;\n   Status status = Success;\n\n   if (success) {\n      QDomDocument doc;\n\n      \/* Some servers insert whitespace before the  declaration.\n       * QDom doesn't tolerate that (and it's right, that's invalid XML),\n       * so we strip that.\n       *\/\n\n      const char *charData = data.data();\n      int len = data.count();\n\n      while (len && QChar(*charData).isSpace()) {\n         --len;\n         ++charData;\n      }\n\n      QCString tmpData(charData, len);\n      \n      \/\/ hack: support formatting inside 
 tags\n      QRegExp pres(\"<pre>(.+)<\/pre>\", false);\n      pres.setMinimal(TRUE);\n      int pos = 0;\n      while( (pos = pres.search(tmpData, pos)) != -1 )\n      {\n\tint len = pres.matchedLength();\n\t\n\tQCString str = tmpData.mid(pos, len);\n\tstr.replace(\"\\n\", \"<br\/>\");\n\t\n\ttmpData.replace(pos, len, str);\n\tpos += len;\n      }\n\n      if (doc.setContent(tmpData))\n      {\n         rssDoc = Document(doc);\n         if (!rssDoc.isValid())\n         {\n            discoverFeeds(tmpData);\n            status = ParseError;\n         }\n      }\n      else\n      {\n         discoverFeeds(tmpData);\n         status = ParseError;\n      }\n      \n   } else\n      status = RetrieveError;\n\n   emit loadingComplete(this, rssDoc, status);\n\n   delete this;\n}\n\nvoid Loader::discoverFeeds(const QByteArray &data)\n{\n    QString str, s2;\n    QTextStream ts( &str, IO_WriteOnly );\n    ts << data.data();\n    QRegExp rx( \"(?:REL)[^=]*=[^sAa]*(?:service.feed|ALTERNATE)[\\\\s]*[^s][^s](?:[^>]*)(?:HREF)[^=]*=[^A-Z0-9-_~,.\/$]*([^'\\\">\\\\s]*)\", false);\n    if (rx.search(str)!=-1)\n        s2=rx.cap(1);\n    else{\n    \/\/ does not support Atom\/RSS autodiscovery.. try finding feeds by brute force....\n        int pos=0;\n        QStringList feeds;\n        QString host=d->url.host();\n        rx.setPattern(\"(?:\\\\s]*)\");\n        while ( pos >= 0 ) {\n            pos = rx.search( str, pos );\n            s2=rx.cap(1);\n            if (s2.endsWith(\".rdf\")|s2.endsWith(\".rss\")|s2.endsWith(\".xml\"))\n                    feeds.append(s2);\n            if ( pos >= 0 ) {\n                pos += rx.matchedLength();\n            }\n        }\n\n        s2=feeds.first();\n        KURL testURL;\n        \/\/ loop through, prefer feeds on same host\n        for ( QStringList::Iterator it = feeds.begin(); it != feeds.end(); ++it ) {\n            testURL=*it;\n            if (testURL.host()==host)\n            {\n                s2=*it;\n                break;\n            }\n        }\n    }\n    \n    if (s2.isNull())\n        return;\n\n    if (KURL::isRelativeURL(s2))\n    {\n        if (s2.startsWith(\"\/\/\"))\n        {\n            s2=s2.prepend(d->url.protocol()+\":\");\n            d->discoveredFeedURL=s2;\n        }\n        else if (s2.startsWith(\"\/\"))\n        {\n            d->discoveredFeedURL=d->url;\n            d->discoveredFeedURL.setPath(s2);\n        }\n        else\n        {\n            d->discoveredFeedURL=d->url;\n            d->discoveredFeedURL.addPath(s2);\n        }\n        d->discoveredFeedURL.cleanPath();\n    }\n    else\n        d->discoveredFeedURL=s2;\n    \n    d->discoveredFeedURL.cleanPath();\n}\n    \n#include \"loader.moc\"\n\/\/ vim:noet:ts=4\n<|endoftext|>"}
{"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"taskfile.h\"\n\n#include \"tasklistplugin.h\"\n\nusing namespace TaskList;\nusing namespace TaskList::Internal;\n\n\/\/ --------------------------------------------------------------------------\n\/\/ TaskFile\n\/\/ --------------------------------------------------------------------------\n\nTaskFile::TaskFile(QObject *parent) : Core::IFile(parent),\n    m_context(0)\n{ }\n\nTaskFile::~TaskFile()\n{ }\n\nbool TaskFile::save(const QString &fileName)\n{\n    Q_UNUSED(fileName);\n    return false;\n}\n\nQString TaskFile::fileName() const\n{\n    return m_fileName;\n}\n\nQString TaskFile::defaultPath() const\n{\n    return QString();\n}\n\nQString TaskFile::suggestedFileName() const\n{\n    return QString();\n}\n\nQString TaskFile::mimeType() const\n{\n    return QString();\n}\n\nbool TaskFile::isModified() const\n{\n    return false;\n}\n\nbool TaskFile::isReadOnly() const\n{\n    return true;\n}\n\nbool TaskFile::isSaveAsAllowed() const\n{\n    return false;\n}\n\nCore::IFile::ReloadBehavior TaskFile::reloadBehavior(ChangeTrigger state, ChangeType type) const\n{\n    Q_UNUSED(state);\n    if (type != TypePermissions)\n        return BehaviorSilent;\n    return BehaviorAsk;\n}\n\nvoid TaskFile::reload(ReloadFlag flag, ChangeType type)\n{\n    Q_UNUSED(flag);\n\n    if (type == TypePermissions)\n        return;\n    open(m_fileName);\n    if (type == TypeRemoved)\n        deleteLater();\n}\n\nvoid TaskFile::rename(const QString &newName)\n{\n    Q_UNUSED(newName);\n}\n\nbool TaskFile::open(const QString &fileName)\n{\n    m_fileName = fileName;\n    return TaskList::TaskListPlugin::instance()->loadFile(m_context, m_fileName);\n}\n\nProjectExplorer::Project *TaskFile::context() const\n{\n    return m_context;\n}\n\nvoid TaskFile::setContext(ProjectExplorer::Project *context)\n{\n    m_context = context;\n}\n\nTaskList: Clean up reopen behavior\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"taskfile.h\"\n\n#include \"tasklistplugin.h\"\n\nusing namespace TaskList;\nusing namespace TaskList::Internal;\n\n\/\/ --------------------------------------------------------------------------\n\/\/ TaskFile\n\/\/ --------------------------------------------------------------------------\n\nTaskFile::TaskFile(QObject *parent) : Core::IFile(parent),\n    m_context(0)\n{ }\n\nTaskFile::~TaskFile()\n{ }\n\nbool TaskFile::save(const QString &fileName)\n{\n    Q_UNUSED(fileName);\n    return false;\n}\n\nQString TaskFile::fileName() const\n{\n    return m_fileName;\n}\n\nQString TaskFile::defaultPath() const\n{\n    return QString();\n}\n\nQString TaskFile::suggestedFileName() const\n{\n    return QString();\n}\n\nQString TaskFile::mimeType() const\n{\n    return QString();\n}\n\nbool TaskFile::isModified() const\n{\n    return false;\n}\n\nbool TaskFile::isReadOnly() const\n{\n    return true;\n}\n\nbool TaskFile::isSaveAsAllowed() const\n{\n    return false;\n}\n\nCore::IFile::ReloadBehavior TaskFile::reloadBehavior(ChangeTrigger state, ChangeType type) const\n{\n    Q_UNUSED(state);\n    Q_UNUSED(type);\n    return BehaviorSilent;\n}\n\nvoid TaskFile::reload(ReloadFlag flag, ChangeType type)\n{\n    Q_UNUSED(flag);\n\n    if (type == TypePermissions)\n        return;\n    open(m_fileName);\n    if (type == TypeRemoved)\n        deleteLater();\n}\n\nvoid TaskFile::rename(const QString &newName)\n{\n    Q_UNUSED(newName);\n}\n\nbool TaskFile::open(const QString &fileName)\n{\n    m_fileName = fileName;\n    return TaskList::TaskListPlugin::instance()->loadFile(m_context, m_fileName);\n}\n\nProjectExplorer::Project *TaskFile::context() const\n{\n    return m_context;\n}\n\nvoid TaskFile::setContext(ProjectExplorer::Project *context)\n{\n    m_context = context;\n}\n\n<|endoftext|>"}
{"text":"fix fetching of geom information from neons<|endoftext|>"}
{"text":"\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* tests\/test-dense.C\n * Copyright (C) 2001, 2002 Bradford Hovinen\n *\n * Written by Bradford Hovinen \n * Modified by Zhendong Wan \n *\n * --------------------------------------------------------\n *\n * See COPYING for license information\n *\/\n\n#include \"linbox\/linbox-config.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/modular.h\"\n#include \"linbox\/blackbox\/dense.h\"\n\n#include \"test-common.h\"\n#include \"test-generic.h\"\n\nusing namespace LinBox;\n\n\/* Test 1: Identity matrix in dense representation\n *\n * Construct a dense representation of an n x n identity matrix and check\n * whether the output of its application to a series of random vectors is equal\n * to the input.\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrix\n * iterations - Number of random vectors to which to apply identity inverse\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testIdentity (Field &F, long n, int iterations) \n{\n\ttypedef typename Vector::Dense Vector;\n\ttypedef DenseMatrix  Blackbox;\n\n\tcommentator.start (\"Testing identity apply\", \"testIdentity\", iterations);\n\n\tbool ret = true;\n\tbool iter_passed = true;\n\n\tint i, j;\n\n\tBlackbox I (F, n, n);\n\ttypename Field::Element one;\n\n\tF.init (one, 1);\n\n\tfor (i = 0; i < n; i++)\n\t\tI.setEntry (i, i, one);\n\n\tVector v(n), w(n);\n\ttypename Field::RandIter r (F);\n\n\tfor (i = 0; i < iterations; i++) {\n\t\tchar buf[80];\n\t\tsnprintf (buf, 80, \"Iteration %d\", i);\n\t\tcommentator.start (buf);\n\n\t\titer_passed = true;\n\n\t\tfor (j = 0; j < n; j++)\n\t\t\tr.random (v[j]);\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\treport << \"Input vector: \";\n\t\tprintVector (F, report, v);\n\n\t\tI.apply (w, v);\n\n\t\treport << \"Output vector: \";\n\t\tprintVector (F, report, w);\n\n\t\tfor (j = 0; j < n; j++)\n\t\t\tif (!F.areEqual (w[j], v[j]))\n\t\t\t\tret = iter_passed = false;\n\n\t\tif (!iter_passed)\n\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t<< \"ERROR: Vectors are not equal\" << endl;\n\n\t\tcommentator.stop (\"done\");\n\t\tcommentator.progress ();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testIdentity\");\n\n\treturn ret;\n}\n\n\/* Test 2: Application of Vandermonde matrix in dense representation\n *\n * Computes a random Vandermonde matrix and applies it to a series of random\n * vectors. The random vectors contain the coefficients of polynomials over the\n * ground field. The output of the application is the result of evaluating these\n * polynomials at the points given by the second column of the matrix. This\n * function interpolates (using Lagrange interpolants) the evaluation points to\n * get the original polynomials and checks whether the coefficients match the\n * original vectors.\n * \n * F - Field over which to perform computations\n * n - Dimension to which to make matrix\n * iterations - Number of random diagonal matrices to construct\n * N - Number of random vectors to which to apply random Vandermonde matrix\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testVandermonde (Field &F, long n, int iterations, int N) \n{\n\ttypedef typename Vector::Dense Vector;\n\ttypedef vector  Polynomial;\n\ttypedef DenseMatrix  Blackbox;\n\n\tcommentator.start (\"Testing Vandermonde apply\", \"testVandermonde\", iterations);\n\n\tbool ret = true;\n\tbool inner_iter_passed;\n\n\tint i, j, k;\n\n\tBlackbox V (F, n, n);\n\n\tVector x(n), v(n), y(n), f(n);\n\ttypename Field::RandIter r (F);\n\ttypename Field::Element t;\n\n\tfor (i = 0; i < iterations; i++) {\n\t\tchar buf[80];\n\t\tsnprintf (buf, 80, \"Iteration %d\", i);\n\t\tcommentator.start (buf);\n\n\t\t\/* Evaluation points *\/\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tbool flag = true;\n\n\t\t\t\/\/ Make sure points are all distinct\n\t\t\twhile (flag) {\n\t\t\t\tr.random (x[j]);\n\t\t\t\tflag = false;\n\t\t\t\tfor (k = 0; k < j; k++)\n\t\t\t\t\tif (F.areEqual (x[j], x[k]))\n\t\t\t\t\t\tflag = true;\n\t\t\t}\n\t\t}\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\treport << \"Evaluation points: \";\n\t\tprintVector (F, report, x);\n\n\t\t\/* Build the Vandermonde matrix *\/\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tF.init (t, 1);\n\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tV.setEntry (j, k, t);\n\t\t\t\tF.mulin (t, x[j]);\n\t\t\t}\n\t\t}\n\n\t\tfor (j = 0; j < N; j++) {\n\t\t\tinner_iter_passed = true;\n\n\t\t\t\/* Random vector of evaluation results *\/\n\t\t\tfor (k = 0; k < n; k++)\n\t\t\t\tr.random (v[k]);\n\n\t\t\treport << \"Input vector: \";\n\t\t\tprintVector (F, report, v);\n\n\t\t\t\/* w should now be a vector of polynomial evaluations *\/\n\t\t\tV.apply (y, v);\n\n\t\t\treport << \"Output vector: \";\n\t\t\tprintVector (F, report, y);\n\n\t\t\t\/* Polynomial interpolation to check whether w is correct *\/\n\t\t\tinterpolatePoly (F, f, x, y);\n\n\t\t\treport << \"Interpolation results: \";\n\t\t\tprintVector (F, report, f);\n\n\t\t\tfor (k = 0; k < n; k++)\n\t\t\t\tif (!F.areEqual (f[k], v[k]))\n\t\t\t\t\tret = inner_iter_passed = false;\n\n\t\t\tif (!inner_iter_passed)\n\t\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t\t<< \"ERROR: Vectors are not equal\" << endl;\n\t\t}\n\n\t\tcommentator.stop (\"done\");\n\t\tcommentator.progress ();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testVandermonde\");\n\n\treturn ret;\n}\n\n\/* Test 3: Random linearity\n *\n * Construct a random dense matrix and a submatrix thereof. Call testLinearity\n * in test-generic.h to test that the submatrix is a linear operator\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrices\n * iterations - Number of iterations to run\n * N - Number of random vectors to which to apply\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testRandomLinearity (const Field                                 &F,\n\t\t\t\t VectorStream::Dense> &A_stream,\n\t\t\t\t VectorStream::Dense> &v1_stream,\n\t\t\t\t VectorStream::Dense> &v2_stream) \n{\n\tcommentator.start (\"Testing random linearity\", \"testRandomLinearity\", v1_stream.size ());\n\n\tDenseMatrix A (F, A_stream);\n\n\tbool ret = testLinearity (F, A, v1_stream, v2_stream);\n\n\tA_stream.reset ();\n\tv1_stream.reset ();\n\tv2_stream.reset ();\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testRandomLinearity\");\n\n\treturn ret;\n}\n\n\/* Test 4: Random transpose\n *\n * Construct a random dense matrix and a submatrix thereof. Call testLinearity\n * in test-generic.h to test that the submatrix is a linear operator\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrices\n * iterations - Number of iterations to run\n * N - Number of random vectors to which to apply\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testRandomTranspose (const Field                                 &F,\n\t\t\t\t VectorStream::Dense> &A_stream,\n\t\t\t\t VectorStream::Dense> &v1_stream,\n\t\t\t\t VectorStream::Dense> &v2_stream) \n{\n\tcommentator.start (\"Testing random transpose\", \"testRandomTranspose\", v1_stream.size ());\n\n\tDenseMatrix A (F, A_stream);\n\n\tbool ret = testTranspose (F, A, v1_stream, v2_stream);\n\n\tA_stream.reset ();\n\tv1_stream.reset ();\n\tv2_stream.reset ();\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testRandomTranspose\");\n\n\treturn ret;\n}\n\n\nint main (int argc, char **argv)\n{\n\tbool pass = true;\n\n\tstatic size_t n = 10;\n\tstatic integer q = 101;\n\tstatic int iterations = 2; \/\/ was 100\n\tstatic int N = 1;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN.\", TYPE_INT,     &n },\n\t\t{ 'q', \"-q Q\", \"Operate over the \\\"field\\\" GF(Q) [1].\", TYPE_INTEGER, &q },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations.\",   TYPE_INT,     &iterations },\n\t\t{ '\\0' }\n\t};\n\n\ttypedef Modular Field;\n\n\tparseArguments (argc, argv, args);\n\tField F (q);\n\n\tcommentator.start(\"Dense matrix black box test suite\", \"DenseMatrix\");\n\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\n\tRandomDenseStream A_stream (F, n, n);\n\tRandomDenseStream v1_stream (F, n, iterations);\n\tRandomDenseStream v2_stream (F, n, iterations);\n\n\tif (!testIdentity    (F, n, iterations)) pass = false;\n\tif (!testVandermonde (F, n, iterations, N)) pass = false;\n\tif (!testRandomLinearity (F, A_stream, v1_stream, v2_stream)) pass = false;\n\tif (!testRandomTranspose (F, A_stream, v1_stream, v2_stream)) pass = false;\n\n\tcommentator.stop(\"dense matrix black box test suite\");\n\treturn pass ? 0 : -1;\n}\n to check an autobuild\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* tests\/test-dense.C\n * Copyright (C) 2001, 2002 Bradford Hovinen\n *\n * Written by Bradford Hovinen \n * Modified by Zhendong Wan \n *\n * --------------------------------------------------------\n *\n * See COPYING for license information\n *\/\n\n#include \"linbox\/linbox-config.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/modular.h\"\n#include \"linbox\/matrix\/dense.h\"\n#include \"linbox\/blackbox\/dense.h\"\n#include \"linbox\/matrix\/dense-submatrix.h\"\n\n#include \"test-common.h\"\n#include \"test-generic.h\"\n\nusing namespace LinBox;\n\n\/* Test 1: Identity matrix in dense representation\n *\n * Construct a dense representation of an n x n identity matrix and check\n * whether the output of its application to a series of random vectors is equal\n * to the input.\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrix\n * iterations - Number of random vectors to which to apply identity inverse\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testIdentity (Field &F, long n, int iterations) \n{\n\ttypedef typename Vector::Dense Vector;\n\ttypedef DenseMatrixBase  Base;\n\ttypedef DenseSubmatrix  Matrix;\n\ttypedef DenseMatrix  Blackbox;\n\n\tcommentator.start (\"Testing identity apply\", \"testIdentity\", iterations);\n\n\tbool ret = true;\n\tbool iter_passed = true;\n\n\tint i, j;\n\n\tBlackbox I(F, n, n);\n\tMatrix K(I);\n\ttypename Field::Element x; F.init(x);\n\tF.write(std::cout, K.getEntry(x, i, j)) << std::endl;\n\t\/\/Matrix L(K);\n\ttypename Field::Element one;\n\n\tF.init (one, 1);\n\n\tfor (i = 0; i < n; i++)\n\t\tI.setEntry (i, i, one);\n\n\tVector v(n), w(n);\n\ttypename Field::RandIter r (F);\n\n\tfor (i = 0; i < iterations; i++) {\n\t\tchar buf[80];\n\t\tsnprintf (buf, 80, \"Iteration %d\", i);\n\t\tcommentator.start (buf);\n\n\t\titer_passed = true;\n\n\t\tfor (j = 0; j < n; j++)\n\t\t\tr.random (v[j]);\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\treport << \"Input vector: \";\n\t\tprintVector (F, report, v);\n\n\t\tI.apply (w, v);\n\t\tprintVector (F, report, w);\n\n\t\tBase J (I);\n\t\tBlackbox K(F, J);\n\t\tK.apply (w, v);\n\t\treport << \"Output vector: \";\n\t\tprintVector (F, report, w);\n\n\t\tfor (j = 0; j < n; j++)\n\t\t\tif (!F.areEqual (w[j], v[j]))\n\t\t\t\tret = iter_passed = false;\n\n\t\tif (!iter_passed)\n\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t<< \"ERROR: Vectors are not equal\" << endl;\n\n\t\tcommentator.stop (\"done\");\n\t\tcommentator.progress ();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testIdentity\");\n\n\treturn ret;\n}\n\n\/* Test 2: Application of Vandermonde matrix in dense representation\n *\n * Computes a random Vandermonde matrix and applies it to a series of random\n * vectors. The random vectors contain the coefficients of polynomials over the\n * ground field. The output of the application is the result of evaluating these\n * polynomials at the points given by the second column of the matrix. This\n * function interpolates (using Lagrange interpolants) the evaluation points to\n * get the original polynomials and checks whether the coefficients match the\n * original vectors.\n * \n * F - Field over which to perform computations\n * n - Dimension to which to make matrix\n * iterations - Number of random diagonal matrices to construct\n * N - Number of random vectors to which to apply random Vandermonde matrix\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testVandermonde (Field &F, long n, int iterations, int N) \n{\n\ttypedef typename Vector::Dense Vector;\n\ttypedef vector  Polynomial;\n\ttypedef DenseMatrix  Blackbox;\n\n\tcommentator.start (\"Testing Vandermonde apply\", \"testVandermonde\", iterations);\n\n\tbool ret = true;\n\tbool inner_iter_passed;\n\n\tint i, j, k;\n\n\tBlackbox V (F, n, n);\n\n\tVector x(n), v(n), y(n), f(n);\n\ttypename Field::RandIter r (F);\n\ttypename Field::Element t;\n\n\tfor (i = 0; i < iterations; i++) {\n\t\tchar buf[80];\n\t\tsnprintf (buf, 80, \"Iteration %d\", i);\n\t\tcommentator.start (buf);\n\n\t\t\/* Evaluation points *\/\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tbool flag = true;\n\n\t\t\t\/\/ Make sure points are all distinct\n\t\t\twhile (flag) {\n\t\t\t\tr.random (x[j]);\n\t\t\t\tflag = false;\n\t\t\t\tfor (k = 0; k < j; k++)\n\t\t\t\t\tif (F.areEqual (x[j], x[k]))\n\t\t\t\t\t\tflag = true;\n\t\t\t}\n\t\t}\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\treport << \"Evaluation points: \";\n\t\tprintVector (F, report, x);\n\n\t\t\/* Build the Vandermonde matrix *\/\n\t\tfor (j = 0; j < n; j++) {\n\t\t\tF.init (t, 1);\n\n\t\t\tfor (k = 0; k < n; k++) {\n\t\t\t\tV.setEntry (j, k, t);\n\t\t\t\tF.mulin (t, x[j]);\n\t\t\t}\n\t\t}\n\n\t\tfor (j = 0; j < N; j++) {\n\t\t\tinner_iter_passed = true;\n\n\t\t\t\/* Random vector of evaluation results *\/\n\t\t\tfor (k = 0; k < n; k++)\n\t\t\t\tr.random (v[k]);\n\n\t\t\treport << \"Input vector: \";\n\t\t\tprintVector (F, report, v);\n\n\t\t\t\/* w should now be a vector of polynomial evaluations *\/\n\t\t\tV.apply (y, v);\n\n\t\t\treport << \"Output vector: \";\n\t\t\tprintVector (F, report, y);\n\n\t\t\t\/* Polynomial interpolation to check whether w is correct *\/\n\t\t\tinterpolatePoly (F, f, x, y);\n\n\t\t\treport << \"Interpolation results: \";\n\t\t\tprintVector (F, report, f);\n\n\t\t\tfor (k = 0; k < n; k++)\n\t\t\t\tif (!F.areEqual (f[k], v[k]))\n\t\t\t\t\tret = inner_iter_passed = false;\n\n\t\t\tif (!inner_iter_passed)\n\t\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t\t<< \"ERROR: Vectors are not equal\" << endl;\n\t\t}\n\n\t\tcommentator.stop (\"done\");\n\t\tcommentator.progress ();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testVandermonde\");\n\n\treturn ret;\n}\n\n\/* Test 3: Random linearity\n *\n * Construct a random dense matrix and a submatrix thereof. Call testLinearity\n * in test-generic.h to test that the submatrix is a linear operator\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrices\n * iterations - Number of iterations to run\n * N - Number of random vectors to which to apply\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testRandomLinearity (const Field                                 &F,\n\t\t\t\t VectorStream::Dense> &A_stream,\n\t\t\t\t VectorStream::Dense> &v1_stream,\n\t\t\t\t VectorStream::Dense> &v2_stream) \n{\n\tcommentator.start (\"Testing random linearity\", \"testRandomLinearity\", v1_stream.size ());\n\n\tDenseMatrix A (F, A_stream);\n\n\tbool ret = testLinearity (F, A, v1_stream, v2_stream);\n\n\tA_stream.reset ();\n\tv1_stream.reset ();\n\tv2_stream.reset ();\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testRandomLinearity\");\n\n\treturn ret;\n}\n\n\/* Test 4: Random transpose\n *\n * Construct a random dense matrix and a submatrix thereof. Call testLinearity\n * in test-generic.h to test that the submatrix is a linear operator\n *\n * F - Field over which to perform computations\n * n - Dimension to which to make matrices\n * iterations - Number of iterations to run\n * N - Number of random vectors to which to apply\n *\n * Return true on success and false on failure\n *\/\n\ntemplate \nstatic bool testRandomTranspose (const Field                                 &F,\n\t\t\t\t VectorStream::Dense> &A_stream,\n\t\t\t\t VectorStream::Dense> &v1_stream,\n\t\t\t\t VectorStream::Dense> &v2_stream) \n{\n\tcommentator.start (\"Testing random transpose\", \"testRandomTranspose\", v1_stream.size ());\n\n\tDenseMatrix A (F, A_stream);\n\n\tbool ret = testTranspose (F, A, v1_stream, v2_stream);\n\n\tA_stream.reset ();\n\tv1_stream.reset ();\n\tv2_stream.reset ();\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testRandomTranspose\");\n\n\treturn ret;\n}\n\n\nint main (int argc, char **argv)\n{\n\tbool pass = true;\n\n\tstatic size_t n = 10;\n\tstatic integer q = 101;\n\tstatic int iterations = 2; \/\/ was 100\n\t\/\/static int N = 1;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN.\", TYPE_INT,     &n },\n\t\t{ 'q', \"-q Q\", \"Operate over the \\\"field\\\" GF(Q) [1].\", TYPE_INTEGER, &q },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations.\",   TYPE_INT,     &iterations },\n\t\t{ '\\0' }\n\t};\n\n\ttypedef Modular Field;\n\n\tparseArguments (argc, argv, args);\n\tField F (q);\n\n\tcommentator.start(\"Dense matrix black box test suite\", \"DenseMatrix\");\n\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\n\tRandomDenseStream A_stream (F, n, n);\n\tRandomDenseStream v1_stream (F, n, iterations);\n\tRandomDenseStream v2_stream (F, n, iterations);\n\n\tif (!testIdentity    (F, n, iterations)) pass = false;\n\t\/\/if (!testVandermonde (F, n, iterations, N)) pass = false;\n\t\/\/if (!testRandomLinearity (F, A_stream, v1_stream, v2_stream)) pass = false;\n\t\/\/if (!testRandomTranspose (F, A_stream, v1_stream, v2_stream)) pass = false;\n\n\tcommentator.stop(\"dense matrix black box test suite\");\n\treturn pass ? 0 : -1;\n}\n<|endoftext|>"}
{"text":"#ifndef __OBJECT_HPP_INCLUDED\n#define __OBJECT_HPP_INCLUDED\n\n#include \"shader.hpp\"\n#include \"species.hpp\"\n#include \"glyph.hpp\"\n#include \"render_templates.hpp\"\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include  \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include  \/\/ glm\n#endif\n\n#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef __GLM_GTC_QUATERNION_HPP_INCLUDED\n#define __GLM_GTC_QUATERNION_HPP_INCLUDED\n#include  \/\/ glm::quat\n#endif\n\n#ifndef __GLM_GTX_QUATERNION_HPP_INCLUDED\n#define __GLM_GTX_QUATERNION_HPP_INCLUDED\n#include  \/\/ glm::toMat4\n#endif\n\n\/\/ Include standard headers\n#include     \/\/ std::queue\n#include  \/\/ uint32_t etc.\n#include    \/\/ std::vector\n\nnamespace ontology\n{\n    class Species;\n    class Glyph;\n\n    class Object\n    {\n        public:\n            \/\/ constructor.\n            Object(ObjectStruct object_struct);\n\n            \/\/ destructor.\n            ~Object();\n\n            \/\/ this method sets pointer to this object to nullptr, sets `parent_pointer` according to the input, and requests a new `childID` from the new species.\n            void bind_to_new_parent(void* new_parent_pointer);\n            template\n                friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector &child_pointer_vector, std::queue &free_childID_queue);\n            template\n                friend void hierarchy::bind_child_to_new_parent(T1 child_pointer, T2 new_parent_pointer, std::vector &old_child_pointer_vector, std::queue &old_free_childID_queue);\n            template\n                friend void render_children(std::vector &child_pointer_vector);\n            template\n                friend void render_this_object(ontology::Object* object_pointer, ontology::Shader* shader_pointer);\n\n            \/\/ this method renders this object.\n            void render();\n\n        private:\n            void bind_to_parent();\n\n            ontology::Species* species_parent_pointer; \/\/ pointer to `Species`.\n            ontology::Glyph* glyph_parent_pointer;     \/\/ pointer to `Glyph`.\n            ontology::Text3D* text3D_parent_pointer;   \/\/ pointer to `Text3D`.\n            bool is_character;\n\n            uint32_t childID;                      \/\/ object ID, returned by `ontology::Species->get_objectID()`.\n            bool has_entered;\n\n            glm::vec3 coordinate_vector;           \/\/ coordinate vector.\n            glm::vec3 original_scale_vector;       \/\/ original scale vector.\n            GLfloat rotate_angle;                  \/\/ rotate angle.\n            glm::vec3 rotate_vector;               \/\/ rotate vector.\n            glm::vec3 translate_vector;            \/\/ translate vector.\n\n            \/\/ The rest fields are created in the constructor.\n            glm::mat4 model_matrix;                \/\/ model matrix.\n            glm::mat4 MVP_matrix;                  \/\/ model view projection matrix.\n    };\n\n    template\n        void render_this_object(ontology::Object* object_pointer, ontology::Shader* shader_pointer)\n        {\n            if (!object_pointer->has_entered)\n            {\n                object_pointer->model_matrix = glm::translate(glm::mat4(1.0f), object_pointer->coordinate_vector);\n                object_pointer->model_matrix = glm::scale(object_pointer->model_matrix, object_pointer->original_scale_vector);\n\n                \/\/ store the new coordinates to be used in the next update.\n                object_pointer->coordinate_vector = glm::vec3(object_pointer->model_matrix[0][0], object_pointer->model_matrix[1][1], object_pointer->model_matrix[2][2]);\n                object_pointer->has_entered = true;\n            }\n            else\n            {\n                \/\/ create `rotation_matrix` using quaternions.\n                glm::quat my_quaternion;\n                my_quaternion = glm::quat(DEGREES_TO_RADIANS(object_pointer->rotate_vector));\n                glm::mat4 rotation_matrix = glm::toMat4(my_quaternion);\n\n                \/\/ rotate.\n                \/\/ this->model_matrix = rotation_matrix * this->model_matrix;\n                if (object_pointer->rotate_vector != glm::vec3(0.0f, 0.0f, 0.0f))\n                {\n                    object_pointer->model_matrix = glm::rotate(object_pointer->model_matrix, object_pointer->rotate_angle, object_pointer->rotate_vector);\n                }\n\n                object_pointer->model_matrix = glm::translate(object_pointer->model_matrix, object_pointer->translate_vector);\n                object_pointer->coordinate_vector = glm::vec3(object_pointer->model_matrix[0][0], object_pointer->model_matrix[1][1], object_pointer->model_matrix[2][2]);\n            }\n\n            object_pointer->MVP_matrix = ProjectionMatrix * ViewMatrix * object_pointer->model_matrix;\n\n            \/\/ Send our transformation to the currently bound shader,\n            \/\/ in the \"MVP\" uniform.\n            \/\/ glUniformMatrix4fv(this->parent_pointer->parent_pointer->parent_pointer->MatrixID, 1, GL_FALSE, &this->MVP_matrix[0][0]);\n            glUniformMatrix4fv(shader_pointer->MatrixID, 1, GL_FALSE, &object_pointer->MVP_matrix[0][0]);\n            \/\/ glUniformMatrix4fv(this->parent_pointer->parent_pointer->parent_pointer->ModelMatrixID, 1, GL_FALSE, &this->model_matrix[0][0]);\n            glUniformMatrix4fv(shader_pointer->ModelMatrixID, 1, GL_FALSE, &object_pointer->model_matrix[0][0]);\n\n            GLuint vertexbuffer;\n            GLuint vertexPosition_modelspaceID;\n            GLuint uvbuffer;\n            GLuint vertexUVID;\n            GLuint normalbuffer;\n            GLuint vertexNormal_modelspaceID;\n            GLuint elementbuffer;\n            GLuint indices_size;\n\n            if (object_pointer->is_character)\n            {\n                ontology::Glyph* parent_glyph = object_pointer->glyph_parent_pointer;\n                vertexbuffer = parent_glyph->vertexbuffer;\n                vertexPosition_modelspaceID = parent_glyph->vertexPosition_modelspaceID;\n                uvbuffer = parent_glyph->uvbuffer;\n                vertexUVID = parent_glyph->vertexUVID;\n                normalbuffer = parent_glyph->normalbuffer;\n                vertexNormal_modelspaceID = parent_glyph->vertexNormal_modelspaceID;\n                elementbuffer = parent_glyph->elementbuffer;\n                indices_size = parent_glyph->indices.size();\n            }\n            else\n            {\n                ontology::Species* parent_species = object_pointer->species_parent_pointer;\n                vertexbuffer = parent_species->vertexbuffer;\n                vertexPosition_modelspaceID = parent_species->vertexPosition_modelspaceID;\n                uvbuffer = parent_species->uvbuffer;\n                vertexUVID = parent_species->vertexUVID;\n                normalbuffer = parent_species->normalbuffer;\n                vertexNormal_modelspaceID = parent_species->vertexNormal_modelspaceID;\n                elementbuffer = parent_species->elementbuffer;\n                indices_size = parent_species->indices.size();\n            }\n\n            \/\/ 1st attribute buffer : vertices.\n            glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n            glVertexAttribPointer(\n                    vertexPosition_modelspaceID, \/\/ The attribute we want to configure\n                    3,                           \/\/ size\n                    GL_FLOAT,                    \/\/ type\n                    GL_FALSE,                    \/\/ normalized?\n                    0,                           \/\/ stride\n                    (void*) 0                    \/\/ array buffer offset\n                    );\n\n            \/\/ 2nd attribute buffer : UVs.\n            glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n            glVertexAttribPointer(\n                    vertexUVID, \/\/ The attribute we want to configure\n                    2,          \/\/ size : U+V => 2\n                    GL_FLOAT,   \/\/ type\n                    GL_FALSE,   \/\/ normalized?\n                    0,          \/\/ stride\n                    (void*) 0   \/\/ array buffer offset\n                    );\n\n            \/\/ 3rd attribute buffer : normals.\n            glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);\n            glVertexAttribPointer(\n                    vertexNormal_modelspaceID, \/\/ The attribute we want to configure\n                    3,                         \/\/ size\n                    GL_FLOAT,                  \/\/ type\n                    GL_FALSE,                  \/\/ normalized?\n                    0,                         \/\/ stride\n                    (void*) 0                  \/\/ array buffer offset\n                    );\n\n            \/\/ Index buffer.\n            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);\n\n            \/\/ Draw the triangles!\n            glDrawElements(\n                    GL_TRIANGLES,    \/\/ mode\n                    indices_size,    \/\/ count\n                    GL_UNSIGNED_INT, \/\/ type\n                    (void*) 0        \/\/ element array buffer offset\n                    );\n        }\n}\n\n#endif\n`void Object::render()` is `private` again.#ifndef __OBJECT_HPP_INCLUDED\n#define __OBJECT_HPP_INCLUDED\n\n#include \"shader.hpp\"\n#include \"species.hpp\"\n#include \"glyph.hpp\"\n#include \"render_templates.hpp\"\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include  \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include  \/\/ glm\n#endif\n\n#ifndef __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#define __GLM_GTC_MATRIX_TRANSFORM_HPP_INCLUDED\n#include \n#endif\n\n#ifndef __GLM_GTC_QUATERNION_HPP_INCLUDED\n#define __GLM_GTC_QUATERNION_HPP_INCLUDED\n#include  \/\/ glm::quat\n#endif\n\n#ifndef __GLM_GTX_QUATERNION_HPP_INCLUDED\n#define __GLM_GTX_QUATERNION_HPP_INCLUDED\n#include  \/\/ glm::toMat4\n#endif\n\n\/\/ Include standard headers\n#include     \/\/ std::queue\n#include  \/\/ uint32_t etc.\n#include    \/\/ std::vector\n\nnamespace ontology\n{\n    class Species;\n    class Glyph;\n\n    class Object\n    {\n        public:\n            \/\/ constructor.\n            Object(ObjectStruct object_struct);\n\n            \/\/ destructor.\n            ~Object();\n\n            \/\/ this method sets pointer to this object to nullptr, sets `parent_pointer` according to the input, and requests a new `childID` from the new species.\n            void bind_to_new_parent(void* new_parent_pointer);\n            template\n                friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector &child_pointer_vector, std::queue &free_childID_queue);\n            template\n                friend void hierarchy::bind_child_to_new_parent(T1 child_pointer, T2 new_parent_pointer, std::vector &old_child_pointer_vector, std::queue &old_free_childID_queue);\n            template\n                friend void render_children(std::vector &child_pointer_vector);\n            template\n                friend void render_this_object(ontology::Object* object_pointer, ontology::Shader* shader_pointer);\n\n        private:\n            void bind_to_parent();\n\n            \/\/ this method renders this object.\n            void render();\n\n            ontology::Species* species_parent_pointer; \/\/ pointer to `Species`.\n            ontology::Glyph* glyph_parent_pointer;     \/\/ pointer to `Glyph`.\n            ontology::Text3D* text3D_parent_pointer;   \/\/ pointer to `Text3D`.\n            bool is_character;\n\n            uint32_t childID;                      \/\/ object ID, returned by `ontology::Species->get_objectID()`.\n            bool has_entered;\n\n            glm::vec3 coordinate_vector;           \/\/ coordinate vector.\n            glm::vec3 original_scale_vector;       \/\/ original scale vector.\n            GLfloat rotate_angle;                  \/\/ rotate angle.\n            glm::vec3 rotate_vector;               \/\/ rotate vector.\n            glm::vec3 translate_vector;            \/\/ translate vector.\n\n            \/\/ The rest fields are created in the constructor.\n            glm::mat4 model_matrix;                \/\/ model matrix.\n            glm::mat4 MVP_matrix;                  \/\/ model view projection matrix.\n    };\n\n    template\n        void render_this_object(ontology::Object* object_pointer, ontology::Shader* shader_pointer)\n        {\n            if (!object_pointer->has_entered)\n            {\n                object_pointer->model_matrix = glm::translate(glm::mat4(1.0f), object_pointer->coordinate_vector);\n                object_pointer->model_matrix = glm::scale(object_pointer->model_matrix, object_pointer->original_scale_vector);\n\n                \/\/ store the new coordinates to be used in the next update.\n                object_pointer->coordinate_vector = glm::vec3(object_pointer->model_matrix[0][0], object_pointer->model_matrix[1][1], object_pointer->model_matrix[2][2]);\n                object_pointer->has_entered = true;\n            }\n            else\n            {\n                \/\/ create `rotation_matrix` using quaternions.\n                glm::quat my_quaternion;\n                my_quaternion = glm::quat(DEGREES_TO_RADIANS(object_pointer->rotate_vector));\n                glm::mat4 rotation_matrix = glm::toMat4(my_quaternion);\n\n                \/\/ rotate.\n                \/\/ this->model_matrix = rotation_matrix * this->model_matrix;\n                if (object_pointer->rotate_vector != glm::vec3(0.0f, 0.0f, 0.0f))\n                {\n                    object_pointer->model_matrix = glm::rotate(object_pointer->model_matrix, object_pointer->rotate_angle, object_pointer->rotate_vector);\n                }\n\n                object_pointer->model_matrix = glm::translate(object_pointer->model_matrix, object_pointer->translate_vector);\n                object_pointer->coordinate_vector = glm::vec3(object_pointer->model_matrix[0][0], object_pointer->model_matrix[1][1], object_pointer->model_matrix[2][2]);\n            }\n\n            object_pointer->MVP_matrix = ProjectionMatrix * ViewMatrix * object_pointer->model_matrix;\n\n            \/\/ Send our transformation to the currently bound shader,\n            \/\/ in the \"MVP\" uniform.\n            \/\/ glUniformMatrix4fv(this->parent_pointer->parent_pointer->parent_pointer->MatrixID, 1, GL_FALSE, &this->MVP_matrix[0][0]);\n            glUniformMatrix4fv(shader_pointer->MatrixID, 1, GL_FALSE, &object_pointer->MVP_matrix[0][0]);\n            \/\/ glUniformMatrix4fv(this->parent_pointer->parent_pointer->parent_pointer->ModelMatrixID, 1, GL_FALSE, &this->model_matrix[0][0]);\n            glUniformMatrix4fv(shader_pointer->ModelMatrixID, 1, GL_FALSE, &object_pointer->model_matrix[0][0]);\n\n            GLuint vertexbuffer;\n            GLuint vertexPosition_modelspaceID;\n            GLuint uvbuffer;\n            GLuint vertexUVID;\n            GLuint normalbuffer;\n            GLuint vertexNormal_modelspaceID;\n            GLuint elementbuffer;\n            GLuint indices_size;\n\n            if (object_pointer->is_character)\n            {\n                ontology::Glyph* parent_glyph = object_pointer->glyph_parent_pointer;\n                vertexbuffer = parent_glyph->vertexbuffer;\n                vertexPosition_modelspaceID = parent_glyph->vertexPosition_modelspaceID;\n                uvbuffer = parent_glyph->uvbuffer;\n                vertexUVID = parent_glyph->vertexUVID;\n                normalbuffer = parent_glyph->normalbuffer;\n                vertexNormal_modelspaceID = parent_glyph->vertexNormal_modelspaceID;\n                elementbuffer = parent_glyph->elementbuffer;\n                indices_size = parent_glyph->indices.size();\n            }\n            else\n            {\n                ontology::Species* parent_species = object_pointer->species_parent_pointer;\n                vertexbuffer = parent_species->vertexbuffer;\n                vertexPosition_modelspaceID = parent_species->vertexPosition_modelspaceID;\n                uvbuffer = parent_species->uvbuffer;\n                vertexUVID = parent_species->vertexUVID;\n                normalbuffer = parent_species->normalbuffer;\n                vertexNormal_modelspaceID = parent_species->vertexNormal_modelspaceID;\n                elementbuffer = parent_species->elementbuffer;\n                indices_size = parent_species->indices.size();\n            }\n\n            \/\/ 1st attribute buffer : vertices.\n            glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);\n            glVertexAttribPointer(\n                    vertexPosition_modelspaceID, \/\/ The attribute we want to configure\n                    3,                           \/\/ size\n                    GL_FLOAT,                    \/\/ type\n                    GL_FALSE,                    \/\/ normalized?\n                    0,                           \/\/ stride\n                    (void*) 0                    \/\/ array buffer offset\n                    );\n\n            \/\/ 2nd attribute buffer : UVs.\n            glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);\n            glVertexAttribPointer(\n                    vertexUVID, \/\/ The attribute we want to configure\n                    2,          \/\/ size : U+V => 2\n                    GL_FLOAT,   \/\/ type\n                    GL_FALSE,   \/\/ normalized?\n                    0,          \/\/ stride\n                    (void*) 0   \/\/ array buffer offset\n                    );\n\n            \/\/ 3rd attribute buffer : normals.\n            glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);\n            glVertexAttribPointer(\n                    vertexNormal_modelspaceID, \/\/ The attribute we want to configure\n                    3,                         \/\/ size\n                    GL_FLOAT,                  \/\/ type\n                    GL_FALSE,                  \/\/ normalized?\n                    0,                         \/\/ stride\n                    (void*) 0                  \/\/ array buffer offset\n                    );\n\n            \/\/ Index buffer.\n            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);\n\n            \/\/ Draw the triangles!\n            glDrawElements(\n                    GL_TRIANGLES,    \/\/ mode\n                    indices_size,    \/\/ count\n                    GL_UNSIGNED_INT, \/\/ type\n                    (void*) 0        \/\/ element array buffer offset\n                    );\n        }\n}\n\n#endif\n<|endoftext|>"}
{"text":"\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n                    Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n# include \n\/*!\n\\file match_op.hpp\nCheck if current operator matches a previous operator.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize  {\n\/*!\nSearch for a previous operator that matches the current one.\n\n\\param var2op\nmapping from variable index to operator index.\n\n\\param op_info\nmapping from operator index to operator information\n\n\\param current\nis the index of the current operator.\n\n\\li\nThis must be a unary or binary\noperator; hence, NumArg( op_info[current].op ) is one or two.\nThere is one exception, NumRes( ErfOp ) == 3, but arg[0]\nis the only true arguments (the others are always the same).\n\n\\li\nThis must not be a VecAD load or store operation; i.e.,\nLtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.\nIt also must not be an independent variable operator InvOp.\n\n\\param hash_table_op\nis a vector with size CPPAD_HASH_TABLE_SIZE\nthat maps a hash code to the corresponding\nvariable index in the operation sequence.\nAll the values in this table are less than current.\n\n\\param code [out]\nThe input value of code does not matter.\nThe output value of code is the hash code corresponding to\nthe current operation in the new operation sequence.\n\n\\return\nWe refer to the return value as pevious.\nIf pevious == 0, no match was found.\nIf previous != 0,\nit is a pevious operator that can be used in place of current.\nIn addition op_info[previous].previous == 0.\n*\/\n\ninline size_t match_op(\n\tconst vector&                              var2op         ,\n\tconst vector&                      op_info        ,\n\tsize_t                                             current        ,\n\tconst vector&                              hash_table_op  ,\n\tunsigned short&                                    code           )\n{\t\/\/ current operator\n\tOpCode        op         = op_info[current].op;\n\tconst addr_t* arg        = op_info[current].arg;\n\t\/\/\n\t\/\/ which arguments are variable\n\tsize_t num_arg = NumArg(op);\n\t\/\/\n\tbool   variable[2];\n\tvariable[0] = false;\n\tvariable[1] = false;\n\t\/\/\n\t\/\/ If i-th argument to current operator has a previous operator,\n\t\/\/ this is the i-th argument for previous operator.\n\t\/\/ Otherwise, it is the i-th argument for the current operator\n\t\/\/ (if a previous variable exists)\n\taddr_t arg_match[2];\n\tswitch(op)\n\t{\t\/\/\n\t\tcase ErfOp:\n\t\tcase AbsOp:\n\t\tcase AcosOp:\n\t\tcase AcoshOp:\n\t\tcase AsinOp:\n\t\tcase AsinhOp:\n\t\tcase AtanOp:\n\t\tcase AtanhOp:\n\t\tcase CosOp:\n\t\tcase CoshOp:\n\t\tcase ExpOp:\n\t\tcase Expm1Op:\n\t\tcase LogOp:\n\t\tcase Log1pOp:\n\t\tcase SignOp:\n\t\tcase SinOp:\n\t\tcase SinhOp:\n\t\tcase SqrtOp:\n\t\tcase TanOp:\n\t\tcase TanhOp:\n\t\t{\targ_match[0] = arg[0];\n\t\t\tsize_t previous = op_info[ var2op[arg[0]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\targ_match[0] = op_info[previous].i_var;\n\t\t\t}\n\t\t\tnum_arg = 1;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate  = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\tif( (candidate == 0) | (op != op_info[candidate].op) )\n\t\t\t\treturn 0;\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match;\n\t\t\tprevious = op_info[ var2op[op_info[candidate].arg[0]] ].previous;\n\t\t\tif( previous == 0 )\n\t\t\t\tmatch = arg_match[0] == op_info[candidate].arg[0];\n\t\t\telse\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\tmatch = arg_match[0] == addr_t( op_info[previous].i_var );\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\n\t\tcase AddpvOp:\n\t\tcase DisOp:\n\t\tcase DivpvOp:\n\t\tcase EqpvOp:\n\t\tcase LepvOp:\n\t\tcase LtpvOp:\n\t\tcase MulpvOp:\n\t\tcase NepvOp:\n\t\tcase PowpvOp:\n\t\tcase SubpvOp:\n\t\tcase ZmulpvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tcase DivvpOp:\n\t\tcase LevpOp:\n\t\tcase LtvpOp:\n\t\tcase PowvpOp:\n\t\tcase SubvpOp:\n\t\tcase ZmulvpOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tbreak;\n\n\t\tcase AddvvOp:\n\t\tcase DivvvOp:\n\t\tcase EqvvOp:\n\t\tcase LevvOp:\n\t\tcase LtvvOp:\n\t\tcase MulvvOp:\n\t\tcase NevvOp:\n\t\tcase PowvvOp:\n\t\tcase SubvvOp:\n\t\tcase ZmulvvOp:\n\t\tCPPAD_ASSERT_UNKNOWN( num_arg == 2 );\n\t\tvariable[0] = true;\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t}\n\tfor(size_t j = 0; j < num_arg; ++j)\n\t{\targ_match[j] = arg[j];\n\t\tif( variable[j] )\n\t\t{\tsize_t previous = op_info[ var2op[arg[j]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\/\/\n\t\t\t\targ_match[j] = op_info[previous].i_var;\n\t\t\t}\n\t\t}\n\t}\n\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\/\/\n\t\/\/ candidate previous for current operator\n\tsize_t  candidate  = hash_table_op[code];\n\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\/\/\n\t\/\/ check for a match\n\tbool match = candidate != 0;\n\tmatch     &= op == op_info[candidate].op;\n\tif( match )\n\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t{\tif( variable[j] )\n\t\t\t{\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t}\n\t\tif( match )\n\t\t\treturn candidate;\n\t}\n\n\t\/\/ special case where operator is commutative\n\tif( (op == AddvvOp) | (op == MulvvOp ) )\n\t{\tCPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );\n\t\tstd::swap( arg_match[0], arg_match[1] );\n\t\t\/\/\n\t\tcode      = optimize_hash_code(op, num_arg, arg_match);\n\t\tcandidate  = hash_table_op[code];\n\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\/\/\n\t\tmatch  = candidate != 0;\n\t\tmatch &= op == op_info[candidate].op;\n\t\tif( match )\n\t\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( variable[j] )\n\t\t\t\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t}\n\t}\n\t\/\/ special op code used for no match\n\treturn 0;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n# endif\noptimize branch: match_op.hpp: Convert more operators to special cases.\/\/ $Id$\n# ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP\n\/* --------------------------------------------------------------------------\nCppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell\n\nCppAD is distributed under multiple licenses. This distribution is under\nthe terms of the\n                    Eclipse Public License Version 1.0.\n\nA copy of this license is included in the COPYING file of this distribution.\nPlease visit http:\/\/www.coin-or.org\/CppAD\/ for information on other licenses.\n-------------------------------------------------------------------------- *\/\n# include \n\/*!\n\\file match_op.hpp\nCheck if current operator matches a previous operator.\n*\/\n\/\/ BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\nnamespace CppAD { namespace local { namespace optimize  {\n\/*!\nSearch for a previous operator that matches the current one.\n\n\\param var2op\nmapping from variable index to operator index.\n\n\\param op_info\nmapping from operator index to operator information\n\n\\param current\nis the index of the current operator.\n\n\\li\nThis must be a unary or binary\noperator; hence, NumArg( op_info[current].op ) is one or two.\nThere is one exception, NumRes( ErfOp ) == 3, but arg[0]\nis the only true arguments (the others are always the same).\n\n\\li\nThis must not be a VecAD load or store operation; i.e.,\nLtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.\nIt also must not be an independent variable operator InvOp.\n\n\\param hash_table_op\nis a vector with size CPPAD_HASH_TABLE_SIZE\nthat maps a hash code to the corresponding\nvariable index in the operation sequence.\nAll the values in this table are less than current.\n\n\\param code [out]\nThe input value of code does not matter.\nThe output value of code is the hash code corresponding to\nthe current operation in the new operation sequence.\n\n\\return\nWe refer to the return value as pevious.\nIf pevious == 0, no match was found.\nIf previous != 0,\nit is a pevious operator that can be used in place of current.\nIn addition op_info[previous].previous == 0.\n*\/\n\ninline size_t match_op(\n\tconst vector&                              var2op         ,\n\tconst vector&                      op_info        ,\n\tsize_t                                             current        ,\n\tconst vector&                              hash_table_op  ,\n\tunsigned short&                                    code           )\n{\t\/\/ current operator\n\tOpCode        op         = op_info[current].op;\n\tconst addr_t* arg        = op_info[current].arg;\n\t\/\/\n\t\/\/ which arguments are variable\n\tsize_t num_arg = NumArg(op);\n\t\/\/\n\tbool   variable[2];\n\tvariable[0] = false;\n\tvariable[1] = false;\n\t\/\/\n\t\/\/ If i-th argument to current operator has a previous operator,\n\t\/\/ this is the i-th argument for previous operator.\n\t\/\/ Otherwise, it is the i-th argument for the current operator\n\t\/\/ (if a previous variable exists)\n\taddr_t arg_match[2];\n\tswitch(op)\n\t{\t\/\/\n\t\tcase ErfOp:\n\t\tcase AbsOp:\n\t\tcase AcosOp:\n\t\tcase AcoshOp:\n\t\tcase AsinOp:\n\t\tcase AsinhOp:\n\t\tcase AtanOp:\n\t\tcase AtanhOp:\n\t\tcase CosOp:\n\t\tcase CoshOp:\n\t\tcase ExpOp:\n\t\tcase Expm1Op:\n\t\tcase LogOp:\n\t\tcase Log1pOp:\n\t\tcase SignOp:\n\t\tcase SinOp:\n\t\tcase SinhOp:\n\t\tcase SqrtOp:\n\t\tcase TanOp:\n\t\tcase TanhOp:\n\t\t{\t\/\/ arg[0] is a variable index\n\t\t\targ_match[0] = arg[0];\n\t\t\tsize_t previous = op_info[ var2op[arg[0]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\targ_match[0] = op_info[previous].i_var;\n\t\t\t}\n\t\t\tnum_arg = 1;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate  = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\tif( (candidate == 0) | (op != op_info[candidate].op) )\n\t\t\t\treturn 0;\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match;\n\t\t\tprevious = op_info[ var2op[op_info[candidate].arg[0]] ].previous;\n\t\t\tif( previous == 0 )\n\t\t\t\tmatch = arg_match[0] == op_info[candidate].arg[0];\n\t\t\telse\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\tmatch = arg_match[0] == addr_t( op_info[previous].i_var );\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\n\t\tcase AddpvOp:\n\t\tcase DisOp:\n\t\tcase DivpvOp:\n\t\tcase EqpvOp:\n\t\tcase LepvOp:\n\t\tcase LtpvOp:\n\t\tcase MulpvOp:\n\t\tcase NepvOp:\n\t\tcase PowpvOp:\n\t\tcase SubpvOp:\n\t\tcase ZmulpvOp:\n\t\t{\t\/\/ arg[0] is a parameter index, arg[1] is a variable index\n\t\t\targ_match[0] = arg[0];\n\t\t\targ_match[1] = arg[1];\n\t\t\tsize_t previous = op_info[ var2op[arg[1]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\targ_match[1] = op_info[previous].i_var;\n\t\t\t}\n\t\t\tnum_arg = 2;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate  = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match = candidate != 0;\n\t\t\tmatch     &= op == op_info[candidate].op;\n\t\t\tmatch     &= arg[0] == op_info[candidate].arg[0];\n\t\t\tif( ! match )\n\t\t\t\treturn 0;\n\t\t\t\/\/\n\t\t\tprevious = op_info[ var2op[op_info[candidate].arg[1]] ].previous;\n\t\t\tif( previous == 0 )\n\t\t\t\tmatch = arg_match[1] == op_info[candidate].arg[1];\n\t\t\telse\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\tmatch = arg_match[1] == addr_t( op_info[previous].i_var );\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\t\tcase DivvpOp:\n\t\tcase LevpOp:\n\t\tcase LtvpOp:\n\t\tcase PowvpOp:\n\t\tcase SubvpOp:\n\t\tcase ZmulvpOp:\n\t\t{\t\/\/ arg[0] is a variable index, arg[1] is a parameter index\n\t\t\targ_match[0] = arg[0];\n\t\t\targ_match[1] = arg[1];\n\t\t\tsize_t previous = op_info[ var2op[arg[0]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\targ_match[0] = op_info[previous].i_var;\n\t\t\t}\n\t\t\tnum_arg = 2;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate  = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match = candidate != 0;\n\t\t\tmatch     &= op == op_info[candidate].op;\n\t\t\tmatch     &= arg[1] == op_info[candidate].arg[1];\n\t\t\tif( ! match )\n\t\t\t\treturn 0;\n\t\t\t\/\/\n\t\t\tprevious = op_info[ var2op[op_info[candidate].arg[0]] ].previous;\n\t\t\tif( previous == 0 )\n\t\t\t\tmatch = arg_match[0] == op_info[candidate].arg[0];\n\t\t\telse\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\tmatch = arg_match[0] == addr_t( op_info[previous].i_var );\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\t\tcase DivvvOp:\n\t\tcase EqvvOp:\n\t\tcase LevvOp:\n\t\tcase LtvvOp:\n\t\tcase NevvOp:\n\t\tcase PowvvOp:\n\t\tcase SubvvOp:\n\t\tcase ZmulvvOp:\n\t\t{\t\/\/ arg[0] is a variable index, arg[1] is a variable index\n\t\t\targ_match[0] = arg[0];\n\t\t\targ_match[1] = arg[1];\n\t\t\tsize_t previous;\n\t\t\tfor(size_t j = 0; j < 2; j++)\n\t\t\t{\tprevious = op_info[ var2op[arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\targ_match[j] = op_info[previous].i_var;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnum_arg = 2;\n\t\t\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\t\t\/\/\n\t\t\t\/\/ candidate previous for current operator\n\t\t\tsize_t candidate  = hash_table_op[code];\n\t\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\t\/\/\n\t\t\t\/\/ check for a match\n\t\t\tbool match = candidate != 0;\n\t\t\tmatch     &= op == op_info[candidate].op;\n\t\t\tif( ! match )\n\t\t\t\treturn 0;\n\t\t\tfor(size_t j = 0; j < 2; j++)\n\t\t\t{\tprevious =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous == 0 )\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t\telse\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN(op_info[previous].previous == 0);\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t\treturn 0;\n\t\t}\n\t\tbreak;\n\n\t\tcase AddvvOp:\n\t\tcase MulvvOp:\n\t\tnum_arg = 2;\n\t\tvariable[0] = true;\n\t\tvariable[1] = true;\n\t\tbreak;\n\n\t\tdefault:\n\t\tCPPAD_ASSERT_UNKNOWN(false);\n\t}\n\tfor(size_t j = 0; j < num_arg; ++j)\n\t{\targ_match[j] = arg[j];\n\t\tif( variable[j] )\n\t\t{\tsize_t previous = op_info[ var2op[arg[j]] ].previous;\n\t\t\tif( previous != 0 )\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\/\/\n\t\t\t\targ_match[j] = op_info[previous].i_var;\n\t\t\t}\n\t\t}\n\t}\n\tcode = optimize_hash_code(op, num_arg, arg_match);\n\t\/\/\n\t\/\/ candidate previous for current operator\n\tsize_t  candidate  = hash_table_op[code];\n\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\/\/\n\t\/\/ check for a match\n\tbool match = candidate != 0;\n\tmatch     &= op == op_info[candidate].op;\n\tif( match )\n\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t{\tif( variable[j] )\n\t\t\t{\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t}\n\t\tif( match )\n\t\t\treturn candidate;\n\t}\n\n\t\/\/ special case where operator is commutative\n\tif( (op == AddvvOp) | (op == MulvvOp ) )\n\t{\tCPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );\n\t\tstd::swap( arg_match[0], arg_match[1] );\n\t\t\/\/\n\t\tcode      = optimize_hash_code(op, num_arg, arg_match);\n\t\tcandidate  = hash_table_op[code];\n\t\tCPPAD_ASSERT_UNKNOWN( candidate < current );\n\t\tCPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );\n\t\t\/\/\n\t\tmatch  = candidate != 0;\n\t\tmatch &= op == op_info[candidate].op;\n\t\tif( match )\n\t\t{\tfor(size_t j = 0; j < num_arg; j++)\n\t\t\t{\tCPPAD_ASSERT_UNKNOWN( variable[j] )\n\t\t\t\tsize_t previous =\n\t\t\t\t\top_info[ var2op[op_info[candidate].arg[j]] ].previous;\n\t\t\t\tif( previous != 0 )\n\t\t\t\t{\tCPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );\n\t\t\t\t\t\/\/\n\t\t\t\t\tmatch &= arg_match[j] == addr_t( op_info[previous].i_var );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tmatch &= arg_match[j] == op_info[candidate].arg[j];\n\t\t\t}\n\t\t\tif( match )\n\t\t\t\treturn candidate;\n\t\t}\n\t}\n\t\/\/ special op code used for no match\n\treturn 0;\n}\n\n} } } \/\/ END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE\n\n# endif\n<|endoftext|>"}
{"text":"INTEGRATION: CWS locales201 (1.8.80); FILE MERGED 2005\/10\/08 08:55:23 er 1.8.80.2: RESYNC: (1.8-1.9); FILE MERGED 2005\/08\/23 15:41:00 er 1.8.80.1: #i46908# parseText: during rewind from value switch state if ignoring leading whitespace, don't loop forever<|endoftext|>"}
{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nnamespace\n{\n\nusing cppuhelper::detail::XExceptionThrower;\n\n\nstruct ExceptionThrower : public uno_Interface, XExceptionThrower\n{\n    inline ExceptionThrower();\n\n    virtual ~ExceptionThrower() {}\n\n    static inline Type const & getCppuType()\n    {\n        return ::getCppuType(\n            reinterpret_cast< Reference< XExceptionThrower > const * >(0) );\n    }\n\n    \/\/ XInterface\n    virtual Any SAL_CALL queryInterface( Type const & type )\n        throw (RuntimeException, std::exception) SAL_OVERRIDE;\n    virtual void SAL_CALL acquire() throw () SAL_OVERRIDE;\n    virtual void SAL_CALL release() throw () SAL_OVERRIDE;\n\n    \/\/ XExceptionThrower\n    virtual void SAL_CALL throwException( Any const & exc ) throw (Exception, std::exception) SAL_OVERRIDE;\n    virtual void SAL_CALL rethrowException() throw (Exception, std::exception) SAL_OVERRIDE;\n};\n\nextern \"C\"\n{\n\n\nstatic void SAL_CALL ExceptionThrower_acquire_release_nop(\n    SAL_UNUSED_PARAMETER uno_Interface * )\n{}\n\n\nstatic void SAL_CALL ExceptionThrower_dispatch(\n    uno_Interface * pUnoI, typelib_TypeDescription const * pMemberType,\n    void * pReturn, void * pArgs [], uno_Any ** ppException )\n{\n    OSL_ASSERT( pMemberType->eTypeClass == typelib_TypeClass_INTERFACE_METHOD );\n\n    switch (reinterpret_cast< typelib_InterfaceMemberTypeDescription * >(\n                const_cast< typelib_TypeDescription * >( pMemberType ) )->\n            nPosition)\n    {\n    case 0: \/\/ queryInterace()\n    {\n        Type const & rType_demanded =\n            *reinterpret_cast< Type const * >( pArgs[ 0 ] );\n        if (rType_demanded.equals(\n                ::getCppuType( reinterpret_cast<\n                               Reference< XInterface > const * >(0) ) ) ||\n            rType_demanded.equals( ExceptionThrower::getCppuType() ))\n        {\n            typelib_TypeDescription * pTD = 0;\n            TYPELIB_DANGER_GET( &pTD, rType_demanded.getTypeLibType() );\n            uno_any_construct(\n                reinterpret_cast< uno_Any * >( pReturn ), &pUnoI, pTD, 0 );\n            TYPELIB_DANGER_RELEASE( pTD );\n        }\n        else\n        {\n            uno_any_construct(\n                reinterpret_cast< uno_Any * >( pReturn ), 0, 0, 0 );\n        }\n        *ppException = 0;\n        break;\n    }\n    case 1: \/\/ acquire()\n    case 2: \/\/ release()\n        *ppException = 0;\n        break;\n    case 3: \/\/ throwException()\n    {\n        uno_Any * pAny = reinterpret_cast< uno_Any * >( pArgs[ 0 ] );\n        OSL_ASSERT( pAny->pType->eTypeClass == typelib_TypeClass_EXCEPTION );\n        uno_type_any_construct( *ppException, pAny->pData, pAny->pType, 0 );\n        break;\n    }\n    default:\n    {\n        OSL_ASSERT( false );\n        RuntimeException exc( \"not implemented!\" );\n        uno_type_any_construct(\n            *ppException, &exc, ::getCppuType( &exc ).getTypeLibType(), 0 );\n        break;\n    }\n    }\n}\n\n} \/\/ extern \"C\"\n\n\nAny ExceptionThrower::queryInterface( Type const & type )\n    throw (RuntimeException, std::exception)\n{\n    if (type.equals( ::getCppuType( reinterpret_cast<\n                                    Reference< XInterface > const * >(0) ) ) ||\n        type.equals( ExceptionThrower::getCppuType() ))\n    {\n        XExceptionThrower * that = static_cast< XExceptionThrower * >( this );\n        return Any( &that, type );\n    }\n    return Any();\n}\n\n\nvoid ExceptionThrower::acquire() throw ()\n{\n}\n\nvoid ExceptionThrower::release() throw ()\n{\n}\n\n\nvoid ExceptionThrower::throwException( Any const & exc ) throw (Exception, std::exception)\n{\n    OSL_FAIL( \"unexpected!\" );\n    throwException( exc );\n}\n\n\nvoid ExceptionThrower::rethrowException() throw (Exception, std::exception)\n{\n    throw;\n}\n\n\ninline ExceptionThrower::ExceptionThrower()\n{\n    uno_Interface::acquire = ExceptionThrower_acquire_release_nop;\n    uno_Interface::release = ExceptionThrower_acquire_release_nop;\n    uno_Interface::pDispatcher = ExceptionThrower_dispatch;\n}\n\nclass theExceptionThrower : public rtl::Static {};\n\n} \/\/ anonymous namespace\n\n\nnamespace cppu\n{\n\n\nvoid SAL_CALL throwException( Any const & exc )\n{\n    if (exc.getValueTypeClass() != TypeClass_EXCEPTION)\n    {\n        throw RuntimeException(\n            \"no UNO exception given \"\n            \"(must be derived from com::sun::star::uno::Exception)!\" );\n    }\n\n    Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent());\n    if (! uno2cpp.is())\n    {\n        throw RuntimeException(\n            \"cannot get binary UNO to C++ mapping!\" );\n    }\n\n    Reference< XExceptionThrower > xThrower;\n    uno2cpp.mapInterface(\n        reinterpret_cast< void ** >( &xThrower ),\n        static_cast< uno_Interface * >( &theExceptionThrower::get() ),\n        ExceptionThrower::getCppuType() );\n    OSL_ASSERT( xThrower.is() );\n    xThrower->throwException( exc );\n}\n\n\nAny SAL_CALL getCaughtException()\n{\n    Mapping cpp2uno(Environment::getCurrent(), Environment(UNO_LB_UNO));\n    if (! cpp2uno.is())\n    {\n        throw RuntimeException(\n            \"cannot get C++ to binary UNO mapping!\" );\n    }\n    Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent());\n    if (! uno2cpp.is())\n    {\n        throw RuntimeException(\n            \"cannot get binary UNO to C++ mapping!\" );\n    }\n\n    typelib_TypeDescription * pTD = 0;\n    TYPELIB_DANGER_GET(\n        &pTD, ExceptionThrower::getCppuType().getTypeLibType() );\n\n    UnoInterfaceReference unoI;\n    cpp2uno.mapInterface(\n        reinterpret_cast< void ** >( &unoI.m_pUnoI ),\n        static_cast< XExceptionThrower * >( &theExceptionThrower::get() ), pTD );\n    OSL_ASSERT( unoI.is() );\n\n    typelib_TypeDescription * pMemberTD = 0;\n    TYPELIB_DANGER_GET(\n        &pMemberTD,\n        reinterpret_cast< typelib_InterfaceTypeDescription * >( pTD )->\n        ppMembers[ 1 ] \/* rethrowException() *\/ );\n\n    uno_Any exc_mem;\n    uno_Any * exc = &exc_mem;\n    unoI.dispatch( pMemberTD, 0, 0, &exc );\n\n    TYPELIB_DANGER_RELEASE( pMemberTD );\n    TYPELIB_DANGER_RELEASE( pTD );\n\n    if (exc == 0)\n    {\n        throw RuntimeException( \"rethrowing C++ exception failed!\" );\n    }\n\n    Any ret;\n    uno_any_destruct( &ret, reinterpret_cast< uno_ReleaseFunc >(cpp_release) );\n    uno_type_any_constructAndConvert(\n        &ret, exc->pData, exc->pType, uno2cpp.get() );\n    uno_any_destruct( exc, 0 );\n    return ret;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n-Werror,-Winfinite-recursion\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ::osl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nnamespace\n{\n\nusing cppuhelper::detail::XExceptionThrower;\n\n\nstruct ExceptionThrower : public uno_Interface, XExceptionThrower\n{\n    inline ExceptionThrower();\n\n    virtual ~ExceptionThrower() {}\n\n    static inline Type const & getCppuType()\n    {\n        return ::getCppuType(\n            reinterpret_cast< Reference< XExceptionThrower > const * >(0) );\n    }\n\n    \/\/ XInterface\n    virtual Any SAL_CALL queryInterface( Type const & type )\n        throw (RuntimeException, std::exception) SAL_OVERRIDE;\n    virtual void SAL_CALL acquire() throw () SAL_OVERRIDE;\n    virtual void SAL_CALL release() throw () SAL_OVERRIDE;\n\n    \/\/ XExceptionThrower\n    virtual void SAL_CALL throwException( Any const & exc ) throw (Exception, std::exception) SAL_OVERRIDE;\n    virtual void SAL_CALL rethrowException() throw (Exception, std::exception) SAL_OVERRIDE;\n};\n\nextern \"C\"\n{\n\n\nstatic void SAL_CALL ExceptionThrower_acquire_release_nop(\n    SAL_UNUSED_PARAMETER uno_Interface * )\n{}\n\n\nstatic void SAL_CALL ExceptionThrower_dispatch(\n    uno_Interface * pUnoI, typelib_TypeDescription const * pMemberType,\n    void * pReturn, void * pArgs [], uno_Any ** ppException )\n{\n    OSL_ASSERT( pMemberType->eTypeClass == typelib_TypeClass_INTERFACE_METHOD );\n\n    switch (reinterpret_cast< typelib_InterfaceMemberTypeDescription * >(\n                const_cast< typelib_TypeDescription * >( pMemberType ) )->\n            nPosition)\n    {\n    case 0: \/\/ queryInterace()\n    {\n        Type const & rType_demanded =\n            *reinterpret_cast< Type const * >( pArgs[ 0 ] );\n        if (rType_demanded.equals(\n                ::getCppuType( reinterpret_cast<\n                               Reference< XInterface > const * >(0) ) ) ||\n            rType_demanded.equals( ExceptionThrower::getCppuType() ))\n        {\n            typelib_TypeDescription * pTD = 0;\n            TYPELIB_DANGER_GET( &pTD, rType_demanded.getTypeLibType() );\n            uno_any_construct(\n                reinterpret_cast< uno_Any * >( pReturn ), &pUnoI, pTD, 0 );\n            TYPELIB_DANGER_RELEASE( pTD );\n        }\n        else\n        {\n            uno_any_construct(\n                reinterpret_cast< uno_Any * >( pReturn ), 0, 0, 0 );\n        }\n        *ppException = 0;\n        break;\n    }\n    case 1: \/\/ acquire()\n    case 2: \/\/ release()\n        *ppException = 0;\n        break;\n    case 3: \/\/ throwException()\n    {\n        uno_Any * pAny = reinterpret_cast< uno_Any * >( pArgs[ 0 ] );\n        OSL_ASSERT( pAny->pType->eTypeClass == typelib_TypeClass_EXCEPTION );\n        uno_type_any_construct( *ppException, pAny->pData, pAny->pType, 0 );\n        break;\n    }\n    default:\n    {\n        OSL_ASSERT( false );\n        RuntimeException exc( \"not implemented!\" );\n        uno_type_any_construct(\n            *ppException, &exc, ::getCppuType( &exc ).getTypeLibType(), 0 );\n        break;\n    }\n    }\n}\n\n} \/\/ extern \"C\"\n\n\nAny ExceptionThrower::queryInterface( Type const & type )\n    throw (RuntimeException, std::exception)\n{\n    if (type.equals( ::getCppuType( reinterpret_cast<\n                                    Reference< XInterface > const * >(0) ) ) ||\n        type.equals( ExceptionThrower::getCppuType() ))\n    {\n        XExceptionThrower * that = static_cast< XExceptionThrower * >( this );\n        return Any( &that, type );\n    }\n    return Any();\n}\n\n\nvoid ExceptionThrower::acquire() throw ()\n{\n}\n\nvoid ExceptionThrower::release() throw ()\n{\n}\n\n\nvoid ExceptionThrower::throwException( Any const & exc ) throw (Exception, std::exception)\n{\n    OSL_FAIL( \"unexpected!\" );\n    cppu::throwException( exc );\n}\n\n\nvoid ExceptionThrower::rethrowException() throw (Exception, std::exception)\n{\n    throw;\n}\n\n\ninline ExceptionThrower::ExceptionThrower()\n{\n    uno_Interface::acquire = ExceptionThrower_acquire_release_nop;\n    uno_Interface::release = ExceptionThrower_acquire_release_nop;\n    uno_Interface::pDispatcher = ExceptionThrower_dispatch;\n}\n\nclass theExceptionThrower : public rtl::Static {};\n\n} \/\/ anonymous namespace\n\n\nnamespace cppu\n{\n\n\nvoid SAL_CALL throwException( Any const & exc )\n{\n    if (exc.getValueTypeClass() != TypeClass_EXCEPTION)\n    {\n        throw RuntimeException(\n            \"no UNO exception given \"\n            \"(must be derived from com::sun::star::uno::Exception)!\" );\n    }\n\n    Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent());\n    if (! uno2cpp.is())\n    {\n        throw RuntimeException(\n            \"cannot get binary UNO to C++ mapping!\" );\n    }\n\n    Reference< XExceptionThrower > xThrower;\n    uno2cpp.mapInterface(\n        reinterpret_cast< void ** >( &xThrower ),\n        static_cast< uno_Interface * >( &theExceptionThrower::get() ),\n        ExceptionThrower::getCppuType() );\n    OSL_ASSERT( xThrower.is() );\n    xThrower->throwException( exc );\n}\n\n\nAny SAL_CALL getCaughtException()\n{\n    Mapping cpp2uno(Environment::getCurrent(), Environment(UNO_LB_UNO));\n    if (! cpp2uno.is())\n    {\n        throw RuntimeException(\n            \"cannot get C++ to binary UNO mapping!\" );\n    }\n    Mapping uno2cpp(Environment(UNO_LB_UNO), Environment::getCurrent());\n    if (! uno2cpp.is())\n    {\n        throw RuntimeException(\n            \"cannot get binary UNO to C++ mapping!\" );\n    }\n\n    typelib_TypeDescription * pTD = 0;\n    TYPELIB_DANGER_GET(\n        &pTD, ExceptionThrower::getCppuType().getTypeLibType() );\n\n    UnoInterfaceReference unoI;\n    cpp2uno.mapInterface(\n        reinterpret_cast< void ** >( &unoI.m_pUnoI ),\n        static_cast< XExceptionThrower * >( &theExceptionThrower::get() ), pTD );\n    OSL_ASSERT( unoI.is() );\n\n    typelib_TypeDescription * pMemberTD = 0;\n    TYPELIB_DANGER_GET(\n        &pMemberTD,\n        reinterpret_cast< typelib_InterfaceTypeDescription * >( pTD )->\n        ppMembers[ 1 ] \/* rethrowException() *\/ );\n\n    uno_Any exc_mem;\n    uno_Any * exc = &exc_mem;\n    unoI.dispatch( pMemberTD, 0, 0, &exc );\n\n    TYPELIB_DANGER_RELEASE( pMemberTD );\n    TYPELIB_DANGER_RELEASE( pTD );\n\n    if (exc == 0)\n    {\n        throw RuntimeException( \"rethrowing C++ exception failed!\" );\n    }\n\n    Any ret;\n    uno_any_destruct( &ret, reinterpret_cast< uno_ReleaseFunc >(cpp_release) );\n    uno_type_any_constructAndConvert(\n        &ret, exc->pData, exc->pType, uno2cpp.get() );\n    uno_any_destruct( exc, 0 );\n    return ret;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"Fixing an oopsie (1)<|endoftext|>"}
{"text":"#ifndef OCCA_PARSER_STATEMENT_HEADER\n#define OCCA_PARSER_STATEMENT_HEADER\n\n#include \"occaParserDefines.hpp\"\n#include \"occaParserMacro.hpp\"\n#include \"occaParserTools.hpp\"\n#include \"occaParserNodes.hpp\"\n#include \"occaParserTypes.hpp\"\n\nnamespace occa {\n  namespace parserNamespace {\n    class statement;\n\n    \/\/---[ Exp Node ]-------------------------------\n    namespace expType {\n      static const int root            = (1 << 0);\n\n      static const int LCR             = (7 << 1);\n      static const int L               = (1 << 1);\n      static const int C               = (1 << 2);\n      static const int R               = (1 << 3);\n\n      static const int qualifier       = (1 <<  4);\n      static const int type            = (1 <<  5);\n      static const int presetValue     = (1 <<  6);\n      static const int operator_       = (1 <<  7);\n      static const int unknown         = (1 <<  8);\n      static const int variable        = (1 <<  9);\n      static const int function        = (1 << 11);\n      static const int functionPointer = (1 << 12);\n      static const int typedef_        = (1 << 13);\n      static const int prototype       = (1 << 14);\n      static const int declaration     = (1 << 15);\n      static const int struct_         = (1 << 16);\n      static const int namespace_      = (1 << 17);\n      static const int cast_           = (1 << 18);\n      static const int macro_          = (1 << 19);\n      static const int goto_           = (1 << 20);\n      static const int gotoLabel_      = (1 << 21);\n      static const int case_           = (1 << 22);\n      static const int return_         = (1 << 23);\n      static const int occaFor         = (1 << 24);\n      static const int checkSInfo      = (1 << 25);\n\n      static const int printValue      = (1 << 26);\n      static const int printLeaves     = (1 << 27);\n      static const int maxBit          = 27;\n    };\n\n    class _varInfo;\n\n    class expNode {\n    public:\n      statement *sInfo;\n\n      std::string value;\n      int info;\n\n      expNode *up;\n\n      int leafCount;\n\n      union {\n        expNode **leaves;\n        _varInfo **varLeaves;\n      };\n\n      expNode();\n      expNode(statement &s);\n      expNode(expNode &up_);\n\n      \/\/---[ Find Statement ]-----------\n      void labelStatement(strNode *&nodeRoot);\n\n      int loadMacroStatement(strNode *&nodeRoot);\n      int loadOccaForStatement(strNode *&nodeRoot);\n      int loadTypedefStatement(strNode *&nodeRoot);\n      int loadStructStatement(strNode *&nodeRoot);\n      int loadUpdateStatement(strNode *&nodeRoot);\n      int loadDescriptorStatement(strNode *&nodeRoot);\n      int loadGotoStatement(strNode *&nodeRoot);\n      int loadFlowStatement(strNode *&nodeRoot);\n      int loadSpecialStatement(strNode *&nodeRoot);\n      int loadBlockStatement(strNode *&nodeRoot);\n      \/\/================================\n\n      void loadFromNode(strNode *&nodePos);\n\n      void splitAndOrganizeNode(strNode *nodeRoot);\n      void organize();\n\n      void addNewVariables(strNode *nodePos);\n\n      void splitDeclareStatement();\n      void splitForStatement();\n      void splitFunctionStatement();\n      void splitStructStatement();\n      void splitStructStatements();\n      void splitTypedefStatement();\n\n      void initLoadFromNode(strNode *nodeRoot,\n                            const int initPos = 0);\n\n      int initDownsFromNode(strNode *nodeRoot,\n                            int leafPos = 0);\n\n      void initOrganization();\n\n      void organizeLeaves();\n      void organizeLeaves(const int level);\n\n      int mergeRange(const int newLeafType,\n                     const int leafPosStart,\n                     const int leafPosEnd);\n\n      \/\/ [a][::][b]\n      void mergeNamespaces();\n\n      \/\/ [(class)]\n      void labelCasts();\n\n      \/\/ const int [*] x\n      void labelReferenceQualifiers();\n\n      \/\/ [const] int x\n      void mergeQualifiers();\n\n      \/\/ [[const] [int] [*]] x\n      void mergeTypes();\n\n      \/\/ [[[const] [int] [*]] [x]]\n      void mergeVariables();\n\n      \/\/ 1 [type]                           2 [(]       3 [(]\n      \/\/ [[qualifiers] [type] [qualifiers]] [(*[name])] [([args])]\n      void mergeFunctionPointers();\n\n      \/\/ class(...), class{1,2,3}\n      void mergeClassConstructs();\n\n      \/\/ static_cast<>()\n      void mergeCasts();\n\n      \/\/ [max(a,b)]\n      void mergeFunctionCalls();\n\n      void mergeArguments();\n\n      \/\/ a[3]\n      void mergeArrays();\n\n      \/\/ (class) x\n      void mergeClassCasts();\n\n      \/\/ sizeof x\n      void mergeSizeOf();\n\n      \/\/ new, new [], delete, delete []\n      void mergeNewsAndDeletes();\n\n      \/\/ throw x\n      void mergeThrows();\n\n      \/\/ [++]i\n      int mergeLeftUnary(const int leafPos);\n\n      \/\/ i[++]\n      int mergeRightUnary(const int leafPos);\n\n      \/\/ a [+] b\n      int mergeBinary(const int leafPos);\n\n      \/\/ a [?] b : c\n      int mergeTernary(const int leafPos);\n\n      \/\/---[ Custom Functions ]---------\n      void labelNewVariables();\n      \/\/================================\n\n      \/\/---[ Custom Type Info ]---------\n      bool qualifierEndsWithStar() const;\n\n      bool typeEndsWithStar() const;\n\n      bool hasAnArrayQualifier(const int pos = 0) const;\n      \/\/================================\n\n      static void swap(expNode &a, expNode &b);\n\n      expNode* clone(statement &s);\n      expNode* clone(expNode *original);\n\n      void cloneTo(expNode &newRoot);\n\n      expNode* lastLeaf();\n\n      \/\/---[ Exp Info ]-----------------\n      int depth();\n      int whichLeafAmI();\n      int nestedLeafCount();\n\n      expNode* makeFlatHandle();\n      void makeFlatHandle(int &offset,\n                          expNode **flatLeaves);\n\n      void addNode(const int info_, const int pos = 0);\n      void removeNode(const int pos = 0);\n\n      void convertTo(const int info_ = 0);\n\n      bool hasQualifier(const std::string &qualifier) const;\n\n      void addQualifier(const std::string &qualifier, const int pos = 0);\n      void addPostQualifier(const std::string &qualifier, const int pos = 0);\n\n      void removeQualifier(const std::string &qualifier);\n\n      void changeType(const std::string &newType);\n\n      std::string getVariableName() const;\n\n      void setVarInfo(varInfo &var);\n      \/\/================================\n\n      void freeLeaf(const int leafPos);\n\n      void free();\n\n      void print(const std::string &tab = \"\");\n      void printOn(std::ostream &out, const std::string &tab = \"\");\n\n      std::string getString(const std::string &tab = \"\");\n      operator std::string ();\n\n      friend std::ostream& operator << (std::ostream &out, expNode &n);\n    };\n\n    struct statementExp {\n      int sType;\n      expNode exp;\n    };\n    \/\/==============================================\n\n\n    \/\/---[ Statement ]------------------------------\n    class statement {\n    public:\n      scopeTypeMap_t scopeTypeMap;\n      scopeVarMap_t scopeVarMap;\n\n      varOriginMap_t &varOriginMap;\n      varUsedMap_t   &varUsedMap;\n\n      strNode *nodeStart, *nodeEnd;\n\n      int depth;\n      statement *up;\n\n      int type;\n\n      expNode expRoot;\n\n      int statementCount;\n      statementNode *statementStart, *statementEnd;\n\n      statement(parserBase &pb);\n\n      statement(const int depth_, statement *up_);\n\n      statement(const int depth_,\n                const int type_,\n                statement *up_);\n\n      ~statement();\n\n      statement* makeSubStatement();\n\n      std::string getTab() const;\n\n      int statementType(strNode *&nodeRoot);\n\n      int checkMacroStatementType(strNode *&nodeRoot);\n      int checkOccaForStatementType(strNode *&nodeRoot);\n      int checkStructStatementType(strNode *&nodeRoot);\n      int checkUpdateStatementType(strNode *&nodeRoot);\n      int checkDescriptorStatementType(strNode *&nodeRoot);\n      int checkGotoStatementType(strNode *&nodeRoot);\n      int checkFlowStatementType(strNode *&nodeRoot);\n      int checkSpecialStatementType(strNode *&nodeRoot);\n      int checkBlockStatementType(strNode *&nodeRoot);\n\n      void addTypeDef(const std::string &typeDefName);\n\n      bool nodeHasQualifier(strNode *n) const;\n      bool nodeHasSpecifier(strNode *n) const;\n      bool nodeHasDescriptor(strNode *n) const;\n\n      varInfo loadVarInfo(strNode *&nodePos);\n\n      typeDef* hasTypeInScope(const std::string &typeName) const;\n\n      varInfo* hasVariableInScope(const std::string &varName) const;\n\n      bool hasDescriptorVariable(const std::string descriptor) const;\n      bool hasDescriptorVariableInScope(const std::string descriptor) const;\n\n      void loadAllFromNode(strNode *nodeRoot);\n      strNode* loadFromNode(strNode *nodeRoot);\n\n      void setExpNodeFromStrNode(expNode &exp,\n                                 strNode *nodePos);\n\n      expNode* createExpNodeFrom(strNode *nodePos);\n      expNode* createExpNodeFrom(const std::string &source);\n\n      void loadBlocksFromLastNode(strNode *end,\n                                  const int startBlockPos = 0);\n\n      strNode* loadSimpleFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      strNode* loadForFromNode(const int st,\n                               strNode *nodeRoot,\n                               strNode *nodeRootEnd);\n\n      strNode* loadWhileFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      strNode* loadIfFromNode(const int st,\n                              strNode *nodeRoot,\n                              strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadSwitchFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      strNode* loadGotoFromNode(const int st,\n                                strNode *nodeRoot,\n                                strNode *nodeRootEnd);\n\n      strNode* loadFunctionDefinitionFromNode(const int st,\n                                              strNode *nodeRoot,\n                                              strNode *nodeRootEnd);\n\n      strNode* loadFunctionPrototypeFromNode(const int st,\n                                             strNode *nodeRoot,\n                                             strNode *nodeRootEnd);\n\n      strNode* loadBlockFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadStructFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadBlankFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadMacroFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      statementNode* getStatementNode();\n\n      varInfo* addVariable(const varInfo &info,\n                           statement *origin = NULL);\n\n      void addStatement(statement *newStatement);\n\n      statement* clone();\n\n      void printVariablesInStatement();\n\n      void printVariablesInScope();\n\n      void printTypesInScope();\n      void printTypesInStatement();\n      void printTypeDefsInStatement();\n\n      \/\/---[ Statement Info ]-----------\n      void swapExpWith(statement &s);\n\n      bool hasQualifier(const std::string &qualifier) const;\n\n      void addQualifier(const std::string &qualifier, const int pos = 0);\n      void removeQualifier(const std::string &qualifier);\n\n      expNode* getDeclarationTypeNode();\n      expNode* getDeclarationVarNode(const int pos);\n      std::string getDeclarationVarName(const int pos) const;\n      int getDeclarationVarCount() const;\n\n      std::string getFunctionName() const;\n      void setFunctionName(const std::string &newName);\n      expNode* getFunctionArgsNode();\n      expNode* getFunctionArgNode(const int pos);\n      std::string getFunctionArgType(const int pos);\n      std::string getFunctionArgName(const int pos);\n      varInfo* getFunctionArgVar(const int pos);\n      int getFunctionArgCount() const;\n\n      int getForStatementCount() const;\n      \/\/================================\n\n      \/\/ autoMode: Handles newlines and tabs\n      std::string prettyString(strNode *nodeRoot,\n                               const std::string &tab_ = \"\",\n                               const bool autoMode = true) const;\n\n      operator std::string();\n    };\n\n    std::ostream& operator << (std::ostream &out, statement &s);\n  };\n};\n\n#endif\n[Parser] Going to start typeInfo#ifndef OCCA_PARSER_STATEMENT_HEADER\n#define OCCA_PARSER_STATEMENT_HEADER\n\n#include \"occaParserDefines.hpp\"\n#include \"occaParserMacro.hpp\"\n#include \"occaParserTools.hpp\"\n#include \"occaParserNodes.hpp\"\n#include \"occaParserTypes.hpp\"\n\nnamespace occa {\n  namespace parserNamespace {\n    class statement;\n\n    \/\/---[ Exp Node ]-------------------------------\n    namespace expType {\n      static const int root            = (1 << 0);\n\n      static const int LCR             = (7 << 1);\n      static const int L               = (1 << 1);\n      static const int C               = (1 << 2);\n      static const int R               = (1 << 3);\n\n      static const int qualifier       = (1 <<  4);\n      static const int type            = (1 <<  5);\n      static const int presetValue     = (1 <<  6);\n      static const int operator_       = (1 <<  7);\n      static const int unknown         = (1 <<  8);\n      static const int variable        = (1 <<  9);\n      static const int function        = (1 << 11);\n      static const int functionPointer = (1 << 12);\n      static const int typedef_        = (1 << 13);\n      static const int prototype       = (1 << 14);\n      static const int declaration     = (1 << 15);\n      static const int struct_         = (1 << 16);\n      static const int namespace_      = (1 << 17);\n      static const int cast_           = (1 << 18);\n      static const int macro_          = (1 << 19);\n      static const int goto_           = (1 << 20);\n      static const int gotoLabel_      = (1 << 21);\n      static const int case_           = (1 << 22);\n      static const int return_         = (1 << 23);\n      static const int occaFor         = (1 << 24);\n      static const int checkSInfo      = (1 << 25);\n\n      static const int printValue      = (1 << 26);\n      static const int printLeaves     = (1 << 27);\n      static const int maxBit          = 27;\n    };\n\n    class _varInfo;\n    class _typeInfo;\n\n    class expNode {\n    public:\n      statement *sInfo;\n\n      std::string value;\n      int info;\n\n      expNode *up;\n\n      int leafCount;\n\n      union {\n        expNode **leaves;\n        _varInfo **varLeaves;\n        _typeInfo **typeLeaves;\n      };\n\n      expNode();\n      expNode(statement &s);\n      expNode(expNode &up_);\n\n      \/\/---[ Find Statement ]-----------\n      void labelStatement(strNode *&nodeRoot);\n\n      int loadMacroStatement(strNode *&nodeRoot);\n      int loadOccaForStatement(strNode *&nodeRoot);\n      int loadTypedefStatement(strNode *&nodeRoot);\n      int loadStructStatement(strNode *&nodeRoot);\n      int loadUpdateStatement(strNode *&nodeRoot);\n      int loadDescriptorStatement(strNode *&nodeRoot);\n      int loadGotoStatement(strNode *&nodeRoot);\n      int loadFlowStatement(strNode *&nodeRoot);\n      int loadSpecialStatement(strNode *&nodeRoot);\n      int loadBlockStatement(strNode *&nodeRoot);\n      \/\/================================\n\n      void loadFromNode(strNode *&nodePos);\n\n      void splitAndOrganizeNode(strNode *nodeRoot);\n      void organize();\n\n      void addNewVariables(strNode *nodePos);\n\n      void splitDeclareStatement();\n      void splitForStatement();\n      void splitFunctionStatement();\n      void splitStructStatement();\n      void splitStructStatements();\n      void splitTypedefStatement();\n\n      void initLoadFromNode(strNode *nodeRoot,\n                            const int initPos = 0);\n\n      int initDownsFromNode(strNode *nodeRoot,\n                            int leafPos = 0);\n\n      void initOrganization();\n\n      void organizeLeaves();\n      void organizeLeaves(const int level);\n\n      int mergeRange(const int newLeafType,\n                     const int leafPosStart,\n                     const int leafPosEnd);\n\n      \/\/ [a][::][b]\n      void mergeNamespaces();\n\n      \/\/ [(class)]\n      void labelCasts();\n\n      \/\/ const int [*] x\n      void labelReferenceQualifiers();\n\n      \/\/ [const] int x\n      void mergeQualifiers();\n\n      \/\/ [[const] [int] [*]] x\n      void mergeTypes();\n\n      \/\/ [[[const] [int] [*]] [x]]\n      void mergeVariables();\n\n      \/\/ 1 [type]                           2 [(]       3 [(]\n      \/\/ [[qualifiers] [type] [qualifiers]] [(*[name])] [([args])]\n      void mergeFunctionPointers();\n\n      \/\/ class(...), class{1,2,3}\n      void mergeClassConstructs();\n\n      \/\/ static_cast<>()\n      void mergeCasts();\n\n      \/\/ [max(a,b)]\n      void mergeFunctionCalls();\n\n      void mergeArguments();\n\n      \/\/ a[3]\n      void mergeArrays();\n\n      \/\/ (class) x\n      void mergeClassCasts();\n\n      \/\/ sizeof x\n      void mergeSizeOf();\n\n      \/\/ new, new [], delete, delete []\n      void mergeNewsAndDeletes();\n\n      \/\/ throw x\n      void mergeThrows();\n\n      \/\/ [++]i\n      int mergeLeftUnary(const int leafPos);\n\n      \/\/ i[++]\n      int mergeRightUnary(const int leafPos);\n\n      \/\/ a [+] b\n      int mergeBinary(const int leafPos);\n\n      \/\/ a [?] b : c\n      int mergeTernary(const int leafPos);\n\n      \/\/---[ Custom Functions ]---------\n      void labelNewVariables();\n      \/\/================================\n\n      \/\/---[ Custom Type Info ]---------\n      bool qualifierEndsWithStar() const;\n\n      bool typeEndsWithStar() const;\n\n      bool hasAnArrayQualifier(const int pos = 0) const;\n      \/\/================================\n\n      static void swap(expNode &a, expNode &b);\n\n      expNode* clone(statement &s);\n      expNode* clone(expNode *original);\n\n      void cloneTo(expNode &newRoot);\n\n      expNode* lastLeaf();\n\n      \/\/---[ Exp Info ]-----------------\n      int depth();\n      int whichLeafAmI();\n      int nestedLeafCount();\n\n      expNode* makeFlatHandle();\n      void makeFlatHandle(int &offset,\n                          expNode **flatLeaves);\n\n      void addNode(const int info_, const int pos = 0);\n      void removeNode(const int pos = 0);\n\n      void convertTo(const int info_ = 0);\n\n      bool hasQualifier(const std::string &qualifier) const;\n\n      void addQualifier(const std::string &qualifier, const int pos = 0);\n      void addPostQualifier(const std::string &qualifier, const int pos = 0);\n\n      void removeQualifier(const std::string &qualifier);\n\n      void changeType(const std::string &newType);\n\n      std::string getVariableName() const;\n\n      void setVarInfo(varInfo &var);\n      \/\/================================\n\n      void freeLeaf(const int leafPos);\n\n      void free();\n\n      void print(const std::string &tab = \"\");\n      void printOn(std::ostream &out, const std::string &tab = \"\");\n\n      std::string getString(const std::string &tab = \"\");\n      operator std::string ();\n\n      friend std::ostream& operator << (std::ostream &out, expNode &n);\n    };\n\n    struct statementExp {\n      int sType;\n      expNode exp;\n    };\n    \/\/==============================================\n\n\n    \/\/---[ Statement ]------------------------------\n    class statement {\n    public:\n      scopeTypeMap_t scopeTypeMap;\n      scopeVarMap_t scopeVarMap;\n\n      varOriginMap_t &varOriginMap;\n      varUsedMap_t   &varUsedMap;\n\n      strNode *nodeStart, *nodeEnd;\n\n      int depth;\n      statement *up;\n\n      int type;\n\n      expNode expRoot;\n\n      int statementCount;\n      statementNode *statementStart, *statementEnd;\n\n      statement(parserBase &pb);\n\n      statement(const int depth_, statement *up_);\n\n      statement(const int depth_,\n                const int type_,\n                statement *up_);\n\n      ~statement();\n\n      statement* makeSubStatement();\n\n      std::string getTab() const;\n\n      int statementType(strNode *&nodeRoot);\n\n      int checkMacroStatementType(strNode *&nodeRoot);\n      int checkOccaForStatementType(strNode *&nodeRoot);\n      int checkStructStatementType(strNode *&nodeRoot);\n      int checkUpdateStatementType(strNode *&nodeRoot);\n      int checkDescriptorStatementType(strNode *&nodeRoot);\n      int checkGotoStatementType(strNode *&nodeRoot);\n      int checkFlowStatementType(strNode *&nodeRoot);\n      int checkSpecialStatementType(strNode *&nodeRoot);\n      int checkBlockStatementType(strNode *&nodeRoot);\n\n      void addTypeDef(const std::string &typeDefName);\n\n      bool nodeHasQualifier(strNode *n) const;\n      bool nodeHasSpecifier(strNode *n) const;\n      bool nodeHasDescriptor(strNode *n) const;\n\n      varInfo loadVarInfo(strNode *&nodePos);\n\n      typeDef* hasTypeInScope(const std::string &typeName) const;\n\n      varInfo* hasVariableInScope(const std::string &varName) const;\n\n      bool hasDescriptorVariable(const std::string descriptor) const;\n      bool hasDescriptorVariableInScope(const std::string descriptor) const;\n\n      void loadAllFromNode(strNode *nodeRoot);\n      strNode* loadFromNode(strNode *nodeRoot);\n\n      void setExpNodeFromStrNode(expNode &exp,\n                                 strNode *nodePos);\n\n      expNode* createExpNodeFrom(strNode *nodePos);\n      expNode* createExpNodeFrom(const std::string &source);\n\n      void loadBlocksFromLastNode(strNode *end,\n                                  const int startBlockPos = 0);\n\n      strNode* loadSimpleFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      strNode* loadForFromNode(const int st,\n                               strNode *nodeRoot,\n                               strNode *nodeRootEnd);\n\n      strNode* loadWhileFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      strNode* loadIfFromNode(const int st,\n                              strNode *nodeRoot,\n                              strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadSwitchFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      strNode* loadGotoFromNode(const int st,\n                                strNode *nodeRoot,\n                                strNode *nodeRootEnd);\n\n      strNode* loadFunctionDefinitionFromNode(const int st,\n                                              strNode *nodeRoot,\n                                              strNode *nodeRootEnd);\n\n      strNode* loadFunctionPrototypeFromNode(const int st,\n                                             strNode *nodeRoot,\n                                             strNode *nodeRootEnd);\n\n      strNode* loadBlockFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadStructFromNode(const int st,\n                                  strNode *nodeRoot,\n                                  strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadBlankFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      \/\/ [-] Missing\n      strNode* loadMacroFromNode(const int st,\n                                 strNode *nodeRoot,\n                                 strNode *nodeRootEnd);\n\n      statementNode* getStatementNode();\n\n      varInfo* addVariable(const varInfo &info,\n                           statement *origin = NULL);\n\n      void addStatement(statement *newStatement);\n\n      statement* clone();\n\n      void printVariablesInStatement();\n\n      void printVariablesInScope();\n\n      void printTypesInScope();\n      void printTypesInStatement();\n      void printTypeDefsInStatement();\n\n      \/\/---[ Statement Info ]-----------\n      void swapExpWith(statement &s);\n\n      bool hasQualifier(const std::string &qualifier) const;\n\n      void addQualifier(const std::string &qualifier, const int pos = 0);\n      void removeQualifier(const std::string &qualifier);\n\n      expNode* getDeclarationTypeNode();\n      expNode* getDeclarationVarNode(const int pos);\n      std::string getDeclarationVarName(const int pos) const;\n      int getDeclarationVarCount() const;\n\n      std::string getFunctionName() const;\n      void setFunctionName(const std::string &newName);\n      expNode* getFunctionArgsNode();\n      expNode* getFunctionArgNode(const int pos);\n      std::string getFunctionArgType(const int pos);\n      std::string getFunctionArgName(const int pos);\n      varInfo* getFunctionArgVar(const int pos);\n      int getFunctionArgCount() const;\n\n      int getForStatementCount() const;\n      \/\/================================\n\n      \/\/ autoMode: Handles newlines and tabs\n      std::string prettyString(strNode *nodeRoot,\n                               const std::string &tab_ = \"\",\n                               const bool autoMode = true) const;\n\n      operator std::string();\n    };\n\n    std::ostream& operator << (std::ostream &out, statement &s);\n  };\n};\n\n#endif\n<|endoftext|>"}
{"text":"fix stdtbb<|endoftext|>"}
{"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"persistentsettings.h\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\n\/*!\n    \\class Utils::PersistentSettingsReader\n\n    \\brief Reads a QVariantMap of arbitrary, nested data structures from a XML file.\n\n    Handles all string-serializable simple types and QVariantList and QVariantMap. Example:\n    \\code\n\n    \n        ProjectExplorer.Project.ActiveTarget<\/variable>\n        0<\/value>\n    <\/data>\n    \n        ProjectExplorer.Project.EditorSettings<\/variable>\n        \n            true<\/value>\n        <\/valuemap>\n    <\/data>\n    \\endcode\n\n    When parsing the structure, a parse stack of ParseValueStackEntry is used for each\n     element. ParseValueStackEntry is a variant\/union of:\n    \\list\n    \\o simple value\n    \\o map\n    \\o list\n    \\endlist\n\n    When entering a value element ( \\c  \/ \\c  , \\c  ), entry is pushed\n    accordingly. When leaving the element, the QVariant-value of the entry is taken off the stack\n    and added to the stack entry below (added to list or inserted into map). The first element\n    of the stack is the value of the  element.\n\n    \\sa Utils::PersistentSettingsWriter\n*\/\n\nnamespace Utils {\n\nstruct Context \/\/ Basic context containing element name string constants.\n{\n    Context();\n\n    const QString qtCreatorElement;\n    const QString dataElement;\n    const QString variableElement;\n    const QString typeAttribute;\n    const QString valueElement;\n    const QString valueListElement;\n    const QString valueMapElement;\n    const QString keyAttribute;\n};\n\nContext::Context() :\n    qtCreatorElement(QLatin1String(\"qtcreator\")),\n    dataElement(QLatin1String(\"data\")),\n    variableElement(QLatin1String(\"variable\")),\n    typeAttribute(QLatin1String(\"type\")),\n    valueElement(QLatin1String(\"value\")),\n    valueListElement(QLatin1String(\"valuelist\")),\n    valueMapElement(QLatin1String(\"valuemap\")),\n    keyAttribute(QLatin1String(\"key\"))\n{\n}\n\nstruct ParseValueStackEntry\n{\n    explicit ParseValueStackEntry(QVariant::Type t = QVariant::Invalid, const QString &k = QString()) : type(t), key(k) {}\n    explicit ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k);\n\n    QVariant value() const;\n    void addChild(const QString &key, const QVariant &v);\n\n    QVariant::Type type;\n    QString key;\n    QVariant simpleValue;\n    QVariantList listValue;\n    QVariantMap mapValue;\n};\n\nParseValueStackEntry::ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k) :\n    type(aSimpleValue.type()), key(k), simpleValue(aSimpleValue)\n{\n    QTC_ASSERT(simpleValue.isValid(), return);\n}\n\nQVariant ParseValueStackEntry::value() const\n{\n    switch (type) {\n    case QVariant::Invalid:\n        return QVariant();\n    case QVariant::Map:\n        return QVariant(mapValue);\n    case QVariant::List:\n        return QVariant(listValue);\n    default:\n        break;\n    }\n    return simpleValue;\n}\n\nvoid ParseValueStackEntry::addChild(const QString &key, const QVariant &v)\n{\n    switch (type) {\n    case QVariant::Map:\n        mapValue.insert(key, v);\n        break;\n    case QVariant::List:\n        listValue.push_back(v);\n        break;\n    default:\n        qWarning() << \"ParseValueStackEntry::Internal error adding \" << key << v << \" to \"\n                 << QVariant::typeToName(type) << value();\n        break;\n    }\n}\n\nclass ParseContext : public Context\n{\npublic:\n    QVariantMap parse(QFile &file);\n\nprivate:\n    enum Element { QtCreatorElement, DataElement, VariableElement,\n                   SimpleValueElement, ListValueElement, MapValueElement, UnknownElement };\n\n    Element element(const QStringRef &r) const;\n    static inline bool isValueElement(Element e)\n        { return e == SimpleValueElement || e == ListValueElement || e == MapValueElement; }\n    QVariant readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const;\n\n    bool handleStartElement(QXmlStreamReader &r);\n    bool handleEndElement(const QStringRef &name);\n\n    QStack m_valueStack;\n    QVariantMap m_result;\n    QString m_currentVariableName;\n};\n\nQVariantMap ParseContext::parse(QFile &file)\n{\n    QXmlStreamReader r(&file);\n\n    m_result.clear();\n    m_currentVariableName.clear();\n\n    while (!r.atEnd()) {\n        switch (r.readNext()) {\n        case QXmlStreamReader::StartElement:\n            if (handleStartElement(r))\n                return m_result;\n            break;\n        case QXmlStreamReader::EndElement:\n            if (handleEndElement(r.name()))\n                return m_result;\n            break;\n        case QXmlStreamReader::Invalid:\n            qWarning(\"Error reading %s:%d: %s\", qPrintable(file.fileName()),\n                     int(r.lineNumber()), qPrintable(r.errorString()));\n            return QVariantMap();\n            break;\n        default:\n            break;\n        } \/\/ switch token\n    } \/\/ while (!r.atEnd())\n    return m_result;\n}\n\nbool ParseContext::handleStartElement(QXmlStreamReader &r)\n{\n    const QStringRef name = r.name();\n    const Element e = element(name);\n    if (e == VariableElement) {\n        m_currentVariableName = r.readElementText();\n        return false;\n    }\n    if (!ParseContext::isValueElement(e))\n        return false;\n\n    const QXmlStreamAttributes attributes = r.attributes();\n    const QString key = attributes.hasAttribute(keyAttribute) ?\n                attributes.value(keyAttribute).toString() : QString();\n    switch (e) {\n    case SimpleValueElement:\n        \/\/ This reads away the end element, so, handle end element right here.\n        m_valueStack.push_back(ParseValueStackEntry(readSimpleValue(r, attributes), key));\n        return handleEndElement(name);\n    case ListValueElement:\n        m_valueStack.push_back(ParseValueStackEntry(QVariant::List, key));\n        break;\n    case MapValueElement:\n        m_valueStack.push_back(ParseValueStackEntry(QVariant::Map, key));\n        break;\n    default:\n        break;\n    }\n    return false;\n}\n\nbool ParseContext::handleEndElement(const QStringRef &name)\n{\n    const Element e = element(name);\n    if (ParseContext::isValueElement(e)) {\n        QTC_ASSERT(!m_valueStack.isEmpty(), return true);\n        const ParseValueStackEntry top = m_valueStack.pop();\n        if (m_valueStack.isEmpty()) { \/\/ Last element? -> Done with that variable.\n            QTC_ASSERT(!m_currentVariableName.isEmpty(), return true);\n            m_result.insert(m_currentVariableName, top.value());\n            m_currentVariableName.clear();\n            return false;\n        }\n        m_valueStack.top().addChild(top.key, top.value());\n    }\n    return e == QtCreatorElement;\n}\n\nParseContext::Element ParseContext::element(const QStringRef &r) const\n{\n    if (r == valueElement)\n        return SimpleValueElement;\n    if (r == valueListElement)\n        return ListValueElement;\n    if (r == valueMapElement)\n        return MapValueElement;\n    if (r == qtCreatorElement)\n        return QtCreatorElement;\n    if (r == dataElement)\n        return DataElement;\n    if (r == variableElement)\n        return VariableElement;\n    return UnknownElement;\n}\n\nQVariant ParseContext::readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const\n{\n    \/\/ Simple value\n    const QString type = attributes.value(typeAttribute).toString();\n    const QString text = r.readElementText();\n    if (type == QLatin1String(\"QChar\")) { \/\/ Workaround: QTBUG-12345\n        QTC_ASSERT(text.size() == 1, return QVariant());\n        return QVariant(QChar(text.at(0)));\n    }\n    QVariant value;\n    value.setValue(text);\n    value.convert(QVariant::nameToType(type.toLatin1().data()));\n    return value;\n}\n\n\/\/ =================================== PersistentSettingsReader\n\nPersistentSettingsReader::PersistentSettingsReader()\n{\n}\n\nQVariant PersistentSettingsReader::restoreValue(const QString &variable) const\n{\n    if (m_valueMap.contains(variable))\n        return m_valueMap.value(variable);\n    return QVariant();\n}\n\nQVariantMap PersistentSettingsReader::restoreValues() const\n{\n    return m_valueMap;\n}\n\nbool PersistentSettingsReader::load(const QString &fileName)\n{\n    m_valueMap.clear();\n\n    QFile file(fileName);\n    if (!file.open(QIODevice::ReadOnly|QIODevice::Text))\n        return false;\n    ParseContext ctx;\n    m_valueMap = ctx.parse(file);\n    file.close();\n    return true;\n}\n\n\/*!\n    \\class Utils::PersistentSettingsWriter\n\n    \\brief Serializes a QVariantMap of arbitrary, nested data structures to a XML file.\n    \\sa Utils::PersistentSettingsReader\n*\/\n\nPersistentSettingsWriter::PersistentSettingsWriter()\n{\n}\n\nstatic void writeVariantValue(QXmlStreamWriter &w, const Context &ctx,\n                              const QVariant &variant, const QString &key = QString())\n{\n    switch (static_cast(variant.type())) {\n    case static_cast(QVariant::StringList):\n    case static_cast(QVariant::List):\n        w.writeStartElement(ctx.valueListElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::List)));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        foreach (const QVariant &var, variant.toList())\n            writeVariantValue(w, ctx, var);\n        w.writeEndElement();\n        break;\n    case static_cast(QVariant::Map): {\n        w.writeStartElement(ctx.valueMapElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::Map)));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        const QVariantMap varMap = variant.toMap();\n        const QVariantMap::const_iterator cend = varMap.constEnd();\n        for (QVariantMap::const_iterator i = varMap.constBegin(); i != cend; ++i)\n            writeVariantValue(w, ctx, i.value(), i.key());\n        w.writeEndElement();\n    }\n    break;\n    case static_cast(QMetaType::QObjectStar): \/\/ ignore QObjects!\n    case static_cast(QMetaType::VoidStar): \/\/ ignore void pointers!\n        break;\n    default:\n        w.writeStartElement(ctx.valueElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(variant.typeName()));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        w.writeCharacters(variant.toString());\n        w.writeEndElement();\n        break;\n    }\n}\n\nvoid PersistentSettingsWriter::saveValue(const QString &variable, const QVariant &value)\n{\n    m_valueMap.insert(variable, value);\n}\n\nbool PersistentSettingsWriter::save(const QString &fileName, const QString &docType,\n                                    QWidget *parent) const\n{\n    Utils::FileSaver saver(fileName, QIODevice::Text);\n    if (!saver.hasError()) {\n        const Context ctx;\n        QXmlStreamWriter w(saver.file());\n        w.setAutoFormatting(true);\n        w.setAutoFormattingIndent(1); \/\/ Historical, used to be QDom.\n        w.writeStartDocument();\n        w.writeDTD(QLatin1String(\"'));\n        w.writeComment(QString::fromAscii(\" Written by Qt Creator %1, %2. \").\n                       arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),\n                           QDateTime::currentDateTime().toString(Qt::ISODate)));\n        w.writeStartElement(ctx.qtCreatorElement);\n        const QVariantMap::const_iterator cend = m_valueMap.constEnd();\n        for (QVariantMap::const_iterator it =  m_valueMap.constBegin(); it != cend; ++it) {\n            w.writeStartElement(ctx.dataElement);\n            w.writeTextElement(ctx.variableElement, it.key());\n            writeVariantValue(w, ctx, it.value());\n            w.writeEndElement();\n        }\n        w.writeEndDocument();\n\n        saver.setResult(&w);\n    }\n    return saver.finalize(parent);\n}\n} \/\/ namespace Utils\nPersistentSettingsWriter: Ensure that the directory exists\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"persistentsettings.h\"\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\n\/*!\n    \\class Utils::PersistentSettingsReader\n\n    \\brief Reads a QVariantMap of arbitrary, nested data structures from a XML file.\n\n    Handles all string-serializable simple types and QVariantList and QVariantMap. Example:\n    \\code\n\n    \n        ProjectExplorer.Project.ActiveTarget<\/variable>\n        0<\/value>\n    <\/data>\n    \n        ProjectExplorer.Project.EditorSettings<\/variable>\n        \n            true<\/value>\n        <\/valuemap>\n    <\/data>\n    \\endcode\n\n    When parsing the structure, a parse stack of ParseValueStackEntry is used for each\n     element. ParseValueStackEntry is a variant\/union of:\n    \\list\n    \\o simple value\n    \\o map\n    \\o list\n    \\endlist\n\n    When entering a value element ( \\c  \/ \\c  , \\c  ), entry is pushed\n    accordingly. When leaving the element, the QVariant-value of the entry is taken off the stack\n    and added to the stack entry below (added to list or inserted into map). The first element\n    of the stack is the value of the  element.\n\n    \\sa Utils::PersistentSettingsWriter\n*\/\n\nnamespace Utils {\n\nstruct Context \/\/ Basic context containing element name string constants.\n{\n    Context();\n\n    const QString qtCreatorElement;\n    const QString dataElement;\n    const QString variableElement;\n    const QString typeAttribute;\n    const QString valueElement;\n    const QString valueListElement;\n    const QString valueMapElement;\n    const QString keyAttribute;\n};\n\nContext::Context() :\n    qtCreatorElement(QLatin1String(\"qtcreator\")),\n    dataElement(QLatin1String(\"data\")),\n    variableElement(QLatin1String(\"variable\")),\n    typeAttribute(QLatin1String(\"type\")),\n    valueElement(QLatin1String(\"value\")),\n    valueListElement(QLatin1String(\"valuelist\")),\n    valueMapElement(QLatin1String(\"valuemap\")),\n    keyAttribute(QLatin1String(\"key\"))\n{\n}\n\nstruct ParseValueStackEntry\n{\n    explicit ParseValueStackEntry(QVariant::Type t = QVariant::Invalid, const QString &k = QString()) : type(t), key(k) {}\n    explicit ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k);\n\n    QVariant value() const;\n    void addChild(const QString &key, const QVariant &v);\n\n    QVariant::Type type;\n    QString key;\n    QVariant simpleValue;\n    QVariantList listValue;\n    QVariantMap mapValue;\n};\n\nParseValueStackEntry::ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k) :\n    type(aSimpleValue.type()), key(k), simpleValue(aSimpleValue)\n{\n    QTC_ASSERT(simpleValue.isValid(), return);\n}\n\nQVariant ParseValueStackEntry::value() const\n{\n    switch (type) {\n    case QVariant::Invalid:\n        return QVariant();\n    case QVariant::Map:\n        return QVariant(mapValue);\n    case QVariant::List:\n        return QVariant(listValue);\n    default:\n        break;\n    }\n    return simpleValue;\n}\n\nvoid ParseValueStackEntry::addChild(const QString &key, const QVariant &v)\n{\n    switch (type) {\n    case QVariant::Map:\n        mapValue.insert(key, v);\n        break;\n    case QVariant::List:\n        listValue.push_back(v);\n        break;\n    default:\n        qWarning() << \"ParseValueStackEntry::Internal error adding \" << key << v << \" to \"\n                 << QVariant::typeToName(type) << value();\n        break;\n    }\n}\n\nclass ParseContext : public Context\n{\npublic:\n    QVariantMap parse(QFile &file);\n\nprivate:\n    enum Element { QtCreatorElement, DataElement, VariableElement,\n                   SimpleValueElement, ListValueElement, MapValueElement, UnknownElement };\n\n    Element element(const QStringRef &r) const;\n    static inline bool isValueElement(Element e)\n        { return e == SimpleValueElement || e == ListValueElement || e == MapValueElement; }\n    QVariant readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const;\n\n    bool handleStartElement(QXmlStreamReader &r);\n    bool handleEndElement(const QStringRef &name);\n\n    QStack m_valueStack;\n    QVariantMap m_result;\n    QString m_currentVariableName;\n};\n\nQVariantMap ParseContext::parse(QFile &file)\n{\n    QXmlStreamReader r(&file);\n\n    m_result.clear();\n    m_currentVariableName.clear();\n\n    while (!r.atEnd()) {\n        switch (r.readNext()) {\n        case QXmlStreamReader::StartElement:\n            if (handleStartElement(r))\n                return m_result;\n            break;\n        case QXmlStreamReader::EndElement:\n            if (handleEndElement(r.name()))\n                return m_result;\n            break;\n        case QXmlStreamReader::Invalid:\n            qWarning(\"Error reading %s:%d: %s\", qPrintable(file.fileName()),\n                     int(r.lineNumber()), qPrintable(r.errorString()));\n            return QVariantMap();\n            break;\n        default:\n            break;\n        } \/\/ switch token\n    } \/\/ while (!r.atEnd())\n    return m_result;\n}\n\nbool ParseContext::handleStartElement(QXmlStreamReader &r)\n{\n    const QStringRef name = r.name();\n    const Element e = element(name);\n    if (e == VariableElement) {\n        m_currentVariableName = r.readElementText();\n        return false;\n    }\n    if (!ParseContext::isValueElement(e))\n        return false;\n\n    const QXmlStreamAttributes attributes = r.attributes();\n    const QString key = attributes.hasAttribute(keyAttribute) ?\n                attributes.value(keyAttribute).toString() : QString();\n    switch (e) {\n    case SimpleValueElement:\n        \/\/ This reads away the end element, so, handle end element right here.\n        m_valueStack.push_back(ParseValueStackEntry(readSimpleValue(r, attributes), key));\n        return handleEndElement(name);\n    case ListValueElement:\n        m_valueStack.push_back(ParseValueStackEntry(QVariant::List, key));\n        break;\n    case MapValueElement:\n        m_valueStack.push_back(ParseValueStackEntry(QVariant::Map, key));\n        break;\n    default:\n        break;\n    }\n    return false;\n}\n\nbool ParseContext::handleEndElement(const QStringRef &name)\n{\n    const Element e = element(name);\n    if (ParseContext::isValueElement(e)) {\n        QTC_ASSERT(!m_valueStack.isEmpty(), return true);\n        const ParseValueStackEntry top = m_valueStack.pop();\n        if (m_valueStack.isEmpty()) { \/\/ Last element? -> Done with that variable.\n            QTC_ASSERT(!m_currentVariableName.isEmpty(), return true);\n            m_result.insert(m_currentVariableName, top.value());\n            m_currentVariableName.clear();\n            return false;\n        }\n        m_valueStack.top().addChild(top.key, top.value());\n    }\n    return e == QtCreatorElement;\n}\n\nParseContext::Element ParseContext::element(const QStringRef &r) const\n{\n    if (r == valueElement)\n        return SimpleValueElement;\n    if (r == valueListElement)\n        return ListValueElement;\n    if (r == valueMapElement)\n        return MapValueElement;\n    if (r == qtCreatorElement)\n        return QtCreatorElement;\n    if (r == dataElement)\n        return DataElement;\n    if (r == variableElement)\n        return VariableElement;\n    return UnknownElement;\n}\n\nQVariant ParseContext::readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const\n{\n    \/\/ Simple value\n    const QString type = attributes.value(typeAttribute).toString();\n    const QString text = r.readElementText();\n    if (type == QLatin1String(\"QChar\")) { \/\/ Workaround: QTBUG-12345\n        QTC_ASSERT(text.size() == 1, return QVariant());\n        return QVariant(QChar(text.at(0)));\n    }\n    QVariant value;\n    value.setValue(text);\n    value.convert(QVariant::nameToType(type.toLatin1().data()));\n    return value;\n}\n\n\/\/ =================================== PersistentSettingsReader\n\nPersistentSettingsReader::PersistentSettingsReader()\n{\n}\n\nQVariant PersistentSettingsReader::restoreValue(const QString &variable) const\n{\n    if (m_valueMap.contains(variable))\n        return m_valueMap.value(variable);\n    return QVariant();\n}\n\nQVariantMap PersistentSettingsReader::restoreValues() const\n{\n    return m_valueMap;\n}\n\nbool PersistentSettingsReader::load(const QString &fileName)\n{\n    m_valueMap.clear();\n\n    QFile file(fileName);\n    if (!file.open(QIODevice::ReadOnly|QIODevice::Text))\n        return false;\n    ParseContext ctx;\n    m_valueMap = ctx.parse(file);\n    file.close();\n    return true;\n}\n\n\/*!\n    \\class Utils::PersistentSettingsWriter\n\n    \\brief Serializes a QVariantMap of arbitrary, nested data structures to a XML file.\n    \\sa Utils::PersistentSettingsReader\n*\/\n\nPersistentSettingsWriter::PersistentSettingsWriter()\n{\n}\n\nstatic void writeVariantValue(QXmlStreamWriter &w, const Context &ctx,\n                              const QVariant &variant, const QString &key = QString())\n{\n    switch (static_cast(variant.type())) {\n    case static_cast(QVariant::StringList):\n    case static_cast(QVariant::List):\n        w.writeStartElement(ctx.valueListElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::List)));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        foreach (const QVariant &var, variant.toList())\n            writeVariantValue(w, ctx, var);\n        w.writeEndElement();\n        break;\n    case static_cast(QVariant::Map): {\n        w.writeStartElement(ctx.valueMapElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::Map)));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        const QVariantMap varMap = variant.toMap();\n        const QVariantMap::const_iterator cend = varMap.constEnd();\n        for (QVariantMap::const_iterator i = varMap.constBegin(); i != cend; ++i)\n            writeVariantValue(w, ctx, i.value(), i.key());\n        w.writeEndElement();\n    }\n    break;\n    case static_cast(QMetaType::QObjectStar): \/\/ ignore QObjects!\n    case static_cast(QMetaType::VoidStar): \/\/ ignore void pointers!\n        break;\n    default:\n        w.writeStartElement(ctx.valueElement);\n        w.writeAttribute(ctx.typeAttribute, QLatin1String(variant.typeName()));\n        if (!key.isEmpty())\n            w.writeAttribute(ctx.keyAttribute, key);\n        w.writeCharacters(variant.toString());\n        w.writeEndElement();\n        break;\n    }\n}\n\nvoid PersistentSettingsWriter::saveValue(const QString &variable, const QVariant &value)\n{\n    m_valueMap.insert(variable, value);\n}\n\nbool PersistentSettingsWriter::save(const QString &fileName, const QString &docType,\n                                    QWidget *parent) const\n{\n    QDir tmp;\n    tmp.mkpath(QFileInfo(fileName).path());\n    Utils::FileSaver saver(fileName, QIODevice::Text);\n    if (!saver.hasError()) {\n        const Context ctx;\n        QXmlStreamWriter w(saver.file());\n        w.setAutoFormatting(true);\n        w.setAutoFormattingIndent(1); \/\/ Historical, used to be QDom.\n        w.writeStartDocument();\n        w.writeDTD(QLatin1String(\"'));\n        w.writeComment(QString::fromAscii(\" Written by Qt Creator %1, %2. \").\n                       arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),\n                           QDateTime::currentDateTime().toString(Qt::ISODate)));\n        w.writeStartElement(ctx.qtCreatorElement);\n        const QVariantMap::const_iterator cend = m_valueMap.constEnd();\n        for (QVariantMap::const_iterator it =  m_valueMap.constBegin(); it != cend; ++it) {\n            w.writeStartElement(ctx.dataElement);\n            w.writeTextElement(ctx.variableElement, it.key());\n            writeVariantValue(w, ctx, it.value());\n            w.writeEndElement();\n        }\n        w.writeEndDocument();\n\n        saver.setResult(&w);\n    }\n    return saver.finalize(parent);\n}\n} \/\/ namespace Utils\n<|endoftext|>"}
{"text":"\/\/---------------------------------------------------------\n\/\/ Copyright 2015 Ontario Institute for Cancer Research\n\/\/ Written by Jared Simpson (jared.simpson@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\/\/ nanopolish.cpp -- main driver program\n\/\/\n#include \n#include \n#include \n#include \"logsum.h\"\n#include \"nanopolish_extract.h\"\n#include \"nanopolish_call_variants.h\"\n#include \"nanopolish_consensus.h\"\n#include \"nanopolish_eventalign.h\"\n#include \"nanopolish_getmodel.h\"\n#include \"nanopolish_methyltrain.h\"\n#include \"nanopolish_call_methylation.h\"\n#include \"nanopolish_scorereads.h\"\n#include \"nanopolish_phase_reads.h\"\n#include \"nanopolish_train_poremodel_from_basecalls.h\"\n\nint print_usage(int argc, char **argv);\nint print_version(int argc, char **argv);\n\nstatic std::map< std::string, std::function > programs = {\n    {\"help\",        print_usage},\n    {\"--help\",      print_usage},\n    {\"--version\",   print_version},\n    {\"extract\",     extract_main},\n    {\"consensus\",   consensus_main},\n    {\"eventalign\",  eventalign_main},\n    {\"getmodel\",    getmodel_main},\n    {\"variants\",    call_variants_main},\n    {\"methyltrain\", methyltrain_main},\n    {\"scorereads\",  scorereads_main} ,\n    {\"phase-reads\",  phase_reads_main} ,\n    {\"call-methylation\",  call_methylation_main},\n    {\"train-poremodel-from-basecalls\",  train_poremodel_from_basecalls_main}\n};\n\nint print_usage(int, char **)\n{\n    std::cout << \"usage: nanopolish [command] [options]\" << std::endl;\n    std::cout << \"  valid commands: \" << std::endl;\n    for (const auto &item : programs){\n        std::cout << \"    \" << item.first << std::endl;\n    }\n    std::cout << \"  for help on given command, type nanopolish command --help\" << std::endl;\n    return 0;\n}\n\nint print_version(int, char **)\n{\n    static const char *VERSION_MESSAGE =\n    \"nanopolish version \" PACKAGE_VERSION \"\\n\"\n    \"Written by Jared Simpson.\\n\"\n    \"\\n\"\n    \"Copyright 2015-2017 Ontario Institute for Cancer Research\\n\";\n    std::cout << VERSION_MESSAGE << std::endl;\n    return 0;\n}\n\nint main(int argc, char** argv)\n{\n    int ret = 0;\n    if(argc <= 1) {\n        printf(\"error: no command provided\\n\");\n        print_usage(argc - 1 , argv + 1);\n        return 0;\n    } else {\n        std::string command(argv[1]);\n        auto iter = programs.find(command);\n        if (iter != programs.end()) \n            ret = iter->second( argc - 1, argv + 1);\n        else\n            ret = print_usage( argc - 1, argv + 1);\n    }\n\n    \/\/ Emit a warning when some reads had to be skipped\n    extern int g_total_reads;\n    extern int g_unparseable_reads;\n    if(g_unparseable_reads > 0) {\n        fprintf(stderr, \"warning: nanopolish could not parse %d read out of %d\\n\", g_unparseable_reads, g_total_reads);\n    }\n    return ret;\n}\nupdate warning\/\/---------------------------------------------------------\n\/\/ Copyright 2015 Ontario Institute for Cancer Research\n\/\/ Written by Jared Simpson (jared.simpson@oicr.on.ca)\n\/\/---------------------------------------------------------\n\/\/\n\/\/ nanopolish.cpp -- main driver program\n\/\/\n#include \n#include \n#include \n#include \"logsum.h\"\n#include \"nanopolish_extract.h\"\n#include \"nanopolish_call_variants.h\"\n#include \"nanopolish_consensus.h\"\n#include \"nanopolish_eventalign.h\"\n#include \"nanopolish_getmodel.h\"\n#include \"nanopolish_methyltrain.h\"\n#include \"nanopolish_call_methylation.h\"\n#include \"nanopolish_scorereads.h\"\n#include \"nanopolish_phase_reads.h\"\n#include \"nanopolish_train_poremodel_from_basecalls.h\"\n\nint print_usage(int argc, char **argv);\nint print_version(int argc, char **argv);\n\nstatic std::map< std::string, std::function > programs = {\n    {\"help\",        print_usage},\n    {\"--help\",      print_usage},\n    {\"--version\",   print_version},\n    {\"extract\",     extract_main},\n    {\"consensus\",   consensus_main},\n    {\"eventalign\",  eventalign_main},\n    {\"getmodel\",    getmodel_main},\n    {\"variants\",    call_variants_main},\n    {\"methyltrain\", methyltrain_main},\n    {\"scorereads\",  scorereads_main} ,\n    {\"phase-reads\",  phase_reads_main} ,\n    {\"call-methylation\",  call_methylation_main},\n    {\"train-poremodel-from-basecalls\",  train_poremodel_from_basecalls_main}\n};\n\nint print_usage(int, char **)\n{\n    std::cout << \"usage: nanopolish [command] [options]\" << std::endl;\n    std::cout << \"  valid commands: \" << std::endl;\n    for (const auto &item : programs){\n        std::cout << \"    \" << item.first << std::endl;\n    }\n    std::cout << \"  for help on given command, type nanopolish command --help\" << std::endl;\n    return 0;\n}\n\nint print_version(int, char **)\n{\n    static const char *VERSION_MESSAGE =\n    \"nanopolish version \" PACKAGE_VERSION \"\\n\"\n    \"Written by Jared Simpson.\\n\"\n    \"\\n\"\n    \"Copyright 2015-2017 Ontario Institute for Cancer Research\\n\";\n    std::cout << VERSION_MESSAGE << std::endl;\n    return 0;\n}\n\nint main(int argc, char** argv)\n{\n    int ret = 0;\n    if(argc <= 1) {\n        printf(\"error: no command provided\\n\");\n        print_usage(argc - 1 , argv + 1);\n        return 0;\n    } else {\n        std::string command(argv[1]);\n        auto iter = programs.find(command);\n        if (iter != programs.end()) \n            ret = iter->second( argc - 1, argv + 1);\n        else\n            ret = print_usage( argc - 1, argv + 1);\n    }\n\n    \/\/ Emit a warning when some reads had to be skipped\n    extern int g_total_reads;\n    extern int g_unparseable_reads;\n    if(g_unparseable_reads > 0) {\n        fprintf(stderr, \"warning: nanopolish could not parse %d reads out of %d\\n\", g_unparseable_reads, g_total_reads);\n    }\n    return ret;\n}\n<|endoftext|>"}
{"text":"#pragma once\n\n#define randf() (rand() \/ (float)RAND_MAX)\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#define GLM_ENABLE_EXPERIMENTAL\n#define GLM_FORCE_RADIANS\n#include \n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\n#include \n\nnamespace glm {\n\n    inline void to_json( nlohmann::json &j, const glm::vec3 &p ) {\n        j.array( {p.x, p.y, p.z} );\n    }\n\n    inline void from_json( const nlohmann::json &j, glm::vec3 &p ) {\n        int ix = 0;\n        for ( auto it = j.begin( ); it != j.end( ); ++it, ix++ ) {\n            p[ix] = *it;\n        }\n    }\n\n} \/\/ namespace glm\nFix warnings#pragma once\n\n#define randf() (rand() \/ (float)RAND_MAX)\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow\"\n#define GLM_ENABLE_EXPERIMENTAL\n#define GLM_FORCE_RADIANS\n#include \n#include \n#include \n#include \n#pragma GCC diagnostic pop\n\n#include \n\nnamespace glm {\n\n    static inline void to_json( nlohmann::json &j, const glm::vec3 &p ) {\n        j.array( {p.x, p.y, p.z} );\n    }\n\n    static inline void from_json( const nlohmann::json &j, glm::vec3 &p ) {\n        int ix = 0;\n        for ( auto it = j.begin( ); it != j.end( ); ++it, ix++ ) {\n            p[ix] = *it;\n        }\n    }\n\n} \/\/ namespace glm\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Created by David on 25-Dec-15.\n\/\/\n\n#include \"nova_renderer.h\"\n#include \"..\/utils\/utils.h\"\n#include \"..\/data_loading\/loaders\/loaders.h\"\n\n#include \n\nINITIALIZE_EASYLOGGINGPP\n\nnamespace nova {\n    std::unique_ptr nova_renderer::instance;\n\n    nova_renderer::nova_renderer(){\n\t\tenable_debug();\n\t\trender_settings->register_change_listener(&ubo_manager);\n\t\trender_settings->register_change_listener(&game_window);\n        render_settings->register_change_listener(this);\n\n        render_settings->update_config_loaded();\n\t\trender_settings->update_config_changed();\n\n        init_opengl_state();\n    }\n\n    void nova_renderer::init_opengl_state() const {\n        glClearColor(0.0, 0.0, 0.0, 1.0);\n       \n    }\n\n    nova_renderer::~nova_renderer() {\n        game_window.destroy();\n    }\n\n    void nova_renderer::render_frame() {\n        \/\/ Clear to the clear color\n        glClear(GL_COLOR_BUFFER_BIT);\n\n        render_shadow_pass();\n\n        render_gbuffers();\n\n        render_composite_passes();\n\n        render_final_pass();\n\n        \/\/ We want to draw the GUI on top of the other things, so we'll render it last\n        \/\/ Additionally, I could use the stencil buffer to not draw MC underneath the GUI. Could be a fun\n        \/\/ optimization - I'd have to watch out for when the user hides the GUI, though. I can just re-render the\n        \/\/ stencil buffer when the GUI screen changes\n        render_gui();\n\n        game_window.end_frame();\n    }\n\n    void nova_renderer::render_shadow_pass() {\n\n    }\n\n    void nova_renderer::render_gbuffers() {\n\n    }\n\n    void nova_renderer::render_composite_passes() {\n\n    }\n\n    void nova_renderer::render_final_pass() {\n\n    }\n\n    void nova_renderer::render_gui() {\n        \/\/ Bind all the GUI data\n        gl_shader_program &gui_shader = (*loaded_shaderpack)[\"gui\"];\n        gui_shader.bind();\n\n        \/\/ Render GUI objects\n        std::vector gui_geometry = meshes.get_meshes_for_shader(\"gui\");\n        for(const auto *geom : gui_geometry) {\n            geom->geometry->draw();\n        }\n    }\n\n    bool nova_renderer::should_end() {\n        \/\/ If the window wants to close, the user probably clicked on the \"X\" button\n        return game_window.should_close();\n    }\n\n\tstd::unique_ptr nova_renderer::render_settings;\n\n    void nova_renderer::init() {\n\t\trender_settings = std::make_unique(\"config\/config.json\");\n\t\n\t\tinstance = std::make_unique();\n    }\n\n    std::string translate_debug_source(GLenum source) {\n        switch(source) {\n            case GL_DEBUG_SOURCE_API:\n                return \"API\";\n            case GL_DEBUG_SOURCE_WINDOW_SYSTEM:\n                return \"window system\";\n            case GL_DEBUG_SOURCE_SHADER_COMPILER:\n                return \"shader compiler\";\n            case GL_DEBUG_SOURCE_THIRD_PARTY:\n                return \"third party\";\n            case GL_DEBUG_SOURCE_APPLICATION:\n                return \"application\";\n            case GL_DEBUG_SOURCE_OTHER:\n                return \"other\";\n            default:\n                return \"something else somehow\";\n        }\n    }\n\n    std::string translate_debug_type(GLenum type) {\n        switch(type) {\n            case GL_DEBUG_TYPE_ERROR:\n                return \"error\";\n            case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n                return \"some behavior marked deprecated has been used\";\n            case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:\n                return \"something has invoked undefined behavior\";\n            case GL_DEBUG_TYPE_PORTABILITY:\n                return \"some functionality the user relies upon is not portable\";\n            case GL_DEBUG_TYPE_PERFORMANCE:\n                return \"code has triggered possible performance issues\";\n            case GL_DEBUG_TYPE_MARKER:\n                return \"command stream annotation\";\n            case GL_DEBUG_TYPE_PUSH_GROUP:\n                return \"group pushing\";\n            case GL_DEBUG_TYPE_POP_GROUP:\n                return \"group popping\";\n            case GL_DEBUG_TYPE_OTHER:\n                return \"other\";\n            default:\n                return \"something else somwhow\";\n        }\n    }\n\n    void APIENTRY\n    debug_logger(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message,\n                 const void *user_param) {\n        std::string source_name = translate_debug_source(source);\n        std::string type_name = translate_debug_type(type);\n\n        switch(severity) {\n            case GL_DEBUG_SEVERITY_HIGH:\n                LOG(ERROR) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_MEDIUM:\n                LOG(INFO) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \" << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_LOW:\n                LOG(DEBUG) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_NOTIFICATION:\n                LOG(TRACE) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            default:\n                LOG(INFO) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \" << message;\n        }\n    }\n\n    void nova_renderer::enable_debug() {\n        glEnable(GL_DEBUG_OUTPUT);\n        glDebugMessageCallback(debug_logger, NULL);\n    }\n\n    void nova_renderer::on_config_change(nlohmann::json &new_config) {\n\t\t\n\t\tauto& shaderpack_name = new_config[\"loadedShaderpack\"];\n        load_new_shaderpack(shaderpack_name);\n    }\n\n    void nova_renderer::on_config_loaded(nlohmann::json &config) {\n        \/\/ TODO: Probably want to do some setup here, don't need to do that now\n    }\n\n    settings &nova_renderer::get_render_settings() {\n        return *render_settings;\n    }\n\n    texture_manager &nova_renderer::get_texture_manager() {\n        return textures;\n    }\n\n\tglfw_gl_window &nova_renderer::get_game_window() {\n\t\treturn game_window;\n\t}\n\n\tinput_handler &nova_renderer::get_input_handler() {\n\t\treturn input_handler;\n\t}\n\n    mesh_store &nova_renderer::get_mesh_store() {\n        return meshes;\n    }\n\n    void nova_renderer::load_new_shaderpack(const std::string &new_shaderpack_name) {\n\t\t\n        LOG(INFO) << \"Loading shaderpack \" << new_shaderpack_name;\n        loaded_shaderpack = std::experimental::make_optional(load_shaderpack(new_shaderpack_name));\n        meshes.set_shaderpack(*loaded_shaderpack);\n        LOG(INFO) << \"Loading complete\";\n\t\t\n        link_up_uniform_buffers(loaded_shaderpack->get_loaded_shaders(), ubo_manager);\n        LOG(DEBUG) << \"Linked up UBOs\";\n    }\n\n    void nova_renderer::deinit() {\n        instance.release();\n    }\n\n    void link_up_uniform_buffers(std::unordered_map &shaders, uniform_buffer_store &ubos) {\n        nova::foreach(shaders, [&](auto shader) { ubos.register_all_buffers_with_shader(shader.second); });\n    }\n}\n\nfix geometry->draw();\/\/\n\/\/ Created by David on 25-Dec-15.\n\/\/\n\n#include \"nova_renderer.h\"\n#include \"..\/utils\/utils.h\"\n#include \"..\/data_loading\/loaders\/loaders.h\"\n\n#include \n\nINITIALIZE_EASYLOGGINGPP\n\nnamespace nova {\n    std::unique_ptr nova_renderer::instance;\n\n    nova_renderer::nova_renderer(){\n\t\tenable_debug();\n\t\trender_settings->register_change_listener(&ubo_manager);\n\t\trender_settings->register_change_listener(&game_window);\n        render_settings->register_change_listener(this);\n\n        render_settings->update_config_loaded();\n\t\trender_settings->update_config_changed();\n\n        init_opengl_state();\n    }\n\n    void nova_renderer::init_opengl_state() const {\n        glClearColor(0.0, 0.0, 0.0, 1.0);\n       \n    }\n\n    nova_renderer::~nova_renderer() {\n        game_window.destroy();\n    }\n\n    void nova_renderer::render_frame() {\n        \/\/ Clear to the clear color\n        glClear(GL_COLOR_BUFFER_BIT);\n\n        render_shadow_pass();\n\n        render_gbuffers();\n\n        render_composite_passes();\n\n        render_final_pass();\n\n        \/\/ We want to draw the GUI on top of the other things, so we'll render it last\n        \/\/ Additionally, I could use the stencil buffer to not draw MC underneath the GUI. Could be a fun\n        \/\/ optimization - I'd have to watch out for when the user hides the GUI, though. I can just re-render the\n        \/\/ stencil buffer when the GUI screen changes\n        render_gui();\n\n        game_window.end_frame();\n    }\n\n    void nova_renderer::render_shadow_pass() {\n\n    }\n\n    void nova_renderer::render_gbuffers() {\n\n    }\n\n    void nova_renderer::render_composite_passes() {\n\n    }\n\n    void nova_renderer::render_final_pass() {\n\n    }\n\n    void nova_renderer::render_gui() {\n        \/\/ Bind all the GUI data\n        gl_shader_program &gui_shader = (*loaded_shaderpack)[\"gui\"];\n        gui_shader.bind();\n\n        \/\/ Render GUI objects\n        std::vector gui_geometry = meshes.get_meshes_for_shader(\"gui\");\n        for(const auto *geom : gui_geometry) {\n            geom->geometry->set_active();\n            geom->geometry->draw();\n        }\n    }\n\n    bool nova_renderer::should_end() {\n        \/\/ If the window wants to close, the user probably clicked on the \"X\" button\n        return game_window.should_close();\n    }\n\n\tstd::unique_ptr nova_renderer::render_settings;\n\n    void nova_renderer::init() {\n\t\trender_settings = std::make_unique(\"config\/config.json\");\n\t\n\t\tinstance = std::make_unique();\n    }\n\n    std::string translate_debug_source(GLenum source) {\n        switch(source) {\n            case GL_DEBUG_SOURCE_API:\n                return \"API\";\n            case GL_DEBUG_SOURCE_WINDOW_SYSTEM:\n                return \"window system\";\n            case GL_DEBUG_SOURCE_SHADER_COMPILER:\n                return \"shader compiler\";\n            case GL_DEBUG_SOURCE_THIRD_PARTY:\n                return \"third party\";\n            case GL_DEBUG_SOURCE_APPLICATION:\n                return \"application\";\n            case GL_DEBUG_SOURCE_OTHER:\n                return \"other\";\n            default:\n                return \"something else somehow\";\n        }\n    }\n\n    std::string translate_debug_type(GLenum type) {\n        switch(type) {\n            case GL_DEBUG_TYPE_ERROR:\n                return \"error\";\n            case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:\n                return \"some behavior marked deprecated has been used\";\n            case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:\n                return \"something has invoked undefined behavior\";\n            case GL_DEBUG_TYPE_PORTABILITY:\n                return \"some functionality the user relies upon is not portable\";\n            case GL_DEBUG_TYPE_PERFORMANCE:\n                return \"code has triggered possible performance issues\";\n            case GL_DEBUG_TYPE_MARKER:\n                return \"command stream annotation\";\n            case GL_DEBUG_TYPE_PUSH_GROUP:\n                return \"group pushing\";\n            case GL_DEBUG_TYPE_POP_GROUP:\n                return \"group popping\";\n            case GL_DEBUG_TYPE_OTHER:\n                return \"other\";\n            default:\n                return \"something else somwhow\";\n        }\n    }\n\n    void APIENTRY\n    debug_logger(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message,\n                 const void *user_param) {\n        std::string source_name = translate_debug_source(source);\n        std::string type_name = translate_debug_type(type);\n\n        switch(severity) {\n            case GL_DEBUG_SEVERITY_HIGH:\n                LOG(ERROR) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_MEDIUM:\n                LOG(INFO) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \" << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_LOW:\n                LOG(DEBUG) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            case GL_DEBUG_SEVERITY_NOTIFICATION:\n                LOG(TRACE) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \"\n                           << message;\n                break;\n\n            default:\n                LOG(INFO) << id << \" - Message from \" << source_name << \" of type \" << type_name << \": \" << message;\n        }\n    }\n\n    void nova_renderer::enable_debug() {\n        glEnable(GL_DEBUG_OUTPUT);\n        glDebugMessageCallback(debug_logger, NULL);\n    }\n\n    void nova_renderer::on_config_change(nlohmann::json &new_config) {\n\t\t\n\t\tauto& shaderpack_name = new_config[\"loadedShaderpack\"];\n        load_new_shaderpack(shaderpack_name);\n    }\n\n    void nova_renderer::on_config_loaded(nlohmann::json &config) {\n        \/\/ TODO: Probably want to do some setup here, don't need to do that now\n    }\n\n    settings &nova_renderer::get_render_settings() {\n        return *render_settings;\n    }\n\n    texture_manager &nova_renderer::get_texture_manager() {\n        return textures;\n    }\n\n\tglfw_gl_window &nova_renderer::get_game_window() {\n\t\treturn game_window;\n\t}\n\n\tinput_handler &nova_renderer::get_input_handler() {\n\t\treturn input_handler;\n\t}\n\n    mesh_store &nova_renderer::get_mesh_store() {\n        return meshes;\n    }\n\n    void nova_renderer::load_new_shaderpack(const std::string &new_shaderpack_name) {\n\t\t\n        LOG(INFO) << \"Loading shaderpack \" << new_shaderpack_name;\n        loaded_shaderpack = std::experimental::make_optional(load_shaderpack(new_shaderpack_name));\n        meshes.set_shaderpack(*loaded_shaderpack);\n        LOG(INFO) << \"Loading complete\";\n\t\t\n        link_up_uniform_buffers(loaded_shaderpack->get_loaded_shaders(), ubo_manager);\n        LOG(DEBUG) << \"Linked up UBOs\";\n    }\n\n    void nova_renderer::deinit() {\n        instance.release();\n    }\n\n    void link_up_uniform_buffers(std::unordered_map &shaders, uniform_buffer_store &ubos) {\n        nova::foreach(shaders, [&](auto shader) { ubos.register_all_buffers_with_shader(shader.second); });\n    }\n}\n\n<|endoftext|>"}
{"text":"#include \n#include \n\/\/#include \n\/\/#include \n\n#include \"generator.h\"\n#include \"type_generator.h\"\n\/\/#include \"serialize_tuple.h\"\n\n#ifndef RANDOM_SEED\n  #define RANDOM_SEED 0xAC0\n#endif \n\n\/\/ Clang requires forward declarations for overloaded < operators.\n\/\/ g++5 does not. Who's correct?\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::tuple & tuple);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::vector & vector);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const boost::optional & opt);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::pair & pair);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::array & arr)\n{\n  for (auto & elem : arr)\n    o << elem;\n\n  return o << \"\\n\";\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::vector & vector)\n{\n  for (const auto & elem : vector)\n    o << elem << \" \";\n\n  return o;\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const boost::optional & opt)\n{\n  if (opt)\n    o << opt.get();\n\n  return o;\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::pair & pair)\n{\n  o << \"pair.first = \" << pair.first << \"\\n\"\n    << \"pair.second = \" << pair.second;\n\n  return o;\n}\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream & o, const Tuple & tuple)\n  {\n    TuplePrinter::print(o, tuple);\n    o << std::get(tuple) << \" \";\n  }\n};\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream & o, const Tuple & tuple)\n  {\n    o << std::get<0>(tuple) << \" \";\n  }\n};\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream &, const Tuple &)\n  {\n    \/\/ no-op\n  }\n};\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::tuple & tuple)\n{\n  TuplePrinter, sizeof...(Args)>::print(o, tuple);\n  return o;\n}\n\nstruct ShapeType\n{\n  int x, y, shapesize;\n  std::string color;\n};\n\nstd::ostream & operator << (std::ostream & o, const ShapeType & shape)\n{\n  o << \"shape.x = \"         << shape.x << \"\\n\"\n    << \"shape.y = \"         << shape.y << \"\\n\"\n    << \"shape.shapesize = \" << shape.shapesize << \"\\n\"\n    << \"shape.color = \"     << shape.color << \"\\n\";\n\n  return o;\n}\n\nauto test_shape_gen()\n{\n  auto xgen = gen::make_range_gen(0, 200);\n  auto ygen = gen::make_range_gen(0, 200);\n  auto sizegen = gen::make_constant_gen(30);\n  auto colorgen = gen::make_oneof_gen({ \"RED\", \"GREEN\", \"BLUE\" });\n\n  auto shapegen =\n    gen::make_zip_gen(\n      [](int x, int y, int size, const char * color) {\n          return ShapeType { x, y, size, color };\n      }, xgen, ygen, sizegen, colorgen);\n\n  std::cout << shapegen.generate() << \"\\n\";\n\n  return shapegen;\n}\n\nvoid test_generators(void)\n{\n  gen::initialize();\n\n  auto strgen =\n    gen::make_string_gen(gen::make_printable_gen());\n\n  std::cout << \"size of strgen = \" << sizeof(strgen) << \"\\n\"\n            << \"string = \" << strgen.generate() << \"\\n\";\n\n  auto vecgen =\n    \/\/gen::make_seq_gen(gen::GenFactory::make(), 5, true);\n    gen::GenFactory>::make(gen::GenFactory::make(), 5, true);\n\n  std::cout << \"vector = \" << vecgen.generate() << \"\\n\";\n\n  auto optgen = gen::make_optional_gen(strgen);\n  std::cout << \"optional string = \" << optgen.generate() << \"\\n\";\n\n  auto pairgen = gen::make_pair_gen(strgen, vecgen);\n  std::cout << pairgen.generate() << \"\\n\";\n\n  auto tuplegen = gen::make_composed_gen(strgen, vecgen);\n  std::cout << tuplegen.generate() << \"\\n\";\n\n  auto shapegen = test_shape_gen();\n\n  auto arraygen = gen::make_array_gen(shapegen, gen::dim_list<2, 2>());\n  std::cout << arraygen.generate() << \"\\n\";\n\n  auto inordergen = \n    gen::make_inorder_gen({ 10, 20 });\n\n  assert(inordergen.generate() == 10);\n  assert(inordergen.generate() == 20);\n\n  auto concatgen = \n    gen::make_inorder_gen({ 10, 20 })\n       .concat(gen::make_inorder_gen({ 30 }));\n\n  assert(concatgen.generate() == 10);\n  assert(concatgen.generate() == 20);\n  assert(concatgen.generate() == 30);\n\n  auto v1 = gen::make_stepper_gen().take(5).to_vector();\n  std::vector v2 { 0, 1, 2, 3, 4 };\n  assert(v1 == v2);\n\n  std::cout << \"All assertions satisfied\\n\";\n}\n\nvoid triangle()\n{\n  auto triangle_gen = \n    gen::make_inorder_gen({1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1})\n        .concat_map([](int i) {\n              std::cout << \"\\n\";\n              return gen::make_stepper_gen(1, i);\n            });\n\n  try {\n    while(true)\n      std::cout << triangle_gen.generate();\n  }\n  catch(std::out_of_range &) { \n  }\n}\n\nint main(void)\n{\n  test_generators();\n  triangle();\n}\nmonad laws#include \n#include \n\/\/#include \n\/\/#include \n\n#include \"generator.h\"\n#include \"type_generator.h\"\n\/\/#include \"serialize_tuple.h\"\n\n#ifndef RANDOM_SEED\n  #define RANDOM_SEED 0xAC0\n#endif \n\n\/\/ Clang requires forward declarations for overloaded < operators.\n\/\/ g++5 does not. Who's correct?\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::tuple & tuple);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::vector & vector);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const boost::optional & opt);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::pair & pair);\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::array & arr)\n{\n  for (auto & elem : arr)\n    o << elem;\n\n  return o << \"\\n\";\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::vector & vector)\n{\n  for (const auto & elem : vector)\n    o << elem << \" \";\n\n  return o;\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const boost::optional & opt)\n{\n  if (opt)\n    o << opt.get();\n\n  return o;\n}\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::pair & pair)\n{\n  o << \"pair.first = \" << pair.first << \"\\n\"\n    << \"pair.second = \" << pair.second;\n\n  return o;\n}\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream & o, const Tuple & tuple)\n  {\n    TuplePrinter::print(o, tuple);\n    o << std::get(tuple) << \" \";\n  }\n};\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream & o, const Tuple & tuple)\n  {\n    o << std::get<0>(tuple) << \" \";\n  }\n};\n\ntemplate \nstruct TuplePrinter\n{\n  static void print(std::ostream &, const Tuple &)\n  {\n    \/\/ no-op\n  }\n};\n\ntemplate \nstd::ostream & operator << (std::ostream & o, const std::tuple & tuple)\n{\n  TuplePrinter, sizeof...(Args)>::print(o, tuple);\n  return o;\n}\n\nstruct ShapeType\n{\n  int x, y, shapesize;\n  std::string color;\n};\n\nstd::ostream & operator << (std::ostream & o, const ShapeType & shape)\n{\n  o << \"shape.x = \"         << shape.x << \"\\n\"\n    << \"shape.y = \"         << shape.y << \"\\n\"\n    << \"shape.shapesize = \" << shape.shapesize << \"\\n\"\n    << \"shape.color = \"     << shape.color << \"\\n\";\n\n  return o;\n}\n\nauto test_shape_gen()\n{\n  auto xgen = gen::make_range_gen(0, 200);\n  auto ygen = gen::make_range_gen(0, 200);\n  auto sizegen = gen::make_constant_gen(30);\n  auto colorgen = gen::make_oneof_gen({ \"RED\", \"GREEN\", \"BLUE\" });\n\n  auto shapegen =\n    gen::make_zip_gen(\n      [](int x, int y, int size, const char * color) {\n          return ShapeType { x, y, size, color };\n      }, xgen, ygen, sizegen, colorgen);\n\n  std::cout << shapegen.generate() << \"\\n\";\n\n  return shapegen;\n}\n\nvoid test_generators(void)\n{\n  gen::initialize();\n\n  auto strgen =\n    gen::make_string_gen(gen::make_printable_gen());\n\n  std::cout << \"size of strgen = \" << sizeof(strgen) << \"\\n\"\n            << \"string = \" << strgen.generate() << \"\\n\";\n\n  auto vecgen =\n    \/\/gen::make_seq_gen(gen::GenFactory::make(), 5, true);\n    gen::GenFactory>::make(gen::GenFactory::make(), 5, true);\n\n  std::cout << \"vector = \" << vecgen.generate() << \"\\n\";\n\n  auto optgen = gen::make_optional_gen(strgen);\n  std::cout << \"optional string = \" << optgen.generate() << \"\\n\";\n\n  auto pairgen = gen::make_pair_gen(strgen, vecgen);\n  std::cout << pairgen.generate() << \"\\n\";\n\n  auto tuplegen = gen::make_composed_gen(strgen, vecgen);\n  std::cout << tuplegen.generate() << \"\\n\";\n\n  auto shapegen = test_shape_gen();\n\n  auto arraygen = gen::make_array_gen(shapegen, gen::dim_list<2, 2>());\n  std::cout << arraygen.generate() << \"\\n\";\n\n  auto inordergen = \n    gen::make_inorder_gen({ 10, 20 });\n\n  assert(inordergen.generate() == 10);\n  assert(inordergen.generate() == 20);\n\n  auto concatgen = \n    gen::make_inorder_gen({ 10, 20 })\n       .concat(gen::make_inorder_gen({ 30 }));\n\n  assert(concatgen.generate() == 10);\n  assert(concatgen.generate() == 20);\n  assert(concatgen.generate() == 30);\n\n  auto v1 = gen::make_stepper_gen().take(5).to_vector();\n  std::vector v2 { 0, 1, 2, 3, 4 };\n  assert(v1 == v2);\n\n  std::cout << \"All assertions satisfied\\n\";\n}\n\nvoid triangle()\n{\n  auto triangle_gen = \n    gen::make_inorder_gen({1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1})\n        .concat_map([](int i) {\n              std::cout << \"\\n\";\n              return gen::make_stepper_gen(1, i);\n            });\n\n  try {\n    while(true)\n      std::cout << triangle_gen.generate();\n  }\n  catch(std::out_of_range &) { \n  }\n}\n\ntemplate\nvoid is_same(Gen1 g1, Gen2 g2)\n{\n  assert(g1.to_vector() == g2.to_vector());\n}\n\nvoid monad_laws()\n{\n  auto f = [](int i) { return gen::make_stepper_gen(1, i); };\n  auto g = [](int i) { return gen::make_stepper_gen(i, 1, -1); };\n  auto M = gen::make_single_gen(300);\n\n  \/\/ left identity\n  is_same(M.concat_map(f), f(300));\n  \n  \/\/ right identity\n  is_same(M.concat_map([](int i) { \n            return gen::make_single_gen(i); \n          }), M);\n  \n  \/\/ associativity\n  is_same(M.concat_map(f).concat_map(g), \n          M.concat_map([f,g](int i) mutable { \n            return f(i).concat_map(g);\n          }));\n}\n\nint main(void)\n{\n  test_generators();\n  monad_laws();\n  triangle();\n\n  std::cout << \"\\n\";\n}\n<|endoftext|>"}
{"text":"\/*\n * Copyright (c) 2011-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ron Dreslinski\n *          Ali Saidi\n *          Andreas Hansson\n *          William Wang\n *\/\n\n\/**\n * @file\n * Declaration of a coherent bus.\n *\/\n\n#ifndef __MEM_COHERENT_BUS_HH__\n#define __MEM_COHERENT_BUS_HH__\n\n#include \"base\/hashmap.hh\"\n#include \"mem\/bus.hh\"\n#include \"params\/CoherentBus.hh\"\n\n\/**\n * A coherent bus connects a number of (potentially) snooping masters\n * and slaves, and routes the request and response packets based on\n * the address, and also forwards all requests to the snoopers and\n * deals with the snoop responses.\n *\n * The coherent bus can be used as a template for modelling QPI,\n* HyperTransport, ACE and coherent OCP buses, and is typically used\n * for the L1-to-L2 buses and as the main system interconnect.\n * @sa  \\ref gem5MemorySystem \"gem5 Memory System\"\n *\/\nclass CoherentBus : public BaseBus\n{\n\n  protected:\n\n    \/**\n     * Declare the layers of this bus, one vector for requests, one\n     * for responses, and one for snoop responses\n     *\/\n    typedef Layer ReqLayer;\n    typedef Layer RespLayer;\n    typedef Layer SnoopLayer;\n    std::vector reqLayers;\n    std::vector respLayers;\n    std::vector snoopLayers;\n\n    \/**\n     * Declaration of the coherent bus slave port type, one will be\n     * instantiated for each of the master ports connecting to the\n     * bus.\n     *\/\n    class CoherentBusSlavePort : public SlavePort\n    {\n\n      private:\n\n        \/** A reference to the bus to which this port belongs. *\/\n        CoherentBus &bus;\n\n      public:\n\n        CoherentBusSlavePort(const std::string &_name,\n                             CoherentBus &_bus, PortID _id)\n            : SlavePort(_name, &_bus, _id), bus(_bus)\n        { }\n\n      protected:\n\n        \/**\n         * When receiving a timing request, pass it to the bus.\n         *\/\n        virtual bool recvTimingReq(PacketPtr pkt)\n        { return bus.recvTimingReq(pkt, id); }\n\n        \/**\n         * When receiving a timing snoop response, pass it to the bus.\n         *\/\n        virtual bool recvTimingSnoopResp(PacketPtr pkt)\n        { return bus.recvTimingSnoopResp(pkt, id); }\n\n        \/**\n         * When receiving an atomic request, pass it to the bus.\n         *\/\n        virtual Tick recvAtomic(PacketPtr pkt)\n        { return bus.recvAtomic(pkt, id); }\n\n        \/**\n         * When receiving a functional request, pass it to the bus.\n         *\/\n        virtual void recvFunctional(PacketPtr pkt)\n        { bus.recvFunctional(pkt, id); }\n\n        \/**\n         * When receiving a retry, pass it to the bus.\n         *\/\n        virtual void recvRetry()\n        { panic(\"Bus slave ports always succeed and should never retry.\\n\"); }\n\n        \/**\n         * Return the union of all adress ranges seen by this bus.\n         *\/\n        virtual AddrRangeList getAddrRanges() const\n        { return bus.getAddrRanges(); }\n\n        \/**\n         * Get the maximum block size as seen by the bus.\n         *\/\n        virtual unsigned deviceBlockSize() const\n        { return bus.deviceBlockSize(); }\n\n    };\n\n    \/**\n     * Declaration of the coherent bus master port type, one will be\n     * instantiated for each of the slave interfaces connecting to the\n     * bus.\n     *\/\n    class CoherentBusMasterPort : public MasterPort\n    {\n      private:\n        \/** A reference to the bus to which this port belongs. *\/\n        CoherentBus &bus;\n\n      public:\n\n        CoherentBusMasterPort(const std::string &_name,\n                              CoherentBus &_bus, PortID _id)\n            : MasterPort(_name, &_bus, _id), bus(_bus)\n        { }\n\n      protected:\n\n        \/**\n         * Determine if this port should be considered a snooper. For\n         * a coherent bus master port this is always true.\n         *\n         * @return a boolean that is true if this port is snooping\n         *\/\n        virtual bool isSnooping() const\n        { return true; }\n\n        \/**\n         * When receiving a timing response, pass it to the bus.\n         *\/\n        virtual bool recvTimingResp(PacketPtr pkt)\n        { return bus.recvTimingResp(pkt, id); }\n\n        \/**\n         * When receiving a timing snoop request, pass it to the bus.\n         *\/\n        virtual void recvTimingSnoopReq(PacketPtr pkt)\n        { return bus.recvTimingSnoopReq(pkt, id); }\n\n        \/**\n         * When receiving an atomic snoop request, pass it to the bus.\n         *\/\n        virtual Tick recvAtomicSnoop(PacketPtr pkt)\n        { return bus.recvAtomicSnoop(pkt, id); }\n\n        \/**\n         * When receiving a functional snoop request, pass it to the bus.\n         *\/\n        virtual void recvFunctionalSnoop(PacketPtr pkt)\n        { bus.recvFunctionalSnoop(pkt, id); }\n\n        \/** When reciving a range change from the peer port (at id),\n            pass it to the bus. *\/\n        virtual void recvRangeChange()\n        { bus.recvRangeChange(id); }\n\n        \/** When reciving a retry from the peer port (at id),\n            pass it to the bus. *\/\n        virtual void recvRetry()\n        { bus.recvRetry(id); }\n\n        \/\/ Ask the bus to ask everyone on the bus what their block size is and\n        \/\/ take the max of it. This might need to be changed a bit if we ever\n        \/\/ support multiple block sizes.\n        virtual unsigned deviceBlockSize() const\n        { return bus.deviceBlockSize(); }\n\n    };\n\n    \/**\n     * Internal class to bridge between an incoming snoop response\n     * from a slave port and forwarding it through an outgoing slave\n     * port. It is effectively a dangling master port.\n     *\/\n    class SnoopRespPort : public MasterPort\n    {\n\n      private:\n\n        \/** The port which we mirror internally. *\/\n        SlavePort& slavePort;\n\n        \/** The bus to which this port belongs. *\/\n        CoherentBus &bus;\n\n      public:\n\n        \/**\n         * Create a snoop response port that mirrors a given slave port.\n         *\/\n        SnoopRespPort(SlavePort& slave_port, CoherentBus& _bus) :\n            MasterPort(slave_port.name() + \".snoopRespPort\", &_bus),\n            slavePort(slave_port), bus(_bus) { }\n\n        \/**\n         * Override the sending of retries and pass them on through\n         * the mirrored slave port.\n         *\/\n        void sendRetry() {\n            slavePort.sendRetry();\n        }\n\n        \/**\n         * Provided as necessary.\n         *\/\n        void recvRetry() { panic(\"SnoopRespPort should never see retry\\n\"); }\n\n        \/**\n         * Provided as necessary.\n         *\/\n        bool recvTimingResp(PacketPtr pkt)\n        {\n            panic(\"SnoopRespPort should never see timing response\\n\");\n            return false;\n        }\n\n    };\n\n    std::vector snoopRespPorts;\n\n    std::vector snoopPorts;\n\n    \/**\n     * Store the outstanding requests so we can determine which ones\n     * we generated and which ones were merely forwarded. This is used\n     * in the coherent bus when coherency responses come back.\n     *\/\n    m5::hash_set outstandingReq;\n\n    \/**\n     * Keep a pointer to the system to be allow to querying memory system\n     * properties.\n     *\/\n    System *system;\n\n    \/** Function called by the port when the bus is recieving a Timing\n      request packet.*\/\n    virtual bool recvTimingReq(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Timing\n      response packet.*\/\n    virtual bool recvTimingResp(PacketPtr pkt, PortID master_port_id);\n\n    \/** Function called by the port when the bus is recieving a timing\n        snoop request.*\/\n    virtual void recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id);\n\n    \/** Function called by the port when the bus is recieving a timing\n        snoop response.*\/\n    virtual bool recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Timing function called by port when it is once again able to process\n     * requests. *\/\n    void recvRetry(PortID master_port_id);\n\n    \/**\n     * Forward a timing packet to our snoopers, potentially excluding\n     * one of the connected coherent masters to avoid sending a packet\n     * back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\/\n    void forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Atomic\n      transaction.*\/\n    Tick recvAtomic(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving an\n        atomic snoop transaction.*\/\n    Tick recvAtomicSnoop(PacketPtr pkt, PortID master_port_id);\n\n    \/**\n     * Forward an atomic packet to our snoopers, potentially excluding\n     * one of the connected coherent masters to avoid sending a packet\n     * back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\n     * @return a pair containing the snoop response and snoop latency\n     *\/\n    std::pair forwardAtomic(PacketPtr pkt,\n                                          PortID exclude_slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Functional\n        transaction.*\/\n    void recvFunctional(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a functional\n        snoop transaction.*\/\n    void recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id);\n\n    \/**\n     * Forward a functional packet to our snoopers, potentially\n     * excluding one of the connected coherent masters to avoid\n     * sending a packet back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\/\n    void forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id);\n\n    Stats::Scalar dataThroughBus;\n    Stats::Scalar snoopDataThroughBus;\n\n  public:\n\n    virtual void init();\n\n    CoherentBus(const CoherentBusParams *p);\n\n    virtual ~CoherentBus();\n\n    unsigned int drain(DrainManager *dm);\n\n    virtual void regStats();\n};\n\n#endif \/\/__MEM_COHERENT_BUS_HH__\nmem: Remove CoherentBus snoop port unused private member\/*\n * Copyright (c) 2011-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder.  You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ron Dreslinski\n *          Ali Saidi\n *          Andreas Hansson\n *          William Wang\n *\/\n\n\/**\n * @file\n * Declaration of a coherent bus.\n *\/\n\n#ifndef __MEM_COHERENT_BUS_HH__\n#define __MEM_COHERENT_BUS_HH__\n\n#include \"base\/hashmap.hh\"\n#include \"mem\/bus.hh\"\n#include \"params\/CoherentBus.hh\"\n\n\/**\n * A coherent bus connects a number of (potentially) snooping masters\n * and slaves, and routes the request and response packets based on\n * the address, and also forwards all requests to the snoopers and\n * deals with the snoop responses.\n *\n * The coherent bus can be used as a template for modelling QPI,\n* HyperTransport, ACE and coherent OCP buses, and is typically used\n * for the L1-to-L2 buses and as the main system interconnect.\n * @sa  \\ref gem5MemorySystem \"gem5 Memory System\"\n *\/\nclass CoherentBus : public BaseBus\n{\n\n  protected:\n\n    \/**\n     * Declare the layers of this bus, one vector for requests, one\n     * for responses, and one for snoop responses\n     *\/\n    typedef Layer ReqLayer;\n    typedef Layer RespLayer;\n    typedef Layer SnoopLayer;\n    std::vector reqLayers;\n    std::vector respLayers;\n    std::vector snoopLayers;\n\n    \/**\n     * Declaration of the coherent bus slave port type, one will be\n     * instantiated for each of the master ports connecting to the\n     * bus.\n     *\/\n    class CoherentBusSlavePort : public SlavePort\n    {\n\n      private:\n\n        \/** A reference to the bus to which this port belongs. *\/\n        CoherentBus &bus;\n\n      public:\n\n        CoherentBusSlavePort(const std::string &_name,\n                             CoherentBus &_bus, PortID _id)\n            : SlavePort(_name, &_bus, _id), bus(_bus)\n        { }\n\n      protected:\n\n        \/**\n         * When receiving a timing request, pass it to the bus.\n         *\/\n        virtual bool recvTimingReq(PacketPtr pkt)\n        { return bus.recvTimingReq(pkt, id); }\n\n        \/**\n         * When receiving a timing snoop response, pass it to the bus.\n         *\/\n        virtual bool recvTimingSnoopResp(PacketPtr pkt)\n        { return bus.recvTimingSnoopResp(pkt, id); }\n\n        \/**\n         * When receiving an atomic request, pass it to the bus.\n         *\/\n        virtual Tick recvAtomic(PacketPtr pkt)\n        { return bus.recvAtomic(pkt, id); }\n\n        \/**\n         * When receiving a functional request, pass it to the bus.\n         *\/\n        virtual void recvFunctional(PacketPtr pkt)\n        { bus.recvFunctional(pkt, id); }\n\n        \/**\n         * When receiving a retry, pass it to the bus.\n         *\/\n        virtual void recvRetry()\n        { panic(\"Bus slave ports always succeed and should never retry.\\n\"); }\n\n        \/**\n         * Return the union of all adress ranges seen by this bus.\n         *\/\n        virtual AddrRangeList getAddrRanges() const\n        { return bus.getAddrRanges(); }\n\n        \/**\n         * Get the maximum block size as seen by the bus.\n         *\/\n        virtual unsigned deviceBlockSize() const\n        { return bus.deviceBlockSize(); }\n\n    };\n\n    \/**\n     * Declaration of the coherent bus master port type, one will be\n     * instantiated for each of the slave interfaces connecting to the\n     * bus.\n     *\/\n    class CoherentBusMasterPort : public MasterPort\n    {\n      private:\n        \/** A reference to the bus to which this port belongs. *\/\n        CoherentBus &bus;\n\n      public:\n\n        CoherentBusMasterPort(const std::string &_name,\n                              CoherentBus &_bus, PortID _id)\n            : MasterPort(_name, &_bus, _id), bus(_bus)\n        { }\n\n      protected:\n\n        \/**\n         * Determine if this port should be considered a snooper. For\n         * a coherent bus master port this is always true.\n         *\n         * @return a boolean that is true if this port is snooping\n         *\/\n        virtual bool isSnooping() const\n        { return true; }\n\n        \/**\n         * When receiving a timing response, pass it to the bus.\n         *\/\n        virtual bool recvTimingResp(PacketPtr pkt)\n        { return bus.recvTimingResp(pkt, id); }\n\n        \/**\n         * When receiving a timing snoop request, pass it to the bus.\n         *\/\n        virtual void recvTimingSnoopReq(PacketPtr pkt)\n        { return bus.recvTimingSnoopReq(pkt, id); }\n\n        \/**\n         * When receiving an atomic snoop request, pass it to the bus.\n         *\/\n        virtual Tick recvAtomicSnoop(PacketPtr pkt)\n        { return bus.recvAtomicSnoop(pkt, id); }\n\n        \/**\n         * When receiving a functional snoop request, pass it to the bus.\n         *\/\n        virtual void recvFunctionalSnoop(PacketPtr pkt)\n        { bus.recvFunctionalSnoop(pkt, id); }\n\n        \/** When reciving a range change from the peer port (at id),\n            pass it to the bus. *\/\n        virtual void recvRangeChange()\n        { bus.recvRangeChange(id); }\n\n        \/** When reciving a retry from the peer port (at id),\n            pass it to the bus. *\/\n        virtual void recvRetry()\n        { bus.recvRetry(id); }\n\n        \/\/ Ask the bus to ask everyone on the bus what their block size is and\n        \/\/ take the max of it. This might need to be changed a bit if we ever\n        \/\/ support multiple block sizes.\n        virtual unsigned deviceBlockSize() const\n        { return bus.deviceBlockSize(); }\n\n    };\n\n    \/**\n     * Internal class to bridge between an incoming snoop response\n     * from a slave port and forwarding it through an outgoing slave\n     * port. It is effectively a dangling master port.\n     *\/\n    class SnoopRespPort : public MasterPort\n    {\n\n      private:\n\n        \/** The port which we mirror internally. *\/\n        SlavePort& slavePort;\n\n      public:\n\n        \/**\n         * Create a snoop response port that mirrors a given slave port.\n         *\/\n        SnoopRespPort(SlavePort& slave_port, CoherentBus& _bus) :\n            MasterPort(slave_port.name() + \".snoopRespPort\", &_bus),\n            slavePort(slave_port) { }\n\n        \/**\n         * Override the sending of retries and pass them on through\n         * the mirrored slave port.\n         *\/\n        void sendRetry() {\n            slavePort.sendRetry();\n        }\n\n        \/**\n         * Provided as necessary.\n         *\/\n        void recvRetry() { panic(\"SnoopRespPort should never see retry\\n\"); }\n\n        \/**\n         * Provided as necessary.\n         *\/\n        bool recvTimingResp(PacketPtr pkt)\n        {\n            panic(\"SnoopRespPort should never see timing response\\n\");\n            return false;\n        }\n\n    };\n\n    std::vector snoopRespPorts;\n\n    std::vector snoopPorts;\n\n    \/**\n     * Store the outstanding requests so we can determine which ones\n     * we generated and which ones were merely forwarded. This is used\n     * in the coherent bus when coherency responses come back.\n     *\/\n    m5::hash_set outstandingReq;\n\n    \/**\n     * Keep a pointer to the system to be allow to querying memory system\n     * properties.\n     *\/\n    System *system;\n\n    \/** Function called by the port when the bus is recieving a Timing\n      request packet.*\/\n    virtual bool recvTimingReq(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Timing\n      response packet.*\/\n    virtual bool recvTimingResp(PacketPtr pkt, PortID master_port_id);\n\n    \/** Function called by the port when the bus is recieving a timing\n        snoop request.*\/\n    virtual void recvTimingSnoopReq(PacketPtr pkt, PortID master_port_id);\n\n    \/** Function called by the port when the bus is recieving a timing\n        snoop response.*\/\n    virtual bool recvTimingSnoopResp(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Timing function called by port when it is once again able to process\n     * requests. *\/\n    void recvRetry(PortID master_port_id);\n\n    \/**\n     * Forward a timing packet to our snoopers, potentially excluding\n     * one of the connected coherent masters to avoid sending a packet\n     * back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\/\n    void forwardTiming(PacketPtr pkt, PortID exclude_slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Atomic\n      transaction.*\/\n    Tick recvAtomic(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving an\n        atomic snoop transaction.*\/\n    Tick recvAtomicSnoop(PacketPtr pkt, PortID master_port_id);\n\n    \/**\n     * Forward an atomic packet to our snoopers, potentially excluding\n     * one of the connected coherent masters to avoid sending a packet\n     * back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\n     * @return a pair containing the snoop response and snoop latency\n     *\/\n    std::pair forwardAtomic(PacketPtr pkt,\n                                          PortID exclude_slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a Functional\n        transaction.*\/\n    void recvFunctional(PacketPtr pkt, PortID slave_port_id);\n\n    \/** Function called by the port when the bus is recieving a functional\n        snoop transaction.*\/\n    void recvFunctionalSnoop(PacketPtr pkt, PortID master_port_id);\n\n    \/**\n     * Forward a functional packet to our snoopers, potentially\n     * excluding one of the connected coherent masters to avoid\n     * sending a packet back to where it came from.\n     *\n     * @param pkt Packet to forward\n     * @param exclude_slave_port_id Id of slave port to exclude\n     *\/\n    void forwardFunctional(PacketPtr pkt, PortID exclude_slave_port_id);\n\n    Stats::Scalar dataThroughBus;\n    Stats::Scalar snoopDataThroughBus;\n\n  public:\n\n    virtual void init();\n\n    CoherentBus(const CoherentBusParams *p);\n\n    virtual ~CoherentBus();\n\n    unsigned int drain(DrainManager *dm);\n\n    virtual void regStats();\n};\n\n#endif \/\/__MEM_COHERENT_BUS_HH__\n<|endoftext|>"}
{"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\/\/\n\n#include \"kudu\/gutil\/macros.h\" \/\/ IWYU pragma: keep\n\n\/\/ Functions returning default options are declared weak in the runtime\n\/\/ libraries. To make the linker pick the strong replacements for those\n\/\/ functions from this module, we explicitly force its inclusion by passing\n\/\/ -Wl,-u_sanitizer_options_link_helper\nextern \"C\"\nvoid _sanitizer_options_link_helper() { }\n\n\/\/ The callbacks we define here will be called from the sanitizer runtime, but\n\/\/ aren't referenced from the executable. We must ensure that those callbacks\n\/\/ are not sanitizer-instrumented, and that they aren't stripped by the linker.\n#define SANITIZER_HOOK_ATTRIBUTE                                           \\\n  extern \"C\"                                                               \\\n  __attribute__((no_sanitize(\"address\", \"memory\", \"thread\", \"undefined\"))) \\\n  __attribute__((visibility(\"default\")))                                   \\\n  __attribute__((used))\n\n#if defined(ADDRESS_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__asan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n#endif  \/\/ ADDRESS_SANITIZER\n\n#if defined(THREAD_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__tsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Flush TSAN memory every 10 seconds\n  \/\/ this prevents RSS blowup in unit tests which can cause tests to get\n  \/\/ killed by the OOM killer.\n  \"flush_memory_ms=10000 \"\n\n  \/\/ make the history buffer proportional to 2^7 (the maximum value) to\n  \/\/ keep more stack traces.\n  \"history_size=7 \"\n\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n\nSANITIZER_HOOK_ATTRIBUTE const char *__tsan_default_suppressions() {\n  return\n  \/\/ libunwind uses some double-checked locking which isn't perfectly safe.\n  \/\/ Reported at http:\/\/savannah.nongnu.org\/bugs\/index.php?42677\n  \/\/\n  \/\/ With TSAN in clang 3.5, it's the init() function that's flagged as a data\n  \/\/ race (not local_addr_space_init()), due to the former calling sigfillset()\n  \/\/ on an unprotected global variable. Although init() calls local_addr_space_init(),\n  \/\/ it can sometimes be eliminated from the call stack by inlining or a tail-call\n  \/\/ # optimization, so adding the suppression on both is necessary.\n  \"race:_ULx86_64_init\\n\"\n  \"race:_ULx86_64_local_addr_space_init\\n\"\n\n  \/\/ TODO(todd) After upgrading to clang 6.0, libunwind's cache is getting\n  \/\/ flagged as unsafe.\n  \"race:_ULx86_64_step\\n\"\n\n  \/\/ libev uses some lock-free synchronization, but doesn't have TSAN annotations.\n  \"race:epoll_ctl\\n\"\n\n  \/\/ TSAN complains about data races on the global signals variable in\n  \/\/ ev_feed_signal and spoiled errno in ev_sighandler. Both are probably noise.\n  \"race:ev_sighandler\\n\"\n\n  \/\/ See https:\/\/github.com\/google\/glog\/issues\/80 for a general list of TSAN\n  \/\/ issues in glog.\n  \/\/ 1. glog's fatal signal handler isn't signal-safe -- it allocates memory.\n  \/\/    This isn't great, but nothing we can do about it. See\n  \/\/    https:\/\/code.google.com\/p\/google-glog\/issues\/detail?id=191\n  \/\/ 2. LOG(FATAL) from multiple threads can also end up triggering a TSAN error.\n  \/\/ 3. g_now_entering in stacktrace_libunwind-inl.h is reset to false without\n  \/\/    a Release_Store.\n  \/\/ 4. glog's ANNOTATE_BENIGN_RACE macro doesn't do anything.\n  \/\/ 5. Mutex::is_safe_ is accessed in an unsafe way.\n  \/\/ 6. vlocal__ is access in an unsafe way at every VLOG() or VLOG_IS_ON()\n  \/\/    call-site.\n  \"signal:logging_fail\\n\"\n  \"race:google::LogMessage::Init\\n\"\n  \"race:google::GetStackTrace\\n\"\n  \"race:google::InitVLOG3__\\n\"\n  \"race:glog_internal_namespace_::Mutex\\n\"\n  \"race:vlocal__\\n\"\n  \/\/ See https:\/\/issues.apache.org\/jira\/browse\/KUDU-2212 for details on\n  \/\/ the destruction of a locked mutex in glog.\n  \"mutex:glog_internal_namespace_::Mutex::~Mutex\\n\"\n\n  \/\/ gflags variables are accessed without synchronization, but FlagSaver and other\n  \/\/ APIs acquire locks when accessing them. This should be safe on x86 for\n  \/\/ primitive flag types, but not for string flags, which is why fLS is omitted.\n  \"race:fLB::\\n\"\n  \"race:fLD::\\n\"\n  \"race:fLI::\\n\"\n  \"race:fLI64::\\n\"\n  \"race:fLU64::\\n\"\n\n  \/\/ This method in Boost's UUID library operates on static state with impunity,\n  \/\/ triggering (harmless) data races in TSAN when boost::uuids::random_generator\n  \/\/ instances are created across threads (see kudu::ObjectIdGenerator).\n  \"race:boost::uuids::detail::seed_rng::sha1_random_digest_\\n\"\n\n  \/\/ Squeasel uses ctx->stop_flag to synchronize stopping. It always sets it with\n  \/\/ the context lock held, but sometimes reads it without the context lock. This\n  \/\/ should be safe on x86, but is nonetheless flagged by TSAN.\n  \"race:sq_stop\\n\"\n\n  \/\/ Squeasel reads and frees ctx->listening_sockets without taking any locks. This\n  \/\/ may be an unsafe race.\n  \"race:close_all_listening_sockets\\n\"\n\n  \/\/ ------------------------------------------------------------\n  \/\/ Known bugs below. As these JIRAs are resolved, please remove the relevant\n  \/\/ suppression.\n  \/\/ ------------------------------------------------------------\n\n  \/\/ KUDU-1283: TSAN warning from consensus OpId\n  \"race:kudu::consensus::OpId::CopyFrom\\n\"\n\n  \/\/ KUDU-186: sketchy synchronization in catalog manager\n  \"race:kudu::master::CatalogManager::Shutdown\\n\"\n  \"race:kudu::master::CatalogManagerBgTasks::Shutdown\\n\"\n  \"race:kudu::master::CatalogManager::~CatalogManager\\n\"\n\n  \/\/ KUDU-574: raft_consensus_quorum-test race on LocalTestPeerProxy destruction\n  \"race:kudu::consensus::LocalTestPeerProxy::~LocalTestPeerProxy\\n\"\n\n  \/\/ KUDU-569: unsynchronized access to 'state_', 'acceptor_pools_', in\n  \/\/ GetBoundAddresses()\n  \"race:kudu::Webserver::GetBoundAddresses\\n\"\n  \"race:kudu::RpcServer::GetBoundAddresses\\n\"\n\n  \/\/ KUDU-2439: OpenSSL 1.1's atexit() handler may destroy global state while a\n  \/\/ Messenger is shutting down and still accessing that state. See\n  \/\/ https:\/\/github.com\/openssl\/openssl\/issues\/6214 for more details.\n  \/\/\n  \/\/ This is carried out by OPENSSL_cleanup, but TSAN's unwinder doesn't\n  \/\/ include any stack frame above the libcrypto lock destruction or memory release\n  \/\/ call for some reason, so we have to do something more generic.\n  \"called_from_lib:libcrypto.so\\n\";\n}\n#endif  \/\/ THREAD_SANITIZER\n\n#if defined(LEAK_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__lsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n\nSANITIZER_HOOK_ATTRIBUTE const char *__lsan_default_suppressions() {\n  return\n  \/\/ False positive from atexit() registration in libc\n  \"leak:*__new_exitfn*\\n\"\n\n  \/\/ False positive from krb5 < 1.12\n  \/\/ Fixed by upstream commit 379d39c17b8930718e98185a5b32a0f7f3e3b4b6\n  \"leak:krb5_authdata_import_attributes\\n\"\n\n  \/\/ KUDU-2653: Memory leak in libgssapi_krb5 [1]. Exists in certain patched\n  \/\/ versions of krb5-1.12 (such as krb5 in Debian 8).\n  \/\/\n  \/\/ Unfortunately there's no narrower match without resorting to\n  \/\/ fast_unwind_on_malloc=0; the best alternative is to match on glob, but that\n  \/\/ seems like overkill too.\n  \/\/\n  \/\/ 1. http:\/\/krbdev.mit.edu\/rt\/Ticket\/Display.html?id=7981\n  \"leak:libgssapi_krb5.so.2\\n\";\n}\n#endif  \/\/ LEAK_SANITIZER\n\n#if defined(UNDEFINED_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char* __ubsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Print the stacktrace when UBSan reports an error.\n  \"print_stacktrace=1 \"\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n#endif  \/\/ UNDEFINED_SANITIZER\nKUDU-2059: add a TSAN suppression\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\/\/\n\n#include \"kudu\/gutil\/macros.h\" \/\/ IWYU pragma: keep\n\n\/\/ Functions returning default options are declared weak in the runtime\n\/\/ libraries. To make the linker pick the strong replacements for those\n\/\/ functions from this module, we explicitly force its inclusion by passing\n\/\/ -Wl,-u_sanitizer_options_link_helper\nextern \"C\"\nvoid _sanitizer_options_link_helper() { }\n\n\/\/ The callbacks we define here will be called from the sanitizer runtime, but\n\/\/ aren't referenced from the executable. We must ensure that those callbacks\n\/\/ are not sanitizer-instrumented, and that they aren't stripped by the linker.\n#define SANITIZER_HOOK_ATTRIBUTE                                           \\\n  extern \"C\"                                                               \\\n  __attribute__((no_sanitize(\"address\", \"memory\", \"thread\", \"undefined\"))) \\\n  __attribute__((visibility(\"default\")))                                   \\\n  __attribute__((used))\n\n#if defined(ADDRESS_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__asan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n#endif  \/\/ ADDRESS_SANITIZER\n\n#if defined(THREAD_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__tsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Flush TSAN memory every 10 seconds\n  \/\/ this prevents RSS blowup in unit tests which can cause tests to get\n  \/\/ killed by the OOM killer.\n  \"flush_memory_ms=10000 \"\n\n  \/\/ make the history buffer proportional to 2^7 (the maximum value) to\n  \/\/ keep more stack traces.\n  \"history_size=7 \"\n\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n\nSANITIZER_HOOK_ATTRIBUTE const char *__tsan_default_suppressions() {\n  return\n  \/\/ libunwind uses some double-checked locking which isn't perfectly safe.\n  \/\/ Reported at http:\/\/savannah.nongnu.org\/bugs\/index.php?42677\n  \/\/\n  \/\/ With TSAN in clang 3.5, it's the init() function that's flagged as a data\n  \/\/ race (not local_addr_space_init()), due to the former calling sigfillset()\n  \/\/ on an unprotected global variable. Although init() calls local_addr_space_init(),\n  \/\/ it can sometimes be eliminated from the call stack by inlining or a tail-call\n  \/\/ # optimization, so adding the suppression on both is necessary.\n  \"race:_ULx86_64_init\\n\"\n  \"race:_ULx86_64_local_addr_space_init\\n\"\n\n  \/\/ TODO(todd) After upgrading to clang 6.0, libunwind's cache is getting\n  \/\/ flagged as unsafe.\n  \"race:_ULx86_64_step\\n\"\n\n  \/\/ libev uses some lock-free synchronization, but doesn't have TSAN annotations.\n  \"race:epoll_ctl\\n\"\n\n  \/\/ TSAN complains about data races on the global signals variable in\n  \/\/ ev_feed_signal and spoiled errno in ev_sighandler. Both are probably noise.\n  \"race:ev_sighandler\\n\"\n\n  \/\/ See https:\/\/github.com\/google\/glog\/issues\/80 for a general list of TSAN\n  \/\/ issues in glog.\n  \/\/ 1. glog's fatal signal handler isn't signal-safe -- it allocates memory.\n  \/\/    This isn't great, but nothing we can do about it. See\n  \/\/    https:\/\/code.google.com\/p\/google-glog\/issues\/detail?id=191\n  \/\/ 2. LOG(FATAL) from multiple threads can also end up triggering a TSAN error.\n  \/\/ 3. g_now_entering in stacktrace_libunwind-inl.h is reset to false without\n  \/\/    a Release_Store.\n  \/\/ 4. glog's ANNOTATE_BENIGN_RACE macro doesn't do anything.\n  \/\/ 5. Mutex::is_safe_ is accessed in an unsafe way.\n  \/\/ 6. vlocal__ is access in an unsafe way at every VLOG() or VLOG_IS_ON()\n  \/\/    call-site.\n  \"signal:logging_fail\\n\"\n  \"race:google::LogMessage::Init\\n\"\n  \"race:google::GetStackTrace\\n\"\n  \"race:google::InitVLOG3__\\n\"\n  \"race:glog_internal_namespace_::Mutex\\n\"\n  \"race:vlocal__\\n\"\n  \/\/ See https:\/\/issues.apache.org\/jira\/browse\/KUDU-2212 for details on\n  \/\/ the destruction of a locked mutex in glog.\n  \"mutex:glog_internal_namespace_::Mutex::~Mutex\\n\"\n\n  \/\/ gflags variables are accessed without synchronization, but FlagSaver and other\n  \/\/ APIs acquire locks when accessing them. This should be safe on x86 for\n  \/\/ primitive flag types, but not for string flags, which is why fLS is omitted.\n  \"race:fLB::\\n\"\n  \"race:fLD::\\n\"\n  \"race:fLI::\\n\"\n  \"race:fLI64::\\n\"\n  \"race:fLU64::\\n\"\n\n  \/\/ This method in Boost's UUID library operates on static state with impunity,\n  \/\/ triggering (harmless) data races in TSAN when boost::uuids::random_generator\n  \/\/ instances are created across threads (see kudu::ObjectIdGenerator).\n  \"race:boost::uuids::detail::seed_rng::sha1_random_digest_\\n\"\n\n  \/\/ Squeasel uses ctx->stop_flag to synchronize stopping. It always sets it with\n  \/\/ the context lock held, but sometimes reads it without the context lock. This\n  \/\/ should be safe on x86, but is nonetheless flagged by TSAN.\n  \"race:sq_stop\\n\"\n\n  \/\/ Squeasel reads and frees ctx->listening_sockets without taking any locks. This\n  \/\/ may be an unsafe race.\n  \"race:close_all_listening_sockets\\n\"\n\n  \/\/ ------------------------------------------------------------\n  \/\/ Known bugs below. As these JIRAs are resolved, please remove the relevant\n  \/\/ suppression.\n  \/\/ ------------------------------------------------------------\n\n  \/\/ KUDU-1283: TSAN warning from consensus OpId\n  \"race:kudu::consensus::OpId::CopyFrom\\n\"\n\n  \/\/ KUDU-186: sketchy synchronization in catalog manager\n  \"race:kudu::master::CatalogManager::Shutdown\\n\"\n  \"race:kudu::master::CatalogManagerBgTasks::Shutdown\\n\"\n  \"race:kudu::master::CatalogManager::~CatalogManager\\n\"\n\n  \/\/ KUDU-574: raft_consensus_quorum-test race on LocalTestPeerProxy destruction\n  \"race:kudu::consensus::LocalTestPeerProxy::~LocalTestPeerProxy\\n\"\n\n  \/\/ KUDU-569: unsynchronized access to 'state_', 'acceptor_pools_', in\n  \/\/ GetBoundAddresses()\n  \"race:kudu::Webserver::GetBoundAddresses\\n\"\n  \"race:kudu::RpcServer::GetBoundAddresses\\n\"\n\n  \/\/ KUDU-2439: OpenSSL 1.1's atexit() handler may destroy global state while a\n  \/\/ Messenger is shutting down and still accessing that state. See\n  \/\/ https:\/\/github.com\/openssl\/openssl\/issues\/6214 for more details.\n  \/\/\n  \/\/ This is carried out by OPENSSL_cleanup, but TSAN's unwinder doesn't\n  \/\/ include any stack frame above the libcrypto lock destruction or memory release\n  \/\/ call for some reason, so we have to do something more generic.\n  \"called_from_lib:libcrypto.so\\n\"\n\n  \/\/ KUDU-2059: there may be outstanding reactor threads in DnsResolver at the\n  \/\/ time that the KuduClient (and DnsResolver) is destroyed.\n  \"race:kudu::DnsResolver::ResolveAddressesAsync\\n\";\n}\n#endif  \/\/ THREAD_SANITIZER\n\n#if defined(LEAK_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char *__lsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n\nSANITIZER_HOOK_ATTRIBUTE const char *__lsan_default_suppressions() {\n  return\n  \/\/ False positive from atexit() registration in libc\n  \"leak:*__new_exitfn*\\n\"\n\n  \/\/ False positive from krb5 < 1.12\n  \/\/ Fixed by upstream commit 379d39c17b8930718e98185a5b32a0f7f3e3b4b6\n  \"leak:krb5_authdata_import_attributes\\n\"\n\n  \/\/ KUDU-2653: Memory leak in libgssapi_krb5 [1]. Exists in certain patched\n  \/\/ versions of krb5-1.12 (such as krb5 in Debian 8).\n  \/\/\n  \/\/ Unfortunately there's no narrower match without resorting to\n  \/\/ fast_unwind_on_malloc=0; the best alternative is to match on glob, but that\n  \/\/ seems like overkill too.\n  \/\/\n  \/\/ 1. http:\/\/krbdev.mit.edu\/rt\/Ticket\/Display.html?id=7981\n  \"leak:libgssapi_krb5.so.2\\n\";\n}\n#endif  \/\/ LEAK_SANITIZER\n\n#if defined(UNDEFINED_SANITIZER)\nSANITIZER_HOOK_ATTRIBUTE const char* __ubsan_default_options() {\n  return\n#if defined(KUDU_EXTERNAL_SYMBOLIZER_PATH)\n  \/\/ Overried the symbolizer used when generating reports.\n  \"external_symbolizer_path=\" AS_STRING(KUDU_EXTERNAL_SYMBOLIZER_PATH) \" \"\n#endif\n  \/\/ Print the stacktrace when UBSan reports an error.\n  \"print_stacktrace=1 \"\n  \/\/ Prefixes up to and including this substring will be stripped from source\n  \/\/ file paths in symbolized reports.\n  \"strip_path_prefix=\/..\/ \";\n}\n#endif  \/\/ UNDEFINED_SANITIZER\n<|endoftext|>"}
{"text":"#include \"test_macros.hpp\"\n#include \n\nusing namespace matrix;\n\nint main()\n{\n    \/\/ general wraps\n    TEST(fabs(wrap(4.0, 0.0, 10.0) - 4.0) < FLT_EPSILON);\n    TEST(fabs(wrap(4.0, 0.0, 1.0)) < FLT_EPSILON);\n    TEST(fabs(wrap(-4.0, 0.0, 10.0) - 6.0) < FLT_EPSILON);\n    TEST(fabs(wrap(-18.0, 0.0, 10.0) - 2.0) < FLT_EPSILON);\n    TEST(fabs(wrap(-1.5, 3.0, 5.0) - 4.5) < FLT_EPSILON);\n    TEST(fabs(wrap(15.5, 3.0, 5.0) - 3.5) < FLT_EPSILON);\n    TEST(fabs(wrap(-1.0, 30.0, 40.0) - 39.0) < FLT_EPSILON);\n    TEST(fabs(wrap(-8000.0, -555.0, 1.0) - (-216.0)) < FLT_EPSILON);\n    TEST(fabs(wrap(0.0, 0.0, 360.0)) < FLT_EPSILON);\n    TEST(!is_finite(wrap(1000.,0.,.01)));\n\n    \/\/ wrap pi\n    TEST(fabs(wrap_pi(4.0) - (4.0 - M_TWOPI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(-4.0) - (-4.0 + M_TWOPI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(3.0) - (3.0)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(100.0f) - (100.0f - 32 * float(M_PI))) < 10e-5);\n    TEST(fabs(wrap_pi(-100.0f) - (-100.0f + 32 * float(M_PI))) < 10e-5);\n    TEST(fabs(wrap_pi(-101.0f) - (-101.0f + 32 * float(M_PI))) < 10e-5);\n    TEST(!is_finite(wrap_pi(NAN)));\n\n    \/\/ wrap 2pi\n    TEST(fabs(wrap_2pi(-4.0) - (-4.0 + 2*M_PI)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(3.0) - (3.0)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(200.0f) - (200.0f - 31 * float(M_TWOPI))) < 10e-5);\n    TEST(fabs(wrap_2pi(-201.0f) - (-201.0f + 32 * float(M_TWOPI))) < 10e-5);\n    TEST(fabs(wrap_2pi(0.0f)) < FLT_EPSILON);\n    TEST(!is_finite(wrap_2pi(NAN)));\n\n    Vector3f a(1, 2, 3);\n    Vector3f b(4, 5, 6);\n    TEST(!isEqual(a, b));\n    TEST(isEqual(a, a));\n\n    TEST(isEqualF(1.0f, 1.0f));\n    TEST(!isEqualF(1.0f, 2.0f));\n    return 0;\n}\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\nhelper test: cover wrap close to limits cases (#84)#include \"test_macros.hpp\"\n#include \n\nusing namespace matrix;\n\nint main()\n{\n    \/\/ general wraps\n    TEST(fabs(wrap(4., 0., 10.) - 4.) < FLT_EPSILON);\n    TEST(fabs(wrap(4., 0., 1.)) < FLT_EPSILON);\n    TEST(fabs(wrap(-4., 0., 10.) - 6.) < FLT_EPSILON);\n    TEST(fabs(wrap(-18., 0., 10.) - 2.) < FLT_EPSILON);\n    TEST(fabs(wrap(-1.5, 3., 5.) - 4.5) < FLT_EPSILON);\n    TEST(fabs(wrap(15.5, 3., 5.) - 3.5) < FLT_EPSILON);\n    TEST(fabs(wrap(-1., 30., 40.) - 39.) < FLT_EPSILON);\n    TEST(fabs(wrap(-8000., -555., 1.) - (-216.)) < FLT_EPSILON);\n    TEST(fabs(wrap(0., 0., 360.)) < FLT_EPSILON);\n    TEST(fabs(wrap(0. - FLT_EPSILON, 0., 360.) - (360. - FLT_EPSILON)) < FLT_EPSILON);\n    TEST(fabs(wrap(0. + FLT_EPSILON, 0., 360.) - FLT_EPSILON) < FLT_EPSILON);\n    TEST(fabs(wrap(360., 0., 360.)) < FLT_EPSILON);\n    TEST(fabs(wrap(360. - FLT_EPSILON, 0., 360.) - (360. - FLT_EPSILON)) < FLT_EPSILON);\n    TEST(fabs(wrap(360. + FLT_EPSILON, 0., 360.) - FLT_EPSILON) < FLT_EPSILON);\n    TEST(!is_finite(wrap(1000., 0., .01)));\n\n    \/\/ wrap pi\n    TEST(fabs(wrap_pi(0.)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(4.) - (4. - M_TWOPI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(-4.) - (-4. + M_TWOPI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(3.) - (3.)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(100.) - (100. - 32. * M_PI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(-100.) - (-100. + 32. * M_PI)) < FLT_EPSILON);\n    TEST(fabs(wrap_pi(-101.) - (-101. + 32. * M_PI)) < FLT_EPSILON);\n    TEST(!is_finite(wrap_pi(NAN)));\n\n    \/\/ wrap 2pi\n    TEST(fabs(wrap_2pi(0.)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(-4.) - (-4. + 2. * M_PI)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(3.) - (3.)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(200.) - (200. - 31. * M_TWOPI)) < FLT_EPSILON);\n    TEST(fabs(wrap_2pi(-201.) - (-201. + 32. * M_TWOPI)) < FLT_EPSILON);\n    TEST(!is_finite(wrap_2pi(NAN)));\n\n    Vector3f a(1, 2, 3);\n    Vector3f b(4, 5, 6);\n    TEST(!isEqual(a, b));\n    TEST(isEqual(a, a));\n\n    TEST(isEqualF(1., 1.));\n    TEST(!isEqualF(1., 2.));\n    return 0;\n}\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\n<|endoftext|>"}
{"text":"\/*\n * xtensor-fftw\n * Copyright (c) 2017, Patrick Bos\n * Distributed under the terms of the BSD 3-Clause License.\n *\n * The full license is in the file LICENSE, distributed with this software.\n *\/\n\n#include \n#include \n#include   \/\/ M_PI\n\n#include \"gtest\/gtest.h\"\n\n\nTEST(helper, fftshift) {\n  xt::xarray odd = {3, 4, 0, 1, 2};\n  xt::xarray even = {3, 4, 5, 0, 1, 2};\n  xt::xarray odd_range = xt::arange(5);\n  xt::xarray even_range = xt::arange(6);\n  EXPECT_EQ(xt::fftw::fftshift(odd_range), odd);\n  EXPECT_EQ(xt::fftw::fftshift(even_range), even);\n}\n\nTEST(helper, ifftshift) {\n  xt::xarray odd = {3, 4, 0, 1, 2};\n  xt::xarray even = {3, 4, 5, 0, 1, 2};\n  EXPECT_EQ(xt::fftw::ifftshift(odd), xt::arange(5));\n  EXPECT_EQ(xt::fftw::ifftshift(even), xt::arange(6));\n}\n\nTEST(helper, fftfreq) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4., -4., -3., -2., -1.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, -0.2 , -0.16, -0.12, -0.08, -0.04};\n  EXPECT_EQ(xt::fftw::fftfreq(9, 1.\/9), reference9);\n  EXPECT_EQ(xt::fftw::fftfreq(10, 2.5), reference10);\n}\n\nTEST(helper, fftscale) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4., -4., -3., -2., -1.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, -0.2 , -0.16, -0.12, -0.08, -0.04};\n  EXPECT_EQ(xt::fftw::fftscale(9, 1.\/9), 2 * M_PI * reference9);\n  EXPECT_EQ(xt::fftw::fftscale(10, 2.5), 2 * M_PI * reference10);\n}\n\nTEST(helper, rfftfreq) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, 0.2};\n  EXPECT_EQ(xt::fftw::rfftfreq(9, 1.\/9), reference9);\n  EXPECT_EQ(xt::fftw::rfftfreq(10, 2.5), reference10);\n}\n\nTEST(helper, rfftscale) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, 0.2};\n  EXPECT_EQ(xt::fftw::rfftscale(9, 1.\/9), 2 * M_PI * reference9);\n  EXPECT_EQ(xt::fftw::rfftscale(10, 2.5), 2 * M_PI * reference10);\n}\nFix helper tests on Appveyor Windows\/*\n * xtensor-fftw\n * Copyright (c) 2017, Patrick Bos\n * Distributed under the terms of the BSD 3-Clause License.\n *\n * The full license is in the file LICENSE, distributed with this software.\n *\/\n\n#define _USE_MATH_DEFINES  \/\/ for MSVC (\"Math Constants are not defined in Standard C\/C++\")\n#include            \/\/ M_PI\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n\nTEST(helper, fftshift) {\n  xt::xarray odd = {3, 4, 0, 1, 2};\n  xt::xarray even = {3, 4, 5, 0, 1, 2};\n  xt::xarray odd_range = xt::arange(5);\n  xt::xarray even_range = xt::arange(6);\n  EXPECT_EQ(xt::fftw::fftshift(odd_range), odd);\n  EXPECT_EQ(xt::fftw::fftshift(even_range), even);\n}\n\nTEST(helper, ifftshift) {\n  xt::xarray odd = {3, 4, 0, 1, 2};\n  xt::xarray even = {3, 4, 5, 0, 1, 2};\n  EXPECT_EQ(xt::fftw::ifftshift(odd), xt::arange(5));\n  EXPECT_EQ(xt::fftw::ifftshift(even), xt::arange(6));\n}\n\nTEST(helper, fftfreq) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4., -4., -3., -2., -1.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, -0.2 , -0.16, -0.12, -0.08, -0.04};\n  EXPECT_EQ(xt::fftw::fftfreq(9, 1.\/9), reference9);\n  EXPECT_EQ(xt::fftw::fftfreq(10, 2.5), reference10);\n}\n\nTEST(helper, fftscale) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4., -4., -3., -2., -1.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, -0.2 , -0.16, -0.12, -0.08, -0.04};\n  EXPECT_EQ(xt::fftw::fftscale(9, 1.\/9), 2 * M_PI * reference9);\n  EXPECT_EQ(xt::fftw::fftscale(10, 2.5), 2 * M_PI * reference10);\n}\n\nTEST(helper, rfftfreq) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, 0.2};\n  EXPECT_EQ(xt::fftw::rfftfreq(9, 1.\/9), reference9);\n  EXPECT_EQ(xt::fftw::rfftfreq(10, 2.5), reference10);\n}\n\nTEST(helper, rfftscale) {\n  xt::xarray reference9 = {0.,  1.,  2.,  3.,  4.};\n  xt::xarray reference10 = {0.  ,  0.04,  0.08,  0.12,  0.16, 0.2};\n  EXPECT_EQ(xt::fftw::rfftscale(9, 1.\/9), 2 * M_PI * reference9);\n  EXPECT_EQ(xt::fftw::rfftscale(10, 2.5), 2 * M_PI * reference10);\n}\n<|endoftext|>"}
{"text":"#include \"toyfs.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::istringstream;\nusing std::fstream;\nusing std::make_shared;\nusing std::shared_ptr;\nusing std::string;\nusing std::vector;\nusing std::weak_ptr;\nusing std::deque;\nusing std::setw;\n\n#define ops_at_least(x)                                 \\\n  if (static_cast(args.size()) < x+1) {            \\\n    cerr << args[0] << \": missing operand\" << endl;     \\\n    return;                                             \\\n  }\n\n#define ops_less_than(x)                                \\\n  if (static_cast(args.size()) > x+1) {            \\\n    cerr << args[0] << \": too many operands\" << endl;   \\\n    return;                                             \\\n  }\n\n#define ops_exactly(x)                          \\\n  ops_at_least(x);                              \\\n  ops_less_than(x);\n\n\nvector parse_path(string path_str) {\n  istringstream is(path_str);\n  string token;\n  vector tokens;\n\n  while (getline(is, token, '\/')) {\n    tokens.push_back(token);\n  }\n  return tokens;\n}\n\nToyFS::ToyFS(const string& filename,\n             const uint fs_size,\n             const uint block_size)\n    : filename(filename),\n      fs_size(fs_size),\n      block_size(block_size),\n      num_blocks(ceil(fs_size \/ block_size)) {\n\n  root_dir = DirEntry::mk_DirEntry(\"root\", nullptr);\n  root_dir->type = dir;\n  \/\/ start at root dir;\n  pwd = root_dir;\n  init_disk(filename);\n  free_list.emplace_back(num_blocks, 0);\n}\n\nToyFS::~ToyFS() {\n  disk_file.close();\n  remove(filename.c_str());\n}\n\nvoid ToyFS::init_disk(const string& filename) {\n  const vectorzeroes(num_blocks, 0);\n\n  disk_file.open(filename,\n                 fstream::in |\n                 fstream::out |\n                 fstream::binary |\n                 fstream::trunc);\n\n  for (uint i = 0; i < num_blocks; ++i) {\n    disk_file.write(zeroes.data(), block_size);\n  }\n}\n\n\/\/ walk the dir tree from start, returning a pointer to the file\n\/\/ or directory specified in path_str\nshared_ptr ToyFS::find_file(const shared_ptr &start,\n                                      const vector &path_tokens) {\n  auto entry = start;\n  for (auto &tok : path_tokens) {\n    entry = entry->find_child(tok);\n    if (entry == nullptr) {\n      return entry;\n    }\n  }\n  return entry;\n}\n\nvoid ToyFS::open(vector args) {\n  ops_exactly(2);\n  uint mode;\n  istringstream(args[2]) >> mode;\n  auto where = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    where = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  if(path_tokens.size() == 0) {\n      cerr << \"cannot open root\" << endl;\n      return;\n  }\n\n  auto file_name = path_tokens.back();\n\n  \/\/ walk the input until we have the right dir\n  if (path_tokens.size() >= 2) {\n    path_tokens.pop_back();\n    where = find_file(where, path_tokens);\n  }\n  if (where == nullptr) {\n    cerr << \"Invalid path or something like that.\" << endl;\n    return;\n  }\n\n  auto file = find_file(where, vector{file_name});\n  \/\/ make sure we have a file, or explain why not\n  if (file == nullptr) {\n    if (mode == 1) {\n      cout << \"File does not exist.\" << endl;\n      return;\n    } else {\n      file = where->add_file(file_name);\n    }\n  }\n  if (file->type == dir) {\n    cout << \"Cannot open a directory.\" << endl;\n    return;\n  }\n\n  \/\/ get a descriptor\n  uint fd = next_descriptor++;\n  open_files[fd] = Descriptor{mode, 0, file->inode};\n  cout << fd << endl;\n  return;\n}\n\nvoid ToyFS::read(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::write(vector args) {\n  ops_at_least(2);\n}\n\nvoid ToyFS::seek(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::close(vector args) {\n  ops_exactly(1);\n  uint fd;\n  istringstream(args[1]) >> fd;\n  open_files.erase(fd);\n}\n\nvoid ToyFS::mkdir(vector args) {\n  ops_at_least(1);\n  \/* add each new directory one at a time *\/\n  for (uint i = 1; i < args.size(); i++) {\n    auto where = pwd;\n\n    \/* remove initial '\/' *\/\n    if (args[i][0] == '\/') {\n      args[i].erase(0,1);\n      where = root_dir;\n    }\n\n    \/* figure out new name and path *\/\n    auto path_tokens = parse_path(args[i]);\n    if(path_tokens.size() == 0) {\n        cerr << \"cannot recreate root\" << endl;\n        return;\n    }\n    auto new_dir_name = path_tokens.back();\n    if (path_tokens.size() >= 2) {\n      path_tokens.pop_back();\n      where = find_file(where, path_tokens);\n    }\n    if (where == nullptr) {\n      cerr << \"Invalid path or something like that\" << endl;\n      return;\n    }\n\n    \/* check that this directory doesn't exist *\/\n    auto file = find_file(where, vector{new_dir_name});\n    if (file != nullptr) {\n        cerr << new_dir_name << \" already exists\" << endl;\n        continue;\n    }\n\n    \/* actually add the directory *\/\n    where->add_dir(new_dir_name);\n  }\n}\n\nvoid ToyFS::rmdir(vector args) {\n  ops_at_least(1);\n\n  auto rm_dir = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    rm_dir = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  rm_dir = find_file(rm_dir, path_tokens);\n\n  if (rm_dir == nullptr) {\n    cerr << \"Invalid path\" << endl;\n  } else if (rm_dir == root_dir) {\n    cerr << \"rmdir: error: cannot remove root\" << endl;\n  } else if (rm_dir == pwd) {\n    cerr << \"rmdir: error: cannot remove working directory\" << endl;\n  } else if (rm_dir->contents.size() > 0) {\n    cerr << \"rmdir: error: directory not empty\" << endl;\n  } else if (rm_dir->type != dir) {\n    cerr << \"rmdir: error: \" << rm_dir->name << \" must be directory\\n\";\n  } else {\n    auto parent = rm_dir->parent.lock();\n    parent->contents.remove(rm_dir);\n  }\n}\n\nvoid ToyFS::printwd(vector args) {\n  ops_exactly(0);\n\n  if (pwd == root_dir) {\n      cout << \"\/\" << endl;\n      return;\n  }\n\n  auto wd = pwd;\n  deque plist;\n  while (wd != root_dir) {\n    plist.push_front(wd->name);\n    wd = wd->parent.lock();\n  }\n\n  for (auto dirname : plist) {\n      cout << \"\/\" << dirname;\n  }\n  cout << endl;\n}\n\nvoid ToyFS::cd(vector args) {\n  ops_exactly(1);\n\n  auto where = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    where = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  if (path_tokens.size() == 0) {\n    pwd = root_dir;\n    return;\n  }\n\n  where = find_file(where, path_tokens);\n\n  if (where == nullptr) {\n    cerr << \"cd: error: invalid path: \" << args[1] << endl;\n  } else if (where->type != dir) {\n    cerr << \"cd: error: \" << args[1] << \" must be a directory\" << endl; \n  } else {\n    pwd = where;\n  }\n}\n\nvoid ToyFS::link(vector args) {\n  ops_exactly(2);\n\n  auto src = pwd;\n  auto dest = pwd;\n\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    src = root_dir;\n  }\n  if (args[2][0] == '\/') {\n    args[2].erase(0,1);\n    dest = root_dir;\n  }\n\n  \/* get src file *\/\n  auto path_tokens = parse_path(args[1]);\n  auto src_file = find_file(src, path_tokens); \n\n  \/* get dest path *\/\n  path_tokens = parse_path(args[2]);\n  if (path_tokens.size() == 0) {\n    \/* dest is root *\/\n    cerr << \"link: error: \" << args[2] << \" already exists\" << endl;\n    return;\n  }\n  auto dest_file_name = path_tokens.back();\n  if (path_tokens.size() >= 2) {\n    path_tokens.pop_back();\n    dest = find_file(dest, path_tokens);\n  }\n\n  if (src_file == nullptr) {\n    cerr << \"link: error: cannot find \" << args[1] << endl;\n  } else if (find_file(dest,vector{dest_file_name}) != nullptr) {\n    cerr << \"link: error: \" << args[2] << \" already exists\" << endl;\n  } else if (src_file->type != file) {\n    cerr << \"link: error: \" << args[1] << \" must be a file\" << endl;\n  } else if (src_file->parent.lock() == dest) {\n    cerr << \"link: error: src and dest must be in different directories\\n\";\n  } else {\n    auto new_file = dest->mk_DirEntry(dest_file_name, dest, src_file->inode);\n    new_file->type = file;\n    dest->contents.push_back(new_file);\n  }\n}\n\nvoid ToyFS::unlink(vector args) {\n  ops_exactly(1);\n\n  auto linked = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    linked = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  linked = find_file(linked, path_tokens);\n  \n  if(linked == nullptr) {\n    cerr << \"unlink: error: file not found\" << endl;\n  } else if(linked->type != file) {\n    cerr << \"unlink: error: \" << args[1] << \" must be a file\" << endl;\n  } else {\n    auto parent = linked->parent.lock();\n    parent->contents.remove(linked);\n  }\n}\n\nvoid ToyFS::stat(vector args) {\n  ops_at_least(1);\n\n  auto filepath = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    filepath = root_dir;\n  }\n  \n  auto path_tokens = parse_path(args[1]);\n  filepath = find_file(filepath, path_tokens); \n  \n  if (filepath == nullptr) {\n    cerr << \"stat: error: \" << args[1] << \" not found\" << endl;\n  } else {\n    cout << \"  File: \" << filepath->name << endl;\n    if(filepath->type == file) {\n      cout << \"  Type: file\" << endl;\n      cout << \" Inode: \" << filepath->inode << endl;\n      cout << \" Links: \" << filepath->inode.use_count() << endl;\n      cout << \"  Size: \" << filepath->inode->size << endl;\n      cout << \"Blocks: \" << filepath->inode->blocks_used << endl;\n    } else if(filepath->type == dir) {\n      cout << \"  Type: directory\" << endl;\n    }\n  }\n}\n\nvoid ToyFS::ls(vector args) {\n  ops_exactly(0);\n  for(auto dir : pwd->contents) {\n    cout << dir->name << endl;\n  }\n}\n\nvoid ToyFS::cat(vector args) {\n  ops_at_least(1);\n}\n\nvoid ToyFS::cp(vector args) {\n  ops_exactly(2);\n}\n\nvoid tree_helper(shared_ptr directory, string indent) {\n  auto cont = directory->contents;\n  cout << directory->name << endl;\n  if (cont.size() == 0) return;\n\n  if (cont.size() >= 2) {\n    auto last = *(cont.rbegin());\n    for(auto entry = cont.begin(); *entry != last; entry++) {\n      cout << indent << \"├───\";\n      auto new_indent = \"│   \" + indent;\n      tree_helper(*entry, new_indent);\n    }\n  }\n  \n  cout << indent + \"└───\";\n  tree_helper(*(cont.rbegin()), indent + \"    \");\n}\n\nvoid ToyFS::tree(vector args) {\n  ops_exactly(0);\n\n  tree_helper(pwd, \"\");\n}\n\nvoid ToyFS::import(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::FS_export(vector args) {\n  ops_exactly(2);\n}\nspoke too soon, but found and corrected a bug in tree#include \"toyfs.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::istringstream;\nusing std::fstream;\nusing std::make_shared;\nusing std::shared_ptr;\nusing std::string;\nusing std::vector;\nusing std::weak_ptr;\nusing std::deque;\nusing std::setw;\n\n#define ops_at_least(x)                                 \\\n  if (static_cast(args.size()) < x+1) {            \\\n    cerr << args[0] << \": missing operand\" << endl;     \\\n    return;                                             \\\n  }\n\n#define ops_less_than(x)                                \\\n  if (static_cast(args.size()) > x+1) {            \\\n    cerr << args[0] << \": too many operands\" << endl;   \\\n    return;                                             \\\n  }\n\n#define ops_exactly(x)                          \\\n  ops_at_least(x);                              \\\n  ops_less_than(x);\n\n\nvector parse_path(string path_str) {\n  istringstream is(path_str);\n  string token;\n  vector tokens;\n\n  while (getline(is, token, '\/')) {\n    tokens.push_back(token);\n  }\n  return tokens;\n}\n\nToyFS::ToyFS(const string& filename,\n             const uint fs_size,\n             const uint block_size)\n    : filename(filename),\n      fs_size(fs_size),\n      block_size(block_size),\n      num_blocks(ceil(fs_size \/ block_size)) {\n\n  root_dir = DirEntry::mk_DirEntry(\"root\", nullptr);\n  root_dir->type = dir;\n  \/\/ start at root dir;\n  pwd = root_dir;\n  init_disk(filename);\n  free_list.emplace_back(num_blocks, 0);\n}\n\nToyFS::~ToyFS() {\n  disk_file.close();\n  remove(filename.c_str());\n}\n\nvoid ToyFS::init_disk(const string& filename) {\n  const vectorzeroes(num_blocks, 0);\n\n  disk_file.open(filename,\n                 fstream::in |\n                 fstream::out |\n                 fstream::binary |\n                 fstream::trunc);\n\n  for (uint i = 0; i < num_blocks; ++i) {\n    disk_file.write(zeroes.data(), block_size);\n  }\n}\n\n\/\/ walk the dir tree from start, returning a pointer to the file\n\/\/ or directory specified in path_str\nshared_ptr ToyFS::find_file(const shared_ptr &start,\n                                      const vector &path_tokens) {\n  auto entry = start;\n  for (auto &tok : path_tokens) {\n    entry = entry->find_child(tok);\n    if (entry == nullptr) {\n      return entry;\n    }\n  }\n  return entry;\n}\n\nvoid ToyFS::open(vector args) {\n  ops_exactly(2);\n  uint mode;\n  istringstream(args[2]) >> mode;\n  auto where = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    where = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  if(path_tokens.size() == 0) {\n      cerr << \"cannot open root\" << endl;\n      return;\n  }\n\n  auto file_name = path_tokens.back();\n\n  \/\/ walk the input until we have the right dir\n  if (path_tokens.size() >= 2) {\n    path_tokens.pop_back();\n    where = find_file(where, path_tokens);\n  }\n  if (where == nullptr) {\n    cerr << \"Invalid path or something like that.\" << endl;\n    return;\n  }\n\n  auto file = find_file(where, vector{file_name});\n  \/\/ make sure we have a file, or explain why not\n  if (file == nullptr) {\n    if (mode == 1) {\n      cout << \"File does not exist.\" << endl;\n      return;\n    } else {\n      file = where->add_file(file_name);\n    }\n  }\n  if (file->type == dir) {\n    cout << \"Cannot open a directory.\" << endl;\n    return;\n  }\n\n  \/\/ get a descriptor\n  uint fd = next_descriptor++;\n  open_files[fd] = Descriptor{mode, 0, file->inode};\n  cout << fd << endl;\n  return;\n}\n\nvoid ToyFS::read(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::write(vector args) {\n  ops_at_least(2);\n}\n\nvoid ToyFS::seek(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::close(vector args) {\n  ops_exactly(1);\n  uint fd;\n  istringstream(args[1]) >> fd;\n  open_files.erase(fd);\n}\n\nvoid ToyFS::mkdir(vector args) {\n  ops_at_least(1);\n  \/* add each new directory one at a time *\/\n  for (uint i = 1; i < args.size(); i++) {\n    auto where = pwd;\n\n    \/* remove initial '\/' *\/\n    if (args[i][0] == '\/') {\n      args[i].erase(0,1);\n      where = root_dir;\n    }\n\n    \/* figure out new name and path *\/\n    auto path_tokens = parse_path(args[i]);\n    if(path_tokens.size() == 0) {\n        cerr << \"cannot recreate root\" << endl;\n        return;\n    }\n    auto new_dir_name = path_tokens.back();\n    if (path_tokens.size() >= 2) {\n      path_tokens.pop_back();\n      where = find_file(where, path_tokens);\n    }\n    if (where == nullptr) {\n      cerr << \"Invalid path or something like that\" << endl;\n      return;\n    }\n\n    \/* check that this directory doesn't exist *\/\n    auto file = find_file(where, vector{new_dir_name});\n    if (file != nullptr) {\n        cerr << new_dir_name << \" already exists\" << endl;\n        continue;\n    }\n\n    \/* actually add the directory *\/\n    where->add_dir(new_dir_name);\n  }\n}\n\nvoid ToyFS::rmdir(vector args) {\n  ops_at_least(1);\n\n  auto rm_dir = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    rm_dir = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  rm_dir = find_file(rm_dir, path_tokens);\n\n  if (rm_dir == nullptr) {\n    cerr << \"Invalid path\" << endl;\n  } else if (rm_dir == root_dir) {\n    cerr << \"rmdir: error: cannot remove root\" << endl;\n  } else if (rm_dir == pwd) {\n    cerr << \"rmdir: error: cannot remove working directory\" << endl;\n  } else if (rm_dir->contents.size() > 0) {\n    cerr << \"rmdir: error: directory not empty\" << endl;\n  } else if (rm_dir->type != dir) {\n    cerr << \"rmdir: error: \" << rm_dir->name << \" must be directory\\n\";\n  } else {\n    auto parent = rm_dir->parent.lock();\n    parent->contents.remove(rm_dir);\n  }\n}\n\nvoid ToyFS::printwd(vector args) {\n  ops_exactly(0);\n\n  if (pwd == root_dir) {\n      cout << \"\/\" << endl;\n      return;\n  }\n\n  auto wd = pwd;\n  deque plist;\n  while (wd != root_dir) {\n    plist.push_front(wd->name);\n    wd = wd->parent.lock();\n  }\n\n  for (auto dirname : plist) {\n      cout << \"\/\" << dirname;\n  }\n  cout << endl;\n}\n\nvoid ToyFS::cd(vector args) {\n  ops_exactly(1);\n\n  auto where = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    where = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  if (path_tokens.size() == 0) {\n    pwd = root_dir;\n    return;\n  }\n\n  where = find_file(where, path_tokens);\n\n  if (where == nullptr) {\n    cerr << \"cd: error: invalid path: \" << args[1] << endl;\n  } else if (where->type != dir) {\n    cerr << \"cd: error: \" << args[1] << \" must be a directory\" << endl; \n  } else {\n    pwd = where;\n  }\n}\n\nvoid ToyFS::link(vector args) {\n  ops_exactly(2);\n\n  auto src = pwd;\n  auto dest = pwd;\n\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    src = root_dir;\n  }\n  if (args[2][0] == '\/') {\n    args[2].erase(0,1);\n    dest = root_dir;\n  }\n\n  \/* get src file *\/\n  auto path_tokens = parse_path(args[1]);\n  auto src_file = find_file(src, path_tokens); \n\n  \/* get dest path *\/\n  path_tokens = parse_path(args[2]);\n  if (path_tokens.size() == 0) {\n    \/* dest is root *\/\n    cerr << \"link: error: \" << args[2] << \" already exists\" << endl;\n    return;\n  }\n  auto dest_file_name = path_tokens.back();\n  if (path_tokens.size() >= 2) {\n    path_tokens.pop_back();\n    dest = find_file(dest, path_tokens);\n  }\n\n  if (src_file == nullptr) {\n    cerr << \"link: error: cannot find \" << args[1] << endl;\n  } else if (find_file(dest,vector{dest_file_name}) != nullptr) {\n    cerr << \"link: error: \" << args[2] << \" already exists\" << endl;\n  } else if (src_file->type != file) {\n    cerr << \"link: error: \" << args[1] << \" must be a file\" << endl;\n  } else if (src_file->parent.lock() == dest) {\n    cerr << \"link: error: src and dest must be in different directories\\n\";\n  } else {\n    auto new_file = dest->mk_DirEntry(dest_file_name, dest, src_file->inode);\n    new_file->type = file;\n    dest->contents.push_back(new_file);\n  }\n}\n\nvoid ToyFS::unlink(vector args) {\n  ops_exactly(1);\n\n  auto linked = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    linked = root_dir;\n  }\n\n  auto path_tokens = parse_path(args[1]);\n  linked = find_file(linked, path_tokens);\n  \n  if(linked == nullptr) {\n    cerr << \"unlink: error: file not found\" << endl;\n  } else if(linked->type != file) {\n    cerr << \"unlink: error: \" << args[1] << \" must be a file\" << endl;\n  } else {\n    auto parent = linked->parent.lock();\n    parent->contents.remove(linked);\n  }\n}\n\nvoid ToyFS::stat(vector args) {\n  ops_at_least(1);\n\n  auto filepath = pwd;\n  if (args[1][0] == '\/') {\n    args[1].erase(0,1);\n    filepath = root_dir;\n  }\n  \n  auto path_tokens = parse_path(args[1]);\n  filepath = find_file(filepath, path_tokens); \n  \n  if (filepath == nullptr) {\n    cerr << \"stat: error: \" << args[1] << \" not found\" << endl;\n  } else {\n    cout << \"  File: \" << filepath->name << endl;\n    if(filepath->type == file) {\n      cout << \"  Type: file\" << endl;\n      cout << \" Inode: \" << filepath->inode << endl;\n      cout << \" Links: \" << filepath->inode.use_count() << endl;\n      cout << \"  Size: \" << filepath->inode->size << endl;\n      cout << \"Blocks: \" << filepath->inode->blocks_used << endl;\n    } else if(filepath->type == dir) {\n      cout << \"  Type: directory\" << endl;\n    }\n  }\n}\n\nvoid ToyFS::ls(vector args) {\n  ops_exactly(0);\n  for(auto dir : pwd->contents) {\n    cout << dir->name << endl;\n  }\n}\n\nvoid ToyFS::cat(vector args) {\n  ops_at_least(1);\n}\n\nvoid ToyFS::cp(vector args) {\n  ops_exactly(2);\n}\n\nvoid tree_helper(shared_ptr directory, string indent) {\n  auto cont = directory->contents;\n  cout << directory->name << endl;\n  if (cont.size() == 0) return;\n\n  if (cont.size() >= 2) {\n    auto last = *(cont.rbegin());\n    for(auto entry = cont.begin(); *entry != last; entry++) {\n      cout << indent << \"├───\";\n      tree_helper(*entry, indent + \"│   \");\n    }\n  }\n  \n  cout << indent << \"└───\";\n  tree_helper(*(cont.rbegin()), indent + \"    \");\n}\n\nvoid ToyFS::tree(vector args) {\n  ops_exactly(0);\n\n  tree_helper(pwd, \"\");\n}\n\nvoid ToyFS::import(vector args) {\n  ops_exactly(2);\n}\n\nvoid ToyFS::FS_export(vector args) {\n  ops_exactly(2);\n}\n<|endoftext|>"}
{"text":"#include \"runtime_internal.h\"\n#include \"HalideRuntime.h\"\n#include \"printer.h\"\n#include \"scoped_mutex_lock.h\"\n\n\/\/ Note: The profiler thread may out-live any valid user_context, or\n\/\/ be used across many different user_contexts, so nothing it calls\n\/\/ can depend on the user context.\n\nextern \"C\" {\n\/\/ Returns the address of the global halide_profiler state\nWEAK halide_profiler_state *halide_profiler_get_state() {\n    static halide_profiler_state s = {{{0}}, NULL, 1, 0, 0, false};\n    return &s;\n}\n}\n\nnamespace Halide { namespace Runtime { namespace Internal {\n\nWEAK halide_profiler_pipeline_stats *find_or_create_pipeline(const char *pipeline_name, int num_funcs, const uint64_t *func_names) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        \/\/ The same pipeline will deliver the same global constant\n        \/\/ string, so they can be compared by pointer.\n        if (p->name == pipeline_name &&\n            p->num_funcs == num_funcs) {\n            return p;\n        }\n    }\n    \/\/ Create a new pipeline stats entry.\n    halide_profiler_pipeline_stats *p =\n        (halide_profiler_pipeline_stats *)malloc(sizeof(halide_profiler_pipeline_stats));\n    if (!p) return NULL;\n    p->next = s->pipelines;\n    p->name = pipeline_name;\n    p->first_func_id = s->first_free_id;\n    p->num_funcs = num_funcs;\n    p->runs = 0;\n    p->time = 0;\n    p->samples = 0;\n    p->memory_current = 0;\n    p->memory_peak = 0;\n    p->memory_total = 0;\n    p->num_allocs = 0;\n    p->funcs = (halide_profiler_func_stats *)malloc(num_funcs * sizeof(halide_profiler_func_stats));\n    if (!p->funcs) {\n        free(p);\n        return NULL;\n    }\n    for (int i = 0; i < num_funcs; i++) {\n        p->funcs[i].time = 0;\n        p->funcs[i].name = (const char *)(func_names[i]);\n        p->funcs[i].memory_current = 0;\n        p->funcs[i].memory_peak = 0;\n        p->funcs[i].memory_total = 0;\n        p->funcs[i].num_allocs = 0;\n    }\n    s->first_free_id += num_funcs;\n    s->pipelines = p;\n    return p;\n}\n\nWEAK void bill_func(halide_profiler_state *s, int func_id, uint64_t time) {\n    halide_profiler_pipeline_stats *p_prev = NULL;\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        if (func_id >= p->first_func_id && func_id < p->first_func_id + p->num_funcs) {\n            if (p_prev) {\n                \/\/ Bubble the pipeline to the top to speed up future queries.\n                p_prev->next = (halide_profiler_pipeline_stats *)(p->next);\n                p->next = s->pipelines;\n                s->pipelines = p;\n            }\n            p->funcs[func_id - p->first_func_id].time += time;\n            p->time += time;\n            p->samples++;\n            return;\n        }\n        p_prev = p;\n    }\n    \/\/ Someone must have called reset_state while a kernel was running. Do nothing.\n}\n\nWEAK void sampling_profiler_thread(void *) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    \/\/ grab the lock\n    halide_mutex_lock(&s->lock);\n\n    while (s->current_func != halide_profiler_please_stop) {\n\n        uint64_t t1 = halide_current_time_ns(NULL);\n        uint64_t t = t1;\n        while (1) {\n            uint64_t t_now = halide_current_time_ns(NULL);\n            int func = s->current_func;\n            if (func == halide_profiler_please_stop) {\n                break;\n            } else if (func >= 0) {\n                \/\/ Assume all time since I was last awake is due to\n                \/\/ the currently running func.\n                bill_func(s, func, t_now - t);\n            }\n            t = t_now;\n\n            \/\/ Release the lock, sleep, reacquire.\n            int sleep_ms = s->sleep_time;\n            halide_mutex_unlock(&s->lock);\n            halide_sleep_ms(NULL, sleep_ms);\n            halide_mutex_lock(&s->lock);\n        }\n    }\n\n    s->started = false;\n\n    halide_mutex_unlock(&s->lock);\n}\n\n}}}\n\nextern \"C\" {\n\n\/\/ Returns a token identifying this pipeline instance.\nWEAK int halide_profiler_pipeline_start(void *user_context,\n                                        const char *pipeline_name,\n                                        int num_funcs,\n                                        const uint64_t *func_names) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    ScopedMutexLock lock(&s->lock);\n\n    if (!s->started) {\n        halide_start_clock(user_context);\n        halide_spawn_thread(user_context, sampling_profiler_thread, NULL);\n        s->started = true;\n    }\n\n    halide_profiler_pipeline_stats *p =\n        find_or_create_pipeline(pipeline_name, num_funcs, func_names);\n    if (!p) {\n        \/\/ Allocating space to track the statistics failed.\n        return halide_error_out_of_memory(user_context);\n    }\n    p->runs++;\n\n    return p->first_func_id;\n}\n\nWEAK void halide_profiler_memory_allocate(void *user_context,\n                                          const char *pipeline_name,\n                                          int token,\n                                          int func_id,\n                                          int incr) {\n    halide_profiler_state *s = halide_profiler_get_state();\n    ScopedMutexLock lock(&s->lock);\n\n    func_id += token;\n\n    halide_profiler_pipeline_stats *p_stats = NULL;\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        \/\/ The same pipeline will deliver the same global constant\n        \/\/ string, so they can be compared by pointer.\n        if (p->name == pipeline_name) {\n            p_stats = p;\n            break;\n        }\n    }\n\n    halide_assert(user_context, p_stats != NULL);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) >= 0);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) < p_stats->num_funcs);\n\n    halide_profiler_func_stats *f_stats = &p_stats->funcs[func_id - p_stats->first_func_id];\n\n    \/\/ Update per-pipeline memory stats\n    p_stats->num_allocs += 1;\n    p_stats->memory_total += incr;\n    p_stats->memory_current += incr;\n    if (p_stats->memory_current > p_stats->memory_peak) {\n        p_stats->memory_peak = p_stats->memory_current;\n    }\n\n    \/\/ Update per-func memory stats\n    f_stats->num_allocs += 1;\n    f_stats->memory_total += incr;\n    f_stats->memory_current += incr;\n    if (f_stats->memory_current > f_stats->memory_peak) {\n        f_stats->memory_peak = f_stats->memory_current;\n    }\n\n    \/*\/\/ Update per-pipeline memory stats\n    __sync_add_and_fetch(&p_stats->num_allocs, 1);\n    __sync_add_and_fetch(&p_stats->memory_total, incr);\n    int p_mem_current = __sync_add_and_fetch(&p_stats->memory_current, incr);\n    if (p_mem_current > p_stats->memory_peak) {\n        p_stats->memory_peak = p_mem_current;\n    }\n\n    \/\/ Update per-func memory stats\n    _sync_add_and_fetch(&f_stats->num_allocs, incr);\n    __sync_add_and_fetch(&f_stats->memory_total, incr);\n    int f_mem_current = __sync_add_and_fetch(&f_stats->memory_current, incr);\n    if (f_mem_current > f_stats->memory_peak) {\n        f_stats->memory_peak = f_mem_current;\n    }*\/\n}\n\nWEAK void halide_profiler_memory_free(void *user_context,\n                                      const char *pipeline_name,\n                                      int token,\n                                      int func_id,\n                                      int decr) {\n    halide_profiler_state *s = halide_profiler_get_state();\n    ScopedMutexLock lock(&s->lock);\n\n    func_id += token;\n\n    halide_profiler_pipeline_stats *p_stats = NULL;\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        \/\/ The same pipeline will deliver the same global constant\n        \/\/ string, so they can be compared by pointer.\n        if (p->name == pipeline_name) {\n            p_stats = p;\n            break;\n        }\n    }\n    halide_assert(user_context, p_stats != NULL);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) >= 0);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) < p_stats->num_funcs);\n\n    halide_profiler_func_stats *f_stats = &p_stats->funcs[func_id - p_stats->first_func_id];\n\n    \/\/ Update per-pipeline memory stats\n    p_stats->memory_current -= decr;\n\n    \/\/ Update per-func memory stats\n    f_stats->memory_current -= decr;\n\n    \/*\/\/ Update per-pipeline memory stats\n    __sync_sub_and_fetch(&p_stats->memory_current, decr);\n\n    \/\/ Update per-func memory stats\n    __sync_sub_and_fetch(&f_stats->memory_current, decr);*\/\n}\n\nWEAK void halide_profiler_report_unlocked(void *user_context, halide_profiler_state *s) {\n\n    char line_buf[400];\n    Printer sstr(user_context, line_buf);\n\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        float t = p->time \/ 1000000.0f;\n        if (!p->runs) continue;\n        sstr.clear();\n        int alloc_avg = 0;\n        if (p->num_allocs != 0) {\n            alloc_avg = p->memory_total\/p->num_allocs;\n        }\n        sstr << p->name\n             << \"  total time: \" << t << \" ms\"\n             << \"  samples: \" << p->samples\n             << \"  runs: \" << p->runs\n             << \"  time\/run: \" << t \/ p->runs << \" ms\"\n             << \"  num_allocs: \" << p->num_allocs\n             << \"  mem_peak: \" << p->memory_peak << \" bytes\"\n             << \"  mem_total: \" << p->memory_total << \" bytes\"\n             << \"  alloc_avg: \" << alloc_avg << \" bytes\\n\";\n        halide_print(user_context, sstr.str());\n        if (p->time || p->memory_total) {\n            for (int i = 0; i < p->num_funcs; i++) {\n                sstr.clear();\n                halide_profiler_func_stats *fs = p->funcs + i;\n\n                \/\/ The first func is always a catch-all overhead\n                \/\/ slot. Only report overhead time if it's non-zero\n                if (i == 0 && fs->time == 0) continue;\n\n                sstr << \"  \" << fs->name << \": \";\n                while (sstr.size() < 25) sstr << \" \";\n\n                float ft = fs->time \/ (p->runs * 1000000.0f);\n                sstr << ft << \"ms\";\n                while (sstr.size() < 40) sstr << \" \";\n\n                int percent = 0;\n                if (p->time != 0) {\n                    percent = fs->time \/ (p->time \/ 100);\n                }\n                sstr << \"(\" << percent << \"%)\";\n                while (sstr.size() < 55) sstr << \" \";\n\n                int alloc_avg = 0;\n                if (fs->num_allocs != 0) {\n                    alloc_avg = fs->memory_total\/fs->num_allocs;\n                }\n\n                sstr << \"(\" << fs->memory_current << \", \" << fs->memory_peak\n                     << \", \" << fs->memory_total << \", \" << fs->num_allocs\n                     << \", \" << alloc_avg << \") bytes\\n\";\n\n                halide_print(user_context, sstr.str());\n            }\n        }\n    }\n}\n\nWEAK void halide_profiler_report(void *user_context) {\n    halide_profiler_state *s = halide_profiler_get_state();\n    ScopedMutexLock lock(&s->lock);\n    halide_profiler_report_unlocked(user_context, s);\n}\n\n\nWEAK void halide_profiler_reset() {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    ScopedMutexLock lock(&s->lock);\n\n    while (s->pipelines) {\n        halide_profiler_pipeline_stats *p = s->pipelines;\n        s->pipelines = (halide_profiler_pipeline_stats *)(p->next);\n        free(p->funcs);\n        free(p);\n    }\n    s->first_free_id = 0;\n}\n\nnamespace {\n__attribute__((destructor))\nWEAK void halide_profiler_shutdown() {\n    halide_profiler_state *s = halide_profiler_get_state();\n    if (!s->started) return;\n    s->current_func = halide_profiler_please_stop;\n    do {\n        \/\/ Memory barrier.\n        __sync_synchronize(&s->started,\n                           &s->current_func);\n    } while (s->started);\n    s->current_func = halide_profiler_outside_of_halide;\n\n    \/\/ Print results. No need to lock anything because we just shut\n    \/\/ down the thread.\n    halide_profiler_report_unlocked(NULL, s);\n\n    \/\/ Leak the memory. Not all implementations of ScopedMutexLock may\n    \/\/ be safe to use at static destruction time (windows).\n    \/\/ halide_profiler_reset();\n}\n}\n\nWEAK void halide_profiler_pipeline_end(void *user_context, void *state) {\n    ((halide_profiler_state *)state)->current_func = halide_profiler_outside_of_halide;\n}\n\n}\nAdded temp fix for the profiler_allocate\/free locking issues#include \"runtime_internal.h\"\n#include \"HalideRuntime.h\"\n#include \"printer.h\"\n#include \"scoped_mutex_lock.h\"\n\n\/\/ Note: The profiler thread may out-live any valid user_context, or\n\/\/ be used across many different user_contexts, so nothing it calls\n\/\/ can depend on the user context.\n\nextern \"C\" {\n\/\/ Returns the address of the global halide_profiler state\nWEAK halide_profiler_state *halide_profiler_get_state() {\n    static halide_profiler_state s = {{{0}}, NULL, 1, 0, 0, false};\n    return &s;\n}\n}\n\nnamespace Halide { namespace Runtime { namespace Internal {\n\nWEAK halide_profiler_pipeline_stats *find_or_create_pipeline(const char *pipeline_name, int num_funcs, const uint64_t *func_names) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        \/\/ The same pipeline will deliver the same global constant\n        \/\/ string, so they can be compared by pointer.\n        if (p->name == pipeline_name &&\n            p->num_funcs == num_funcs) {\n            return p;\n        }\n    }\n    \/\/ Create a new pipeline stats entry.\n    halide_profiler_pipeline_stats *p =\n        (halide_profiler_pipeline_stats *)malloc(sizeof(halide_profiler_pipeline_stats));\n    if (!p) return NULL;\n    p->next = s->pipelines;\n    p->name = pipeline_name;\n    p->first_func_id = s->first_free_id;\n    p->num_funcs = num_funcs;\n    p->runs = 0;\n    p->time = 0;\n    p->samples = 0;\n    p->memory_current = 0;\n    p->memory_peak = 0;\n    p->memory_total = 0;\n    p->num_allocs = 0;\n    p->funcs = (halide_profiler_func_stats *)malloc(num_funcs * sizeof(halide_profiler_func_stats));\n    if (!p->funcs) {\n        free(p);\n        return NULL;\n    }\n    for (int i = 0; i < num_funcs; i++) {\n        p->funcs[i].time = 0;\n        p->funcs[i].name = (const char *)(func_names[i]);\n        p->funcs[i].memory_current = 0;\n        p->funcs[i].memory_peak = 0;\n        p->funcs[i].memory_total = 0;\n        p->funcs[i].num_allocs = 0;\n    }\n    s->first_free_id += num_funcs;\n    s->pipelines = p;\n    return p;\n}\n\nWEAK void bill_func(halide_profiler_state *s, int func_id, uint64_t time) {\n    halide_profiler_pipeline_stats *p_prev = NULL;\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        if (func_id >= p->first_func_id && func_id < p->first_func_id + p->num_funcs) {\n            if (p_prev) {\n                \/\/ Bubble the pipeline to the top to speed up future queries.\n                p_prev->next = (halide_profiler_pipeline_stats *)(p->next);\n                p->next = s->pipelines;\n                s->pipelines = p;\n            }\n            p->funcs[func_id - p->first_func_id].time += time;\n            p->time += time;\n            p->samples++;\n            return;\n        }\n        p_prev = p;\n    }\n    \/\/ Someone must have called reset_state while a kernel was running. Do nothing.\n}\n\nWEAK void sampling_profiler_thread(void *) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    \/\/ grab the lock\n    halide_mutex_lock(&s->lock);\n\n    while (s->current_func != halide_profiler_please_stop) {\n\n        uint64_t t1 = halide_current_time_ns(NULL);\n        uint64_t t = t1;\n        while (1) {\n            uint64_t t_now = halide_current_time_ns(NULL);\n            int func = s->current_func;\n            if (func == halide_profiler_please_stop) {\n                break;\n            } else if (func >= 0) {\n                \/\/ Assume all time since I was last awake is due to\n                \/\/ the currently running func.\n                bill_func(s, func, t_now - t);\n            }\n            t = t_now;\n\n            \/\/ Release the lock, sleep, reacquire.\n            int sleep_ms = s->sleep_time;\n            halide_mutex_unlock(&s->lock);\n            halide_sleep_ms(NULL, sleep_ms);\n            halide_mutex_lock(&s->lock);\n        }\n    }\n\n    s->started = false;\n\n    halide_mutex_unlock(&s->lock);\n}\n\nWEAK halide_profiler_pipeline_stats *find_pipeline_stats(const char *pipeline_name) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    halide_profiler_pipeline_stats *p_stats = NULL;\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        \/\/ The same pipeline will deliver the same global constant\n        \/\/ string, so they can be compared by pointer.\n        if (p->name == pipeline_name) {\n            p_stats = p;\n            break;\n        }\n    }\n    return p_stats;\n}\n\n}}}\n\nextern \"C\" {\n\n\/\/ Returns a token identifying this pipeline instance.\nWEAK int halide_profiler_pipeline_start(void *user_context,\n                                        const char *pipeline_name,\n                                        int num_funcs,\n                                        const uint64_t *func_names) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    ScopedMutexLock lock(&s->lock);\n\n    if (!s->started) {\n        halide_start_clock(user_context);\n        halide_spawn_thread(user_context, sampling_profiler_thread, NULL);\n        s->started = true;\n    }\n\n    halide_profiler_pipeline_stats *p =\n        find_or_create_pipeline(pipeline_name, num_funcs, func_names);\n    if (!p) {\n        \/\/ Allocating space to track the statistics failed.\n        return halide_error_out_of_memory(user_context);\n    }\n    p->runs++;\n\n    return p->first_func_id;\n}\n\nWEAK void halide_profiler_memory_allocate(void *user_context,\n                                          const char *pipeline_name,\n                                          int token,\n                                          int func_id,\n                                          int incr) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    func_id += token;\n\n    halide_profiler_pipeline_stats *p_stats = find_pipeline_stats(pipeline_name);\n    if (p_stats == NULL) {\n        ScopedMutexLock lock(&s->lock);\n        p_stats = find_pipeline_stats(pipeline_name);\n    }\n\n    halide_assert(user_context, p_stats != NULL);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) >= 0);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) < p_stats->num_funcs);\n\n    halide_profiler_func_stats *f_stats = &p_stats->funcs[func_id - p_stats->first_func_id];\n\n    \/\/ Update per-pipeline memory stats\n    \/*p_stats->num_allocs += 1;\n    p_stats->memory_total += incr;\n    p_stats->memory_current += incr;\n    if (p_stats->memory_current > p_stats->memory_peak) {\n        p_stats->memory_peak = p_stats->memory_current;\n    }\n\n    \/\/ Update per-func memory stats\n    f_stats->num_allocs += 1;\n    f_stats->memory_total += incr;\n    f_stats->memory_current += incr;\n    if (f_stats->memory_current > f_stats->memory_peak) {\n        f_stats->memory_peak = f_stats->memory_current;\n    }*\/\n\n    \/\/ Update per-pipeline memory stats\n    __sync_add_and_fetch(&p_stats->num_allocs, 1);\n    __sync_add_and_fetch(&p_stats->memory_total, incr);\n    int p_mem_current = __sync_add_and_fetch(&p_stats->memory_current, incr);\n    if (p_mem_current > p_stats->memory_peak) {\n        p_stats->memory_peak = p_mem_current;\n    }\n\n    \/\/ Update per-func memory stats\n    __sync_add_and_fetch(&f_stats->num_allocs, incr);\n    __sync_add_and_fetch(&f_stats->memory_total, incr);\n    int f_mem_current = __sync_add_and_fetch(&f_stats->memory_current, incr);\n    if (f_mem_current > f_stats->memory_peak) {\n        f_stats->memory_peak = f_mem_current;\n    }\n}\n\nWEAK void halide_profiler_memory_free(void *user_context,\n                                      const char *pipeline_name,\n                                      int token,\n                                      int func_id,\n                                      int decr) {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    func_id += token;\n\n    halide_profiler_pipeline_stats *p_stats = find_pipeline_stats(pipeline_name);\n    if (p_stats == NULL) {\n        ScopedMutexLock lock(&s->lock);\n        p_stats = find_pipeline_stats(pipeline_name);\n    }\n\n    if (p_stats == NULL) {\n        ScopedMutexLock lock(&s->lock);\n        for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n             p = (halide_profiler_pipeline_stats *)(p->next)) {\n            \/\/ The same pipeline will deliver the same global constant\n            \/\/ string, so they can be compared by pointer.\n            if (p->name == pipeline_name) {\n                p_stats = p;\n                break;\n            }\n        }\n    }\n    halide_assert(user_context, p_stats != NULL);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) >= 0);\n    halide_assert(user_context, (func_id - p_stats->first_func_id) < p_stats->num_funcs);\n\n    halide_profiler_func_stats *f_stats = &p_stats->funcs[func_id - p_stats->first_func_id];\n\n    \/*\/\/ Update per-pipeline memory stats\n    p_stats->memory_current -= decr;\n\n    \/\/ Update per-func memory stats\n    f_stats->memory_current -= decr;*\/\n\n    \/\/ Update per-pipeline memory stats\n    __sync_sub_and_fetch(&p_stats->memory_current, decr);\n\n    \/\/ Update per-func memory stats\n    __sync_sub_and_fetch(&f_stats->memory_current, decr);\n}\n\nWEAK void halide_profiler_report_unlocked(void *user_context, halide_profiler_state *s) {\n\n    char line_buf[400];\n    Printer sstr(user_context, line_buf);\n\n    for (halide_profiler_pipeline_stats *p = s->pipelines; p;\n         p = (halide_profiler_pipeline_stats *)(p->next)) {\n        float t = p->time \/ 1000000.0f;\n        if (!p->runs) continue;\n        sstr.clear();\n        int alloc_avg = 0;\n        if (p->num_allocs != 0) {\n            alloc_avg = p->memory_total\/p->num_allocs;\n        }\n        sstr << p->name\n             << \"  total time: \" << t << \" ms\"\n             << \"  samples: \" << p->samples\n             << \"  runs: \" << p->runs\n             << \"  time\/run: \" << t \/ p->runs << \" ms\"\n             << \"  num_allocs: \" << p->num_allocs\n             << \"  mem_peak: \" << p->memory_peak << \" bytes\"\n             << \"  mem_total: \" << p->memory_total << \" bytes\"\n             << \"  alloc_avg: \" << alloc_avg << \" bytes\\n\";\n        halide_print(user_context, sstr.str());\n        if (p->time || p->memory_total) {\n            for (int i = 0; i < p->num_funcs; i++) {\n                sstr.clear();\n                halide_profiler_func_stats *fs = p->funcs + i;\n\n                \/\/ The first func is always a catch-all overhead\n                \/\/ slot. Only report overhead time if it's non-zero\n                if (i == 0 && fs->time == 0) continue;\n\n                sstr << \"  \" << fs->name << \": \";\n                while (sstr.size() < 25) sstr << \" \";\n\n                float ft = fs->time \/ (p->runs * 1000000.0f);\n                sstr << ft << \"ms\";\n                while (sstr.size() < 40) sstr << \" \";\n\n                int percent = 0;\n                if (p->time != 0) {\n                    percent = fs->time \/ (p->time \/ 100);\n                }\n                sstr << \"(\" << percent << \"%)\";\n                while (sstr.size() < 55) sstr << \" \";\n\n                int alloc_avg = 0;\n                if (fs->num_allocs != 0) {\n                    alloc_avg = fs->memory_total\/fs->num_allocs;\n                }\n\n                sstr << \"(\" << fs->memory_current << \", \" << fs->memory_peak\n                     << \", \" << fs->memory_total << \", \" << fs->num_allocs\n                     << \", \" << alloc_avg << \") bytes\\n\";\n\n                halide_print(user_context, sstr.str());\n            }\n        }\n    }\n}\n\nWEAK void halide_profiler_report(void *user_context) {\n    halide_profiler_state *s = halide_profiler_get_state();\n    ScopedMutexLock lock(&s->lock);\n    halide_profiler_report_unlocked(user_context, s);\n}\n\n\nWEAK void halide_profiler_reset() {\n    halide_profiler_state *s = halide_profiler_get_state();\n\n    ScopedMutexLock lock(&s->lock);\n\n    while (s->pipelines) {\n        halide_profiler_pipeline_stats *p = s->pipelines;\n        s->pipelines = (halide_profiler_pipeline_stats *)(p->next);\n        free(p->funcs);\n        free(p);\n    }\n    s->first_free_id = 0;\n}\n\nnamespace {\n__attribute__((destructor))\nWEAK void halide_profiler_shutdown() {\n    halide_profiler_state *s = halide_profiler_get_state();\n    if (!s->started) return;\n    s->current_func = halide_profiler_please_stop;\n    do {\n        \/\/ Memory barrier.\n        __sync_synchronize(&s->started,\n                           &s->current_func);\n    } while (s->started);\n    s->current_func = halide_profiler_outside_of_halide;\n\n    \/\/ Print results. No need to lock anything because we just shut\n    \/\/ down the thread.\n    halide_profiler_report_unlocked(NULL, s);\n\n    \/\/ Leak the memory. Not all implementations of ScopedMutexLock may\n    \/\/ be safe to use at static destruction time (windows).\n    \/\/ halide_profiler_reset();\n}\n}\n\nWEAK void halide_profiler_pipeline_end(void *user_context, void *state) {\n    ((halide_profiler_state *)state)->current_func = halide_profiler_outside_of_halide;\n}\n\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \"cairo_cairo.hxx\"\n#include \"cairo_helper.hxx\"\n\nnamespace cairo\n{\n\n#include \n#include \n\n    Surface::Surface( const void* pSysData, int x, int y, int width, int height )\n        : mnRefCount( 1 ),\n          mpSysData( pSysData ),\n          mbFreePixmap( false )\n    {\n        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, x, y, width, height );\n        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );\n        mhDrawable = cairoHelperGetWindow( pSysData );\n    }\n\n    Surface::Surface( const void* pSysData, void *pBmpData, int width, int height )\n        : mnRefCount( 1 ),\n          mpSysData( pSysData ),\n          mbFreePixmap( false )\n    {\n        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, pBmpData, width, height );\n        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );\n        mhDrawable = cairoHelperGetWindow( pSysData );\n    }\n\n\n    Surface::~Surface()\n    {\n        if( mpSurface )\n        {\n            cairo_surface_destroy( mpSurface );\n            mpSurface = NULL;\n        }\n        if( mbFreePixmap && mhDrawable )\n            XFreePixmap( (Display*) mpDisplay, mhDrawable );\n    }\n\n    Surface* Surface::getSimilar( Content aContent, int width, int height )\n    {\n        Pixmap hPixmap;\n\n        if( mpSysData && mpDisplay && mhDrawable ) {\n            XRenderPictFormat *pFormat;\n            int nFormat;\n\n            switch (aContent) {\n            case CAIRO_CONTENT_ALPHA:\n                nFormat = PictStandardA8;\n                break;\n            case CAIRO_CONTENT_COLOR:\n                nFormat = PictStandardRGB24;\n                break;\n            case CAIRO_CONTENT_COLOR_ALPHA:\n            default:\n                nFormat = PictStandardARGB32;\n                break;\n            }\n\n            pFormat = XRenderFindStandardFormat( (Display*) mpDisplay, nFormat );\n            hPixmap = XCreatePixmap( (Display*) mpDisplay, cairoHelperGetWindow( mpSysData ),\n                                     width > 0 ? width : 1, height > 0 ? height : 1,\n                                     pFormat->depth );\n\n            return new Surface( mpSysData, mpDisplay, (long) hPixmap, pFormat,\n                                cairo_xlib_surface_create_with_xrender_format( (Display*) mpDisplay, hPixmap,\n                                                                               DefaultScreenOfDisplay( (Display *) mpDisplay ),\n                                                                               pFormat, width, height ) );\n        } else\n            return new Surface( mpSysData, mpDisplay, 0, NULL, cairo_surface_create_similar( mpSurface, aContent, width, height ) );\n    }\n\n    void\n    Surface::Resize( int width, int height )\n    {\n        cairo_xlib_surface_set_size( mpSurface, width, height );\n    }\n\n    int\n    Surface::getDepth()\n    {\n        if( mpRenderFormat )\n            return ( ( XRenderPictFormat * ) mpRenderFormat )->depth;\n\n        return -1;\n    }\n}\nINTEGRATION: CWS pchfix02 (1.3.28); FILE MERGED 2006\/09\/01 17:17:59 kaib 1.3.28.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: cairo_cairo.cxx,v $\n *\n *  $Revision: 1.4 $\n *\n *  last change: $Author: obo $ $Date: 2006-09-17 03:17:37 $\n *\n *  The Contents of this file are made available subject to\n *  the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n *    GNU Lesser General Public License Version 2.1\n *    =============================================\n *    Copyright 2005 by Sun Microsystems, Inc.\n *    901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *    This library is free software; you can redistribute it and\/or\n *    modify it under the terms of the GNU Lesser General Public\n *    License version 2.1, as published by the Free Software Foundation.\n *\n *    This library is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *    Lesser General Public License for more details.\n *\n *    You should have received a copy of the GNU Lesser General Public\n *    License along with this library; if not, write to the Free Software\n *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *    MA  02111-1307  USA\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_canvas.hxx\"\n#include \n#include \n#include \"cairo_cairo.hxx\"\n#include \"cairo_helper.hxx\"\n\nnamespace cairo\n{\n\n#include \n#include \n\n    Surface::Surface( const void* pSysData, int x, int y, int width, int height )\n        : mnRefCount( 1 ),\n          mpSysData( pSysData ),\n          mbFreePixmap( false )\n    {\n        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, x, y, width, height );\n        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );\n        mhDrawable = cairoHelperGetWindow( pSysData );\n    }\n\n    Surface::Surface( const void* pSysData, void *pBmpData, int width, int height )\n        : mnRefCount( 1 ),\n          mpSysData( pSysData ),\n          mbFreePixmap( false )\n    {\n        mpSurface = (cairo_surface_t*) cairoHelperGetSurface( pSysData, pBmpData, width, height );\n        mpDisplay = (Display*) cairoHelperGetDisplay( pSysData );\n        mhDrawable = cairoHelperGetWindow( pSysData );\n    }\n\n\n    Surface::~Surface()\n    {\n        if( mpSurface )\n        {\n            cairo_surface_destroy( mpSurface );\n            mpSurface = NULL;\n        }\n        if( mbFreePixmap && mhDrawable )\n            XFreePixmap( (Display*) mpDisplay, mhDrawable );\n    }\n\n    Surface* Surface::getSimilar( Content aContent, int width, int height )\n    {\n        Pixmap hPixmap;\n\n        if( mpSysData && mpDisplay && mhDrawable ) {\n            XRenderPictFormat *pFormat;\n            int nFormat;\n\n            switch (aContent) {\n            case CAIRO_CONTENT_ALPHA:\n                nFormat = PictStandardA8;\n                break;\n            case CAIRO_CONTENT_COLOR:\n                nFormat = PictStandardRGB24;\n                break;\n            case CAIRO_CONTENT_COLOR_ALPHA:\n            default:\n                nFormat = PictStandardARGB32;\n                break;\n            }\n\n            pFormat = XRenderFindStandardFormat( (Display*) mpDisplay, nFormat );\n            hPixmap = XCreatePixmap( (Display*) mpDisplay, cairoHelperGetWindow( mpSysData ),\n                                     width > 0 ? width : 1, height > 0 ? height : 1,\n                                     pFormat->depth );\n\n            return new Surface( mpSysData, mpDisplay, (long) hPixmap, pFormat,\n                                cairo_xlib_surface_create_with_xrender_format( (Display*) mpDisplay, hPixmap,\n                                                                               DefaultScreenOfDisplay( (Display *) mpDisplay ),\n                                                                               pFormat, width, height ) );\n        } else\n            return new Surface( mpSysData, mpDisplay, 0, NULL, cairo_surface_create_similar( mpSurface, aContent, width, height ) );\n    }\n\n    void\n    Surface::Resize( int width, int height )\n    {\n        cairo_xlib_surface_set_size( mpSurface, width, height );\n    }\n\n    int\n    Surface::getDepth()\n    {\n        if( mpRenderFormat )\n            return ( ( XRenderPictFormat * ) mpRenderFormat )->depth;\n\n        return -1;\n    }\n}\n<|endoftext|>"}
{"text":"\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\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 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"msvcinfo.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \n#endif\n\nusing namespace qbs;\nusing namespace qbs::Internal;\n\nstatic QString mkStr(const char *s) { return QString::fromLocal8Bit(s); }\nstatic QString mkStr(const QByteArray &ba) { return mkStr(ba.constData()); }\n\nclass TemporaryEnvChanger\n{\npublic:\n    TemporaryEnvChanger(const QProcessEnvironment &envChanges)\n    {\n        QProcessEnvironment currentEnv = QProcessEnvironment::systemEnvironment();\n        foreach (const QString &key, envChanges.keys()) {\n            m_changesToRestore.insert(key, currentEnv.value(key));\n            qputenv(qPrintable(key), qPrintable(envChanges.value(key)));\n        }\n    }\n\n    ~TemporaryEnvChanger()\n    {\n        foreach (const QString &key, m_changesToRestore.keys())\n            qputenv(qPrintable(key), qPrintable(m_changesToRestore.value(key)));\n    }\n\nprivate:\n    QProcessEnvironment m_changesToRestore;\n};\n\nstatic QByteArray runProcess(const QString &exeFilePath, const QStringList &args,\n                             const QProcessEnvironment &env = QProcessEnvironment(),\n                             bool allowFailure = false)\n{\n    TemporaryEnvChanger envChanger(env);\n    QProcess process;\n    process.start(exeFilePath, args);\n    if (!process.waitForStarted() || !process.waitForFinished()\n            || process.exitStatus() != QProcess::NormalExit) {\n        throw ErrorInfo(mkStr(\"Could not run %1 (%2)\").arg(exeFilePath, process.errorString()));\n    }\n    if (process.exitCode() != 0 && !allowFailure) {\n        ErrorInfo e(mkStr(\"Process '%1' failed with exit code %2.\")\n                    .arg(exeFilePath).arg(process.exitCode()));\n        const QByteArray stdErr = process.readAllStandardError();\n        if (!stdErr.isEmpty())\n            e.append(mkStr(\"stderr was: %1\").arg(mkStr(stdErr)));\n        const QByteArray stdOut = process.readAllStandardOutput();\n        if (!stdOut.isEmpty())\n            e.append(mkStr(\"stdout was: %1\").arg(mkStr(stdOut)));\n        throw e;\n    }\n    return process.readAllStandardOutput().trimmed();\n}\n\nclass DummyFile {\npublic:\n    DummyFile(const QString &fp) : filePath(fp) { }\n    ~DummyFile() { QFile::remove(filePath); }\n    const QString filePath;\n};\n\nstatic QStringList parseCommandLine(const QString &commandLine)\n{\n    QStringList list;\n#ifdef Q_OS_WIN\n    wchar_t *buf = new wchar_t[commandLine.size() + 1];\n    buf[commandLine.toWCharArray(buf)] = 0;\n    int argCount = 0;\n    LPWSTR *args = CommandLineToArgvW(buf, &argCount);\n    if (!args)\n        throw ErrorInfo(mkStr(\"Could not parse command line arguments: \") + commandLine);\n    for (int i = 0; i < argCount; ++i)\n        list.append(QString::fromWCharArray(args[i]));\n    delete[] buf;\n#else\n    Q_UNUSED(commandLine);\n#endif\n    return list;\n}\n\nstatic QVariantMap getMsvcDefines(const QString &hostCompilerFilePath,\n                                  const QString &compilerFilePath,\n                                  const QProcessEnvironment &compilerEnv)\n{\n    const QScopedPointer dummyFile(\n                new QTemporaryFile(QDir::tempPath() + QLatin1String(\"\/qbs_dummy\")));\n    if (!dummyFile->open()) {\n        throw ErrorInfo(mkStr(\"Could not create temporary file (%1)\")\n                        .arg(dummyFile->errorString()));\n    }\n    dummyFile->write(\"#include \\n\");\n    dummyFile->write(\"#include \\n\");\n    dummyFile->write(\"int main(void) { char *p = getenv(\\\"MSC_CMD_FLAGS\\\");\"\n                     \"if (p) printf(\\\"%s\\\", p); return EXIT_FAILURE; }\\n\");\n    dummyFile->close();\n\n    \/\/ We cannot use the temporary file itself, as Qt has a lock on it\n    \/\/ even after it was closed, causing a \"Permission denied\" message from MSVC.\n    const QString actualDummyFilePath = dummyFile->fileName() + QLatin1String(\".1\");\n    const QString nativeDummyFilePath = QDir::toNativeSeparators(actualDummyFilePath);\n    if (!QFile::copy(dummyFile->fileName(), actualDummyFilePath)) {\n        throw ErrorInfo(mkStr(\"Could not create source '%1' file for compiler.\")\n                        .arg(nativeDummyFilePath));\n    }\n    DummyFile actualDummyFile(actualDummyFilePath);\n    const QString qbsClFrontend = nativeDummyFilePath + QStringLiteral(\".exe\");\n    const QString qbsClFrontendObj = nativeDummyFilePath + QStringLiteral(\".obj\");\n    DummyFile actualQbsClFrontend(qbsClFrontend);\n    DummyFile actualQbsClFrontendObj(qbsClFrontendObj);\n\n    \/\/ The host compiler is the x86 compiler, which will execute on any edition of Windows\n    \/\/ for which host compilers have been released so far (x86, x86_64, ia64)\n    MSVC msvc2(hostCompilerFilePath);\n    VsEnvironmentDetector envdetector;\n    if (!envdetector.start(&msvc2))\n        throw ErrorInfo(QStringLiteral(\"Detecting the MSVC build environment failed: \")\n                        + envdetector.errorString());\n    runProcess(hostCompilerFilePath, QStringList()\n               << QStringLiteral(\"\/nologo\")\n               << QStringLiteral(\"\/TC\")\n               << (QStringLiteral(\"\/Fo\") + qbsClFrontendObj)\n               << nativeDummyFilePath\n               << QStringLiteral(\"\/link\")\n               << (QStringLiteral(\"\/out:\") + qbsClFrontend), msvc2.environment);\n\n    QStringList out = QString::fromLocal8Bit(runProcess(compilerFilePath, QStringList()\n               << QStringLiteral(\"\/nologo\")\n               << QStringLiteral(\"\/B1\")\n               << qbsClFrontend\n               << QStringLiteral(\"\/c\")\n               << QStringLiteral(\"\/TC\")\n               << QStringLiteral(\"NUL\"), compilerEnv, true)).split(QStringLiteral(\"\\r\\n\"));\n\n    if (out.size() != 2)\n        throw ErrorInfo(QStringLiteral(\"Unexpected compiler frontend output: \")\n                        + out.join(QLatin1Char('\\n')));\n\n    if (out.first() == QStringLiteral(\"NUL\"))\n        out.removeFirst();\n\n    QVariantMap map;\n    const QStringList args = parseCommandLine(out.first());\n    for (const QString &arg : args) {\n        if (!arg.startsWith(QStringLiteral(\"-D\")))\n            continue;\n        int idx = arg.indexOf(QLatin1Char('='), 2);\n        if (idx > 2)\n            map.insert(arg.mid(2, idx - 2), arg.mid(idx + 1));\n        else\n            map.insert(arg.mid(2), QVariant());\n    }\n\n    return map;\n}\n\nvoid MSVC::init()\n{\n    determineCompilerVersion();\n}\n\nQString MSVC::binPathForArchitecture(const QString &arch) const\n{\n    QString archSubDir;\n    if (arch != QStringLiteral(\"x86\"))\n        archSubDir = arch;\n    return QDir::cleanPath(vcInstallPath + QLatin1Char('\/') + pathPrefix + QLatin1Char('\/')\n                           + archSubDir);\n}\n\nQString MSVC::clPathForArchitecture(const QString &arch) const\n{\n    return binPathForArchitecture(arch) + QLatin1String(\"\/cl.exe\");\n}\n\nQVariantMap MSVC::compilerDefines(const QString &compilerFilePath) const\n{\n    return getMsvcDefines(clPathForArchitecture(QStringLiteral(\"x86\")), compilerFilePath,\n                          environment);\n}\n\nvoid MSVC::determineCompilerVersion()\n{\n    QString cppFilePath;\n    {\n        QTemporaryFile cppFile(QDir::tempPath() + QLatin1String(\"\/qbsXXXXXX.cpp\"));\n        cppFile.setAutoRemove(false);\n        if (!cppFile.open()) {\n            throw ErrorInfo(mkStr(\"Could not create temporary file (%1)\")\n                            .arg(cppFile.errorString()));\n        }\n        cppFilePath = cppFile.fileName();\n        cppFile.write(\"_MSC_FULL_VER\");\n        cppFile.close();\n    }\n    DummyFile fileDeleter(cppFilePath);\n\n    const QByteArray origPath = qgetenv(\"PATH\");\n    qputenv(\"PATH\", environment.value(QStringLiteral(\"PATH\")).toLatin1() + ';' + origPath);\n    QByteArray versionStr = runProcess(\n                binPath + QStringLiteral(\"\/cl.exe\"),\n                QStringList() << QStringLiteral(\"\/nologo\") << QStringLiteral(\"\/EP\")\n                << QDir::toNativeSeparators(cppFilePath));\n    qputenv(\"PATH\", origPath);\n    compilerVersion = Version(versionStr.mid(0, 2).toInt(), versionStr.mid(2, 2).toInt(),\n                              versionStr.mid(4).toInt());\n}\nSimplify determination of MSVC compiler defines\/****************************************************************************\n**\n** Copyright (C) 2016 The Qt Company Ltd.\n** Contact: https:\/\/www.qt.io\/licensing\/\n**\n** This file is part of Qbs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\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 3 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL3 included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 3 requirements\n** will be met: https:\/\/www.gnu.org\/licenses\/lgpl-3.0.html.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 2.0 or (at your option) the GNU General\n** Public license version 3 or any later version approved by the KDE Free\n** Qt Foundation. The licenses are as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3\n** included in the packaging of this file. Please review the following\n** information to ensure the GNU General Public License requirements will\n** be met: https:\/\/www.gnu.org\/licenses\/gpl-2.0.html and\n** https:\/\/www.gnu.org\/licenses\/gpl-3.0.html.\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"msvcinfo.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_WIN\n#include \n#endif\n\n#include \n\nusing namespace qbs;\nusing namespace qbs::Internal;\n\nstatic QString mkStr(const char *s) { return QString::fromLocal8Bit(s); }\nstatic QString mkStr(const QByteArray &ba) { return mkStr(ba.constData()); }\n\nclass TemporaryEnvChanger\n{\npublic:\n    TemporaryEnvChanger(const QProcessEnvironment &envChanges)\n    {\n        QProcessEnvironment currentEnv = QProcessEnvironment::systemEnvironment();\n        foreach (const QString &key, envChanges.keys()) {\n            m_changesToRestore.insert(key, currentEnv.value(key));\n            qputenv(qPrintable(key), qPrintable(envChanges.value(key)));\n        }\n    }\n\n    ~TemporaryEnvChanger()\n    {\n        foreach (const QString &key, m_changesToRestore.keys())\n            qputenv(qPrintable(key), qPrintable(m_changesToRestore.value(key)));\n    }\n\nprivate:\n    QProcessEnvironment m_changesToRestore;\n};\n\nstatic QByteArray runProcess(const QString &exeFilePath, const QStringList &args,\n                             const QProcessEnvironment &env = QProcessEnvironment(),\n                             bool allowFailure = false,\n                             const QByteArray &pipeData = QByteArray())\n{\n    TemporaryEnvChanger envChanger(env);\n    QProcess process;\n    process.start(exeFilePath, args);\n    if (!process.waitForStarted())\n        throw ErrorInfo(mkStr(\"Could not start %1 (%2)\").arg(exeFilePath, process.errorString()));\n    if (!pipeData.isEmpty()) {\n        process.write(pipeData);\n        process.closeWriteChannel();\n    }\n    if (!process.waitForFinished() || process.exitStatus() != QProcess::NormalExit)\n        throw ErrorInfo(mkStr(\"Could not run %1 (%2)\").arg(exeFilePath, process.errorString()));\n    if (process.exitCode() != 0 && !allowFailure) {\n        ErrorInfo e(mkStr(\"Process '%1' failed with exit code %2.\")\n                    .arg(exeFilePath).arg(process.exitCode()));\n        const QByteArray stdErr = process.readAllStandardError();\n        if (!stdErr.isEmpty())\n            e.append(mkStr(\"stderr was: %1\").arg(mkStr(stdErr)));\n        const QByteArray stdOut = process.readAllStandardOutput();\n        if (!stdOut.isEmpty())\n            e.append(mkStr(\"stdout was: %1\").arg(mkStr(stdOut)));\n        throw e;\n    }\n    return process.readAllStandardOutput().trimmed();\n}\n\nclass DummyFile {\npublic:\n    DummyFile(const QString &fp) : filePath(fp) { }\n    ~DummyFile() { QFile::remove(filePath); }\n    const QString filePath;\n};\n\nstatic QStringList parseCommandLine(const QString &commandLine)\n{\n    QStringList list;\n#ifdef Q_OS_WIN\n    wchar_t *buf = new wchar_t[commandLine.size() + 1];\n    buf[commandLine.toWCharArray(buf)] = 0;\n    int argCount = 0;\n    LPWSTR *args = CommandLineToArgvW(buf, &argCount);\n    if (!args)\n        throw ErrorInfo(mkStr(\"Could not parse command line arguments: \") + commandLine);\n    for (int i = 0; i < argCount; ++i)\n        list.append(QString::fromWCharArray(args[i]));\n    delete[] buf;\n#else\n    Q_UNUSED(commandLine);\n#endif\n    return list;\n}\n\nstatic QVariantMap getMsvcDefines(const QString &compilerFilePath,\n                                  const QProcessEnvironment &compilerEnv)\n{\n#ifdef Q_OS_WIN\n    const QByteArray commands(\"set MSC_CMD_FLAGS\\n\");\n    QStringList out = QString::fromLocal8Bit(runProcess(compilerFilePath, QStringList()\n               << QStringLiteral(\"\/nologo\")\n               << QStringLiteral(\"\/B1\")\n               << QString::fromWCharArray(_wgetenv(L\"COMSPEC\"))\n               << QStringLiteral(\"\/c\")\n               << QStringLiteral(\"\/TC\")\n               << QStringLiteral(\"NUL\"),\n               compilerEnv, true, commands)).split(QLatin1Char('\\n'));\n\n    auto findResult = std::find_if(out.cbegin(), out.cend(), [] (const QString &line) {\n            return line.startsWith(QLatin1String(\"MSC_CMD_FLAGS=\"));\n        });\n    if (findResult == out.cend()) {\n        throw ErrorInfo(QStringLiteral(\"Unexpected compiler frontend output: \")\n                        + out.join(QLatin1Char('\\n')));\n    }\n\n    QVariantMap map;\n    const QStringList args = parseCommandLine(findResult->trimmed());\n    for (const QString &arg : args) {\n        if (!arg.startsWith(QStringLiteral(\"-D\")))\n            continue;\n        int idx = arg.indexOf(QLatin1Char('='), 2);\n        if (idx > 2)\n            map.insert(arg.mid(2, idx - 2), arg.mid(idx + 1));\n        else\n            map.insert(arg.mid(2), QVariant());\n    }\n\n    return map;\n#else\n    Q_UNUSED(compilerFilePath);\n    Q_UNUSED(compilerEnv);\n    return QVariantMap();\n#endif\n}\n\nvoid MSVC::init()\n{\n    determineCompilerVersion();\n}\n\nQString MSVC::binPathForArchitecture(const QString &arch) const\n{\n    QString archSubDir;\n    if (arch != QStringLiteral(\"x86\"))\n        archSubDir = arch;\n    return QDir::cleanPath(vcInstallPath + QLatin1Char('\/') + pathPrefix + QLatin1Char('\/')\n                           + archSubDir);\n}\n\nQString MSVC::clPathForArchitecture(const QString &arch) const\n{\n    return binPathForArchitecture(arch) + QLatin1String(\"\/cl.exe\");\n}\n\nQVariantMap MSVC::compilerDefines(const QString &compilerFilePath) const\n{\n    return getMsvcDefines(compilerFilePath, environment);\n}\n\nvoid MSVC::determineCompilerVersion()\n{\n    QString cppFilePath;\n    {\n        QTemporaryFile cppFile(QDir::tempPath() + QLatin1String(\"\/qbsXXXXXX.cpp\"));\n        cppFile.setAutoRemove(false);\n        if (!cppFile.open()) {\n            throw ErrorInfo(mkStr(\"Could not create temporary file (%1)\")\n                            .arg(cppFile.errorString()));\n        }\n        cppFilePath = cppFile.fileName();\n        cppFile.write(\"_MSC_FULL_VER\");\n        cppFile.close();\n    }\n    DummyFile fileDeleter(cppFilePath);\n\n    const QByteArray origPath = qgetenv(\"PATH\");\n    qputenv(\"PATH\", environment.value(QStringLiteral(\"PATH\")).toLatin1() + ';' + origPath);\n    QByteArray versionStr = runProcess(\n                binPath + QStringLiteral(\"\/cl.exe\"),\n                QStringList() << QStringLiteral(\"\/nologo\") << QStringLiteral(\"\/EP\")\n                << QDir::toNativeSeparators(cppFilePath));\n    qputenv(\"PATH\", origPath);\n    compilerVersion = Version(versionStr.mid(0, 2).toInt(), versionStr.mid(2, 2).toInt(),\n                              versionStr.mid(4).toInt());\n}\n<|endoftext|>"}
{"text":"\/\/===- ScriptParser.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the base parser class for linker script and dynamic\n\/\/ list.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ScriptParser.h\"\n#include \"Error.h\"\n#include \"llvm\/ADT\/Twine.h\"\n\nusing namespace llvm;\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Returns the line that the token Tok is in.\nstatic StringRef getLine(StringRef Data, StringRef Tok) {\n  size_t Pos = Tok.data() - Data.data();\n  size_t Begin = Data.rfind('\\n', Pos);\n  size_t End = Data.find('\\n', Pos);\n  Begin = (Begin == StringRef::npos) ? 0 : Begin + 1;\n  if (End == StringRef::npos)\n    End = Data.size();\n  \/\/ rtrim for DOS-style newlines.\n  return Data.substr(Begin, End - Begin).rtrim();\n}\n\nstatic std::pair getPos(StringRef Data, StringRef Tok) {\n  StringRef Line = getLine(Data, Tok);\n  size_t LineNo =\n      StringRef(Data.data(), Tok.data() - Data.data()).count('\\n') + 1;\n  return {LineNo, Tok.data() - Line.data()};\n}\n\nScriptParserBase::ScriptParserBase(MemoryBufferRef MB) { tokenize(MB); }\n\n\/\/ We don't want to record cascading errors. Keep only the first one.\nvoid ScriptParserBase::setError(const Twine &Msg) {\n  if (Error)\n    return;\n\n  std::pair ErrPos;\n  MemoryBufferRef MB = currentBuffer();\n  std::string Location = MB.getBufferIdentifier();\n  if (Pos) {\n    ErrPos = getPos(MB.getBuffer(), Tokens[Pos - 1]);\n    Location += \":\";\n    Location += std::to_string(ErrPos.first);\n  }\n  error(Location + \": \" + Msg);\n  if (Pos) {\n    error(Location + \": \" + getLine(MB.getBuffer(), Tokens[Pos - 1]));\n    error(Location + \": \" + std::string(ErrPos.second, ' ') + \"^\");\n  }\n\n  Error = true;\n}\n\n\/\/ Split S into linker script tokens.\nvoid ScriptParserBase::tokenize(MemoryBufferRef MB) {\n  std::vector Ret;\n  MBs.push_back(MB);\n  StringRef S = MB.getBuffer();\n  StringRef Begin = S;\n  for (;;) {\n    S = skipSpace(S);\n    if (S.empty())\n      break;\n\n    \/\/ Quoted token. Note that double-quote characters are parts of a token\n    \/\/ because, in a glob match context, only unquoted tokens are interpreted\n    \/\/ as glob patterns. Double-quoted tokens are literal patterns in that\n    \/\/ context.\n    if (S.startswith(\"\\\"\")) {\n      size_t E = S.find(\"\\\"\", 1);\n      if (E == StringRef::npos) {\n        auto ErrPos = getPos(Begin, S);\n        error(MB.getBufferIdentifier() + \":\" + Twine(ErrPos.first) +\n              \": unclosed quote\");\n        return;\n      }\n      Ret.push_back(S.take_front(E + 1));\n      S = S.substr(E + 1);\n      continue;\n    }\n\n    \/\/ Unquoted token. This is more relaxed than tokens in C-like language,\n    \/\/ so that you can write \"file-name.cpp\" as one bare token, for example.\n    size_t Pos = S.find_first_not_of(\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n        \"0123456789_.$\/\\\\~=+[]*?-:!<>^\");\n\n    \/\/ A character that cannot start a word (which is usually a\n    \/\/ punctuation) forms a single character token.\n    if (Pos == 0)\n      Pos = 1;\n    Ret.push_back(S.substr(0, Pos));\n    S = S.substr(Pos);\n  }\n  Tokens.insert(Tokens.begin() + Pos, Ret.begin(), Ret.end());\n}\n\n\/\/ Skip leading whitespace characters or comments.\nStringRef ScriptParserBase::skipSpace(StringRef S) {\n  for (;;) {\n    if (S.startswith(\"\/*\")) {\n      size_t E = S.find(\"*\/\", 2);\n      if (E == StringRef::npos) {\n        error(\"unclosed comment in a linker script\");\n        return \"\";\n      }\n      S = S.substr(E + 2);\n      continue;\n    }\n    if (S.startswith(\"#\")) {\n      size_t E = S.find('\\n', 1);\n      if (E == StringRef::npos)\n        E = S.size() - 1;\n      S = S.substr(E + 1);\n      continue;\n    }\n    size_t Size = S.size();\n    S = S.ltrim();\n    if (S.size() == Size)\n      return S;\n  }\n}\n\n\/\/ An erroneous token is handled as if it were the last token before EOF.\nbool ScriptParserBase::atEOF() { return Error || Tokens.size() == Pos; }\n\nStringRef ScriptParserBase::next() {\n  if (Error)\n    return \"\";\n  if (atEOF()) {\n    setError(\"unexpected EOF\");\n    return \"\";\n  }\n  return Tokens[Pos++];\n}\n\nStringRef ScriptParserBase::peek() {\n  StringRef Tok = next();\n  if (Error)\n    return \"\";\n  --Pos;\n  return Tok;\n}\n\nbool ScriptParserBase::consume(StringRef Tok) {\n  if (peek() == Tok) {\n    skip();\n    return true;\n  }\n  return false;\n}\n\nvoid ScriptParserBase::skip() { (void)next(); }\n\nvoid ScriptParserBase::expect(StringRef Expect) {\n  if (Error)\n    return;\n  StringRef Tok = next();\n  if (Tok != Expect)\n    setError(Expect + \" expected, but got \" + Tok);\n}\n\nstd::string ScriptParserBase::currentLocation() {\n  MemoryBufferRef MB = currentBuffer();\n  return (MB.getBufferIdentifier() + \":\" +\n          Twine(getPos(MB.getBuffer(), Tokens[Pos - 1]).first))\n      .str();\n}\n\n\/\/ Returns true if string 'Bigger' contains string 'Shorter'.\nstatic bool containsString(StringRef Bigger, StringRef Shorter) {\n  const char *BiggerEnd = Bigger.data() + Bigger.size();\n  const char *ShorterEnd = Shorter.data() + Shorter.size();\n\n  return Bigger.data() <= Shorter.data() && BiggerEnd >= ShorterEnd;\n}\n\nMemoryBufferRef ScriptParserBase::currentBuffer() {\n  \/\/ Find input buffer containing the current token.\n  assert(!MBs.empty());\n  if (Pos)\n    for (MemoryBufferRef MB : MBs)\n      if (containsString(MB.getBuffer(), Tokens[Pos - 1]))\n        return MB;\n\n  return MBs.front();\n}\nSplit getPos into getLineNumber and getColumnNumber.\/\/===- ScriptParser.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/                             The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the base parser class for linker script and dynamic\n\/\/ list.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ScriptParser.h\"\n#include \"Error.h\"\n#include \"llvm\/ADT\/Twine.h\"\n\nusing namespace llvm;\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ Returns a line containing a token.\nstatic StringRef getLine(StringRef S, StringRef Tok) {\n  size_t Pos = S.rfind('\\n', Tok.data() - S.data());\n  if (Pos != StringRef::npos)\n    S = S.substr(Pos + 1);\n  return S.substr(0, S.find_first_of(\"\\r\\n\"));\n}\n\n\/\/ Returns 1-based line number of a given token.\nstatic size_t getLineNumber(StringRef S, StringRef Tok) {\n  return S.substr(0, Tok.data() - S.data()).count('\\n') + 1;\n}\n\n\/\/ Returns 0-based column number of a given token.\nstatic size_t getColumnNumber(StringRef S, StringRef Tok) {\n  return Tok.data() - getLine(S, Tok).data();\n}\n\nScriptParserBase::ScriptParserBase(MemoryBufferRef MB) { tokenize(MB); }\n\n\/\/ We don't want to record cascading errors. Keep only the first one.\nvoid ScriptParserBase::setError(const Twine &Msg) {\n  if (Error)\n    return;\n  Error = true;\n\n  MemoryBufferRef MB = currentBuffer();\n  std::string Filename = MB.getBufferIdentifier();\n\n  if (!Pos) {\n    error(Filename + \": \" + Msg);\n    return;\n  }\n\n  StringRef Buf = MB.getBuffer();\n  StringRef Tok = Tokens[Pos - 1];\n  std::string S = (Filename + \":\" + Twine(getLineNumber(Buf, Tok))).str();\n\n  error(S + \": \" + Msg);\n  error(S + \": \" + getLine(Buf, Tok));\n  error(S + \": \" + std::string(getColumnNumber(Buf, Tok), ' ') + \"^\");\n}\n\n\/\/ Split S into linker script tokens.\nvoid ScriptParserBase::tokenize(MemoryBufferRef MB) {\n  std::vector Ret;\n  MBs.push_back(MB);\n  StringRef S = MB.getBuffer();\n  StringRef Begin = S;\n  for (;;) {\n    S = skipSpace(S);\n    if (S.empty())\n      break;\n\n    \/\/ Quoted token. Note that double-quote characters are parts of a token\n    \/\/ because, in a glob match context, only unquoted tokens are interpreted\n    \/\/ as glob patterns. Double-quoted tokens are literal patterns in that\n    \/\/ context.\n    if (S.startswith(\"\\\"\")) {\n      size_t E = S.find(\"\\\"\", 1);\n      if (E == StringRef::npos) {\n        error(MB.getBufferIdentifier() + \":\" + Twine(getLineNumber(Begin, S)) +\n              \": unclosed quote\");\n        return;\n      }\n      Ret.push_back(S.take_front(E + 1));\n      S = S.substr(E + 1);\n      continue;\n    }\n\n    \/\/ Unquoted token. This is more relaxed than tokens in C-like language,\n    \/\/ so that you can write \"file-name.cpp\" as one bare token, for example.\n    size_t Pos = S.find_first_not_of(\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n        \"0123456789_.$\/\\\\~=+[]*?-:!<>^\");\n\n    \/\/ A character that cannot start a word (which is usually a\n    \/\/ punctuation) forms a single character token.\n    if (Pos == 0)\n      Pos = 1;\n    Ret.push_back(S.substr(0, Pos));\n    S = S.substr(Pos);\n  }\n  Tokens.insert(Tokens.begin() + Pos, Ret.begin(), Ret.end());\n}\n\n\/\/ Skip leading whitespace characters or comments.\nStringRef ScriptParserBase::skipSpace(StringRef S) {\n  for (;;) {\n    if (S.startswith(\"\/*\")) {\n      size_t E = S.find(\"*\/\", 2);\n      if (E == StringRef::npos) {\n        error(\"unclosed comment in a linker script\");\n        return \"\";\n      }\n      S = S.substr(E + 2);\n      continue;\n    }\n    if (S.startswith(\"#\")) {\n      size_t E = S.find('\\n', 1);\n      if (E == StringRef::npos)\n        E = S.size() - 1;\n      S = S.substr(E + 1);\n      continue;\n    }\n    size_t Size = S.size();\n    S = S.ltrim();\n    if (S.size() == Size)\n      return S;\n  }\n}\n\n\/\/ An erroneous token is handled as if it were the last token before EOF.\nbool ScriptParserBase::atEOF() { return Error || Tokens.size() == Pos; }\n\nStringRef ScriptParserBase::next() {\n  if (Error)\n    return \"\";\n  if (atEOF()) {\n    setError(\"unexpected EOF\");\n    return \"\";\n  }\n  return Tokens[Pos++];\n}\n\nStringRef ScriptParserBase::peek() {\n  StringRef Tok = next();\n  if (Error)\n    return \"\";\n  --Pos;\n  return Tok;\n}\n\nbool ScriptParserBase::consume(StringRef Tok) {\n  if (peek() == Tok) {\n    skip();\n    return true;\n  }\n  return false;\n}\n\nvoid ScriptParserBase::skip() { (void)next(); }\n\nvoid ScriptParserBase::expect(StringRef Expect) {\n  if (Error)\n    return;\n  StringRef Tok = next();\n  if (Tok != Expect)\n    setError(Expect + \" expected, but got \" + Tok);\n}\n\nstd::string ScriptParserBase::currentLocation() {\n  MemoryBufferRef MB = currentBuffer();\n  return (MB.getBufferIdentifier() + \":\" +\n          Twine(getLineNumber(MB.getBuffer(), Tokens[Pos - 1])))\n      .str();\n}\n\n\/\/ Returns true if string 'Bigger' contains string 'Shorter'.\nstatic bool containsString(StringRef Bigger, StringRef Shorter) {\n  const char *BiggerEnd = Bigger.data() + Bigger.size();\n  const char *ShorterEnd = Shorter.data() + Shorter.size();\n\n  return Bigger.data() <= Shorter.data() && BiggerEnd >= ShorterEnd;\n}\n\nMemoryBufferRef ScriptParserBase::currentBuffer() {\n  \/\/ Find input buffer containing the current token.\n  assert(!MBs.empty());\n  if (Pos)\n    for (MemoryBufferRef MB : MBs)\n      if (containsString(MB.getBuffer(), Tokens[Pos - 1]))\n        return MB;\n\n  return MBs.front();\n}\n<|endoftext|>"}
{"text":"Reset to last checkpoint<|endoftext|>"}
{"text":"\/*\n * Copyright (c) 2013-2016 John Connor\n * Copyright (c) 2016-2017 The Vcash developers\n *\n * This file is part of vcash.\n *\n * vcash is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#ifndef COIN_RPC_JSON_PARSER_HPP\n#define COIN_RPC_JSON_PARSER_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace coin {\n\n    \/** \n     * Implements a JSON-RPC parser.\n     *\/\n    class rpc_json_parser\n    {\n        public:\n        \n            template \n            struct translator\n            {\n                typedef T internal_type;\n                typedef T external_type;\n\n                boost::optional get_value(const T & v)\n                {\n                    return v.substr(1, v.size() - 2) ;\n                }\n                \n                boost::optional put_value(const T & v)\n                {\n                    return '\"' + v + '\"';\n                }\n            };\n\n            template\n            static void write_json(\n                std::basic_ostream &\n                stream, const Ptree & pt, bool pretty = true\n                )\n            {\n                write_json_internal(\n                    stream, pt, std::string(), pretty\n                );\n            }\n    \n        private:\n        \n            \/\/ ...\n        \n        protected:\n        \n            template\n            static std::basic_string create_escapes(\n                const std::basic_string & s\n                )\n            {\n                std::basic_string result;\n                \n                auto b = s.begin();\n                auto e = s.end();\n                \n                while (b != e)\n                {\n                    if (\n                        *b == 0x20 || *b == 0x21 ||\n                        (*b >= 0x23 && *b <= 0x2E) ||\n                        (*b >= 0x30 && *b <= 0x5B) ||\n                        (*b >= 0x5D && *b <= 0xFF)\n                        )\n                    {\n                        result += *b;\n                    }\n                    else if (*b == Ch('\\b'))\n                    {\n                        result += Ch('\\\\'), result += Ch('b');\n                    }\n                    else if (*b == Ch('\\f'))\n                    {\n                        result += Ch('\\\\'), result += Ch('f');\n                    }\n                    else if (*b == Ch('\\n'))\n                    {\n                        result += Ch('\\\\'), result += Ch('n');\n                    }\n                    else if (*b == Ch('\\r'))\n                    {\n                        result += Ch('\\\\'), result += Ch('r');\n                    }\n                    else if (*b == Ch('\/'))\n                    {\n                        result += Ch('\\\\'), result += Ch('\/');\n                    }\n                    else if (*b == Ch('\"'))\n                    {\n                        result+= Ch('\"');\n                    }\n                    else if (*b == Ch('\\\\'))\n                    {\n                        result += Ch('\\\\'), result += Ch('\\\\');\n                    }\n                    else\n                    {\n                        const char * hexdigits = \"0123456789ABCDEF\";\n                        \n                        typedef typename boost::make_unsigned::type UCh;\n                        \n                        unsigned long u =\n                            (std::min)(static_cast(\n                            static_cast(*b)), 0xFFFFul\n                        );\n                        \n                        auto d1 = u \/ 4096; u -= d1 * 4096;\n                        auto d2 = u \/ 256; u -= d2 * 256;\n                        auto d3 = u \/ 16; u -= d3 * 16;\n                        auto d4 = u;\n                        \n                        result += Ch('\\\\'); result += Ch('u');\n                        result += Ch(hexdigits[d1]); result += Ch(hexdigits[d2]);\n                        result += Ch(hexdigits[d3]); result += Ch(hexdigits[d4]);\n                    }\n                    ++b;\n                }\n                return result;\n            }\n\n            template\n            static void write_json_helper(\n                std::basic_ostream &\n                stream, const Ptree & pt, int indent, bool pretty\n                )\n            {\n                typedef typename Ptree::key_type::value_type Ch;\n                typedef typename std::basic_string Str;\n\n                if (pt.empty())\n                {\n                    auto data = create_escapes(pt.template get_value());\n\n                    stream << data;\n\n                }\n                else if (pt.count(Str()) == pt.size())\n                {\n                    stream << Ch('[');\n                    \n                    if (pretty)\n                    {\n                        stream << Ch('\\n');\n                    }\n                    \n                    auto it = pt.begin();\n                    \n                    for (; it != pt.end(); ++it)\n                    {\n                        if (pretty)\n                        {\n                            stream << Str(4 * (indent + 1), Ch(' '));\n                        }\n                        \n                        write_json_helper(\n                            stream, it->second, indent + 1, pretty\n                        );\n                        \n                        if (boost::next(it) != pt.end())\n                        {\n                            stream << Ch(',');\n                        }\n                        \n                        if (pretty)\n                        {\n                            stream << Ch('\\n');\n                        }\n                    }\n                    stream << Str(4 * indent, Ch(' ')) << Ch(']');\n\n                }\n                else\n                {\n                    stream << Ch('{');\n                    \n                    if (pretty)\n                    {\n                        stream << Ch('\\n');\n                    }\n                    \n                    typename Ptree::const_iterator it = pt.begin();\n                    \n                    for (; it != pt.end(); ++it)\n                    {\n                        if (pretty)\n                        {\n                            stream << Str(4 * (indent + 1), Ch(' '));\n                        }\n                        \n                        stream << Ch('\"') <<\n                            create_escapes(it->first) << Ch('\"') << Ch(':')\n                        ;\n                        \n                        if (pretty)\n                        {\n                            if (it->second.empty())\n                            {\n                                stream << Ch(' ');\n                            }\n                            else\n                            {\n                                stream <<\n                                    Ch('\\n') << Str(4 * (indent + 1), Ch(' '))\n                                ;\n                            }\n                        }\n                        \n                        write_json_helper(\n                            stream, it->second, indent + 1, pretty\n                        );\n                        \n                        if (boost::next(it) != pt.end())\n                        {\n                            stream << Ch(',');\n                        }\n                        \n                        if (pretty)\n                        {\n                            stream << Ch('\\n');\n                        }\n                    }\n                    \n                    if (pretty) stream << Str(4 * indent, Ch(' '));\n                    {\n                        stream << Ch('}');\n                    }\n                }\n\n            }\n\n            template\n            static bool verify_json(const Ptree & pt, int depth)\n            {\n                typedef typename Ptree::key_type::value_type Ch;\n                typedef typename std::basic_string Str;\n\n                if (depth == 0 && !pt.template get_value().empty())\n                {\n                    return false;\n                }\n                \n                if (!pt.template get_value().empty() && !pt.empty())\n                {\n                    return false;\n                }\n                \n                typename Ptree::const_iterator it = pt.begin();\n                \n                for (; it != pt.end(); ++it)\n                {\n                    if (!verify_json(it->second, depth + 1))\n                    {\n                        return false;\n                    }\n                }\n                \n                return true;\n\n            }\n\n            template\n            static void write_json_internal(\n                std::basic_ostream & stream,\n                const Ptree & pt, const std::string & filename, bool pretty\n                )\n            {\n                if (verify_json(pt, 0) == false)\n                {\n                    BOOST_PROPERTY_TREE_THROW(\n                        boost::property_tree::json_parser::json_parser_error(\n                        \"ptree contains data that cannot be represented \"\n                        \"in JSON format\", filename, 0)\n                    );\n                }\n                \n                write_json_helper(stream, pt, 0, pretty);\n                stream << std::endl;\n                \n                if (stream.good() == false)\n                {\n                    BOOST_PROPERTY_TREE_THROW(\n                        boost::property_tree::json_parser::json_parser_error(\n                        \"write error\", filename, 0)\n                    );\n                }\n            }\n    };\n    \n} \/\/ namespace coin\n\n#endif \/\/ COIN_RPC_JSON_PARSER_HPP\nwrite_json_helper (un)pretty edit\/*\n * Copyright (c) 2013-2016 John Connor\n * Copyright (c) 2016-2017 The Vcash developers\n *\n * This file is part of vcash.\n *\n * vcash is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#ifndef COIN_RPC_JSON_PARSER_HPP\n#define COIN_RPC_JSON_PARSER_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace coin {\n\n    \/** \n     * Implements a JSON-RPC parser.\n     *\/\n    class rpc_json_parser\n    {\n        public:\n        \n            template \n            struct translator\n            {\n                typedef T internal_type;\n                typedef T external_type;\n\n                boost::optional get_value(const T & v)\n                {\n                    return v.substr(1, v.size() - 2) ;\n                }\n                \n                boost::optional put_value(const T & v)\n                {\n                    return '\"' + v + '\"';\n                }\n            };\n\n            template\n            static void write_json(\n                std::basic_ostream &\n                stream, const Ptree & pt, bool pretty = true\n                )\n            {\n                write_json_internal(\n                    stream, pt, std::string(), pretty\n                );\n            }\n    \n        private:\n        \n            \/\/ ...\n        \n        protected:\n        \n            template\n            static std::basic_string create_escapes(\n                const std::basic_string & s\n                )\n            {\n                std::basic_string result;\n                \n                auto b = s.begin();\n                auto e = s.end();\n                \n                while (b != e)\n                {\n                    if (\n                        *b == 0x20 || *b == 0x21 ||\n                        (*b >= 0x23 && *b <= 0x2E) ||\n                        (*b >= 0x30 && *b <= 0x5B) ||\n                        (*b >= 0x5D && *b <= 0xFF)\n                        )\n                    {\n                        result += *b;\n                    }\n                    else if (*b == Ch('\\b'))\n                    {\n                        result += Ch('\\\\'), result += Ch('b');\n                    }\n                    else if (*b == Ch('\\f'))\n                    {\n                        result += Ch('\\\\'), result += Ch('f');\n                    }\n                    else if (*b == Ch('\\n'))\n                    {\n                        result += Ch('\\\\'), result += Ch('n');\n                    }\n                    else if (*b == Ch('\\r'))\n                    {\n                        result += Ch('\\\\'), result += Ch('r');\n                    }\n                    else if (*b == Ch('\/'))\n                    {\n                        result += Ch('\\\\'), result += Ch('\/');\n                    }\n                    else if (*b == Ch('\"'))\n                    {\n                        result+= Ch('\"');\n                    }\n                    else if (*b == Ch('\\\\'))\n                    {\n                        result += Ch('\\\\'), result += Ch('\\\\');\n                    }\n                    else\n                    {\n                        const char * hexdigits = \"0123456789ABCDEF\";\n                        \n                        typedef typename boost::make_unsigned::type UCh;\n                        \n                        unsigned long u =\n                            (std::min)(static_cast(\n                            static_cast(*b)), 0xFFFFul\n                        );\n                        \n                        auto d1 = u \/ 4096; u -= d1 * 4096;\n                        auto d2 = u \/ 256; u -= d2 * 256;\n                        auto d3 = u \/ 16; u -= d3 * 16;\n                        auto d4 = u;\n                        \n                        result += Ch('\\\\'); result += Ch('u');\n                        result += Ch(hexdigits[d1]); result += Ch(hexdigits[d2]);\n                        result += Ch(hexdigits[d3]); result += Ch(hexdigits[d4]);\n                    }\n                    ++b;\n                }\n                return result;\n            }\n\n            template\n            static void write_json_helper(\n                std::basic_ostream &\n                stream, const Ptree & pt, int indent, bool pretty\n                )\n            {\n                typedef typename Ptree::key_type::value_type Ch;\n                typedef typename std::basic_string Str;\n\n                if (pt.empty())\n                {\n                    auto data = create_escapes(pt.template get_value());\n\n                    stream << data;\n\n                }\n                else if (pt.count(Str()) == pt.size())\n                {\n                    stream << Ch('[');\n                    \n                    if (pretty)\n                    {\n                        stream << Ch('\\n');\n                    }\n                    \n                    auto it = pt.begin();\n                    \n                    for (; it != pt.end(); ++it)\n                    {\n                        if (pretty)\n                        {\n                            stream << Str(4 * (indent + 1), Ch(' '));\n                        }\n                        \n                        write_json_helper(\n                            stream, it->second, indent + 1, pretty\n                        );\n                        \n                        if (boost::next(it) != pt.end())\n                        {\n                            stream << Ch(',');\n                        }\n                        \n                        if (pretty)\n                        {\n                            stream << Ch('\\n');\n                        }\n                    }\n                    if (pretty) stream << Str(4 * indent, Ch(' '));\n                    {\n                        stream << Ch(']');\n                    }\n\n                }\n                else\n                {\n                    stream << Ch('{');\n                    \n                    if (pretty)\n                    {\n                        stream << Ch('\\n');\n                    }\n                    \n                    typename Ptree::const_iterator it = pt.begin();\n                    \n                    for (; it != pt.end(); ++it)\n                    {\n                        if (pretty)\n                        {\n                            stream << Str(4 * (indent + 1), Ch(' '));\n                        }\n                        \n                        stream << Ch('\"') <<\n                            create_escapes(it->first) << Ch('\"') << Ch(':')\n                        ;\n                        \n                        if (pretty)\n                        {\n                            if (it->second.empty())\n                            {\n                                stream << Ch(' ');\n                            }\n                            else\n                            {\n                                stream <<\n                                    Ch('\\n') << Str(4 * (indent + 1), Ch(' '))\n                                ;\n                            }\n                        }\n                        \n                        write_json_helper(\n                            stream, it->second, indent + 1, pretty\n                        );\n                        \n                        if (boost::next(it) != pt.end())\n                        {\n                            stream << Ch(',');\n                        }\n                        \n                        if (pretty)\n                        {\n                            stream << Ch('\\n');\n                        }\n                    }\n                    \n                    if (pretty) stream << Str(4 * indent, Ch(' '));\n                    {\n                        stream << Ch('}');\n                    }\n                }\n\n            }\n\n            template\n            static bool verify_json(const Ptree & pt, int depth)\n            {\n                typedef typename Ptree::key_type::value_type Ch;\n                typedef typename std::basic_string Str;\n\n                if (depth == 0 && !pt.template get_value().empty())\n                {\n                    return false;\n                }\n                \n                if (!pt.template get_value().empty() && !pt.empty())\n                {\n                    return false;\n                }\n                \n                typename Ptree::const_iterator it = pt.begin();\n                \n                for (; it != pt.end(); ++it)\n                {\n                    if (!verify_json(it->second, depth + 1))\n                    {\n                        return false;\n                    }\n                }\n                \n                return true;\n\n            }\n\n            template\n            static void write_json_internal(\n                std::basic_ostream & stream,\n                const Ptree & pt, const std::string & filename, bool pretty\n                )\n            {\n                if (verify_json(pt, 0) == false)\n                {\n                    BOOST_PROPERTY_TREE_THROW(\n                        boost::property_tree::json_parser::json_parser_error(\n                        \"ptree contains data that cannot be represented \"\n                        \"in JSON format\", filename, 0)\n                    );\n                }\n                \n                write_json_helper(stream, pt, 0, pretty);\n                stream << std::endl;\n                \n                if (stream.good() == false)\n                {\n                    BOOST_PROPERTY_TREE_THROW(\n                        boost::property_tree::json_parser::json_parser_error(\n                        \"write error\", filename, 0)\n                    );\n                }\n            }\n    };\n    \n} \/\/ namespace coin\n\n#endif \/\/ COIN_RPC_JSON_PARSER_HPP\n<|endoftext|>"}
{"text":"\/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *\n*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *\n*                                                                             *\n* This library is free software; you can redistribute it and\/or modify it     *\n* under the terms of the GNU Lesser General Public License as published by    *\n* the Free Software Foundation; either version 2.1 of the License, or (at     *\n* your option) any later version.                                             *\n*                                                                             *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details.                                                           *\n*                                                                             *\n* You should have received a copy of the GNU Lesser General Public License    *\n* along with this library; if not, write to the Free Software Foundation,     *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *\n*******************************************************************************\n*                               SOFA :: Modules                               *\n*                                                                             *\n* This component is open-source                                               *\n*                                                                             *\n* Authors: Bruno Carrez                                                       *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************\/\n\/*****************************************************************************\n* User of this library should read the documentation\n* in the messaging.h file.\n******************************************************************************\/\n\n#include \"ClangStyleMessageFormatter.h\"\n#include \"Message.h\"\n\nusing std::ostringstream ;\n\n#include \nusing std::endl ;\nusing std::cout ;\nusing std::cerr ;\n\n\n\nnamespace sofa\n{\n\nnamespace helper\n{\n\nnamespace logging\n{\n\nstatic ClangStyleMessageFormatter s_ClangStyleMessageFormatter;\n\nMessageFormatter* ClangStyleMessageFormatter::getInstance()\n{\n    return &s_ClangStyleMessageFormatter;\n}\n\nvoid ClangStyleMessageFormatter::formatMessage(const Message& m,std::ostream& out)\n{\n    out << m.fileInfo().filename << \":\" << m.fileInfo().line << \":1: \" << m.type() << \": \" << m.message().rdbuf() << std::endl ;\n    out << \" message id: \" << m.id() << std::endl ;\n}\n\n\n} \/\/ logging\n} \/\/ helper\n} \/\/ sofa\nImprove the way clang format the message for a good looking qt.\/******************************************************************************\n*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *\n*                (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS                    *\n*                                                                             *\n* This library is free software; you can redistribute it and\/or modify it     *\n* under the terms of the GNU Lesser General Public License as published by    *\n* the Free Software Foundation; either version 2.1 of the License, or (at     *\n* your option) any later version.                                             *\n*                                                                             *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details.                                                           *\n*                                                                             *\n* You should have received a copy of the GNU Lesser General Public License    *\n* along with this library; if not, write to the Free Software Foundation,     *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *\n*******************************************************************************\n*                               SOFA :: Modules                               *\n*                                                                             *\n* This component is open-source                                               *\n*                                                                             *\n* Authors: Bruno Carrez                                                       *\n*                                                                             *\n* Contact information: contact@sofa-framework.org                             *\n******************************************************************************\/\n\/*****************************************************************************\n* User of this library should read the documentation\n* in the messaging.h file.\n******************************************************************************\/\n\n#include \"ClangStyleMessageFormatter.h\"\n#include \"Message.h\"\n\nusing std::ostringstream ;\n\n#include \nusing std::endl ;\nusing std::cout ;\nusing std::cerr ;\n\n\n\nnamespace sofa\n{\n\nnamespace helper\n{\n\nnamespace logging\n{\n\nstatic ClangStyleMessageFormatter s_ClangStyleMessageFormatter;\n\nMessageFormatter* ClangStyleMessageFormatter::getInstance()\n{\n    return &s_ClangStyleMessageFormatter;\n}\n\nconst char* typeToString(const Message::Type& t)\n{\n    switch(t){\n    case Message::Info:\n        return \"info\" ;\n    case Message::Warning:\n        return \"warning\" ;\n    case Message::Error:\n        return \"error\" ;\n    case Message::Fatal:\n        return \"fatal\" ;\n    case Message::TEmpty:\n        return \"empty\" ;\n    case Message::TypeCount:\n        return \"count\" ;\n    }\n    return \"undefined\" ;\n}\n\nvoid ClangStyleMessageFormatter::formatMessage(const Message& m,std::ostream& out)\n{\n    if(m.sender()!=\"\")\n        out << m.fileInfo().filename << \":\" << m.fileInfo().line << \":1: \" << typeToString(m.type()) << \": \" << m.message().rdbuf() << std::endl ;\n    else\n        out << m.fileInfo().filename << \":\" << m.fileInfo().line << \":1: \" << typeToString(m.type()) << \": [\"<< m.sender() <<\"] \" << m.message().rdbuf() << std::endl ;\n    out << \" message id: \" << m.id() << std::endl ;\n}\n\n\n} \/\/ logging\n} \/\/ helper\n} \/\/ sofa\n<|endoftext|>"}
{"text":"\/*\n *  Copyright 2010 Utkin Dmitry\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n\/*\n *  This file is part of the WSF Staff project.\n *  Please, visit http:\/\/code.google.com\/p\/staff for more information.\n *\/\n\n#ifdef WIN32\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MySql.h\"\n\nnamespace staff\n{\nnamespace das\n{\n\n  class MySqlProvider::MySqlImpl\n  {\n  public:\n    MySqlImpl():\n      m_sHost(\"localhost\"),\n      m_sPort(\"3306\"),\n      m_bConnected(false)\n    {\n    }\n\n\n  public:\n    static const std::string m_sName;\n    static const std::string m_sDescr;\n\n    MYSQL m_tConn;\n    std::string m_sHost;\n    std::string m_sPort;\n    std::string m_sDataBase;\n    std::string m_sLogin;\n    std::string m_sPassword;\n    bool m_bConnected;\n  };\n\n  const std::string MySqlProvider::MySqlImpl::m_sName = \"staff.das.MySql\";\n  const std::string MySqlProvider::MySqlImpl::m_sDescr = \"MySql data access provider\";\n\n\n  \/\/  ---------------------------------------------------------------\n\n  class MySqlQueryExecutor: public IQueryExecutor\n  {\n  public:\n    MySqlQueryExecutor(MySqlProvider* pProvider):\n      m_pProvider(pProvider), m_pResult(NULL),\n      m_nFieldsCount(0), m_nRowsCount(0), m_nCurrentRow(0)\n    {\n    }\n\n    virtual ~MySqlQueryExecutor()\n    {\n      Reset();\n    }\n\n    virtual void Reset()\n    {\n      if (m_pResult)\n      {\n        mysql_free_result(m_pResult);\n        m_pResult = NULL;\n        m_nFieldsCount = 0;\n        m_nRowsCount = 0;\n        m_nCurrentRow = 0;\n      }\n    }\n\n    virtual void Execute(const std::string& sExecute, const StringList& rlsParams)\n    {\n      STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pImpl->m_bConnected, \"Not Initialized\");\n\n      Reset();\n      MYSQL_BIND* paBind = NULL;\n      unsigned long* paSizes = NULL;\n\n      MYSQL_STMT* pStmt = mysql_stmt_init(&m_pProvider->m_pImpl->m_tConn);\n      STAFF_ASSERT(pStmt, \"Can't init STMT: \"\n                   + std::string(mysql_error(&m_pProvider->m_pImpl->m_tConn))\n                   + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n      try\n      {\n        paBind = reinterpret_cast(malloc(sizeof(MYSQL_BIND) * rlsParams.size()));\n        STAFF_ASSERT(paBind, \"Memory allocation failed!\");\n        memset(paBind, 0, sizeof(MYSQL_BIND) * rlsParams.size());\n\n        paSizes = reinterpret_cast(malloc(sizeof(unsigned long) * rlsParams.size()));\n        STAFF_ASSERT(paSizes, \"Memory allocation failed!\");\n        memset(paSizes, 0, sizeof(unsigned long) * rlsParams.size());\n\n        int nStatus = mysql_stmt_prepare(pStmt, sExecute.c_str(), sExecute.size());\n        STAFF_ASSERT(nStatus == 0, \"Failed to prepare STMT: \"\n                     + std::string(mysql_stmt_error(pStmt))\n                     + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        unsigned long nParamCount = mysql_stmt_param_count(pStmt);\n        STAFF_ASSERT(nParamCount == rlsParams.size(), \"STMT count != params count: \"\n                     + ToString(nParamCount) + \" != \" + ToString(rlsParams.size()) );\n\n\n        int nPos = 0;\n        static my_bool bNull = 1;\n        static my_bool bNotNull = 0;\n\n        for (StringList::const_iterator itParam = rlsParams.begin();\n             itParam != rlsParams.end(); ++itParam, ++nPos)\n        {\n          MYSQL_BIND* pBind = &paBind[nPos];\n          pBind->buffer_type = MYSQL_TYPE_STRING;\n\n          if (*itParam == STAFF_DAS_NULL_VALUE)\n          {\n            pBind->is_null = &bNull;\n          }\n          else\n          {\n            pBind->is_null = &bNotNull;\n            pBind->buffer = const_cast(reinterpret_cast(itParam->c_str()));\n            pBind->buffer_length = itParam->size();\n            paSizes[nPos] = pBind->buffer_length + 1;\n            pBind->length = &paSizes[nPos];\n          }\n        }\n\n        STAFF_ASSERT(mysql_stmt_bind_param(pStmt, paBind) == 0,\n                     \"Failed to bind param: #\" + ToString(nStatus) + \": \\n\"\n                     + std::string(mysql_stmt_error(pStmt))\n                     + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        nStatus = mysql_stmt_execute(pStmt);\n        STAFF_ASSERT(nStatus == 0, \"error executing query #\" + ToString(nStatus) + \": \\n\"\n                    + std::string(mysql_stmt_error(pStmt))\n                    + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        mysql_stmt_close(pStmt);\n        free(paBind);\n        free(paSizes);\n      }\n      catch (...)\n      {\n        mysql_stmt_close(pStmt);\n        free(paBind);\n        free(paSizes);\n        throw;\n      }\n\n      if (mysql_field_count(&m_pProvider->m_pImpl->m_tConn) > 0)\n      {\n        m_pResult = mysql_store_result(&m_pProvider->m_pImpl->m_tConn);\n        STAFF_ASSERT(m_pResult, \"Cannot retreive result: \\n\"\n                     + std::string(mysql_error(&m_pProvider->m_pImpl->m_tConn)));\n\n        m_nFieldsCount = mysql_num_fields(m_pResult);\n        m_nRowsCount = mysql_num_rows(m_pResult);\n      }\n    }\n\n    virtual void GetFieldsNames(StringList& rNames)\n    {\n      if (rNames.size() != m_nFieldsCount)\n      {\n        rNames.resize(m_nFieldsCount);\n      }\n\n      if (m_pResult)\n      {\n        MYSQL_FIELD* pFields = mysql_fetch_fields(m_pResult);\n        const char* szFieldName = NULL;\n        int nField = 0;\n        for (StringList::iterator itItem = rNames.begin();\n            itItem != rNames.end(); ++itItem, ++nField)\n        {\n          szFieldName = pFields[nField].name;\n          STAFF_ASSERT(szFieldName, \"Error while getting field name\");\n          *itItem = szFieldName;\n        }\n      }\n    }\n\n    virtual bool GetNextResult(StringList& rResult)\n    {\n      if (!m_pResult || m_nCurrentRow == m_nRowsCount)\n      {\n        return false;\n      }\n\n      if (rResult.size() != m_nFieldsCount)\n      {\n        rResult.resize(m_nFieldsCount);\n      }\n\n      MYSQL_ROW pRow = mysql_fetch_row(m_pResult);\n      STAFF_ASSERT(pRow, \"Error while fetching row\");\n\n      int nField = 0;\n      for (StringList::iterator itResult = rResult.begin();\n          itResult != rResult.end(); ++itResult, ++nField)\n      {\n        *itResult = pRow[nField] ? pRow[nField] : STAFF_DAS_NULL_VALUE;\n      }\n\n      ++m_nCurrentRow;\n      return true;\n    }\n\n  private:\n    MySqlProvider* m_pProvider;\n    MYSQL_RES* m_pResult;\n    unsigned m_nFieldsCount;\n    unsigned long long m_nRowsCount;\n    unsigned long long m_nCurrentRow;\n  };\n\n\n  MySqlProvider::MySqlProvider()\n  {\n    m_pImpl = new MySqlImpl;\n  }\n\n  MySqlProvider::~MySqlProvider()\n  {\n    delete m_pImpl;\n  }\n\n  void MySqlProvider::Init(const xml::Element& rConfig)\n  {\n    \/\/ initialize connection\n    const xml::Element& rConnection = rConfig.GetChildElementByName(\"connection\");\n\n    m_pImpl->m_sHost = rConnection.GetChildElementByName(\"host\").GetTextValue();\n    m_pImpl->m_sPort = rConnection.GetChildElementByName(\"port\").GetTextValue();\n    m_pImpl->m_sDataBase = rConnection.GetChildElementByName(\"db\").GetTextValue();\n    m_pImpl->m_sLogin = rConnection.GetChildElementByName(\"login\").GetTextValue();\n    m_pImpl->m_sPassword = rConnection.GetChildElementByName(\"password\").GetTextValue();\n\n    STAFF_ASSERT(!m_pImpl->m_bConnected, \"Already connected\");\n    unsigned short ushPort = 0;\n    FromString(m_pImpl->m_sPort, ushPort);\n    mysql_init(&m_pImpl->m_tConn);\n    MYSQL* pResult = mysql_real_connect(&m_pImpl->m_tConn,\n                           m_pImpl->m_sHost.c_str(), m_pImpl->m_sLogin.c_str(),\n                           m_pImpl->m_sPassword.c_str(), m_pImpl->m_sDataBase.c_str(),\n                           ushPort, NULL, 0);\n\n    STAFF_ASSERT(pResult, std::string(\"Failed to connect to db: \") + mysql_error(&m_pImpl->m_tConn));\n\n    m_pImpl->m_bConnected = true;\n\n    int nResult = mysql_set_character_set(&m_pImpl->m_tConn, \"UTF8\");\n    STAFF_ASSERT(nResult == 0, std::string(\"error setting encoding: \") + mysql_error(&m_pImpl->m_tConn));\n  }\n\n  void MySqlProvider::Deinit()\n  {\n    if (m_pImpl->m_bConnected)\n    {\n      mysql_close(&m_pImpl->m_tConn);\n      m_pImpl->m_bConnected = false;\n    }\n  }\n\n  const std::string& MySqlProvider::GetName() const\n  {\n    return MySqlImpl::m_sName;\n  }\n\n  const std::string& MySqlProvider::GetDescr() const\n  {\n    return MySqlImpl::m_sDescr;\n  }\n\n  PExecutor MySqlProvider::GetExecutor()\n  {\n    return new MySqlQueryExecutor(this);\n  }\n\n}\n}\n\ndas: Fixed MySql provider\/*\n *  Copyright 2010 Utkin Dmitry\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n\/*\n *  This file is part of the WSF Staff project.\n *  Please, visit http:\/\/code.google.com\/p\/staff for more information.\n *\/\n\n#ifdef WIN32\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MySql.h\"\n\nnamespace staff\n{\nnamespace das\n{\n\n  class MySqlProvider::MySqlImpl\n  {\n  public:\n    MySqlImpl():\n      m_sHost(\"localhost\"),\n      m_sPort(\"3306\"),\n      m_bConnected(false)\n    {\n    }\n\n\n  public:\n    static const std::string m_sName;\n    static const std::string m_sDescr;\n\n    MYSQL m_tConn;\n    std::string m_sHost;\n    std::string m_sPort;\n    std::string m_sDataBase;\n    std::string m_sLogin;\n    std::string m_sPassword;\n    bool m_bConnected;\n  };\n\n  const std::string MySqlProvider::MySqlImpl::m_sName = \"staff.das.MySql\";\n  const std::string MySqlProvider::MySqlImpl::m_sDescr = \"MySql data access provider\";\n\n\n  \/\/  ---------------------------------------------------------------\n\n  class MySqlQueryExecutor: public IQueryExecutor\n  {\n  public:\n    MySqlQueryExecutor(MySqlProvider* pProvider):\n      m_pProvider(pProvider), m_pStmt(NULL),\n      m_nFieldsCount(0), m_nRowsCount(0), m_nCurrentRow(0)\n    {\n    }\n\n    virtual ~MySqlQueryExecutor()\n    {\n      Reset();\n    }\n\n    virtual void Reset()\n    {\n      if (m_pStmt)\n      {\n        mysql_stmt_close(m_pStmt);\n        m_pStmt = NULL;\n        m_nFieldsCount = 0;\n        m_nRowsCount = 0;\n        m_nCurrentRow = 0;\n      }\n    }\n\n    virtual void Execute(const std::string& sExecute, const StringList& rlsParams)\n    {\n      STAFF_ASSERT(m_pProvider != NULL && m_pProvider->m_pImpl->m_bConnected, \"Not Initialized\");\n\n      Reset();\n\n      MYSQL_BIND* paBind = NULL;\n      unsigned long* paSizes = NULL;\n\n      m_pStmt = mysql_stmt_init(&m_pProvider->m_pImpl->m_tConn);\n      STAFF_ASSERT(m_pStmt, \"Can't init STMT: \"\n                   + std::string(mysql_error(&m_pProvider->m_pImpl->m_tConn))\n                   + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n      try\n      {\n        paBind = reinterpret_cast(malloc(sizeof(MYSQL_BIND) * rlsParams.size()));\n        STAFF_ASSERT(paBind, \"Memory allocation failed!\");\n        memset(paBind, 0, sizeof(MYSQL_BIND) * rlsParams.size());\n\n        paSizes = reinterpret_cast(malloc(sizeof(unsigned long) * rlsParams.size()));\n        STAFF_ASSERT(paSizes, \"Memory allocation failed!\");\n        memset(paSizes, 0, sizeof(unsigned long) * rlsParams.size());\n\n        int nStatus = mysql_stmt_prepare(m_pStmt, sExecute.c_str(), sExecute.size());\n        STAFF_ASSERT(nStatus == 0, \"Failed to prepare STMT: \"\n                     + std::string(mysql_stmt_error(m_pStmt))\n                     + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        unsigned long nParamCount = mysql_stmt_param_count(m_pStmt);\n        STAFF_ASSERT(nParamCount == rlsParams.size(), \"STMT count != params count: \"\n                     + ToString(nParamCount) + \" != \" + ToString(rlsParams.size()) );\n\n\n        int nPos = 0;\n        static my_bool bNull = 1;\n        static my_bool bNotNull = 0;\n\n        for (StringList::const_iterator itParam = rlsParams.begin();\n             itParam != rlsParams.end(); ++itParam, ++nPos)\n        {\n          MYSQL_BIND* pBind = &paBind[nPos];\n          pBind->buffer_type = MYSQL_TYPE_STRING;\n\n          if (*itParam == STAFF_DAS_NULL_VALUE)\n          {\n            pBind->is_null = &bNull;\n          }\n          else\n          {\n            pBind->is_null = &bNotNull;\n            pBind->buffer = const_cast(reinterpret_cast(itParam->c_str()));\n            pBind->buffer_length = itParam->size();\n            paSizes[nPos] = pBind->buffer_length + 1;\n            pBind->length = &paSizes[nPos];\n          }\n        }\n\n        STAFF_ASSERT(mysql_stmt_bind_param(m_pStmt, paBind) == 0,\n                     \"Failed to bind param: #\" + ToString(nStatus) + \": \\n\"\n                     + std::string(mysql_stmt_error(m_pStmt))\n                     + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        nStatus = mysql_stmt_execute(m_pStmt);\n        STAFF_ASSERT(nStatus == 0, \"error executing query #\" + ToString(nStatus) + \": \\n\"\n                    + std::string(mysql_stmt_error(m_pStmt))\n                    + \"\\nQuery was:\\n----------\\n\" + sExecute + \"\\n----------\\n\");\n\n        free(paBind);\n        free(paSizes);\n      }\n      catch (...)\n      {\n        mysql_stmt_close(m_pStmt);\n        free(paBind);\n        free(paSizes);\n        throw;\n      }\n\n      int nFieldsCount = mysql_stmt_field_count(m_pStmt);\n      if (nFieldsCount > 0)\n      {\n        int nRes = mysql_stmt_store_result(m_pStmt);\n        STAFF_ASSERT(!nRes, \"Can not retrieve result: \\n\"\n                     + std::string(mysql_error(&m_pProvider->m_pImpl->m_tConn)));\n\n        m_nFieldsCount = nFieldsCount;\n        m_nRowsCount = mysql_stmt_num_rows(m_pStmt);\n      }\n    }\n\n    virtual void GetFieldsNames(StringList& rNames)\n    {\n      if (rNames.size() != m_nFieldsCount)\n      {\n        rNames.resize(m_nFieldsCount);\n      }\n\n      if (m_pStmt)\n      {\n        MYSQL_FIELD* pFields = m_pStmt->fields;\n        const char* szFieldName = NULL;\n        int nField = 0;\n        for (StringList::iterator itItem = rNames.begin();\n            itItem != rNames.end(); ++itItem, ++nField)\n        {\n          szFieldName = pFields[nField].name;\n          STAFF_ASSERT(szFieldName, \"Error while getting field name\");\n          *itItem = szFieldName;\n        }\n      }\n    }\n\n    virtual bool GetNextResult(StringList& rResult)\n    {\n      if (!m_pStmt || m_nCurrentRow == m_nRowsCount)\n      {\n        return false;\n      }\n\n      if (rResult.size() != m_nFieldsCount)\n      {\n        rResult.resize(m_nFieldsCount);\n      }\n\n\n      my_bool* pbIsNull = reinterpret_cast(\n            malloc(sizeof(my_bool) * m_nFieldsCount));\n      STAFF_ASSERT(pbIsNull, \"Memory allocation failed!\");\n      memset(pbIsNull, 0, sizeof(my_bool) * m_nFieldsCount);\n\n      unsigned long* pulLengths = reinterpret_cast(\n            malloc(sizeof(unsigned long) * m_nFieldsCount));\n      STAFF_ASSERT(pulLengths, \"Memory allocation failed!\");\n      memset(pulLengths, 0, sizeof(unsigned long) * m_nFieldsCount);\n\n      MYSQL_BIND* paBind = reinterpret_cast(malloc(sizeof(MYSQL_BIND) * m_nFieldsCount));\n      STAFF_ASSERT(paBind, \"Memory allocation failed!\");\n      memset(paBind, 0, sizeof(MYSQL_BIND) * m_nFieldsCount);\n\n      char* szData = NULL;\n\n      try\n      {\n        for (unsigned i = 0; i < m_nFieldsCount; ++i)\n        {\n          paBind[i].is_null = &pbIsNull[i];\n          paBind[i].length = &pulLengths[i];\n        }\n\n        STAFF_ASSERT(!mysql_stmt_bind_result(m_pStmt, paBind), \"Can't bind result: \\n\"\n                     + std::string(mysql_stmt_error(m_pStmt)));\n\n        if (!mysql_stmt_fetch(m_pStmt))\n        {\n          Reset();\n          return false;\n        }\n\n        int nField = 0;\n        for (StringList::iterator itResult = rResult.begin();\n            itResult != rResult.end(); ++itResult, ++nField)\n        {\n          if (*paBind[nField].is_null)\n          {\n            *itResult = STAFF_DAS_NULL_VALUE;\n          }\n          else\n          if (pulLengths[nField] > 0)\n          {\n            const unsigned int nLength = pulLengths[nField] + 1;\n            szData = reinterpret_cast(malloc(nLength));\n            STAFF_ASSERT(szData, \"Memory allocation failed!\");\n            memset(szData, 0, nLength);\n            paBind[nField].buffer = szData;\n            paBind[nField].buffer_length = nLength;\n\n            STAFF_ASSERT(!mysql_stmt_fetch_column(m_pStmt, &paBind[nField], nField, 0),\n                         \"Failed to fetch column: \" + std::string(mysql_stmt_error(m_pStmt)));\n\n            *itResult = szData;\n            free(szData);\n            szData = NULL;\n          }\n        }\n      }\n      catch (...)\n      {\n        free(szData);\n        free(paBind);\n        free(pulLengths);\n        free(pbIsNull);\n        throw;\n      }\n\n      free(szData);\n      free(paBind);\n      free(pulLengths);\n      free(pbIsNull);\n\n      ++m_nCurrentRow;\n      return true;\n    }\n\n  private:\n    MySqlProvider* m_pProvider;\n    MYSQL_RES* m_pResult;\n    MYSQL_STMT* m_pStmt;\n    unsigned m_nFieldsCount;\n    unsigned long long m_nRowsCount;\n    unsigned long long m_nCurrentRow;\n  };\n\n\n  MySqlProvider::MySqlProvider()\n  {\n    m_pImpl = new MySqlImpl;\n  }\n\n  MySqlProvider::~MySqlProvider()\n  {\n    delete m_pImpl;\n  }\n\n  void MySqlProvider::Init(const xml::Element& rConfig)\n  {\n    \/\/ initialize connection\n    const xml::Element& rConnection = rConfig.GetChildElementByName(\"connection\");\n\n    m_pImpl->m_sHost = rConnection.GetChildElementByName(\"host\").GetTextValue();\n    m_pImpl->m_sPort = rConnection.GetChildElementByName(\"port\").GetTextValue();\n    m_pImpl->m_sDataBase = rConnection.GetChildElementByName(\"db\").GetTextValue();\n    m_pImpl->m_sLogin = rConnection.GetChildElementByName(\"login\").GetTextValue();\n    m_pImpl->m_sPassword = rConnection.GetChildElementByName(\"password\").GetTextValue();\n\n    STAFF_ASSERT(!m_pImpl->m_bConnected, \"Already connected\");\n    unsigned short ushPort = 0;\n    FromString(m_pImpl->m_sPort, ushPort);\n    mysql_init(&m_pImpl->m_tConn);\n    MYSQL* pResult = mysql_real_connect(&m_pImpl->m_tConn,\n                           m_pImpl->m_sHost.c_str(), m_pImpl->m_sLogin.c_str(),\n                           m_pImpl->m_sPassword.c_str(), m_pImpl->m_sDataBase.c_str(),\n                           ushPort, NULL, 0);\n\n    STAFF_ASSERT(pResult, std::string(\"Failed to connect to db: \") + mysql_error(&m_pImpl->m_tConn));\n\n    m_pImpl->m_bConnected = true;\n\n    int nResult = mysql_set_character_set(&m_pImpl->m_tConn, \"UTF8\");\n    STAFF_ASSERT(nResult == 0, std::string(\"error setting encoding: \") + mysql_error(&m_pImpl->m_tConn));\n  }\n\n  void MySqlProvider::Deinit()\n  {\n    if (m_pImpl->m_bConnected)\n    {\n      mysql_close(&m_pImpl->m_tConn);\n      m_pImpl->m_bConnected = false;\n    }\n  }\n\n  const std::string& MySqlProvider::GetName() const\n  {\n    return MySqlImpl::m_sName;\n  }\n\n  const std::string& MySqlProvider::GetDescr() const\n  {\n    return MySqlImpl::m_sDescr;\n  }\n\n  PExecutor MySqlProvider::GetExecutor()\n  {\n    return new MySqlQueryExecutor(this);\n  }\n\n}\n}\n\n<|endoftext|>"}
{"text":"\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \"re.h\"\n\nTEST(Regex, RegexSimple) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\"a+\", NULL));\n\n    EXPECT_FALSE(re.Match(\"\"));\n    EXPECT_TRUE(re.Match(\"a\"));\n    EXPECT_TRUE(re.Match(\"aa\"));\n    EXPECT_FALSE(re.Match(\"b\"));\n}\n\nTEST(Regex, InvalidNoErrorMessage) {\n    benchmark::Regex re;\n    EXPECT_FALSE(re.Init(\"[\", NULL));\n}\n\nTEST(Regex, Invalid) {\n    std::string error;\n    benchmark::Regex re;\n    EXPECT_FALSE(re.Init(\"[\", &error));\n\n    EXPECT_NE(\"\", error);\n}\nAdded more complicated regex test patterns\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \"re.h\"\n\nTEST(Regex, RegexSimple) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\"a+\", NULL));\n\n    EXPECT_FALSE(re.Match(\"\"));\n    EXPECT_TRUE(re.Match(\"a\"));\n    EXPECT_TRUE(re.Match(\"aa\"));\n    EXPECT_TRUE(re.Match(\"baa\"));\n    EXPECT_FALSE(re.Match(\"b\"));\n}\n\nTEST(Regex, RegexWildcard) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\"^a*$\", NULL));\n\n    EXPECT_TRUE(re.Match(\"\"));\n    EXPECT_TRUE(re.Match(\"a\"));\n    EXPECT_TRUE(re.Match(\"aa\"));\n    EXPECT_FALSE(re.Match(\"baa\"));\n    EXPECT_FALSE(re.Match(\"b\"));\n}\n\nTEST(Regex, RegexAny) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\".\", NULL));\n\n    EXPECT_FALSE(re.Match(\"\"));\n    EXPECT_TRUE(re.Match(\"a\"));\n    EXPECT_TRUE(re.Match(\"aa\"));\n}\n\nTEST(Regex, RegexExact) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\"^.$\", NULL));\n\n    EXPECT_FALSE(re.Match(\"\"));\n    EXPECT_TRUE(re.Match(\"a\"));\n    EXPECT_FALSE(re.Match(\"aa\"));\n}\n\nTEST(Regex, RegexComplicated) {\n    benchmark::Regex re;\n    EXPECT_TRUE(re.Init(\"([0-9]+ )?(mon|low)key(s)?\", NULL));\n\n    EXPECT_TRUE(re.Match(\"something monkey hands\"));\n    EXPECT_TRUE(re.Match(\"1 lowkey\"));\n    EXPECT_TRUE(re.Match(\"19 monkeys\"));\n    EXPECT_FALSE(re.Match(\"09 a\"));\n}\n\nTEST(Regex, InvalidNoErrorMessage) {\n    benchmark::Regex re;\n    EXPECT_FALSE(re.Init(\"[\", NULL));\n}\n\nTEST(Regex, Invalid) {\n    std::string error;\n    benchmark::Regex re;\n    EXPECT_FALSE(re.Init(\"[\", &error));\n\n    EXPECT_NE(\"\", error);\n}\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  $RCSfile: customshapeitem.cxx,v $\n *\n *  $Revision: 1.2 $\n *\n *  last change: $Author: rt $ $Date: 2004-04-02 14:07:39 $\n *\n *  The Contents of this file are made available subject to the terms of\n *  either of the following licenses\n *\n *         - GNU Lesser General Public License Version 2.1\n *         - Sun Industry Standards Source License Version 1.1\n *\n *  Sun Microsystems Inc., October, 2000\n *\n *  GNU Lesser General Public License Version 2.1\n *  =============================================\n *  Copyright 2000 by Sun Microsystems, Inc.\n *  901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n *  This library is free software; you can redistribute it and\/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License version 2.1, as published by the Free Software Foundation.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n *  MA  02111-1307  USA\n *\n *\n *  Sun Industry Standards Source License Version 1.1\n *  =================================================\n *  The contents of this file are subject to the Sun Industry Standards\n *  Source License Version 1.1 (the \"License\"); You may not use this file\n *  except in compliance with the License. You may obtain a copy of the\n *  License at http:\/\/www.openoffice.org\/license.html.\n *\n *  Software provided under this License is provided on an \"AS IS\" basis,\n *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n *  See the License for the specific provisions governing your rights and\n *  obligations concerning the Software.\n *\n *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n *  Copyright: 2000 by Sun Microsystems, Inc.\n *\n *  All Rights Reserved.\n *\n *  Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDASITM_HXX\n#include \"sdasitm.hxx\"\n#endif\n#include \"svdattr.hxx\"\n\nusing namespace ::std;\nusing namespace com::sun::star;\n\nSdrCustomShapeEngineItem::SdrCustomShapeEngineItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_ENGINE, String() )\n{}\nSdrCustomShapeEngineItem::SdrCustomShapeEngineItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_ENGINE, rVal )\n{}\n\nSdrCustomShapeDataItem::SdrCustomShapeDataItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_DATA, String() )\n{}\nSdrCustomShapeDataItem::SdrCustomShapeDataItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_DATA, rVal )\n{}\n\nbool SdrCustomShapeGeometryItem::PropertyEq::operator()( const rtl::OUString& r1, const rtl::OUString& r2 ) const\n{\n    return r1.equals( r2 );\n}\nbool SdrCustomShapeGeometryItem::PropertyPairEq::operator()( const SdrCustomShapeGeometryItem::PropertyPair& r1, const SdrCustomShapeGeometryItem::PropertyPair& r2 ) const\n{\n    return ( r1.first.equals( r2.first ) ) && ( r1.second.equals( r2.second ) );\n}\nsize_t SdrCustomShapeGeometryItem::PropertyPairHash::operator()( const SdrCustomShapeGeometryItem::PropertyPair &r1 ) const\n{\n    return (size_t)r1.first.hashCode() + r1.second.hashCode();\n};\n\nTYPEINIT1_AUTOFACTORY( SdrCustomShapeGeometryItem, SfxPoolItem );\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem()\n:   SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{}\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem( const uno::Sequence< beans::PropertyValue >& rVal )\n:   SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{\n    sal_Int32 i, j;\n    aPropSeq = rVal;\n\n    \/\/ hashing property values\n    beans::PropertyValue* pPropValues = aPropSeq.getArray();\n    const rtl::OUString* pPtr = NULL;\n    for ( i = 0; i < aPropSeq.getLength(); i++ )\n    {\n        beans::PropertyValue& rPropVal = aPropSeq[ i ];\n        aPropHashMap[ rPropVal.Name ] = i;\n        if ( rPropVal.Value.getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {\n            uno::Sequence< beans::PropertyValue >& rPropSeq = *( uno::Sequence< beans::PropertyValue >*)rPropVal.Value.getValue();\n            for ( j = 0; j < rPropSeq.getLength(); j++ )\n            {\n                beans::PropertyValue& rPropVal2 = rPropSeq[ j ];\n                aPropPairHashMap[ PropertyPair( rPropVal.Name, rPropVal2.Name ) ] = j;\n            }\n        }\n    }\n}\n\ncom::sun::star::uno::Any* SdrCustomShapeGeometryItem::GetPropertyValueByName( const rtl::OUString& rPropName )\n{\n    com::sun::star::uno::Any* pRet = NULL;\n    PropertyHashMap::iterator aHashIter( aPropHashMap.find( rPropName ) );\n    if ( aHashIter != aPropHashMap.end() )\n        pRet = &aPropSeq[ (*aHashIter).second ].Value;\n    return pRet;\n}\n\ncom::sun::star::uno::Any* SdrCustomShapeGeometryItem::GetPropertyValueByName( const rtl::OUString& rSequenceName, const rtl::OUString& rPropName )\n{\n    com::sun::star::uno::Any* pRet = NULL;\n    com::sun::star::uno::Any* pSeqAny = GetPropertyValueByName( rSequenceName );\n    if ( pSeqAny )\n    {\n        if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {\n            PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rSequenceName, rPropName ) ) );\n            if ( aHashIter != aPropPairHashMap.end() )\n            {\n                ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                    *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n                pRet = &rSecSequence[ (*aHashIter).second ].Value;\n            }\n        }\n    }\n    return pRet;\n}\n\nvoid SdrCustomShapeGeometryItem::SetPropertyValue( const com::sun::star::beans::PropertyValue& rPropVal )\n{\n    com::sun::star::uno::Any* pAny = GetPropertyValueByName( rPropVal.Name );\n    if ( pAny )\n        *pAny = rPropVal.Value;\n    else\n    {\n        sal_uInt32 nIndex = aPropSeq.getLength();\n        aPropSeq.realloc( nIndex + 1 );\n        aPropSeq[ nIndex ] = rPropVal ;\n\n        aPropHashMap[ rPropVal.Name ] = nIndex;\n    }\n}\n\nvoid SdrCustomShapeGeometryItem::SetPropertyValue( const rtl::OUString& rSequenceName, const com::sun::star::beans::PropertyValue& rPropVal )\n{\n    com::sun::star::uno::Any* pAny = GetPropertyValueByName( rSequenceName, rPropVal.Name );\n    if ( pAny )\n        *pAny = rPropVal.Value;\n    else\n    {\n        com::sun::star::uno::Any* pSeqAny = GetPropertyValueByName( rSequenceName );\n        if( pSeqAny == NULL )\n        {\n            ::com::sun::star::uno::Sequence < beans::PropertyValue > aSeq;\n            beans::PropertyValue aValue;\n            aValue.Name = rSequenceName;\n            aValue.Value = ::com::sun::star::uno::makeAny( aSeq );\n            SetPropertyValue( aValue );\n\n            pSeqAny = GetPropertyValueByName( rSequenceName );\n        }\n\n        DBG_ASSERT( pSeqAny, \"SdrCustomShapeGeometryItem::SetPropertyValue() - No Value??\" );\n\n        if( pSeqAny )\n        {\n            if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n            {\n                PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rSequenceName, rPropVal.Name ) ) );\n                if ( aHashIter != aPropPairHashMap.end() )\n                {\n                    ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                        *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n                    rSecSequence[ (*aHashIter).second ].Value = rPropVal.Value;\n                }\n                else\n                {\n                    ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                        *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n\n                    sal_Int32 nCount = rSecSequence.getLength();\n                    rSecSequence.realloc( nCount + 1 );\n                    rSecSequence[ nCount ] = rPropVal;\n\n                    aPropPairHashMap[ PropertyPair( rSequenceName, rPropVal.Name ) ] = nCount;\n                }\n            }\n        }\n    }\n}\n\nSdrCustomShapeGeometryItem::~SdrCustomShapeGeometryItem()\n{\n}\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem( SvStream& rIn, sal_uInt16 nVersion ):\n    SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{\n    if ( nVersion )\n    {\n\n    }\n}\nint __EXPORT SdrCustomShapeGeometryItem::operator==( const SfxPoolItem& rCmp ) const\n{\n    int bRet = SfxPoolItem::operator==( rCmp );\n    if ( bRet )\n        bRet = ((SdrCustomShapeGeometryItem&)rCmp).aPropSeq == aPropSeq;\n    return bRet;\n}\n\nSfxItemPresentation __EXPORT SdrCustomShapeGeometryItem::GetPresentation(\n    SfxItemPresentation ePresentation, SfxMapUnit eCoreMetric,\n    SfxMapUnit ePresentationMetric, XubString &rText, const IntlWrapper *) const\n{\n    rText += sal_Unicode( ' ' );\n    if ( ePresentation == SFX_ITEM_PRESENTATION_COMPLETE )\n    {\n        XubString aStr;\n\/\/      SdrItemPool::TakeItemName( Which(), aStr );\n        aStr += sal_Unicode( ' ' );\n        rText.Insert( aStr, 0 );\n    }\n    return ePresentation;\n}\n\nSfxPoolItem* __EXPORT SdrCustomShapeGeometryItem::Create( SvStream& rIn, sal_uInt16 nItemVersion ) const\n{\n    return new SdrCustomShapeGeometryItem( rIn, nItemVersion );\n}\n\nSvStream& __EXPORT SdrCustomShapeGeometryItem::Store( SvStream& rOut, sal_uInt16 nItemVersion ) const\n{\n    if ( nItemVersion )\n    {\n\n    }\n    return rOut;\n}\n\nSfxPoolItem* __EXPORT SdrCustomShapeGeometryItem::Clone( SfxItemPool *pPool ) const\n{\n    SdrCustomShapeGeometryItem* pItem = new SdrCustomShapeGeometryItem( GetGeometry() );\n\/\/  SdrCustomShapeGeometryItem* pItem = new SdrCustomShapeGeometryItem( *this );\n\n\/*\n    for ( i = 0; i < GetCount(); i++ )\n    {\n        const SdrCustomShapeAdjustmentValue& rVal = GetValue( i );\n        pItem->SetValue( i, rVal );\n    }\n*\/\n    return pItem;\n}\n\n#ifdef SDR_ISPOOLABLE\nint __EXPORT SdrCustomShapeGeometryItem::IsPoolable() const\n{\n    USHORT nId=Which();\n    return nId < SDRATTR_NOTPERSIST_FIRST || nId > SDRATTR_NOTPERSIST_LAST;\n}\n#endif\nsal_uInt16 SdrCustomShapeGeometryItem::GetVersion( sal_uInt16 nFileFormatVersion ) const\n{\n    return 1;\n}\nsal_Bool SdrCustomShapeGeometryItem::QueryValue( uno::Any& rVal, BYTE nMemberId ) const\n{\n    rVal <<= aPropSeq;\n    return sal_True;\n}\nsal_Bool SdrCustomShapeGeometryItem::PutValue( const uno::Any& rVal, BYTE nMemberId )\n{\n    if ( ! ( rVal >>= aPropSeq ) )\n        return sal_False;\n    else\n        return sal_True;\n}\nconst uno::Sequence< beans::PropertyValue >& SdrCustomShapeGeometryItem::GetGeometry() const\n{\n    return aPropSeq;\n}\n\/*\nconst uno::Any* GetValueByName( const rtl::OUString& rProperty ) const\n{\n\n}\n*\/\nSdrCustomShapeReplacementURLItem::SdrCustomShapeReplacementURLItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_REPLACEMENT_URL, String() )\n{}\nSdrCustomShapeReplacementURLItem::SdrCustomShapeReplacementURLItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_REPLACEMENT_URL, rVal )\n{}\n\nINTEGRATION: CWS sj09 (1.2.8); FILE MERGED 2004\/08\/04 18:43:58 sj 1.2.8.1: added methods to remove property values\/*************************************************************************\n *\n *  $RCSfile: customshapeitem.cxx,v $\n *\n *  $Revision: 1.3 $\n *\n *  last change: $Author: hr $ $Date: 2004-10-12 14:14: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): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDASITM_HXX\n#include \"sdasitm.hxx\"\n#endif\n#include \"svdattr.hxx\"\n\nusing namespace ::std;\nusing namespace com::sun::star;\n\nSdrCustomShapeEngineItem::SdrCustomShapeEngineItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_ENGINE, String() )\n{}\nSdrCustomShapeEngineItem::SdrCustomShapeEngineItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_ENGINE, rVal )\n{}\n\nSdrCustomShapeDataItem::SdrCustomShapeDataItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_DATA, String() )\n{}\nSdrCustomShapeDataItem::SdrCustomShapeDataItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_DATA, rVal )\n{}\n\nbool SdrCustomShapeGeometryItem::PropertyEq::operator()( const rtl::OUString& r1, const rtl::OUString& r2 ) const\n{\n    return r1.equals( r2 );\n}\nbool SdrCustomShapeGeometryItem::PropertyPairEq::operator()( const SdrCustomShapeGeometryItem::PropertyPair& r1, const SdrCustomShapeGeometryItem::PropertyPair& r2 ) const\n{\n    return ( r1.first.equals( r2.first ) ) && ( r1.second.equals( r2.second ) );\n}\nsize_t SdrCustomShapeGeometryItem::PropertyPairHash::operator()( const SdrCustomShapeGeometryItem::PropertyPair &r1 ) const\n{\n    return (size_t)r1.first.hashCode() + r1.second.hashCode();\n};\n\nTYPEINIT1_AUTOFACTORY( SdrCustomShapeGeometryItem, SfxPoolItem );\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem()\n:   SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{}\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem( const uno::Sequence< beans::PropertyValue >& rVal )\n:   SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{\n    sal_Int32 i, j;\n    aPropSeq = rVal;\n\n    \/\/ hashing property values\n    beans::PropertyValue* pPropValues = aPropSeq.getArray();\n    const rtl::OUString* pPtr = NULL;\n    for ( i = 0; i < aPropSeq.getLength(); i++ )\n    {\n        beans::PropertyValue& rPropVal = aPropSeq[ i ];\n        aPropHashMap[ rPropVal.Name ] = i;\n        if ( rPropVal.Value.getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {\n            uno::Sequence< beans::PropertyValue >& rPropSeq = *( uno::Sequence< beans::PropertyValue >*)rPropVal.Value.getValue();\n            for ( j = 0; j < rPropSeq.getLength(); j++ )\n            {\n                beans::PropertyValue& rPropVal2 = rPropSeq[ j ];\n                aPropPairHashMap[ PropertyPair( rPropVal.Name, rPropVal2.Name ) ] = j;\n            }\n        }\n    }\n}\n\ncom::sun::star::uno::Any* SdrCustomShapeGeometryItem::GetPropertyValueByName( const rtl::OUString& rPropName )\n{\n    com::sun::star::uno::Any* pRet = NULL;\n    PropertyHashMap::iterator aHashIter( aPropHashMap.find( rPropName ) );\n    if ( aHashIter != aPropHashMap.end() )\n        pRet = &aPropSeq[ (*aHashIter).second ].Value;\n    return pRet;\n}\n\ncom::sun::star::uno::Any* SdrCustomShapeGeometryItem::GetPropertyValueByName( const rtl::OUString& rSequenceName, const rtl::OUString& rPropName )\n{\n    com::sun::star::uno::Any* pRet = NULL;\n    com::sun::star::uno::Any* pSeqAny = GetPropertyValueByName( rSequenceName );\n    if ( pSeqAny )\n    {\n        if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {\n            PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rSequenceName, rPropName ) ) );\n            if ( aHashIter != aPropPairHashMap.end() )\n            {\n                ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                    *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n                pRet = &rSecSequence[ (*aHashIter).second ].Value;\n            }\n        }\n    }\n    return pRet;\n}\n\nvoid SdrCustomShapeGeometryItem::SetPropertyValue( const com::sun::star::beans::PropertyValue& rPropVal )\n{\n    com::sun::star::uno::Any* pAny = GetPropertyValueByName( rPropVal.Name );\n    if ( pAny )\n    {   \/\/ property is already available\n        sal_Int32 i;\n        if ( pAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {   \/\/ old property is a sequence->each entry has to be removed from the HashPairMap\n            ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pAny->getValue());\n            for ( i = 0; i < rSecSequence.getLength(); i++ )\n            {\n                PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rPropVal.Name, rSecSequence[ i ].Name ) ) );\n                if ( aHashIter != aPropPairHashMap.end() )\n                    aPropPairHashMap.erase( aHashIter );\n            }\n        }\n        *pAny = rPropVal.Value;\n        if ( rPropVal.Value.getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {   \/\/ the new property is a sequence->each entry has to be inserted into the HashPairMap\n            ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pAny->getValue());\n            for ( i = 0; i < rSecSequence.getLength(); i++ )\n            {\n                beans::PropertyValue& rPropVal2 = rSecSequence[ i ];\n                aPropPairHashMap[ PropertyPair( rPropVal.Name, rPropVal2.Name ) ] = i;\n            }\n        }\n    }\n    else\n    {   \/\/ its a new property\n        sal_uInt32 nIndex = aPropSeq.getLength();\n        aPropSeq.realloc( nIndex + 1 );\n        aPropSeq[ nIndex ] = rPropVal ;\n\n        aPropHashMap[ rPropVal.Name ] = nIndex;\n    }\n}\n\nvoid SdrCustomShapeGeometryItem::SetPropertyValue( const rtl::OUString& rSequenceName, const com::sun::star::beans::PropertyValue& rPropVal )\n{\n    com::sun::star::uno::Any* pAny = GetPropertyValueByName( rSequenceName, rPropVal.Name );\n    if ( pAny ) \/\/ just replacing\n        *pAny = rPropVal.Value;\n    else\n    {\n        com::sun::star::uno::Any* pSeqAny = GetPropertyValueByName( rSequenceName );\n        if( pSeqAny == NULL )\n        {\n            ::com::sun::star::uno::Sequence < beans::PropertyValue > aSeq;\n            beans::PropertyValue aValue;\n            aValue.Name = rSequenceName;\n            aValue.Value = ::com::sun::star::uno::makeAny( aSeq );\n\n            sal_uInt32 nIndex = aPropSeq.getLength();\n            aPropSeq.realloc( nIndex + 1 );\n            aPropSeq[ nIndex ] = aValue;\n            aPropHashMap[ rSequenceName ] = nIndex;\n\n            pSeqAny = &aPropSeq[ nIndex ].Value;\n        }\n\n        DBG_ASSERT( pSeqAny, \"SdrCustomShapeGeometryItem::SetPropertyValue() - No Value??\" );\n\n        if( pSeqAny )\n        {\n            if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n            {\n                PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rSequenceName, rPropVal.Name ) ) );\n                if ( aHashIter != aPropPairHashMap.end() )\n                {\n                    ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                        *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n                    rSecSequence[ (*aHashIter).second ].Value = rPropVal.Value;\n                }\n                else\n                {\n                    ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                        *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n\n                    sal_Int32 nCount = rSecSequence.getLength();\n                    rSecSequence.realloc( nCount + 1 );\n                    rSecSequence[ nCount ] = rPropVal;\n\n                    aPropPairHashMap[ PropertyPair( rSequenceName, rPropVal.Name ) ] = nCount;\n                }\n            }\n        }\n    }\n}\n\nvoid SdrCustomShapeGeometryItem::ClearPropertyValue( const rtl::OUString& rPropName )\n{\n    if ( aPropSeq.getLength() )\n    {\n        PropertyHashMap::iterator aHashIter( aPropHashMap.find( rPropName ) );\n        if ( aHashIter != aPropHashMap.end() )\n        {\n             com::sun::star::uno::Any* pSeqAny = &aPropSeq[ (*aHashIter).second ].Value;\n            if ( pSeqAny )\n            {\n                if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n                {\n                    ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                        *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n\n                    sal_Int32 i;\n                    for ( i = 0; i < rSecSequence.getLength(); i++ )\n                    {\n                        PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rPropName, rSecSequence[ i ].Name ) ) );\n                        if ( aHashIter != aPropPairHashMap.end() )\n                            aPropPairHashMap.erase( aHashIter );        \/\/ removing property from pair hashmap\n                    }\n                }\n            }\n            sal_Int32 nLength = aPropSeq.getLength();\n            if ( nLength )\n            {\n                sal_Int32 nIndex  = (*aHashIter).second;\n                if ( nIndex != ( nLength - 1 ) )                        \/\/ resizing sequence\n                {\n                    PropertyHashMap::iterator aHashIter2( aPropHashMap.find( aPropSeq[ nLength - 1 ].Name ) );\n                    (*aHashIter2).second = nIndex;\n                    aPropSeq[ (*aHashIter).second ] = aPropSeq[ aPropSeq.getLength() - 1 ];\n                }\n                aPropSeq.realloc( aPropSeq.getLength() - 1 );\n            }\n            aPropHashMap.erase( aHashIter );                            \/\/ removing property from hashmap\n        }\n    }\n}\n\nvoid SdrCustomShapeGeometryItem::ClearPropertyValue( const rtl::OUString& rSequenceName, const rtl::OUString& rPropName )\n{\n    com::sun::star::uno::Any* pSeqAny = GetPropertyValueByName( rSequenceName );\n    if ( pSeqAny )\n    {\n        if ( pSeqAny->getValueType() == ::getCppuType((const ::com::sun::star::uno::Sequence < beans::PropertyValue >*)0) )\n        {\n            PropertyPairHashMap::iterator aHashIter( aPropPairHashMap.find( PropertyPair( rSequenceName, rPropName ) ) );\n            if ( aHashIter != aPropPairHashMap.end() )\n            {\n                ::com::sun::star::uno::Sequence < beans::PropertyValue >& rSecSequence =\n                    *((::com::sun::star::uno::Sequence < beans::PropertyValue >*)pSeqAny->getValue());\n\n                sal_Int32 nLength = rSecSequence.getLength();\n                if ( nLength )\n                {\n                    sal_Int32 nIndex  = (*aHashIter).second;\n                    if ( nIndex != ( nLength - 1 ) )                            \/\/ resizing sequence\n                    {\n                        PropertyPairHashMap::iterator aHashIter2( aPropPairHashMap.find( PropertyPair( rSequenceName, rSecSequence[ nLength - 1 ].Name ) ) );\n                        (*aHashIter2).second = nIndex;\n                        rSecSequence[ nIndex ] = rSecSequence[ nLength - 1 ];\n                    }\n                    rSecSequence.realloc( aPropSeq.getLength() - 1 );\n                }\n                aPropPairHashMap.erase( aHashIter );\n            }\n        }\n    }\n}\n\nSdrCustomShapeGeometryItem::~SdrCustomShapeGeometryItem()\n{\n}\nSdrCustomShapeGeometryItem::SdrCustomShapeGeometryItem( SvStream& rIn, sal_uInt16 nVersion ):\n    SfxPoolItem( SDRATTR_CUSTOMSHAPE_GEOMETRY )\n{\n    if ( nVersion )\n    {\n\n    }\n}\nint __EXPORT SdrCustomShapeGeometryItem::operator==( const SfxPoolItem& rCmp ) const\n{\n    int bRet = SfxPoolItem::operator==( rCmp );\n    if ( bRet )\n        bRet = ((SdrCustomShapeGeometryItem&)rCmp).aPropSeq == aPropSeq;\n    return bRet;\n}\n\nSfxItemPresentation __EXPORT SdrCustomShapeGeometryItem::GetPresentation(\n    SfxItemPresentation ePresentation, SfxMapUnit eCoreMetric,\n    SfxMapUnit ePresentationMetric, XubString &rText, const IntlWrapper *) const\n{\n    rText += sal_Unicode( ' ' );\n    if ( ePresentation == SFX_ITEM_PRESENTATION_COMPLETE )\n    {\n        XubString aStr;\n\/\/      SdrItemPool::TakeItemName( Which(), aStr );\n        aStr += sal_Unicode( ' ' );\n        rText.Insert( aStr, 0 );\n    }\n    return ePresentation;\n}\n\nSfxPoolItem* __EXPORT SdrCustomShapeGeometryItem::Create( SvStream& rIn, sal_uInt16 nItemVersion ) const\n{\n    return new SdrCustomShapeGeometryItem( rIn, nItemVersion );\n}\n\nSvStream& __EXPORT SdrCustomShapeGeometryItem::Store( SvStream& rOut, sal_uInt16 nItemVersion ) const\n{\n    if ( nItemVersion )\n    {\n\n    }\n    return rOut;\n}\n\nSfxPoolItem* __EXPORT SdrCustomShapeGeometryItem::Clone( SfxItemPool *pPool ) const\n{\n    SdrCustomShapeGeometryItem* pItem = new SdrCustomShapeGeometryItem( GetGeometry() );\n\/\/  SdrCustomShapeGeometryItem* pItem = new SdrCustomShapeGeometryItem( *this );\n\n\/*\n    for ( i = 0; i < GetCount(); i++ )\n    {\n        const SdrCustomShapeAdjustmentValue& rVal = GetValue( i );\n        pItem->SetValue( i, rVal );\n    }\n*\/\n    return pItem;\n}\n\n#ifdef SDR_ISPOOLABLE\nint __EXPORT SdrCustomShapeGeometryItem::IsPoolable() const\n{\n    USHORT nId=Which();\n    return nId < SDRATTR_NOTPERSIST_FIRST || nId > SDRATTR_NOTPERSIST_LAST;\n}\n#endif\nsal_uInt16 SdrCustomShapeGeometryItem::GetVersion( sal_uInt16 nFileFormatVersion ) const\n{\n    return 1;\n}\nsal_Bool SdrCustomShapeGeometryItem::QueryValue( uno::Any& rVal, BYTE nMemberId ) const\n{\n    rVal <<= aPropSeq;\n    return sal_True;\n}\nsal_Bool SdrCustomShapeGeometryItem::PutValue( const uno::Any& rVal, BYTE nMemberId )\n{\n    if ( ! ( rVal >>= aPropSeq ) )\n        return sal_False;\n    else\n        return sal_True;\n}\nconst uno::Sequence< beans::PropertyValue >& SdrCustomShapeGeometryItem::GetGeometry() const\n{\n    return aPropSeq;\n}\n\/*\nconst uno::Any* GetValueByName( const rtl::OUString& rProperty ) const\n{\n\n}\n*\/\nSdrCustomShapeReplacementURLItem::SdrCustomShapeReplacementURLItem()\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_REPLACEMENT_URL, String() )\n{}\nSdrCustomShapeReplacementURLItem::SdrCustomShapeReplacementURLItem( const String& rVal )\n:   SfxStringItem( SDRATTR_CUSTOMSHAPE_REPLACEMENT_URL, rVal )\n{}\n\n<|endoftext|>"}
{"text":"#include \"potholedetector.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\n\ncv_bridge::CvImagePtr cv_ptr;\ntypedef pcl::PointCloud PCLCloud;\n\/\/Used to threshold the sum of a 60x60 matrix whose values are between 0-255\n\/\/Want mostly (>50%) white pixels (values around >200) in the matrix\n\/\/60x60x200ish = 720,000\/2 = ~400000\nconst int sumThreshold = 400000;\nconst int sizeThreshold = 200;\n\nconstexpr double radians(double degrees)\n{\n    return degrees \/ 180.0 * M_PI;\n}\n\nconstexpr int getDiff(int a, int b) {\n    return abs(a - b);\n}\n\nvoid PotholeDetector::img_callback(const sensor_msgs::ImageConstPtr& msg)\n{\n    cv_ptr = cv_bridge::toCvCopy(msg, \"\");\n    Mat orig = cv_ptr->image.clone();\n    src = cv_ptr->image.clone();\n\n    \/\/Crops the image (removes sky)\n    cv::Rect myROI(0, src.rows\/2 - 100, src.cols, src.rows\/2 - 50);\n    src = src(myROI);\n\n    cvtColor(src, src_gray, CV_BGR2GRAY);\n\n    \/\/Find the mean and stddev of the grayscale image in order to do adaptive thresholding\n    Mat mean;\n    Mat stddev;\n    meanStdDev(src_gray, mean, stddev);\n\n    double thresh = mean.at(0,0) + (stddev.at(0,0) * 2);\n    if(thresh > 254)\n    {\n        thresh = 254;\n    }\n\n    threshold(src_gray, src_gray, thresh, 255, THRESH_BINARY);\n\n    GaussianBlur(src_gray, src_gray, Size(gaussian_size, gaussian_size), 100, 100);\n\n    vector> contours;\n    findContours(src_gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);\n\n    \/\/ Filter smaller contours\n    for (unsigned int i = 0; i < contours.size(); i++) {\n        vector curCont = contours[i];\n        if (curCont.size() <= sizeThreshold) {\n            contours.erase(contours.begin() + i);\n            i--;\n        }\n    }\n\n    \/\/ Get min \/ max Y and X\n    int minY = 10000;\n    int minX;\n    int maxY = 0;\n    int maxX;\n    for (unsigned int i = 0; i < contours.size(); i++) {\n        for (Point p : contours[i]) {\n            int y = p.y;\n            if (y > maxY) {\n                maxY = y;\n                maxX = p.x;\n            } else if (y < minY) {\n                minY = y;\n                minX = p.x;\n            }\n        }\n\n        \/\/ Delete if there is orange below or above\n        Vec3b intensityAbove = orig.at(minX, minY - 5);\n        uchar greenAbove = intensityAbove.val[1];\n        uchar redAbove = intensityAbove.val[2];\n        Vec3b intensityBelow = orig.at(maxX, maxY + 5);\n        uchar greenBelow = intensityBelow.val[1];\n        uchar redBelow = intensityBelow.val[2];\n        if (getDiff(greenAbove, 125) > 50 && getDiff(redAbove, 240) > 50 && getDiff(greenBelow, 125) > 50 && getDiff(redBelow, 240) > 50) {    \/\/ Play with these thresholds\n            contours.erase(contours.begin() + i);\n            i--;\n        }\n\n        \/\/ Delete if the contour itself is orange\n        Vec3b intensity = orig.at((minX + maxX) \/ 2, (minY + maxY) \/ 2);\n        uchar green = intensity.val[1];\n        uchar red = intensity.val[2];\n        if (getDiff(green, 125) > 50 && getDiff(red, 240) > 50) {    \/\/ Play with these thresholds\n            contours.erase(contours.begin() + i);\n            i--;\n        }\n    }\n\n    \/\/\/ Draw contours \n    drawContours(src, contours, -1, Scalar(255), 2, 8);\n\n    Mat cloudMat = Mat::zeros(orig.rows, orig.cols, CV_32F);\n    cvtColor(src_gray, src_gray, CV_GRAY2BGR);\n\n    cv_bridge::CvImage out_msg;\n    out_msg.header   = msg->header;\n    out_msg.encoding = msg->encoding;\n    out_msg.image    = src_gray;\n\n    cv_ptr->image = src;\n    _pothole_filt_img.publish(cv_ptr->toImageMsg());\n    _pothole_thres.publish(out_msg.toImageMsg());\n    cloud = toPointCloud(cloudMat);\n    _pothole_cloud.publish(cloud);\n}\n\nPotholeDetector::PotholeDetector(ros::NodeHandle &handle)\n    : gaussian_size(7),\n      _it(handle),\n      tf_listener(handle)\n{\n    _src_img = _it.subscribe(\"\/left\/image_rect_color\", 1, &PotholeDetector::img_callback, this);\n    _pothole_filt_img = _it.advertise(\"\/pothole_filt_img\", 1);\n    _pothole_thres = _it.advertise(\"\/pothole_thres\", 1);\n    _pothole_cloud = handle.advertise(\"\/pothole_cloud\", 100);\n}\n\nPointCloud::Ptr PotholeDetector::toPointCloud(Mat src)\n{\n    PointCloud::Ptr cloud(new PointCloud);\n    for(int r = 0; r < src.rows; r++)\n    {\n        float *row = src.ptr(r);\n        for(int c = 0; c < src.cols; c++)\n        {\n            if(row[c] > 0)\n            {\n                cloud->points.push_back(PointXYZ(r, c, 0));\n            }\n        }\n    }\n\tcloud->header.frame_id = \"base_footprint\";\n\treturn cloud;\n}Pothole detector semi-working#include \"potholedetector.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\nusing namespace pcl;\n\ncv_bridge::CvImagePtr cv_ptr;\ntypedef pcl::PointCloud PCLCloud;\n\/\/Used to threshold the sum of a 60x60 matrix whose values are between 0-255\n\/\/Want mostly (>50%) white pixels (values around >200) in the matrix\n\/\/60x60x200ish = 720,000\/2 = ~400000\nconst int sumThreshold = 400000;\nconst int sizeThreshold = 200;\nconst int rOrange = 190;\nconst int gOrange = 60;\nconst int bOrange = 35;\n\ndouble radians(double degrees)\n{\n    return degrees \/ 180.0 * M_PI;\n}\n\nint getDiff(int a, int b) {\n    return abs(a - b);\n}\n\nvoid PotholeDetector::img_callback(const sensor_msgs::ImageConstPtr& msg)\n{\n    cv_ptr = cv_bridge::toCvCopy(msg, \"\");\n    src = cv_ptr->image.clone();\n\n    \/\/Crops the image (removes sky)\n    cv::Rect myROI(0, src.rows\/2 - 100, src.cols, src.rows\/2 - 50);\n    src = src(myROI);\n    Mat orig = src.clone();\n\n    cvtColor(src, src_gray, CV_BGR2GRAY);\n\n    \/\/Find the mean and stddev of the grayscale image in order to do adaptive thresholding\n    Mat mean;\n    Mat stddev;\n    meanStdDev(src_gray, mean, stddev);\n\n    double thresh = mean.at(0,0) + (stddev.at(0,0) * 2);\n    if(thresh > 254)\n    {\n        thresh = 254;\n    }\n\n    threshold(src_gray, src_gray, thresh, 255, THRESH_BINARY);\n\n    GaussianBlur(src_gray, src_gray, Size(gaussian_size, gaussian_size),\n            100, 100);\n\n    vector> contours;\n    findContours(src_gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);\n\n    \/\/ Filter smaller contours\n    for (vector>::iterator it = contours.begin();\n            it != contours.end(); ++it) {\n        vector curCont = *it;\n        if (curCont.size() <= sizeThreshold) {\n            contours.erase(it);\n            --it;\n        }\n    }\n    for (vector>::iterator it = contours.begin();\n            it != contours.end(); ++it) {\n        \/\/ Get min \/ max Y and X\n        int minY = 10000;\n        int minX = 10000;\n        int maxY = 0;\n        int maxX = 0;\n        for (Point p : *it) {\n            int x = p.x;\n            if (x > maxX) {\n                maxX = x;\n            }\n            if (x < minX) {\n                minX = x;\n            }\n        }\n\n        int centerX = (minX + maxX) \/ 2;\n\n        for (Point p : *it) {\n            int x = p.x;\n            int y = p.y;\n            if (x == centerX && y > maxY) {\n                maxY = y;\n            }\n            if (x == centerX && y < minY) {\n                minY = y;\n            }\n        }\n\n        if (minY - 35 >= 0) {\n            \/\/ Delete if there is orange below or above\n            int blueAbove = 0;\n            int greenAbove = 0;\n            int redAbove = 0;\n            int blueBelow = 0;\n            int greenBelow = 0;\n            int redBelow = 0;\n            for (int j = 5; j < 36; j++) {\n                blueAbove += orig.at(minY - j, centerX)[0];\n                greenAbove += orig.at(minY - j, centerX)[1];\n                redAbove += orig.at(minY - j, centerX)[2];\n                blueBelow += orig.at(maxY + j, centerX)[0];\n                greenBelow += orig.at(maxY + j, centerX)[1];\n                redBelow += orig.at(maxY + j, centerX)[2];\n            }\n            blueAbove \/= 30;\n            greenAbove \/= 30;\n            redAbove \/= 30;\n            blueBelow \/= 30;\n            greenBelow \/= 30;\n            redBelow \/= 30;\n            if (getDiff(redAbove, rOrange) < 50\n                    && getDiff(greenAbove, gOrange) < 50\n                    && getDiff(blueAbove, bOrange) < 50\n                    && getDiff(redBelow, rOrange) < 50\n                    && getDiff(greenBelow, gOrange) < 50\n                    && getDiff(blueBelow, bOrange) < 50) {\n                contours.erase(it);\n                --it;\n            }\n\n            \/\/ Delete if the contour itself is orange\n            Vec3b intensity = orig.at((minY + maxY) \/ 2, centerX);\n            uchar blue = intensity.val[0];\n            uchar green = intensity.val[1];\n            uchar red = intensity.val[2];\n            if (getDiff(red, rOrange) < 50 && getDiff(green, gOrange) < 50\n                    && getDiff(blue, bOrange) < 50) {\n                contours.erase(it);\n                --it;\n            }\n        } else {\n            contours.erase(it);\n            --it;\n        }\n    }\n    \/\/\/ Draw contours \n    drawContours(src, contours, -1, Scalar(255), 2, 8);\n\n    Mat cloudMat = Mat::zeros(orig.rows, orig.cols, CV_32F);\n    cvtColor(src_gray, src_gray, CV_GRAY2BGR);\n\n    cv_bridge::CvImage out_msg;\n    out_msg.header   = msg->header;\n    out_msg.encoding = msg->encoding;\n    out_msg.image    = src_gray;\n\n    cv_ptr->image = src;\n    _pothole_filt_img.publish(cv_ptr->toImageMsg());\n    _pothole_thres.publish(out_msg.toImageMsg());\n    cloud = toPointCloud(cloudMat);\n    _pothole_cloud.publish(cloud);\n}\n\nPotholeDetector::PotholeDetector(ros::NodeHandle &handle)\n    : gaussian_size(7),\n      _it(handle),\n      tf_listener(handle)\n{\n    _src_img = _it.subscribe(\"\/left\/image_rect_color\", 1, &PotholeDetector::img_callback, this);\n    _pothole_filt_img = _it.advertise(\"\/pothole_filt_img\", 1);\n    _pothole_thres = _it.advertise(\"\/pothole_thres\", 1);\n    _pothole_cloud = handle.advertise(\"\/pothole_cloud\", 100);\n}\n\nPointCloud::Ptr PotholeDetector::toPointCloud(Mat src)\n{\n    PointCloud::Ptr cloud(new PointCloud);\n    for(int r = 0; r < src.rows; r++)\n    {\n        float *row = src.ptr(r);\n        for(int c = 0; c < src.cols; c++)\n        {\n            if(row[c] > 0)\n            {\n                cloud->points.push_back(PointXYZ(r, c, 0));\n            }\n        }\n    }\n\tcloud->header.frame_id = \"base_footprint\";\n\treturn cloud;\n}\n<|endoftext|>"}
{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/************************************************************************* *\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include  \/\/ SwPostItField\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nnamespace sw { namespace annotation {\n\nSwAnnotationWin::SwAnnotationWin( SwEditWin& rEditWin,\n                                  WinBits nBits,\n                                  SwPostItMgr& aMgr,\n                                  SwPostItBits aBits,\n                                  SwSidebarItem& rSidebarItem,\n                                  SwFmtFld* aField )\n    : SwSidebarWin( rEditWin, nBits, aMgr, aBits, rSidebarItem )\n    , mpFmtFld(aField)\n    , mpFld( static_cast(aField->GetFld()))\n    , mpButtonPopup(0)\n{\n}\n\nSwAnnotationWin::~SwAnnotationWin()\n{\n    delete mpButtonPopup;\n}\n\nvoid SwAnnotationWin::SetPostItText()\n{\n    \/\/ get text from SwPostItField and insert into our textview\n    Engine()->SetModifyHdl( Link() );\n    Engine()->EnableUndo( sal_False );\n    mpFld = static_cast(mpFmtFld->GetFld());\n    if( mpFld->GetTextObject() )\n        Engine()->SetText( *mpFld->GetTextObject() );\n    else\n    {\n        Engine()->Clear();\n        GetOutlinerView()->SetAttribs(DefaultItem());\n        GetOutlinerView()->InsertText(mpFld->GetPar2(),false);\n    }\n\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n    Engine()->EnableUndo( sal_True );\n    Engine()->SetModifyHdl( LINK( this, SwAnnotationWin, ModifyHdl ) );\n    Invalidate();\n}\n\nvoid SwAnnotationWin::UpdateData()\n{\n    if ( Engine()->IsModified() )\n    {\n        IDocumentUndoRedo & rUndoRedo(\n            DocView().GetDocShell()->GetDoc()->GetIDocumentUndoRedo());\n        boost::scoped_ptr pOldField;\n        if (rUndoRedo.DoesUndo())\n        {\n            pOldField.reset(mpFld->Copy());\n        }\n        mpFld->SetPar2(Engine()->GetEditEngine().GetText());\n        mpFld->SetTextObject(Engine()->CreateParaObject());\n        if (rUndoRedo.DoesUndo())\n        {\n            SwTxtFld *const pTxtFld = mpFmtFld->GetTxtFld();\n            SwPosition aPosition( pTxtFld->GetTxtNode() );\n            aPosition.nContent = *pTxtFld->GetStart();\n            rUndoRedo.AppendUndo(\n                new SwUndoFieldFromDoc(aPosition, *pOldField, *mpFld, 0, true));\n        }\n        \/\/ so we get a new layout of notes (anchor position is still the same and we would otherwise not get one)\n        Mgr().SetLayout();\n        \/\/ #i98686# if we have several views, all notes should update their text\n        mpFmtFld->Broadcast(SwFmtFldHint( 0, SWFMTFLD_CHANGED));\n        DocView().GetDocShell()->SetModified();\n    }\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n}\n\nvoid SwAnnotationWin::Delete()\n{\n    SwSidebarWin::Delete();\n    \/\/ we delete the field directly, the Mgr cleans up the PostIt by listening\n    DocView().GetWrtShellPtr()->GotoField(*mpFmtFld);\n    GrabFocusToDocument();\n    DocView().GetWrtShellPtr()->DelRight();\n}\n\nvoid SwAnnotationWin::GotoPos()\n{\n    DocView().GetDocShell()->GetWrtShell()->GotoField(*mpFmtFld);\n}\n\nsal_uInt32 SwAnnotationWin::MoveCaret()\n{\n    \/\/ if this is an answer, do not skip over all following ones, but insert directly behind the current one\n    \/\/ but when just leaving a note, skip all following ones as well to continue typing\n    return Mgr().IsAnswer()\n           ? 1\n           : 1 + CountFollowing();\n}\n\n\/\/returns true, if there is another note right before this note\nbool SwAnnotationWin::CalcFollow()\n{\n    SwTxtFld* pTxtFld = mpFmtFld->GetTxtFld();\n    SwPosition aPosition( pTxtFld->GetTxtNode() );\n    aPosition.nContent = *pTxtFld->GetStart();\n    SwTxtAttr * const pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                    aPosition.nContent.GetIndex() - 1, RES_TXTATR_FIELD );\n    const SwField* pFld = pTxtAttr ? pTxtAttr->GetFld().GetFld() : 0;\n    return pFld && (pFld->Which()== RES_POSTITFLD);\n}\n\n\/\/ counts how many SwPostItField we have right after the current one\nsal_uInt32 SwAnnotationWin::CountFollowing()\n{\n    sal_uInt32 aCount = 1;  \/\/ we start with 1, so we have to subtract one at the end again\n    SwTxtFld* pTxtFld = mpFmtFld->GetTxtFld();\n    SwPosition aPosition( pTxtFld->GetTxtNode() );\n    aPosition.nContent = *pTxtFld->GetStart();\n\n    SwTxtAttr * pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                                        aPosition.nContent.GetIndex() + 1,\n                                        RES_TXTATR_FIELD );\n    SwField* pFld = pTxtAttr\n                    ? const_cast(pTxtAttr->GetFld().GetFld())\n                    : 0;\n    while ( pFld && ( pFld->Which()== RES_POSTITFLD ) )\n    {\n        aCount++;\n        pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                                        aPosition.nContent.GetIndex() + aCount,\n                                        RES_TXTATR_FIELD );\n        pFld = pTxtAttr\n               ? const_cast(pTxtAttr->GetFld().GetFld())\n               : 0;\n    }\n    return aCount - 1;\n}\n\nMenuButton* SwAnnotationWin::CreateMenuButton()\n{\n    mpButtonPopup = new PopupMenu(SW_RES(MN_ANNOTATION_BUTTON));\n    XubString aText = mpButtonPopup->GetItemText( FN_DELETE_NOTE_AUTHOR );\n    SwRewriter aRewriter;\n    aRewriter.AddRule(UndoArg1,GetAuthor());\n    aText = aRewriter.Apply(aText);\n    mpButtonPopup->SetItemText(FN_DELETE_NOTE_AUTHOR,aText);\n    MenuButton* pMenuButton = new AnnotationMenuButton( *this );\n    pMenuButton->SetPopupMenu( mpButtonPopup );\n    pMenuButton->Show();\n    return pMenuButton;\n}\n\nvoid SwAnnotationWin::InitAnswer(OutlinerParaObject* pText)\n{\n    \/\/collect our old meta data\n    SwSidebarWin* pWin = Mgr().GetNextPostIt(KEY_PAGEUP, this);\n    const SvtSysLocale aSysLocale;\n    const LocaleDataWrapper& rLocalData = aSysLocale.GetLocaleData();\n    String aText = String(SW_RES(STR_REPLY));\n        SwRewriter aRewriter;\n        aRewriter.AddRule(UndoArg1, pWin->GetAuthor());\n        aText = aRewriter.Apply(aText);\n        aText.Append(String(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\" (\")) +\n        String(rLocalData.getDate( pWin->GetDate())) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\", \")) +\n        String(rLocalData.getTime( pWin->GetTime(),false)) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"): \\\"\"))));\n    GetOutlinerView()->InsertText(aText,false);\n\n    \/\/ insert old, selected text or \"...\"\n    \/\/ TOOD: iterate over all paragraphs, not only first one to find out if it is empty\n    if (pText->GetTextObject().GetText(0).Len())\n        GetOutlinerView()->GetEditView().InsertText(pText->GetTextObject());\n    else\n        GetOutlinerView()->InsertText(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"...\")),false);\n    GetOutlinerView()->InsertText(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"\\\"\\n\")),false);\n\n    GetOutlinerView()->SetSelection(ESelection(0x0,0x0,0xFFFF,0xFFFF));\n    SfxItemSet aAnswerSet( DocView().GetDocShell()->GetPool() );\n    aAnswerSet.Put(SvxFontHeightItem(200,80,EE_CHAR_FONTHEIGHT));\n    aAnswerSet.Put(SvxPostureItem(ITALIC_NORMAL,EE_CHAR_ITALIC));\n    GetOutlinerView()->SetAttribs(aAnswerSet);\n    GetOutlinerView()->SetSelection(ESelection(0xFFFF,0xFFFF,0xFFFF,0xFFFF));\n\n    \/\/remove all attributes and reset our standard ones\n    GetOutlinerView()->GetEditView().RemoveAttribsKeepLanguages(true);\n    GetOutlinerView()->SetAttribs(DefaultItem());\n    \/\/ lets insert an undo step so the initial text can be easily deleted\n    \/\/ but do not use UpdateData() directly, would set modified state again and reentrance into Mgr\n    Engine()->SetModifyHdl( Link() );\n    IDocumentUndoRedo & rUndoRedo(\n        DocView().GetDocShell()->GetDoc()->GetIDocumentUndoRedo());\n    boost::scoped_ptr pOldField;\n    if (rUndoRedo.DoesUndo())\n    {\n        pOldField.reset(mpFld->Copy());\n    }\n    mpFld->SetPar2(Engine()->GetEditEngine().GetText());\n    mpFld->SetTextObject(Engine()->CreateParaObject());\n    if (rUndoRedo.DoesUndo())\n    {\n        SwTxtFld *const pTxtFld = mpFmtFld->GetTxtFld();\n        SwPosition aPosition( pTxtFld->GetTxtNode() );\n        aPosition.nContent = *pTxtFld->GetStart();\n        rUndoRedo.AppendUndo(\n            new SwUndoFieldFromDoc(aPosition, *pOldField, *mpFld, 0, true));\n    }\n    Engine()->SetModifyHdl( LINK( this, SwAnnotationWin, ModifyHdl ) );\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n}\n\nSvxLanguageItem SwAnnotationWin::GetLanguage(void)\n{\n    \/\/ set initial language for outliner\n    sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage( mpFld->GetLanguage() );\n    sal_uInt16 nLangWhichId = 0;\n    switch (nScriptType)\n    {\n        case SCRIPTTYPE_LATIN :    nLangWhichId = EE_CHAR_LANGUAGE ; break;\n        case SCRIPTTYPE_ASIAN :    nLangWhichId = EE_CHAR_LANGUAGE_CJK; break;\n        case SCRIPTTYPE_COMPLEX :  nLangWhichId = EE_CHAR_LANGUAGE_CTL; break;\n        default: OSL_FAIL(\"GetLanguage: wrong script type\");\n    }\n    return SvxLanguageItem(mpFld->GetLanguage(),nLangWhichId);\n}\n\nbool SwAnnotationWin::IsProtected()\n{\n    return SwSidebarWin::IsProtected() ||\n           GetLayoutStatus() == SwPostItHelper::DELETED ||\n           ( mpFmtFld ? mpFmtFld->IsProtect() : false );\n}\n\nString SwAnnotationWin::GetAuthor()\n{\n    return mpFld->GetPar1();\n}\n\nDate SwAnnotationWin::GetDate()\n{\n    return mpFld->GetDate();\n}\n\nTime SwAnnotationWin::GetTime()\n{\n    return mpFld->GetTime();\n}\n\n} } \/\/ end of namespace sw::annotation\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nResolves: fdo#33599 cursor in notes is reset to start on focus out\/focus in\/* -*- 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 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include  \/\/ SwPostItField\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nnamespace sw { namespace annotation {\n\nSwAnnotationWin::SwAnnotationWin( SwEditWin& rEditWin,\n                                  WinBits nBits,\n                                  SwPostItMgr& aMgr,\n                                  SwPostItBits aBits,\n                                  SwSidebarItem& rSidebarItem,\n                                  SwFmtFld* aField )\n    : SwSidebarWin( rEditWin, nBits, aMgr, aBits, rSidebarItem )\n    , mpFmtFld(aField)\n    , mpFld( static_cast(aField->GetFld()))\n    , mpButtonPopup(0)\n{\n}\n\nSwAnnotationWin::~SwAnnotationWin()\n{\n    delete mpButtonPopup;\n}\n\nvoid SwAnnotationWin::SetPostItText()\n{\n    \/\/If the cursor was visible, then make it visible again after\n    \/\/changing text, e.g. fdo#33599\n    Cursor *pCursor = GetOutlinerView()->GetEditView().GetCursor();\n    bool bCursorVisible = pCursor ? pCursor->IsVisible() : false;\n\n    \/\/If the new text is the same as the old text, keep the same insertion\n    \/\/point .e.g. fdo#33599\n    mpFld = static_cast(mpFmtFld->GetFld());\n    rtl::OUString sNewText = mpFld->GetPar2();\n    bool bTextUnchanged = sNewText.equals(Engine()->GetEditEngine().GetText());\n    ESelection aOrigSelection(GetOutlinerView()->GetEditView().GetSelection());\n\n    \/\/ get text from SwPostItField and insert into our textview\n    Engine()->SetModifyHdl( Link() );\n    Engine()->EnableUndo( sal_False );\n    if( mpFld->GetTextObject() )\n        Engine()->SetText( *mpFld->GetTextObject() );\n    else\n    {\n        Engine()->Clear();\n        GetOutlinerView()->SetAttribs(DefaultItem());\n        GetOutlinerView()->InsertText(sNewText,false);\n    }\n\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n    Engine()->EnableUndo( sal_True );\n    Engine()->SetModifyHdl( LINK( this, SwAnnotationWin, ModifyHdl ) );\n    if (bTextUnchanged)\n        GetOutlinerView()->GetEditView().SetSelection(aOrigSelection);\n    if (bCursorVisible)\n        GetOutlinerView()->ShowCursor();\n    Invalidate();\n}\n\nvoid SwAnnotationWin::UpdateData()\n{\n    if ( Engine()->IsModified() )\n    {\n        IDocumentUndoRedo & rUndoRedo(\n            DocView().GetDocShell()->GetDoc()->GetIDocumentUndoRedo());\n        boost::scoped_ptr pOldField;\n        if (rUndoRedo.DoesUndo())\n        {\n            pOldField.reset(mpFld->Copy());\n        }\n        mpFld->SetPar2(Engine()->GetEditEngine().GetText());\n        mpFld->SetTextObject(Engine()->CreateParaObject());\n        if (rUndoRedo.DoesUndo())\n        {\n            SwTxtFld *const pTxtFld = mpFmtFld->GetTxtFld();\n            SwPosition aPosition( pTxtFld->GetTxtNode() );\n            aPosition.nContent = *pTxtFld->GetStart();\n            rUndoRedo.AppendUndo(\n                new SwUndoFieldFromDoc(aPosition, *pOldField, *mpFld, 0, true));\n        }\n        \/\/ so we get a new layout of notes (anchor position is still the same and we would otherwise not get one)\n        Mgr().SetLayout();\n        \/\/ #i98686# if we have several views, all notes should update their text\n        mpFmtFld->Broadcast(SwFmtFldHint( 0, SWFMTFLD_CHANGED));\n        DocView().GetDocShell()->SetModified();\n    }\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n}\n\nvoid SwAnnotationWin::Delete()\n{\n    SwSidebarWin::Delete();\n    \/\/ we delete the field directly, the Mgr cleans up the PostIt by listening\n    DocView().GetWrtShellPtr()->GotoField(*mpFmtFld);\n    GrabFocusToDocument();\n    DocView().GetWrtShellPtr()->DelRight();\n}\n\nvoid SwAnnotationWin::GotoPos()\n{\n    DocView().GetDocShell()->GetWrtShell()->GotoField(*mpFmtFld);\n}\n\nsal_uInt32 SwAnnotationWin::MoveCaret()\n{\n    \/\/ if this is an answer, do not skip over all following ones, but insert directly behind the current one\n    \/\/ but when just leaving a note, skip all following ones as well to continue typing\n    return Mgr().IsAnswer()\n           ? 1\n           : 1 + CountFollowing();\n}\n\n\/\/returns true, if there is another note right before this note\nbool SwAnnotationWin::CalcFollow()\n{\n    SwTxtFld* pTxtFld = mpFmtFld->GetTxtFld();\n    SwPosition aPosition( pTxtFld->GetTxtNode() );\n    aPosition.nContent = *pTxtFld->GetStart();\n    SwTxtAttr * const pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                    aPosition.nContent.GetIndex() - 1, RES_TXTATR_FIELD );\n    const SwField* pFld = pTxtAttr ? pTxtAttr->GetFld().GetFld() : 0;\n    return pFld && (pFld->Which()== RES_POSTITFLD);\n}\n\n\/\/ counts how many SwPostItField we have right after the current one\nsal_uInt32 SwAnnotationWin::CountFollowing()\n{\n    sal_uInt32 aCount = 1;  \/\/ we start with 1, so we have to subtract one at the end again\n    SwTxtFld* pTxtFld = mpFmtFld->GetTxtFld();\n    SwPosition aPosition( pTxtFld->GetTxtNode() );\n    aPosition.nContent = *pTxtFld->GetStart();\n\n    SwTxtAttr * pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                                        aPosition.nContent.GetIndex() + 1,\n                                        RES_TXTATR_FIELD );\n    SwField* pFld = pTxtAttr\n                    ? const_cast(pTxtAttr->GetFld().GetFld())\n                    : 0;\n    while ( pFld && ( pFld->Which()== RES_POSTITFLD ) )\n    {\n        aCount++;\n        pTxtAttr = pTxtFld->GetTxtNode().GetTxtAttrForCharAt(\n                                        aPosition.nContent.GetIndex() + aCount,\n                                        RES_TXTATR_FIELD );\n        pFld = pTxtAttr\n               ? const_cast(pTxtAttr->GetFld().GetFld())\n               : 0;\n    }\n    return aCount - 1;\n}\n\nMenuButton* SwAnnotationWin::CreateMenuButton()\n{\n    mpButtonPopup = new PopupMenu(SW_RES(MN_ANNOTATION_BUTTON));\n    XubString aText = mpButtonPopup->GetItemText( FN_DELETE_NOTE_AUTHOR );\n    SwRewriter aRewriter;\n    aRewriter.AddRule(UndoArg1,GetAuthor());\n    aText = aRewriter.Apply(aText);\n    mpButtonPopup->SetItemText(FN_DELETE_NOTE_AUTHOR,aText);\n    MenuButton* pMenuButton = new AnnotationMenuButton( *this );\n    pMenuButton->SetPopupMenu( mpButtonPopup );\n    pMenuButton->Show();\n    return pMenuButton;\n}\n\nvoid SwAnnotationWin::InitAnswer(OutlinerParaObject* pText)\n{\n    \/\/collect our old meta data\n    SwSidebarWin* pWin = Mgr().GetNextPostIt(KEY_PAGEUP, this);\n    const SvtSysLocale aSysLocale;\n    const LocaleDataWrapper& rLocalData = aSysLocale.GetLocaleData();\n    String aText = String(SW_RES(STR_REPLY));\n        SwRewriter aRewriter;\n        aRewriter.AddRule(UndoArg1, pWin->GetAuthor());\n        aText = aRewriter.Apply(aText);\n        aText.Append(String(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\" (\")) +\n        String(rLocalData.getDate( pWin->GetDate())) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\", \")) +\n        String(rLocalData.getTime( pWin->GetTime(),false)) + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"): \\\"\"))));\n    GetOutlinerView()->InsertText(aText,false);\n\n    \/\/ insert old, selected text or \"...\"\n    \/\/ TOOD: iterate over all paragraphs, not only first one to find out if it is empty\n    if (pText->GetTextObject().GetText(0).Len())\n        GetOutlinerView()->GetEditView().InsertText(pText->GetTextObject());\n    else\n        GetOutlinerView()->InsertText(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"...\")),false);\n    GetOutlinerView()->InsertText(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"\\\"\\n\")),false);\n\n    GetOutlinerView()->SetSelection(ESelection(0x0,0x0,0xFFFF,0xFFFF));\n    SfxItemSet aAnswerSet( DocView().GetDocShell()->GetPool() );\n    aAnswerSet.Put(SvxFontHeightItem(200,80,EE_CHAR_FONTHEIGHT));\n    aAnswerSet.Put(SvxPostureItem(ITALIC_NORMAL,EE_CHAR_ITALIC));\n    GetOutlinerView()->SetAttribs(aAnswerSet);\n    GetOutlinerView()->SetSelection(ESelection(0xFFFF,0xFFFF,0xFFFF,0xFFFF));\n\n    \/\/remove all attributes and reset our standard ones\n    GetOutlinerView()->GetEditView().RemoveAttribsKeepLanguages(true);\n    GetOutlinerView()->SetAttribs(DefaultItem());\n    \/\/ lets insert an undo step so the initial text can be easily deleted\n    \/\/ but do not use UpdateData() directly, would set modified state again and reentrance into Mgr\n    Engine()->SetModifyHdl( Link() );\n    IDocumentUndoRedo & rUndoRedo(\n        DocView().GetDocShell()->GetDoc()->GetIDocumentUndoRedo());\n    boost::scoped_ptr pOldField;\n    if (rUndoRedo.DoesUndo())\n    {\n        pOldField.reset(mpFld->Copy());\n    }\n    mpFld->SetPar2(Engine()->GetEditEngine().GetText());\n    mpFld->SetTextObject(Engine()->CreateParaObject());\n    if (rUndoRedo.DoesUndo())\n    {\n        SwTxtFld *const pTxtFld = mpFmtFld->GetTxtFld();\n        SwPosition aPosition( pTxtFld->GetTxtNode() );\n        aPosition.nContent = *pTxtFld->GetStart();\n        rUndoRedo.AppendUndo(\n            new SwUndoFieldFromDoc(aPosition, *pOldField, *mpFld, 0, true));\n    }\n    Engine()->SetModifyHdl( LINK( this, SwAnnotationWin, ModifyHdl ) );\n    Engine()->ClearModifyFlag();\n    Engine()->GetUndoManager().Clear();\n}\n\nSvxLanguageItem SwAnnotationWin::GetLanguage(void)\n{\n    \/\/ set initial language for outliner\n    sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage( mpFld->GetLanguage() );\n    sal_uInt16 nLangWhichId = 0;\n    switch (nScriptType)\n    {\n        case SCRIPTTYPE_LATIN :    nLangWhichId = EE_CHAR_LANGUAGE ; break;\n        case SCRIPTTYPE_ASIAN :    nLangWhichId = EE_CHAR_LANGUAGE_CJK; break;\n        case SCRIPTTYPE_COMPLEX :  nLangWhichId = EE_CHAR_LANGUAGE_CTL; break;\n        default: OSL_FAIL(\"GetLanguage: wrong script type\");\n    }\n    return SvxLanguageItem(mpFld->GetLanguage(),nLangWhichId);\n}\n\nbool SwAnnotationWin::IsProtected()\n{\n    return SwSidebarWin::IsProtected() ||\n           GetLayoutStatus() == SwPostItHelper::DELETED ||\n           ( mpFmtFld ? mpFmtFld->IsProtect() : false );\n}\n\nString SwAnnotationWin::GetAuthor()\n{\n    return mpFld->GetPar1();\n}\n\nDate SwAnnotationWin::GetDate()\n{\n    return mpFld->GetDate();\n}\n\nTime SwAnnotationWin::GetTime()\n{\n    return mpFld->GetTime();\n}\n\n} } \/\/ end of namespace sw::annotation\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA  02110-1301  USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/parsed_interior_qoi.h\"\n\n\/\/ GRINS\n#include \"grins\/multiphysics_sys.h\"\n#include \"grins\/assembly_context.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/fem_system.h\"\n#include \"libmesh\/quadrature.h\"\n#include \"libmesh\/fe_base.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n\nnamespace GRINS\n{\n  ParsedInteriorQoI::ParsedInteriorQoI( const std::string& qoi_name )\n    : QoIBase(qoi_name) {}\n\n  ParsedInteriorQoI::ParsedInteriorQoI( const ParsedInteriorQoI& original )\n    : QoIBase(original.name())\n  {\n    this->qoi_functional = original.qoi_functional->clone();\n  }\n\n  ParsedInteriorQoI::~ParsedInteriorQoI() {}\n\n  QoIBase* ParsedInteriorQoI::clone() const\n  {\n    return new ParsedInteriorQoI( *this );\n  }\n\n  void ParsedInteriorQoI::init( const GetPot& input, const MultiphysicsSystem& system )\n  {\n    std::string qoi_functional_string =\n      input(\"QoI\/ParsedInterior\/\", std::string(\"0\"));\n\n    if (qoi_functional_string == \"0\")\n      libmesh_error_msg(\"Error! Zero ParsedInteriorQoI specified!\" <<\n                        std::endl);\n\n    this->qoi_functional.reset\n      (new libMesh::ParsedFEMFunction\n       (system, qoi_functional_string));\n  }\n\n  void ParsedInteriorQoI::init_context( AssemblyContext& context )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    element_fe->get_JxW();\n    element_fe->get_xyz();\n\n    qoi_functional->init_context(context);\n  }\n\n  void ParsedInteriorQoI::element_qoi( AssemblyContext& context,\n                                       const unsigned int qoi_index )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    const std::vector &JxW = element_fe->get_JxW();\n\n    const std::vector& x_qp = element_fe->get_xyz();\n\n    unsigned int n_qpoints = context.get_element_qrule().n_points();\n\n    \/*! \\todo Need to generalize this to the multiple QoI case *\/\n    libMesh::Number& qoi = context.get_qois()[qoi_index];\n\n    for( unsigned int qp = 0; qp != n_qpoints; qp++ )\n      {\n        const libMesh::Number func_val =\n          (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n        qoi += func_val;\n      }\n  }\n\n  void ParsedInteriorQoI::element_qoi_derivative( AssemblyContext& context,\n                                                  const unsigned int qoi_index )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    const std::vector &JxW = element_fe->get_JxW();\n\n    const std::vector& x_qp = element_fe->get_xyz();\n\n    \/\/ Local DOF count and quadrature point count\n    const unsigned int n_u_dofs = context.get_dof_indices().size();\n\n    unsigned int n_qpoints = context.get_element_qrule().n_points();\n\n    \/\/ Local solution vector - non-const version for finite\n    \/\/ differenting purposes\n    libMesh::DenseVector& elem_solution =\n      const_cast&>\n        (context.get_elem_solution());\n\n    \/*! \\todo Need to generalize this to the multiple QoI case *\/\n    libMesh::DenseVector &Qu =\n      context.get_qoi_derivatives()[qoi_index];\n\n    for( unsigned int qp = 0; qp != n_qpoints; qp++ )\n      {\n        \/\/ Central finite differencing to approximate derivatives.\n        \/\/ FIXME - we should hook the FParserAD stuff into\n        \/\/ ParsedFEMFunction\n\n        for( unsigned int i = 0; i != n_u_dofs; ++i )\n          {\n            libMesh::Number ¤t_solution = elem_solution(i);\n            const libMesh::Number original_solution = current_solution;\n\n            current_solution = original_solution + libMesh::TOLERANCE;\n\n            const libMesh::Number plus_val =\n              (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n            current_solution = original_solution - libMesh::TOLERANCE;\n\n            const libMesh::Number minus_val =\n              (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n            Qu(i) += (plus_val - minus_val) * (0.5 \/ libMesh::TOLERANCE);\n\n            \/\/ Don't forget to restore the correct solution...\n            current_solution = original_solution;\n          }\n      }\n  }\n\n} \/\/namespace GRINS\nFix ParsedInteriorQoI input variable name\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA  02110-1301  USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/parsed_interior_qoi.h\"\n\n\/\/ GRINS\n#include \"grins\/multiphysics_sys.h\"\n#include \"grins\/assembly_context.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/fem_system.h\"\n#include \"libmesh\/quadrature.h\"\n#include \"libmesh\/fe_base.h\"\n#include \"libmesh\/parsed_fem_function.h\"\n\nnamespace GRINS\n{\n  ParsedInteriorQoI::ParsedInteriorQoI( const std::string& qoi_name )\n    : QoIBase(qoi_name) {}\n\n  ParsedInteriorQoI::ParsedInteriorQoI( const ParsedInteriorQoI& original )\n    : QoIBase(original.name())\n  {\n    this->qoi_functional = original.qoi_functional->clone();\n  }\n\n  ParsedInteriorQoI::~ParsedInteriorQoI() {}\n\n  QoIBase* ParsedInteriorQoI::clone() const\n  {\n    return new ParsedInteriorQoI( *this );\n  }\n\n  void ParsedInteriorQoI::init( const GetPot& input, const MultiphysicsSystem& system )\n  {\n    std::string qoi_functional_string =\n      input(\"QoI\/ParsedInterior\/qoi_functional\", std::string(\"0\"));\n\n    if (qoi_functional_string == \"0\")\n      libmesh_error_msg(\"Error! Zero ParsedInteriorQoI specified!\" <<\n                        std::endl);\n\n    this->qoi_functional.reset\n      (new libMesh::ParsedFEMFunction\n       (system, qoi_functional_string));\n  }\n\n  void ParsedInteriorQoI::init_context( AssemblyContext& context )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    element_fe->get_JxW();\n    element_fe->get_xyz();\n\n    qoi_functional->init_context(context);\n  }\n\n  void ParsedInteriorQoI::element_qoi( AssemblyContext& context,\n                                       const unsigned int qoi_index )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    const std::vector &JxW = element_fe->get_JxW();\n\n    const std::vector& x_qp = element_fe->get_xyz();\n\n    unsigned int n_qpoints = context.get_element_qrule().n_points();\n\n    \/*! \\todo Need to generalize this to the multiple QoI case *\/\n    libMesh::Number& qoi = context.get_qois()[qoi_index];\n\n    for( unsigned int qp = 0; qp != n_qpoints; qp++ )\n      {\n        const libMesh::Number func_val =\n          (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n        qoi += func_val;\n      }\n  }\n\n  void ParsedInteriorQoI::element_qoi_derivative( AssemblyContext& context,\n                                                  const unsigned int qoi_index )\n  {\n    libMesh::FEBase* element_fe;\n    context.get_element_fe(0, element_fe);\n    const std::vector &JxW = element_fe->get_JxW();\n\n    const std::vector& x_qp = element_fe->get_xyz();\n\n    \/\/ Local DOF count and quadrature point count\n    const unsigned int n_u_dofs = context.get_dof_indices().size();\n\n    unsigned int n_qpoints = context.get_element_qrule().n_points();\n\n    \/\/ Local solution vector - non-const version for finite\n    \/\/ differenting purposes\n    libMesh::DenseVector& elem_solution =\n      const_cast&>\n        (context.get_elem_solution());\n\n    \/*! \\todo Need to generalize this to the multiple QoI case *\/\n    libMesh::DenseVector &Qu =\n      context.get_qoi_derivatives()[qoi_index];\n\n    for( unsigned int qp = 0; qp != n_qpoints; qp++ )\n      {\n        \/\/ Central finite differencing to approximate derivatives.\n        \/\/ FIXME - we should hook the FParserAD stuff into\n        \/\/ ParsedFEMFunction\n\n        for( unsigned int i = 0; i != n_u_dofs; ++i )\n          {\n            libMesh::Number ¤t_solution = elem_solution(i);\n            const libMesh::Number original_solution = current_solution;\n\n            current_solution = original_solution + libMesh::TOLERANCE;\n\n            const libMesh::Number plus_val =\n              (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n            current_solution = original_solution - libMesh::TOLERANCE;\n\n            const libMesh::Number minus_val =\n              (*qoi_functional)(context, x_qp[qp], context.get_time());\n\n            Qu(i) += (plus_val - minus_val) * (0.5 \/ libMesh::TOLERANCE);\n\n            \/\/ Don't forget to restore the correct solution...\n            current_solution = original_solution;\n          }\n      }\n  }\n\n} \/\/namespace GRINS\n<|endoftext|>"}
{"text":"Deleted unnecessary files<|endoftext|>"}
{"text":"\nDelete 1.cpp<|endoftext|>"}
{"text":"#ifndef AIKIDO_CONTROL_TRAJECTORYEXECUTOR_HPP_\n#define AIKIDO_CONTROL_TRAJECTORYEXECUTOR_HPP_\n\n#include \n#include \n#include \n#include \"aikido\/common\/pointers.hpp\"\n#include \"aikido\/trajectory\/Trajectory.hpp\"\n\nnamespace aikido {\nnamespace control {\n\nAIKIDO_DECLARE_POINTERS(TrajectoryExecutor)\n\n\/\/\/ Abstract class for executing trajectories.\nclass TrajectoryExecutor\n{\npublic:\n  virtual ~TrajectoryExecutor() = default;\n\n  \/\/\/ Validate the traj in preparation for execution.\n  \/\/\/\n  \/\/\/ \\param traj Trajectory to be validated\n  virtual void validate(const trajectory::Trajectory* traj) = 0;\n\n  \/\/\/ Validate and execute traj, setting future upon completion. If a trajectory\n  \/\/\/ is already running, raise an exception unless the executor supports\n  \/\/\/ queuing.\n  \/\/\/\n  \/\/\/ \\param _traj Trajectory to be executed.\n  \/\/\/ \\return future for trajectory execution. If trajectory terminates\n  \/\/\/        before completion, future will be set to a runtime_error.\n  virtual std::future execute(const trajectory::ConstTrajectoryPtr& traj)\n      = 0;\n\n  \/\/\/ Step to a point in time.\n  \/\/\/ \\note \\c timepoint can be a time in the future to enable faster than\n  \/\/\/ real-time execution.\n  \/\/\/\n  \/\/\/ \\param timepoint Time to simulate to\n  virtual void step(const std::chrono::system_clock::time_point& timepoint) = 0;\n\n  \/\/\/ Abort the current trajectory.\n  \/\/\/ \\note This is currently only supported in simulation.\n  virtual void abort() = 0;\n\nprotected:\n  \/\/\/ Set of trajectories validated by executor\n  std::set mValidatedTrajectories;\n\n  \/\/\/ Time of previous call\n  std::chrono::system_clock::time_point mExecutionStartTime;\n};\n\n} \/\/ namespace control\n} \/\/ namespace aikido\n\n#endif\nFix documentation typo. (#406)#ifndef AIKIDO_CONTROL_TRAJECTORYEXECUTOR_HPP_\n#define AIKIDO_CONTROL_TRAJECTORYEXECUTOR_HPP_\n\n#include \n#include \n#include \n#include \"aikido\/common\/pointers.hpp\"\n#include \"aikido\/trajectory\/Trajectory.hpp\"\n\nnamespace aikido {\nnamespace control {\n\nAIKIDO_DECLARE_POINTERS(TrajectoryExecutor)\n\n\/\/\/ Abstract class for executing trajectories.\nclass TrajectoryExecutor\n{\npublic:\n  virtual ~TrajectoryExecutor() = default;\n\n  \/\/\/ Validate the traj in preparation for execution.\n  \/\/\/\n  \/\/\/ \\param traj Trajectory to be validated\n  virtual void validate(const trajectory::Trajectory* traj) = 0;\n\n  \/\/\/ Validate and execute traj, setting future upon completion. If a trajectory\n  \/\/\/ is already running, raise an exception unless the executor supports\n  \/\/\/ queuing.\n  \/\/\/\n  \/\/\/ \\param traj Trajectory to be executed.\n  \/\/\/ \\return future for trajectory execution. If trajectory terminates\n  \/\/\/        before completion, future will be set to a runtime_error.\n  virtual std::future execute(const trajectory::ConstTrajectoryPtr& traj)\n      = 0;\n\n  \/\/\/ Step to a point in time.\n  \/\/\/ \\note \\c timepoint can be a time in the future to enable faster than\n  \/\/\/ real-time execution.\n  \/\/\/\n  \/\/\/ \\param timepoint Time to simulate to\n  virtual void step(const std::chrono::system_clock::time_point& timepoint) = 0;\n\n  \/\/\/ Abort the current trajectory.\n  \/\/\/ \\note This is currently only supported in simulation.\n  virtual void abort() = 0;\n\nprotected:\n  \/\/\/ Set of trajectories validated by executor\n  std::set mValidatedTrajectories;\n\n  \/\/\/ Time of previous call\n  std::chrono::system_clock::time_point mExecutionStartTime;\n};\n\n} \/\/ namespace control\n} \/\/ namespace aikido\n\n#endif\n<|endoftext|>"}
{"text":"\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#ifndef COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C\n#define COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C\n\n#include \n#include \n#include \n\n#include \"member_like_base.hpp\"\n\nnamespace commata {\nnamespace detail {\n\nnamespace allocation_only {\n\ntemplate \nstruct reference_forwarded\n{\n    using type = typename A::value_type&;\n};\n\ntemplate \nstruct reference_forwarded\n{\n    using type = typename A::reference;\n};\n\ntemplate \nstruct const_reference_forwarded\n{\n    using type = const typename A::value_type&;\n};\n\ntemplate \nstruct const_reference_forwarded\n{\n    using type = typename A::const_reference;\n};\n\n} \/\/ end allocation_only\n\ntemplate \nclass allocation_only_allocator :\n    member_like_base\n{\n    using base_traits_t = typename std::allocator_traits;\n\n    \/\/ To rebind\n    template \n    friend class allocation_only_allocator;\n\npublic:\n    using pointer = typename base_traits_t::pointer;\n    using const_pointer = typename base_traits_t::const_pointer;\n    using void_pointer = typename base_traits_t::void_pointer;\n    using const_void_pointer = typename base_traits_t::const_void_pointer;\n    using value_type = typename base_traits_t::value_type;\n    using size_type = typename base_traits_t::size_type;\n    using difference_type = typename base_traits_t::difference_type;\n\n    \/\/ These types are not required by the C++14 standard, but\n    \/\/ std::basic_string which comes with gcc 7.3.1 seems to do\n    using reference =\n        typename allocation_only::reference_forwarded::type;\n    using const_reference =\n        typename allocation_only::const_reference_forwarded::type;\n\n    template \n    struct rebind\n    {\n        using other = allocation_only_allocator<\n            typename base_traits_t::template rebind_alloc>;\n    };\n\n    \/\/ Default-constructibility of an allocator is not mandated by the C++14\n    \/\/ standard, but std::basic_string which comes with gcc 7.3.1 requires it\n    allocation_only_allocator() = default;\n\n    \/\/ To make wrappers\n    explicit allocation_only_allocator(const Allocator& other) noexcept :\n        member_like_base(other)\n    {}\n\n    \/\/ ditto\n    explicit allocation_only_allocator(Allocator&& other) noexcept :\n        member_like_base(std::move(other))\n    {}\n\n    \/\/ To make rebound copies\n    template \n    explicit allocation_only_allocator(\n        const allocation_only_allocator& other) noexcept :\n        member_like_base(other.base())\n    {}\n\n    \/\/ ditto\n    template \n    explicit allocation_only_allocator(\n        allocation_only_allocator&& other) noexcept :\n        member_like_base(std::move(other.base()))\n    {}\n\n    \/\/ copy\/move ctor\/assignment ops are defaulted\n\n    template \n    auto allocate(size_type n, Args&&... args)\n    {\n        return base_traits_t::allocate(base(),\n            n, std::forward(args)...);\n    }\n\n    auto deallocate(pointer p, size_type n) noexcept\n    {\n        return base_traits_t::deallocate(base(), p, n);\n    }\n\n    auto max_size() noexcept(noexcept(\n        base_traits_t::max_size(std::declval())))\n    {\n        return base_traits_t::max_size(base());\n    }\n\n    template \n    void construct(T* p, Args&&... args)\n    {\n        ::new(p) T(std::forward(args)...);\n    }\n\n    template \n    void destroy(T* p)\n    {\n        destroy(p, std::is_trivially_destructible());\n    }\n\n    auto select_on_container_copy_construction() const noexcept(noexcept(\n        base_traits_t::select_on_container_copy_construction(\n            std::declval())))\n    {\n        return base_traits_t::select_on_container_copy_construction(base());\n    }\n\n    using propagate_on_container_copy_assignment =\n        typename base_traits_t::propagate_on_container_copy_assignment;\n    using propagate_on_container_move_assignment =\n        typename base_traits_t::propagate_on_container_move_assignment;\n    using propagate_on_container_swap =\n        typename base_traits_t::propagate_on_container_swap;\n\n    decltype(auto) base() noexcept\n    {\n        return this->get();\n    }\n\n    decltype(auto) base() const noexcept\n    {\n        return this->get();\n    }\n\nprivate:\n    template \n    void destroy(T*, std::true_type)\n    {}\n\n    template \n    void destroy(T* p, std::false_type)\n    {\n        p->~T();\n    }\n};\n\ntemplate \nbool operator==(\n    const allocation_only_allocator& left,\n    const allocation_only_allocator& right) noexcept\n{\n    return left.base() == right.base();\n}\n\ntemplate \nbool operator!=(\n    const allocation_only_allocator& left,\n    const allocation_only_allocator& right) noexcept\n{\n    return left.base() != right.base();\n}\n\n}}\n\n#endif\nRefactor allocation_only_allocator\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#ifndef COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C\n#define COMMATA_GUARD_F6071085_9476_4724_95ED_E1DA376E837C\n\n#include \n#include \n#include \n\n#include \"member_like_base.hpp\"\n\nnamespace commata {\nnamespace detail {\n\nnamespace allocation_only {\n\ntemplate \nstruct reference_forwarded\n{\n    using type = typename A::value_type&;\n};\n\ntemplate \nstruct reference_forwarded\n{\n    using type = typename A::reference;\n};\n\ntemplate \nstruct const_reference_forwarded\n{\n    using type = const typename A::value_type&;\n};\n\ntemplate \nstruct const_reference_forwarded\n{\n    using type = typename A::const_reference;\n};\n\n} \/\/ end allocation_only\n\ntemplate \nclass allocation_only_allocator :\n    member_like_base\n{\n    using base_traits_t = typename std::allocator_traits;\n\npublic:\n    using pointer = typename base_traits_t::pointer;\n    using const_pointer = typename base_traits_t::const_pointer;\n    using void_pointer = typename base_traits_t::void_pointer;\n    using const_void_pointer = typename base_traits_t::const_void_pointer;\n    using value_type = typename base_traits_t::value_type;\n    using size_type = typename base_traits_t::size_type;\n    using difference_type = typename base_traits_t::difference_type;\n\n    \/\/ These types are not required by the C++14 standard, but\n    \/\/ std::basic_string which comes with gcc 7.3.1 seems to do\n    using reference =\n        typename allocation_only::reference_forwarded::type;\n    using const_reference =\n        typename allocation_only::const_reference_forwarded::type;\n\n    template \n    struct rebind\n    {\n        using other = allocation_only_allocator<\n            typename base_traits_t::template rebind_alloc>;\n    };\n\n    \/\/ Default-constructibility of an allocator is not mandated by the C++14\n    \/\/ standard, but std::basic_string which comes with gcc 7.3.1 requires it\n    allocation_only_allocator() = default;\n\n    \/\/ To make wrappers\n    explicit allocation_only_allocator(const A& other)\n            noexcept(std::is_nothrow_copy_constructible::value):\n        member_like_base(other)\n    {}\n\n    \/\/ ditto\n    explicit allocation_only_allocator(A&& other)\n            noexcept(std::is_nothrow_move_constructible::value) :\n        member_like_base(std::move(other))\n    {}\n\n    \/\/ To make rebound copies\n    template \n    explicit allocation_only_allocator(\n        const allocation_only_allocator& other)\n            noexcept(std::is_nothrow_constructible::value) :\n        member_like_base(other.base())\n    {}\n\n    \/\/ ditto\n    template \n    explicit allocation_only_allocator(\n        allocation_only_allocator&& other)\n            noexcept(std::is_nothrow_constructible::value) :\n        member_like_base(std::move(other.base()))\n    {}\n\n    \/\/ copy\/move ctor\/assignment ops are defaulted\n\n    template \n    auto allocate(size_type n, Args&&... args)\n    {\n        return base_traits_t::allocate(base(), n, std::forward(args)...);\n    }\n\n    auto deallocate(pointer p, size_type n)\n    {\n        return base_traits_t::deallocate(base(), p, n);\n    }\n\n    size_type max_size() const noexcept\n        \/\/ this noexceptness is mandated in the spec of\n        \/\/ std::allocator_traits::max_size\n    {\n        return base_traits_t::max_size(base());\n    }\n\n    template \n    void construct(T* p, Args&&... args)\n    {\n        ::new(p) T(std::forward(args)...);\n    }\n\n    template \n    void destroy(T* p)\n    {\n        destroy(p, std::is_trivially_destructible());\n    }\n\n    allocation_only_allocator select_on_container_copy_construction() const\n        noexcept(noexcept(base_traits_t::select_on_container_copy_construction(\n                            std::declval())))\n    {\n        return base_traits_t::select_on_container_copy_construction(base());\n    }\n\n    using propagate_on_container_copy_assignment =\n        typename base_traits_t::propagate_on_container_copy_assignment;\n    using propagate_on_container_move_assignment =\n        typename base_traits_t::propagate_on_container_move_assignment;\n    using propagate_on_container_swap =\n        typename base_traits_t::propagate_on_container_swap;\n\n    decltype(auto) base() noexcept\n    {\n        return this->get();\n    }\n\n    decltype(auto) base() const noexcept\n    {\n        return this->get();\n    }\n\nprivate:\n    template \n    void destroy(T*, std::true_type)\n    {}\n\n    template \n    void destroy(T* p, std::false_type)\n    {\n        p->~T();\n    }\n};\n\ntemplate \nbool operator==(\n    const allocation_only_allocator& left,\n    const allocation_only_allocator& right)\n    noexcept(noexcept(std::declval()\n                   == std::declval()))\n{\n    return left.base() == right.base();\n}\n\ntemplate \nbool operator==(\n    const allocation_only_allocator& left,\n    const AllocatorR& right)\n    noexcept(noexcept(std::declval()\n                   == std::declval()))\n{\n    return left.base() == right;\n}\n\ntemplate \nbool operator==(\n    const AllocatorL& left,\n    const allocation_only_allocator& right)\n    noexcept(noexcept(std::declval()\n                   == std::declval()))\n{\n    return left == right.base();\n}\n\ntemplate \nbool operator!=(\n    const allocation_only_allocator& left,\n    const allocation_only_allocator& right)\n    noexcept(noexcept(std::declval()\n                   != std::declval()))\n{\n    return left.base() != right.base();\n}\n\ntemplate \nbool operator!=(\n    const allocation_only_allocator& left,\n    const AllocatorR& right)\n    noexcept(noexcept(std::declval()\n                   != std::declval()))\n{\n    return left.base() != right;\n}\n\ntemplate \nbool operator!=(\n    const AllocatorL& left,\n    const allocation_only_allocator& right)\n    noexcept(noexcept(std::declval()\n                   != std::declval()))\n{\n    return left != right.base();\n}\n}}\n\n#endif\n<|endoftext|>"}
{"text":"#ifndef DATATRANSFER_BINARY_SERIALIZATION_HPP\n#define DATATRANSFER_BINARY_SERIALIZATION_HPP\n\n#include \n\nnamespace datatransfer\n{\n\nstruct binary_serialization\n{\n    template \n    class write_policy\n    {\n    public:\n        using stream_type = output_stream;\n        output_stream& os;\n\n        write_policy(output_stream& os) : os(os) {}\n\n        template \n        write_policy& operator% (T& x)\n        {\n            operate(x);\n\n            return *this;\n        }\n\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n        template \n        void operate(T& t)\n        {\n            t.template method >(os);\n        }\n\n    protected:\n        void operate(int& x)\t\t\t{ write(x); }\n        void operate(float& x)\t\t\t{ write(x); }\n        void operate(double& x)\t\t\t{ write(x); }\n        void operate(char& x)\t\t\t{ write(x); }\n        void operate(uint8_t& x)\t\t{ write(x); }\n        void operate(bool& x)\t\t\t{ write(x); }\n        void operate(uint64_t& x)\t\t{ write(x); }\n\n    private:\n        template \n        void write(const T& t)\n        {\n            \/\/ Assume little endian encoding\n            os.write(reinterpret_cast(&t), sizeof(T));\n        }\n    };\n\n    template \n    struct read_policy\n    {\n        using stream_type = input_stream;\n        input_stream& is;\n\n        read_policy(input_stream& is) : is(is) {}\n\n        template \n        read_policy& operator% (T& x)\n        {\n            operate(x);\n\n            return *this;\n        }\n\n    protected:\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n    public:\n        template \n        void operate(T& t)\n        {\n            t.template method >(is);\n        }\n\n        bool operate(int& x) \t\t{ return read(x); }\n        bool operate(float& x) \t\t{ return read(x); }\n        bool operate(double& x) \t{ return read(x); }\n        bool operate(char& x)   \t{ return read(x); }\n        bool operate(bool& x)   \t{ return read(x); }\n        bool operate(uint64_t& x)\t{ return read(x); }\n\n        template \n        bool read(T& t)\n        {\n            \/\/ Assume little endian encoding\n\t\t\tconst auto n = sizeof(T);\n\t\t\treturn is.read(reinterpret_cast(&t), n) == n;\n        }\n    };\n\n    class checksum_policy\n    {\n    private:\n        uint8_t& _checksum;\n\n    public:\n        using data_type = uint8_t;\n        using stream_type = data_type;\n\n        checksum_policy(data_type& checksum)\n            : _checksum(checksum)\n        {}\n\n        uint8_t checksum() const { return _checksum; }\n\n        template \n        void operator% (T& x)\n        {\n            operate(x);\n        }\n\n    protected:\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n        template \n        void operate(T& t)\n        {\n            t.template method(_checksum);\n        }\n\n        void operate(float& x) \t\t{ read(x); }\n        void operate(double& x) \t{ read(x); }\n        void operate(char& x)   \t{ read(x); }\n        void operate(bool& x)   \t{ read(x); }\n        void operate(uint8_t& x)    { read(x); }\n        void operate(uint64_t& x)\t{ read(x); }\n\n        template \n        void read(T& t)\n        {\n            \/\/ Assume little endian encoding\n            auto* buf = reinterpret_cast(&t);\n            for (int i = 0; i < sizeof(T); ++i)\n                _checksum ^= buf[i];\n        }\n    };\n};\n\n}\n\n#endif \/\/ DATATRANSFER_BINARY_SERIALIZATION_HPP\nInitialise checksum value#ifndef DATATRANSFER_BINARY_SERIALIZATION_HPP\n#define DATATRANSFER_BINARY_SERIALIZATION_HPP\n\n#include \n\nnamespace datatransfer\n{\n\nstruct binary_serialization\n{\n    template \n    class write_policy\n    {\n    public:\n        using stream_type = output_stream;\n        output_stream& os;\n\n        write_policy(output_stream& os) : os(os) {}\n\n        template \n        write_policy& operator% (T& x)\n        {\n            operate(x);\n\n            return *this;\n        }\n\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n        template \n        void operate(T& t)\n        {\n            t.template method >(os);\n        }\n\n    protected:\n        void operate(int& x)\t\t\t{ write(x); }\n        void operate(float& x)\t\t\t{ write(x); }\n        void operate(double& x)\t\t\t{ write(x); }\n        void operate(char& x)\t\t\t{ write(x); }\n        void operate(uint8_t& x)\t\t{ write(x); }\n        void operate(bool& x)\t\t\t{ write(x); }\n        void operate(uint64_t& x)\t\t{ write(x); }\n\n    private:\n        template \n        void write(const T& t)\n        {\n            \/\/ Assume little endian encoding\n            os.write(reinterpret_cast(&t), sizeof(T));\n        }\n    };\n\n    template \n    struct read_policy\n    {\n        using stream_type = input_stream;\n        input_stream& is;\n\n        read_policy(input_stream& is) : is(is) {}\n\n        template \n        read_policy& operator% (T& x)\n        {\n            operate(x);\n\n            return *this;\n        }\n\n    protected:\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n    public:\n        template \n        void operate(T& t)\n        {\n            t.template method >(is);\n        }\n\n        bool operate(int& x) \t\t{ return read(x); }\n        bool operate(float& x) \t\t{ return read(x); }\n        bool operate(double& x) \t{ return read(x); }\n        bool operate(char& x)   \t{ return read(x); }\n        bool operate(bool& x)   \t{ return read(x); }\n        bool operate(uint64_t& x)\t{ return read(x); }\n\n        template \n        bool read(T& t)\n        {\n            \/\/ Assume little endian encoding\n\t\t\tconst auto n = sizeof(T);\n\t\t\treturn is.read(reinterpret_cast(&t), n) == n;\n        }\n    };\n\n    class checksum_policy\n    {\n    private:\n        uint8_t& _checksum;\n\n    public:\n        using data_type = uint8_t;\n        using stream_type = data_type;\n\n        checksum_policy(data_type& checksum)\n            : _checksum(checksum)\n        {\n            _checksum = 0;\n        }\n\n        uint8_t checksum() const { return _checksum; }\n\n        template \n        void operator% (T& x)\n        {\n            operate(x);\n        }\n\n    protected:\n        template \n        void operate(Eigen::Matrix& matrix)\n        {\n            for (int j = 0; j < N; j++)\n            {\n                for (int i = 0; i < M; i++)\n                {\n                    operate(matrix(i,j));\n                }\n            }\n        }\n\n        template \n        void operate(T& t)\n        {\n            t.template method(_checksum);\n        }\n\n        void operate(float& x) \t\t{ read(x); }\n        void operate(double& x) \t{ read(x); }\n        void operate(char& x)   \t{ read(x); }\n        void operate(bool& x)   \t{ read(x); }\n        void operate(uint8_t& x)    { read(x); }\n        void operate(uint64_t& x)\t{ read(x); }\n\n        template \n        void read(T& t)\n        {\n            \/\/ Assume little endian encoding\n            auto* buf = reinterpret_cast(&t);\n            for (int i = 0; i < sizeof(T); ++i)\n                _checksum ^= buf[i];\n        }\n    };\n};\n\n}\n\n#endif \/\/ DATATRANSFER_BINARY_SERIALIZATION_HPP\n<|endoftext|>"}
{"text":"\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file moments.hpp\n * \\date May 2014\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP\n#define FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP\n\n#include \n#include \n#include \n\nnamespace fl\n{\n\n\/\/ Forward declaration\ntemplate  class Moments;\n\n\/**\n * \\ingroup distribution_interfaces\n *\n * \\brief Represents the interface providing the first two moments\n *\n * \\tparam Variate        Random variable type. This is equivalent to the first\n *                        moment type.\n * \\tparam SecondMoment   Second moment type. The second moment is either\n *                        the second uncentered moment \\f$Var(X) + X^2\\f$ or\n *                        simply the second central moment, the variance or\n *                        covariance \\f$Var(X) = Cov(X, X)\\f$. Both have the\n *                        same type \\c SecondMoment.\n *\n *\n * The Moments interface provides access to the exact first moments of\n * a distribution. The moments represent a subset of the approximate moments.\n *\/\ntemplate \nclass Moments\n    : public ApproximateMoments\n{\npublic:\n    \/**\n     * \\brief Variate Random variable type. This is equivalent to the first\n     *        moment type.\n     *\/\n    typedef Variate_ Variate;\n\n    \/**\n     * \\brief Second central moment type (e.g. Variance or the Covariance)\n     *\/\n    typedef SecondMoment_ SecondMoment;\n\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n\n    \/**\n     * \\return First moment of the underlying distribution, the mean\n     *\n     * \\f$ \\mu = \\sum\\limits_i x_i p(x_i)\\f$\n     *\/\n    virtual const Variate& mean() const = 0;\n\n    \/**\n     * \\return Second centered moment of the underlying distribution,\n     *         the covariance\n     *\n     * \\f$ \\Sigma =\n     *     \\sum\\limits_i (x_i - \\mu)(x_i - \\mu)^T \\f$\n     *\/\n    virtual const SecondMoment& covariance() const = 0;\n\n    \/**\n     * \\copydoc ApproximateMoments::approximate_mean\n     *\/\n    virtual const Variate& approximate_mean() const\n    {\n        return mean();\n    }\n\n    \/**\n     * \\copydoc ApproximateMoments::approximate_covariance\n     *\/\n    virtual const SecondMoment& approximate_covariance() const\n    {\n        return covariance();\n    }\n};\n\n\/**\n * \\ingroup distribution_interfaces\n *\/\ntemplate \nclass Moments\n    : public Moments::Type>\n{\npublic:\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n};\n\n\/**\n * \\ingroup distribution_interfaces\n *\/\ntemplate <>\nclass Moments\n    : public Moments\n{\npublic:\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n};\n\n}\n\n#endif\nadded Doxygen workaround for template specialization\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file moments.hpp\n * \\date May 2014\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP\n#define FL__DISTRIBUTION__INTERFACE__MOMENTS_HPP\n\n#include \n#include \n#include \n\nnamespace fl\n{\n\n#ifndef GENERATING_DOCUMENTATION\n\/\/ Forward declaration\ntemplate  class Moments;\n#endif\n\n\/**\n * \\ingroup distribution_interfaces\n *\n * \\brief Represents the interface providing the first two moments\n *\n * \\tparam Variate        Random variable type. This is equivalent to the first\n *                        moment type.\n * \\tparam SecondMoment   Second moment type. The second moment is either\n *                        the second uncentered moment \\f$Var(X) + X^2\\f$ or\n *                        simply the second central moment, the variance or\n *                        covariance \\f$Var(X) = Cov(X, X)\\f$. Both have the\n *                        same type \\c SecondMoment.\n *\n *\n * The Moments interface provides access to the exact first moments of\n * a distribution. The moments represent a subset of the approximate moments.\n *\/\ntemplate \n#ifndef GENERATING_DOCUMENTATION\nclass Moments\n#else\nclass Moments\n#endif\n    : public ApproximateMoments\n{\npublic:\n    \/**\n     * \\brief Variate Random variable type. This is equivalent to the first\n     *        moment type.\n     *\/\n    typedef Variate_ Variate;\n\n    \/**\n     * \\brief Second central moment type (e.g. Variance or the Covariance)\n     *\/\n    typedef SecondMoment_ SecondMoment;\n\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n\n    \/**\n     * \\return First moment of the underlying distribution, the mean\n     *\n     * \\f$ \\mu = \\sum\\limits_i x_i p(x_i)\\f$\n     *\/\n    virtual const Variate& mean() const = 0;\n\n    \/**\n     * \\return Second centered moment of the underlying distribution,\n     *         the covariance\n     *\n     * \\f$ \\Sigma =\n     *     \\sum\\limits_i (x_i - \\mu)(x_i - \\mu)^T \\f$\n     *\/\n    virtual const SecondMoment& covariance() const = 0;\n\n    \/**\n     * \\copydoc ApproximateMoments::approximate_mean\n     *\/\n    virtual const Variate& approximate_mean() const\n    {\n        return mean();\n    }\n\n    \/**\n     * \\copydoc ApproximateMoments::approximate_covariance\n     *\/\n    virtual const SecondMoment& approximate_covariance() const\n    {\n        return covariance();\n    }\n};\n\n\/**\n * \\ingroup distribution_interfaces\n *\n *\/\ntemplate \nclass Moments\n    : public Moments::Type>\n{\npublic:\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n};\n\n\/**\n * \\ingroup distribution_interfaces\n *\n *\/\ntemplate < >\nclass Moments\n    : public Moments\n{\npublic:\n    \/**\n     * \\brief Overridable default destructor\n     *\/\n    virtual ~Moments() { }\n};\n\n}\n\n#endif\n<|endoftext|>"}
{"text":"namespace mant {\n  template \n  \/\/ TODO Add random translation, ... xy methods\n  class OptimisationProblem : public Printable {\n    public:\n      const unsigned int numberOfDimensions_;\n\n      explicit OptimisationProblem(\n        const unsigned int& numberOfDimensions) noexcept;\n\n      void setLowerBounds(\n        const arma::Col lowerBounds);\n\n      void setUpperBounds(\n        const arma::Col upperBounds);\n\n      arma::Col getLowerBounds() const noexcept;\n\n      arma::Col getUpperBounds() const noexcept;\n\n      double getSoftConstraintsValue(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingLowerBounds(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingUpperBounds(\n        const arma::Col& parameter);\n\n      bool isSatisfyingSoftConstraints(\n        const arma::Col& parameter);\n\n      bool isSatisfyingConstraints(\n        const arma::Col& parameter);\n\n      void setParameterPermutation(\n          const arma::Col parameterPermutation);\n\n      void setParameterTranslation(\n          const arma::Col parameterTranslation);\n\n      void setParameterScaling(\n        const arma::Col parameterScaling);\n\n      void setParameterRotation(\n        const arma::Mat parameterRotation);\n\n      void setObjectiveValueTranslation(\n        const double objectiveValueTranslation) noexcept;\n\n      void setObjectiveValueScaling(\n        const double objectiveValueScaling) noexcept;\n      \n      void setAcceptableObjectiveValue(\n          const double acceptableObjectiveValue) noexcept;\n        \n      double getAcceptableObjectiveValue() const noexcept;\n\n      double getObjectiveValue(\n        const arma::Col& parameter);\n\n      unsigned int getNumberOfEvaluations() const noexcept;\n\n      unsigned int getNumberOfDistinctEvaluations() const noexcept;\n\n      void reset() noexcept;\n\n      std::unordered_map, double, Hash, IsEqual> getCachedObjectiveValues() const noexcept;\n\n      virtual ~OptimisationProblem() = default;\n\n    protected:\n      arma::Col lowerBounds_;\n      arma::Col upperBounds_;\n\n      arma::Col parameterPermutation_;\n      arma::Col parameterTranslation_;\n      arma::Col parameterScaling_;\n      arma::Mat parameterRotation_;\n\n      double objectiveValueTranslation_;\n      double objectiveValueScaling_;\n\n      double acceptableObjectiveValue_;\n\n      unsigned int numberOfEvaluations_;\n      unsigned int numberOfDistinctEvaluations_;\n\n      arma::Col getDiversifiedParameter(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getSoftConstraintsValueImplementation(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getObjectiveValueImplementation(\n        const arma::Col& parameter) const noexcept = 0;\n\n      std::unordered_map, double, Hash, IsEqual> cachedObjectiveValues_;\n\n #if defined(MANTELLA_USE_PARALLEL)\n      friend class cereal::access;\n      OptimisationProblem() = default;\n      \n      template \n      void serialize(\n          Archive& archive) noexcept {\n        archive(cereal::make_nvp(\"numberOfDimensions\", numberOfDimensions_));\n        archive(cereal::make_nvp(\"lowerBounds\", lowerBounds_));\n        archive(cereal::make_nvp(\"upperBounds\", upperBounds_));\n        archive(cereal::make_nvp(\"parameterTranslation\", parameterTranslation_));\n        archive(cereal::make_nvp(\"parameterRotation\", parameterRotation_));\n        archive(cereal::make_nvp(\"parameterScaling\", parameterScaling_));\n        archive(cereal::make_nvp(\"objectiveValueTranslation\", objectiveValueTranslation_));\n        archive(cereal::make_nvp(\"objectiveValueScaling\", objectiveValueScaling_));\n        archive(cereal::make_nvp(\"acceptableObjectiveValue\", acceptableObjectiveValue_));\n      }\n#endif\n  };\n\n  \/\/\n  \/\/ Implementation\n  \/\/\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept;\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation);\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation);\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling);\n\n  template <>\n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept;\n\n  template \n  OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterPermutation(arma::linspace>(0, numberOfDimensions_ - 1, numberOfDimensions));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScaling(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterPermutation(arma::linspace>(0, numberOfDimensions_ - 1, numberOfDimensions));\n    setParameterTranslation(arma::zeros>(numberOfDimensions_));\n    setParameterRotation(arma::eye>(numberOfDimensions_, numberOfDimensions_));\n    setParameterScaling(arma::ones>(numberOfDimensions_));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScaling(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingLowerBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter >= lowerBounds_);\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingUpperBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter <= upperBounds_);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingSoftConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (getSoftConstraintsValue(parameter) == 0);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n    \n    return (arma::all(isSatisfyingLowerBounds(parameter)) && arma::all(isSatisfyingUpperBounds(parameter)) && isSatisfyingSoftConstraints(parameter));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return objectiveValueScaling_ * getSoftConstraintsValueImplementation(parameter);\n  }\n\n  template \n  inline double OptimisationProblem::getObjectiveValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    \/\/ Always increase the number of evaluations (whether its computed or retrived from cache).\n    ++numberOfEvaluations_;\n\n    \/\/ Check if the result is already cached.\n    const auto& cachePosition = cachedObjectiveValues_.find(parameter);\n    if (cachePosition == cachedObjectiveValues_.cend()) {\n      \/\/ Increase the number of distinct evaluations only if we actually compute the value.\n      ++numberOfDistinctEvaluations_;\n\n      \/\/ The result was not found, compute it.\n      const double& result = objectiveValueScaling_ * getObjectiveValueImplementation(getDiversifiedParameter(parameter)) + objectiveValueTranslation_;\n      cachedObjectiveValues_.insert({parameter, result});\n      return result;\n    } else {\n      \/\/ Return the found result.\n      return cachePosition->second;\n    }\n  }\n\n  template \n  arma::Col OptimisationProblem::getLowerBounds() const noexcept {\n    return lowerBounds_;\n  }\n\n  template \n  void OptimisationProblem::setLowerBounds(\n      const arma::Col lowerBounds) {\n    checkDimensionCompatible(\"The number of elements\", lowerBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    lowerBounds_ = lowerBounds;\n  }\n\n  template \n  arma::Col OptimisationProblem::getUpperBounds() const noexcept {\n    return upperBounds_;\n  }\n\n  template \n  void OptimisationProblem::setUpperBounds(\n      const arma::Col upperBounds) {\n    checkDimensionCompatible(\"The number of elements\", upperBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    upperBounds_ = upperBounds;\n  }\n\n  template \n  inline void OptimisationProblem::setParameterPermutation(\n      const arma::Col parameterPermutation) {\n    \/\/ TODO Check if this is actually a permutaion\n    checkDimensionCompatible(\"The number of elements\", parameterPermutation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterPermutation_ = parameterPermutation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation) {\n    checkDimensionCompatible(\"The number of elements\", parameterTranslation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterTranslation_ = parameterTranslation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation) {\n    checkDimensionCompatible(\"The number of rows\", parameterRotation.n_rows, \"the number of dimensions\", numberOfDimensions_);\n    checkRotationMatrix(\"The matrix\", parameterRotation);\n\n    parameterRotation_ = parameterRotation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling) {\n    checkDimensionCompatible(\"The number of elements\", parameterScaling.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterScaling_ = parameterScaling;\n  }\n\n  template \n  void OptimisationProblem::setObjectiveValueTranslation(\n      const double objectiveValueTranslation) noexcept {\n    objectiveValueTranslation_ = objectiveValueTranslation;\n  }\n\n  template \n  void OptimisationProblem::OptimisationProblem::setObjectiveValueScaling(\n      const double objectiveValueScaling) noexcept {\n    objectiveValueScaling_ = objectiveValueScaling;\n  }\n\n  template \n  double OptimisationProblem::getAcceptableObjectiveValue() const noexcept {\n    return acceptableObjectiveValue_;\n  }\n\n  template \n  void OptimisationProblem::setAcceptableObjectiveValue(\n      const double acceptableObjectiveValue) noexcept {\n    acceptableObjectiveValue_ = acceptableObjectiveValue;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfEvaluations() const noexcept {\n    return numberOfEvaluations_;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfDistinctEvaluations() const noexcept {\n    return numberOfDistinctEvaluations_;\n  }\n\n  template \n  void OptimisationProblem::reset() noexcept {\n    numberOfEvaluations_ = 0;\n    numberOfDistinctEvaluations_ = 0;\n\n    cachedObjectiveValues_.clear();\n  }\n\n  template \n  std::unordered_map, double, Hash, IsEqual> OptimisationProblem::getCachedObjectiveValues() const noexcept {\n    return cachedObjectiveValues_;\n  }\n\n  template \n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameter.elem(parameterPermutation_);\n  }\n\n  template <>\n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameterRotation_ * (parameterScaling_ % parameter.elem(parameterPermutation_) - parameterTranslation_);\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValueImplementation(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return 0.0;\n  }\n}\nRemoved completed ToDo [ci skip]namespace mant {\n  template \n  class OptimisationProblem : public Printable {\n    public:\n      const unsigned int numberOfDimensions_;\n\n      explicit OptimisationProblem(\n        const unsigned int& numberOfDimensions) noexcept;\n\n      void setLowerBounds(\n        const arma::Col lowerBounds);\n\n      void setUpperBounds(\n        const arma::Col upperBounds);\n\n      arma::Col getLowerBounds() const noexcept;\n\n      arma::Col getUpperBounds() const noexcept;\n\n      double getSoftConstraintsValue(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingLowerBounds(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingUpperBounds(\n        const arma::Col& parameter);\n\n      bool isSatisfyingSoftConstraints(\n        const arma::Col& parameter);\n\n      bool isSatisfyingConstraints(\n        const arma::Col& parameter);\n\n      void setParameterPermutation(\n          const arma::Col parameterPermutation);\n\n      void setParameterTranslation(\n          const arma::Col parameterTranslation);\n\n      void setParameterScaling(\n        const arma::Col parameterScaling);\n\n      void setParameterRotation(\n        const arma::Mat parameterRotation);\n\n      void setObjectiveValueTranslation(\n        const double objectiveValueTranslation) noexcept;\n\n      void setObjectiveValueScaling(\n        const double objectiveValueScaling) noexcept;\n      \n      void setAcceptableObjectiveValue(\n          const double acceptableObjectiveValue) noexcept;\n        \n      double getAcceptableObjectiveValue() const noexcept;\n\n      double getObjectiveValue(\n        const arma::Col& parameter);\n\n      unsigned int getNumberOfEvaluations() const noexcept;\n\n      unsigned int getNumberOfDistinctEvaluations() const noexcept;\n\n      void reset() noexcept;\n\n      std::unordered_map, double, Hash, IsEqual> getCachedObjectiveValues() const noexcept;\n\n      virtual ~OptimisationProblem() = default;\n\n    protected:\n      arma::Col lowerBounds_;\n      arma::Col upperBounds_;\n\n      arma::Col parameterPermutation_;\n      arma::Col parameterTranslation_;\n      arma::Col parameterScaling_;\n      arma::Mat parameterRotation_;\n\n      double objectiveValueTranslation_;\n      double objectiveValueScaling_;\n\n      double acceptableObjectiveValue_;\n\n      unsigned int numberOfEvaluations_;\n      unsigned int numberOfDistinctEvaluations_;\n\n      arma::Col getDiversifiedParameter(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getSoftConstraintsValueImplementation(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getObjectiveValueImplementation(\n        const arma::Col& parameter) const noexcept = 0;\n\n      std::unordered_map, double, Hash, IsEqual> cachedObjectiveValues_;\n\n #if defined(MANTELLA_USE_PARALLEL)\n      friend class cereal::access;\n      OptimisationProblem() = default;\n      \n      template \n      void serialize(\n          Archive& archive) noexcept {\n        archive(cereal::make_nvp(\"numberOfDimensions\", numberOfDimensions_));\n        archive(cereal::make_nvp(\"lowerBounds\", lowerBounds_));\n        archive(cereal::make_nvp(\"upperBounds\", upperBounds_));\n        archive(cereal::make_nvp(\"parameterTranslation\", parameterTranslation_));\n        archive(cereal::make_nvp(\"parameterRotation\", parameterRotation_));\n        archive(cereal::make_nvp(\"parameterScaling\", parameterScaling_));\n        archive(cereal::make_nvp(\"objectiveValueTranslation\", objectiveValueTranslation_));\n        archive(cereal::make_nvp(\"objectiveValueScaling\", objectiveValueScaling_));\n        archive(cereal::make_nvp(\"acceptableObjectiveValue\", acceptableObjectiveValue_));\n      }\n#endif\n  };\n\n  \/\/\n  \/\/ Implementation\n  \/\/\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept;\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation);\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation);\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling);\n\n  template <>\n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept;\n\n  template \n  OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterPermutation(arma::linspace>(0, numberOfDimensions_ - 1, numberOfDimensions));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScaling(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterPermutation(arma::linspace>(0, numberOfDimensions_ - 1, numberOfDimensions));\n    setParameterTranslation(arma::zeros>(numberOfDimensions_));\n    setParameterRotation(arma::eye>(numberOfDimensions_, numberOfDimensions_));\n    setParameterScaling(arma::ones>(numberOfDimensions_));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScaling(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingLowerBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter >= lowerBounds_);\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingUpperBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter <= upperBounds_);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingSoftConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (getSoftConstraintsValue(parameter) == 0);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n    \n    return (arma::all(isSatisfyingLowerBounds(parameter)) && arma::all(isSatisfyingUpperBounds(parameter)) && isSatisfyingSoftConstraints(parameter));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return objectiveValueScaling_ * getSoftConstraintsValueImplementation(parameter);\n  }\n\n  template \n  inline double OptimisationProblem::getObjectiveValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    \/\/ Always increase the number of evaluations (whether its computed or retrived from cache).\n    ++numberOfEvaluations_;\n\n    \/\/ Check if the result is already cached.\n    const auto& cachePosition = cachedObjectiveValues_.find(parameter);\n    if (cachePosition == cachedObjectiveValues_.cend()) {\n      \/\/ Increase the number of distinct evaluations only if we actually compute the value.\n      ++numberOfDistinctEvaluations_;\n\n      \/\/ The result was not found, compute it.\n      const double& result = objectiveValueScaling_ * getObjectiveValueImplementation(getDiversifiedParameter(parameter)) + objectiveValueTranslation_;\n      cachedObjectiveValues_.insert({parameter, result});\n      return result;\n    } else {\n      \/\/ Return the found result.\n      return cachePosition->second;\n    }\n  }\n\n  template \n  arma::Col OptimisationProblem::getLowerBounds() const noexcept {\n    return lowerBounds_;\n  }\n\n  template \n  void OptimisationProblem::setLowerBounds(\n      const arma::Col lowerBounds) {\n    checkDimensionCompatible(\"The number of elements\", lowerBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    lowerBounds_ = lowerBounds;\n  }\n\n  template \n  arma::Col OptimisationProblem::getUpperBounds() const noexcept {\n    return upperBounds_;\n  }\n\n  template \n  void OptimisationProblem::setUpperBounds(\n      const arma::Col upperBounds) {\n    checkDimensionCompatible(\"The number of elements\", upperBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    upperBounds_ = upperBounds;\n  }\n\n  template \n  inline void OptimisationProblem::setParameterPermutation(\n      const arma::Col parameterPermutation) {\n    \/\/ TODO Check if this is actually a permutaion\n    checkDimensionCompatible(\"The number of elements\", parameterPermutation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterPermutation_ = parameterPermutation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation) {\n    checkDimensionCompatible(\"The number of elements\", parameterTranslation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterTranslation_ = parameterTranslation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation) {\n    checkDimensionCompatible(\"The number of rows\", parameterRotation.n_rows, \"the number of dimensions\", numberOfDimensions_);\n    checkRotationMatrix(\"The matrix\", parameterRotation);\n\n    parameterRotation_ = parameterRotation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling) {\n    checkDimensionCompatible(\"The number of elements\", parameterScaling.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterScaling_ = parameterScaling;\n  }\n\n  template \n  void OptimisationProblem::setObjectiveValueTranslation(\n      const double objectiveValueTranslation) noexcept {\n    objectiveValueTranslation_ = objectiveValueTranslation;\n  }\n\n  template \n  void OptimisationProblem::OptimisationProblem::setObjectiveValueScaling(\n      const double objectiveValueScaling) noexcept {\n    objectiveValueScaling_ = objectiveValueScaling;\n  }\n\n  template \n  double OptimisationProblem::getAcceptableObjectiveValue() const noexcept {\n    return acceptableObjectiveValue_;\n  }\n\n  template \n  void OptimisationProblem::setAcceptableObjectiveValue(\n      const double acceptableObjectiveValue) noexcept {\n    acceptableObjectiveValue_ = acceptableObjectiveValue;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfEvaluations() const noexcept {\n    return numberOfEvaluations_;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfDistinctEvaluations() const noexcept {\n    return numberOfDistinctEvaluations_;\n  }\n\n  template \n  void OptimisationProblem::reset() noexcept {\n    numberOfEvaluations_ = 0;\n    numberOfDistinctEvaluations_ = 0;\n\n    cachedObjectiveValues_.clear();\n  }\n\n  template \n  std::unordered_map, double, Hash, IsEqual> OptimisationProblem::getCachedObjectiveValues() const noexcept {\n    return cachedObjectiveValues_;\n  }\n\n  template \n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameter.elem(parameterPermutation_);\n  }\n\n  template <>\n  inline arma::Col OptimisationProblem::getDiversifiedParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameterRotation_ * (parameterScaling_ % parameter.elem(parameterPermutation_) - parameterTranslation_);\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValueImplementation(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return 0.0;\n  }\n}\n<|endoftext|>"}
{"text":"namespace mant {\n  template \n  class OptimisationProblem : public Printable {\n    public:\n      const unsigned int numberOfDimensions_;\n\n      explicit OptimisationProblem(\n        const unsigned int& numberOfDimensions) noexcept;\n\n      void setLowerBounds(\n        const arma::Col lowerBounds);\n\n      void setUpperBounds(\n        const arma::Col upperBounds);\n\n      arma::Col getLowerBounds() const noexcept;\n\n      arma::Col getUpperBounds() const noexcept;\n\n      double getSoftConstraintsValue(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingLowerBounds(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingUpperBounds(\n        const arma::Col& parameter);\n\n      bool isSatisfyingSoftConstraints(\n        const arma::Col& parameter);\n\n      bool isSatisfyingConstraints(\n        const arma::Col& parameter);\n\n      void setParameterTranslation(\n          const arma::Col parameterTranslation);\n\n      void setParameterScale(\n        const arma::Col parameterScale);\n\n      void setParameterRotation(\n        const arma::Mat parameterRotation);\n\n      void setObjectiveValueTranslation(\n        const double objectiveValueTranslation) noexcept;\n\n      void setObjectiveValueScale(\n        const double objectiveValueScale) noexcept;\n      \n      void setAcceptableObjectiveValue(\n          const double acceptableObjectiveValue) noexcept;\n        \n      double getAcceptableObjectiveValue() const noexcept;\n\n      double getObjectiveValue(\n        const arma::Col& parameter);\n\n      unsigned int getNumberOfEvaluations() const noexcept;\n\n      unsigned int getNumberOfDistinctEvaluations() const noexcept;\n\n      void reset() noexcept;\n\n      std::unordered_map, double, Hash, IsEqual> getCachedObjectiveValues() const noexcept;\n\n      virtual ~OptimisationProblem() = default;\n\n    protected:\n      arma::Col lowerBounds_;\n      arma::Col upperBounds_;\n\n      arma::Col parameterTranslation_;\n      arma::Col parameterScale_;\n      arma::Mat parameterRotation_;\n\n      double objectiveValueTranslation_;\n      double objectiveValueScale_;\n\n      double acceptableObjectiveValue_;\n\n      unsigned int numberOfEvaluations_;\n      unsigned int numberOfDistinctEvaluations_;\n\n      arma::Col getScaledCongruentParameter(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getSoftConstraintsValueImplementation(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getObjectiveValueImplementation(\n        const arma::Col& parameter) const noexcept = 0;\n\n      std::unordered_map, double, Hash, IsEqual> cachedObjectiveValues_;\n\n #if defined(MANTELLA_USE_PARALLEL)\n      friend class cereal::access;\n      OptimisationProblem() = default;\n      \n      template \n      void serialize(\n          Archive& archive) noexcept {\n        archive(cereal::make_nvp(\"numberOfDimensions\", numberOfDimensions_));\n        archive(cereal::make_nvp(\"lowerBounds\", lowerBounds_));\n        archive(cereal::make_nvp(\"upperBounds\", upperBounds_));\n        archive(cereal::make_nvp(\"parameterTranslation\", parameterTranslation_));\n        archive(cereal::make_nvp(\"parameterRotation\", parameterRotation_));\n        archive(cereal::make_nvp(\"parameterScale\", parameterScale_));\n        archive(cereal::make_nvp(\"objectiveValueTranslation\", objectiveValueTranslation_));\n        archive(cereal::make_nvp(\"objectiveValueScale\", objectiveValueScale_));\n        archive(cereal::make_nvp(\"acceptableObjectiveValue\", acceptableObjectiveValue_));\n      }\n#endif\n  };\n\n  \/\/\n  \/\/ Implementation\n  \/\/\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept;\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation);\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation);\n\n  template <>\n  inline void OptimisationProblem::setParameterScale(\n      const arma::Col parameterScale);\n\n  template <>\n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept;\n\n  template \n  OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScale(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterTranslation(arma::zeros>(numberOfDimensions_));\n    setParameterRotation(arma::eye>(numberOfDimensions_, numberOfDimensions_));\n    setParameterScale(arma::ones>(numberOfDimensions_));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScale(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingLowerBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter >= lowerBounds_);\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingUpperBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter <= upperBounds_);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingSoftConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (getSoftConstraintsValue(parameter) == 0);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n    \n    return (arma::all(isSatisfyingLowerBounds(parameter)) && arma::all(isSatisfyingUpperBounds(parameter)) && isSatisfyingSoftConstraints(parameter));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return getSoftConstraintsValueImplementation(parameter);\n  }\n\n  template \n  inline double OptimisationProblem::getObjectiveValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    \/\/ Always increase the number of evaluations (whether its computed or retrived from cache).\n    ++numberOfEvaluations_;\n\n    \/\/ Check if the result is already cached.\n    const auto& cachePosition = cachedObjectiveValues_.find(parameter);\n    if (cachePosition == cachedObjectiveValues_.cend()) {\n      \/\/ Increase the number of distinct evaluations only if we actually compute the value.\n      ++numberOfDistinctEvaluations_;\n\n      \/\/ The result was not found, compute it.\n      const double& result = objectiveValueScale_ * getObjectiveValueImplementation(getScaledCongruentParameter(parameter)) + objectiveValueTranslation_;\n      cachedObjectiveValues_.insert({parameter, result});\n      return result;\n    } else {\n      \/\/ Return the found result.\n      return cachePosition->second;\n    }\n  }\n\n  template \n  arma::Col OptimisationProblem::getLowerBounds() const noexcept {\n    return lowerBounds_;\n  }\n\n  template \n  void OptimisationProblem::setLowerBounds(\n      const arma::Col lowerBounds) {\n    checkDimensionCompatible(\"The number of elements\", lowerBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    lowerBounds_ = lowerBounds;\n  }\n\n  template \n  arma::Col OptimisationProblem::getUpperBounds() const noexcept {\n    return upperBounds_;\n  }\n\n  template \n  void OptimisationProblem::setUpperBounds(\n      const arma::Col upperBounds) {\n    checkDimensionCompatible(\"The number of elements\", upperBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    upperBounds_ = upperBounds;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation) {\n    checkDimensionCompatible(\"The number of elements\", parameterTranslation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterTranslation_ = parameterTranslation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation) {\n    checkDimensionCompatible(\"The number of rows\", parameterRotation.n_rows, \"the number of dimensions\", numberOfDimensions_);\n    checkRotationMatrix(\"The matrix\", parameterRotation);\n\n    parameterRotation_ = parameterRotation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterScale(\n      const arma::Col parameterScale) {\n    checkDimensionCompatible(\"The number of elements\", parameterScale.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterScale_ = parameterScale;\n  }\n\n  template \n  void OptimisationProblem::setObjectiveValueTranslation(\n      const double objectiveValueTranslation) noexcept {\n    objectiveValueTranslation_ = objectiveValueTranslation;\n  }\n\n  template \n  void OptimisationProblem::OptimisationProblem::setObjectiveValueScale(\n      const double objectiveValueScale) noexcept {\n    objectiveValueScale_ = objectiveValueScale;\n  }\n\n  template \n  double OptimisationProblem::getAcceptableObjectiveValue() const noexcept {\n    return acceptableObjectiveValue_;\n  }\n\n  template \n  void OptimisationProblem::setAcceptableObjectiveValue(\n      const double acceptableObjectiveValue) noexcept {\n    acceptableObjectiveValue_ = acceptableObjectiveValue;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfEvaluations() const noexcept {\n    return numberOfEvaluations_;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfDistinctEvaluations() const noexcept {\n    return numberOfDistinctEvaluations_;\n  }\n\n  template \n  void OptimisationProblem::reset() noexcept {\n    numberOfEvaluations_ = 0;\n    numberOfDistinctEvaluations_ = 0;\n\n    cachedObjectiveValues_.clear();\n  }\n\n  template \n  std::unordered_map, double, Hash, IsEqual> OptimisationProblem::getCachedObjectiveValues() const noexcept {\n    return cachedObjectiveValues_;\n  }\n\n  template \n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameter;\n  }\n\n  template <>\n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameterRotation_ * (parameter + (parameterScale_ % parameterTranslation_));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValueImplementation(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return 0.0;\n  }\n}\nRenamed ParameterScale to ParameterScalingnamespace mant {\n  template \n  class OptimisationProblem : public Printable {\n    public:\n      const unsigned int numberOfDimensions_;\n\n      explicit OptimisationProblem(\n        const unsigned int& numberOfDimensions) noexcept;\n\n      void setLowerBounds(\n        const arma::Col lowerBounds);\n\n      void setUpperBounds(\n        const arma::Col upperBounds);\n\n      arma::Col getLowerBounds() const noexcept;\n\n      arma::Col getUpperBounds() const noexcept;\n\n      double getSoftConstraintsValue(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingLowerBounds(\n        const arma::Col& parameter);\n\n      arma::Col isSatisfyingUpperBounds(\n        const arma::Col& parameter);\n\n      bool isSatisfyingSoftConstraints(\n        const arma::Col& parameter);\n\n      bool isSatisfyingConstraints(\n        const arma::Col& parameter);\n\n      void setParameterTranslation(\n          const arma::Col parameterTranslation);\n\n      void setParameterScaling(\n        const arma::Col parameterScaling);\n\n      void setParameterRotation(\n        const arma::Mat parameterRotation);\n\n      void setObjectiveValueTranslation(\n        const double objectiveValueTranslation) noexcept;\n\n      void setObjectiveValueScale(\n        const double objectiveValueScale) noexcept;\n      \n      void setAcceptableObjectiveValue(\n          const double acceptableObjectiveValue) noexcept;\n        \n      double getAcceptableObjectiveValue() const noexcept;\n\n      double getObjectiveValue(\n        const arma::Col& parameter);\n\n      unsigned int getNumberOfEvaluations() const noexcept;\n\n      unsigned int getNumberOfDistinctEvaluations() const noexcept;\n\n      void reset() noexcept;\n\n      std::unordered_map, double, Hash, IsEqual> getCachedObjectiveValues() const noexcept;\n\n      virtual ~OptimisationProblem() = default;\n\n    protected:\n      arma::Col lowerBounds_;\n      arma::Col upperBounds_;\n\n      arma::Col parameterTranslation_;\n      arma::Col parameterScaling_;\n      arma::Mat parameterRotation_;\n\n      double objectiveValueTranslation_;\n      double objectiveValueScale_;\n\n      double acceptableObjectiveValue_;\n\n      unsigned int numberOfEvaluations_;\n      unsigned int numberOfDistinctEvaluations_;\n\n      arma::Col getScaledCongruentParameter(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getSoftConstraintsValueImplementation(\n        const arma::Col& parameter) const noexcept;\n\n      virtual double getObjectiveValueImplementation(\n        const arma::Col& parameter) const noexcept = 0;\n\n      std::unordered_map, double, Hash, IsEqual> cachedObjectiveValues_;\n\n #if defined(MANTELLA_USE_PARALLEL)\n      friend class cereal::access;\n      OptimisationProblem() = default;\n      \n      template \n      void serialize(\n          Archive& archive) noexcept {\n        archive(cereal::make_nvp(\"numberOfDimensions\", numberOfDimensions_));\n        archive(cereal::make_nvp(\"lowerBounds\", lowerBounds_));\n        archive(cereal::make_nvp(\"upperBounds\", upperBounds_));\n        archive(cereal::make_nvp(\"parameterTranslation\", parameterTranslation_));\n        archive(cereal::make_nvp(\"parameterRotation\", parameterRotation_));\n        archive(cereal::make_nvp(\"parameterScaling\", parameterScaling_));\n        archive(cereal::make_nvp(\"objectiveValueTranslation\", objectiveValueTranslation_));\n        archive(cereal::make_nvp(\"objectiveValueScale\", objectiveValueScale_));\n        archive(cereal::make_nvp(\"acceptableObjectiveValue\", acceptableObjectiveValue_));\n      }\n#endif\n  };\n\n  \/\/\n  \/\/ Implementation\n  \/\/\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept;\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation);\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation);\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling);\n\n  template <>\n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept;\n\n  template \n  OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScale(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template <>\n  inline OptimisationProblem::OptimisationProblem(\n      const unsigned int& numberOfDimensions) noexcept\n    : numberOfDimensions_(numberOfDimensions),\n      numberOfEvaluations_(0),\n      numberOfDistinctEvaluations_(0) {\n    setLowerBounds(arma::zeros>(numberOfDimensions_) - std::numeric_limits::max());\n    setUpperBounds(arma::zeros>(numberOfDimensions_) + std::numeric_limits::max());\n    setParameterTranslation(arma::zeros>(numberOfDimensions_));\n    setParameterRotation(arma::eye>(numberOfDimensions_, numberOfDimensions_));\n    setParameterScaling(arma::ones>(numberOfDimensions_));\n    setObjectiveValueTranslation(0.0);\n    setObjectiveValueScale(1.0);\n    setAcceptableObjectiveValue(std::numeric_limits::lowest());\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingLowerBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter >= lowerBounds_);\n  }\n\n  template \n  arma::Col OptimisationProblem::isSatisfyingUpperBounds(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (parameter <= upperBounds_);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingSoftConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return (getSoftConstraintsValue(parameter) == 0);\n  }\n\n  template \n  bool OptimisationProblem::isSatisfyingConstraints(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n    \n    return (arma::all(isSatisfyingLowerBounds(parameter)) && arma::all(isSatisfyingUpperBounds(parameter)) && isSatisfyingSoftConstraints(parameter));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    return getSoftConstraintsValueImplementation(parameter);\n  }\n\n  template \n  inline double OptimisationProblem::getObjectiveValue(\n      const arma::Col& parameter) {\n    checkDimensionCompatible(\"The number of elements\", parameter.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    \/\/ Always increase the number of evaluations (whether its computed or retrived from cache).\n    ++numberOfEvaluations_;\n\n    \/\/ Check if the result is already cached.\n    const auto& cachePosition = cachedObjectiveValues_.find(parameter);\n    if (cachePosition == cachedObjectiveValues_.cend()) {\n      \/\/ Increase the number of distinct evaluations only if we actually compute the value.\n      ++numberOfDistinctEvaluations_;\n\n      \/\/ The result was not found, compute it.\n      const double& result = objectiveValueScale_ * getObjectiveValueImplementation(getScaledCongruentParameter(parameter)) + objectiveValueTranslation_;\n      cachedObjectiveValues_.insert({parameter, result});\n      return result;\n    } else {\n      \/\/ Return the found result.\n      return cachePosition->second;\n    }\n  }\n\n  template \n  arma::Col OptimisationProblem::getLowerBounds() const noexcept {\n    return lowerBounds_;\n  }\n\n  template \n  void OptimisationProblem::setLowerBounds(\n      const arma::Col lowerBounds) {\n    checkDimensionCompatible(\"The number of elements\", lowerBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    lowerBounds_ = lowerBounds;\n  }\n\n  template \n  arma::Col OptimisationProblem::getUpperBounds() const noexcept {\n    return upperBounds_;\n  }\n\n  template \n  void OptimisationProblem::setUpperBounds(\n      const arma::Col upperBounds) {\n    checkDimensionCompatible(\"The number of elements\", upperBounds.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    upperBounds_ = upperBounds;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterTranslation(\n      const arma::Col parameterTranslation) {\n    checkDimensionCompatible(\"The number of elements\", parameterTranslation.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterTranslation_ = parameterTranslation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterRotation(\n      const arma::Mat parameterRotation) {\n    checkDimensionCompatible(\"The number of rows\", parameterRotation.n_rows, \"the number of dimensions\", numberOfDimensions_);\n    checkRotationMatrix(\"The matrix\", parameterRotation);\n\n    parameterRotation_ = parameterRotation;\n  }\n\n  template <>\n  inline void OptimisationProblem::setParameterScaling(\n      const arma::Col parameterScaling) {\n    checkDimensionCompatible(\"The number of elements\", parameterScaling.n_elem, \"the number of dimensions\", numberOfDimensions_);\n\n    parameterScaling_ = parameterScaling;\n  }\n\n  template \n  void OptimisationProblem::setObjectiveValueTranslation(\n      const double objectiveValueTranslation) noexcept {\n    objectiveValueTranslation_ = objectiveValueTranslation;\n  }\n\n  template \n  void OptimisationProblem::OptimisationProblem::setObjectiveValueScale(\n      const double objectiveValueScale) noexcept {\n    objectiveValueScale_ = objectiveValueScale;\n  }\n\n  template \n  double OptimisationProblem::getAcceptableObjectiveValue() const noexcept {\n    return acceptableObjectiveValue_;\n  }\n\n  template \n  void OptimisationProblem::setAcceptableObjectiveValue(\n      const double acceptableObjectiveValue) noexcept {\n    acceptableObjectiveValue_ = acceptableObjectiveValue;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfEvaluations() const noexcept {\n    return numberOfEvaluations_;\n  }\n\n  template \n  unsigned int OptimisationProblem::getNumberOfDistinctEvaluations() const noexcept {\n    return numberOfDistinctEvaluations_;\n  }\n\n  template \n  void OptimisationProblem::reset() noexcept {\n    numberOfEvaluations_ = 0;\n    numberOfDistinctEvaluations_ = 0;\n\n    cachedObjectiveValues_.clear();\n  }\n\n  template \n  std::unordered_map, double, Hash, IsEqual> OptimisationProblem::getCachedObjectiveValues() const noexcept {\n    return cachedObjectiveValues_;\n  }\n\n  template \n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameter;\n  }\n\n  template <>\n  inline arma::Col OptimisationProblem::getScaledCongruentParameter(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return parameterRotation_ * (parameter + (parameterScale_ % parameterTranslation_));\n  }\n\n  template \n  double OptimisationProblem::getSoftConstraintsValueImplementation(\n      const arma::Col& parameter) const noexcept {\n    assert(isDimensionCompatible(parameter.n_elem, numberOfDimensions_));\n\n    return 0.0;\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\/\/ ChromeFrameHost implementation.\n#include \"ceee\/ie\/common\/chrome_frame_host.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/common\/process_utils_win.h\"\n#include \"ceee\/ie\/common\/ceee_module_util.h\"\n#include \"chrome\/browser\/automation\/extension_automation_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#include \"toolband.h\"  \/\/ NOLINT\n\nnamespace ext = extension_automation_constants;\n\n\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_ =\n    { CC_STDCALL, VT_EMPTY, 1, { VT_DISPATCH } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_long_ =\n    { CC_STDCALL, VT_EMPTY, 1, { VT_I4 } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_bstr_ =\n    { CC_STDCALL, VT_EMPTY, 2, { VT_DISPATCH, VT_BSTR } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_variantptr_ =\n    { CC_STDCALL, VT_EMPTY, 2, { VT_DISPATCH, VT_BYREF | VT_VARIANT } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_bstr_i4_=\n    { CC_STDCALL, VT_EMPTY, 2, { VT_BSTR, VT_I4 } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_bstrarray_=\n    { CC_STDCALL, VT_EMPTY, 1, { VT_ARRAY | VT_BSTR } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_void_=\n    { CC_STDCALL, VT_EMPTY, 0, { } };\n\n\/\/ {AFA3E2CF-2C8E-4546-8CD0-A2D93759A4DE}\nextern const GUID IID_IChromeFrameHost =\n  { 0xafa3e2cf, 0x2c8e, 0x4546,\n      { 0x8c, 0xd0, 0xa2, 0xd9, 0x37, 0x59, 0xa4, 0xde } };\n\nChromeFrameHost::ChromeFrameHost()\n    : document_loaded_(false), origin_(ext::kAutomationOrigin) {\n  LOG(INFO) << \"Create ChromeFrameHost(\" << this << \")\";\n}\n\nChromeFrameHost::~ChromeFrameHost() {\n  LOG(INFO) << \"Destroy ChromeFrameHost(\" << this << \")\";\n}\n\nHRESULT ChromeFrameHost::FinalConstruct() {\n  return S_OK;\n}\n\nvoid ChromeFrameHost::FinalRelease() {\n}\n\nSTDMETHODIMP ChromeFrameHost::GetWantsPrivileged(boolean* wants_privileged) {\n  *wants_privileged = true;\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::GetChromeExtraArguments(BSTR* args) {\n  DCHECK(args);\n\n  \/\/ Extra arguments are passed on verbatim, so we add the -- prefix.\n  CComBSTR str = \"--\";\n  str.Append(switches::kEnableExperimentalExtensionApis);\n\n  *args = str.Detach();\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::GetChromeProfileName(BSTR* profile_name) {\n  return chrome_profile_name_.CopyTo(profile_name);\n}\n\nSTDMETHODIMP ChromeFrameHost::GetExtensionApisToAutomate(\n    BSTR* functions_enabled) {\n  DCHECK(functions_enabled != NULL);\n  HRESULT hr = S_FALSE;\n  if (event_sink_ != NULL) {\n    hr = event_sink_->OnCfGetExtensionApisToAutomate(functions_enabled);\n#ifndef NDEBUG\n    if (*functions_enabled != NULL) {\n      \/\/ Only one chrome frame host is allowed to return a list of functions\n      \/\/ to enable automation on, so make sure we are the one and only.\n      std::wstring event_name(L\"google-ceee-apiautomation!\");\n\n      DCHECK(chrome_profile_name_ != NULL);\n      if (chrome_profile_name_ != NULL)\n        event_name += chrome_profile_name_;\n\n      std::replace(event_name.begin(), event_name.end(), '\\\\', '!');\n      std::transform(\n          event_name.begin(), event_name.end(), event_name.begin(), tolower);\n      automating_extension_api_.Set(\n          ::CreateEvent(NULL, TRUE, TRUE, event_name.c_str()));\n      DWORD we = ::GetLastError();\n      DCHECK(automating_extension_api_ != NULL &&\n             we != ERROR_ALREADY_EXISTS &&\n             we != ERROR_ACCESS_DENIED);\n    }\n#endif  \/\/ NDEBUG\n  }\n  return hr;\n}\n\nHRESULT ChromeFrameHost::Initialize() {\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::TearDown() {\n  if (IsWindow()) {\n    \/\/ TearDown the ActiveX host window.\n    CAxWindow host(m_hWnd);\n    CComPtr host_with_site;\n    HRESULT hr = host.QueryHost(&host_with_site);\n    if (SUCCEEDED(hr))\n      host_with_site->SetSite(NULL);\n\n    DestroyWindow();\n  }\n\n  if (chrome_frame_)\n    ChromeFrameEvents::DispEventUnadvise(chrome_frame_);\n\n  chrome_frame_.Release();\n#ifndef NDEBUG\n  automating_extension_api_.Close();\n#endif\n  return S_OK;\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::SetEventSink(\n    IChromeFrameHostEvents* event_sink) {\n  event_sink_ = event_sink;\n}\n\nHRESULT ChromeFrameHost::InstallExtension(BSTR crx_path) {\n  if (chrome_frame_) {\n    return chrome_frame_->installExtension(crx_path);\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::LoadExtension(BSTR extension_dir) {\n  if (chrome_frame_) {\n    return chrome_frame_->installExtension(extension_dir);\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::GetEnabledExtensions() {\n  if (chrome_frame_) {\n    return chrome_frame_->getEnabledExtensions();\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::GetSessionId(int *session_id) {\n  if (chrome_frame_) {\n    CComQIPtr chrome_frame_internal_(chrome_frame_);\n    if (chrome_frame_internal_)\n      return chrome_frame_internal_->getSessionId(session_id);\n    else\n      return kInvalidChromeSessionId;\n  }\n  NOTREACHED();\n  return E_UNEXPECTED;\n}\n\nvoid ChromeFrameHost::OnFinalMessage(HWND window) {\n  GetUnknown()->Release();\n}\n\nHRESULT ChromeFrameHost::SetChildSite(IUnknown* child) {\n  if (child == NULL)\n    return E_POINTER;\n\n  HRESULT hr = S_OK;\n  CComPtr child_site;\n  hr = child->QueryInterface(&child_site);\n  if (SUCCEEDED(hr))\n    hr = child_site->SetSite(GetUnknown());\n\n  return hr;\n}\n\nLRESULT ChromeFrameHost::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n  \/\/ Grab a self-reference.\n  GetUnknown()->AddRef();\n\n  return 0;\n}\n\nHRESULT ChromeFrameHost::SetUrl(BSTR url) {\n  HRESULT hr = chrome_frame_->put_src(url);\n  DCHECK(SUCCEEDED(hr)) << \"Failed to navigate Chrome Frame: \" <<\n    com::LogHr(hr);\n  return hr;\n}\n\nSTDMETHODIMP ChromeFrameHost::StartChromeFrame() {\n  DCHECK(!IsWindow());\n\n  \/\/ Create a message window to host our control.\n  if (NULL == Create(HWND_MESSAGE))\n    return E_FAIL;\n\n  \/\/ Create a host window instance.\n  CComPtr host;\n  HRESULT hr = CreateActiveXHost(&host);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to create ActiveX host window: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ We're the site for the host window, this needs to be in place\n  \/\/ before we attach ChromeFrame to the ActiveX control window, so\n  \/\/ as to allow it to probe our service provider.\n  hr = SetChildSite(host);\n  DCHECK(SUCCEEDED(hr));\n\n  \/\/ Create the chrome frame instance.\n  hr = CreateChromeFrame(&chrome_frame_);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed create Chrome Frame: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ And attach it to our window. This causes the host to subclass\n  \/\/ our window and attach itself to it.\n  hr = host->AttachControl(chrome_frame_, m_hWnd);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to attach Chrome Frame to the host\" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ Hook up the chrome frame event listener.\n  hr = ChromeFrameEvents::DispEventAdvise(chrome_frame_);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to hook up event sink: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  return hr;\n}\n\nHRESULT ChromeFrameHost::CreateActiveXHost(IAxWinHostWindow** host) {\n  return CAxHostWindow::CreateInstance(host);\n}\n\nHRESULT ChromeFrameHost::CreateChromeFrame(IChromeFrame** chrome_frame) {\n  CComPtr new_cf;\n  HRESULT hr = new_cf.CoCreateInstance(L\"ChromeTab.ChromeFrame\");\n  if (SUCCEEDED(hr))\n    hr = new_cf.CopyTo(chrome_frame);\n\n  return hr;\n}\n\nSTDMETHODIMP ChromeFrameHost::PostMessage(BSTR message, BSTR target) {\n  if (!document_loaded_) {\n    PostedMessage posted_message = { message, target };\n    posted_messages_.push_back(posted_message);\n    return S_FALSE;\n  }\n\n  HRESULT hr = chrome_frame_->postPrivateMessage(message, origin_, target);\n\n  return hr;\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfLoad(IDispatch* event) {\n  DLOG(INFO) << \"OnCfLoad\";\n  if (document_loaded_) {\n    \/\/ If we were already loaded, our list should be empty.\n    DCHECK(posted_messages_.empty());\n    return;\n  }\n  document_loaded_ = true;\n\n  \/\/ Flush all posted messages.\n  PostedMessageList::iterator it(posted_messages_.begin());\n  for (; it != posted_messages_.end(); ++it) {\n    HRESULT hr = chrome_frame_->postPrivateMessage(it->message, origin_,\n                                                   it->target);\n    DCHECK(SUCCEEDED(hr)) << \"postPrivateMessage failed with: \" <<\n        com::LogHr(hr);\n  }\n  posted_messages_.clear();\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfLoadError(IDispatch* event) {\n  DLOG(ERROR) << \"OnCfLoadError\";\n  DCHECK(false) << \"OnCfLoadError\";\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfExtensionReady(BSTR path,\n                                                        int response) {\n  DLOG(INFO) << \"OnCfExtensionReady: \" << path << \", \" << response;\n  \/\/ Early exit if there's no sink.\n  if (event_sink_ == NULL)\n    return;\n  event_sink_->OnCfExtensionReady(path, response);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfGetEnabledExtensionsComplete(\n    SAFEARRAY* extension_directories) {\n  DLOG(INFO) << \"OnCfGetEnabledExtensionsComplete\";\n  if (event_sink_)\n    event_sink_->OnCfGetEnabledExtensionsComplete(extension_directories);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfChannelError() {\n  DCHECK(false) << \"OnCfChannelError means that Chrome has Crashed!\";\n  if (event_sink_)\n    event_sink_->OnCfChannelError();\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfMessage(IDispatch* event) {\n  DLOG(INFO) << \"OnCfMessage\";\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfReadyStateChanged(LONG state) {\n  DLOG(INFO) << \"OnCfReadyStateChanged(\" << state << \")\";\n  if (event_sink_)\n    event_sink_->OnCfReadyStateChanged(state);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfPrivateMessage(IDispatch* event,\n                                                        BSTR target) {\n  \/\/ Early exit if there's no sink.\n  if (event_sink_ == NULL)\n    return;\n\n  \/\/ Make sure that the message has a \"data\" member and get it.  This should\n  \/\/ be a JSON-encoded command to execute.\n  CComDispatchDriver event_dispatch(event);\n\n  CComVariant origin;\n  HRESULT hr = event_dispatch.GetPropertyByName(L\"origin\", &origin);\n  DCHECK(SUCCEEDED(hr) && origin.vt == VT_BSTR);\n  if (FAILED(hr) || origin.vt != VT_BSTR) {\n    NOTREACHED() << \"No origin on event\";\n    return;\n  }\n\n  CComVariant data;\n  hr = event_dispatch.GetPropertyByName(L\"data\", &data);\n  DCHECK(SUCCEEDED(hr) && data.vt == VT_BSTR);\n  if (FAILED(hr) || data.vt != VT_BSTR) {\n    NOTREACHED() << \"No data on event\";\n    return;\n  }\n\n  \/\/ Forward to the sink.\n  event_sink_->OnCfPrivateMessage(V_BSTR(&data), V_BSTR(&origin), target);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::SetChromeProfileName(\n    const wchar_t* chrome_profile_name) {\n  chrome_profile_name_ = chrome_profile_name;\n  DLOG(INFO) << \"Assigned profile name \" << chrome_profile_name_;\n}\nFixed return value of CFHost::getSession() BUG=none TEST=none\/\/ 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\/\/ ChromeFrameHost implementation.\n#include \"ceee\/ie\/common\/chrome_frame_host.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"ceee\/common\/com_utils.h\"\n#include \"ceee\/common\/process_utils_win.h\"\n#include \"ceee\/ie\/common\/ceee_module_util.h\"\n#include \"chrome\/browser\/automation\/extension_automation_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#include \"toolband.h\"  \/\/ NOLINT\n\nnamespace ext = extension_automation_constants;\n\n\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_ =\n    { CC_STDCALL, VT_EMPTY, 1, { VT_DISPATCH } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_long_ =\n    { CC_STDCALL, VT_EMPTY, 1, { VT_I4 } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_bstr_ =\n    { CC_STDCALL, VT_EMPTY, 2, { VT_DISPATCH, VT_BSTR } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_idispatch_variantptr_ =\n    { CC_STDCALL, VT_EMPTY, 2, { VT_DISPATCH, VT_BYREF | VT_VARIANT } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_bstr_i4_=\n    { CC_STDCALL, VT_EMPTY, 2, { VT_BSTR, VT_I4 } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_bstrarray_=\n    { CC_STDCALL, VT_EMPTY, 1, { VT_ARRAY | VT_BSTR } };\n_ATL_FUNC_INFO ChromeFrameHost::handler_type_void_=\n    { CC_STDCALL, VT_EMPTY, 0, { } };\n\n\/\/ {AFA3E2CF-2C8E-4546-8CD0-A2D93759A4DE}\nextern const GUID IID_IChromeFrameHost =\n  { 0xafa3e2cf, 0x2c8e, 0x4546,\n      { 0x8c, 0xd0, 0xa2, 0xd9, 0x37, 0x59, 0xa4, 0xde } };\n\nChromeFrameHost::ChromeFrameHost()\n    : document_loaded_(false), origin_(ext::kAutomationOrigin) {\n  LOG(INFO) << \"Create ChromeFrameHost(\" << this << \")\";\n}\n\nChromeFrameHost::~ChromeFrameHost() {\n  LOG(INFO) << \"Destroy ChromeFrameHost(\" << this << \")\";\n}\n\nHRESULT ChromeFrameHost::FinalConstruct() {\n  return S_OK;\n}\n\nvoid ChromeFrameHost::FinalRelease() {\n}\n\nSTDMETHODIMP ChromeFrameHost::GetWantsPrivileged(boolean* wants_privileged) {\n  *wants_privileged = true;\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::GetChromeExtraArguments(BSTR* args) {\n  DCHECK(args);\n\n  \/\/ Extra arguments are passed on verbatim, so we add the -- prefix.\n  CComBSTR str = \"--\";\n  str.Append(switches::kEnableExperimentalExtensionApis);\n\n  *args = str.Detach();\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::GetChromeProfileName(BSTR* profile_name) {\n  return chrome_profile_name_.CopyTo(profile_name);\n}\n\nSTDMETHODIMP ChromeFrameHost::GetExtensionApisToAutomate(\n    BSTR* functions_enabled) {\n  DCHECK(functions_enabled != NULL);\n  HRESULT hr = S_FALSE;\n  if (event_sink_ != NULL) {\n    hr = event_sink_->OnCfGetExtensionApisToAutomate(functions_enabled);\n#ifndef NDEBUG\n    if (*functions_enabled != NULL) {\n      \/\/ Only one chrome frame host is allowed to return a list of functions\n      \/\/ to enable automation on, so make sure we are the one and only.\n      std::wstring event_name(L\"google-ceee-apiautomation!\");\n\n      DCHECK(chrome_profile_name_ != NULL);\n      if (chrome_profile_name_ != NULL)\n        event_name += chrome_profile_name_;\n\n      std::replace(event_name.begin(), event_name.end(), '\\\\', '!');\n      std::transform(\n          event_name.begin(), event_name.end(), event_name.begin(), tolower);\n      automating_extension_api_.Set(\n          ::CreateEvent(NULL, TRUE, TRUE, event_name.c_str()));\n      DWORD we = ::GetLastError();\n      DCHECK(automating_extension_api_ != NULL &&\n             we != ERROR_ALREADY_EXISTS &&\n             we != ERROR_ACCESS_DENIED);\n    }\n#endif  \/\/ NDEBUG\n  }\n  return hr;\n}\n\nHRESULT ChromeFrameHost::Initialize() {\n  return S_OK;\n}\n\nSTDMETHODIMP ChromeFrameHost::TearDown() {\n  if (IsWindow()) {\n    \/\/ TearDown the ActiveX host window.\n    CAxWindow host(m_hWnd);\n    CComPtr host_with_site;\n    HRESULT hr = host.QueryHost(&host_with_site);\n    if (SUCCEEDED(hr))\n      host_with_site->SetSite(NULL);\n\n    DestroyWindow();\n  }\n\n  if (chrome_frame_)\n    ChromeFrameEvents::DispEventUnadvise(chrome_frame_);\n\n  chrome_frame_.Release();\n#ifndef NDEBUG\n  automating_extension_api_.Close();\n#endif\n  return S_OK;\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::SetEventSink(\n    IChromeFrameHostEvents* event_sink) {\n  event_sink_ = event_sink;\n}\n\nHRESULT ChromeFrameHost::InstallExtension(BSTR crx_path) {\n  if (chrome_frame_) {\n    return chrome_frame_->installExtension(crx_path);\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::LoadExtension(BSTR extension_dir) {\n  if (chrome_frame_) {\n    return chrome_frame_->installExtension(extension_dir);\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::GetEnabledExtensions() {\n  if (chrome_frame_) {\n    return chrome_frame_->getEnabledExtensions();\n  } else {\n    NOTREACHED();\n    return E_UNEXPECTED;\n  }\n}\n\nHRESULT ChromeFrameHost::GetSessionId(int* session_id) {\n  if (chrome_frame_) {\n    CComQIPtr chrome_frame_internal_(chrome_frame_);\n    if (chrome_frame_internal_) {\n      return chrome_frame_internal_->getSessionId(session_id);\n    } else {\n      *session_id = kInvalidChromeSessionId;\n      return S_OK;\n    }\n  }\n  NOTREACHED();\n  return E_UNEXPECTED;\n}\n\nvoid ChromeFrameHost::OnFinalMessage(HWND window) {\n  GetUnknown()->Release();\n}\n\nHRESULT ChromeFrameHost::SetChildSite(IUnknown* child) {\n  if (child == NULL)\n    return E_POINTER;\n\n  HRESULT hr = S_OK;\n  CComPtr child_site;\n  hr = child->QueryInterface(&child_site);\n  if (SUCCEEDED(hr))\n    hr = child_site->SetSite(GetUnknown());\n\n  return hr;\n}\n\nLRESULT ChromeFrameHost::OnCreate(LPCREATESTRUCT lpCreateStruct) {\n  \/\/ Grab a self-reference.\n  GetUnknown()->AddRef();\n\n  return 0;\n}\n\nHRESULT ChromeFrameHost::SetUrl(BSTR url) {\n  HRESULT hr = chrome_frame_->put_src(url);\n  DCHECK(SUCCEEDED(hr)) << \"Failed to navigate Chrome Frame: \" <<\n    com::LogHr(hr);\n  return hr;\n}\n\nSTDMETHODIMP ChromeFrameHost::StartChromeFrame() {\n  DCHECK(!IsWindow());\n\n  \/\/ Create a message window to host our control.\n  if (NULL == Create(HWND_MESSAGE))\n    return E_FAIL;\n\n  \/\/ Create a host window instance.\n  CComPtr host;\n  HRESULT hr = CreateActiveXHost(&host);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to create ActiveX host window: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ We're the site for the host window, this needs to be in place\n  \/\/ before we attach ChromeFrame to the ActiveX control window, so\n  \/\/ as to allow it to probe our service provider.\n  hr = SetChildSite(host);\n  DCHECK(SUCCEEDED(hr));\n\n  \/\/ Create the chrome frame instance.\n  hr = CreateChromeFrame(&chrome_frame_);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed create Chrome Frame: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ And attach it to our window. This causes the host to subclass\n  \/\/ our window and attach itself to it.\n  hr = host->AttachControl(chrome_frame_, m_hWnd);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to attach Chrome Frame to the host\" << com::LogHr(hr);\n    return hr;\n  }\n\n  \/\/ Hook up the chrome frame event listener.\n  hr = ChromeFrameEvents::DispEventAdvise(chrome_frame_);\n  if (FAILED(hr)) {\n    LOG(ERROR) << \"Failed to hook up event sink: \" << com::LogHr(hr);\n    return hr;\n  }\n\n  return hr;\n}\n\nHRESULT ChromeFrameHost::CreateActiveXHost(IAxWinHostWindow** host) {\n  return CAxHostWindow::CreateInstance(host);\n}\n\nHRESULT ChromeFrameHost::CreateChromeFrame(IChromeFrame** chrome_frame) {\n  CComPtr new_cf;\n  HRESULT hr = new_cf.CoCreateInstance(L\"ChromeTab.ChromeFrame\");\n  if (SUCCEEDED(hr))\n    hr = new_cf.CopyTo(chrome_frame);\n\n  return hr;\n}\n\nSTDMETHODIMP ChromeFrameHost::PostMessage(BSTR message, BSTR target) {\n  if (!document_loaded_) {\n    PostedMessage posted_message = { message, target };\n    posted_messages_.push_back(posted_message);\n    return S_FALSE;\n  }\n\n  HRESULT hr = chrome_frame_->postPrivateMessage(message, origin_, target);\n\n  return hr;\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfLoad(IDispatch* event) {\n  DLOG(INFO) << \"OnCfLoad\";\n  if (document_loaded_) {\n    \/\/ If we were already loaded, our list should be empty.\n    DCHECK(posted_messages_.empty());\n    return;\n  }\n  document_loaded_ = true;\n\n  \/\/ Flush all posted messages.\n  PostedMessageList::iterator it(posted_messages_.begin());\n  for (; it != posted_messages_.end(); ++it) {\n    HRESULT hr = chrome_frame_->postPrivateMessage(it->message, origin_,\n                                                   it->target);\n    DCHECK(SUCCEEDED(hr)) << \"postPrivateMessage failed with: \" <<\n        com::LogHr(hr);\n  }\n  posted_messages_.clear();\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfLoadError(IDispatch* event) {\n  DLOG(ERROR) << \"OnCfLoadError\";\n  DCHECK(false) << \"OnCfLoadError\";\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfExtensionReady(BSTR path,\n                                                        int response) {\n  DLOG(INFO) << \"OnCfExtensionReady: \" << path << \", \" << response;\n  \/\/ Early exit if there's no sink.\n  if (event_sink_ == NULL)\n    return;\n  event_sink_->OnCfExtensionReady(path, response);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfGetEnabledExtensionsComplete(\n    SAFEARRAY* extension_directories) {\n  DLOG(INFO) << \"OnCfGetEnabledExtensionsComplete\";\n  if (event_sink_)\n    event_sink_->OnCfGetEnabledExtensionsComplete(extension_directories);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfChannelError() {\n  DCHECK(false) << \"OnCfChannelError means that Chrome has Crashed!\";\n  if (event_sink_)\n    event_sink_->OnCfChannelError();\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfMessage(IDispatch* event) {\n  DLOG(INFO) << \"OnCfMessage\";\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfReadyStateChanged(LONG state) {\n  DLOG(INFO) << \"OnCfReadyStateChanged(\" << state << \")\";\n  if (event_sink_)\n    event_sink_->OnCfReadyStateChanged(state);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::OnCfPrivateMessage(IDispatch* event,\n                                                        BSTR target) {\n  \/\/ Early exit if there's no sink.\n  if (event_sink_ == NULL)\n    return;\n\n  \/\/ Make sure that the message has a \"data\" member and get it.  This should\n  \/\/ be a JSON-encoded command to execute.\n  CComDispatchDriver event_dispatch(event);\n\n  CComVariant origin;\n  HRESULT hr = event_dispatch.GetPropertyByName(L\"origin\", &origin);\n  DCHECK(SUCCEEDED(hr) && origin.vt == VT_BSTR);\n  if (FAILED(hr) || origin.vt != VT_BSTR) {\n    NOTREACHED() << \"No origin on event\";\n    return;\n  }\n\n  CComVariant data;\n  hr = event_dispatch.GetPropertyByName(L\"data\", &data);\n  DCHECK(SUCCEEDED(hr) && data.vt == VT_BSTR);\n  if (FAILED(hr) || data.vt != VT_BSTR) {\n    NOTREACHED() << \"No data on event\";\n    return;\n  }\n\n  \/\/ Forward to the sink.\n  event_sink_->OnCfPrivateMessage(V_BSTR(&data), V_BSTR(&origin), target);\n}\n\nSTDMETHODIMP_(void) ChromeFrameHost::SetChromeProfileName(\n    const wchar_t* chrome_profile_name) {\n  chrome_profile_name_ = chrome_profile_name;\n  DLOG(INFO) << \"Assigned profile name \" << chrome_profile_name_;\n}\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP\n#define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP\n\n#include \n\n#include \"..\/config.hpp\"\n\n#include \"..\/analysis\/counted.hpp\"\n\n#include \"..\/internal\/bump_help.hpp\"\n#include \"..\/internal\/skip_control.hpp\"\n\nnamespace tao\n{\n   namespace TAOCPP_PEGTL_NAMESPACE\n   {\n      namespace internal\n      {\n         template< unsigned Min, unsigned Max, char C >\n         struct rep_one_min_max\n         {\n            using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >;\n\n            static_assert( Min <= Max, \"invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)\" );\n\n            template< typename Input >\n            static bool match( Input& in )\n            {\n               const auto size = in.size( Max + 1 );\n               if( size < Min ) {\n                  return false;\n               }\n               std::size_t i = 0;\n               for( ; i != Min; ++i ) {\n                  if( in.peek_char( i ) != C ) {\n                     return false;\n                  }\n               }\n               const auto n = std::min( std::size_t( Max ), std::size_t( size ) );\n               for( ; i != n; ++i ) {\n                  if( in.peek_char( i ) != C ) {\n                     bump_help< result_on_found::SUCCESS, Input, char, C >( in, i );\n                     return true;\n                  }\n               }\n               if( ( size <= Max ) || ( in.peek_char( Max ) != C ) ) {\n                  bump_help< result_on_found::SUCCESS, Input, char, C >( in, i );\n                  return true;\n               }\n               return false;\n            }\n         };\n\n         template< unsigned Min, unsigned Max, char C >\n         struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type\n         {\n         };\n\n      } \/\/ namespace internal\n\n      inline namespace ascii\n      {\n         template< unsigned Min, unsigned Max, char C > struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C > {};\n         struct ellipsis : internal::rep_one_min_max< 3, 3, '.' > {};\n\n      } \/\/ namespace ascii\n\n   } \/\/ namespace TAOCPP_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\nSimplify.\/\/ Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP\n#define TAOCPP_PEGTL_INCLUDE_CONTRIB_REP_ONE_MIN_MAX_HPP\n\n#include \n\n#include \"..\/config.hpp\"\n\n#include \"..\/analysis\/counted.hpp\"\n\n#include \"..\/internal\/bump_help.hpp\"\n#include \"..\/internal\/skip_control.hpp\"\n\nnamespace tao\n{\n   namespace TAOCPP_PEGTL_NAMESPACE\n   {\n      namespace internal\n      {\n         template< unsigned Min, unsigned Max, char C >\n         struct rep_one_min_max\n         {\n            using analyze_t = analysis::counted< analysis::rule_type::ANY, Min >;\n\n            static_assert( Min <= Max, \"invalid rep_one_min_max rule (maximum number of repetitions smaller than minimum)\" );\n\n            template< typename Input >\n            static bool match( Input& in )\n            {\n               const auto size = in.size( Max + 1 );\n               std::size_t i = 0;\n               while( ( i < size ) && ( in.peek_char( i ) == C ) ) {\n                  ++i;\n               }\n               if( ( Min <= i ) && ( i <= Max ) ) {\n                  bump_help< result_on_found::SUCCESS, Input, char, C >( in, i );\n                  return true;\n               }\n               return false;\n            }\n         };\n\n         template< unsigned Min, unsigned Max, char C >\n         struct skip_control< rep_one_min_max< Min, Max, C > > : std::true_type\n         {\n         };\n\n      } \/\/ namespace internal\n\n      inline namespace ascii\n      {\n         template< unsigned Min, unsigned Max, char C > struct rep_one_min_max : internal::rep_one_min_max< Min, Max, C > {};\n         struct ellipsis : internal::rep_one_min_max< 3, 3, '.' > {};\n\n      } \/\/ namespace ascii\n\n   } \/\/ namespace TAOCPP_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\n<|endoftext|>"}
{"text":"\n\/\/ LuaChunkStay.cpp\n\n\/\/ Implements the cLuaChunkStay class representing a cChunkStay binding for plugins, used by cWorld:ChunkStay() Lua API\n\n#include \"Globals.h\"\n#include \"LuaChunkStay.h\"\n#include \"PluginLua.h\"\n\n\n\n\n\ncLuaChunkStay::cLuaChunkStay(cPluginLua & a_Plugin) :\n\tm_Plugin(a_Plugin),\n\tm_LuaState(NULL)\n{\n}\n\n\n\n\n\nbool cLuaChunkStay::AddChunks(int a_ChunkCoordTableStackPos)\n{\n\t\/\/ This function is expected to be called just once, with all the coords in a table\n\tASSERT(m_Chunks.empty());\n\t\n\tcPluginLua::cOperation Op(m_Plugin);\n\tcLuaState & L = Op();\n\t\n\t\/\/ Check that we got a table:\n\tif (!lua_istable(L, a_ChunkCoordTableStackPos))\n\t{\n\t\tLOGWARNING(\"%s: The parameter is not a table of coords (got %s). Ignoring the call.\",\n\t\t\t__FUNCTION__, lua_typename(L, lua_type(L, a_ChunkCoordTableStackPos))\n\t\t);\n\t\tL.LogStackTrace();\n\t\treturn false;\n\t}\n\t\n\t\/\/ Add each set of coords:\n\tint NumChunks = luaL_getn(L, a_ChunkCoordTableStackPos);\n\tm_Chunks.reserve((size_t)NumChunks);\n\tfor (int idx = 1; idx <= NumChunks; idx++)\n\t{\n\t\t\/\/ Push the idx-th element of the array onto stack top, check that it's a table:\n\t\tlua_rawgeti(L, a_ChunkCoordTableStackPos, idx);\n\t\tif (!lua_istable(L, -1))\n\t\t{\n\t\t\tLOGWARNING(\"%s: Element #%d is not a table (got %s). Ignoring the element.\",\n\t\t\t\t__FUNCTION__, idx, lua_typename(L, -1)\n\t\t\t);\n\t\t\tL.LogStackTrace();\n\t\t\tlua_pop(L, 1);\n\t\t\tcontinue;\n\t\t}\n\t\tAddChunkCoord(L, idx);\n\t\tlua_pop(L, 1);\n\t}\n\t\n\t\/\/ If there are no chunks, log a warning and return failure:\n\tif (m_Chunks.empty())\n\t{\n\t\tLOGWARNING(\"%s: Zero chunks to stay.\", __FUNCTION__);\n\t\tL.LogStackTrace();\n\t\treturn false;\n\t}\n\t\n\t\/\/ All ok\n\treturn true;\n}\n\n\n\n\n\nvoid cLuaChunkStay::AddChunkCoord(cLuaState & L, int a_Index)\n{\n\t\/\/ Check that the element has 2 coords:\n\tint NumCoords = luaL_getn(L, -1);\n\tif (NumCoords != 2)\n\t{\n\t\tLOGWARNING(\"%s: Element #%d doesn't contain 2 coords (got %d). Ignoring the element.\",\n\t\t\t__FUNCTION__, a_Index, NumCoords\n\t\t);\n\t\treturn;\n\t}\n\t\n\t\/\/ Read the two coords from the element:\n\tlua_rawgeti(L, -1, 1);\n\tlua_rawgeti(L, -2, 2);\n\tint ChunkX = luaL_checkint(L, -2);\n\tint ChunkZ = luaL_checkint(L, -1);\n\tlua_pop(L, 2);\n\t\n\t\/\/ Check that a coord is not yet present:\n\tfor (cChunkCoordsVector::iterator itr = m_Chunks.begin(), end = m_Chunks.end(); itr != end; ++itr)\n\t{\n\t\tif ((itr->m_ChunkX == ChunkX) && (itr->m_ChunkZ == ChunkZ))\n\t\t{\n\t\t\tLOGWARNING(\"%s: Element #%d is a duplicate, ignoring it.\",\n\t\t\t\t__FUNCTION__, a_Index\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}  \/\/ for itr - m_Chunks[]\n\t\n\tm_Chunks.push_back(cChunkCoords(ChunkX, ChunkZ));\n}\n\n\n\n\n\nvoid cLuaChunkStay::Enable(cChunkMap & a_ChunkMap, int a_OnChunkAvailableStackPos, int a_OnAllChunksAvailableStackPos)\n{\n\t\/\/ Get the references to the callback functions:\n\tm_LuaState = &m_Plugin.GetLuaState();\n\tm_OnChunkAvailable.RefStack(*m_LuaState, a_OnChunkAvailableStackPos);\n\tm_OnAllChunksAvailable.RefStack(*m_LuaState, a_OnAllChunksAvailableStackPos);\n\t\n\t\/\/ Enable the ChunkStay:\n\tsuper::Enable(a_ChunkMap);\n}\n\n\n\n\n\nvoid cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ)\n{\n\tcPluginLua::cOperation Op(m_Plugin);\n\tOp().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ);\n}\n\n\n\n\n\nbool cLuaChunkStay::OnAllChunksAvailable(void)\n{\n\t{\n\t\t\/\/ Call the callback:\n\t\tcPluginLua::cOperation Op(m_Plugin);\n\t\tOp().Call((int)m_OnAllChunksAvailable);\n\t\t\n\t\t\/\/ Remove the callback references - they won't be needed anymore\n\t\tm_OnChunkAvailable.UnRef();\n\t\tm_OnAllChunksAvailable.UnRef();\n\t}\n\t\n\t\/\/ Disable the ChunkStay by returning true\n\treturn true;\n}\n\n\n\n\n\nvoid cLuaChunkStay::OnDisabled(void)\n{\n\t\/\/ This object is no longer needed, delete it\n\tdelete this;\n}\n\n\n\n\nLuaChunkStay: Fixed a crash on unused callback.\n\/\/ LuaChunkStay.cpp\n\n\/\/ Implements the cLuaChunkStay class representing a cChunkStay binding for plugins, used by cWorld:ChunkStay() Lua API\n\n#include \"Globals.h\"\n#include \"LuaChunkStay.h\"\n#include \"PluginLua.h\"\n\n\n\n\n\ncLuaChunkStay::cLuaChunkStay(cPluginLua & a_Plugin) :\n\tm_Plugin(a_Plugin),\n\tm_LuaState(NULL)\n{\n}\n\n\n\n\n\nbool cLuaChunkStay::AddChunks(int a_ChunkCoordTableStackPos)\n{\n\t\/\/ This function is expected to be called just once, with all the coords in a table\n\tASSERT(m_Chunks.empty());\n\t\n\tcPluginLua::cOperation Op(m_Plugin);\n\tcLuaState & L = Op();\n\t\n\t\/\/ Check that we got a table:\n\tif (!lua_istable(L, a_ChunkCoordTableStackPos))\n\t{\n\t\tLOGWARNING(\"%s: The parameter is not a table of coords (got %s). Ignoring the call.\",\n\t\t\t__FUNCTION__, lua_typename(L, lua_type(L, a_ChunkCoordTableStackPos))\n\t\t);\n\t\tL.LogStackTrace();\n\t\treturn false;\n\t}\n\t\n\t\/\/ Add each set of coords:\n\tint NumChunks = luaL_getn(L, a_ChunkCoordTableStackPos);\n\tm_Chunks.reserve((size_t)NumChunks);\n\tfor (int idx = 1; idx <= NumChunks; idx++)\n\t{\n\t\t\/\/ Push the idx-th element of the array onto stack top, check that it's a table:\n\t\tlua_rawgeti(L, a_ChunkCoordTableStackPos, idx);\n\t\tif (!lua_istable(L, -1))\n\t\t{\n\t\t\tLOGWARNING(\"%s: Element #%d is not a table (got %s). Ignoring the element.\",\n\t\t\t\t__FUNCTION__, idx, lua_typename(L, -1)\n\t\t\t);\n\t\t\tL.LogStackTrace();\n\t\t\tlua_pop(L, 1);\n\t\t\tcontinue;\n\t\t}\n\t\tAddChunkCoord(L, idx);\n\t\tlua_pop(L, 1);\n\t}\n\t\n\t\/\/ If there are no chunks, log a warning and return failure:\n\tif (m_Chunks.empty())\n\t{\n\t\tLOGWARNING(\"%s: Zero chunks to stay.\", __FUNCTION__);\n\t\tL.LogStackTrace();\n\t\treturn false;\n\t}\n\t\n\t\/\/ All ok\n\treturn true;\n}\n\n\n\n\n\nvoid cLuaChunkStay::AddChunkCoord(cLuaState & L, int a_Index)\n{\n\t\/\/ Check that the element has 2 coords:\n\tint NumCoords = luaL_getn(L, -1);\n\tif (NumCoords != 2)\n\t{\n\t\tLOGWARNING(\"%s: Element #%d doesn't contain 2 coords (got %d). Ignoring the element.\",\n\t\t\t__FUNCTION__, a_Index, NumCoords\n\t\t);\n\t\treturn;\n\t}\n\t\n\t\/\/ Read the two coords from the element:\n\tlua_rawgeti(L, -1, 1);\n\tlua_rawgeti(L, -2, 2);\n\tint ChunkX = luaL_checkint(L, -2);\n\tint ChunkZ = luaL_checkint(L, -1);\n\tlua_pop(L, 2);\n\t\n\t\/\/ Check that a coord is not yet present:\n\tfor (cChunkCoordsVector::iterator itr = m_Chunks.begin(), end = m_Chunks.end(); itr != end; ++itr)\n\t{\n\t\tif ((itr->m_ChunkX == ChunkX) && (itr->m_ChunkZ == ChunkZ))\n\t\t{\n\t\t\tLOGWARNING(\"%s: Element #%d is a duplicate, ignoring it.\",\n\t\t\t\t__FUNCTION__, a_Index\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t}  \/\/ for itr - m_Chunks[]\n\t\n\tm_Chunks.push_back(cChunkCoords(ChunkX, ChunkZ));\n}\n\n\n\n\n\nvoid cLuaChunkStay::Enable(cChunkMap & a_ChunkMap, int a_OnChunkAvailableStackPos, int a_OnAllChunksAvailableStackPos)\n{\n\t\/\/ Get the references to the callback functions:\n\tm_LuaState = &m_Plugin.GetLuaState();\n\tm_OnChunkAvailable.RefStack(*m_LuaState, a_OnChunkAvailableStackPos);\n\tm_OnAllChunksAvailable.RefStack(*m_LuaState, a_OnAllChunksAvailableStackPos);\n\t\n\t\/\/ Enable the ChunkStay:\n\tsuper::Enable(a_ChunkMap);\n}\n\n\n\n\n\nvoid cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ)\n{\n\tif (m_OnChunkAvailable.IsValid())\n\t{\n\t\tcPluginLua::cOperation Op(m_Plugin);\n\t\tOp().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ);\n\t}\n}\n\n\n\n\n\nbool cLuaChunkStay::OnAllChunksAvailable(void)\n{\n\tif (m_OnAllChunksAvailable.IsValid())\n\t{\n\t\t\/\/ Call the callback:\n\t\tcPluginLua::cOperation Op(m_Plugin);\n\t\tOp().Call((int)m_OnAllChunksAvailable);\n\t\t\n\t\t\/\/ Remove the callback references - they won't be needed anymore\n\t\tm_OnChunkAvailable.UnRef();\n\t\tm_OnAllChunksAvailable.UnRef();\n\t}\n\t\n\t\/\/ Disable the ChunkStay by returning true\n\treturn true;\n}\n\n\n\n\n\nvoid cLuaChunkStay::OnDisabled(void)\n{\n\t\/\/ This object is no longer needed, delete it\n\tdelete this;\n}\n\n\n\n\n<|endoftext|>"}
{"text":"\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company.  For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions.  For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\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 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file.  Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights.  These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"ansiescapecodehandler.h\"\n#include \"outputformatter.h\"\n#include \"theme\/theme.h\"\n\n#include \n#include \n\nnamespace Utils {\n\nnamespace Internal {\n\nclass OutputFormatterPrivate\n{\npublic:\n    OutputFormatterPrivate()\n        : plainTextEdit(0)\n        , formats(0)\n        , escapeCodeHandler(new AnsiEscapeCodeHandler)\n        , overwriteOutput(false)\n    {\n    }\n\n    ~OutputFormatterPrivate()\n    {\n        delete[] formats;\n        delete escapeCodeHandler;\n    }\n\n    QPlainTextEdit *plainTextEdit;\n    QTextCharFormat *formats;\n    QFont font;\n    QTextCursor cursor;\n    AnsiEscapeCodeHandler *escapeCodeHandler;\n    bool overwriteOutput;\n};\n\n} \/\/ namespace Internal\n\nOutputFormatter::OutputFormatter()\n    : d(new Internal::OutputFormatterPrivate)\n{\n}\n\nOutputFormatter::~OutputFormatter()\n{\n    delete d;\n}\n\nQPlainTextEdit *OutputFormatter::plainTextEdit() const\n{\n    return d->plainTextEdit;\n}\n\nvoid OutputFormatter::setPlainTextEdit(QPlainTextEdit *plainText)\n{\n    d->plainTextEdit = plainText;\n    d->cursor = plainText ? plainText->textCursor() : QTextCursor();\n    initFormats();\n}\n\nvoid OutputFormatter::appendMessage(const QString &text, OutputFormat format)\n{\n    appendMessage(text, d->formats[format]);\n}\n\nvoid OutputFormatter::appendMessage(const QString &text, const QTextCharFormat &format)\n{\n    if (!d->cursor.atEnd())\n        d->cursor.movePosition(QTextCursor::End);\n\n    foreach (const FormattedText &output, parseAnsi(text, format)) {\n        int startPos = 0;\n        int crPos = -1;\n        while ((crPos = output.text.indexOf(QLatin1Char('\\r'), startPos)) >= 0)  {\n            append(d->cursor, output.text.mid(startPos, crPos - startPos), output.format);\n            startPos = crPos + 1;\n            d->overwriteOutput = true;\n        }\n        if (startPos < output.text.count())\n            append(d->cursor, output.text.mid(startPos), output.format);\n    }\n}\n\nQTextCharFormat OutputFormatter::charFormat(OutputFormat format) const\n{\n    return d->formats[format];\n}\n\nQList OutputFormatter::parseAnsi(const QString &text, const QTextCharFormat &format)\n{\n    return d->escapeCodeHandler->parseText(FormattedText(text, format));\n}\n\nvoid OutputFormatter::append(QTextCursor &cursor, const QString &text,\n                             const QTextCharFormat &format)\n{\n    if (d->overwriteOutput) {\n        cursor.clearSelection();\n        cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n        d->overwriteOutput = false;\n    }\n    cursor.insertText(text, format);\n}\n\nvoid OutputFormatter::clearLastLine()\n{\n    if (!d->cursor.atEnd())\n        d->cursor.movePosition(QTextCursor::End);\n    d->cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n    d->cursor.removeSelectedText();\n}\n\nvoid OutputFormatter::initFormats()\n{\n    if (!plainTextEdit())\n        return;\n\n    QFont boldFont = d->font;\n    boldFont.setBold(true);\n\n    d->formats = new QTextCharFormat[NumberOfFormats];\n\n    Theme *theme = creatorTheme();\n\n    \/\/ NormalMessageFormat\n    d->formats[NormalMessageFormat].setFont(boldFont);\n    d->formats[NormalMessageFormat].setForeground(theme->color(Theme::OutputFormatter_NormalMessageTextColor));\n\n    \/\/ ErrorMessageFormat\n    d->formats[ErrorMessageFormat].setFont(boldFont);\n    d->formats[ErrorMessageFormat].setForeground(theme->color(Theme::OutputFormatter_ErrorMessageTextColor));\n\n    \/\/ StdOutFormat\n    d->formats[StdOutFormat].setFont(d->font);\n    d->formats[StdOutFormat].setForeground(theme->color(Theme::OutputFormatter_StdOutTextColor));\n    d->formats[StdOutFormatSameLine] = d->formats[StdOutFormat];\n\n    \/\/ StdErrFormat\n    d->formats[StdErrFormat].setFont(d->font);\n    d->formats[StdErrFormat].setForeground(theme->color(Theme::OutputFormatter_StdErrTextColor));\n    d->formats[StdErrFormatSameLine] = d->formats[StdErrFormat];\n\n    d->formats[DebugFormat].setFont(d->font);\n    d->formats[DebugFormat].setForeground(theme->color(Theme::OutputFormatter_DebugTextColor));\n}\n\nvoid OutputFormatter::handleLink(const QString &href)\n{\n    Q_UNUSED(href);\n}\n\nQFont OutputFormatter::font() const\n{\n    return d->font;\n}\n\nvoid OutputFormatter::setFont(const QFont &font)\n{\n    d->font = font;\n    initFormats();\n}\n\nvoid OutputFormatter::flush()\n{\n    d->escapeCodeHandler->endFormatScope();\n}\n\n} \/\/ namespace Utils\nUtils: Remove unneeded double indirection in OutputFormatter\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company.  For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions.  For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\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 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file.  Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights.  These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"ansiescapecodehandler.h\"\n#include \"outputformatter.h\"\n#include \"theme\/theme.h\"\n\n#include \n#include \n\nnamespace Utils {\n\nnamespace Internal {\n\nclass OutputFormatterPrivate\n{\npublic:\n    OutputFormatterPrivate()\n        : plainTextEdit(0), overwriteOutput(false)\n    {}\n\n    QPlainTextEdit *plainTextEdit;\n    QTextCharFormat formats[NumberOfFormats];\n    QFont font;\n    QTextCursor cursor;\n    AnsiEscapeCodeHandler escapeCodeHandler;\n    bool overwriteOutput;\n};\n\n} \/\/ namespace Internal\n\nOutputFormatter::OutputFormatter()\n    : d(new Internal::OutputFormatterPrivate)\n{\n}\n\nOutputFormatter::~OutputFormatter()\n{\n    delete d;\n}\n\nQPlainTextEdit *OutputFormatter::plainTextEdit() const\n{\n    return d->plainTextEdit;\n}\n\nvoid OutputFormatter::setPlainTextEdit(QPlainTextEdit *plainText)\n{\n    d->plainTextEdit = plainText;\n    d->cursor = plainText ? plainText->textCursor() : QTextCursor();\n    initFormats();\n}\n\nvoid OutputFormatter::appendMessage(const QString &text, OutputFormat format)\n{\n    appendMessage(text, d->formats[format]);\n}\n\nvoid OutputFormatter::appendMessage(const QString &text, const QTextCharFormat &format)\n{\n    if (!d->cursor.atEnd())\n        d->cursor.movePosition(QTextCursor::End);\n\n    foreach (const FormattedText &output, parseAnsi(text, format)) {\n        int startPos = 0;\n        int crPos = -1;\n        while ((crPos = output.text.indexOf(QLatin1Char('\\r'), startPos)) >= 0)  {\n            append(d->cursor, output.text.mid(startPos, crPos - startPos), output.format);\n            startPos = crPos + 1;\n            d->overwriteOutput = true;\n        }\n        if (startPos < output.text.count())\n            append(d->cursor, output.text.mid(startPos), output.format);\n    }\n}\n\nQTextCharFormat OutputFormatter::charFormat(OutputFormat format) const\n{\n    return d->formats[format];\n}\n\nQList OutputFormatter::parseAnsi(const QString &text, const QTextCharFormat &format)\n{\n    return d->escapeCodeHandler.parseText(FormattedText(text, format));\n}\n\nvoid OutputFormatter::append(QTextCursor &cursor, const QString &text,\n                             const QTextCharFormat &format)\n{\n    if (d->overwriteOutput) {\n        cursor.clearSelection();\n        cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n        d->overwriteOutput = false;\n    }\n    cursor.insertText(text, format);\n}\n\nvoid OutputFormatter::clearLastLine()\n{\n    if (!d->cursor.atEnd())\n        d->cursor.movePosition(QTextCursor::End);\n    d->cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);\n    d->cursor.removeSelectedText();\n}\n\nvoid OutputFormatter::initFormats()\n{\n    if (!plainTextEdit())\n        return;\n\n    QFont boldFont = d->font;\n    boldFont.setBold(true);\n\n    Theme *theme = creatorTheme();\n\n    \/\/ NormalMessageFormat\n    d->formats[NormalMessageFormat].setFont(boldFont);\n    d->formats[NormalMessageFormat].setForeground(theme->color(Theme::OutputFormatter_NormalMessageTextColor));\n\n    \/\/ ErrorMessageFormat\n    d->formats[ErrorMessageFormat].setFont(boldFont);\n    d->formats[ErrorMessageFormat].setForeground(theme->color(Theme::OutputFormatter_ErrorMessageTextColor));\n\n    \/\/ StdOutFormat\n    d->formats[StdOutFormat].setFont(d->font);\n    d->formats[StdOutFormat].setForeground(theme->color(Theme::OutputFormatter_StdOutTextColor));\n    d->formats[StdOutFormatSameLine] = d->formats[StdOutFormat];\n\n    \/\/ StdErrFormat\n    d->formats[StdErrFormat].setFont(d->font);\n    d->formats[StdErrFormat].setForeground(theme->color(Theme::OutputFormatter_StdErrTextColor));\n    d->formats[StdErrFormatSameLine] = d->formats[StdErrFormat];\n\n    d->formats[DebugFormat].setFont(d->font);\n    d->formats[DebugFormat].setForeground(theme->color(Theme::OutputFormatter_DebugTextColor));\n}\n\nvoid OutputFormatter::handleLink(const QString &href)\n{\n    Q_UNUSED(href);\n}\n\nQFont OutputFormatter::font() const\n{\n    return d->font;\n}\n\nvoid OutputFormatter::setFont(const QFont &font)\n{\n    d->font = font;\n    initFormats();\n}\n\nvoid OutputFormatter::flush()\n{\n    d->escapeCodeHandler.endFormatScope();\n}\n\n} \/\/ namespace Utils\n<|endoftext|>"}
{"text":"\/\/ NOTE: Breadboard code --- can refactor into nice bits later.  This is \n\/\/ not meant to be final in any way, but I'd like to lay as much out here\n\/\/ and see what it looks like before we go making fancy classes to do \n\/\/ stuff and realize we did something stupid.\n\/\/\n\/\/ The MPI environment needs to be sectioned away in a singleton that can\n\/\/  work even if the MPI isn't present.  I have code that can do this with\n\/\/  minimal confusion.\n\/\/ It would probably be nice to have some kind of coherent logging here but\n\/\/  I haven't thought hard about it.  I would like to not have to depend\n\/\/  on anything external, unless there is a compelling reason.  Like there\n\/\/  are some drop-in header-only logging things we could use.\n\/\/ Since this is in MPI the logging either has to know that (which would\n\/\/  be easy to mess up) or dead simple (like one per MPI task).\n\/\/ Bunch of cut-n-pasted stuff for reading header stuff.  This should be\n\/\/  sectioned off into an IO manager, etc.  Also should not come from header?\n\/\/ The image math looks clunky, I had better looking stuff in an earlier \n\/\/  iteration of C3.  I am not opposed to extending the containers \n\/\/  to have more math semantics, but I want it done cleanly.\n\/\/ Probably using OpenMP to iterate over HDUs is enough work per thread to\n\/\/  get a payoff.  We are probably looking at 1-2 MPI tasks per edison node.\n\/\/  More than that is not enough memory and we seem to peg the I\/O. \n\/\/ IO interface through CFITSIO needs to have traits to map types.\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"C3.hh\"\n#include \"DECam.hh\"\n\n\/\/ Convert MPI error status into an exception.\n\nvoid assert_mpi_status( const int mpi_status )\n{\n    if( mpi_status == MPI_SUCCESS ) return;\n   \n    int error_class;\n    MPI_Error_class( mpi_status, &error_class );\n\n    char error_string[ MPI_MAX_ERROR_STRING ];\n    int length;\n    MPI_Error_string( mpi_status, error_string, &length );\n\n    std::stringstream ss;\n    ss << \"MPI error code \" << mpi_status;\n    ss << \" | error class \" << error_class;\n    ss << \" | \"             << error_string;\n\n    throw C3::Exception( ss.str() );\n}\n\n\/\/ Convert CFITSIO error status into an exception.\n\nvoid assert_cfitsio_status( const int cfitsio_status )\n{\n    if( cfitsio_status == 0 ) return;\n\n    char message[ FLEN_STATUS ];\n    fits_get_errstatus( cfitsio_status, message );\n\n    std::stringstream ss;\n    ss << message;\n\n    throw C3::Exception( ss.str() );\n}\n\n\/\/ \n\nint main( int argc, char* argv[] )\n{\n\n    \/\/ Initialize MPI environment.\n\n    int mpi_status;\n    mpi_status = MPI_Init( &argc, &argv );\n    assert_mpi_status( mpi_status );\n\n    int mpi_size;\n    mpi_status = MPI_Comm_size( MPI_COMM_WORLD, &mpi_size );\n    assert_mpi_status( mpi_status );\n    \n    int mpi_rank;\n    mpi_status = MPI_Comm_rank( MPI_COMM_WORLD, &mpi_rank );\n    assert_mpi_status( mpi_status );\n\n    \/\/ Need to load up our assets (bias, flats, cross-talk model, etc.)\n    \/\/ TODO\n\n    \/\/ Main loop over exposures, round-robin over MPI task.\n\n    for( size_t arg = 1 + mpi_rank; arg < argc; arg += mpi_size )\n    {\n\n        \/\/ Open FITS file.\n\n        int cfitsio_status = 0;\n\n        fitsfile* fptr = 0;\n        fits_open_file( &fptr, argv[ arg ], READONLY, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        \/\/ Number of HDUs.\n\n        int numhdus = 0;\n        fits_get_num_hdus( fptr, &numhdus, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        \/\/ Load remaining HDUs into the exposure.\n\n        std::vector< C3::Image< float > > exposure; \/\/ or std::map< std::string, C3::Image< float >* >, whatevz\n\n        for( int hdunum = 1; hdunum < numhdus; ++ hdunum )\n        {\n            \n            \/\/ Move to the next HDU.\n\n            int hdutype = IMAGE_HDU;\n            fits_movrel_hdu( fptr, 1, &hdutype, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ DATASEC.\n\n            size_t d_imin, d_imax, d_jmin, d_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASEC\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> d_imin >> tmp >> d_imax >> tmp >> d_jmin >> tmp >> d_jmax;\n                d_imin -= 1;\n                d_jmin -= 1;\n            }\n\n            \/\/ DATASEC A.\n\n            size_t da_imin, da_imax, da_jmin, da_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASECA\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> da_imin >> tmp >> da_imax >> tmp >> da_jmin >> tmp >> da_jmax;\n                da_imin -= 1;\n                da_jmin -= 1;\n            }\n\n            \/\/ BIASSEC A.\n\n            size_t ba_imin, ba_imax, ba_jmin, ba_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"BIASSECA\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> ba_imin >> tmp >> ba_imax >> tmp >> ba_jmin >> tmp >> ba_jmax;\n                ba_imin -= 1;\n                ba_jmin -= 1;\n            }\n\n            \/\/ DATASEC B.\n\n            size_t db_imin, db_imax, db_jmin, db_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASECB\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> db_imin >> tmp >> db_imax >> tmp >> db_jmin >> tmp >> db_jmax;\n                db_imin -= 1;\n                db_jmin -= 1;\n            }\n\n            \/\/ BIASSEC B.\n\n            size_t bb_imin, bb_imax, bb_jmin, bb_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"BIASSECB\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> bb_imin >> tmp >> bb_imax >> tmp >> bb_jmin >> tmp >> bb_jmax;\n                bb_imin -= 1;\n                bb_jmin -= 1;\n            }\n\n            \/\/ Image parameters.\n\n            int  maxdim = 2;\n            int  bitpix = 0;\n            int  naxis  = 0;\n            long naxes[ 2 ] = { 0, 0 };\n\n            fits_get_img_param( fptr, maxdim, &bitpix, &naxis, naxes, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ Create empty image.\n\n            C3::Image< float > image = C3::Image< float >::create( naxes[ 0 ], naxes[ 1 ] );\n\n            \/\/ Fill image.\n\n            int     datatype  = TFLOAT; \/\/C3::Traits< T >::cfitsio_type;\n            long    firstelem = 1;\n            long    nelements = naxes[ 0 ] * naxes[ 1 ];\n            float   nulval    = 0;\n            int     anynul    = 0;\n\n            fits_read_img( fptr, datatype, firstelem, nelements, &nulval, image._data, &anynul, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ Overscan subtraction.\n\n            C3::View< float > dataseca  = C3::View< float >::create( image, da_imin, da_imax - da_imin, da_jmin, da_jmax - da_jmin );\n            C3::View< float > biasseca  = C3::View< float >::create( image, ba_imin, ba_imax - ba_imin, ba_jmin, ba_jmax - ba_jmin );\n            dataseca -= C3::Reduce< C3::Median, C3::View< float >, C3::Column< float > >::compute( biasseca );\n\n            C3::View< float > datasecb = C3::View< float >::create( image, db_imin, db_imax - db_imin, db_jmin, db_jmax - db_jmin );\n            C3::View< float > biassecb = C3::View< float >::create( image, bb_imin, bb_imax - bb_imin, bb_jmin, bb_jmax - bb_jmin );\n            datasecb -= C3::Reduce< C3::Median, C3::View< float >, C3::Column< float > >::compute( biassecb );\n\n            \/\/ New image from the view.\n\n            C3::View< float >  datasec = C3::View< float >::create( image, d_imin, d_imax - d_imin, d_jmin, d_jmax - d_jmin );\n            C3::Image< float > trimmed = C3::Image< float >::create( datasec.ncols(), datasec.nrows() );\n            trimmed = datasec;\n            exposure.push_back( trimmed );\n\n        }\n\n        \/\/ Close FITS file.\n\n        fits_close_file( fptr, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        if( mpi_rank == 0 ) std::cerr << argv[ arg ] << std::endl; \/\/ tmp\n\n        \/\/ now do more stuff, subtract bias, flat field, etc...\n\n    }\n\n    \/\/ Goodbye.\n\n    mpi_status = MPI_Finalize();\n    return 0;\n\n}\nGoing to be re-done soon anyway.\/\/ NOTE: Breadboard code --- can refactor into nice bits later.  This is \n\/\/ not meant to be final in any way, but I'd like to lay as much out here\n\/\/ and see what it looks like before we go making fancy classes to do \n\/\/ stuff and realize we did something stupid.\n\/\/\n\/\/ The MPI environment needs to be sectioned away in a singleton that can\n\/\/  work even if the MPI isn't present.  I have code that can do this with\n\/\/  minimal confusion.\n\/\/ It would probably be nice to have some kind of coherent logging here but\n\/\/  I haven't thought hard about it.  I would like to not have to depend\n\/\/  on anything external, unless there is a compelling reason.  Like there\n\/\/  are some drop-in header-only logging things we could use.\n\/\/ Since this is in MPI the logging either has to know that (which would\n\/\/  be easy to mess up) or dead simple (like one per MPI task).\n\/\/ Bunch of cut-n-pasted stuff for reading header stuff.  This should be\n\/\/  sectioned off into an IO manager, etc.  Also should not come from header?\n\/\/ The image math looks clunky, I had better looking stuff in an earlier \n\/\/  iteration of C3.  I am not opposed to extending the containers \n\/\/  to have more math semantics, but I want it done cleanly.\n\/\/ Probably using OpenMP to iterate over HDUs is enough work per thread to\n\/\/  get a payoff.  We are probably looking at 1-2 MPI tasks per edison node.\n\/\/  More than that is not enough memory and we seem to peg the I\/O. \n\/\/ IO interface through CFITSIO needs to have traits to map types.\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"C3.hh\"\n#include \"DECam.hh\"\n\n\/\/ Convert MPI error status into an exception.\n\nvoid assert_mpi_status( const int mpi_status )\n{\n    if( mpi_status == MPI_SUCCESS ) return;\n   \n    int error_class;\n    MPI_Error_class( mpi_status, &error_class );\n\n    char error_string[ MPI_MAX_ERROR_STRING ];\n    int length;\n    MPI_Error_string( mpi_status, error_string, &length );\n\n    std::stringstream ss;\n    ss << \"MPI error code \" << mpi_status;\n    ss << \" | error class \" << error_class;\n    ss << \" | \"             << error_string;\n\n    throw C3::Exception( ss.str() );\n}\n\n\/\/ Convert CFITSIO error status into an exception.\n\nvoid assert_cfitsio_status( const int cfitsio_status )\n{\n    if( cfitsio_status == 0 ) return;\n\n    char message[ FLEN_STATUS ];\n    fits_get_errstatus( cfitsio_status, message );\n\n    std::stringstream ss;\n    ss << message;\n\n    throw C3::Exception( ss.str() );\n}\n\n\/\/ \n\nint main( int argc, char* argv[] )\n{\n\n    \/\/ Initialize MPI environment.\n\n    int mpi_status;\n    mpi_status = MPI_Init( &argc, &argv );\n    assert_mpi_status( mpi_status );\n\n    int mpi_size;\n    mpi_status = MPI_Comm_size( MPI_COMM_WORLD, &mpi_size );\n    assert_mpi_status( mpi_status );\n    \n    int mpi_rank;\n    mpi_status = MPI_Comm_rank( MPI_COMM_WORLD, &mpi_rank );\n    assert_mpi_status( mpi_status );\n\n    \/\/ Need to load up our assets (bias, flats, cross-talk model, etc.)\n    \/\/ TODO\n\n    \/\/ Main loop over exposures, round-robin over MPI task.\n\n    for( size_t arg = 1 + mpi_rank; arg < argc; arg += mpi_size )\n    {\n\n        \/\/ Open FITS file.\n\n        int cfitsio_status = 0;\n\n        fitsfile* fptr = 0;\n        fits_open_file( &fptr, argv[ arg ], READONLY, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        \/\/ Number of HDUs.\n\n        int numhdus = 0;\n        fits_get_num_hdus( fptr, &numhdus, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        \/\/ Load remaining HDUs into the exposure.\n\n        std::vector< C3::Image< float > > exposure; \/\/ or std::map< std::string, C3::Image< float >* >, whatevz\n\n        for( int hdunum = 1; hdunum < numhdus; ++ hdunum )\n        {\n            \n            \/\/ Move to the next HDU.\n\n            int hdutype = IMAGE_HDU;\n            fits_movrel_hdu( fptr, 1, &hdutype, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ DATASEC.\n\n            size_t d_imin, d_imax, d_jmin, d_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASEC\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> d_imin >> tmp >> d_imax >> tmp >> d_jmin >> tmp >> d_jmax;\n                d_imin -= 1;\n                d_jmin -= 1;\n            }\n\n            \/\/ DATASEC A.\n\n            size_t da_imin, da_imax, da_jmin, da_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASECA\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> da_imin >> tmp >> da_imax >> tmp >> da_jmin >> tmp >> da_jmax;\n                da_imin -= 1;\n                da_jmin -= 1;\n            }\n\n            \/\/ BIASSEC A.\n\n            size_t ba_imin, ba_imax, ba_jmin, ba_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"BIASSECA\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> ba_imin >> tmp >> ba_imax >> tmp >> ba_jmin >> tmp >> ba_jmax;\n                ba_imin -= 1;\n                ba_jmin -= 1;\n            }\n\n            \/\/ DATASEC B.\n\n            size_t db_imin, db_imax, db_jmin, db_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"DATASECB\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> db_imin >> tmp >> db_imax >> tmp >> db_jmin >> tmp >> db_jmax;\n                db_imin -= 1;\n                db_jmin -= 1;\n            }\n\n            \/\/ BIASSEC B.\n\n            size_t bb_imin, bb_imax, bb_jmin, bb_jmax;\n\n            {\n                char buffer[ FLEN_VALUE ];\n\n                fits_read_key( fptr, TSTRING, \"BIASSECB\", buffer, 0, &cfitsio_status );\n                assert_cfitsio_status( cfitsio_status );\n\n                char tmp;\n                std::stringstream ss( buffer );\n                ss >> tmp >> bb_imin >> tmp >> bb_imax >> tmp >> bb_jmin >> tmp >> bb_jmax;\n                bb_imin -= 1;\n                bb_jmin -= 1;\n            }\n\n            \/\/ Image parameters.\n\n            int  maxdim = 2;\n            int  bitpix = 0;\n            int  naxis  = 0;\n            long naxes[ 2 ] = { 0, 0 };\n\n            fits_get_img_param( fptr, maxdim, &bitpix, &naxis, naxes, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ Create empty image.\n\n            C3::Image< float > image = C3::Image< float >::create( naxes[ 0 ], naxes[ 1 ] );\n\n            \/\/ Fill image.\n\n            int     datatype  = TFLOAT; \/\/C3::Traits< T >::cfitsio_type;\n            long    firstelem = 1;\n            long    nelements = naxes[ 0 ] * naxes[ 1 ];\n            float   nulval    = 0;\n            int     anynul    = 0;\n\n            fits_read_img( fptr, datatype, firstelem, nelements, &nulval, image._data, &anynul, &cfitsio_status );\n            assert_cfitsio_status( cfitsio_status );\n\n            \/\/ Overscan subtraction.\n\n            C3::View< float > dataseca  = C3::View< float >::create( image, da_imin, da_imax - da_imin, da_jmin, da_jmax - da_jmin );\n            C3::View< float > biasseca  = C3::View< float >::create( image, ba_imin, ba_imax - ba_imin, ba_jmin, ba_jmax - ba_jmin );\n            dataseca -= C3::Reduce< C3::Median, C3::View< float >, C3::Column< float > >::compute( biasseca );\n\n            C3::View< float > datasecb = C3::View< float >::create( image, db_imin, db_imax - db_imin, db_jmin, db_jmax - db_jmin );\n            C3::View< float > biassecb = C3::View< float >::create( image, bb_imin, bb_imax - bb_imin, bb_jmin, bb_jmax - bb_jmin );\n            datasecb -= C3::Reduce< C3::Median, C3::View< float >, C3::Column< float > >::compute( biassecb );\n\n            \/\/ New image from the view.\n\n            C3::View< float >  datasec = C3::View< float >::create( image, d_imin, d_imax - d_imin, d_jmin, d_jmax - d_jmin );\n            C3::Image< float > trimmed = C3::Image< float >::create( datasec.ncols(), datasec.nrows() );\n            trimmed = datasec;\n            exposure.push_back( trimmed );\n\n        }\n\n        \/\/ Close FITS file.\n\n        fits_close_file( fptr, &cfitsio_status );\n        assert_cfitsio_status( cfitsio_status );\n\n        if( mpi_rank == 0 ) std::cerr << argv[ arg ] << std::endl; \/\/ tmp\n\n        \/\/ now do more stuff, subtract bias, flat field, etc...\n\n    }\n\n    \/\/ Goodbye.\n\n    mpi_status = MPI_Finalize();\n    return 0;\n\n}\n<|endoftext|>"}
{"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"assert.hpp\"\n#include \"Function.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/call_graph.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Function.hpp\"\n\nusing namespace eddic;\n        \nmtac::call_graph::~call_graph(){\n    for(auto& node_key : nodes){\n        auto& node = node_key.second;\n\n        for(auto& edge : node->in_edges){\n            edge->source = nullptr;\n            edge->target = nullptr;\n        }\n        \n        for(auto& edge : node->out_edges){\n            edge->source = nullptr;\n            edge->target = nullptr;\n        }\n\n        node->in_edges.clear();\n        node->out_edges.clear();\n    }\n}\n\nmtac::call_graph_node_p mtac::call_graph::node(eddic::Function& function){\n    auto it = nodes.find(function.mangled_name());\n\n    if(it == nodes.end()){\n        auto node = std::make_shared(function);\n        nodes[function.mangled_name()] = node;\n        return node;\n    }\n\n    return it->second;\n}\n        \nmtac::call_graph_edge_p mtac::call_graph::edge(eddic::Function& source, eddic::Function& target){\n    auto source_node = node(source);\n    auto target_node = node(target);\n\n    for(auto& edge : source_node->out_edges){\n        if(edge->target == target_node){\n            return edge;\n        }\n    }\n\n    return nullptr;\n}\n        \nvoid mtac::call_graph::add_edge(eddic::Function& source, eddic::Function& target){\n    auto edge = this->edge(source, target);\n    \n    if(!edge){\n        auto source_node = node(source);\n        auto target_node = node(target);\n\n        edge = std::make_shared(source_node, target_node);\n\n        source_node->out_edges.push_back(edge);\n        target_node->in_edges.push_back(edge);\n    }\n    \n    ++edge->count;\n}\n\nvoid compute_reachable(mtac::Reachable& reachable, mtac::call_graph_node_p node){\n    if(reachable.find(node->function) == reachable.end()){\n        reachable.insert(node->function);\n\n        for(auto& edge : node->out_edges){\n            if(edge->count > 0){\n                compute_reachable(reachable, edge->target);\n            }\n        }\n    }\n}\n\nvoid mtac::call_graph::compute_reachable(){\n    eddic_assert(entry, \"The call graph must be built before computing reachable\");\n\n    release_reachable();\n\n    ::compute_reachable(reachable, entry);\n}\n\nvoid mtac::call_graph::release_reachable(){\n    reachable.clear();\n}\n\nbool mtac::call_graph::is_reachable(eddic::Function& function){\n    return reachable.find(function) != reachable.end();\n}\n\nvoid mtac::build_call_graph(mtac::Program& program){\n    timing_timer timer(program.context->timing(), \"build_cg\");\n\n    auto& cg = program.call_graph;\n\n    for(auto& function : program){\n        for(auto& block : function){\n            for(auto& quadruple : block){\n                if(quadruple.op == mtac::Operator::CALL){\n                    cg.add_edge(function.definition(), quadruple.function());\n                }\n            }\n        }\n\n        if(function.is_main()){\n            cg.entry = cg.node(function.definition());\n        }\n    }\n}\n\nvoid post_dfs_visit(mtac::call_graph_node_p& node, std::vector>& order){\n    for(auto& edge : node->out_edges){\n        if(edge->target->function != node->function){\n            post_dfs_visit(edge->target, order);\n        }\n    }\n\n    order.push_back(node->function);\n}\n        \nstd::vector> mtac::call_graph::topological_order(){\n    std::vector> order;   \n\n    post_dfs_visit(entry, order);\n\n    return order;\n}\nFix call_graph -> cg\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/  http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"assert.hpp\"\n#include \"Function.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/call_graph.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Function.hpp\"\n\nusing namespace eddic;\n\nmtac::call_graph::~call_graph(){\n    for(auto& node_key : nodes){\n        auto& node = node_key.second;\n\n        for(auto& edge : node->in_edges){\n            edge->source = nullptr;\n            edge->target = nullptr;\n        }\n\n        for(auto& edge : node->out_edges){\n            edge->source = nullptr;\n            edge->target = nullptr;\n        }\n\n        node->in_edges.clear();\n        node->out_edges.clear();\n    }\n}\n\nmtac::call_graph_node_p mtac::call_graph::node(eddic::Function& function){\n    auto it = nodes.find(function.mangled_name());\n\n    if(it == nodes.end()){\n        auto node = std::make_shared(function);\n        nodes[function.mangled_name()] = node;\n        return node;\n    }\n\n    return it->second;\n}\n\nmtac::call_graph_edge_p mtac::call_graph::edge(eddic::Function& source, eddic::Function& target){\n    auto source_node = node(source);\n    auto target_node = node(target);\n\n    for(auto& edge : source_node->out_edges){\n        if(edge->target == target_node){\n            return edge;\n        }\n    }\n\n    return nullptr;\n}\n\nvoid mtac::call_graph::add_edge(eddic::Function& source, eddic::Function& target){\n    auto edge = this->edge(source, target);\n\n    if(!edge){\n        auto source_node = node(source);\n        auto target_node = node(target);\n\n        edge = std::make_shared(source_node, target_node);\n\n        source_node->out_edges.push_back(edge);\n        target_node->in_edges.push_back(edge);\n    }\n\n    ++edge->count;\n}\n\nvoid compute_reachable(mtac::Reachable& reachable, mtac::call_graph_node_p node){\n    if(reachable.find(node->function) == reachable.end()){\n        reachable.insert(node->function);\n\n        for(auto& edge : node->out_edges){\n            if(edge->count > 0){\n                compute_reachable(reachable, edge->target);\n            }\n        }\n    }\n}\n\nvoid mtac::call_graph::compute_reachable(){\n    eddic_assert(entry, \"The call graph must be built before computing reachable\");\n\n    release_reachable();\n\n    ::compute_reachable(reachable, entry);\n}\n\nvoid mtac::call_graph::release_reachable(){\n    reachable.clear();\n}\n\nbool mtac::call_graph::is_reachable(eddic::Function& function){\n    return reachable.find(function) != reachable.end();\n}\n\nvoid mtac::build_call_graph(mtac::Program& program){\n    timing_timer timer(program.context->timing(), \"build_cg\");\n\n    auto& cg = program.cg;\n\n    for(auto& function : program){\n        for(auto& block : function){\n            for(auto& quadruple : block){\n                if(quadruple.op == mtac::Operator::CALL){\n                    cg.add_edge(function.definition(), quadruple.function());\n                }\n            }\n        }\n\n        if(function.is_main()){\n            cg.entry = cg.node(function.definition());\n        }\n    }\n}\n\nvoid post_dfs_visit(mtac::call_graph_node_p& node, std::vector>& order){\n    for(auto& edge : node->out_edges){\n        if(edge->target->function != node->function){\n            post_dfs_visit(edge->target, order);\n        }\n    }\n\n    order.push_back(node->function);\n}\n\nstd::vector> mtac::call_graph::topological_order(){\n    std::vector> order;\n\n    post_dfs_visit(entry, order);\n\n    return order;\n}\n<|endoftext|>"}
{"text":"#include \"evaluator.h\"\n#include \"mugen_exception.h\"\n#include \"character.h\"\n#include \"mugen_animation.h\"\n#include \"ast\/all.h\"\n#include \n\n\/* TODO:\n * 1. Change RuntimeValue into an object that stores pointers so that the\n * overhead of copying values is not so high.\n * 2. 1 necessitates garbage collection. Implement precise mark\/sweep.\n * 3. Convert interpreter into a compiler. Refresher\n *   (define intepreter (lambda (env) (lambda (input) (eval env input))))\n *   (define compiler (lambda (input) (let ([compiled (compile input)])\n *                       (lambda (env) (eval env compiled)))))\n * 4. Implement simple optimizations: constant folding, dead code elimintation.\n *\/\n\nusing namespace std;\n\nnamespace Mugen{\n\nstring toString(const RuntimeValue & value){\n    if (value.isString()){\n        return value.getStringValue();\n    }\n    throw MugenException(\"Not a string\");\n}\n\ndouble toNumber(const RuntimeValue & value){\n    if (value.isDouble()){\n        return value.getDoubleValue();\n    }\n    if (value.isBool()){\n        if (value.getBoolValue()){\n            return 1;\n        } else {\n            return 0;\n        }\n    }\n    throw MugenException(\"Not a number\");\n}\n\nbool toBool(const RuntimeValue & value){\n    if (value.isBool()){\n        return value.getBoolValue();\n    }\n    if (value.isDouble()){\n        return value.getDoubleValue() != 0;\n    }\n    throw MugenException(\"Not a bool\");\n}\n\n\/* a meta-circular evaluator! *\/\nclass Evaluator: public Ast::Walker {\npublic:\n    Evaluator(const Environment & environment):\n        environment(environment){\n        }\n\n    const Environment & environment;\n    RuntimeValue result;\n\n    \/* value1 == value2 *\/\n    RuntimeValue same(const RuntimeValue & value1, const RuntimeValue & value2){\n        switch (value1.type){\n            case RuntimeValue::ListOfString : {\n                switch (value2.type){\n                    case RuntimeValue::String : {\n                        const vector & strings = value1.strings_value;\n                        for (vector::const_iterator it = strings.begin(); it != strings.end(); it++){\n                            const string & check = *it;\n                            if (check == value2.string_value){\n                                return RuntimeValue(true);\n                            }\n                        }\n                        return RuntimeValue(false);\n                    }\n                }\n                break;\n            }\n            case RuntimeValue::String : {\n                switch (value2.type){\n                    case RuntimeValue::ListOfString : {\n                        return same(value2, value1);\n                    }\n                    case RuntimeValue::String : {\n                        return toString(value1) == toString(value2);\n                    }\n                }\n                break;\n            }\n            case RuntimeValue::Double : {\n                switch (value2.type){\n                    case RuntimeValue::Double : {\n                        double epsilon = 0.0000001;\n                        return RuntimeValue(fabs(value1.getDoubleValue() - value2.getDoubleValue()) < epsilon);\n                    }\n                }\n                break;\n            }\n        }\n\n        return RuntimeValue(false);\n    }\n   \n    RuntimeValue evaluate(const Ast::Value * value){\n        return Mugen::evaluate(value, environment);\n    }\n\n    RuntimeValue evalIdentifier(const Ast::Identifier & identifier){\n        if (identifier == \"command\"){\n            return RuntimeValue(environment.getCommands());\n        }\n\n        if (identifier == \"anim\"){\n            return RuntimeValue(environment.getCharacter().getAnimation());\n        }\n\n        if (identifier == \"alive\"){\n            \/* FIXME *\/\n            return RuntimeValue(true);\n        }\n\n        if (identifier == \"p2statetype\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        if (identifier == \"animtime\"){\n            return RuntimeValue(environment.getCharacter().getCurrentAnimation()->animationTime());\n        }\n\n        if (identifier == \"animelem\"){\n            \/* FIXME! *\/\n            return RuntimeValue(0);\n        }\n\n        if (identifier == \"time\"){\n            return RuntimeValue(environment.getCharacter().getStateTime());\n        }\n\n        if (identifier == \"A\"){\n            return RuntimeValue(string(\"A\"));\n        }\n        \n        if (identifier == \"S\"){\n            \/* states are just strings *\/\n            return RuntimeValue(string(\"S\"));\n        }\n\n        if (identifier == \"C\"){\n            return RuntimeValue(string(\"C\"));\n        }\n        \n        if (identifier == \"L\"){\n            return RuntimeValue(string(\"L\"));\n        }\n\n        if (identifier == \"statetype\"){\n            return RuntimeValue(environment.getCharacter().getStateType());\n        }\n\n        \/* true if the player has control *\/\n        if (identifier == \"ctrl\"){\n            return RuntimeValue(environment.getCharacter().hasControl());\n        }\n\n        if (identifier == \"stateno\"){\n            return RuntimeValue(environment.getCharacter().getCurrentState());\n        }\n\n        if (identifier == \"power\"){\n            return RuntimeValue(environment.getCharacter().getPower());\n        }\n\n        if (identifier == \"velocity.walk.back.x\"){\n            return RuntimeValue(environment.getCharacter().getWalkBackX());\n        }\n\n        if (identifier == \"velocity.walk.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getWalkForwardX());\n        }\n\n        if (identifier == \"velocity.run.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getRunForwardX());\n        }\n        \n        if (identifier == \"velocity.jump.neu.x\"){\n            return RuntimeValue(environment.getCharacter().getNeutralJumpingX());\n        }\n        \n        if (identifier == \"velocity.jump.y\"){\n            return RuntimeValue(environment.getCharacter().getNeutralJumpingY());\n        }\n\n        if (identifier == \"prevstateno\"){\n            return RuntimeValue(environment.getCharacter().getPreviousState());\n        }\n        \n        if (identifier == \"velocity.run.back.x\"){\n            return RuntimeValue(environment.getCharacter().getRunBackX());\n        }\n        \n        if (identifier == \"velocity.run.back.y\"){\n            return RuntimeValue(environment.getCharacter().getRunBackY());\n        }\n\n        if (identifier == \"velocity.jump.back.x\"){\n            return RuntimeValue(environment.getCharacter().getJumpBack());\n        }\n\n        if (identifier == \"velocity.jump.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getJumpForward());\n        }\n\n        if (identifier == \"velocity.runjump.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getRunJumpForward());\n        }\n\n        ostringstream out;\n        out << \"Unknown identifier '\" << identifier.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onIdenfitier(const Ast::Identifier & identifier){\n        result = evalIdentifier(identifier);\n    }\n\n    RuntimeValue evalKeyword(const Ast::Keyword & keyword){\n        if (keyword == \"vel x\"){\n            return RuntimeValue(environment.getCharacter().getXVelocity());\n        }\n\n        if (keyword == \"vel y\"){\n            return RuntimeValue(environment.getCharacter().getYVelocity());\n        }\n        \n        if (keyword == \"pos y\"){\n            return RuntimeValue(-environment.getCharacter().getYPosition());\n        }\n        \n        if (keyword == \"p2bodydist x\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        ostringstream out;\n        out << \"Unknown keyword '\" << keyword.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onKeyword(const Ast::Keyword & keyword){\n        result = evalKeyword(keyword);\n    }\n\n    RuntimeValue evalString(const Ast::String & string_value){\n        string out;\n        string_value >> out;\n        return RuntimeValue(out);\n    }\n\n    virtual void onString(const Ast::String & string){\n        result = evalString(string);\n    }\n\n    RuntimeValue evalFunction(const Ast::Function & function){\n        if (function == \"const\"){\n            return evaluate(function.getArg1());\n        }\n\n        if (function == \"abs\"){\n            return RuntimeValue(fabs(toNumber(evaluate(function.getArg1()))));\n        }\n\n        if (function == \"var\"){\n            int index = (int) toNumber(evaluate(function.getArg1()));\n            Ast::Value * value = environment.getCharacter().getVariable(index);\n            if (value == 0){\n                ostringstream out;\n                out << \"No variable for index \" << index;\n                throw MugenException(out.str());\n            }\n            return evaluate(value);\n        }\n\n        if (function == \"sysvar\"){\n            int index = (int) toNumber(evaluate(function.getArg1()));\n            Ast::Value * value = environment.getCharacter().getSystemVariable(index);\n            if (value == 0){\n                ostringstream out;\n                out << \"No system variable for index \" << index;\n                throw MugenException(out.str());\n            }\n            return evaluate(value);\n        }\n\n\n        if (function == \"ifelse\"){\n            if (toBool(evaluate(function.getArg1()))){\n                return evaluate(function.getArg2());\n            } else {\n                return evaluate(function.getArg3());\n            }\n        }\n\n        if (function == \"selfanimexist\"){\n            int animation = (int) toNumber(evaluate(function.getArg1()));\n            return RuntimeValue(environment.getCharacter().hasAnimation(animation));\n        }\n\n        \/* Gets the animation-time elapsed since the start of a specified element\n         * of the current animation action. Useful for synchronizing events to\n         * elements of an animation action.\n         *\n         * (reminder: first element of an action is element 1, not 0)\n         *\/\n        if (function == \"animelemtime\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        ostringstream out;\n        out << \"Unknown function '\" << function.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onFunction(const Ast::Function & string){\n        result = evalFunction(string);\n    }\n\n    RuntimeValue evalNumber(const Ast::Number & number){\n        double x;\n        number >> x;\n        return RuntimeValue(x);\n    }\n\n    virtual void onNumber(const Ast::Number & number){\n        result = evalNumber(number);\n    }\n\n    virtual RuntimeValue evalExpressionInfix(const Ast::ExpressionInfix & expression){\n        Global::debug(1) << \"Evaluate expression \" << expression.toString() << endl;\n        using namespace Ast;\n        switch (expression.getExpressionType()){\n            case ExpressionInfix::Or : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) ||\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::XOr : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) ^\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::And : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) &&\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseOr : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) |\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseXOr : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) ^\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseAnd : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) &\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Assignment : {\n                \/* FIXME: is this needed? *\/\n                break;\n            }\n            case ExpressionInfix::Equals : {\n                return same(evaluate(expression.getLeft()), evaluate(expression.getRight()));\n                break;\n            }\n            case ExpressionInfix::Unequals : {\n                return RuntimeValue(!toBool(same(evaluate(expression.getLeft()), evaluate(expression.getRight()))));\n            }\n            case ExpressionInfix::GreaterThanEquals : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) >= toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::GreaterThan : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) > toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::LessThanEquals : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) <= toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::LessThan : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) < toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Add : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) + toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Subtract : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) - toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Multiply : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) * toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Divide : {\n                \/* FIXME: catch divide by 0 *\/\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) \/ toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Modulo : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) % (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Power : {\n                return RuntimeValue(pow(toNumber(evaluate(expression.getLeft())), toNumber(evaluate(expression.getRight()))));\n            }\n        }\n\n        ostringstream out;\n        out << \"Unknown expression: \" << expression.toString();\n        throw MugenException(out.str());\n    }\n\n    virtual void onExpressionInfix(const Ast::ExpressionInfix & expression){\n        result = evalExpressionInfix(expression);\n    }\n\n    RuntimeValue evalExpressionUnary(const Ast::ExpressionUnary & expression){\n        switch (expression.getExpressionType()){\n            case Ast::ExpressionUnary::Not : {\n                return RuntimeValue(!toBool(evaluate(expression.getExpression())));\n            }\n            case Ast::ExpressionUnary::Minus : {\n                return RuntimeValue(-toNumber(evaluate(expression.getExpression())));\n            }\n            case Ast::ExpressionUnary::Negation : {\n                return RuntimeValue(~(int)toNumber(evaluate(expression.getExpression())));\n            }\n        }\n\n        ostringstream out;\n        out << \"Unknown expression: \" << expression.toString();\n        throw MugenException(out.str());\n    }\n    \n    virtual void onExpressionUnary(const Ast::ExpressionUnary & expression){\n        result = evalExpressionUnary(expression);\n    }\n};\n\nRuntimeValue evaluate(const Ast::Value * value, const Environment & environment){\n    try{\n        Evaluator eval(environment);\n        value->walk(eval);\n        return eval.result;\n    } catch (const MugenException & e){\n        ostringstream out;\n        out << \"Error while evaluating expression `\" << value->toString() << \"': \" << e.getReason();\n        throw MugenException(out.str());\n    }\n}\n\n}\nstart to add hitdef stuff#include \"evaluator.h\"\n#include \"mugen_exception.h\"\n#include \"character.h\"\n#include \"mugen_animation.h\"\n#include \"ast\/all.h\"\n#include \n\n\/* TODO:\n * 1. Change RuntimeValue into an object that stores pointers so that the\n * overhead of copying values is not so high.\n * 2. 1 necessitates garbage collection. Implement precise mark\/sweep.\n * 3. Convert interpreter into a compiler. Refresher\n *   (define intepreter (lambda (env) (lambda (input) (eval env input))))\n *   (define compiler (lambda (input) (let ([compiled (compile input)])\n *                       (lambda (env) (eval env compiled)))))\n * 4. Implement simple optimizations: constant folding, dead code elimintation.\n *\/\n\nusing namespace std;\n\nnamespace Mugen{\n\nstring toString(const RuntimeValue & value){\n    if (value.isString()){\n        return value.getStringValue();\n    }\n    throw MugenException(\"Not a string\");\n}\n\ndouble toNumber(const RuntimeValue & value){\n    if (value.isDouble()){\n        return value.getDoubleValue();\n    }\n    if (value.isBool()){\n        if (value.getBoolValue()){\n            return 1;\n        } else {\n            return 0;\n        }\n    }\n    throw MugenException(\"Not a number\");\n}\n\nbool toBool(const RuntimeValue & value){\n    if (value.isBool()){\n        return value.getBoolValue();\n    }\n    if (value.isDouble()){\n        return value.getDoubleValue() != 0;\n    }\n    throw MugenException(\"Not a bool\");\n}\n\n\/* a meta-circular evaluator! *\/\nclass Evaluator: public Ast::Walker {\npublic:\n    Evaluator(const Environment & environment):\n        environment(environment){\n        }\n\n    const Environment & environment;\n    RuntimeValue result;\n\n    \/* value1 == value2 *\/\n    RuntimeValue same(const RuntimeValue & value1, const RuntimeValue & value2){\n        switch (value1.type){\n            case RuntimeValue::ListOfString : {\n                switch (value2.type){\n                    case RuntimeValue::String : {\n                        const vector & strings = value1.strings_value;\n                        for (vector::const_iterator it = strings.begin(); it != strings.end(); it++){\n                            const string & check = *it;\n                            if (check == value2.string_value){\n                                return RuntimeValue(true);\n                            }\n                        }\n                        return RuntimeValue(false);\n                    }\n                }\n                break;\n            }\n            case RuntimeValue::String : {\n                switch (value2.type){\n                    case RuntimeValue::ListOfString : {\n                        return same(value2, value1);\n                    }\n                    case RuntimeValue::String : {\n                        return toString(value1) == toString(value2);\n                    }\n                }\n                break;\n            }\n            case RuntimeValue::Double : {\n                switch (value2.type){\n                    case RuntimeValue::Double : {\n                        double epsilon = 0.0000001;\n                        return RuntimeValue(fabs(value1.getDoubleValue() - value2.getDoubleValue()) < epsilon);\n                    }\n                }\n                break;\n            }\n        }\n\n        return RuntimeValue(false);\n    }\n   \n    RuntimeValue evaluate(const Ast::Value * value){\n        return Mugen::evaluate(value, environment);\n    }\n\n    RuntimeValue evalIdentifier(const Ast::Identifier & identifier){\n        if (identifier == \"command\"){\n            return RuntimeValue(environment.getCommands());\n        }\n\n        if (identifier == \"anim\"){\n            return RuntimeValue(environment.getCharacter().getAnimation());\n        }\n\n        if (identifier == \"alive\"){\n            \/* FIXME *\/\n            return RuntimeValue(true);\n        }\n\n        if (identifier == \"p2statetype\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        if (identifier == \"animtime\"){\n            return RuntimeValue(environment.getCharacter().getCurrentAnimation()->animationTime());\n        }\n\n        if (identifier == \"animelem\"){\n            \/* FIXME! *\/\n            return RuntimeValue(0);\n        }\n\n        if (identifier == \"hitshakeover\"){\n            \/* FIXME *\/\n            return RuntimeValue(1);\n        }\n\n        if (identifier == \"hitover\"){\n            \/* FIXME *\/\n            return RuntimeValue(1);\n        }\n\n        if (identifier == \"hitfall\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        if (identifier == \"time\"){\n            return RuntimeValue(environment.getCharacter().getStateTime());\n        }\n\n        if (identifier == \"A\"){\n            return RuntimeValue(string(\"A\"));\n        }\n        \n        if (identifier == \"S\"){\n            \/* states are just strings *\/\n            return RuntimeValue(string(\"S\"));\n        }\n\n        if (identifier == \"C\"){\n            return RuntimeValue(string(\"C\"));\n        }\n        \n        if (identifier == \"L\"){\n            return RuntimeValue(string(\"L\"));\n        }\n\n        if (identifier == \"statetype\"){\n            return RuntimeValue(environment.getCharacter().getStateType());\n        }\n\n        \/* true if the player has control *\/\n        if (identifier == \"ctrl\"){\n            return RuntimeValue(environment.getCharacter().hasControl());\n        }\n\n        if (identifier == \"stateno\"){\n            return RuntimeValue(environment.getCharacter().getCurrentState());\n        }\n\n        if (identifier == \"power\"){\n            return RuntimeValue(environment.getCharacter().getPower());\n        }\n\n        if (identifier == \"velocity.walk.back.x\"){\n            return RuntimeValue(environment.getCharacter().getWalkBackX());\n        }\n\n        if (identifier == \"velocity.walk.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getWalkForwardX());\n        }\n\n        if (identifier == \"velocity.run.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getRunForwardX());\n        }\n        \n        if (identifier == \"velocity.jump.neu.x\"){\n            return RuntimeValue(environment.getCharacter().getNeutralJumpingX());\n        }\n        \n        if (identifier == \"velocity.jump.y\"){\n            return RuntimeValue(environment.getCharacter().getNeutralJumpingY());\n        }\n\n        if (identifier == \"prevstateno\"){\n            return RuntimeValue(environment.getCharacter().getPreviousState());\n        }\n        \n        if (identifier == \"velocity.run.back.x\"){\n            return RuntimeValue(environment.getCharacter().getRunBackX());\n        }\n        \n        if (identifier == \"velocity.run.back.y\"){\n            return RuntimeValue(environment.getCharacter().getRunBackY());\n        }\n\n        if (identifier == \"velocity.jump.back.x\"){\n            return RuntimeValue(environment.getCharacter().getJumpBack());\n        }\n\n        if (identifier == \"velocity.jump.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getJumpForward());\n        }\n\n        if (identifier == \"velocity.runjump.fwd.x\"){\n            return RuntimeValue(environment.getCharacter().getRunJumpForward());\n        }\n\n        ostringstream out;\n        out << \"Unknown identifier '\" << identifier.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onIdenfitier(const Ast::Identifier & identifier){\n        result = evalIdentifier(identifier);\n    }\n\n    RuntimeValue evalKeyword(const Ast::Keyword & keyword){\n        if (keyword == \"vel x\"){\n            return RuntimeValue(environment.getCharacter().getXVelocity());\n        }\n\n        if (keyword == \"vel y\"){\n            return RuntimeValue(environment.getCharacter().getYVelocity());\n        }\n        \n        if (keyword == \"pos y\"){\n            return RuntimeValue(-environment.getCharacter().getYPosition());\n        }\n        \n        if (keyword == \"p2bodydist x\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        ostringstream out;\n        out << \"Unknown keyword '\" << keyword.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onKeyword(const Ast::Keyword & keyword){\n        result = evalKeyword(keyword);\n    }\n\n    RuntimeValue evalString(const Ast::String & string_value){\n        string out;\n        string_value >> out;\n        return RuntimeValue(out);\n    }\n\n    virtual void onString(const Ast::String & string){\n        result = evalString(string);\n    }\n\n    RuntimeValue evalFunction(const Ast::Function & function){\n        if (function == \"const\"){\n            return evaluate(function.getArg1());\n        }\n\n        if (function == \"abs\"){\n            return RuntimeValue(fabs(toNumber(evaluate(function.getArg1()))));\n        }\n\n        if (function == \"var\"){\n            int index = (int) toNumber(evaluate(function.getArg1()));\n            Ast::Value * value = environment.getCharacter().getVariable(index);\n            if (value == 0){\n                ostringstream out;\n                out << \"No variable for index \" << index;\n                throw MugenException(out.str());\n            }\n            return evaluate(value);\n        }\n\n        if (function == \"gethitvar\"){\n            if (function.getArg1() == 0){\n                throw MugenException(\"No argument given to gethitvar\");\n            }\n            string var = function.getArg1()->toString();\n            if (var == \"xveladd\"){\n            } else if (var == \"yveladd\"){\n            } else if (var == \"type\"){\n            } else if (var == \"animtype\"){\n            } else if (var == \"airtype\"){\n            } else if (var == \"groundtype\"){\n            } else if (var == \"damage\"){\n            } else if (var == \"hitcount\"){\n            } else if (var == \"fallcount\"){\n            } else if (var == \"hitshaketime\"){\n            } else if (var == \"hittime\"){\n            } else if (var == \"slidetime\"){\n            } else if (var == \"ctrltime\"){\n            } else if (var == \"recovertime\"){\n            } else if (var == \"xoff\"){\n            } else if (var == \"yoff\"){\n            } else if (var == \"zoff\"){\n            } else if (var == \"xvel\"){\n            } else if (var == \"yvel\"){\n            } else if (var == \"yaccel\"){\n            } else if (var == \"hitid\"){\n            } else if (var == \"chainid\"){\n            } else if (var == \"guarded\"){\n            } else if (var == \"fall\"){\n            } else if (var == \"fall.damage\"){\n            } else if (var == \"fall.xvel\"){\n            } else if (var == \"fall.yvel\"){\n            } else if (var == \"fall.recover\"){\n            } else if (var == \"fall.time\"){\n            } else if (var == \"fall.recovertime\"){\n            }\n\n            throw MugenException(\"Unknown gethitvar variable \" + var);\n        }\n\n        if (function == \"sysvar\"){\n            int index = (int) toNumber(evaluate(function.getArg1()));\n            Ast::Value * value = environment.getCharacter().getSystemVariable(index);\n            if (value == 0){\n                ostringstream out;\n                out << \"No system variable for index \" << index;\n                throw MugenException(out.str());\n            }\n            return evaluate(value);\n        }\n\n\n        if (function == \"ifelse\"){\n            if (toBool(evaluate(function.getArg1()))){\n                return evaluate(function.getArg2());\n            } else {\n                return evaluate(function.getArg3());\n            }\n        }\n\n        if (function == \"selfanimexist\"){\n            int animation = (int) toNumber(evaluate(function.getArg1()));\n            return RuntimeValue(environment.getCharacter().hasAnimation(animation));\n        }\n\n        \/* Gets the animation-time elapsed since the start of a specified element\n         * of the current animation action. Useful for synchronizing events to\n         * elements of an animation action.\n         *\n         * (reminder: first element of an action is element 1, not 0)\n         *\/\n        if (function == \"animelemtime\"){\n            \/* FIXME *\/\n            return RuntimeValue(0);\n        }\n\n        ostringstream out;\n        out << \"Unknown function '\" << function.toString() << \"'\";\n        throw MugenException(out.str());\n    }\n\n    virtual void onFunction(const Ast::Function & string){\n        result = evalFunction(string);\n    }\n\n    RuntimeValue evalNumber(const Ast::Number & number){\n        double x;\n        number >> x;\n        return RuntimeValue(x);\n    }\n\n    virtual void onNumber(const Ast::Number & number){\n        result = evalNumber(number);\n    }\n\n    virtual RuntimeValue evalExpressionInfix(const Ast::ExpressionInfix & expression){\n        Global::debug(1) << \"Evaluate expression \" << expression.toString() << endl;\n        using namespace Ast;\n        switch (expression.getExpressionType()){\n            case ExpressionInfix::Or : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) ||\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::XOr : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) ^\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::And : {\n                return RuntimeValue(toBool(evaluate(expression.getLeft())) &&\n                                    toBool(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseOr : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) |\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseXOr : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) ^\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::BitwiseAnd : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) &\n                                    (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Assignment : {\n                \/* FIXME: is this needed? *\/\n                break;\n            }\n            case ExpressionInfix::Equals : {\n                return same(evaluate(expression.getLeft()), evaluate(expression.getRight()));\n                break;\n            }\n            case ExpressionInfix::Unequals : {\n                return RuntimeValue(!toBool(same(evaluate(expression.getLeft()), evaluate(expression.getRight()))));\n            }\n            case ExpressionInfix::GreaterThanEquals : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) >= toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::GreaterThan : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) > toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::LessThanEquals : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) <= toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::LessThan : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) < toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Add : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) + toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Subtract : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) - toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Multiply : {\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) * toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Divide : {\n                \/* FIXME: catch divide by 0 *\/\n                return RuntimeValue(toNumber(evaluate(expression.getLeft())) \/ toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Modulo : {\n                return RuntimeValue((int)toNumber(evaluate(expression.getLeft())) % (int)toNumber(evaluate(expression.getRight())));\n            }\n            case ExpressionInfix::Power : {\n                return RuntimeValue(pow(toNumber(evaluate(expression.getLeft())), toNumber(evaluate(expression.getRight()))));\n            }\n        }\n\n        ostringstream out;\n        out << \"Unknown expression: \" << expression.toString();\n        throw MugenException(out.str());\n    }\n\n    virtual void onExpressionInfix(const Ast::ExpressionInfix & expression){\n        result = evalExpressionInfix(expression);\n    }\n\n    RuntimeValue evalExpressionUnary(const Ast::ExpressionUnary & expression){\n        switch (expression.getExpressionType()){\n            case Ast::ExpressionUnary::Not : {\n                return RuntimeValue(!toBool(evaluate(expression.getExpression())));\n            }\n            case Ast::ExpressionUnary::Minus : {\n                return RuntimeValue(-toNumber(evaluate(expression.getExpression())));\n            }\n            case Ast::ExpressionUnary::Negation : {\n                return RuntimeValue(~(int)toNumber(evaluate(expression.getExpression())));\n            }\n        }\n\n        ostringstream out;\n        out << \"Unknown expression: \" << expression.toString();\n        throw MugenException(out.str());\n    }\n    \n    virtual void onExpressionUnary(const Ast::ExpressionUnary & expression){\n        result = evalExpressionUnary(expression);\n    }\n};\n\nRuntimeValue evaluate(const Ast::Value * value, const Environment & environment){\n    try{\n        Evaluator eval(environment);\n        value->walk(eval);\n        return eval.result;\n    } catch (const MugenException & e){\n        ostringstream out;\n        out << \"Error while evaluating expression `\" << value->toString() << \"': \" << e.getReason();\n        throw MugenException(out.str());\n    }\n}\n\n}\n<|endoftext|>"}
{"text":"\/\/ CS3230-PA1-DE\n\/\/ Multiplication of 2 n-digit integers.\n\/\/ Naive O(n^2) multiplication algorithm (Karatsuba + Long Multiplication)\n\/\/ Name: Tay Yang Shun\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define     FOR(i,s,e)      for(int64_t (i) = (s); (i) <  (e); ++(i))\n#define     REP(i,n)        FOR(i,0,n)\n#define     FORE(i,s,e)     for(int64_t (i) = (s); (i) <= (e); ++(i))\n\nconst string        Digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst char          RADIX_POINT = '.';\nconst int64_t       CHUNK_SIZE = 8;\nconst int64_t       MAXSIZE = 130000;\nconst int64_t       CUT_OFF = 300;\nconst int64_t       CHUNK_BASE = pow(10, CHUNK_SIZE);\n\nlong getMemoryUsage() {\n    struct rusage usage;\n    if(0 == getrusage(RUSAGE_SELF, &usage)) {\n        return usage.ru_maxrss \/ 1000; \/\/ bytes\n    } else {\n        return 0;\n    }\n}\n\ninline int64_t valueOf(char x){ \/\/ integer value of a digit\n    if ('0' <= x and x <= '9') return x - '0';\n    if ('A' <= x and x <= 'Z') return x - 'A' +10;\n    return 255;\n};\n\nint64_t A[MAXSIZE], B[MAXSIZE], *temp, *res;\n\n\/\/ Trim unnecessary zeros and radix point\nstring trim(string aStr){\n    string X = aStr;\n    \/\/leading zeros:\n    while(X.length()>1 and X[0] == '0'and X[1] != RADIX_POINT) X.erase(0,1); \/\/000.001\n\n    \/\/trailing zeros and radix point:\n    if (X.find(RADIX_POINT) != string::npos) {\n        while (X.length() >= 1 and X[X.length()-1] == '0') {\n            X.erase(X.length()-1,1);\/\/0.010; 1.000\n        }\n        if (X.length() >= 1 and X[X.length()-1] == RADIX_POINT) {\n            X.erase(X.length()-1);\/\/123.\n        }\n        if (X[0] == RADIX_POINT) {\n            X = \"0\" + X; \/\/ insert \"0\" into \".123\"\n        }\n    };\n    if (X == \"\") X = \"0\";\n    return X;\n};\n\n\/\/ Convert string into array of integer:\n\/\/ A[0] stores length of the number;\n\/\/ Digits are stored in reverse order, example:\n\/\/ X = \"123456789\"\n\/\/ A = {3,6789,2345,1};\nvoid convert2IntArr(string X, int64_t *A){\n\n    X = trim(X);\n    int64_t len = X.length() \/ CHUNK_SIZE;\n    int64_t rem = (X.length() % CHUNK_SIZE);\n    int64_t padLength;\n    if (rem > 0) {\n        padLength = CHUNK_SIZE - rem;\n        for (int64_t i = 0; i < padLength; i++) {\n            X = \"0\" + X;\n        }\n        len += 1;\n    }\n    A[0] = len;\n    int64_t j = 1;\n    for (int64_t i = X.length()-1; i >= 0; i-=CHUNK_SIZE) {\n        int64_t num = 0;\n        for (int64_t k = 0; k < CHUNK_SIZE; k++) {\n            num += valueOf(X[i-k]) * pow(10, k);\n        }\n        A[j] = num;\n        j++;\n    }\n}\n\nstring numberToString(int64_t number) {\n    string s = \"\";\n    if (number == 0) {\n        return \"0\";\n    } else {\n        while (number > 0) {\n            int64_t digit = number % 10;\n            s = Digits[digit] + s;\n            number \/= 10;\n        }\n        return s;\n    }\n}\n\n\/\/ Convert an array A to string:\nstring convertIntArr2Str(int64_t *A){\n    string result = \"\";\n    int64_t len = A[0];\n    \n    for (int64_t i = len; i >= 1; i--) {\n        string s = numberToString(A[i]);\n        int64_t currLen = s.length();\n        for (int64_t j = 0; j < CHUNK_SIZE - currLen; j++) {\n            s = \"0\" + s;\n        }\n        result += s;\n    }\n    return trim(result);\n};\n\n\/\/ Adding two arrays with offset: USEFUL for karatsuba algorithm!!\n\/\/ A = A + B * base^offset\ninline void add(int64_t *A, int64_t *B, int64_t offset, int64_t base){\n    int64_t lenA = A[0], lenB = B[0];\n    int64_t carry = 0;\n    int64_t i = 1;\n    offset++;\n\n    int64_t b;\n    while (i <= lenB or carry > 0) {\n        if (offset > lenA) {\n            A[offset] = 0;\n        }\n        if (i > lenB) {\n            b = 0;\n        } else {\n            b = B[i];\n        }\n\n        carry = A[offset] + b + carry;\n        A[offset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        offset++;\n    };\n\n    offset--;\n    while (offset > 1 and A[offset] == 0) {\n        offset--;\n    }\n    if (offset > lenA) {\n        A[0] = offset;\n    }\n};\n\ninline void addFast(int64_t *A, int64_t *B, int64_t *C, int64_t offset, int64_t base){\n    int64_t lenA = A[0], lenB = B[0];\n    int64_t carry = 0;\n    int64_t i = 1;\n    int64_t firstOffset = offset * 2 + 1;\n\n    int64_t b;\n    while (i <= lenB or carry > 0) {\n        if (firstOffset > lenA) {\n            A[firstOffset] = 0;\n        }\n        if (i > lenB) {\n            b = 0;\n        } else {\n            b = B[i];\n        }\n\n        carry = A[firstOffset] + b + carry;\n        A[firstOffset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        firstOffset++;\n    };\n\n    firstOffset--;\n    while (firstOffset > 1 and A[firstOffset] == 0) {\n        firstOffset--;\n    }\n    if (firstOffset > lenA) {\n        A[0] = firstOffset;\n    }\n\n    \/\/ Second\n    lenA = A[0];\n    int64_t lenC = C[0];\n    carry = 0;\n    i = 1;\n    int64_t c;\n    offset++;\n\n    while (i <= lenC or carry > 0) {\n        if (offset > lenA) {\n            A[offset] = 0;\n        }\n        if (i > lenC) {\n            c = 0;\n        } else {\n            c = C[i];\n        }\n\n        carry = A[offset] + c + carry;\n        A[offset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        offset++;\n    };\n\n    offset--;\n    while (offset > 1 and A[offset] == 0) {\n        offset--;\n    }\n    if (offset > lenA) {\n        A[0] = offset;\n    }\n};\n\ninline void subtract(int64_t *A, int64_t *B, int64_t base) {\n    \/\/ A = A - B\n    \/\/ Requirement: A > B\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n    for (int64_t i = 1; i <= lenB; i++) {\n        if (A[i] < B[i]) {\n            int64_t j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            int64_t temp = A[i];\n            A[i] = base + A[i] - B[i];\n        } else {\n            A[i] -= B[i];\n        }\n    }\n    while (lenA > 1 and A[lenA] == 0) {\n        lenA--;\n    }\n    A[0] = lenA;\n};\n\ninline void subtractFast(int64_t *A, int64_t *B, int64_t *C, int64_t base) {\n    \/\/ A = A - B - C\n    \/\/ Requirement: A > B\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n    int64_t lenC = C[0];\n\n    int64_t j;\n    for (int64_t i = 1; i <= lenB; i++) {\n        if (A[i] < B[i]) {\n            j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            A[i] = base + A[i] - B[i];\n        } else {\n            A[i] -= B[i];\n        }\n    }\n\n    for (int64_t i = 1; i <= lenC; i++) {\n        if (A[i] < C[i]) {\n            j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            A[i] = base + A[i] - C[i];\n        } else {\n            A[i] -= C[i];\n        }\n    }\n\n    while (lenA > 1 and A[lenA] == 0) {\n        lenA--;\n    }\n    A[0] = lenA;\n};\n\n\/\/ Faster multiplication:\n\/\/ res = A * B;\ninline int64_t* mulTwoArrays(int64_t *A, int64_t *B, int64_t base) {\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n\n    res = new int64_t[MAXSIZE];\n    temp = new int64_t[MAXSIZE];\n\n    REP(i, A[0]+2) res[i] = temp[i] = 0;\n\n    FORE(i, 1, lenA)\n    FORE(j, 1, lenB) {\n        temp[i+j-1] += A[i] * B[j];\n    };\n\n    int64_t lenR = lenA + lenB + 1;\n    int64_t carry = 0;\n    FORE(i, 1, lenR) {\n        carry += temp[i];\n        res[i] = carry % base;\n        carry  = carry \/ base;\n    };\n\n    while (lenR>1 and res[lenR] == 0) {\n        lenR--;\n    }\n    res[0] = lenR;\n    delete[] temp;\n\n    return res;\n};\n\ninline void splitAt(int64_t *input, int64_t *high, int64_t *low, int64_t R) {\n    int64_t lenInput = input[0];\n\n    for (int64_t i = 1; i <= R; i++) {\n        low[i] = (i <= lenInput) ? input[i] : 0;\n    }\n    low[0] = (lenInput <= R) ? lenInput : R;\n\n    for (int64_t i = 1; i <= R; i++) {\n        high[i] = (i <= lenInput) ? input[i+R] : 0;\n    }\n    high[0] = (lenInput - R > 0) ? lenInput - R : 0;\n\n};\n\nint64_t* karatsuba(int64_t *A, int64_t *B, int64_t base) {\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n\n    if (lenA < CUT_OFF or lenB < CUT_OFF) {\n        return mulTwoArrays(A, B, base);\n    }\n\n    int64_t R = ((lenA > lenB ? lenA : lenB)+1) \/ 2;\n\n    int64_t highX[R+2];\n    int64_t lowX[R+2];\n    int64_t highY[R+2];\n    int64_t lowY[R+2];\n    splitAt(A, highX, lowX, R);\n    splitAt(B, highY, lowY, R);\n\n    int64_t *z0 = karatsuba(lowX, lowY, base);\n    int64_t *z2 = karatsuba(highX, highY, base);\n\n    add(lowX, highX, 0, base);\n    add(lowY, highY, 0, base);\n\n    int64_t *z1 = karatsuba(lowX, lowY, base);\n\n    subtractFast(z1, z0, z2, base);\n    addFast(z0, z2, z1, R, base);\n\n    delete[] z1;\n    delete[] z2;\n    return z0;\n}\n\nint main() {\n    int64_t T;\n    string V, M, P;\n    int64_t base;\n\n    cin >> T;\n    FORE(t, 1, T) {\n        cin >> base;\n        cin >> V >> M;\n\n        convert2IntArr(V, A);\n        convert2IntArr(M, B);\n        string s = convertIntArr2Str(karatsuba(A, B, CHUNK_BASE));\n        cout << s << endl;\n    };\n    \/\/ cout << \"Memory used: \" << getMemoryUsage() << \" KB\" << endl;\n    return 0;\n}\n[PA1] Optimize split\/\/ CS3230-PA1-DE\n\/\/ Multiplication of 2 n-digit integers.\n\/\/ Naive O(n^2) multiplication algorithm (Karatsuba + Long Multiplication)\n\/\/ Name: Tay Yang Shun\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define     FOR(i,s,e)      for(int64_t (i) = (s); (i) <  (e); ++(i))\n#define     REP(i,n)        FOR(i,0,n)\n#define     FORE(i,s,e)     for(int64_t (i) = (s); (i) <= (e); ++(i))\n\nconst string        Digits = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst char          RADIX_POINT = '.';\nconst int64_t       CHUNK_SIZE = 8;\nconst int64_t       MAXSIZE = 130000;\nconst int64_t       CUT_OFF = 300;\nconst int64_t       CHUNK_BASE = pow(10, CHUNK_SIZE);\n\nlong getMemoryUsage() {\n    struct rusage usage;\n    if(0 == getrusage(RUSAGE_SELF, &usage)) {\n        return usage.ru_maxrss \/ 1000; \/\/ bytes\n    } else {\n        return 0;\n    }\n}\n\ninline int64_t valueOf(char x){ \/\/ integer value of a digit\n    if ('0' <= x and x <= '9') return x - '0';\n    if ('A' <= x and x <= 'Z') return x - 'A' +10;\n    return 255;\n};\n\nint64_t A[MAXSIZE], B[MAXSIZE], *temp, *res;\n\n\/\/ Trim unnecessary zeros and radix point\nstring trim(string aStr){\n    string X = aStr;\n    \/\/leading zeros:\n    while(X.length()>1 and X[0] == '0'and X[1] != RADIX_POINT) X.erase(0,1); \/\/000.001\n\n    \/\/trailing zeros and radix point:\n    if (X.find(RADIX_POINT) != string::npos) {\n        while (X.length() >= 1 and X[X.length()-1] == '0') {\n            X.erase(X.length()-1,1);\/\/0.010; 1.000\n        }\n        if (X.length() >= 1 and X[X.length()-1] == RADIX_POINT) {\n            X.erase(X.length()-1);\/\/123.\n        }\n        if (X[0] == RADIX_POINT) {\n            X = \"0\" + X; \/\/ insert \"0\" into \".123\"\n        }\n    };\n    if (X == \"\") X = \"0\";\n    return X;\n};\n\n\/\/ Convert string into array of integer:\n\/\/ A[0] stores length of the number;\n\/\/ Digits are stored in reverse order, example:\n\/\/ X = \"123456789\"\n\/\/ A = {3,6789,2345,1};\nvoid convert2IntArr(string X, int64_t *A){\n\n    X = trim(X);\n    int64_t len = X.length() \/ CHUNK_SIZE;\n    int64_t rem = (X.length() % CHUNK_SIZE);\n    int64_t padLength;\n    if (rem > 0) {\n        padLength = CHUNK_SIZE - rem;\n        for (int64_t i = 0; i < padLength; i++) {\n            X = \"0\" + X;\n        }\n        len += 1;\n    }\n    A[0] = len;\n    int64_t j = 1;\n    for (int64_t i = X.length()-1; i >= 0; i-=CHUNK_SIZE) {\n        int64_t num = 0;\n        for (int64_t k = 0; k < CHUNK_SIZE; k++) {\n            num += valueOf(X[i-k]) * pow(10, k);\n        }\n        A[j] = num;\n        j++;\n    }\n}\n\nstring numberToString(int64_t number) {\n    string s = \"\";\n    if (number == 0) {\n        return \"0\";\n    } else {\n        while (number > 0) {\n            int64_t digit = number % 10;\n            s = Digits[digit] + s;\n            number \/= 10;\n        }\n        return s;\n    }\n}\n\n\/\/ Convert an array A to string:\nstring convertIntArr2Str(int64_t *A){\n    string result = \"\";\n    int64_t len = A[0];\n    \n    for (int64_t i = len; i >= 1; i--) {\n        string s = numberToString(A[i]);\n        int64_t currLen = s.length();\n        for (int64_t j = 0; j < CHUNK_SIZE - currLen; j++) {\n            s = \"0\" + s;\n        }\n        result += s;\n    }\n    return trim(result);\n};\n\n\/\/ Adding two arrays with offset: USEFUL for karatsuba algorithm!!\n\/\/ A = A + B * base^offset\ninline void add(int64_t *A, int64_t *B, int64_t offset, int64_t base){\n    int64_t lenA = A[0], lenB = B[0];\n    int64_t carry = 0;\n    int64_t i = 1;\n    offset++;\n\n    int64_t b;\n    while (i <= lenB or carry > 0) {\n        if (offset > lenA) {\n            A[offset] = 0;\n        }\n        if (i > lenB) {\n            b = 0;\n        } else {\n            b = B[i];\n        }\n\n        carry = A[offset] + b + carry;\n        A[offset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        offset++;\n    };\n\n    offset--;\n    while (offset > 1 and A[offset] == 0) {\n        offset--;\n    }\n    if (offset > lenA) {\n        A[0] = offset;\n    }\n};\n\ninline void addFast(int64_t *A, int64_t *B, int64_t *C, int64_t offset, int64_t base){\n    int64_t lenA = A[0], lenB = B[0];\n    int64_t carry = 0;\n    int64_t i = 1;\n    int64_t firstOffset = offset * 2 + 1;\n\n    int64_t b;\n    while (i <= lenB or carry > 0) {\n        if (firstOffset > lenA) {\n            A[firstOffset] = 0;\n        }\n        if (i > lenB) {\n            b = 0;\n        } else {\n            b = B[i];\n        }\n\n        carry = A[firstOffset] + b + carry;\n        A[firstOffset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        firstOffset++;\n    };\n\n    firstOffset--;\n    while (firstOffset > 1 and A[firstOffset] == 0) {\n        firstOffset--;\n    }\n    if (firstOffset > lenA) {\n        A[0] = firstOffset;\n    }\n\n    \/\/ Second\n    lenA = A[0];\n    int64_t lenC = C[0];\n    carry = 0;\n    i = 1;\n    int64_t c;\n    offset++;\n\n    while (i <= lenC or carry > 0) {\n        if (offset > lenA) {\n            A[offset] = 0;\n        }\n        if (i > lenC) {\n            c = 0;\n        } else {\n            c = C[i];\n        }\n\n        carry = A[offset] + c + carry;\n        A[offset] = carry % base;\n        carry = carry >= base ? 1 : 0;\n\n        i++;\n        offset++;\n    };\n\n    offset--;\n    while (offset > 1 and A[offset] == 0) {\n        offset--;\n    }\n    if (offset > lenA) {\n        A[0] = offset;\n    }\n};\n\ninline void subtract(int64_t *A, int64_t *B, int64_t base) {\n    \/\/ A = A - B\n    \/\/ Requirement: A > B\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n    for (int64_t i = 1; i <= lenB; i++) {\n        if (A[i] < B[i]) {\n            int64_t j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            int64_t temp = A[i];\n            A[i] = base + A[i] - B[i];\n        } else {\n            A[i] -= B[i];\n        }\n    }\n    while (lenA > 1 and A[lenA] == 0) {\n        lenA--;\n    }\n    A[0] = lenA;\n};\n\ninline void subtractFast(int64_t *A, int64_t *B, int64_t *C, int64_t base) {\n    \/\/ A = A - B - C\n    \/\/ Requirement: A > B\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n    int64_t lenC = C[0];\n\n    int64_t j;\n    for (int64_t i = 1; i <= lenB; i++) {\n        if (A[i] < B[i]) {\n            j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            A[i] = base + A[i] - B[i];\n        } else {\n            A[i] -= B[i];\n        }\n    }\n\n    for (int64_t i = 1; i <= lenC; i++) {\n        if (A[i] < C[i]) {\n            j = i + 1;\n            while (A[j] == 0) {\n                A[j] = base - 1;\n                j++;\n            }\n            A[j] -= 1;\n            A[i] = base + A[i] - C[i];\n        } else {\n            A[i] -= C[i];\n        }\n    }\n\n    while (lenA > 1 and A[lenA] == 0) {\n        lenA--;\n    }\n    A[0] = lenA;\n};\n\n\/\/ Faster multiplication:\n\/\/ res = A * B;\ninline int64_t* mulTwoArrays(int64_t *A, int64_t *B, int64_t base) {\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n\n    res = new int64_t[MAXSIZE];\n    temp = new int64_t[MAXSIZE];\n\n    REP(i, A[0]+2) res[i] = temp[i] = 0;\n\n    FORE(i, 1, lenA)\n    FORE(j, 1, lenB) {\n        temp[i+j-1] += A[i] * B[j];\n    };\n\n    int64_t lenR = lenA + lenB + 1;\n    int64_t carry = 0;\n    FORE(i, 1, lenR) {\n        carry += temp[i];\n        res[i] = carry % base;\n        carry  = carry \/ base;\n    };\n\n    while (lenR>1 and res[lenR] == 0) {\n        lenR--;\n    }\n    res[0] = lenR;\n    delete[] temp;\n\n    return res;\n};\n\ninline void splitAt(int64_t *input, int64_t *high, int64_t *low, int64_t R) {\n    int64_t lenInput = input[0];\n\n    for (int64_t i = 1; i <= R; i++) {\n        low[i] = (i <= lenInput) ? input[i] : 0;\n        high[i] = (i <= lenInput) ? input[i+R] : 0;\n    }\n    low[0] = (lenInput <= R) ? lenInput : R;\n    high[0] = (lenInput - R > 0) ? lenInput - R : 0;\n};\n\nint64_t* karatsuba(int64_t *A, int64_t *B, int64_t base) {\n    int64_t lenA = A[0];\n    int64_t lenB = B[0];\n\n    if (lenA < CUT_OFF or lenB < CUT_OFF) {\n        return mulTwoArrays(A, B, base);\n    }\n\n    int64_t R = ((lenA > lenB ? lenA : lenB)+1) \/ 2;\n\n    int64_t highX[R+2];\n    int64_t lowX[R+2];\n    int64_t highY[R+2];\n    int64_t lowY[R+2];\n    splitAt(A, highX, lowX, R);\n    splitAt(B, highY, lowY, R);\n\n    int64_t *z0 = karatsuba(lowX, lowY, base);\n    int64_t *z2 = karatsuba(highX, highY, base);\n\n    add(lowX, highX, 0, base);\n    add(lowY, highY, 0, base);\n\n    int64_t *z1 = karatsuba(lowX, lowY, base);\n\n    subtractFast(z1, z0, z2, base);\n    addFast(z0, z2, z1, R, base);\n\n    delete[] z1;\n    delete[] z2;\n    return z0;\n}\n\nint main() {\n    int64_t T;\n    string V, M, P;\n    int64_t base;\n\n    cin >> T;\n    FORE(t, 1, T) {\n        cin >> base;\n        cin >> V >> M;\n\n        convert2IntArr(V, A);\n        convert2IntArr(M, B);\n        string s = convertIntArr2Str(karatsuba(A, B, CHUNK_BASE));\n        cout << s << endl;\n    };\n    \/\/ cout << \"Memory used: \" << getMemoryUsage() << \" KB\" << endl;\n    return 0;\n}\n<|endoftext|>"}
{"text":"updated Aff_op to be created when it is actually possible to create it.  Change required by solver change for NKA creation time<|endoftext|>"}
{"text":"\/******************************************************\n * cpu_tests.cpp - cpu unit tests\n * created 140204 jonathan howard (j@hovverd.com)\n ******************************************************\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"utils.h\"\n#include \"cpu.h\"\n#include \"opcodes.h\"\n\nTEST(OpCode, IsCorrectSize)\n{\n    ASSERT_TRUE(sizeof(INSTR_Arithmatic) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Register) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Immediate) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Flow) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Branch) == 4);\n}\nCPU properly initializes registers\/******************************************************\n * cpu_tests.cpp - cpu unit tests\n * created 140204 jonathan howard (j@hovverd.com)\n ******************************************************\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"utils.h\"\n#include \"cpu.h\"\n#include \"opcodes.h\"\n\nTEST(OpCode, IsCorrectSize)\n{\n    ASSERT_TRUE(sizeof(INSTR_Arithmatic) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Register) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Immediate) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Flow) == 4);\n    ASSERT_TRUE(sizeof(INSTR_Branch) == 4);\n}\n\nTEST(CPU_Fetch, InitializesToNULL)\n{\n    CPU * cpu = new CPU();\n    ASSERT_EQ(*R(cpu, -2), NULL);\n}\n\n<|endoftext|>"}
{"text":"Added a simple gamma correction node - allows for \"tonemapping\" that doesn't influence black levels<|endoftext|>"}
{"text":"#pragma once\n\n#include \n#include \n\nnamespace dai {\n\n\/**\n * Specify properties for VideoEncoder such as profile, bitrate, ...\n *\/\nstruct VideoEncoderProperties {\n    \/**\n     * Rate control mode specifies if constant or variable bitrate should be used (H264 \/ H265)\n     *\/\n    enum class RateControlMode : int { CBR, VBR };\n\n    \/**\n     * Encoding profile, H264 (AVC), H265 (HEVC) or MJPEG\n     *\/\n    enum class Profile : int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG };\n    \/**\n     * Specifies preferred bitrate (in bit\/s) of compressed output bitstream in CBR mode\n     *\n     * \"0\" for automatic computation, based on input resolution and FPS:\n     * 720p30: 4Mbps, 1080p30: 8.5Mbps, 1440p30: 14Mbps, 2160p30: 20Mbps\n     *\/\n    std::int32_t bitrate = 0;\n    \/**\n     * Every x number of frames a keyframe will be inserted\n     *\/\n    std::int32_t keyframeFrequency = 30;\n    \/**\n     * Specifies maximum bitrate (in bit\/s) of compressed output bitstream in CBR mode\n     *\n     * \"0\" to follow `bitrate` setting\n     *\/\n    std::int32_t maxBitrate = 0;\n    \/**\n     * Specifies number of B frames to be inserted\n     *\/\n    std::int32_t numBFrames = 0;\n    \/**\n     * This options specifies how many frames are available in this node's pool.\n     * Helps when receiver is slow at consuming.\n     *\n     * Value \"0\" indicates automatic number of frames assignment\n     *\/\n    std::uint32_t numFramesPool = 0;\n    \/**\n     * Encoding profile, H264, H265 or MJPEG\n     *\/\n    Profile profile = Profile::H264_BASELINE;\n    \/**\n     * Value between 0-100% (approximates quality)\n     *\/\n    std::int32_t quality = 80;\n    \/**\n     * Lossless mode ([M]JPEG only)\n     *\/\n    bool lossless = false;\n    \/**\n     * Rate control mode specifies if constant or variable bitrate should be used (H264 \/ H265)\n     *\/\n    RateControlMode rateCtrlMode = RateControlMode::CBR;\n    \/**\n     * Frame rate\n     *\/\n    float frameRate = 30.0f;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(VideoEncoderProperties,\n                                   bitrate,\n                                   keyframeFrequency,\n                                   maxBitrate,\n                                   numBFrames,\n                                   numFramesPool,\n                                   profile,\n                                   quality,\n                                   lossless,\n                                   rateCtrlMode,\n                                   frameRate);\n\n}  \/\/ namespace dai\nmake clangformat#pragma once\n\n#include \n#include \n\nnamespace dai {\n\n\/**\n * Specify properties for VideoEncoder such as profile, bitrate, ...\n *\/\nstruct VideoEncoderProperties {\n    \/**\n     * Rate control mode specifies if constant or variable bitrate should be used (H264 \/ H265)\n     *\/\n    enum class RateControlMode : int { CBR, VBR };\n\n    \/**\n     * Encoding profile, H264 (AVC), H265 (HEVC) or MJPEG\n     *\/\n    enum class Profile : int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG };\n    \/**\n     * Specifies preferred bitrate (in bit\/s) of compressed output bitstream in CBR mode\n     *\n     * \"0\" for automatic computation, based on input resolution and FPS:\n     * 720p30: 4Mbps, 1080p30: 8.5Mbps, 1440p30: 14Mbps, 2160p30: 20Mbps\n     *\/\n    std::int32_t bitrate = 0;\n    \/**\n     * Every x number of frames a keyframe will be inserted\n     *\/\n    std::int32_t keyframeFrequency = 30;\n    \/**\n     * Specifies maximum bitrate (in bit\/s) of compressed output bitstream in CBR mode\n     *\n     * \"0\" to follow `bitrate` setting\n     *\/\n    std::int32_t maxBitrate = 0;\n    \/**\n     * Specifies number of B frames to be inserted\n     *\/\n    std::int32_t numBFrames = 0;\n    \/**\n     * This options specifies how many frames are available in this node's pool.\n     * Helps when receiver is slow at consuming.\n     *\n     * Value \"0\" indicates automatic number of frames assignment\n     *\/\n    std::uint32_t numFramesPool = 0;\n    \/**\n     * Encoding profile, H264, H265 or MJPEG\n     *\/\n    Profile profile = Profile::H264_BASELINE;\n    \/**\n     * Value between 0-100% (approximates quality)\n     *\/\n    std::int32_t quality = 80;\n    \/**\n     * Lossless mode ([M]JPEG only)\n     *\/\n    bool lossless = false;\n    \/**\n     * Rate control mode specifies if constant or variable bitrate should be used (H264 \/ H265)\n     *\/\n    RateControlMode rateCtrlMode = RateControlMode::CBR;\n    \/**\n     * Frame rate\n     *\/\n    float frameRate = 30.0f;\n};\n\nNLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(\n    VideoEncoderProperties, bitrate, keyframeFrequency, maxBitrate, numBFrames, numFramesPool, profile, quality, lossless, rateCtrlMode, frameRate);\n\n}  \/\/ namespace dai\n<|endoftext|>"}
{"text":"\/*\n *      This node is used to perform inference in a Bayesian network.\n *      It's subscribed to interaction_monitor \/BN_vars topic \n *      to obtain data and then performs inference with a BN using SMILE libraries\n *\n *      At the end it prints some statistics with the performance.\n *\n *      Lunds tekniska högskola | LTH 2015\n *      Felip Marti Carrillo\n *\n *      MIT License (MIT)\n *      Copyright (c) 2015 Felip Marti Carrillo\n *\/\n\n\n#include \"interaction_recognition_node.h\"\n\n\nInteractionRecognition::InteractionRecognition (void)\n{\n\n    \/\/ Init Subscriber\n    this->sub = this->n.subscribe(\"BN_vars\", 1,\n                        &InteractionRecognition::perform_inference_callback, this);\n\n    \/\/ Init Stats\n    for (int i=0; i<9; i++) {\n         Stats_Results[i]=0; \n    }\n\n    \/\/ Max difference to consider 2 objects different\n    MAX_DIFF = 0.1;\n\n    \/\/ Vector of strings with fails\n    statsFails.resize(0);\n\n}\n\n\nInteractionRecognition::~InteractionRecognition (void)\n{\n}\n\n\nvoid InteractionRecognition::perform_inference_callback\n                        (const interaction_monitor::BayesianNetworkVariable& msg)\n{\n\n    if (msg.category==-1) {\n\n        print_statistics();\n        exit(0);\n\n    }\n    \n    \/\/\/ Performing Inference\n    ROS_INFO(\"[Interaction_Recognition] Performing Inference\");\n    \n    \/\/ Vars to get the handle of node\n    int category = theNet.FindNode(\"category\"); \n    int lastCommand = theNet.FindNode(\"lastCommand\"); \n    int usrAnnounce = theNet.FindNode(\"usrAnnounce\"); \n    int usrGesture = theNet.FindNode(\"usrGesture\"); \n    int headingAdj = theNet.FindNode(\"headingAdj\"); \n    int distanceAdj = theNet.FindNode(\"distanceAdj\"); \n\n    \/\/ Vars to store data\n    int lastCommandData=msg.last_cmd;\n    int usrAnnounceData=msg.announce;\n    int usrGestureData=msg.gesture;   \n    int headingAdjData=msg.head_adj;  \n    int distanceAdjData=msg.dist_adj; \n    int categoryData=msg.category;     \n    \n    \/\/ Setting evidence\n    theNet.GetNode(lastCommand)->Value()->SetEvidence(lastCommandData);\n    theNet.GetNode(usrAnnounce)->Value()->SetEvidence(usrAnnounceData);\n    theNet.GetNode(usrGesture)->Value()->SetEvidence(usrGestureData);\n    theNet.GetNode(headingAdj)->Value()->SetEvidence(headingAdjData);\n    theNet.GetNode(distanceAdj)->Value()->SetEvidence(distanceAdjData);\n\n    \/\/ Update the network\n    theNet.UpdateBeliefs();\n\n    \/\/ Get the result values\n    DSL_sysCoordinates theCoordinates(*theNet.GetNode(category)->Value());\n    DSL_idArray *theNames;\n    theNames = theNet.GetNode(category)->Definition()->GetOutcomesNames();\n\n    int objectIndex = theNames->FindPosition(\"object\"); \n    int regionIndex = theNames->FindPosition(\"region\"); \n    int workspaceIndex = theNames->FindPosition(\"workspace\"); \n    int unknownIndex = theNames->FindPosition(\"unknown\"); \n\n    \/\/ Probability of category \n    double P_CategoryIs[4];\n    \/\/ 0 P_CategoryIsObject\n    \/\/ 1 P_CategoryIsRegion\n    \/\/ 2 P_CategoryIsWorkspace\n    \/\/ 3 P_CategoryIsUnknown\n\n    theCoordinates[0] = objectIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = object)\n    P_CategoryIs[0] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = object) = %f\",P_CategoryIs[0]);\n\n    theCoordinates[0] = regionIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = region)\n    P_CategoryIs[1] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = region) = %f\",P_CategoryIs[1]);\n\n    theCoordinates[0] = workspaceIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = workspace)\n    P_CategoryIs[2] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = workspace) = %f\",P_CategoryIs[2]);\n\n    theCoordinates[0] = unknownIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = unknown)\n    P_CategoryIs[3] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = unknown) = %f\",P_CategoryIs[3]);\n\n    ROS_INFO(\"[Interaction_Recognition] User was presenting category %d\", categoryData);\n\n\n    \/\/\/ UPDATING STATISTICS\n    int CategoryWin=-1;\n    double P_CategoryWin=-1;\n    for (int i=0; i<4; i++) {\n        if (P_CategoryWin < P_CategoryIs[i]) {\n            P_CategoryWin = P_CategoryIs[i];\n            CategoryWin=i;\n        }\n    }\n\n    \/\/ Difference\n    P_CategoryIs[0] = P_CategoryWin-P_CategoryIs[0];\n    P_CategoryIs[1] = P_CategoryWin-P_CategoryIs[1];\n    P_CategoryIs[2] = P_CategoryWin-P_CategoryIs[2];\n    P_CategoryIs[3] = P_CategoryWin-P_CategoryIs[3];\n\n    \/\/ Checking results category\n    int equalCategory=0;\n    std::vector equalCategories;\n    for (int i=0; i<4; i++) {\n        if (P_CategoryIs[i]\"\n                         << CategoryWin;\n            statsFails.push_back(stringStream.str());\n        }\n    }\n    else if (equalCategory==2) {    \/\/ 2 are similar\n        if ( P_CategoryIs[categoryData] < MAX_DIFF or categoryData == 3) {\n            Stats_Results[2]++;     \/\/ Category is among them, or is Unknown\n            std::ostringstream stringStream;\n            stringStream << categoryData <<\" -> \"<< equalCategories[0]<<\" or \"\n                         << equalCategories[1];\n            statsBetween2.push_back(stringStream.str());\n        }\n        else {\n            Stats_Results[6]++;     \/\/ Category NOT among them, FAIL\n        }\n    }\n    else if (equalCategory==3) {    \/\/ 3 are similar\n        if ( P_CategoryIs[categoryData] < MAX_DIFF or categoryData == 3) {\n            Stats_Results[3]++;     \/\/ Category is among them, or is Unknown\n            std::ostringstream stringStream;\n            stringStream << categoryData <<\" \"<< equalCategories[0]<<\", \"\n                         << equalCategories[1]<<\" or \" << equalCategories[2];\n            statsAmong3.push_back(stringStream.str());\n        }\n        else {\n            Stats_Results[7]++;     \/\/ Category NOT among them, FAIL\n        }\n    }\n    else if (equalCategory==4) {    \/\/ all are similar\n        Stats_Results[4]++;\n    }\n    else {\n        Stats_Results[8]++;         \/\/WTF??\n    }\n\n    \/\/ Clear the evidence in nodes\n    theNet.GetNode(lastCommand)->Value()->ClearEvidence();\n    theNet.GetNode(usrAnnounce)->Value()->ClearEvidence();\n    theNet.GetNode(usrGesture)->Value()->ClearEvidence();\n    theNet.GetNode(headingAdj)->Value()->ClearEvidence();\n    theNet.GetNode(distanceAdj)->Value()->ClearEvidence();\n\n\n    ROS_INFO(\"[Interaction_Recognition] * * * * \") ;\n    \n}\n\n\nint InteractionRecognition::Main (const char* path) {\n\n    \/\/ Open BN GENIE file\n    if (theNet.ReadFile(path) != 0) {\n        ROS_ERROR(\"[interaction_recognition] Cannot open the Bayesian Network\");\n        ROS_ERROR(\"[interaction_recognition] BN=\\\"%s\\\"\",path);\n        return 1;\n    }\n    else {\n        ROS_INFO(\"[interaction_recognition] Bayesian Network opened successfully\");\n        ROS_INFO(\"[interaction_recognition] BN=\\\"%s\\\"\",path);\n    }\n\n    \/\/ Wait for callbacks\n    ros::spin();\n\n}\n\n\n\n\nvoid InteractionRecognition::print_statistics()\n{\n\n    ROS_WARN(\"[Interaction_Learner] No more data!\");\n    ROS_WARN(\"[Interaction_Learner] So, the node will be stopped gently :)\");\n    ROS_INFO(\"[Interaction_Learner] ********** STATISTICS **********\");\n    ROS_INFO(\"[Interaction_Learner] %d are OK!!\", Stats_Results[0]);\n    ROS_INFO(\"[Interaction_Learner] %d Mismatches!!\", Stats_Results[1]);\n    for (int i=0; i 0, something weird is going on, CHECK CODE!!!\", \n                Stats_Results[8]);\n    ROS_INFO(\"[Interaction_Learner] ********** ********** **********\");\n\n}\n\n\n\nint main(int argc, char **argv)\n{\n\n    ros::init(argc, argv, \"interaction_recognition\");\n    if (argc != 2) {\n        ROS_ERROR(\"[interaction_recognition] usage: interaction_recognition BAYESIAN_NET\");\n        exit(1);\n    }\n\n    InteractionRecognition foo;\n    return foo.Main(argv[1]);\n\n}\n\n\n\n\/**\n *  Dictionary to define commands because some annotations have typographic errors.\n *\n *  back    => 0\n *  follow  => 1\n *  forward => 2\n *  stop    => 3\n *  turn    => 4\n *  none    => 5\n *\n *\/\n\n\/**\n *  Dictionary to define gestures because some annotations have typographic errors.\n *\n *  fingertip_point => 0\n *  hand_point      => 1\n *  hold_item       => 2\n *  sweep_wave      => 3\n *  touch_full_hand => 4\n *  none            => 5\n *\n *\/\n\n\/**\n *  Dictionary to define the presentation category in object, region or workspace.\n *  Besides, unknown category is defined when it was not confirmed by the robot, or\n *  could cause ambiguity\n *\n *  object      => 0\n *  region      => 1\n *  workspace   => 2\n *  unknown     => 3\n *\n *\/\n[interaction_recognition] Little modifications in the output\/*\n *      This node is used to perform inference in a Bayesian network.\n *      It's subscribed to interaction_monitor \/BN_vars topic \n *      to obtain data and then performs inference with a BN using SMILE libraries\n *\n *      At the end it prints some statistics with the performance.\n *\n *      Lunds tekniska högskola | LTH 2015\n *      Felip Marti Carrillo\n *\n *      MIT License (MIT)\n *      Copyright (c) 2015 Felip Marti Carrillo\n *\/\n\n\n#include \"interaction_recognition_node.h\"\n\n\nInteractionRecognition::InteractionRecognition (void)\n{\n\n    \/\/ Init Subscriber\n    this->sub = this->n.subscribe(\"BN_vars\", 1,\n                        &InteractionRecognition::perform_inference_callback, this);\n\n    \/\/ Init Stats\n    for (int i=0; i<9; i++) {\n         Stats_Results[i]=0; \n    }\n\n    \/\/ Max difference to consider 2 objects different\n    MAX_DIFF = 0.1;\n\n    \/\/ Vector of strings with fails\n    statsFails.resize(0);\n\n}\n\n\nInteractionRecognition::~InteractionRecognition (void)\n{\n}\n\n\nvoid InteractionRecognition::perform_inference_callback\n                        (const interaction_monitor::BayesianNetworkVariable& msg)\n{\n\n    if (msg.category==-1) {\n\n        print_statistics();\n        exit(0);\n\n    }\n    \n    \/\/\/ Performing Inference\n    ROS_INFO(\"[Interaction_Recognition] Performing Inference\");\n    \n    \/\/ Vars to get the handle of node\n    int category = theNet.FindNode(\"category\"); \n    int lastCommand = theNet.FindNode(\"lastCommand\"); \n    int usrAnnounce = theNet.FindNode(\"usrAnnounce\"); \n    int usrGesture = theNet.FindNode(\"usrGesture\"); \n    int headingAdj = theNet.FindNode(\"headingAdj\"); \n    int distanceAdj = theNet.FindNode(\"distanceAdj\"); \n\n    \/\/ Vars to store data\n    int lastCommandData=msg.last_cmd;\n    int usrAnnounceData=msg.announce;\n    int usrGestureData=msg.gesture;   \n    int headingAdjData=msg.head_adj;  \n    int distanceAdjData=msg.dist_adj; \n    int categoryData=msg.category;     \n    \n    \/\/ Setting evidence\n    theNet.GetNode(lastCommand)->Value()->SetEvidence(lastCommandData);\n    theNet.GetNode(usrAnnounce)->Value()->SetEvidence(usrAnnounceData);\n    theNet.GetNode(usrGesture)->Value()->SetEvidence(usrGestureData);\n    theNet.GetNode(headingAdj)->Value()->SetEvidence(headingAdjData);\n    theNet.GetNode(distanceAdj)->Value()->SetEvidence(distanceAdjData);\n\n    \/\/ Update the network\n    theNet.UpdateBeliefs();\n\n    \/\/ Get the result values\n    DSL_sysCoordinates theCoordinates(*theNet.GetNode(category)->Value());\n    DSL_idArray *theNames;\n    theNames = theNet.GetNode(category)->Definition()->GetOutcomesNames();\n\n    int objectIndex = theNames->FindPosition(\"object\"); \n    int regionIndex = theNames->FindPosition(\"region\"); \n    int workspaceIndex = theNames->FindPosition(\"workspace\"); \n    int unknownIndex = theNames->FindPosition(\"unknown\"); \n\n    \/\/ Probability of category \n    double P_CategoryIs[4];\n    \/\/ 0 P_CategoryIsObject\n    \/\/ 1 P_CategoryIsRegion\n    \/\/ 2 P_CategoryIsWorkspace\n    \/\/ 3 P_CategoryIsUnknown\n\n    theCoordinates[0] = objectIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = object)\n    P_CategoryIs[0] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = object) = %f\",P_CategoryIs[0]);\n\n    theCoordinates[0] = regionIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = region)\n    P_CategoryIs[1] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = region) = %f\",P_CategoryIs[1]);\n\n    theCoordinates[0] = workspaceIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = workspace)\n    P_CategoryIs[2] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = workspace) = %f\",P_CategoryIs[2]);\n\n    theCoordinates[0] = unknownIndex;\n    theCoordinates.GoToCurrentPosition();\n    \/\/ get P(\"category\" = unknown)\n    P_CategoryIs[3] = theCoordinates.UncheckedValue();\n    ROS_INFO(\"[Interaction_Recognition] P(\\\"category\\\" = unknown) = %f\",P_CategoryIs[3]);\n\n    ROS_INFO(\"[Interaction_Recognition] User was presenting category %d\", categoryData);\n\n\n    \/\/\/ UPDATING STATISTICS\n    int CategoryWin=-1;\n    double P_CategoryWin=-1;\n    for (int i=0; i<4; i++) {\n        if (P_CategoryWin < P_CategoryIs[i]) {\n            P_CategoryWin = P_CategoryIs[i];\n            CategoryWin=i;\n        }\n    }\n\n    \/\/ Difference\n    P_CategoryIs[0] = P_CategoryWin-P_CategoryIs[0];\n    P_CategoryIs[1] = P_CategoryWin-P_CategoryIs[1];\n    P_CategoryIs[2] = P_CategoryWin-P_CategoryIs[2];\n    P_CategoryIs[3] = P_CategoryWin-P_CategoryIs[3];\n\n    \/\/ Checking results category\n    int equalCategory=0;\n    std::vector equalCategories;\n    for (int i=0; i<4; i++) {\n        if (P_CategoryIs[i]\"\n                         << CategoryWin;\n            statsFails.push_back(stringStream.str());\n        }\n    }\n    else if (equalCategory==2) {    \/\/ 2 are similar\n        if ( P_CategoryIs[categoryData] < MAX_DIFF or categoryData == 3) {\n            Stats_Results[2]++;     \/\/ Category is among them, or is Unknown\n            std::ostringstream stringStream;\n            stringStream << categoryData <<\" -> \"<< equalCategories[0]<<\" or \"\n                         << equalCategories[1];\n            statsBetween2.push_back(stringStream.str());\n        }\n        else {\n            Stats_Results[6]++;     \/\/ Category NOT among them, FAIL\n        }\n    }\n    else if (equalCategory==3) {    \/\/ 3 are similar\n        if ( P_CategoryIs[categoryData] < MAX_DIFF or categoryData == 3) {\n            Stats_Results[3]++;     \/\/ Category is among them, or is Unknown\n            std::ostringstream stringStream;\n            stringStream << categoryData <<\" -> \"<< equalCategories[0]<<\", \"\n                         << equalCategories[1]<<\" or \" << equalCategories[2];\n            statsAmong3.push_back(stringStream.str());\n        }\n        else {\n            Stats_Results[7]++;     \/\/ Category NOT among them, FAIL\n        }\n    }\n    else if (equalCategory==4) {    \/\/ all are similar\n        Stats_Results[4]++;\n    }\n    else {\n        Stats_Results[8]++;         \/\/WTF??\n    }\n\n    \/\/ Clear the evidence in nodes\n    theNet.GetNode(lastCommand)->Value()->ClearEvidence();\n    theNet.GetNode(usrAnnounce)->Value()->ClearEvidence();\n    theNet.GetNode(usrGesture)->Value()->ClearEvidence();\n    theNet.GetNode(headingAdj)->Value()->ClearEvidence();\n    theNet.GetNode(distanceAdj)->Value()->ClearEvidence();\n\n\n    ROS_INFO(\"[Interaction_Recognition] * * * * \") ;\n    \n}\n\n\nint InteractionRecognition::Main (const char* path) {\n\n    \/\/ Open BN GENIE file\n    if (theNet.ReadFile(path) != 0) {\n        ROS_ERROR(\"[interaction_recognition] Cannot open the Bayesian Network\");\n        ROS_ERROR(\"[interaction_recognition] BN=\\\"%s\\\"\",path);\n        return 1;\n    }\n    else {\n        ROS_INFO(\"[interaction_recognition] Bayesian Network opened successfully\");\n        ROS_INFO(\"[interaction_recognition] BN=\\\"%s\\\"\",path);\n    }\n\n    \/\/ Wait for callbacks\n    ros::spin();\n\n}\n\n\n\n\nvoid InteractionRecognition::print_statistics()\n{\n\n    ROS_WARN(\"[Interaction_Learner] No more data!\");\n    ROS_WARN(\"[Interaction_Learner] So, the node will be stopped gently :)\");\n    ROS_INFO(\"[Interaction_Learner] ********** STATISTICS **********\");\n    ROS_INFO(\"[Interaction_Learner] %d are OK!!\", Stats_Results[0]);\n    ROS_INFO(\"[Interaction_Learner] %d Mismatches!!\", Stats_Results[1]);\n    for (int i=0; i 0, something weird is going on, CHECK CODE!!!\", \n                Stats_Results[8]);\n    ROS_INFO(\"[Interaction_Learner] ********** ********** **********\");\n\n}\n\n\n\nint main(int argc, char **argv)\n{\n\n    ros::init(argc, argv, \"interaction_recognition\");\n    if (argc != 2) {\n        ROS_ERROR(\"[interaction_recognition] usage: interaction_recognition BAYESIAN_NET\");\n        exit(1);\n    }\n\n    InteractionRecognition foo;\n    return foo.Main(argv[1]);\n\n}\n\n\n\n\/**\n *  Dictionary to define commands because some annotations have typographic errors.\n *\n *  back    => 0\n *  follow  => 1\n *  forward => 2\n *  stop    => 3\n *  turn    => 4\n *  none    => 5\n *\n *\/\n\n\/**\n *  Dictionary to define gestures because some annotations have typographic errors.\n *\n *  fingertip_point => 0\n *  hand_point      => 1\n *  hold_item       => 2\n *  sweep_wave      => 3\n *  touch_full_hand => 4\n *  none            => 5\n *\n *\/\n\n\/**\n *  Dictionary to define the presentation category in object, region or workspace.\n *  Besides, unknown category is defined when it was not confirmed by the robot, or\n *  could cause ambiguity\n *\n *  object      => 0\n *  region      => 1\n *  workspace   => 2\n *  unknown     => 3\n *\n *\/\n<|endoftext|>"}
{"text":"\/*\n *\n * Copyright 2019 Asylo authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"asylo\/platform\/primitives\/sgx\/trusted_sgx.h\"\n\n#include \n\n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"asylo\/platform\/arch\/sgx\/trusted\/generated_bridge_t.h\"\n#include \"asylo\/platform\/posix\/threading\/thread_manager.h\"\n#include \"asylo\/platform\/primitives\/extent.h\"\n#include \"asylo\/platform\/primitives\/primitive_status.h\"\n#include \"asylo\/platform\/primitives\/primitives.h\"\n#include \"asylo\/platform\/primitives\/sgx\/sgx_error_space.h\"\n#include \"asylo\/platform\/primitives\/sgx\/sgx_params.h\"\n#include \"asylo\/platform\/primitives\/trusted_primitives.h\"\n#include \"asylo\/platform\/primitives\/trusted_runtime.h\"\n#include \"asylo\/platform\/primitives\/util\/message.h\"\n#include \"asylo\/platform\/primitives\/util\/primitive_locks.h\"\n#include \"asylo\/platform\/primitives\/util\/trusted_runtime_helper.h\"\n#include \"asylo\/platform\/primitives\/x86\/spin_lock.h\"\n#include \"asylo\/util\/cleanup.h\"\n#include \"asylo\/util\/status.h\"\n#include \"asylo\/util\/status_macros.h\"\n#include \"include\/sgx_trts.h\"\n\nextern \"C\" int enc_untrusted_puts(const char *message);\n\nnamespace asylo {\nnamespace primitives {\n\nnamespace {\n\n#define CHECK_OCALL(status_)                                                 \\\n  do {                                                                       \\\n    sgx_status_t status##__COUNTER__ = status_;                              \\\n    if (status##__COUNTER__ != SGX_SUCCESS) {                                \\\n      TrustedPrimitives::BestEffortAbort(                                    \\\n          absl::StrCat(                                                      \\\n              __FILE__, \":\", __LINE__, \": \",                                 \\\n              asylo::Status(status##__COUNTER__, \"ocall failed\").ToString()) \\\n              .c_str());                                                     \\\n    }                                                                        \\\n  } while (0)\n\n}  \/\/ namespace\n\n\/\/ Entry handler installed by the runtime to finalize the enclave at the time it\n\/\/ is destroyed.\nPrimitiveStatus FinalizeEnclave(void *context, MessageReader *in,\n                                MessageWriter *out) {\n  if (in) {\n    ASYLO_RETURN_IF_READER_NOT_EMPTY(*in);\n  }\n  return asylo_enclave_fini();\n}\n\n\/\/ Entry handler installed by the runtime to start the created thread.\nPrimitiveStatus DonateThread(void *context, MessageReader *in,\n                             MessageWriter *out) {\n  if (in) {\n    ASYLO_RETURN_IF_READER_NOT_EMPTY(*in);\n  }\n  int result = 0;\n  try {\n    ThreadManager *thread_manager = ThreadManager::GetInstance();\n    result = thread_manager->StartThread();\n  } catch (...) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Uncaught exception in enclave entry handler: DonateThread. Failed to \"\n        \"get ThreadManager instance or start the thread.\");\n  }\n  return PrimitiveStatus(result);\n}\n\n\/\/ Registers internal handlers, including entry handlers.\nvoid RegisterInternalHandlers() {\n  \/\/ Register the enclave donate thread entry handler.\n  if (!TrustedPrimitives::RegisterEntryHandler(kSelectorAsyloDonateThread,\n                                               EntryHandler{DonateThread})\n           .ok()) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Could not register entry handler: DonateThread.\");\n  }\n\n  \/\/ Register the enclave finalization entry handler.\n  if (!TrustedPrimitives::RegisterEntryHandler(kSelectorAsyloFini,\n                                               EntryHandler{FinalizeEnclave})\n           .ok()) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Could not register entry handler: FinalizeEnclave\");\n  }\n}\n\nvoid TrustedPrimitives::BestEffortAbort(const char *message) {\n  DebugPuts(message);\n  enc_block_ecalls();\n  MarkEnclaveAborted();\n  abort();\n}\n\nPrimitiveStatus TrustedPrimitives::RegisterEntryHandler(\n    uint64_t selector, const EntryHandler &handler) {\n  return asylo::primitives::RegisterEntryHandler(selector, handler);\n}\n\nint asylo_enclave_call(uint64_t selector, void *buffer) {\n  SgxParams *const sgx_params = reinterpret_cast(buffer);\n\n  const void *input = sgx_params->input;\n  size_t input_size = sgx_params->input_size;\n  sgx_params->input = nullptr;\n  sgx_params->input_size = 0;\n  void *output = nullptr;\n  size_t output_size = 0;\n\n  if (input) {\n    if (TrustedPrimitives::IsTrustedExtent(input, input_size)) {\n      PrimitiveStatus status{error::GoogleError::INVALID_ARGUMENT,\n                             \"input should lie within untrusted memory.\"};\n      return status.error_code();\n    }\n    if (input_size > 0) {\n      \/\/ Copy untrusted |input| to trusted memory and pass that as input.\n      void *trusted_input = malloc(input_size);\n      memcpy(trusted_input, input, input_size);\n      TrustedPrimitives::UntrustedLocalFree(const_cast(input));\n      input = trusted_input;\n    } else {\n      TrustedPrimitives::UntrustedLocalFree(const_cast(input));\n      input = nullptr;\n    }\n  }\n\n  PrimitiveStatus status =\n      InvokeEntryHandler(selector, input, input_size, &output, &output_size);\n\n  if (output) {\n    \/\/ Copy trusted |*output| to untrusted memory and pass that as\n    \/\/ output. We also free trusted |*output| after it is copied to untrusted\n    \/\/ side. The untrusted caller is still responsible for freeing |*output|,\n    \/\/ which now points to untrusted memory.\n    if (!TrustedPrimitives::IsTrustedExtent(output, output_size)) {\n      PrimitiveStatus{error::GoogleError::INVALID_ARGUMENT,\n                      \"output should lie in trusted memory\"};\n      return status.error_code();\n    }\n\n    void *untrusted_output =\n        TrustedPrimitives::UntrustedLocalAlloc(output_size);\n    memcpy(untrusted_output, output, output_size);\n    free(output);\n    output = untrusted_output;\n  }\n\n  sgx_params->output = output;\n  sgx_params->output_size = static_cast(output_size);\n  return status.error_code();\n}\n\n\/\/ For SGX, UntrustedLocalAlloc uses malloc() on the untrusted host to\n\/\/ allocate memory.\nvoid *TrustedPrimitives::UntrustedLocalAlloc(size_t size) noexcept {\n  void *result;\n  CHECK_OCALL(\n      ocall_untrusted_local_alloc(&result, static_cast(size)));\n  if (result && !sgx_is_outside_enclave(result, static_cast(size))) {\n    abort();\n  }\n\n  \/\/ On error, malloc returns nullptr and sets errno to ENOMEM.\n  if (!result) {\n    errno = ENOMEM;\n    TrustedPrimitives::DebugPuts(\"UntrustedLocalAlloc on SGX failed.\");\n  }\n  return result;\n}\n\n\/\/ For SGX, UntrustedLocalFree uses free() on the untrusted host to free the\n\/\/ memory allocated by UntrustedLocalAlloc.\nvoid TrustedPrimitives::UntrustedLocalFree(void *ptr) noexcept {\n  CHECK_OCALL(ocall_untrusted_local_free(ptr));\n}\n\nbool TrustedPrimitives::IsTrustedExtent(const void *addr, size_t size) {\n  return enc_is_within_enclave(addr, size);\n}\n\nvoid TrustedPrimitives::DebugPuts(const char *message) {\n  enc_untrusted_puts(message);\n}\n\nPrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n                                                 MessageWriter *input,\n                                                 MessageReader *output) {\n  int ret;\n\n  SgxParams *const sgx_params = reinterpret_cast(\n      TrustedPrimitives::UntrustedLocalAlloc(sizeof(SgxParams)));\n  Cleanup clean_up(\n      [sgx_params] { TrustedPrimitives::UntrustedLocalFree(sgx_params); });\n  sgx_params->input_size = 0;\n  sgx_params->input = nullptr;\n  if (input) {\n    sgx_params->input_size = input->MessageSize();\n    if (sgx_params->input_size > 0) {\n      sgx_params->input =\n          TrustedPrimitives::UntrustedLocalAlloc(sgx_params->input_size);\n      \/\/ Copy data to |input_buffer|.\n      input->Serialize(const_cast(sgx_params->input));\n    }\n  }\n  sgx_params->output_size = 0;\n  sgx_params->output = nullptr;\n  CHECK_OCALL(\n      ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n  if (sgx_params->output) {\n    \/\/ For the results obtained in |output_buffer|, copy them to |output|\n    \/\/ before freeing the buffer.\n    output->Deserialize(sgx_params->output, sgx_params->output_size);\n    TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n  }\n  return PrimitiveStatus::OkStatus();\n}\n\n\/\/ For SGX, CreateThread() needs to exit the enclave by making an UntrustedCall\n\/\/ to CreateThreadHandler, which makes an EnclaveCall to enter the enclave with\n\/\/ the new thread and register it with the thread manager and execute the\n\/\/ intended callback.\nint TrustedPrimitives::CreateThread() {\n  MessageWriter input;\n  MessageReader output;\n  PrimitiveStatus status =\n      UntrustedCall(kSelectorCreateThread, &input, &output);\n  if (!status.ok()) {\n    DebugPuts(\"CreateThread failed.\");\n    return -1;\n  }\n  if (output.size() != 1) {\n    DebugPuts(\"CreateThread error: unexpected output size received.\");\n    abort();\n  }\n  return output.next();\n}\n\n}  \/\/ namespace primitives\n}  \/\/ namespace asylo\nUse trusted runtime for memory bounds checking\/*\n *\n * Copyright 2019 Asylo authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"asylo\/platform\/primitives\/sgx\/trusted_sgx.h\"\n\n#include \n\n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"asylo\/platform\/arch\/sgx\/trusted\/generated_bridge_t.h\"\n#include \"asylo\/platform\/posix\/threading\/thread_manager.h\"\n#include \"asylo\/platform\/primitives\/extent.h\"\n#include \"asylo\/platform\/primitives\/primitive_status.h\"\n#include \"asylo\/platform\/primitives\/primitives.h\"\n#include \"asylo\/platform\/primitives\/sgx\/sgx_error_space.h\"\n#include \"asylo\/platform\/primitives\/sgx\/sgx_params.h\"\n#include \"asylo\/platform\/primitives\/trusted_primitives.h\"\n#include \"asylo\/platform\/primitives\/trusted_runtime.h\"\n#include \"asylo\/platform\/primitives\/util\/message.h\"\n#include \"asylo\/platform\/primitives\/util\/primitive_locks.h\"\n#include \"asylo\/platform\/primitives\/util\/trusted_runtime_helper.h\"\n#include \"asylo\/platform\/primitives\/x86\/spin_lock.h\"\n#include \"asylo\/util\/cleanup.h\"\n#include \"asylo\/util\/status.h\"\n#include \"asylo\/util\/status_macros.h\"\n#include \"include\/sgx_trts.h\"\n\nextern \"C\" int enc_untrusted_puts(const char *message);\n\nnamespace asylo {\nnamespace primitives {\n\nnamespace {\n\n#define CHECK_OCALL(status_)                                                 \\\n  do {                                                                       \\\n    sgx_status_t status##__COUNTER__ = status_;                              \\\n    if (status##__COUNTER__ != SGX_SUCCESS) {                                \\\n      TrustedPrimitives::BestEffortAbort(                                    \\\n          absl::StrCat(                                                      \\\n              __FILE__, \":\", __LINE__, \": \",                                 \\\n              asylo::Status(status##__COUNTER__, \"ocall failed\").ToString()) \\\n              .c_str());                                                     \\\n    }                                                                        \\\n  } while (0)\n\n}  \/\/ namespace\n\n\/\/ Entry handler installed by the runtime to finalize the enclave at the time it\n\/\/ is destroyed.\nPrimitiveStatus FinalizeEnclave(void *context, MessageReader *in,\n                                MessageWriter *out) {\n  if (in) {\n    ASYLO_RETURN_IF_READER_NOT_EMPTY(*in);\n  }\n  return asylo_enclave_fini();\n}\n\n\/\/ Entry handler installed by the runtime to start the created thread.\nPrimitiveStatus DonateThread(void *context, MessageReader *in,\n                             MessageWriter *out) {\n  if (in) {\n    ASYLO_RETURN_IF_READER_NOT_EMPTY(*in);\n  }\n  int result = 0;\n  try {\n    ThreadManager *thread_manager = ThreadManager::GetInstance();\n    result = thread_manager->StartThread();\n  } catch (...) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Uncaught exception in enclave entry handler: DonateThread. Failed to \"\n        \"get ThreadManager instance or start the thread.\");\n  }\n  return PrimitiveStatus(result);\n}\n\n\/\/ Registers internal handlers, including entry handlers.\nvoid RegisterInternalHandlers() {\n  \/\/ Register the enclave donate thread entry handler.\n  if (!TrustedPrimitives::RegisterEntryHandler(kSelectorAsyloDonateThread,\n                                               EntryHandler{DonateThread})\n           .ok()) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Could not register entry handler: DonateThread.\");\n  }\n\n  \/\/ Register the enclave finalization entry handler.\n  if (!TrustedPrimitives::RegisterEntryHandler(kSelectorAsyloFini,\n                                               EntryHandler{FinalizeEnclave})\n           .ok()) {\n    TrustedPrimitives::BestEffortAbort(\n        \"Could not register entry handler: FinalizeEnclave\");\n  }\n}\n\nvoid TrustedPrimitives::BestEffortAbort(const char *message) {\n  DebugPuts(message);\n  enc_block_ecalls();\n  MarkEnclaveAborted();\n  abort();\n}\n\nPrimitiveStatus TrustedPrimitives::RegisterEntryHandler(\n    uint64_t selector, const EntryHandler &handler) {\n  return asylo::primitives::RegisterEntryHandler(selector, handler);\n}\n\nint asylo_enclave_call(uint64_t selector, void *buffer) {\n  SgxParams *const sgx_params = reinterpret_cast(buffer);\n\n  const void *input = sgx_params->input;\n  size_t input_size = sgx_params->input_size;\n  sgx_params->input = nullptr;\n  sgx_params->input_size = 0;\n  void *output = nullptr;\n  size_t output_size = 0;\n\n  if (input) {\n    if (TrustedPrimitives::IsTrustedExtent(input, input_size)) {\n      PrimitiveStatus status{error::GoogleError::INVALID_ARGUMENT,\n                             \"input should lie within untrusted memory.\"};\n      return status.error_code();\n    }\n    if (input_size > 0) {\n      \/\/ Copy untrusted |input| to trusted memory and pass that as input.\n      void *trusted_input = malloc(input_size);\n      memcpy(trusted_input, input, input_size);\n      TrustedPrimitives::UntrustedLocalFree(const_cast(input));\n      input = trusted_input;\n    } else {\n      TrustedPrimitives::UntrustedLocalFree(const_cast(input));\n      input = nullptr;\n    }\n  }\n\n  PrimitiveStatus status =\n      InvokeEntryHandler(selector, input, input_size, &output, &output_size);\n\n  if (output) {\n    \/\/ Copy trusted |*output| to untrusted memory and pass that as\n    \/\/ output. We also free trusted |*output| after it is copied to untrusted\n    \/\/ side. The untrusted caller is still responsible for freeing |*output|,\n    \/\/ which now points to untrusted memory.\n    if (!TrustedPrimitives::IsTrustedExtent(output, output_size)) {\n      PrimitiveStatus{error::GoogleError::INVALID_ARGUMENT,\n                      \"output should lie in trusted memory\"};\n      return status.error_code();\n    }\n\n    void *untrusted_output =\n        TrustedPrimitives::UntrustedLocalAlloc(output_size);\n    memcpy(untrusted_output, output, output_size);\n    free(output);\n    output = untrusted_output;\n  }\n\n  sgx_params->output = output;\n  sgx_params->output_size = static_cast(output_size);\n  return status.error_code();\n}\n\n\/\/ For SGX, UntrustedLocalAlloc uses malloc() on the untrusted host to\n\/\/ allocate memory.\nvoid *TrustedPrimitives::UntrustedLocalAlloc(size_t size) noexcept {\n  void *result;\n  CHECK_OCALL(\n      ocall_untrusted_local_alloc(&result, static_cast(size)));\n  if (result && !enc_is_outside_enclave(result, static_cast(size))) {\n    abort();\n  }\n\n  \/\/ On error, malloc returns nullptr and sets errno to ENOMEM.\n  if (!result) {\n    errno = ENOMEM;\n    TrustedPrimitives::DebugPuts(\"UntrustedLocalAlloc on SGX failed.\");\n  }\n  return result;\n}\n\n\/\/ For SGX, UntrustedLocalFree uses free() on the untrusted host to free the\n\/\/ memory allocated by UntrustedLocalAlloc.\nvoid TrustedPrimitives::UntrustedLocalFree(void *ptr) noexcept {\n  CHECK_OCALL(ocall_untrusted_local_free(ptr));\n}\n\nbool TrustedPrimitives::IsTrustedExtent(const void *addr, size_t size) {\n  return enc_is_within_enclave(addr, size);\n}\n\nvoid TrustedPrimitives::DebugPuts(const char *message) {\n  enc_untrusted_puts(message);\n}\n\nPrimitiveStatus TrustedPrimitives::UntrustedCall(uint64_t untrusted_selector,\n                                                 MessageWriter *input,\n                                                 MessageReader *output) {\n  int ret;\n\n  SgxParams *const sgx_params = reinterpret_cast(\n      TrustedPrimitives::UntrustedLocalAlloc(sizeof(SgxParams)));\n  Cleanup clean_up(\n      [sgx_params] { TrustedPrimitives::UntrustedLocalFree(sgx_params); });\n  sgx_params->input_size = 0;\n  sgx_params->input = nullptr;\n  if (input) {\n    sgx_params->input_size = input->MessageSize();\n    if (sgx_params->input_size > 0) {\n      sgx_params->input =\n          TrustedPrimitives::UntrustedLocalAlloc(sgx_params->input_size);\n      \/\/ Copy data to |input_buffer|.\n      input->Serialize(const_cast(sgx_params->input));\n    }\n  }\n  sgx_params->output_size = 0;\n  sgx_params->output = nullptr;\n  CHECK_OCALL(\n      ocall_dispatch_untrusted_call(&ret, untrusted_selector, sgx_params));\n  if (sgx_params->output) {\n    \/\/ For the results obtained in |output_buffer|, copy them to |output|\n    \/\/ before freeing the buffer.\n    output->Deserialize(sgx_params->output, sgx_params->output_size);\n    TrustedPrimitives::UntrustedLocalFree(sgx_params->output);\n  }\n  return PrimitiveStatus::OkStatus();\n}\n\n\/\/ For SGX, CreateThread() needs to exit the enclave by making an UntrustedCall\n\/\/ to CreateThreadHandler, which makes an EnclaveCall to enter the enclave with\n\/\/ the new thread and register it with the thread manager and execute the\n\/\/ intended callback.\nint TrustedPrimitives::CreateThread() {\n  MessageWriter input;\n  MessageReader output;\n  PrimitiveStatus status =\n      UntrustedCall(kSelectorCreateThread, &input, &output);\n  if (!status.ok()) {\n    DebugPuts(\"CreateThread failed.\");\n    return -1;\n  }\n  if (output.size() != 1) {\n    DebugPuts(\"CreateThread error: unexpected output size received.\");\n    abort();\n  }\n  return output.next();\n}\n\n}  \/\/ namespace primitives\n}  \/\/ namespace asylo\n<|endoftext|>"}
{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"gstframegrabber.hxx\"\n#include \"gstplayer.hxx\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#ifdef AVMEDIA_GST_0_10\n#  define AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME \"com.sun.star.comp.avmedia.FrameGrabber_GStreamer_0_10\"\n#  define AVMEDIA_GST_FRAMEGRABBER_SERVICENAME \"com.sun.star.media.FrameGrabber_GStreamer_0_10\"\n#else\n#  define AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME \"com.sun.star.comp.avmedia.FrameGrabber_GStreamer\"\n#  define AVMEDIA_GST_FRAMEGRABBER_SERVICENAME \"com.sun.star.media.FrameGrabber_GStreamer\"\n#endif\n\nusing namespace ::com::sun::star;\n\nnamespace avmedia { namespace gstreamer {\n\nvoid FrameGrabber::disposePipeline()\n{\n    if( mpPipeline != NULL )\n    {\n        gst_element_set_state( mpPipeline, GST_STATE_NULL );\n        g_object_unref( G_OBJECT( mpPipeline ) );\n        mpPipeline = NULL;\n    }\n}\n\nFrameGrabber::FrameGrabber( const OUString &rURL ) :\n    FrameGrabber_BASE()\n{\n    gchar *pPipelineStr;\n    pPipelineStr = g_strdup_printf(\n#ifdef AVMEDIA_GST_0_10\n        \"uridecodebin uri=%s ! ffmpegcolorspace ! videoscale ! appsink \"\n        \"name=sink caps=\\\"video\/x-raw-rgb,format=RGB,pixel-aspect-ratio=1\/1,\"\n        \"bpp=(int)24,depth=(int)24,endianness=(int)4321,\"\n        \"red_mask=(int)0xff0000, green_mask=(int)0x00ff00, blue_mask=(int)0x0000ff\\\"\",\n#else\n        \"uridecodebin uri=%s ! videoconvert ! videoscale ! appsink \"\n        \"name=sink caps=\\\"video\/x-raw,format=RGB,pixel-aspect-ratio=1\/1\\\"\",\n#endif\n        rtl::OUStringToOString( rURL, RTL_TEXTENCODING_UTF8 ).getStr() );\n\n    GError *pError = NULL;\n    mpPipeline = gst_parse_launch( pPipelineStr, &pError );\n    if( pError != NULL) {\n        g_warning( \"Failed to construct frame-grabber pipeline '%s'\\n\", pError->message );\n        g_error_free( pError );\n        disposePipeline();\n    }\n\n    if( mpPipeline ) {\n        \/\/ pre-roll\n        switch( gst_element_set_state( mpPipeline, GST_STATE_PAUSED ) ) {\n        case GST_STATE_CHANGE_FAILURE:\n        case GST_STATE_CHANGE_NO_PREROLL:\n            g_warning( \"failure pre-rolling media\" );\n            disposePipeline();\n            break;\n        default:\n            break;\n        }\n    }\n    if( mpPipeline &&\n        gst_element_get_state( mpPipeline, NULL, NULL, 5 * GST_SECOND ) == GST_STATE_CHANGE_FAILURE )\n        disposePipeline();\n}\n\nFrameGrabber::~FrameGrabber()\n{\n    disposePipeline();\n}\n\nFrameGrabber* FrameGrabber::create( const OUString &rURL )\n{\n    return new FrameGrabber( rURL );\n}\n\nuno::Reference< graphic::XGraphic > SAL_CALL FrameGrabber::grabFrame( double fMediaTime )\n    throw (uno::RuntimeException)\n{\n    uno::Reference< graphic::XGraphic > xRet;\n\n    if( !mpPipeline )\n        return xRet;\n\n    gint64 gst_position = llround( fMediaTime * 1E9 );\n    gst_element_seek_simple(\n        mpPipeline, GST_FORMAT_TIME,\n        (GstSeekFlags)(GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_FLUSH),\n        gst_position );\n\n    GstElement *pSink = gst_bin_get_by_name( GST_BIN( mpPipeline ), \"sink\" );\n    if( !pSink )\n        return xRet;\n\n    GstBuffer *pBuf = NULL;\n    GstCaps *pCaps = NULL;\n\n    \/\/ synchronously fetch the frame\n#ifdef AVMEDIA_GST_0_10\n    g_signal_emit_by_name( pSink, \"pull-preroll\", &pBuf, NULL );\n    if( pBuf )\n        pCaps = GST_BUFFER_CAPS( pBuf );\n#else\n    GstSample *pSample = NULL;\n    g_signal_emit_by_name( pSink, \"pull-preroll\", &pSample, NULL );\n\n    if( pSample )\n    {\n        pBuf = gst_sample_get_buffer( pSample );\n        pCaps = gst_sample_get_caps( pSample );\n    }\n#endif\n\n    \/\/ get geometry\n    int nWidth = 0, nHeight = 0;\n    if( !pCaps )\n        g_warning( \"could not get snapshot format\\n\" );\n    else\n    {\n        GstStructure *pStruct = gst_caps_get_structure( pCaps, 0 );\n\n        \/* we need to get the final caps on the buffer to get the size *\/\n        if( !gst_structure_get_int( pStruct, \"width\", &nWidth ) ||\n            !gst_structure_get_int( pStruct, \"height\", &nHeight ) )\n            nWidth = nHeight = 0;\n    }\n\n    if( pBuf && nWidth > 0 && nHeight > 0 &&\n        \/\/ sanity check the size\n#ifdef AVMEDIA_GST_0_10\n        GST_BUFFER_SIZE( pBuf ) >= static_cast( nWidth * nHeight * 3 )\n#else\n        gst_buffer_get_size( pBuf ) >= ( nWidth * nHeight * 3 )\n#endif\n        )\n    {\n        sal_uInt8 *pData = NULL;\n#ifdef AVMEDIA_GST_0_10\n        pData = GST_BUFFER_DATA( pBuf );\n#else\n        GstMapInfo aMapInfo;\n        gst_buffer_map( pBuf, &aMapInfo, GST_MAP_READ );\n        pData = aMapInfo.data;\n#endif\n\n        int nStride = GST_ROUND_UP_4( nWidth * 3 );\n        Bitmap aBmp( Size( nWidth, nHeight ), 24 );\n\n        BitmapWriteAccess *pWrite = aBmp.AcquireWriteAccess();\n        if( pWrite )\n        {\n            \/\/ yet another cheesy pixel copying loop\n            for( int y = 0; y < nHeight; ++y )\n            {\n                sal_uInt8 *p = pData + y * nStride;\n                for( int x = 0; x < nWidth; ++x )\n                {\n                    BitmapColor col( p[0], p[1], p[2] );\n                    pWrite->SetPixel( y, x, col );\n                    p += 3;\n                }\n            }\n        }\n        aBmp.ReleaseAccess( pWrite );\n\n#ifndef AVMEDIA_GST_0_10\n        gst_buffer_unmap( pBuf, &aMapInfo );\n#endif\n\n        xRet = Graphic( aBmp ).GetXGraphic();\n    }\n\n    return xRet;\n}\n\nOUString SAL_CALL FrameGrabber::getImplementationName(  )\n    throw (uno::RuntimeException)\n{\n    return OUString( AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME );\n}\n\nsal_Bool SAL_CALL FrameGrabber::supportsService( const OUString& ServiceName )\n    throw (uno::RuntimeException)\n{\n    return ServiceName == AVMEDIA_GST_FRAMEGRABBER_SERVICENAME;\n}\n\nuno::Sequence< OUString > SAL_CALL FrameGrabber::getSupportedServiceNames()\n    throw (uno::RuntimeException)\n{\n    uno::Sequence< OUString > aRet(1);\n    aRet[0] = AVMEDIA_GST_FRAMEGRABBER_SERVICENAME;\n\n    return aRet;\n}\n\n} \/\/ namespace gstreamer\n} \/\/ namespace avmedia\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n-Werror,-Wsign-compare\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n *   Licensed to the Apache Software Foundation (ASF) under one or more\n *   contributor license agreements. See the NOTICE file distributed\n *   with this work for additional information regarding copyright\n *   ownership. The ASF licenses this file to you under the Apache\n *   License, Version 2.0 (the \"License\"); you may not use this file\n *   except in compliance with the License. You may obtain a copy of\n *   the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"gstframegrabber.hxx\"\n#include \"gstplayer.hxx\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#ifdef AVMEDIA_GST_0_10\n#  define AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME \"com.sun.star.comp.avmedia.FrameGrabber_GStreamer_0_10\"\n#  define AVMEDIA_GST_FRAMEGRABBER_SERVICENAME \"com.sun.star.media.FrameGrabber_GStreamer_0_10\"\n#else\n#  define AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME \"com.sun.star.comp.avmedia.FrameGrabber_GStreamer\"\n#  define AVMEDIA_GST_FRAMEGRABBER_SERVICENAME \"com.sun.star.media.FrameGrabber_GStreamer\"\n#endif\n\nusing namespace ::com::sun::star;\n\nnamespace avmedia { namespace gstreamer {\n\nvoid FrameGrabber::disposePipeline()\n{\n    if( mpPipeline != NULL )\n    {\n        gst_element_set_state( mpPipeline, GST_STATE_NULL );\n        g_object_unref( G_OBJECT( mpPipeline ) );\n        mpPipeline = NULL;\n    }\n}\n\nFrameGrabber::FrameGrabber( const OUString &rURL ) :\n    FrameGrabber_BASE()\n{\n    gchar *pPipelineStr;\n    pPipelineStr = g_strdup_printf(\n#ifdef AVMEDIA_GST_0_10\n        \"uridecodebin uri=%s ! ffmpegcolorspace ! videoscale ! appsink \"\n        \"name=sink caps=\\\"video\/x-raw-rgb,format=RGB,pixel-aspect-ratio=1\/1,\"\n        \"bpp=(int)24,depth=(int)24,endianness=(int)4321,\"\n        \"red_mask=(int)0xff0000, green_mask=(int)0x00ff00, blue_mask=(int)0x0000ff\\\"\",\n#else\n        \"uridecodebin uri=%s ! videoconvert ! videoscale ! appsink \"\n        \"name=sink caps=\\\"video\/x-raw,format=RGB,pixel-aspect-ratio=1\/1\\\"\",\n#endif\n        rtl::OUStringToOString( rURL, RTL_TEXTENCODING_UTF8 ).getStr() );\n\n    GError *pError = NULL;\n    mpPipeline = gst_parse_launch( pPipelineStr, &pError );\n    if( pError != NULL) {\n        g_warning( \"Failed to construct frame-grabber pipeline '%s'\\n\", pError->message );\n        g_error_free( pError );\n        disposePipeline();\n    }\n\n    if( mpPipeline ) {\n        \/\/ pre-roll\n        switch( gst_element_set_state( mpPipeline, GST_STATE_PAUSED ) ) {\n        case GST_STATE_CHANGE_FAILURE:\n        case GST_STATE_CHANGE_NO_PREROLL:\n            g_warning( \"failure pre-rolling media\" );\n            disposePipeline();\n            break;\n        default:\n            break;\n        }\n    }\n    if( mpPipeline &&\n        gst_element_get_state( mpPipeline, NULL, NULL, 5 * GST_SECOND ) == GST_STATE_CHANGE_FAILURE )\n        disposePipeline();\n}\n\nFrameGrabber::~FrameGrabber()\n{\n    disposePipeline();\n}\n\nFrameGrabber* FrameGrabber::create( const OUString &rURL )\n{\n    return new FrameGrabber( rURL );\n}\n\nuno::Reference< graphic::XGraphic > SAL_CALL FrameGrabber::grabFrame( double fMediaTime )\n    throw (uno::RuntimeException)\n{\n    uno::Reference< graphic::XGraphic > xRet;\n\n    if( !mpPipeline )\n        return xRet;\n\n    gint64 gst_position = llround( fMediaTime * 1E9 );\n    gst_element_seek_simple(\n        mpPipeline, GST_FORMAT_TIME,\n        (GstSeekFlags)(GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_FLUSH),\n        gst_position );\n\n    GstElement *pSink = gst_bin_get_by_name( GST_BIN( mpPipeline ), \"sink\" );\n    if( !pSink )\n        return xRet;\n\n    GstBuffer *pBuf = NULL;\n    GstCaps *pCaps = NULL;\n\n    \/\/ synchronously fetch the frame\n#ifdef AVMEDIA_GST_0_10\n    g_signal_emit_by_name( pSink, \"pull-preroll\", &pBuf, NULL );\n    if( pBuf )\n        pCaps = GST_BUFFER_CAPS( pBuf );\n#else\n    GstSample *pSample = NULL;\n    g_signal_emit_by_name( pSink, \"pull-preroll\", &pSample, NULL );\n\n    if( pSample )\n    {\n        pBuf = gst_sample_get_buffer( pSample );\n        pCaps = gst_sample_get_caps( pSample );\n    }\n#endif\n\n    \/\/ get geometry\n    int nWidth = 0, nHeight = 0;\n    if( !pCaps )\n        g_warning( \"could not get snapshot format\\n\" );\n    else\n    {\n        GstStructure *pStruct = gst_caps_get_structure( pCaps, 0 );\n\n        \/* we need to get the final caps on the buffer to get the size *\/\n        if( !gst_structure_get_int( pStruct, \"width\", &nWidth ) ||\n            !gst_structure_get_int( pStruct, \"height\", &nHeight ) )\n            nWidth = nHeight = 0;\n    }\n\n    if( pBuf && nWidth > 0 && nHeight > 0 &&\n        \/\/ sanity check the size\n#ifdef AVMEDIA_GST_0_10\n        GST_BUFFER_SIZE( pBuf ) >= static_cast( nWidth * nHeight * 3 )\n#else\n        gst_buffer_get_size( pBuf ) >= static_cast( nWidth * nHeight * 3 )\n#endif\n        )\n    {\n        sal_uInt8 *pData = NULL;\n#ifdef AVMEDIA_GST_0_10\n        pData = GST_BUFFER_DATA( pBuf );\n#else\n        GstMapInfo aMapInfo;\n        gst_buffer_map( pBuf, &aMapInfo, GST_MAP_READ );\n        pData = aMapInfo.data;\n#endif\n\n        int nStride = GST_ROUND_UP_4( nWidth * 3 );\n        Bitmap aBmp( Size( nWidth, nHeight ), 24 );\n\n        BitmapWriteAccess *pWrite = aBmp.AcquireWriteAccess();\n        if( pWrite )\n        {\n            \/\/ yet another cheesy pixel copying loop\n            for( int y = 0; y < nHeight; ++y )\n            {\n                sal_uInt8 *p = pData + y * nStride;\n                for( int x = 0; x < nWidth; ++x )\n                {\n                    BitmapColor col( p[0], p[1], p[2] );\n                    pWrite->SetPixel( y, x, col );\n                    p += 3;\n                }\n            }\n        }\n        aBmp.ReleaseAccess( pWrite );\n\n#ifndef AVMEDIA_GST_0_10\n        gst_buffer_unmap( pBuf, &aMapInfo );\n#endif\n\n        xRet = Graphic( aBmp ).GetXGraphic();\n    }\n\n    return xRet;\n}\n\nOUString SAL_CALL FrameGrabber::getImplementationName(  )\n    throw (uno::RuntimeException)\n{\n    return OUString( AVMEDIA_GST_FRAMEGRABBER_IMPLEMENTATIONNAME );\n}\n\nsal_Bool SAL_CALL FrameGrabber::supportsService( const OUString& ServiceName )\n    throw (uno::RuntimeException)\n{\n    return ServiceName == AVMEDIA_GST_FRAMEGRABBER_SERVICENAME;\n}\n\nuno::Sequence< OUString > SAL_CALL FrameGrabber::getSupportedServiceNames()\n    throw (uno::RuntimeException)\n{\n    uno::Sequence< OUString > aRet(1);\n    aRet[0] = AVMEDIA_GST_FRAMEGRABBER_SERVICENAME;\n\n    return aRet;\n}\n\n} \/\/ namespace gstreamer\n} \/\/ namespace avmedia\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"}
{"text":"#include \"Network.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"..\/crypto\/Random.hpp\"\n#include \"..\/util\/Log.hpp\"\n#include \"msgtypes\/ConnectionParam.hpp\"\n\n#include \n\nstruct membuf : std::streambuf {\n  membuf(char* begin, char* end) {\n    setg(begin, begin, end);\n  }\n  membuf(void* begin, void* end) :\n    membuf(reinterpret_cast(begin), reinterpret_cast(end)) {}\n  membuf(const void* begin, const void* end) :\n    membuf(const_cast(begin), const_cast(end)) {}\n};\nclass omsgbuf : public std::streambuf {\nprotected:\n  diggler::net::OutMessage &omsg;\npublic:\n  omsgbuf(diggler::net::OutMessage &o) : omsg(o) {}\nprotected:\n  std::streamsize xsputn(const char_type* s, std::streamsize n) override {\n    omsg.writeData(s, n);\n    return n;\n  }\n  int_type overflow(int_type ch) override {\n    omsg.writeI8(ch);\n    return 1;\n  }\n};\n\nnamespace diggler {\nnamespace net {\n\nusing Util::Log;\nusing namespace Util::Logging::LogLevels;\n\nstatic const char *TAG = \"Network\";\n\nstatic bool InitDone = false;\n\nbool Init() {\n  if (InitDone)\n    return true;\n  InitDone = true;\n  return enet_initialize() == 0;\n}\n\nvoid DeInit() {\n  enet_deinitialize();\n}\n\nstd::string GetNetworkLibVersion() {\n  ENetVersion ver = enet_linked_version();\n  std::ostringstream sstm;\n  sstm << \"ENet linked \" << ENET_VERSION_MAJOR << '.' << ENET_VERSION_MINOR\n    << '.' << ENET_VERSION_PATCH << \", using \" << ENET_VERSION_GET_MAJOR(ver)\n    << '.' << ENET_VERSION_GET_MINOR(ver) << '.' << ENET_VERSION_GET_PATCH(ver);\n  return sstm.str();\n}\n\nstatic enet_uint32 TferToFlags(Tfer mode) {\n  switch (mode) {\n  case Tfer::Rel:\n    return ENET_PACKET_FLAG_RELIABLE;\n  case Tfer::Unseq:\n    return ENET_PACKET_FLAG_UNSEQUENCED;\n  case Tfer::Unrel:\n    break;\n  }\n  return 0;\n}\n\nMessage::Message(MessageType t, uint8 s) :\n  MemoryStream(nullptr, 0),\n  m_type(t),\n  m_subtype(s) {\n}\n\n\nInMessage::InMessage() :\n  Message(MessageType::Null, 0),\n  m_chan(Channels::Base) {\n}\n\nInMessage::~InMessage() {\n  free();\n}\n\nvoid InMessage::setType(MessageType type) {\n  free();\n  m_type = type;\n  m_subtype = m_length = m_cursor = 0;\n  m_data = nullptr;\n}\n\nvoid InMessage::fromData(const void *data, SizeT len, Channels chan) {\n  if (len < HeaderSize) {\n    throw std::invalid_argument(\"Message length is smaller than message header\");\n  }\n  const uint8 *const bytes = static_cast(data);\n  free();\n  m_chan = chan;\n  m_cursor = 0;\n  m_length = len - HeaderSize;\n  m_type = static_cast(bytes[0]);\n  m_subtype = bytes[1];\n  \/\/ m_data\/bytes is guaranteed never to be written to, so we can const_cast it\n  m_data = const_cast(bytes) + HeaderSize;\n}\n\nvoid InMessage::free() {\n  if (m_data != nullptr) {\n    delete[] (m_data - HeaderSize);\n  }\n  m_type = MessageType::Null;\n  m_subtype = m_length = m_cursor = 0;\n  m_data = nullptr;\n}\n\nvoid InMessage::readMsgpack(meiose::variant &var) {\n  uint32 len = readU32();\n  if (len > remaining()) {\n    throw std::runtime_error(\"Not enough bytes available for reported msgpack length\");\n  }\n  const void *start = getCursorPtr(len);\n  membuf sbuf(start, getCursorPtr());\n  std::istream in(&sbuf);\n  meiose::msgpack::read(in, var);\n}\n\n\nChannels InMessage::getChannel() const {\n  return m_chan;\n}\n\n\nOutMessage::OutMessage(MessageType t, uint8 subtype) :\n  Message(t, subtype),\n  m_actualData(nullptr) {\n}\n\nOutMessage::~OutMessage() {\n  std::free(m_actualData);\n  m_data = nullptr;\n}\n\nconst static int OutMessage_AllocStep = 1024;\nvoid OutMessage::fit(SizeT len) {\n  if (len <= m_allocated)\n    return;\n  SizeT targetSize = ((len + OutMessage_AllocStep - 1) \/\n    OutMessage_AllocStep)*OutMessage_AllocStep; \/\/ Round up\n  using DataT = decltype(m_actualData);\n  DataT newActualData = static_cast(\n    std::realloc(m_actualData, HeaderSize + targetSize));\n  if (newActualData == nullptr)\n    throw std::bad_alloc();\n  m_actualData = newActualData;\n  m_data = newActualData + HeaderSize;\n  m_allocated = targetSize;\n}\n\nvoid OutMessage::writeMsgpack(const meiose::variant &var) {\n  PosT pos = tell();\n  writeU32(0);\n  omsgbuf sbuf(*this);\n  std::ostream out(&sbuf);\n  meiose::msgpack::write(out, var);\n  PosT posWritten = tell();\n  seek(pos);\n  writeU32(static_cast(posWritten - (pos + sizeof(uint32))));\n  seek(posWritten);\n}\n\n\nglm::vec3 InMessage::readVec3() {\n  float x, y, z;\n  x = readFloat();\n  y = readFloat();\n  z = readFloat();\n  return glm::vec3(x, y, z);\n}\n\nglm::ivec3 InMessage::readIVec3() {\n  int32 x, y, z;\n  x = readI32();\n  y = readI32();\n  z = readI32();\n  return glm::ivec3(x, y, z);\n}\n\n\nPeer::Peer(Host &host, void *peer) :\n  host(host),\n  peer(peer) {\n  reinterpret_cast(this->peer)->data = this;\n  Crypto::Random::randomData(connectionPk);\n  Crypto::DiffieHellman::scalarmultBase(connectionSk, connectionPk);\n}\n\nbool Peer::operator==(const Peer &other) const {\n  return peer == other.peer;\n}\n\nbool Peer::operator!=(const Peer &other) const {\n  return !(*this == other);\n}\n\nvoid Peer::disconnect(uint32 data) {\n  ENetPeer *const peer = reinterpret_cast(this->peer);\n  enet_peer_disconnect(peer, data);\n}\n\nstd::string Peer::peerHost() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  std::ostringstream oss;\n  char *chars = new char[512];\n  enet_address_get_host_ip(&peer->host->address, chars, 512);\n  oss << chars;\n  delete[] chars;\n  oss << ':' << peer->host->address.port;\n  return oss.str();\n}\n\nstd::string Peer::peerIP() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  char *chars = new char[512];\n  enet_address_get_host_ip(&peer->host->address, chars, 512);\n  std::string str(chars);\n  delete[] chars;\n  return str;\n}\n\nPort Peer::peerPort() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  return peer->host->address.port;\n}\n\n\n\nHost::Host() :\n  host(nullptr),\n  rxBytes(0),\n  txBytes(0) {\n}\n\nHost::~Host() {\n  ENetHost *const host = reinterpret_cast(this->host);\n  enet_host_destroy(host);\n}\n\nvoid Host::create(Port port, uint maxconn) {\n  if (port == 0) { \/\/ Client\n    host = enet_host_create(nullptr, 1, static_cast(Channels::MAX), 0, 0);\n  } else { \/\/ Server\n    ENetAddress address;\n    address.host = IN6ADDR_ANY_INIT; \/\/ ENET_HOST_ANY;\n    address.port = port;\n    host = enet_host_create(&address, maxconn, static_cast(Channels::MAX), 0, 0);\n  }\n  if (host == nullptr) {\n    throw Exception();\n  }\n}\n\nPeer& Host::connect(const std::string &hostAddr, Port port, Timeout timeout) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  ENetAddress address;\n  ENetEvent event;\n  ENetPeer *peer;\n\n  enet_address_set_host(&address, hostAddr.c_str());\n  address.port = port;\n\n  peer = enet_host_connect(host, &address, static_cast(Channels::MAX), 0);\n  if (peer == nullptr) {\n    throw Exception();\n  }\n\n  if (enet_host_service(host, &event, timeout) > 0 &&\n    event.type == ENET_EVENT_TYPE_CONNECT) {\n    Peer *p = new Peer(*this, peer);\n    sendKeyExchange(*p);\n    return *p;\n  }\n\n  enet_peer_reset(peer);\n  throw Exception();\n}\n\nvoid Host::processPeersToDelete() {\n  for (Peer *peer : m_peersToDelete) {\n    delete peer;\n  }\n  m_peersToDelete.clear();\n}\n\nvoid Host::sendKeyExchange(Peer &p) {\n  MsgTypes::ConnectionParamDHKeyExchange dhke;\n  dhke.pk = p.connectionPk;\n  OutMessage keMsg;\n  dhke.writeToMsg(keMsg);\n  send(p, keMsg);\n}\n\n\/*static void hexDump(char in, uint8 *buf, int len) {\n  std::cout << in << \": \" << std::setiosflags(std::ios::internal);\n  for (int i=0; i < len; ++i) {\n    std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)buf[i] << ' ';\n  }\n  std::cout << std::dec << std::endl;\n}*\/\n\nbool Host::recv(InMessage &msg, Peer **peer, Timeout timeout) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  processPeersToDelete();\n  auto start = std::chrono::steady_clock::now();\n\n  ENetEvent event;\n  while (true) {\n    auto now = std::chrono::steady_clock::now();\n    enet_uint32 elapsed = static_cast(\n      std::chrono::duration_cast(now - start).count());\n    if (enet_host_service(host, &event, timeout - elapsed) > 0) {\n      Peer *peerPtr = event.peer == nullptr ? nullptr :\n        reinterpret_cast(event.peer->data);\n      switch (event.type) {\n      case ENET_EVENT_TYPE_NONE:\n        break;\n      case ENET_EVENT_TYPE_CONNECT:\n        peerPtr = new Peer(*this, event.peer);\n        *peer = peerPtr;\n        sendKeyExchange(*peerPtr);\n        msg.setType(MessageType::NetConnect);\n        return true;\n      case ENET_EVENT_TYPE_RECEIVE: {\n        if (peer) {\n          *peer = peerPtr;\n        }\n\n        const Message::SizeT pktLen = event.packet->dataLength;\n        const Channels pktChannel = static_cast(event.channelID);\n        const bool decrypt = (pktChannel == Channels::ConnectionMetaPlain);\n        byte *rcvData = new uint8[pktLen];\n        if (decrypt) {\n          \/\/ TODO: decryption\n          std::memcpy(rcvData, event.packet->data, pktLen);\n        } else {\n          std::memcpy(rcvData, event.packet->data, pktLen);\n        }\n        \/\/ pktData's ownership is transferred to msg\n        msg.fromData(rcvData, pktLen, pktChannel);\n        rxBytes += event.packet->dataLength;\n\n        using CPS = MsgTypes::ConnectionParamSubtype;\n        if (msg.getType() == MessageType::ConnectionParam &&\n            msg.getSubtype() == CPS::DHKeyExchange) {\n          MsgTypes::ConnectionParamDHKeyExchange dhke; dhke.readFromMsg(msg);\n          peerPtr->remotePk = dhke.pk;\n          if (Crypto::DiffieHellman::scalarmult(peerPtr->connectionSk, peerPtr->remotePk,\n            peerPtr->sharedSecret) != 0) {\n            \/\/ TODO: properly handle key exchange failure\n            throw std::runtime_error(\"DH key exchange failed\");\n          }\n          Log(Debug, TAG) << \"hello DH! \" << peerPtr->sharedSecret.hex();\n        } else {\n          return true;\n        }\n      } break;\n      case ENET_EVENT_TYPE_DISCONNECT:\n        if (peer) {\n          *peer = peerPtr;\n        }\n        msg.setType(MessageType::NetDisconnect);\n        m_peersToDelete.emplace_back(peerPtr);\n        return true;\n      }\n    } else {\n      return false;\n    }\n  }\n  throw Exception();\n}\n\nvoid Host::send(Peer &peer, const OutMessage &msg, Tfer mode, Channels chan) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  const bool encrypt = (chan == Channels::ConnectionMetaPlain);\n\n  const byte header[Message::HeaderSize] = {\n    static_cast(msg.m_type),\n    msg.m_subtype\n  };\n\n  size_t pktLen = Message::HeaderSize + (msg.m_actualData == nullptr ? 0 : msg.m_length);\n  ENetPacket *packet = enet_packet_create(nullptr, pktLen, TferToFlags(mode));\n  byte *pktData = packet->data;\n  txBytes += pktLen;\n  if (msg.m_actualData != nullptr) {\n    std::memcpy(msg.m_actualData, header, Message::HeaderSize);\n    if (encrypt) {\n      \/\/ TODO: don't memcpy, encrypt!\n      std::memcpy(pktData, msg.m_actualData, pktLen);\n    } else {\n      std::memcpy(pktData, msg.m_actualData, pktLen);\n    }\n  } else {\n    if (encrypt) {\n      \/\/ TODO: don't memcpy, encrypt!\n      std::memcpy(pktData, header, pktLen);\n    } else {\n      std::memcpy(pktData, header, pktLen);\n    }\n  }\n\n  \/\/hexDump('S', pktData, pktLen);\n  enet_peer_send(reinterpret_cast(peer.peer), static_cast(chan), packet);\n  enet_host_flush(host);\n}\n\n}\n}\nHost::create: specify IPv6 scope ID (0)#include \"Network.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"..\/crypto\/Random.hpp\"\n#include \"..\/util\/Log.hpp\"\n#include \"msgtypes\/ConnectionParam.hpp\"\n\n#include \n\nstruct membuf : std::streambuf {\n  membuf(char* begin, char* end) {\n    setg(begin, begin, end);\n  }\n  membuf(void* begin, void* end) :\n    membuf(reinterpret_cast(begin), reinterpret_cast(end)) {}\n  membuf(const void* begin, const void* end) :\n    membuf(const_cast(begin), const_cast(end)) {}\n};\nclass omsgbuf : public std::streambuf {\nprotected:\n  diggler::net::OutMessage &omsg;\npublic:\n  omsgbuf(diggler::net::OutMessage &o) : omsg(o) {}\nprotected:\n  std::streamsize xsputn(const char_type* s, std::streamsize n) override {\n    omsg.writeData(s, n);\n    return n;\n  }\n  int_type overflow(int_type ch) override {\n    omsg.writeI8(ch);\n    return 1;\n  }\n};\n\nnamespace diggler {\nnamespace net {\n\nusing Util::Log;\nusing namespace Util::Logging::LogLevels;\n\nstatic const char *TAG = \"Network\";\n\nstatic bool InitDone = false;\n\nbool Init() {\n  if (InitDone)\n    return true;\n  InitDone = true;\n  return enet_initialize() == 0;\n}\n\nvoid DeInit() {\n  enet_deinitialize();\n}\n\nstd::string GetNetworkLibVersion() {\n  ENetVersion ver = enet_linked_version();\n  std::ostringstream sstm;\n  sstm << \"ENet linked \" << ENET_VERSION_MAJOR << '.' << ENET_VERSION_MINOR\n    << '.' << ENET_VERSION_PATCH << \", using \" << ENET_VERSION_GET_MAJOR(ver)\n    << '.' << ENET_VERSION_GET_MINOR(ver) << '.' << ENET_VERSION_GET_PATCH(ver);\n  return sstm.str();\n}\n\nstatic enet_uint32 TferToFlags(Tfer mode) {\n  switch (mode) {\n  case Tfer::Rel:\n    return ENET_PACKET_FLAG_RELIABLE;\n  case Tfer::Unseq:\n    return ENET_PACKET_FLAG_UNSEQUENCED;\n  case Tfer::Unrel:\n    break;\n  }\n  return 0;\n}\n\nMessage::Message(MessageType t, uint8 s) :\n  MemoryStream(nullptr, 0),\n  m_type(t),\n  m_subtype(s) {\n}\n\n\nInMessage::InMessage() :\n  Message(MessageType::Null, 0),\n  m_chan(Channels::Base) {\n}\n\nInMessage::~InMessage() {\n  free();\n}\n\nvoid InMessage::setType(MessageType type) {\n  free();\n  m_type = type;\n  m_subtype = m_length = m_cursor = 0;\n  m_data = nullptr;\n}\n\nvoid InMessage::fromData(const void *data, SizeT len, Channels chan) {\n  if (len < HeaderSize) {\n    throw std::invalid_argument(\"Message length is smaller than message header\");\n  }\n  const uint8 *const bytes = static_cast(data);\n  free();\n  m_chan = chan;\n  m_cursor = 0;\n  m_length = len - HeaderSize;\n  m_type = static_cast(bytes[0]);\n  m_subtype = bytes[1];\n  \/\/ m_data\/bytes is guaranteed never to be written to, so we can const_cast it\n  m_data = const_cast(bytes) + HeaderSize;\n}\n\nvoid InMessage::free() {\n  if (m_data != nullptr) {\n    delete[] (m_data - HeaderSize);\n  }\n  m_type = MessageType::Null;\n  m_subtype = m_length = m_cursor = 0;\n  m_data = nullptr;\n}\n\nvoid InMessage::readMsgpack(meiose::variant &var) {\n  uint32 len = readU32();\n  if (len > remaining()) {\n    throw std::runtime_error(\"Not enough bytes available for reported msgpack length\");\n  }\n  const void *start = getCursorPtr(len);\n  membuf sbuf(start, getCursorPtr());\n  std::istream in(&sbuf);\n  meiose::msgpack::read(in, var);\n}\n\n\nChannels InMessage::getChannel() const {\n  return m_chan;\n}\n\n\nOutMessage::OutMessage(MessageType t, uint8 subtype) :\n  Message(t, subtype),\n  m_actualData(nullptr) {\n}\n\nOutMessage::~OutMessage() {\n  std::free(m_actualData);\n  m_data = nullptr;\n}\n\nconst static int OutMessage_AllocStep = 1024;\nvoid OutMessage::fit(SizeT len) {\n  if (len <= m_allocated)\n    return;\n  SizeT targetSize = ((len + OutMessage_AllocStep - 1) \/\n    OutMessage_AllocStep)*OutMessage_AllocStep; \/\/ Round up\n  using DataT = decltype(m_actualData);\n  DataT newActualData = static_cast(\n    std::realloc(m_actualData, HeaderSize + targetSize));\n  if (newActualData == nullptr)\n    throw std::bad_alloc();\n  m_actualData = newActualData;\n  m_data = newActualData + HeaderSize;\n  m_allocated = targetSize;\n}\n\nvoid OutMessage::writeMsgpack(const meiose::variant &var) {\n  PosT pos = tell();\n  writeU32(0);\n  omsgbuf sbuf(*this);\n  std::ostream out(&sbuf);\n  meiose::msgpack::write(out, var);\n  PosT posWritten = tell();\n  seek(pos);\n  writeU32(static_cast(posWritten - (pos + sizeof(uint32))));\n  seek(posWritten);\n}\n\n\nglm::vec3 InMessage::readVec3() {\n  float x, y, z;\n  x = readFloat();\n  y = readFloat();\n  z = readFloat();\n  return glm::vec3(x, y, z);\n}\n\nglm::ivec3 InMessage::readIVec3() {\n  int32 x, y, z;\n  x = readI32();\n  y = readI32();\n  z = readI32();\n  return glm::ivec3(x, y, z);\n}\n\n\nPeer::Peer(Host &host, void *peer) :\n  host(host),\n  peer(peer) {\n  reinterpret_cast(this->peer)->data = this;\n  Crypto::Random::randomData(connectionPk);\n  Crypto::DiffieHellman::scalarmultBase(connectionSk, connectionPk);\n}\n\nbool Peer::operator==(const Peer &other) const {\n  return peer == other.peer;\n}\n\nbool Peer::operator!=(const Peer &other) const {\n  return !(*this == other);\n}\n\nvoid Peer::disconnect(uint32 data) {\n  ENetPeer *const peer = reinterpret_cast(this->peer);\n  enet_peer_disconnect(peer, data);\n}\n\nstd::string Peer::peerHost() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  std::ostringstream oss;\n  char *chars = new char[512];\n  enet_address_get_host_ip(&peer->host->address, chars, 512);\n  oss << chars;\n  delete[] chars;\n  oss << ':' << peer->host->address.port;\n  return oss.str();\n}\n\nstd::string Peer::peerIP() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  char *chars = new char[512];\n  enet_address_get_host_ip(&peer->host->address, chars, 512);\n  std::string str(chars);\n  delete[] chars;\n  return str;\n}\n\nPort Peer::peerPort() {\n  const ENetPeer *const peer = reinterpret_cast(this->peer);\n  return peer->host->address.port;\n}\n\n\n\nHost::Host() :\n  host(nullptr),\n  rxBytes(0),\n  txBytes(0) {\n}\n\nHost::~Host() {\n  ENetHost *const host = reinterpret_cast(this->host);\n  enet_host_destroy(host);\n}\n\nvoid Host::create(Port port, uint maxconn) {\n  if (port == 0) { \/\/ Client\n    host = enet_host_create(nullptr, 1, static_cast(Channels::MAX), 0, 0);\n  } else { \/\/ Server\n    ENetAddress address;\n    address.host = in6addr_any;\n    address.sin6_scope_id = 0;\n    address.port = port;\n    host = enet_host_create(&address, maxconn, static_cast(Channels::MAX), 0, 0);\n  }\n  if (host == nullptr) {\n    throw Exception();\n  }\n}\n\nPeer& Host::connect(const std::string &hostAddr, Port port, Timeout timeout) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  ENetAddress address;\n  ENetEvent event;\n  ENetPeer *peer;\n\n  enet_address_set_host(&address, hostAddr.c_str());\n  address.port = port;\n\n  peer = enet_host_connect(host, &address, static_cast(Channels::MAX), 0);\n  if (peer == nullptr) {\n    throw Exception();\n  }\n\n  if (enet_host_service(host, &event, timeout) > 0 &&\n    event.type == ENET_EVENT_TYPE_CONNECT) {\n    Peer *p = new Peer(*this, peer);\n    sendKeyExchange(*p);\n    return *p;\n  }\n\n  enet_peer_reset(peer);\n  throw Exception();\n}\n\nvoid Host::processPeersToDelete() {\n  for (Peer *peer : m_peersToDelete) {\n    delete peer;\n  }\n  m_peersToDelete.clear();\n}\n\nvoid Host::sendKeyExchange(Peer &p) {\n  MsgTypes::ConnectionParamDHKeyExchange dhke;\n  dhke.pk = p.connectionPk;\n  OutMessage keMsg;\n  dhke.writeToMsg(keMsg);\n  send(p, keMsg);\n}\n\n\/*static void hexDump(char in, uint8 *buf, int len) {\n  std::cout << in << \": \" << std::setiosflags(std::ios::internal);\n  for (int i=0; i < len; ++i) {\n    std::cout << std::setfill('0') << std::setw(2) << std::hex << (int)buf[i] << ' ';\n  }\n  std::cout << std::dec << std::endl;\n}*\/\n\nbool Host::recv(InMessage &msg, Peer **peer, Timeout timeout) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  processPeersToDelete();\n  auto start = std::chrono::steady_clock::now();\n\n  ENetEvent event;\n  while (true) {\n    auto now = std::chrono::steady_clock::now();\n    enet_uint32 elapsed = static_cast(\n      std::chrono::duration_cast(now - start).count());\n    if (enet_host_service(host, &event, timeout - elapsed) > 0) {\n      Peer *peerPtr = event.peer == nullptr ? nullptr :\n        reinterpret_cast(event.peer->data);\n      switch (event.type) {\n      case ENET_EVENT_TYPE_NONE:\n        break;\n      case ENET_EVENT_TYPE_CONNECT:\n        peerPtr = new Peer(*this, event.peer);\n        *peer = peerPtr;\n        sendKeyExchange(*peerPtr);\n        msg.setType(MessageType::NetConnect);\n        return true;\n      case ENET_EVENT_TYPE_RECEIVE: {\n        if (peer) {\n          *peer = peerPtr;\n        }\n\n        const Message::SizeT pktLen = event.packet->dataLength;\n        const Channels pktChannel = static_cast(event.channelID);\n        const bool decrypt = (pktChannel == Channels::ConnectionMetaPlain);\n        byte *rcvData = new uint8[pktLen];\n        if (decrypt) {\n          \/\/ TODO: decryption\n          std::memcpy(rcvData, event.packet->data, pktLen);\n        } else {\n          std::memcpy(rcvData, event.packet->data, pktLen);\n        }\n        \/\/ pktData's ownership is transferred to msg\n        msg.fromData(rcvData, pktLen, pktChannel);\n        rxBytes += event.packet->dataLength;\n\n        using CPS = MsgTypes::ConnectionParamSubtype;\n        if (msg.getType() == MessageType::ConnectionParam &&\n            msg.getSubtype() == CPS::DHKeyExchange) {\n          MsgTypes::ConnectionParamDHKeyExchange dhke; dhke.readFromMsg(msg);\n          peerPtr->remotePk = dhke.pk;\n          if (Crypto::DiffieHellman::scalarmult(peerPtr->connectionSk, peerPtr->remotePk,\n            peerPtr->sharedSecret) != 0) {\n            \/\/ TODO: properly handle key exchange failure\n            throw std::runtime_error(\"DH key exchange failed\");\n          }\n          Log(Debug, TAG) << \"hello DH! \" << peerPtr->sharedSecret.hex();\n        } else {\n          return true;\n        }\n      } break;\n      case ENET_EVENT_TYPE_DISCONNECT:\n        if (peer) {\n          *peer = peerPtr;\n        }\n        msg.setType(MessageType::NetDisconnect);\n        m_peersToDelete.emplace_back(peerPtr);\n        return true;\n      }\n    } else {\n      return false;\n    }\n  }\n  throw Exception();\n}\n\nvoid Host::send(Peer &peer, const OutMessage &msg, Tfer mode, Channels chan) {\n  ENetHost *const host = reinterpret_cast(this->host);\n  const bool encrypt = (chan == Channels::ConnectionMetaPlain);\n\n  const byte header[Message::HeaderSize] = {\n    static_cast(msg.m_type),\n    msg.m_subtype\n  };\n\n  size_t pktLen = Message::HeaderSize + (msg.m_actualData == nullptr ? 0 : msg.m_length);\n  ENetPacket *packet = enet_packet_create(nullptr, pktLen, TferToFlags(mode));\n  byte *pktData = packet->data;\n  txBytes += pktLen;\n  if (msg.m_actualData != nullptr) {\n    std::memcpy(msg.m_actualData, header, Message::HeaderSize);\n    if (encrypt) {\n      \/\/ TODO: don't memcpy, encrypt!\n      std::memcpy(pktData, msg.m_actualData, pktLen);\n    } else {\n      std::memcpy(pktData, msg.m_actualData, pktLen);\n    }\n  } else {\n    if (encrypt) {\n      \/\/ TODO: don't memcpy, encrypt!\n      std::memcpy(pktData, header, pktLen);\n    } else {\n      std::memcpy(pktData, header, pktLen);\n    }\n  }\n\n  \/\/hexDump('S', pktData, pktLen);\n  enet_peer_send(reinterpret_cast(peer.peer), static_cast(chan), packet);\n  enet_host_flush(host);\n}\n\n}\n}\n<|endoftext|>"}
{"text":"#include \"EclipseSourceCodeAccessPrivatePCH.h\"\n#include \"EclipseSourceCodeAccessor.h\"\n#include \"ModuleManager.h\"\n#include \"DesktopPlatformModule.h\"\n\n#if WITH_EDITOR\n#include \"Developer\/HotReload\/Public\/IHotReload.h\"\n#endif\n\nDEFINE_LOG_CATEGORY_STATIC(LogEclipseAccessor, Log, All);\n\n#define LOCTEXT_NAMESPACE \"EclipseSourceCodeAccessor\"\n\n\/\/ http:\/\/help.eclipse.org\/juno\/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html\n\nbool FEclipseSourceCodeAccessor::CanAccessSourceCode() const\n{\n\treturn true;\n}\n\nFName FEclipseSourceCodeAccessor::GetFName() const\n{\n\treturn FName(\"EclipseSourceCodeAccessor\");\n}\n\nFText FEclipseSourceCodeAccessor::GetNameText() const\n{\n\treturn LOCTEXT(\"EclipseDisplayName\", \"Eclipse\");\n}\n\nFText FEclipseSourceCodeAccessor::GetDescriptionText() const\n{\n\treturn LOCTEXT(\"EclipseDisplayDesc\", \"Open source code files with Eclipse\");\n}\n\nbool FEclipseSourceCodeAccessor::OpenSolution()\n{\n\tFString Filename = FPaths::GetBaseFilename(GetSolutionPath()) + \".cproject\";\n\tFString Directory = FPaths::GetPath(GetSolutionPath());\n\tFString Solution = \"\\\"\" + Directory + \"\/\" + Filename + \"\\\"\";\n\tFString EclipsePath;\n\tif (!CanRunEclipse(EclipsePath))\n\t{\n\t\treturn false;\n\t}\n\n\tUE_LOG(LogEclipseAccessor, Warning, TEXT(\"FEclipseSourceCodeAccessor::OpenSolution: %s %s\"), *EclipsePath, *Solution);\n\n\tFProcHandle Proc = FPlatformProcess::CreateProc(*EclipsePath, *Solution, true, false, false, nullptr, 0, nullptr, nullptr);\n\tif(Proc.IsValid())\n\t{\n\t\tFPlatformProcess::CloseProc(Proc);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::OpenFileAtLine(const FString& FullPath, int32 LineNumber, int32 ColumnNumber)\n{\n\tconst FString FileWithLine = FString::Printf(TEXT(\"%s:%i \"), *FullPath, LineNumber);\n\tTArray Files(FileWithLine);\n\treturn OpensourceFiles(Files);\n}\n\nbool FEclipseSourceCodeAccessor::OpenSourceFiles(const TArray& AbsoluteSourcePaths)\n{\n\tFString EclipsePath;\n\tif (!CanRunEclipse(EclipsePath))\n\t{\n\t\treturn false;\n\t}\n\tFString Args = FString(TEXT(\"--launcher.timeout 60 --launcher.openFile \"));\n\tfor (const FString& SourcePath : AbsoluteSourcePaths)\n\t{\n\t\tconst FString NewSourcePath = FString::Printf(TEXT(\"\\\"%s\\\" \"), *SourcePath);\n\t\tArgs.Append(NewSourcePath);\n\t}\n\tFProcHandle Proc = FPlatformProcess::CreateProc(*EclipsePath, *Solution, true, false, false, nullptr, 0, nullptr, nullptr);\n\tif(Proc.IsValid())\n\t{\n\t\tFPlatformProcess::CloseProc(Proc);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::AddSourceFiles(const TArray& AbsoluteSourcePaths, const TArray& AvailableModules)\n{\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::SaveAllOpenDocuments() const\n{\n\treturn false;\n}\n\nvoid FEclipseSourceCodeAccessor::Tick(const float DeltaTime)\n{\n}\n\nvoid FEclispeSourceCodeAccessor::CanRunEclipse(FString& OutPath) const\n{\n\t\/\/ TODO This might be not a good idea to find an executable.\n\tOutPath = TEXT(\"\/usr\/bin\/eclipse\");\n\tif (!FPaths::FileExists(OutPath))\n\t{\n\t\tTCHAR EclipseBinaryEnv[32768] = { 0 };\n\t\tFPlatformMisc::GetEnvironmentVariable(TEXT(\"UE4_ECLIPSE_BINARY\"), EclipseBinaryEnv, ARRAY_COUNT(EclipseBinaryEnv));\n\t\tOutPath = EclipseBinaryEnv;\n\n\t\tif (!FPaths::FileExists(OutPath))\n\t\t{\n\t\t\tUE_LOG(LogEclipseAccessor, Warning, TEXT(\"FEclipseSourceCodeAccessor: Can not find eclipse binary - export UE4_ECLIPSE_BINARY environment variable\"));\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nFString FEclipseSourceCodeAccessor::GetSolutionPath() const\n{\n\tif (IsInGameThread())\n\t{\n\t\tFString SolutionPath;\n\t\tif (FDesktopPlatformModule::Get()->GetSolutionPath(SolutionPath))\n\t\t{\n\t\t\tCachedSolutionPath = FPaths::ConvertRelativePathToFull(SolutionPath);\n\t\t}\n\t}\n\treturn CachedSolutionPath;\n}\n\nvoid FEclipseSourceCodeAccessor::Startup()\n{\n\t\/\/ Cache this so we don't have to do it on a background thread\n\tGetSolutionPath();\n}\n\nvoid FEclipseSourceCodeAccessor::Shutdown()\n{\n}\nfixed TArray usage#include \"EclipseSourceCodeAccessPrivatePCH.h\"\n#include \"EclipseSourceCodeAccessor.h\"\n#include \"ModuleManager.h\"\n#include \"DesktopPlatformModule.h\"\n\n#if WITH_EDITOR\n#include \"Developer\/HotReload\/Public\/IHotReload.h\"\n#endif\n\nDEFINE_LOG_CATEGORY_STATIC(LogEclipseAccessor, Log, All);\n\n#define LOCTEXT_NAMESPACE \"EclipseSourceCodeAccessor\"\n\n\/\/ http:\/\/help.eclipse.org\/juno\/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html\n\nbool FEclipseSourceCodeAccessor::CanAccessSourceCode() const\n{\n\treturn true;\n}\n\nFName FEclipseSourceCodeAccessor::GetFName() const\n{\n\treturn FName(\"EclipseSourceCodeAccessor\");\n}\n\nFText FEclipseSourceCodeAccessor::GetNameText() const\n{\n\treturn LOCTEXT(\"EclipseDisplayName\", \"Eclipse\");\n}\n\nFText FEclipseSourceCodeAccessor::GetDescriptionText() const\n{\n\treturn LOCTEXT(\"EclipseDisplayDesc\", \"Open source code files with Eclipse\");\n}\n\nbool FEclipseSourceCodeAccessor::OpenSolution()\n{\n\tFString Filename = FPaths::GetBaseFilename(GetSolutionPath()) + \".cproject\";\n\tFString Directory = FPaths::GetPath(GetSolutionPath());\n\tFString Solution = \"\\\"\" + Directory + \"\/\" + Filename + \"\\\"\";\n\tFString EclipsePath;\n\tif (!CanRunEclipse(EclipsePath))\n\t{\n\t\treturn false;\n\t}\n\n\tUE_LOG(LogEclipseAccessor, Warning, TEXT(\"FEclipseSourceCodeAccessor::OpenSolution: %s %s\"), *EclipsePath, *Solution);\n\n\tFProcHandle Proc = FPlatformProcess::CreateProc(*EclipsePath, *Solution, true, false, false, nullptr, 0, nullptr, nullptr);\n\tif(Proc.IsValid())\n\t{\n\t\tFPlatformProcess::CloseProc(Proc);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::OpenFileAtLine(const FString& FullPath, int32 LineNumber, int32 ColumnNumber)\n{\n\tTArray Files;\n\tFiles.Emplace(FString::Printf(TEXT(\"%s:%i \"), *FullPath, LineNumber));\n\treturn OpensourceFiles(Files);\n}\n\nbool FEclipseSourceCodeAccessor::OpenSourceFiles(const TArray& AbsoluteSourcePaths)\n{\n\tFString EclipsePath;\n\tif (!CanRunEclipse(EclipsePath))\n\t{\n\t\treturn false;\n\t}\n\tFString Args = FString(TEXT(\"--launcher.timeout 60 --launcher.openFile \"));\n\tfor (const FString& SourcePath : AbsoluteSourcePaths)\n\t{\n\t\tconst FString NewSourcePath = FString::Printf(TEXT(\"\\\"%s\\\" \"), *SourcePath);\n\t\tArgs.Append(NewSourcePath);\n\t}\n\tFProcHandle Proc = FPlatformProcess::CreateProc(*EclipsePath, *Solution, true, false, false, nullptr, 0, nullptr, nullptr);\n\tif(Proc.IsValid())\n\t{\n\t\tFPlatformProcess::CloseProc(Proc);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::AddSourceFiles(const TArray& AbsoluteSourcePaths, const TArray& AvailableModules)\n{\n\treturn false;\n}\n\nbool FEclipseSourceCodeAccessor::SaveAllOpenDocuments() const\n{\n\treturn false;\n}\n\nvoid FEclipseSourceCodeAccessor::Tick(const float DeltaTime)\n{\n}\n\nvoid FEclispeSourceCodeAccessor::CanRunEclipse(FString& OutPath) const\n{\n\t\/\/ TODO This might be not a good idea to find an executable.\n\tOutPath = TEXT(\"\/usr\/bin\/eclipse\");\n\tif (!FPaths::FileExists(OutPath))\n\t{\n\t\tTCHAR EclipseBinaryEnv[32768] = { 0 };\n\t\tFPlatformMisc::GetEnvironmentVariable(TEXT(\"UE4_ECLIPSE_BINARY\"), EclipseBinaryEnv, ARRAY_COUNT(EclipseBinaryEnv));\n\t\tOutPath = EclipseBinaryEnv;\n\n\t\tif (!FPaths::FileExists(OutPath))\n\t\t{\n\t\t\tUE_LOG(LogEclipseAccessor, Warning, TEXT(\"FEclipseSourceCodeAccessor: Can not find eclipse binary - export UE4_ECLIPSE_BINARY environment variable\"));\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nFString FEclipseSourceCodeAccessor::GetSolutionPath() const\n{\n\tif (IsInGameThread())\n\t{\n\t\tFString SolutionPath;\n\t\tif (FDesktopPlatformModule::Get()->GetSolutionPath(SolutionPath))\n\t\t{\n\t\t\tCachedSolutionPath = FPaths::ConvertRelativePathToFull(SolutionPath);\n\t\t}\n\t}\n\treturn CachedSolutionPath;\n}\n\nvoid FEclipseSourceCodeAccessor::Startup()\n{\n\t\/\/ Cache this so we don't have to do it on a background thread\n\tGetSolutionPath();\n}\n\nvoid FEclipseSourceCodeAccessor::Shutdown()\n{\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n\n#include \"di\/Injectable.h\"\n#include \"gws\/DevicePairHandler.h\"\n#include \"gws\/DeviceUnpairHandler.h\"\n#include \"model\/Device.h\"\n#include \"model\/Gateway.h\"\n#include \"service\/DeviceServiceImpl.h\"\n\nBEEEON_OBJECT_BEGIN(BeeeOn, DeviceServiceImpl)\nBEEEON_OBJECT_CASTABLE(DeviceService)\nBEEEON_OBJECT_REF(\"deviceDao\", &DeviceServiceImpl::setDeviceDao)\nBEEEON_OBJECT_REF(\"sensorHistoryDao\", &DeviceServiceImpl::setSensorHistoryDao)\nBEEEON_OBJECT_REF(\"devicePropertyDao\", &DeviceServiceImpl::setDevicePropertyDao)\nBEEEON_OBJECT_REF(\"gatewayRPC\", &DeviceServiceImpl::setGatewayRPC)\nBEEEON_OBJECT_REF(\"accessPolicy\", &DeviceServiceImpl::setAccessPolicy)\nBEEEON_OBJECT_REF(\"transactionManager\", &DeviceServiceImpl::setTransactionManager)\nBEEEON_OBJECT_END(BeeeOn, DeviceServiceImpl)\n\nusing namespace std;\nusing namespace Poco;\nusing namespace BeeeOn;\n\nDeviceServiceImpl::DeviceServiceImpl()\n{\n}\n\nvoid DeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)\n{\n\tm_dao = dao;\n}\n\nvoid DeviceServiceImpl::setSensorHistoryDao(SensorHistoryDao::Ptr dao)\n{\n\tm_historyDao = dao;\n}\n\nvoid DeviceServiceImpl::setDevicePropertyDao(DevicePropertyDao::Ptr dao)\n{\n\tm_propertyDao = dao;\n}\n\nvoid DeviceServiceImpl::setGatewayRPC(GatewayRPC::Ptr rpc)\n{\n\tm_gatewayRPC = rpc;\n}\n\nvoid DeviceServiceImpl::setAccessPolicy(DeviceAccessPolicy::Ptr policy)\n{\n\tm_policy = policy;\n}\n\nbool DeviceServiceImpl::doFetch(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.target(), input.base());\n\treturn m_dao->fetch(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::valuesFor(DeviceWithData &device)\n{\n\t\/\/ fetch last value of all device modules\n\tvector modules;\n\n\tfor (const auto &info : *device.type())\n\t\tmodules.emplace_back(info);\n\n\t\/\/ values of all modules\n\tvector values(modules.size());\n\n\t\/\/ a null result means that there is no data for that module yet\n\tvector> nullableValues;\n\tm_historyDao->fetchMany(device, modules, nullableValues);\n\n\tsize_t i = 0;\n\tfor (const auto &module : modules) {\n\t\tconst auto ¤t = nullableValues.at(i++);\n\t\tconst unsigned int index = module.id();\n\n\t\tif (!current.isNull())\n\t\t\tvalues[index] = current;\n\n\t\t\/\/ else leave the value as invalid\n\t}\n\n\tdevice.setValues(values);\n}\n\nvoid DeviceServiceImpl::doFetchMany(Single> &input)\n{\n\tm_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.target());\n\n\tlist &devices = input.target();\n\tm_dao->fetchMany(devices);\n}\n\nvoid DeviceServiceImpl::doFetchMany(Single> &input)\n{\n\tlist devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_dao->fetchMany(devices);\n\n\t\/\/ convert to list of DeviceWithData\n\tlist result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, device.gateway());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvaluesFor(device);\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchMany(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET, input, input.base());\n\n\tlist &devices = input.target();\n\n\tm_dao->fetchMany(devices);\n\n\tlist::iterator it = devices.begin();\n\n\twhile (it != devices.end()) {\n\t\tDevice &device = *it;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\t\/\/ drop inaccessible devices\n\t\t\tit = devices.erase(it);\n\t\t\tcontinue;\n\t\t}\n\n\t\t++it; \/\/ no erase occured, continue\n\t}\n}\n\n\/**\n * The method performs 1 + 2 * N Dao requests where N is the number of devices.\n * The first query obtains list of Device instances. Because we need a list\n * of DeviceWithData instances, the loop would convert it. The conversion\n * fetches module data for every single device.\n *\n * The method should be optimized (moved to Dao layer) if needed.\n *\/\nvoid DeviceServiceImpl::doFetchMany(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tlist devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET, input, devices);\n\n\tm_dao->fetchMany(devices);\n\n\t\/\/ convert to list of DeviceWithData\n\tlist result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvaluesFor(device);\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchActiveBy(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchActiveBy(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doFetchActiveBy(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tvector devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchActiveBy(devices, input.base());\n\n\t\/\/ convert to list of DeviceWithData\n\tvector result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvaluesFor(device);\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchInactiveBy(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchInactiveBy(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doFetchInactiveBy(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tvector devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchInactiveBy(devices, input.base());\n\n\t\/\/ convert to list of DeviceWithData\n\tvector result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tvaluesFor(device);\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n\n}\n\nvoid DeviceServiceImpl::doUnregister(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UNREGISTER,\n\t\t\tinput, input.target(), input.base());\n\n\tDevice &device = input.target();\n\n\tif (!m_dao->fetch(device, input.base()))\n\t\tthrow NotFoundException(\"no such device \" + device);\n\n\tif (!device.status().active())\n\t\treturn;\n\n\tdevice.status().setState(DeviceStatus::STATE_INACTIVE_PENDING);\n\tdevice.status().setLastChanged({});\n\n\tif (!m_dao->update(device, input.base()))\n\t\tthrow NotFoundException(\"device \" + device + \" seems to not exist\");\n\n\tDeviceUnpairHandler::Ptr handler = new DeviceUnpairHandler(device, m_dao);\n\thandler->setTransactionManager(transactionManager());\n\n\tm_gatewayRPC->unpairDevice(handler, input.base(), device);\n}\n\nbool DeviceServiceImpl::doActivate(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_ACTIVATE,\n\t\t\tinput, input.target(), input.base());\n\n\tDevice &device = input.target();\n\n\tif (!m_dao->fetch(device, input.base()))\n\t\treturn false;\n\n\treturn tryActivateAndUpdate(device, input.base());\n}\n\nbool DeviceServiceImpl::tryActivateAndUpdate(Device &device,\n\t\tconst Gateway &gateway, bool forceUpdate)\n{\n\tconst DeviceStatus &status = device.status();\n\n\tif (!status.active()) {\n\t\tdevice.status().setState(DeviceStatus::STATE_ACTIVE_PENDING);\n\t\tdevice.status().setLastChanged({});\n\n\t\tif (!m_dao->update(device, gateway))\n\t\t\tthrow NotFoundException(\"device \" + device + \" seems to not exist\");\n\n\t\tDevicePairHandler::Ptr handler = new DevicePairHandler(device, m_dao);\n\t\thandler->setTransactionManager(transactionManager());\n\n\t\tm_gatewayRPC->pairDevice(handler, gateway, device);\n\t\treturn true;\n\t}\n\n\treturn forceUpdate? m_dao->update(device, gateway) : false;\n}\n\nbool DeviceServiceImpl::prepareUpdate(RelationWithData &input)\n{\n\tif (!m_dao->fetch(input.target(), input.base()))\n\t\treturn false;\n\n\tinput.data().partial(input.target());\n\treturn true;\n}\n\nbool DeviceServiceImpl::doUpdate(RelationWithData &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.target(), input.base());\n\n\tif (!prepareUpdate(input))\n\t\treturn false;\n\n\treturn m_dao->update(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doUpdateAndActivate(\n\t\tRelationWithData &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE_AND_ACTIVATE,\n\t\t\tinput, input.target(), input.base());\n\n\tif (!prepareUpdate(input))\n\t\treturn false;\n\n\treturn tryActivateAndUpdate(input.target(), input.base(), true);\n}\n\nbool DeviceServiceImpl::doCreateProperty(RelationWithData &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\tinput.data().full(input.target());\n\n\treturn m_propertyDao->insert(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doUpdateProperty(RelationWithData &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\tif (!m_propertyDao->fetch(input.target(), input.base()))\n\t\treturn false;\n\n\tinput.data().partial(input.target());\n\n\treturn m_propertyDao->update(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doRemoveProperty(Relation &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->remove(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doFindProperty(Relation &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->fetch(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doListProperties(Relation, Device> &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->fetchByDevice(input.target(), input.base());\n}\nDeviceServiceImpl: do not fail when a device is missing a type#include \n#include \n#include \n#include \n\n#include \"di\/Injectable.h\"\n#include \"gws\/DevicePairHandler.h\"\n#include \"gws\/DeviceUnpairHandler.h\"\n#include \"model\/Device.h\"\n#include \"model\/Gateway.h\"\n#include \"service\/DeviceServiceImpl.h\"\n\nBEEEON_OBJECT_BEGIN(BeeeOn, DeviceServiceImpl)\nBEEEON_OBJECT_CASTABLE(DeviceService)\nBEEEON_OBJECT_REF(\"deviceDao\", &DeviceServiceImpl::setDeviceDao)\nBEEEON_OBJECT_REF(\"sensorHistoryDao\", &DeviceServiceImpl::setSensorHistoryDao)\nBEEEON_OBJECT_REF(\"devicePropertyDao\", &DeviceServiceImpl::setDevicePropertyDao)\nBEEEON_OBJECT_REF(\"gatewayRPC\", &DeviceServiceImpl::setGatewayRPC)\nBEEEON_OBJECT_REF(\"accessPolicy\", &DeviceServiceImpl::setAccessPolicy)\nBEEEON_OBJECT_REF(\"transactionManager\", &DeviceServiceImpl::setTransactionManager)\nBEEEON_OBJECT_END(BeeeOn, DeviceServiceImpl)\n\nusing namespace std;\nusing namespace Poco;\nusing namespace BeeeOn;\n\nDeviceServiceImpl::DeviceServiceImpl()\n{\n}\n\nvoid DeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)\n{\n\tm_dao = dao;\n}\n\nvoid DeviceServiceImpl::setSensorHistoryDao(SensorHistoryDao::Ptr dao)\n{\n\tm_historyDao = dao;\n}\n\nvoid DeviceServiceImpl::setDevicePropertyDao(DevicePropertyDao::Ptr dao)\n{\n\tm_propertyDao = dao;\n}\n\nvoid DeviceServiceImpl::setGatewayRPC(GatewayRPC::Ptr rpc)\n{\n\tm_gatewayRPC = rpc;\n}\n\nvoid DeviceServiceImpl::setAccessPolicy(DeviceAccessPolicy::Ptr policy)\n{\n\tm_policy = policy;\n}\n\nbool DeviceServiceImpl::doFetch(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.target(), input.base());\n\treturn m_dao->fetch(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::valuesFor(DeviceWithData &device)\n{\n\t\/\/ fetch last value of all device modules\n\tvector modules;\n\n\tif (device.type().isNull()) {\n\t\tthrow IllegalStateException(\n\t\t\t\"device \" + device + \" does not have any known type\");\n\t}\n\n\tfor (const auto &info : *device.type())\n\t\tmodules.emplace_back(info);\n\n\t\/\/ values of all modules\n\tvector values(modules.size());\n\n\t\/\/ a null result means that there is no data for that module yet\n\tvector> nullableValues;\n\tm_historyDao->fetchMany(device, modules, nullableValues);\n\n\tsize_t i = 0;\n\tfor (const auto &module : modules) {\n\t\tconst auto ¤t = nullableValues.at(i++);\n\t\tconst unsigned int index = module.id();\n\n\t\tif (!current.isNull())\n\t\t\tvalues[index] = current;\n\n\t\t\/\/ else leave the value as invalid\n\t}\n\n\tdevice.setValues(values);\n}\n\nvoid DeviceServiceImpl::doFetchMany(Single> &input)\n{\n\tm_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.target());\n\n\tlist &devices = input.target();\n\tm_dao->fetchMany(devices);\n}\n\nvoid DeviceServiceImpl::doFetchMany(Single> &input)\n{\n\tlist devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_dao->fetchMany(devices);\n\n\t\/\/ convert to list of DeviceWithData\n\tlist result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, device.gateway());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tvaluesFor(device);\n\t\t}\n\t\tcatch (const Exception &e) {\n\t\t\tlogger().log(e, __FILE__, __LINE__);\n\t\t\tcontinue; \/\/ skip failing devices\n\t\t}\n\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchMany(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET, input, input.base());\n\n\tlist &devices = input.target();\n\n\tm_dao->fetchMany(devices);\n\n\tlist::iterator it = devices.begin();\n\n\twhile (it != devices.end()) {\n\t\tDevice &device = *it;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\t\/\/ drop inaccessible devices\n\t\t\tit = devices.erase(it);\n\t\t\tcontinue;\n\t\t}\n\n\t\t++it; \/\/ no erase occured, continue\n\t}\n}\n\n\/**\n * The method performs 1 + 2 * N Dao requests where N is the number of devices.\n * The first query obtains list of Device instances. Because we need a list\n * of DeviceWithData instances, the loop would convert it. The conversion\n * fetches module data for every single device.\n *\n * The method should be optimized (moved to Dao layer) if needed.\n *\/\nvoid DeviceServiceImpl::doFetchMany(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tlist devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assureMany(DeviceAccessPolicy::ACTION_USER_GET, input, devices);\n\n\tm_dao->fetchMany(devices);\n\n\t\/\/ convert to list of DeviceWithData\n\tlist result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tvaluesFor(device);\n\t\t}\n\t\tcatch (const Exception &e) {\n\t\t\tlogger().log(e, __FILE__, __LINE__);\n\t\t\tcontinue; \/\/ skip failing devices\n\t\t}\n\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchActiveBy(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchActiveBy(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doFetchActiveBy(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tvector devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchActiveBy(devices, input.base());\n\n\t\/\/ convert to list of DeviceWithData\n\tvector result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tvaluesFor(device);\n\t\t}\n\t\tcatch (const Exception &e) {\n\t\t\tlogger().log(e, __FILE__, __LINE__);\n\t\t\tcontinue; \/\/ skip failing devices\n\t\t}\n\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n}\n\nvoid DeviceServiceImpl::doFetchInactiveBy(Relation, Gateway> &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchInactiveBy(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doFetchInactiveBy(Relation, Gateway> &input)\n{\n\t\/\/ fetch list of Devices\n\tvector devices;\n\tfor (const auto &dev : input.target())\n\t\tdevices.emplace_back(dev);\n\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base());\n\tm_dao->fetchInactiveBy(devices, input.base());\n\n\t\/\/ convert to list of DeviceWithData\n\tvector result;\n\tfor (const auto &dev : devices) {\n\t\tDeviceWithData device = dev;\n\n\t\ttry {\n\t\t\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\t\t\tinput, device, input.base());\n\t\t} catch (const InvalidAccessException &e) {\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tvaluesFor(device);\n\t\t}\n\t\tcatch (const Exception &e) {\n\t\t\tlogger().log(e, __FILE__, __LINE__);\n\t\t\tcontinue; \/\/ skip failing devices\n\t\t}\n\n\t\tresult.emplace_back(device);\n\t}\n\n\tinput.target() = result;\n\n}\n\nvoid DeviceServiceImpl::doUnregister(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UNREGISTER,\n\t\t\tinput, input.target(), input.base());\n\n\tDevice &device = input.target();\n\n\tif (!m_dao->fetch(device, input.base()))\n\t\tthrow NotFoundException(\"no such device \" + device);\n\n\tif (!device.status().active())\n\t\treturn;\n\n\tdevice.status().setState(DeviceStatus::STATE_INACTIVE_PENDING);\n\tdevice.status().setLastChanged({});\n\n\tif (!m_dao->update(device, input.base()))\n\t\tthrow NotFoundException(\"device \" + device + \" seems to not exist\");\n\n\tDeviceUnpairHandler::Ptr handler = new DeviceUnpairHandler(device, m_dao);\n\thandler->setTransactionManager(transactionManager());\n\n\tm_gatewayRPC->unpairDevice(handler, input.base(), device);\n}\n\nbool DeviceServiceImpl::doActivate(Relation &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_ACTIVATE,\n\t\t\tinput, input.target(), input.base());\n\n\tDevice &device = input.target();\n\n\tif (!m_dao->fetch(device, input.base()))\n\t\treturn false;\n\n\treturn tryActivateAndUpdate(device, input.base());\n}\n\nbool DeviceServiceImpl::tryActivateAndUpdate(Device &device,\n\t\tconst Gateway &gateway, bool forceUpdate)\n{\n\tconst DeviceStatus &status = device.status();\n\n\tif (!status.active()) {\n\t\tdevice.status().setState(DeviceStatus::STATE_ACTIVE_PENDING);\n\t\tdevice.status().setLastChanged({});\n\n\t\tif (!m_dao->update(device, gateway))\n\t\t\tthrow NotFoundException(\"device \" + device + \" seems to not exist\");\n\n\t\tDevicePairHandler::Ptr handler = new DevicePairHandler(device, m_dao);\n\t\thandler->setTransactionManager(transactionManager());\n\n\t\tm_gatewayRPC->pairDevice(handler, gateway, device);\n\t\treturn true;\n\t}\n\n\treturn forceUpdate? m_dao->update(device, gateway) : false;\n}\n\nbool DeviceServiceImpl::prepareUpdate(RelationWithData &input)\n{\n\tif (!m_dao->fetch(input.target(), input.base()))\n\t\treturn false;\n\n\tinput.data().partial(input.target());\n\treturn true;\n}\n\nbool DeviceServiceImpl::doUpdate(RelationWithData &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.target(), input.base());\n\n\tif (!prepareUpdate(input))\n\t\treturn false;\n\n\treturn m_dao->update(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doUpdateAndActivate(\n\t\tRelationWithData &input)\n{\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE_AND_ACTIVATE,\n\t\t\tinput, input.target(), input.base());\n\n\tif (!prepareUpdate(input))\n\t\treturn false;\n\n\treturn tryActivateAndUpdate(input.target(), input.base(), true);\n}\n\nbool DeviceServiceImpl::doCreateProperty(RelationWithData &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\tinput.data().full(input.target());\n\n\treturn m_propertyDao->insert(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doUpdateProperty(RelationWithData &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\tif (!m_propertyDao->fetch(input.target(), input.base()))\n\t\treturn false;\n\n\tinput.data().partial(input.target());\n\n\treturn m_propertyDao->update(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doRemoveProperty(Relation &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_UPDATE,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->remove(input.target(), input.base());\n}\n\nbool DeviceServiceImpl::doFindProperty(Relation &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->fetch(input.target(), input.base());\n}\n\nvoid DeviceServiceImpl::doListProperties(Relation, Device> &input)\n{\n\tconst Gateway &gateway = input.base().gateway();\n\tm_policy->assure(DeviceAccessPolicy::ACTION_USER_GET,\n\t\t\tinput, input.base(), gateway);\n\n\treturn m_propertyDao->fetchByDevice(input.target(), input.base());\n}\n<|endoftext|>"}
{"text":"\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n\n#include \"grpc\/support\/log.h\"\n\n#include \n#include \n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"call.h\"\n#include \"channel.h\"\n#include \"completion_queue_async_worker.h\"\n#include \"channel_credentials.h\"\n#include \"timeval.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nCallback *Channel::constructor;\nPersistent Channel::fun_tpl;\n\nbool ParseChannelArgs(Local args_val,\n                      grpc_channel_args **channel_args_ptr) {\n  if (args_val->IsUndefined() || args_val->IsNull()) {\n    *channel_args_ptr = NULL;\n    return true;\n  }\n  if (!args_val->IsObject()) {\n    *channel_args_ptr = NULL;\n    return false;\n  }\n  grpc_channel_args *channel_args = reinterpret_cast(\n      malloc(sizeof(channel_args)));\n  *channel_args_ptr = channel_args;\n  Local args_hash = Nan::To(args_val).ToLocalChecked();\n  Local keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked();\n  channel_args->num_args = keys->Length();\n  channel_args->args = reinterpret_cast(\n      calloc(channel_args->num_args, sizeof(grpc_arg)));\n  for (unsigned int i = 0; i < channel_args->num_args; i++) {\n    Local key = Nan::Get(keys, i).ToLocalChecked();\n    Utf8String key_str(key);\n    if (*key_str == NULL) {\n      \/\/ Key string onversion failed\n      return false;\n    }\n    Local value = Nan::Get(args_hash, key).ToLocalChecked();\n    if (value->IsInt32()) {\n      channel_args->args[i].type = GRPC_ARG_INTEGER;\n      channel_args->args[i].value.integer = Nan::To(value).FromJust();\n    } else if (value->IsString()) {\n      Utf8String val_str(value);\n      channel_args->args[i].type = GRPC_ARG_STRING;\n      channel_args->args[i].value.string = reinterpret_cast(\n          calloc(val_str.length() + 1,sizeof(char)));\n      memcpy(channel_args->args[i].value.string,\n             *val_str, val_str.length() + 1);\n    } else {\n      \/\/ The value does not match either of the accepted types\n      return false;\n    }\n    channel_args->args[i].key = reinterpret_cast(\n        calloc(key_str.length() + 1, sizeof(char)));\n    memcpy(channel_args->args[i].key, *key_str, key_str.length() + 1);\n  }\n  return true;\n}\n\nvoid DeallocateChannelArgs(grpc_channel_args *channel_args) {\n  if (channel_args == NULL) {\n    return;\n  }\n  for (size_t i = 0; i < channel_args->num_args; i++) {\n    if (channel_args->args[i].key == NULL) {\n      \/* NULL key implies that this argument and all subsequent arguments failed\n       * to parse *\/\n      break;\n    }\n    free(channel_args->args[i].key);\n    if (channel_args->args[i].type == GRPC_ARG_STRING) {\n      free(channel_args->args[i].value.string);\n    }\n  }\n  free(channel_args->args);\n  free(channel_args);\n}\n\nChannel::Channel(grpc_channel *channel) : wrapped_channel(channel) {}\n\nChannel::~Channel() {\n  if (wrapped_channel != NULL) {\n    grpc_channel_destroy(wrapped_channel);\n  }\n}\n\nvoid Channel::Init(Local exports) {\n  Nan::HandleScope scope;\n  Local tpl = Nan::New(New);\n  tpl->SetClassName(Nan::New(\"Channel\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  Nan::SetPrototypeMethod(tpl, \"close\", Close);\n  Nan::SetPrototypeMethod(tpl, \"getTarget\", GetTarget);\n  Nan::SetPrototypeMethod(tpl, \"getConnectivityState\", GetConnectivityState);\n  Nan::SetPrototypeMethod(tpl, \"watchConnectivityState\",\n                          WatchConnectivityState);\n  fun_tpl.Reset(tpl);\n  Local ctr = Nan::GetFunction(tpl).ToLocalChecked();\n  Nan::Set(exports, Nan::New(\"Channel\").ToLocalChecked(), ctr);\n  constructor = new Callback(ctr);\n}\n\nbool Channel::HasInstance(Local val) {\n  HandleScope scope;\n  return Nan::New(fun_tpl)->HasInstance(val);\n}\n\ngrpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }\n\nNAN_METHOD(Channel::New) {\n  if (info.IsConstructCall()) {\n    if (!info[0]->IsString()) {\n      return Nan::ThrowTypeError(\n          \"Channel expects a string, a credential and an object\");\n    }\n    grpc_channel *wrapped_channel;\n    \/\/ Owned by the Channel object\n    Utf8String host(info[0]);\n    grpc_credentials *creds;\n    if (!ChannelCredentials::HasInstance(info[1])) {\n      return Nan::ThrowTypeError(\n          \"Channel's second argument must be a ChannelCredentials\");\n    }\n    ChannelCredentials *creds_object = ObjectWrap::Unwrap(\n        Nan::To(info[1]).ToLocalChecked());\n    creds = creds_object->GetWrappedCredentials();\n    grpc_channel_args *channel_args_ptr = NULL;\n    if (!ParseChannelArgs(info[2], &channel_args_ptr)) {\n      DeallocateChannelArgs(channel_args_ptr);\n      return Nan::ThrowTypeError(\"Channel options must be an object with \"\n                                 \"string keys and integer or string values\");\n    }\n    if (creds == NULL) {\n      wrapped_channel = grpc_insecure_channel_create(*host, channel_args_ptr,\n                                                     NULL);\n    } else {\n      wrapped_channel =\n          grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);\n    }\n    DeallocateChannelArgs(channel_args_ptr);\n    Channel *channel = new Channel(wrapped_channel);\n    channel->Wrap(info.This());\n    info.GetReturnValue().Set(info.This());\n    return;\n  } else {\n    const int argc = 3;\n    Local argv[argc] = {info[0], info[1], info[2]};\n    MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance(\n        argc, argv);\n    if (maybe_instance.IsEmpty()) {\n      \/\/ There's probably a pending exception\n      return;\n    } else {\n      info.GetReturnValue().Set(maybe_instance.ToLocalChecked());\n    }\n  }\n}\n\nNAN_METHOD(Channel::Close) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\"close can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  if (channel->wrapped_channel != NULL) {\n    grpc_channel_destroy(channel->wrapped_channel);\n    channel->wrapped_channel = NULL;\n  }\n}\n\nNAN_METHOD(Channel::GetTarget) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\"getTarget can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  info.GetReturnValue().Set(Nan::New(\n      grpc_channel_get_target(channel->wrapped_channel)).ToLocalChecked());\n}\n\nNAN_METHOD(Channel::GetConnectivityState) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\n        \"getConnectivityState can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  int try_to_connect = (int)info[0]->Equals(Nan::True());\n  info.GetReturnValue().Set(\n      grpc_channel_check_connectivity_state(channel->wrapped_channel,\n                                            try_to_connect));\n}\n\nNAN_METHOD(Channel::WatchConnectivityState) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState can only be called on Channel objects\");\n  }\n  if (!info[0]->IsUint32()) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's first argument must be a channel state\");\n  }\n  if (!(info[1]->IsNumber() || info[1]->IsDate())) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's second argument must be a date or a number\");\n  }\n  if (!info[2]->IsFunction()) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's third argument must be a callback\");\n  }\n  grpc_connectivity_state last_state =\n      static_cast(\n          Nan::To(info[0]).FromJust());\n  double deadline = Nan::To(info[1]).FromJust();\n  Local callback_func = info[2].As();\n  Nan::Callback *callback = new Callback(callback_func);\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  unique_ptr ops(new OpVec());\n  grpc_channel_watch_connectivity_state(\n      channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline),\n      CompletionQueueAsyncWorker::GetQueue(),\n      new struct tag(callback,\n                     ops.release(),\n                     shared_ptr(nullptr)));\n  CompletionQueueAsyncWorker::Next();\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace grpc\nFixed incorrect type in a malloc in Node extension\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n\n#include \"grpc\/support\/log.h\"\n\n#include \n#include \n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"call.h\"\n#include \"channel.h\"\n#include \"completion_queue_async_worker.h\"\n#include \"channel_credentials.h\"\n#include \"timeval.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nCallback *Channel::constructor;\nPersistent Channel::fun_tpl;\n\nbool ParseChannelArgs(Local args_val,\n                      grpc_channel_args **channel_args_ptr) {\n  if (args_val->IsUndefined() || args_val->IsNull()) {\n    *channel_args_ptr = NULL;\n    return true;\n  }\n  if (!args_val->IsObject()) {\n    *channel_args_ptr = NULL;\n    return false;\n  }\n  grpc_channel_args *channel_args = reinterpret_cast(\n      malloc(sizeof(grpc_channel_args)));\n  *channel_args_ptr = channel_args;\n  Local args_hash = Nan::To(args_val).ToLocalChecked();\n  Local keys = Nan::GetOwnPropertyNames(args_hash).ToLocalChecked();\n  channel_args->num_args = keys->Length();\n  channel_args->args = reinterpret_cast(\n      calloc(channel_args->num_args, sizeof(grpc_arg)));\n  for (unsigned int i = 0; i < channel_args->num_args; i++) {\n    Local key = Nan::Get(keys, i).ToLocalChecked();\n    Utf8String key_str(key);\n    if (*key_str == NULL) {\n      \/\/ Key string onversion failed\n      return false;\n    }\n    Local value = Nan::Get(args_hash, key).ToLocalChecked();\n    if (value->IsInt32()) {\n      channel_args->args[i].type = GRPC_ARG_INTEGER;\n      channel_args->args[i].value.integer = Nan::To(value).FromJust();\n    } else if (value->IsString()) {\n      Utf8String val_str(value);\n      channel_args->args[i].type = GRPC_ARG_STRING;\n      channel_args->args[i].value.string = reinterpret_cast(\n          calloc(val_str.length() + 1,sizeof(char)));\n      memcpy(channel_args->args[i].value.string,\n             *val_str, val_str.length() + 1);\n    } else {\n      \/\/ The value does not match either of the accepted types\n      return false;\n    }\n    channel_args->args[i].key = reinterpret_cast(\n        calloc(key_str.length() + 1, sizeof(char)));\n    memcpy(channel_args->args[i].key, *key_str, key_str.length() + 1);\n  }\n  return true;\n}\n\nvoid DeallocateChannelArgs(grpc_channel_args *channel_args) {\n  if (channel_args == NULL) {\n    return;\n  }\n  for (size_t i = 0; i < channel_args->num_args; i++) {\n    if (channel_args->args[i].key == NULL) {\n      \/* NULL key implies that this argument and all subsequent arguments failed\n       * to parse *\/\n      break;\n    }\n    free(channel_args->args[i].key);\n    if (channel_args->args[i].type == GRPC_ARG_STRING) {\n      free(channel_args->args[i].value.string);\n    }\n  }\n  free(channel_args->args);\n  free(channel_args);\n}\n\nChannel::Channel(grpc_channel *channel) : wrapped_channel(channel) {}\n\nChannel::~Channel() {\n  if (wrapped_channel != NULL) {\n    grpc_channel_destroy(wrapped_channel);\n  }\n}\n\nvoid Channel::Init(Local exports) {\n  Nan::HandleScope scope;\n  Local tpl = Nan::New(New);\n  tpl->SetClassName(Nan::New(\"Channel\").ToLocalChecked());\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  Nan::SetPrototypeMethod(tpl, \"close\", Close);\n  Nan::SetPrototypeMethod(tpl, \"getTarget\", GetTarget);\n  Nan::SetPrototypeMethod(tpl, \"getConnectivityState\", GetConnectivityState);\n  Nan::SetPrototypeMethod(tpl, \"watchConnectivityState\",\n                          WatchConnectivityState);\n  fun_tpl.Reset(tpl);\n  Local ctr = Nan::GetFunction(tpl).ToLocalChecked();\n  Nan::Set(exports, Nan::New(\"Channel\").ToLocalChecked(), ctr);\n  constructor = new Callback(ctr);\n}\n\nbool Channel::HasInstance(Local val) {\n  HandleScope scope;\n  return Nan::New(fun_tpl)->HasInstance(val);\n}\n\ngrpc_channel *Channel::GetWrappedChannel() { return this->wrapped_channel; }\n\nNAN_METHOD(Channel::New) {\n  if (info.IsConstructCall()) {\n    if (!info[0]->IsString()) {\n      return Nan::ThrowTypeError(\n          \"Channel expects a string, a credential and an object\");\n    }\n    grpc_channel *wrapped_channel;\n    \/\/ Owned by the Channel object\n    Utf8String host(info[0]);\n    grpc_credentials *creds;\n    if (!ChannelCredentials::HasInstance(info[1])) {\n      return Nan::ThrowTypeError(\n          \"Channel's second argument must be a ChannelCredentials\");\n    }\n    ChannelCredentials *creds_object = ObjectWrap::Unwrap(\n        Nan::To(info[1]).ToLocalChecked());\n    creds = creds_object->GetWrappedCredentials();\n    grpc_channel_args *channel_args_ptr = NULL;\n    if (!ParseChannelArgs(info[2], &channel_args_ptr)) {\n      DeallocateChannelArgs(channel_args_ptr);\n      return Nan::ThrowTypeError(\"Channel options must be an object with \"\n                                 \"string keys and integer or string values\");\n    }\n    if (creds == NULL) {\n      wrapped_channel = grpc_insecure_channel_create(*host, channel_args_ptr,\n                                                     NULL);\n    } else {\n      wrapped_channel =\n          grpc_secure_channel_create(creds, *host, channel_args_ptr, NULL);\n    }\n    DeallocateChannelArgs(channel_args_ptr);\n    Channel *channel = new Channel(wrapped_channel);\n    channel->Wrap(info.This());\n    info.GetReturnValue().Set(info.This());\n    return;\n  } else {\n    const int argc = 3;\n    Local argv[argc] = {info[0], info[1], info[2]};\n    MaybeLocal maybe_instance = constructor->GetFunction()->NewInstance(\n        argc, argv);\n    if (maybe_instance.IsEmpty()) {\n      \/\/ There's probably a pending exception\n      return;\n    } else {\n      info.GetReturnValue().Set(maybe_instance.ToLocalChecked());\n    }\n  }\n}\n\nNAN_METHOD(Channel::Close) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\"close can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  if (channel->wrapped_channel != NULL) {\n    grpc_channel_destroy(channel->wrapped_channel);\n    channel->wrapped_channel = NULL;\n  }\n}\n\nNAN_METHOD(Channel::GetTarget) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\"getTarget can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  info.GetReturnValue().Set(Nan::New(\n      grpc_channel_get_target(channel->wrapped_channel)).ToLocalChecked());\n}\n\nNAN_METHOD(Channel::GetConnectivityState) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\n        \"getConnectivityState can only be called on Channel objects\");\n  }\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  int try_to_connect = (int)info[0]->Equals(Nan::True());\n  info.GetReturnValue().Set(\n      grpc_channel_check_connectivity_state(channel->wrapped_channel,\n                                            try_to_connect));\n}\n\nNAN_METHOD(Channel::WatchConnectivityState) {\n  if (!HasInstance(info.This())) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState can only be called on Channel objects\");\n  }\n  if (!info[0]->IsUint32()) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's first argument must be a channel state\");\n  }\n  if (!(info[1]->IsNumber() || info[1]->IsDate())) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's second argument must be a date or a number\");\n  }\n  if (!info[2]->IsFunction()) {\n    return Nan::ThrowTypeError(\n        \"watchConnectivityState's third argument must be a callback\");\n  }\n  grpc_connectivity_state last_state =\n      static_cast(\n          Nan::To(info[0]).FromJust());\n  double deadline = Nan::To(info[1]).FromJust();\n  Local callback_func = info[2].As();\n  Nan::Callback *callback = new Callback(callback_func);\n  Channel *channel = ObjectWrap::Unwrap(info.This());\n  unique_ptr ops(new OpVec());\n  grpc_channel_watch_connectivity_state(\n      channel->wrapped_channel, last_state, MillisecondsToTimespec(deadline),\n      CompletionQueueAsyncWorker::GetQueue(),\n      new struct tag(callback,\n                     ops.release(),\n                     shared_ptr(nullptr)));\n  CompletionQueueAsyncWorker::Next();\n}\n\n}  \/\/ namespace node\n}  \/\/ namespace grpc\n<|endoftext|>"}
{"text":"#include \"llvm\/Pass.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/PassRegistry.h\"\n#include \"ExpertSystem\/KnowledgeConstructionEngine.h\"\n#include \"pipeline\/clips\/CLIPSPassGenerator.h\"\n#include \"pipeline\/clips\/CLIPSPass.h\"\n#include \"pipeline\/clips\/CLIPSPassHeader.h\"\n#include \"rampancy\/Cortex.h\"\n#include \"rampancy\/CompilerManager.h\"\n#include \"rampancy\/CompilerRegistry.h\"\n#include \"indirect\/Indirector.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nextern \"C\" {\n#include \"clips.h\"\n}\n\nusing namespace llvm;\nusing namespace indirect;\nextern \"C\" void CLIPSOptimizeCode(void* theEnv);\nextern \"C\" void CLIPSRegisterPass(void* theEnv);\nextern \"C\" void CLIPSUnregisterPass(void* theEnv);\nextern \"C\" void* CLIPSPassRegistered(void* theEnv);\n#define pass_registered (char*)\"pass-registered\"\n#define optimize (char*)\"optimize\"\n#define unregister_pass (char*)\"unregister-pass\"\n#define register_pass (char*)\"register-pass\"\n#define werror (char*)\"werror\"\n#define msg(x) (char*) x\n#define copy(from, to) \\\n\tto = CharBuffer(strlen(from)); \\\nsprintf(to, \"%s\", from) \n#define BoolCast(str, tgt) tgt = (strcmp(str, \"TRUE\") == 0) ? TRUE : FALSE\n\nextern \"C\" void RegisterCLIPSPipelineFunctions(void* theEnv) {\n\tEnvDefineFunction(theEnv, optimize, 'v',\n\t\t\tPTIEF CLIPSOptimizeCode, \"CLIPSOptimizeCode\");\n\tEnvDefineFunction(theEnv, register_pass, 'v',\n\t\t\tPTIEF CLIPSRegisterPass, \"CLIPSRegisterPass\");\n\tEnvDefineFunction(theEnv, unregister_pass, 'v',\n\t\t\tPTIEF CLIPSUnregisterPass, \"CLIPSUnregisterPass\");\n\tEnvDefineFunction2(theEnv, pass_registered, 'w', \n\t\t\tPTIEF CLIPSPassRegistered, \"CLIPSPassRegistered\", \n\t\t\t\"11k\");\n}\n\nvoid CLIPSOptimizeCode(void* theEnv) {\n\n}\n\nvoid CLIPSRegisterPass(void* theEnv) {\n\t\/* register-pass has the following arguments\n\t * 1) name (PassArg)\n\t * 2) description (PassName)\n\t * 3) type (string)\n\t * 4) IsAnalysis (bool)\n\t * 5) isCFGPass (bool)\n\t * 6) needRegions (bool)\n\t * 7) needLoops (bool)\n\t * 8) passes (multifield)\n\t * 9) required (multifield)\n\t * 10) required-transitive (multifield)\n\t * 11) Preserved (multifield)\n\t * 12) preservesAll (bool)\n\t * 13) preservesCFG (bool);\n\t *\/\n\n\tvoid* passes;\n\tvoid* required;\n\tvoid* requiredTransitive;\n\tvoid* preserved;\n\tDATA_OBJECT arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, \n\t\t\t\t\targ10, arg11, arg12;\n\tchar *tmp0, *tmp1, *tmp2, *tmp3, *tmp4, *tmp5, *tmp6, *tmp7, *tmp8, *tmp9,\n\t\t  *tmp10;\n\tchar* pArg;\n\tchar* pName;\n\tbool isAnalysis, isCFG, \n\t\t  needRegions, needLoops,\n\t\t  preservesAll, preservesCFG;\n\tchar* type;\n\tlong long l0, l1, l2, l3;\n\tstd::string tmp;\n\traw_string_ostream stream(tmp);\n\tpipeline::clips::CLIPSPassHeader* header = new pipeline::clips::CLIPSPassHeader();\n\theader->setTemplateSet(\"clips\");\n\tif(EnvArgCountCheck(theEnv, register_pass, EXACTLY, 13) == -1) {\n\t\treturn;\n\t}\n\n\tif(EnvArgTypeCheck(theEnv, register_pass, 1, SYMBOL_OR_STRING, &arg0) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 2, SYMBOL_OR_STRING, &arg1) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 3, SYMBOL_OR_STRING, &arg2) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 4, SYMBOL, &arg3) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 5, SYMBOL, &arg4) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 6, SYMBOL, &arg5) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 7, SYMBOL, &arg6) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 8, MULTIFIELD, &arg7) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 9, MULTIFIELD, &arg8) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 10, MULTIFIELD, &arg9) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 11, MULTIFIELD, &arg10) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 12, SYMBOL, &arg11) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 13, SYMBOL, &arg12) == FALSE) {\n\t\treturn;\n\t}\n\ttmp0 = DOToString(arg0);\n\tcopy(tmp0, pArg);\n\theader->setPassName((const char*)pArg);\n\ttmp1 = DOToString(arg1);\n\tcopy(tmp1, pName);\n\theader->setPassDescription((const char*)pName);\n\ttmp2 = DOToString(arg2);\n\tcopy(tmp2, type);\n\theader->setPassType(type);\n\ttmp3 = DOToString(arg3);\n\tBoolCast(tmp3, isAnalysis);\n\theader->setIsAnalysis(isAnalysis);\n\ttmp4 = DOToString(arg4);\n\tBoolCast(tmp4, isCFG);\n\theader->setIsCFGOnlyPass(isCFG);\n\ttmp5 = DOToString(arg5);\n\tBoolCast(tmp5, needRegions);\n\theader->setNeedsRegions(needRegions);\n\ttmp6 = DOToString(arg6);\n\tBoolCast(tmp6, needLoops);\n\theader->setNeedsLoops(needLoops);\n\t\/\/l0 = (long long)GetDOLength(arg7);\n\t\/\/l1 = (long long)GetDOLength(arg8);\n\t\/\/aUsage = GetValue(arg7);\n\n\n\n   IndirectPassRegistry& indirectRegistry = *IndirectPassRegistry::getIndirectPassRegistry();\n\tindirectRegistry.registerIndirectPassHeader(header);\n\tfree(pArg);\n\tfree(pName);\n\tfree(type);\n\n}\n\nvoid CLIPSUnregisterPass(void* theEnv) {\n\n}\n\nvoid* CLIPSPassRegistered(void* theEnv) {\n\tDATA_OBJECT arg0;\n\tchar* a;\n\tchar* b;\n\tif(EnvArgCountCheck(theEnv, pass_registered, EXACTLY, 1) == -1) {\n\t\treturn FalseSymbol();\n\t}\n\n\tif(EnvArgTypeCheck(theEnv, pass_registered, 1, SYMBOL_OR_STRING, &arg0) == FALSE) {\n\t\treturn FalseSymbol();\n\t}\n\ta = DOToString(arg0);\n\tcopy(a, b);\n\n\tllvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();\n\tconst llvm::PassInfo* pi = registry->getPassInfo(llvm::StringRef(b));\n\tfree(b);\n\tif(pi) {\n\t\treturn TrueSymbol();\n\t} else {\n\t\treturn FalseSymbol();\n\t}\n}\n\/*\n\tllvm::PassManager tmpPassManager;\n\tllvm::PassManagerBuilder builder;\n\/\/taken from opt\nllvm::TargetLibraryInfo *tli = \nnew llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));\ntmpPassManager.add(tli);\nllvm::TargetData *td = 0;\nconst std::string &moduleDataLayout = module->getDataLayout();\nif(!moduleDataLayout.empty())\ntd = new llvm::TargetData(moduleDataLayout);\nif(td)\ntmpPassManager.add(td);\nllvm::PassManager& PM = tmpPassManager;\n\/\/add em all!\nbuilder.OptLevel = 2;\nbuilder.DisableSimplifyLibCalls = false;\nbuilder.populateModulePassManager(PM);\n\/\/let's see if this fixes the issue\nllvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();\nconst llvm::PassInfo* ci = registry->getPassInfo(\nllvm::StringRef(\"function-to-knowledge\"));\nconst llvm::PassInfo* ls = registry->getPassInfo(\nllvm::StringRef(\"loop-simplify\"));\nconst llvm::PassInfo* bce = registry->getPassInfo(\nllvm::StringRef(\"break-crit-edges\"));\nExpertSystem::FunctionKnowledgeConversionPass* copy = \n(ExpertSystem::FunctionKnowledgeConversionPass*)ci->createPass();\ncopy->setEnvironment(tEnv);\ntmpPassManager.add(ls->createPass());\ntmpPassManager.add(bce->createPass());\ntmpPassManager.add(copy);\ntmpPassManager.add(llvm::createVerifierPass());\ntmpPassManager.run(*module);\n\n*\/\nnamespace pipeline {\n\tnamespace clips {\n\t\tvoid initializeCLIPSIndirector() {\n\t\t\tIndirectPassRegistry& indirectRegistry = *IndirectPassRegistry::getIndirectPassRegistry();\n\t\t\tindirectRegistry.registerPassGenerator(\"clips\");\n\t\t}\n\t}\n}\n#undef pass_registered \n#undef optimize \n#undef unregister_pass \n#undef register_pass \n#undef werror\n#undef msg\n#undef copy\n#undef BoolCast\nAdded a translation function for char* => IndirectPassType#include \"llvm\/Pass.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/PassRegistry.h\"\n#include \"ExpertSystem\/KnowledgeConstructionEngine.h\"\n#include \"pipeline\/clips\/CLIPSPassGenerator.h\"\n#include \"pipeline\/clips\/CLIPSPass.h\"\n#include \"pipeline\/clips\/CLIPSPassHeader.h\"\n#include \"rampancy\/Cortex.h\"\n#include \"rampancy\/CompilerManager.h\"\n#include \"rampancy\/CompilerRegistry.h\"\n#include \"indirect\/Indirector.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nextern \"C\" {\n#include \"clips.h\"\n}\n\nusing namespace llvm;\nusing namespace indirect;\nextern \"C\" indirect::IndirectPassHeader::IndirectPassType TranslateInput(char* input);\nextern \"C\" void CLIPSOptimizeCode(void* theEnv);\nextern \"C\" void CLIPSRegisterPass(void* theEnv);\nextern \"C\" void CLIPSUnregisterPass(void* theEnv);\nextern \"C\" void* CLIPSPassRegistered(void* theEnv);\n#define pass_registered (char*)\"pass-registered\"\n#define optimize (char*)\"optimize\"\n#define unregister_pass (char*)\"unregister-pass\"\n#define register_pass (char*)\"register-pass\"\n#define werror (char*)\"werror\"\n#define msg(x) (char*) x\n#define copy(from, to) \\\n\tto = CharBuffer(strlen(from)); \\\nsprintf(to, \"%s\", from) \n#define BoolCast(str, tgt) tgt = (strcmp(str, \"TRUE\") == 0) ? TRUE : FALSE\n\nextern \"C\" void RegisterCLIPSPipelineFunctions(void* theEnv) {\n\tEnvDefineFunction(theEnv, optimize, 'v',\n\t\t\tPTIEF CLIPSOptimizeCode, \"CLIPSOptimizeCode\");\n\tEnvDefineFunction(theEnv, register_pass, 'v',\n\t\t\tPTIEF CLIPSRegisterPass, \"CLIPSRegisterPass\");\n\tEnvDefineFunction(theEnv, unregister_pass, 'v',\n\t\t\tPTIEF CLIPSUnregisterPass, \"CLIPSUnregisterPass\");\n\tEnvDefineFunction2(theEnv, pass_registered, 'w', \n\t\t\tPTIEF CLIPSPassRegistered, \"CLIPSPassRegistered\", \n\t\t\t\"11k\");\n}\n\nvoid CLIPSOptimizeCode(void* theEnv) {\n\n}\n\nvoid CLIPSRegisterPass(void* theEnv) {\n\t\/* register-pass has the following arguments\n\t * 1) name (PassArg)\n\t * 2) description (PassName)\n\t * 3) type (string)\n\t * 4) IsAnalysis (bool)\n\t * 5) isCFGPass (bool)\n\t * 6) needRegions (bool)\n\t * 7) needLoops (bool)\n\t * 8) passes (multifield)\n\t * 9) required (multifield)\n\t * 10) required-transitive (multifield)\n\t * 11) Preserved (multifield)\n\t * 12) preservesAll (bool)\n\t * 13) preservesCFG (bool);\n\t *\/\n\n\tvoid* passes;\n\tvoid* required;\n\tvoid* requiredTransitive;\n\tvoid* preserved;\n\tDATA_OBJECT arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, \n\t\t\t\t\targ10, arg11, arg12;\n\tchar *tmp0, *tmp1, *tmp2, *tmp3, *tmp4, *tmp5, *tmp6, *tmp7, *tmp8, *tmp9,\n\t\t  *tmp10;\n\tchar* pArg;\n\tchar* pName;\n\tbool isAnalysis, isCFG, \n\t\t  needRegions, needLoops,\n\t\t  preservesAll, preservesCFG;\n\tchar* type;\n\tlong long l0, l1, l2, l3;\n\tstd::string tmp;\n\traw_string_ostream stream(tmp);\n\tpipeline::clips::CLIPSPassHeader* header = new pipeline::clips::CLIPSPassHeader();\n\theader->setTemplateSet(\"clips\");\n\tif(EnvArgCountCheck(theEnv, register_pass, EXACTLY, 13) == -1) {\n\t\treturn;\n\t}\n\n\tif(EnvArgTypeCheck(theEnv, register_pass, 1, SYMBOL_OR_STRING, &arg0) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 2, SYMBOL_OR_STRING, &arg1) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 3, SYMBOL_OR_STRING, &arg2) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 4, SYMBOL, &arg3) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 5, SYMBOL, &arg4) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 6, SYMBOL, &arg5) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 7, SYMBOL, &arg6) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 8, MULTIFIELD, &arg7) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 9, MULTIFIELD, &arg8) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 10, MULTIFIELD, &arg9) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 11, MULTIFIELD, &arg10) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 12, SYMBOL, &arg11) == FALSE) {\n\t\treturn;\n\t}\n\tif(EnvArgTypeCheck(theEnv, register_pass, 13, SYMBOL, &arg12) == FALSE) {\n\t\treturn;\n\t}\n\ttmp0 = DOToString(arg0);\n\tcopy(tmp0, pArg);\n\theader->setPassName((const char*)pArg);\n\ttmp1 = DOToString(arg1);\n\tcopy(tmp1, pName);\n\theader->setPassDescription((const char*)pName);\n\ttmp2 = DOToString(arg2);\n\tcopy(tmp2, type);\n\theader->setPassType(TranslateInput(type));\n\ttmp3 = DOToString(arg3);\n\tBoolCast(tmp3, isAnalysis);\n\theader->setIsAnalysis(isAnalysis);\n\ttmp4 = DOToString(arg4);\n\tBoolCast(tmp4, isCFG);\n\theader->setIsCFGOnlyPass(isCFG);\n\ttmp5 = DOToString(arg5);\n\tBoolCast(tmp5, needRegions);\n\theader->setNeedsRegions(needRegions);\n\ttmp6 = DOToString(arg6);\n\tBoolCast(tmp6, needLoops);\n\theader->setNeedsLoops(needLoops);\n\t\/\/l0 = (long long)GetDOLength(arg7);\n\t\/\/l1 = (long long)GetDOLength(arg8);\n\t\/\/aUsage = GetValue(arg7);\n\n\n\n   IndirectPassRegistry& indirectRegistry = *IndirectPassRegistry::getIndirectPassRegistry();\n\tindirectRegistry.registerIndirectPassHeader(header);\n\tfree(pArg);\n\tfree(pName);\n\tfree(type);\n\n}\n\nvoid CLIPSUnregisterPass(void* theEnv) {\n\n}\n\nvoid* CLIPSPassRegistered(void* theEnv) {\n\tDATA_OBJECT arg0;\n\tchar* a;\n\tchar* b;\n\tif(EnvArgCountCheck(theEnv, pass_registered, EXACTLY, 1) == -1) {\n\t\treturn FalseSymbol();\n\t}\n\n\tif(EnvArgTypeCheck(theEnv, pass_registered, 1, SYMBOL_OR_STRING, &arg0) == FALSE) {\n\t\treturn FalseSymbol();\n\t}\n\ta = DOToString(arg0);\n\tcopy(a, b);\n\n\tllvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();\n\tconst llvm::PassInfo* pi = registry->getPassInfo(llvm::StringRef(b));\n\tfree(b);\n\tif(pi) {\n\t\treturn TrueSymbol();\n\t} else {\n\t\treturn FalseSymbol();\n\t}\n}\nIndirectPassHeader::IndirectPassType TranslateInput(char* input) {\n\tif(strcmp(input, \"Module\") == 0) {\n\t\treturn IndirectPassHeader::Module;\n\t} else if(strcmp(input, \"Function\") == 0) {\n\t\treturn IndirectPassHeader::Function;\n\t} else if(strcmp(input, \"BasicBlock\") == 0) {\n\t\treturn IndirectPassHeader::BasicBlock;\n\t} else if(strcmp(input, \"Loop\") == 0) {\n\t\treturn IndirectPassHeader::Loop;\n\t} else if(strcmp(input, \"Region\") == 0) {\n\t\treturn IndirectPassHeader::Region;\n\t} else if(strcmp(input, \"MachineFunction\") == 0) {\n\t\treturn IndirectPassHeader::MachineFunction;\n\t} else if(strcmp(input, \"CallGraphSCC\") == 0) {\n\t\treturn IndirectPassHeader::CallGraphSCC;\n\t} else {\n\t\treturn IndirectPassHeader::Unknown;\n\t}\n}\n\/*\n\tllvm::PassManager tmpPassManager;\n\tllvm::PassManagerBuilder builder;\n\/\/taken from opt\nllvm::TargetLibraryInfo *tli = \nnew llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));\ntmpPassManager.add(tli);\nllvm::TargetData *td = 0;\nconst std::string &moduleDataLayout = module->getDataLayout();\nif(!moduleDataLayout.empty())\ntd = new llvm::TargetData(moduleDataLayout);\nif(td)\ntmpPassManager.add(td);\nllvm::PassManager& PM = tmpPassManager;\n\/\/add em all!\nbuilder.OptLevel = 2;\nbuilder.DisableSimplifyLibCalls = false;\nbuilder.populateModulePassManager(PM);\n\/\/let's see if this fixes the issue\nllvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();\nconst llvm::PassInfo* ci = registry->getPassInfo(\nllvm::StringRef(\"function-to-knowledge\"));\nconst llvm::PassInfo* ls = registry->getPassInfo(\nllvm::StringRef(\"loop-simplify\"));\nconst llvm::PassInfo* bce = registry->getPassInfo(\nllvm::StringRef(\"break-crit-edges\"));\nExpertSystem::FunctionKnowledgeConversionPass* copy = \n(ExpertSystem::FunctionKnowledgeConversionPass*)ci->createPass();\ncopy->setEnvironment(tEnv);\ntmpPassManager.add(ls->createPass());\ntmpPassManager.add(bce->createPass());\ntmpPassManager.add(copy);\ntmpPassManager.add(llvm::createVerifierPass());\ntmpPassManager.run(*module);\n\n*\/\nnamespace pipeline {\n\tnamespace clips {\n\t\tvoid initializeCLIPSIndirector() {\n\t\t\tIndirectPassRegistry& indirectRegistry = *IndirectPassRegistry::getIndirectPassRegistry();\n\t\t\tindirectRegistry.registerPassGenerator(\"clips\");\n\t\t}\n\t}\n}\n#undef pass_registered \n#undef optimize \n#undef unregister_pass \n#undef register_pass \n#undef werror\n#undef msg\n#undef copy\n#undef BoolCast\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DiagramHelper.hxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CHART2_DIAGRAMHELPER_HXX\n#define CHART2_DIAGRAMHELPER_HXX\n\n#include \"StackMode.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nnamespace chart\n{\n\nclass DiagramHelper\n{\npublic:\n    typedef ::std::pair<\n            ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartTypeTemplate >,\n            ::rtl::OUString >\n        tTemplateWithServiceName;\n\n    \/** tries to find a template in the chart-type manager that matches the\n        given diagram.\n\n        @param rPreferredTemplateName\n            Check this template first.  This may speed up searching, if the\n            caller assumes a certain template as most likely to be the one that\n            matches.\n\n        @return\n            A pair containing a template with the correct properties set as\n            first entry and the service name of the templateas second entry.  If\n            no template was found both elements are empty.\n     *\/\n    static tTemplateWithServiceName\n        getTemplateForDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::lang::XMultiServiceFactory > & xChartTypeManager,\n            const ::rtl::OUString & rPreferredTemplateName = ::rtl::OUString());\n\n    \/** Sets the \"SwapXAndYAxis\" property at all coordinate systems found in the\n        given diagram.\n\n        \"vertical==true\" for bar charts, \"vertical==false\" for column charts\n     *\/\n    static void setVertical( const ::com::sun::star::uno::Reference<\n                                 ::com::sun::star::chart2::XDiagram > & xDiagram,\n                             bool bVertical = true );\n\n    \/** Gets the \"SwapXAndYAxis\" property at all coordinate systems found in the\n        given diagram.\n\n        \"vertical==true\" for bar charts, \"vertical==false\" for column charts\n    *\/\n    static bool getVertical( const ::com::sun::star::uno::Reference<\n                                 ::com::sun::star::chart2::XDiagram > & xDiagram,\n                             bool& rbOutFoundResult, bool& rbOutAmbiguousResult );\n\n    static StackMode getStackMode(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        bool& rbFound, bool& rbAmbiguous\n        );\n\n    \/** @param bOnlyAtFirstChartType\n            If <\/TRUE>, the stacking mode is only set at the series found inside\n            the first chart type.  This is the standard for all current\n            templates (the only template that has more than one chart-type and\n            allows stacking is bar\/line combi, and for this the stacking only\n            applies to the first chart type\/the bars)\n     *\/\n    static void setStackMode(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        StackMode eStackMode,\n        bool bOnlyAtFirstChartType = true\n        );\n\n    \/** Retrieves the stackmode of the first DataSeries or none. If the series have differing stack\n        modes, rbAmbiguous is set to true. If no series is there rbFound is set to false.\n\n        @param xCorrespondingCoordinateSystem\n            The coordinate system in which the given chart type xChartType is\n            located.  (This is needed for determining percent stacking.  If\n            omitted, the result will just indicate \"not stacked\", \"stacked\" or\n            \"ambiguous\")\n     *\/\n    static StackMode getStackModeFromChartType(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType > & xChartType,\n        bool& rbFound, bool& rbAmbiguous,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xCorrespondingCoordinateSystem =\n                ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >()\n        );\n\n    \/** Returns the dimension found for all chart types in the tree.  If the\n        dimension is not unique, 0 is returned.\n     *\/\n    static sal_Int32 getDimension(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    \/** Sets the dimension of the diagram given.\n\n        1. Sets the dimension of all used ChartTypes\n        2. Adapts the DataSeriesTree to reflect the new dimension\n        3. If new coordinate-systems have to be created, adapts the\n           XCoordinateSystemContainer of the diagram.\n     *\/\n    static void setDimension(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        sal_Int32 nNewDimensionCount );\n\n    \/** Replaces all occurences of xCooSysToReplace in the tree with\n        xReplacement in the diagram's tree\n     *\/\n    static void replaceCoordinateSystem(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xCooSysToReplace,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xReplacement );\n\n    static bool isSeriesAttachedToMainAxis(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xDataSeries );\n\n    static bool attachSeriesToAxis( bool bMainAxis,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xSeries,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::uno::XComponentContext > & xContext );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XAxis > getAttachedAxis(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xSeries,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType >\n        getChartTypeOfSeries(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDataSeries >& xSeries );\n\n    static ::com::sun::star::uno::Reference<\n    ::com::sun::star::chart2::XCoordinateSystem >\n        getCoordinateSystemOfChartType(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static ::std::vector<\n            ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries > >\n        getDataSeriesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    \/** return all data series in this diagram grouped by chart-types\n     *\/\n    static ::com::sun::star::uno::Sequence<\n               ::com::sun::star::uno::Sequence<\n                   ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > > >\n        getDataSeriesGroups(\n            const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool isCategoryDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static void setCategoriesToDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::data::XLabeledDataSequence >& xCategories,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            bool bSetAxisType = false, \/\/ when this flag is true ...\n            bool bCategoryAxis = true);\/\/ set the AxisType to CATEGORY or back to REALNUMBER\n\n    static ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >\n        getCategoriesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static ::com::sun::star::uno::Sequence< rtl::OUString >\n        generateAutomaticCategories(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartDocument > & xChartDoc );\n\n    static ::com::sun::star::uno::Sequence< rtl::OUString >\n        generateAutomaticCategories(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XCoordinateSystem > & xCooSys );\n\n    static void generateAutomaticCategoriesFromChartType(\n            ::com::sun::star::uno::Sequence< rtl::OUString >& rRet,\n            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType >\n        getChartTypeByIndex( const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram, sal_Int32 nIndex );\n\n    static ::com::sun::star::uno::Sequence<\n            ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType > >\n        getChartTypesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool areChartTypesCompatible( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xFirstType,\n                const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xSecondType );\n\n\n    \/**\n        * Test if a series can be moved.\n        *\n        * @param xDiagram\n        *  Reference to the diagram that contains the series.\n        *\n        * @param xGivenDataSeries\n        *  Reference to the series that should be tested for moving.\n        *\n        * @param bForward\n        *  Direction of the move to be checked.\n        *\n        * @returns <\/TRUE> if the series can be moved.\n        *\n        *\/\n    static bool isSeriesMoveable(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n        ::com::sun::star::chart2::XDataSeries >& xGivenDataSeries,\n            bool bForward );\n\n    \/**\n        * Move a series forward or backward.\n        *\n        * @param xDiagram\n        *  Reference to the diagram that contains the series.\n        *\n        * @param xGivenDataSeries\n        *  Reference to the series that should be moved.\n        *\n        * @param bForward\n        *  Direction in which the series should be moved.\n        *\n        * @returns <\/TRUE> if the series was moved successfully.\n        *\n        *\/\n    static bool moveSeries(\n                const ::com::sun::star::uno::Reference<\n                  ::com::sun::star::chart2::XDiagram >& xDiagram,\n                const ::com::sun::star::uno::Reference<\n          ::com::sun::star::chart2::XDataSeries >& xGivenDataSeries,\n                bool bForward );\n\n    static sal_Int32 getIndexOfSeriesWithinChartType(\n                const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::chart2::XDataSeries >& xDataSeries,\n               const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static bool isSupportingFloorAndWall( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool isPieOrDonutChart( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static sal_Int32 getGeometry3D(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        bool& rbFound, bool& rbAmbiguous );\n\n    static void setGeometry3D(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        sal_Int32 nNewGeometry );\n\nprivate:\n    \/\/ not implemented\n    DiagramHelper();\n\n};\n\n} \/\/  namespace chart\n\n\/\/ CHART2_DIAGRAMHELPER_HXX\n#endif\nINTEGRATION: CWS chart22 (1.6.26); FILE MERGED 2008\/06\/10 11:11:50 iha 1.6.26.3: RESYNC: (1.8-1.9); FILE MERGED 2008\/04\/17 11:30:52 iha 1.6.26.2: RESYNC: (1.6-1.8); FILE MERGED 2008\/02\/21 16:55:59 iha 1.6.26.1: #i65549# Plotting of missing values\/*************************************************************************\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: DiagramHelper.hxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org.  If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CHART2_DIAGRAMHELPER_HXX\n#define CHART2_DIAGRAMHELPER_HXX\n\n#include \"StackMode.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nnamespace chart\n{\n\nclass DiagramHelper\n{\npublic:\n    typedef ::std::pair<\n            ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartTypeTemplate >,\n            ::rtl::OUString >\n        tTemplateWithServiceName;\n\n    \/** tries to find a template in the chart-type manager that matches the\n        given diagram.\n\n        @param rPreferredTemplateName\n            Check this template first.  This may speed up searching, if the\n            caller assumes a certain template as most likely to be the one that\n            matches.\n\n        @return\n            A pair containing a template with the correct properties set as\n            first entry and the service name of the templateas second entry.  If\n            no template was found both elements are empty.\n     *\/\n    static tTemplateWithServiceName\n        getTemplateForDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::lang::XMultiServiceFactory > & xChartTypeManager,\n            const ::rtl::OUString & rPreferredTemplateName = ::rtl::OUString());\n\n    \/** Sets the \"SwapXAndYAxis\" property at all coordinate systems found in the\n        given diagram.\n\n        \"vertical==true\" for bar charts, \"vertical==false\" for column charts\n     *\/\n    static void setVertical( const ::com::sun::star::uno::Reference<\n                                 ::com::sun::star::chart2::XDiagram > & xDiagram,\n                             bool bVertical = true );\n\n    \/** Gets the \"SwapXAndYAxis\" property at all coordinate systems found in the\n        given diagram.\n\n        \"vertical==true\" for bar charts, \"vertical==false\" for column charts\n    *\/\n    static bool getVertical( const ::com::sun::star::uno::Reference<\n                                 ::com::sun::star::chart2::XDiagram > & xDiagram,\n                             bool& rbOutFoundResult, bool& rbOutAmbiguousResult );\n\n    static StackMode getStackMode(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        bool& rbFound, bool& rbAmbiguous\n        );\n\n    \/** @param bOnlyAtFirstChartType\n            If <\/TRUE>, the stacking mode is only set at the series found inside\n            the first chart type.  This is the standard for all current\n            templates (the only template that has more than one chart-type and\n            allows stacking is bar\/line combi, and for this the stacking only\n            applies to the first chart type\/the bars)\n     *\/\n    static void setStackMode(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        StackMode eStackMode,\n        bool bOnlyAtFirstChartType = true\n        );\n\n    \/** Retrieves the stackmode of the first DataSeries or none. If the series have differing stack\n        modes, rbAmbiguous is set to true. If no series is there rbFound is set to false.\n\n        @param xCorrespondingCoordinateSystem\n            The coordinate system in which the given chart type xChartType is\n            located.  (This is needed for determining percent stacking.  If\n            omitted, the result will just indicate \"not stacked\", \"stacked\" or\n            \"ambiguous\")\n     *\/\n    static StackMode getStackModeFromChartType(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType > & xChartType,\n        bool& rbFound, bool& rbAmbiguous,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xCorrespondingCoordinateSystem =\n                ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XCoordinateSystem >()\n        );\n\n    \/** Returns the dimension found for all chart types in the tree.  If the\n        dimension is not unique, 0 is returned.\n     *\/\n    static sal_Int32 getDimension(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    \/** Sets the dimension of the diagram given.\n\n        1. Sets the dimension of all used ChartTypes\n        2. Adapts the DataSeriesTree to reflect the new dimension\n        3. If new coordinate-systems have to be created, adapts the\n           XCoordinateSystemContainer of the diagram.\n     *\/\n    static void setDimension(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        sal_Int32 nNewDimensionCount );\n\n    \/** Replaces all occurences of xCooSysToReplace in the tree with\n        xReplacement in the diagram's tree\n     *\/\n    static void replaceCoordinateSystem(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xCooSysToReplace,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XCoordinateSystem > & xReplacement );\n\n    static bool isSeriesAttachedToMainAxis(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xDataSeries );\n\n    static bool attachSeriesToAxis( bool bMainAxis,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xSeries,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::uno::XComponentContext > & xContext );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XAxis > getAttachedAxis(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries >& xSeries,\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType >\n        getChartTypeOfSeries(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDataSeries >& xSeries );\n\n    static ::com::sun::star::uno::Reference<\n    ::com::sun::star::chart2::XCoordinateSystem >\n        getCoordinateSystemOfChartType(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static ::std::vector<\n            ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDataSeries > >\n        getDataSeriesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    \/** return all data series in this diagram grouped by chart-types\n     *\/\n    static ::com::sun::star::uno::Sequence<\n               ::com::sun::star::uno::Sequence<\n                   ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries > > >\n        getDataSeriesGroups(\n            const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool isCategoryDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static void setCategoriesToDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::data::XLabeledDataSequence >& xCategories,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            bool bSetAxisType = false, \/\/ when this flag is true ...\n            bool bCategoryAxis = true);\/\/ set the AxisType to CATEGORY or back to REALNUMBER\n\n    static ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XLabeledDataSequence >\n        getCategoriesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static ::com::sun::star::uno::Sequence< rtl::OUString >\n        generateAutomaticCategories(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartDocument > & xChartDoc );\n\n    static ::com::sun::star::uno::Sequence< rtl::OUString >\n        generateAutomaticCategories(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XCoordinateSystem > & xCooSys );\n\n    static void generateAutomaticCategoriesFromChartType(\n            ::com::sun::star::uno::Sequence< rtl::OUString >& rRet,\n            const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XChartType >\n        getChartTypeByIndex( const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram >& xDiagram, sal_Int32 nIndex );\n\n    static ::com::sun::star::uno::Sequence<\n            ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType > >\n        getChartTypesFromDiagram(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool areChartTypesCompatible( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xFirstType,\n                const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xSecondType );\n\n\n    \/**\n        * Test if a series can be moved.\n        *\n        * @param xDiagram\n        *  Reference to the diagram that contains the series.\n        *\n        * @param xGivenDataSeries\n        *  Reference to the series that should be tested for moving.\n        *\n        * @param bForward\n        *  Direction of the move to be checked.\n        *\n        * @returns <\/TRUE> if the series can be moved.\n        *\n        *\/\n    static bool isSeriesMoveable(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram,\n            const ::com::sun::star::uno::Reference<\n        ::com::sun::star::chart2::XDataSeries >& xGivenDataSeries,\n            bool bForward );\n\n    \/**\n        * Move a series forward or backward.\n        *\n        * @param xDiagram\n        *  Reference to the diagram that contains the series.\n        *\n        * @param xGivenDataSeries\n        *  Reference to the series that should be moved.\n        *\n        * @param bForward\n        *  Direction in which the series should be moved.\n        *\n        * @returns <\/TRUE> if the series was moved successfully.\n        *\n        *\/\n    static bool moveSeries(\n                const ::com::sun::star::uno::Reference<\n                  ::com::sun::star::chart2::XDiagram >& xDiagram,\n                const ::com::sun::star::uno::Reference<\n          ::com::sun::star::chart2::XDataSeries >& xGivenDataSeries,\n                bool bForward );\n\n    static sal_Int32 getIndexOfSeriesWithinChartType(\n                const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::chart2::XDataSeries >& xDataSeries,\n               const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::chart2::XChartType >& xChartType );\n\n    static bool isSupportingFloorAndWall( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram );\n\n    static bool isPieOrDonutChart( const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram >& xDiagram );\n\n    static sal_Int32 getGeometry3D(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        bool& rbFound, bool& rbAmbiguous );\n\n    static void setGeometry3D(\n        const ::com::sun::star::uno::Reference<\n            ::com::sun::star::chart2::XDiagram > & xDiagram,\n        sal_Int32 nNewGeometry );\n\n    \/\/returns integer from constant group ::com::sun::star::chart::MissingValueTreatment\n    static sal_Int32 getCorrectedMissingValueTreatment(\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XDiagram > & xDiagram,\n            const ::com::sun::star::uno::Reference<\n                ::com::sun::star::chart2::XChartType >& xChartType );\n\nprivate:\n    \/\/ not implemented\n    DiagramHelper();\n\n};\n\n} \/\/  namespace chart\n\n\/\/ CHART2_DIAGRAMHELPER_HXX\n#endif\n<|endoftext|>"}
{"text":"#include \n#include \n#include \"mud.h\"\n#include \"conf.h\"\n#include \"baseObject.h\"\n#include \"objectContainer.h\"\n#include \"entity.h\"\n#include \"serializationHelpers.h\"\n\nstd::list* ObjectContainer::GetContents()\n{\n    return &_contents;\n}\n\nbool ObjectContainer::CanReceive(Entity* obj) const\n{\n    return true;\n}\nvoid ObjectContainer::ObjectLeave(Entity* obj)\n{\n    std::list::iterator it, itEnd;\n\n    itEnd = _contents.end();\n    for (it = _contents.begin(); it != itEnd; ++it)\n        {\n            if ((*it) == obj)\n                {\n                    it = _contents.erase(it);\n                    break;\n                }\n        }\n}\nvoid ObjectContainer::ObjectEnter(Entity* obj)\n{\n    _contents.push_back(obj);\n}\n\nvoid ObjectContainer::Serialize(tinyxml2::XMLElement* root)\n{\n    tinyxml2::XMLDocument* doc = root->GetDocument();\n    tinyxml2::XMLElement* ent = doc->NewElement(\"objc\");\n    BaseObject::Serialize(ent);\n\n    SerializeList>(\"contents\", root, _contents);\n    root->InsertEndChild(ent);\n}\nvoid ObjectContainer::Deserialize(tinyxml2::XMLElement* root)\n{\n    DeserializeList>(root, \"contents\", _contents);\n    for (auto it: _contents)\n        {\n            it->SetLocation(this);\n        }\n\n    BaseObject::Deserialize(root->FirstChildElement(\"BaseObject\"));\n}\nUpdated serialization paths.#include \n#include \n#include \"mud.h\"\n#include \"conf.h\"\n#include \"baseObject.h\"\n#include \"objectContainer.h\"\n#include \"entity.h\"\n#include \"serializationHelpers.h\"\n\nstd::list* ObjectContainer::GetContents()\n{\n    return &_contents;\n}\n\nbool ObjectContainer::CanReceive(Entity* obj) const\n{\n    return true;\n}\nvoid ObjectContainer::ObjectLeave(Entity* obj)\n{\n    std::list::iterator it, itEnd;\n\n    itEnd = _contents.end();\n    for (it = _contents.begin(); it != itEnd; ++it)\n        {\n            if ((*it) == obj)\n                {\n                    it = _contents.erase(it);\n                    break;\n                }\n        }\n}\nvoid ObjectContainer::ObjectEnter(Entity* obj)\n{\n    _contents.push_back(obj);\n}\n\nvoid ObjectContainer::Serialize(tinyxml2::XMLElement* root)\n{\n    tinyxml2::XMLDocument* doc = root->GetDocument();\n    tinyxml2::XMLElement* ent = doc->NewElement(\"objc\");\n    BaseObject::Serialize(ent);\n\n    SerializeList>(\"contents\", ent, _contents);\n    root->InsertEndChild(ent);\n}\nvoid ObjectContainer::Deserialize(tinyxml2::XMLElement* root)\n{\n    DeserializeList>(root, \"contents\", _contents);\n    for (auto it: _contents)\n        {\n            it->SetLocation(this);\n        }\n\n    BaseObject::Deserialize(root->FirstChildElement(\"BaseObject\"));\n}\n<|endoftext|>"}
{"text":"\/\/  File   : SMESH_NumberFilter.cxx\n\/\/  Module : SMESH\n\n#include \"SMESH_NumberFilter.hxx\"\n\n#include \"GEOMBase.h\"\n\n#include \"SUIT_Application.h\"\n#include \"SUIT_Session.h\"\n\n#include \"SalomeApp_Study.h\"\n#include \"SalomeApp_DataOwner.h\"\n\n#include \"SALOME_InteractiveObject.hxx\"\n#include \"SALOMEDSClient_SObject.hxx\"\n#include \"SALOMEDS_SObject.hxx\"\n\n#include \n#include \n\n\/*!\n *  Class       : SMESH_NumberFilter\n *  Description : Filter for geom objects.\n *                Filter geom objects by number of subshapes of the given type\n *\/\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Constructor\n\/\/=======================================================================\nSMESH_NumberFilter::SMESH_NumberFilter (const char*            theKind,\n                                        const TopAbs_ShapeEnum theSubShapeType,\n                                        const int              theNumber,\n                                        const TopAbs_ShapeEnum theShapeType,\n                                        GEOM::GEOM_Object_ptr  theMainObj,\n                                        const bool             theIsClosedOnly)\n{\n  myKind = (char*)theKind;\n  mySubShapeType = theSubShapeType;\n  myNumber = theNumber;\n  myIsClosedOnly = theIsClosedOnly;\n  myShapeTypes.Add(theShapeType);\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Constructor\n\/\/=======================================================================\nSMESH_NumberFilter::SMESH_NumberFilter (const char*                 theKind,\n                                        const TopAbs_ShapeEnum      theSubShapeType,\n                                        const int                   theNumber,\n                                        const TColStd_MapOfInteger& theShapeTypes,\n                                        GEOM::GEOM_Object_ptr       theMainObj,\n                                        const bool                  theIsClosedOnly )\n{\n  myKind = (char*)theKind;\n  mySubShapeType = theSubShapeType;\n  myNumber = theNumber;\n  myIsClosedOnly = theIsClosedOnly;\n  myShapeTypes = theShapeTypes;\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\n\nSMESH_NumberFilter::~SMESH_NumberFilter()\n{\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Verify validity of entry object\n\/\/=======================================================================\nbool SMESH_NumberFilter::isOk (const SUIT_DataOwner* theDataOwner) const\n{\n  if (!theDataOwner)\n    return false;\n\n  \/\/ Get geom object from IO\n  GEOM::GEOM_Object_var aGeomObj = getGeom(theDataOwner);\n  if (aGeomObj->_is_nil())\n    return false;\n\n  \/\/ Get shape from geom object and verify its parameters\n  TopoDS_Shape aShape;\n  if (!GEOMBase::GetShape(aGeomObj, aShape) ||\n      aShape.IsNull() ||\n      !myShapeTypes.Contains(aShape.ShapeType()))\n    return false;\n\n  if (myIsClosedOnly && aShape.ShapeType() == TopAbs_SHELL && !aShape.Closed())\n    return false;\n\n  \/\/ Verify whether shape of entry object is sub-shape of myMainObj\n  if (!myMainObj->_is_nil()) {\n    TopoDS_Shape aMainShape;\n    if (!GEOMBase::GetShape(myMainObj, aMainShape))\n      return false;\n\n    bool isFound = false;\n    TopAbs_ShapeEnum aShapeType = aShape.ShapeType();\n    TopExp_Explorer anExp (aMainShape, aShapeType);\n    for (; anExp.More(); anExp.Next()) {\n      if (anExp.Current() == aShape) {\n        isFound = true;\n        break;\n      }\n    }\n    if (!isFound)\n      return false;\n  }\n\n  \/\/ Verify number of sub-shapes\n  if (mySubShapeType == TopAbs_SHAPE);\n    return true;\n\n  TopExp_Explorer anExp2 (aShape, mySubShapeType);\n  TopTools_MapOfShape aMap;\n  for (; anExp2.More(); anExp2.Next())\n    aMap.Add(anExp2.Current());\n\n  return myNumber == aMap.Extent();\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::getGeom\n\/\/ Purpose : Retrieve geom object from SALOME_InteractiveObject\n\/\/=======================================================================\nGEOM::GEOM_Object_ptr SMESH_NumberFilter::getGeom\n  (const SUIT_DataOwner* theDataOwner) const\n{\n  const SalomeApp_DataOwner* owner =\n    dynamic_cast(theDataOwner);\n  SalomeApp_Study* appStudy = dynamic_cast\n    (SUIT_Session::session()->activeApplication()->activeStudy());\n\n  GEOM::GEOM_Object_var anObj;\n\n  if (!owner || !appStudy)\n    return GEOM::GEOM_Object::_nil();\n\n  _PTR(Study) study = appStudy->studyDS();\n  QString entry = owner->entry();\n\n  _PTR(SObject) aSO(study->FindObjectID(entry.latin1()));\n  if (!aSO)\n    return GEOM::GEOM_Object::_nil();\n\n  CORBA::Object_var anObject = _CAST(SObject,aSO)->GetObject();\n  anObj = GEOM::GEOM_Object::_narrow(anObject);\n  if (!CORBA::is_nil(anObj))\n    return anObj._retn();\n\n  \/\/ Get geom object corresponding to the mesh\n  _PTR(ChildIterator) anIter = study->NewChildIterator(aSO);\n  for (; anIter->More(); anIter->Next()) {\n    _PTR(SObject) aSO = anIter->Value();\n    if (!aSO)\n      continue;\n    _PTR(SObject) aRefSO;\n    _PTR(SObject) anObj;\n    if (aSO->ReferencedObject(aRefSO))\n      anObj = aRefSO;\n\n    if (!anObj)\n      anObj = aSO;\n\n    anObject = _CAST(SObject,anObj)->GetObject();\n    GEOM::GEOM_Object_var aMeshShape = GEOM::GEOM_Object::_narrow(anObject);\n\n    if (!aMeshShape->_is_nil())\n      return aMeshShape._retn();\n  }\n\n  return GEOM::GEOM_Object::_nil();\n}\n\nvoid SMESH_NumberFilter::SetSubShapeType (const TopAbs_ShapeEnum theSubShapeType)\n{\n  mySubShapeType = theSubShapeType;\n}\n\nvoid SMESH_NumberFilter::SetNumber (const int theNumber)\n{\n  myNumber = theNumber;\n}\n\nvoid SMESH_NumberFilter::SetClosedOnly (const bool theIsClosedOnly)\n{\n  myIsClosedOnly = theIsClosedOnly;\n}\n\nvoid SMESH_NumberFilter::SetShapeType (const TopAbs_ShapeEnum theShapeType)\n{\n  myShapeTypes.Add( theShapeType );\n}\n\nvoid SMESH_NumberFilter::SetMainShape (GEOM::GEOM_Object_ptr theMainObj)\n{\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\nImprove NumberFilter: retrieve selected and main shape with the same instance of GEOM_Client()\/\/  File   : SMESH_NumberFilter.cxx\n\/\/  Module : SMESH\n\n#include \"SMESH_NumberFilter.hxx\"\n\n#include \"GEOM_Client.hxx\"\n#include \"GeometryGUI.h\"\n\n#include \"SUIT_Application.h\"\n#include \"SUIT_Session.h\"\n\n#include \"SalomeApp_Study.h\"\n#include \"SalomeApp_DataOwner.h\"\n\n#include \"SALOME_InteractiveObject.hxx\"\n#include \"SALOMEDSClient_SObject.hxx\"\n#include \"SALOMEDS_SObject.hxx\"\n\n#include \n#include \n\n\/*!\n *  Class       : SMESH_NumberFilter\n *  Description : Filter for geom objects.\n *                Filter geom objects by number of subshapes of the given type\n *\/\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Constructor\n\/\/=======================================================================\nSMESH_NumberFilter::SMESH_NumberFilter (const char*            theKind,\n                                        const TopAbs_ShapeEnum theSubShapeType,\n                                        const int              theNumber,\n                                        const TopAbs_ShapeEnum theShapeType,\n                                        GEOM::GEOM_Object_ptr  theMainObj,\n                                        const bool             theIsClosedOnly)\n{\n  myKind = (char*)theKind;\n  mySubShapeType = theSubShapeType;\n  myNumber = theNumber;\n  myIsClosedOnly = theIsClosedOnly;\n  myShapeTypes.Add(theShapeType);\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Constructor\n\/\/=======================================================================\nSMESH_NumberFilter::SMESH_NumberFilter (const char*                 theKind,\n                                        const TopAbs_ShapeEnum      theSubShapeType,\n                                        const int                   theNumber,\n                                        const TColStd_MapOfInteger& theShapeTypes,\n                                        GEOM::GEOM_Object_ptr       theMainObj,\n                                        const bool                  theIsClosedOnly )\n{\n  myKind = (char*)theKind;\n  mySubShapeType = theSubShapeType;\n  myNumber = theNumber;\n  myIsClosedOnly = theIsClosedOnly;\n  myShapeTypes = theShapeTypes;\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\n\nSMESH_NumberFilter::~SMESH_NumberFilter()\n{\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::SMESH_NumberFilter\n\/\/ Purpose : Verify validity of entry object\n\/\/=======================================================================\nbool SMESH_NumberFilter::isOk (const SUIT_DataOwner* theDataOwner) const\n{\n  if (!theDataOwner)\n    return false;\n\n  \/\/ Get geom object from IO\n  GEOM::GEOM_Object_var aGeomObj = getGeom(theDataOwner);\n  if (aGeomObj->_is_nil())\n    return false;\n\n  \/\/ Get shape from geom object and verify its parameters\n  GEOM_Client aGeomClient;\n  TopoDS_Shape aShape = aGeomClient.GetShape(GeometryGUI::GetGeomGen(), aGeomObj);\n  if (aShape.IsNull() ||\n      !myShapeTypes.Contains(aShape.ShapeType()))\n    return false;\n\n  if (myIsClosedOnly && aShape.ShapeType() == TopAbs_SHELL && !aShape.Closed())\n    return false;\n\n  \/\/ Verify whether shape of entry object is sub-shape of myMainObj\n  if (!myMainObj->_is_nil()) {\n    TopoDS_Shape aMainShape = aGeomClient.GetShape(GeometryGUI::GetGeomGen(), myMainObj);\n    if (aMainShape.IsNull())\n      return false;\n\n    bool isFound = false;\n    TopAbs_ShapeEnum aShapeType = aShape.ShapeType();\n    TopExp_Explorer anExp (aMainShape, aShapeType);\n    for (; anExp.More(); anExp.Next()) {\n      if (anExp.Current() == aShape) {\n        isFound = true;\n        break;\n      }\n    }\n    if (!isFound)\n      return false;\n  }\n\n  \/\/ Verify number of sub-shapes\n  if (mySubShapeType == TopAbs_SHAPE);\n    return true;\n\n  TopExp_Explorer anExp2 (aShape, mySubShapeType);\n  TopTools_MapOfShape aMap;\n  for (; anExp2.More(); anExp2.Next())\n    aMap.Add(anExp2.Current());\n\n  return myNumber == aMap.Extent();\n}\n\n\/\/=======================================================================\n\/\/ name    : SMESH_NumberFilter::getGeom\n\/\/ Purpose : Retrieve geom object from SALOME_InteractiveObject\n\/\/=======================================================================\nGEOM::GEOM_Object_ptr SMESH_NumberFilter::getGeom\n  (const SUIT_DataOwner* theDataOwner) const\n{\n  const SalomeApp_DataOwner* owner =\n    dynamic_cast(theDataOwner);\n  SalomeApp_Study* appStudy = dynamic_cast\n    (SUIT_Session::session()->activeApplication()->activeStudy());\n\n  GEOM::GEOM_Object_var anObj;\n\n  if (!owner || !appStudy)\n    return GEOM::GEOM_Object::_nil();\n\n  _PTR(Study) study = appStudy->studyDS();\n  QString entry = owner->entry();\n\n  _PTR(SObject) aSO(study->FindObjectID(entry.latin1()));\n  if (!aSO)\n    return GEOM::GEOM_Object::_nil();\n\n  CORBA::Object_var anObject = _CAST(SObject,aSO)->GetObject();\n  anObj = GEOM::GEOM_Object::_narrow(anObject);\n  if (!CORBA::is_nil(anObj))\n    return anObj._retn();\n\n  \/\/ Get geom object corresponding to the mesh\n  _PTR(ChildIterator) anIter = study->NewChildIterator(aSO);\n  for (; anIter->More(); anIter->Next()) {\n    _PTR(SObject) aSO = anIter->Value();\n    if (!aSO)\n      continue;\n    _PTR(SObject) aRefSO;\n    _PTR(SObject) anObj;\n    if (aSO->ReferencedObject(aRefSO))\n      anObj = aRefSO;\n\n    if (!anObj)\n      anObj = aSO;\n\n    anObject = _CAST(SObject,anObj)->GetObject();\n    GEOM::GEOM_Object_var aMeshShape = GEOM::GEOM_Object::_narrow(anObject);\n\n    if (!aMeshShape->_is_nil())\n      return aMeshShape._retn();\n  }\n\n  return GEOM::GEOM_Object::_nil();\n}\n\nvoid SMESH_NumberFilter::SetSubShapeType (const TopAbs_ShapeEnum theSubShapeType)\n{\n  mySubShapeType = theSubShapeType;\n}\n\nvoid SMESH_NumberFilter::SetNumber (const int theNumber)\n{\n  myNumber = theNumber;\n}\n\nvoid SMESH_NumberFilter::SetClosedOnly (const bool theIsClosedOnly)\n{\n  myIsClosedOnly = theIsClosedOnly;\n}\n\nvoid SMESH_NumberFilter::SetShapeType (const TopAbs_ShapeEnum theShapeType)\n{\n  myShapeTypes.Add( theShapeType );\n}\n\nvoid SMESH_NumberFilter::SetMainShape (GEOM::GEOM_Object_ptr theMainObj)\n{\n  myMainObj = GEOM::GEOM_Object::_duplicate(theMainObj);\n}\n<|endoftext|>"}
{"text":"\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef REALM_OS_OBJECT_ACCESSOR_HPP\n#define REALM_OS_OBJECT_ACCESSOR_HPP\n\n#include \"object.hpp\"\n\n#include \"list.hpp\"\n#include \"object_schema.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"schema.hpp\"\n#include \"util\/format.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace realm {\n\/\/\n\/\/ Value converters - template specializations must be implemented for each platform in order to call templated methods on Object\n\/\/\ntemplate\nclass NativeAccessor {\npublic:\n    static bool dict_has_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name);\n    static ValueType dict_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name);\n\n    static bool has_default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name);\n    static ValueType default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name);\n\n    static bool to_bool(ContextType, ValueType &);\n    static ValueType from_bool(ContextType, bool);\n    static long long to_long(ContextType, ValueType &);\n    static ValueType from_long(ContextType, long long);\n    static float to_float(ContextType, ValueType &);\n    static ValueType from_float(ContextType, float);\n    static double to_double(ContextType, ValueType &);\n    static ValueType from_double(ContextType, double);\n    static std::string to_string(ContextType, ValueType &);\n    static ValueType from_string(ContextType, StringData);\n    static std::string to_binary(ContextType, ValueType &);\n    static ValueType from_binary(ContextType, BinaryData);\n    static Timestamp to_timestamp(ContextType, ValueType &);\n    static ValueType from_timestamp(ContextType, Timestamp);\n\n    static bool is_null(ContextType, ValueType &);\n    static ValueType null_value(ContextType);\n\n    \/\/ convert value to persisted object\n    \/\/ for existing objects return the existing row index\n    \/\/ for new\/updated objects return the row index\n    static size_t to_object_index(ContextType ctx, SharedRealm realm, ValueType &val, const std::string &type, bool try_update);\n    static ValueType from_object(ContextType ctx, Object);\n\n    \/\/ object index for an existing object\n    static size_t to_existing_object_index(ContextType ctx, SharedRealm realm, ValueType &val);\n\n    \/\/ list value accessors\n    static size_t list_size(ContextType ctx, ValueType &val);\n    static ValueType list_value_at_index(ContextType ctx, ValueType &val, size_t index);\n    static ValueType from_list(ContextType ctx, List);\n\n    \/\/ results value accessors\n    static ValueType from_results(ContextType ctx, Results);\n\n    \/\/\n    \/\/ Deprecated\n    \/\/\n    static Mixed to_mixed(ContextType, ValueType&);\n};\n\n\/\/\n\/\/ template method implementations\n\/\/\ntemplate \nvoid Object::set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update)\n{\n    verify_attached();\n    m_realm->verify_in_write();\n    auto& property = property_for_name(prop_name);\n    if (property.is_primary)\n        throw std::logic_error(\"Cannot modify primary key after creation\");\n\n    set_property_value_impl(ctx, property, value, try_update);\n}\n\ntemplate \nValueType Object::get_property_value(ContextType ctx, std::string prop_name)\n{\n    return get_property_value_impl(ctx, property_for_name(prop_name));\n}\n\ntemplate \nvoid Object::set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update, bool is_default)\n{\n    using Accessor = NativeAccessor;\n\n    auto& table = *m_row.get_table();\n    size_t column = property.table_column;\n    size_t row = m_row.get_index();\n    if (property.is_nullable && Accessor::is_null(ctx, value)) {\n        if (property.type == PropertyType::Object) {\n            if (!is_default)\n                table.nullify_link(column, row);\n        }\n        else {\n            table.set_null(column, row, is_default);\n        }\n        return;\n    }\n\n    switch (property.type) {\n        case PropertyType::Bool:\n            table.set_bool(column, row, Accessor::to_bool(ctx, value), is_default);\n            break;\n        case PropertyType::Int:\n            table.set_int(column, row, Accessor::to_long(ctx, value), is_default);\n            break;\n        case PropertyType::Float:\n            table.set_float(column, row, Accessor::to_float(ctx, value), is_default);\n            break;\n        case PropertyType::Double:\n            table.set_double(column, row, Accessor::to_double(ctx, value), is_default);\n            break;\n        case PropertyType::String: {\n            auto str = Accessor::to_string(ctx, value);\n            table.set_string(column, row, str, is_default);\n            break;\n        }\n        case PropertyType::Data: {\n            auto data = Accessor::to_binary(ctx, value);\n            table.set_binary(column, row, BinaryData(data), is_default);\n            break;\n        }\n        case PropertyType::Any:\n            table.set_mixed(column, row, Accessor::to_mixed(ctx, value), is_default);\n            break;\n        case PropertyType::Date:\n            table.set_timestamp(column, row, Accessor::to_timestamp(ctx, value), is_default);\n            break;\n        case PropertyType::Object: {\n            table.set_link(column, row, Accessor::to_object_index(ctx, m_realm, value, property.object_type, try_update), is_default);\n            break;\n        }\n        case PropertyType::Array: {\n            LinkViewRef link_view = m_row.get_linklist(column);\n            link_view->clear();\n            if (!Accessor::is_null(ctx, value)) {\n                size_t count = Accessor::list_size(ctx, value);\n                for (size_t i = 0; i < count; i++) {\n                    ValueType element = Accessor::list_value_at_index(ctx, value, i);\n                    link_view->add(Accessor::to_object_index(ctx, m_realm, element, property.object_type, try_update));\n                }\n            }\n            break;\n        }\n        case PropertyType::LinkingObjects:\n            throw ReadOnlyPropertyException(m_object_schema->name, property.name);\n    }\n}\n\ntemplate \nValueType Object::get_property_value_impl(ContextType ctx, const Property &property)\n{\n    verify_attached();\n\n    using Accessor = NativeAccessor;\n\n    size_t column = property.table_column;\n    if (property.is_nullable && m_row.is_null(column)) {\n        return Accessor::null_value(ctx);\n    }\n\n    switch (property.type) {\n        case PropertyType::Bool:\n            return Accessor::from_bool(ctx, m_row.get_bool(column));\n        case PropertyType::Int:\n            return Accessor::from_long(ctx, m_row.get_int(column));\n        case PropertyType::Float:\n            return Accessor::from_float(ctx, m_row.get_float(column));\n        case PropertyType::Double:\n            return Accessor::from_double(ctx, m_row.get_double(column));\n        case PropertyType::String:\n            return Accessor::from_string(ctx, m_row.get_string(column));\n        case PropertyType::Data:\n            return Accessor::from_binary(ctx, m_row.get_binary(column));\n        case PropertyType::Any:\n            throw \"Any not supported\";\n        case PropertyType::Date:\n            return Accessor::from_timestamp(ctx, m_row.get_timestamp(column));\n        case PropertyType::Object: {\n            auto linkObjectSchema = m_realm->schema().find(property.object_type);\n            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), linkObjectSchema->name);\n            return Accessor::from_object(ctx, Object(m_realm, *linkObjectSchema, table->get(m_row.get_link(column))));\n        }\n        case PropertyType::Array:\n            return Accessor::from_list(ctx, List(m_realm, m_row.get_linklist(column)));\n        case PropertyType::LinkingObjects: {\n            auto target_object_schema = m_realm->schema().find(property.object_type);\n            auto link_property = target_object_schema->property_for_name(property.link_origin_property_name);\n            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), target_object_schema->name);\n            auto tv = m_row.get_table()->get_backlink_view(m_row.get_index(), table.get(), link_property->table_column);\n            return Accessor::from_results(ctx, Results(m_realm, std::move(tv)));\n        }\n    }\n    REALM_UNREACHABLE();\n}\n\ntemplate\nObject Object::create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update)\n{\n    realm->verify_in_write();\n\n    using Accessor = NativeAccessor;\n\n    \/\/ get or create our accessor\n    bool created = false;\n\n    \/\/ try to get existing row if updating\n    size_t row_index = realm::not_found;\n    realm::TableRef table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name);\n\n    if (auto primary_prop = object_schema.primary_key_property()) {\n        \/\/ search for existing object based on primary key type\n        ValueType primary_value = Accessor::dict_value_for_key(ctx, value, object_schema.primary_key);\n        row_index = get_for_primary_key_impl(ctx, *table, *primary_prop, primary_value);\n\n        if (row_index == realm::not_found) {\n            row_index = table->add_empty_row();\n            created = true;\n            if (primary_prop->type == PropertyType::Int)\n                table->set_int_unique(primary_prop->table_column, row_index, Accessor::to_long(ctx, primary_value));\n            else if (primary_prop->type == PropertyType::String) {\n                auto value = Accessor::to_string(ctx, primary_value);\n                table->set_string_unique(primary_prop->table_column, row_index, value);\n            }\n            else\n                REALM_UNREACHABLE();\n        }\n        else if (!try_update) {\n            throw std::logic_error(util::format(\"Attempting to create an object of type '%1' with an existing primary key value.\", object_schema.name));\n        }\n    }\n    else {\n        row_index = table->add_empty_row();\n        created = true;\n    }\n\n    \/\/ populate\n    Object object(realm, object_schema, table->get(row_index));\n    for (const Property& prop : object_schema.persisted_properties) {\n        if (prop.is_primary)\n            continue;\n\n        if (Accessor::dict_has_value_for_key(ctx, value, prop.name)) {\n            object.set_property_value_impl(ctx, prop, Accessor::dict_value_for_key(ctx, value, prop.name), try_update);\n        }\n        else if (created) {\n            if (Accessor::has_default_value_for_property(ctx, realm.get(), object_schema, prop.name)) {\n                object.set_property_value_impl(ctx, prop, Accessor::default_value_for_property(ctx, realm.get(), object_schema, prop.name), try_update, true);\n            }\n            else if (prop.is_nullable || prop.type == PropertyType::Array) {\n                object.set_property_value_impl(ctx, prop, Accessor::null_value(ctx), try_update);\n            }\n            else {\n                throw MissingPropertyValueException(object_schema.name, prop.name);\n            }\n        }\n    }\n    return object;\n}\n\ntemplate\nObject Object::get_for_primary_key(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType primary_value)\n{\n    auto primary_prop = object_schema.primary_key_property();\n    if (!primary_prop) {\n        throw MissingPrimaryKeyException(object_schema.name);\n    }\n\n    auto table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name);\n    auto row_index = get_for_primary_key_impl(ctx, *table, *primary_prop, primary_value);\n\n    return Object(realm, object_schema, row_index == realm::not_found ? Row() : table->get(row_index));\n}\n\ntemplate\nsize_t Object::get_for_primary_key_impl(ContextType ctx, Table const& table, const Property &primary_prop, ValueType primary_value) {\n    using Accessor = NativeAccessor;\n\n    if (primary_prop.type == PropertyType::String) {\n        auto primary_string = Accessor::to_string(ctx, primary_value);\n        return table.find_first_string(primary_prop.table_column, primary_string);\n    }\n    else {\n        return table.find_first_int(primary_prop.table_column, Accessor::to_long(ctx, primary_value));\n    }\n}\n\n\/\/\n\/\/ List implementation\n\/\/\ntemplate\nvoid List::add(ContextType ctx, ValueType value)\n{\n    add(NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n\ntemplate\nvoid List::insert(ContextType ctx, ValueType value, size_t list_ndx)\n{\n    insert(list_ndx, NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n\ntemplate\nvoid List::set(ContextType ctx, ValueType value, size_t list_ndx)\n{\n    set(list_ndx, NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n} \/\/ namespace realm\n\n#endif \/* defined(REALM_OS_OBJECT_ACCESSOR_HPP) *\/\nProperly update according to change in core\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef REALM_OS_OBJECT_ACCESSOR_HPP\n#define REALM_OS_OBJECT_ACCESSOR_HPP\n\n#include \"object.hpp\"\n\n#include \"list.hpp\"\n#include \"object_schema.hpp\"\n#include \"object_store.hpp\"\n#include \"results.hpp\"\n#include \"schema.hpp\"\n#include \"util\/format.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace realm {\n\/\/\n\/\/ Value converters - template specializations must be implemented for each platform in order to call templated methods on Object\n\/\/\ntemplate\nclass NativeAccessor {\npublic:\n    static bool dict_has_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name);\n    static ValueType dict_value_for_key(ContextType ctx, ValueType dict, const std::string &prop_name);\n\n    static bool has_default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name);\n    static ValueType default_value_for_property(ContextType ctx, Realm *realm, const ObjectSchema &object_schema, const std::string &prop_name);\n\n    static bool to_bool(ContextType, ValueType &);\n    static ValueType from_bool(ContextType, bool);\n    static long long to_long(ContextType, ValueType &);\n    static ValueType from_long(ContextType, long long);\n    static float to_float(ContextType, ValueType &);\n    static ValueType from_float(ContextType, float);\n    static double to_double(ContextType, ValueType &);\n    static ValueType from_double(ContextType, double);\n    static std::string to_string(ContextType, ValueType &);\n    static ValueType from_string(ContextType, StringData);\n    static std::string to_binary(ContextType, ValueType &);\n    static ValueType from_binary(ContextType, BinaryData);\n    static Timestamp to_timestamp(ContextType, ValueType &);\n    static ValueType from_timestamp(ContextType, Timestamp);\n\n    static bool is_null(ContextType, ValueType &);\n    static ValueType null_value(ContextType);\n\n    \/\/ convert value to persisted object\n    \/\/ for existing objects return the existing row index\n    \/\/ for new\/updated objects return the row index\n    static size_t to_object_index(ContextType ctx, SharedRealm realm, ValueType &val, const std::string &type, bool try_update);\n    static ValueType from_object(ContextType ctx, Object);\n\n    \/\/ object index for an existing object\n    static size_t to_existing_object_index(ContextType ctx, SharedRealm realm, ValueType &val);\n\n    \/\/ list value accessors\n    static size_t list_size(ContextType ctx, ValueType &val);\n    static ValueType list_value_at_index(ContextType ctx, ValueType &val, size_t index);\n    static ValueType from_list(ContextType ctx, List);\n\n    \/\/ results value accessors\n    static ValueType from_results(ContextType ctx, Results);\n\n    \/\/\n    \/\/ Deprecated\n    \/\/\n    static Mixed to_mixed(ContextType, ValueType&);\n};\n\n\/\/\n\/\/ template method implementations\n\/\/\ntemplate \nvoid Object::set_property_value(ContextType ctx, std::string prop_name, ValueType value, bool try_update)\n{\n    verify_attached();\n    m_realm->verify_in_write();\n    auto& property = property_for_name(prop_name);\n    if (property.is_primary)\n        throw std::logic_error(\"Cannot modify primary key after creation\");\n\n    set_property_value_impl(ctx, property, value, try_update);\n}\n\ntemplate \nValueType Object::get_property_value(ContextType ctx, std::string prop_name)\n{\n    return get_property_value_impl(ctx, property_for_name(prop_name));\n}\n\ntemplate \nvoid Object::set_property_value_impl(ContextType ctx, const Property &property, ValueType value, bool try_update, bool is_default)\n{\n    using Accessor = NativeAccessor;\n\n    auto& table = *m_row.get_table();\n    size_t column = property.table_column;\n    size_t row = m_row.get_index();\n    if (property.is_nullable && Accessor::is_null(ctx, value)) {\n        if (property.type == PropertyType::Object) {\n            if (!is_default)\n                table.nullify_link(column, row);\n        }\n        else {\n            table.set_null(column, row, is_default);\n        }\n        return;\n    }\n\n    switch (property.type) {\n        case PropertyType::Bool:\n            table.set_bool(column, row, Accessor::to_bool(ctx, value), is_default);\n            break;\n        case PropertyType::Int:\n            table.set_int(column, row, Accessor::to_long(ctx, value), is_default);\n            break;\n        case PropertyType::Float:\n            table.set_float(column, row, Accessor::to_float(ctx, value), is_default);\n            break;\n        case PropertyType::Double:\n            table.set_double(column, row, Accessor::to_double(ctx, value), is_default);\n            break;\n        case PropertyType::String: {\n            auto str = Accessor::to_string(ctx, value);\n            table.set_string(column, row, str, is_default);\n            break;\n        }\n        case PropertyType::Data: {\n            auto data = Accessor::to_binary(ctx, value);\n            table.set_binary(column, row, BinaryData(data), is_default);\n            break;\n        }\n        case PropertyType::Any:\n            table.set_mixed(column, row, Accessor::to_mixed(ctx, value), is_default);\n            break;\n        case PropertyType::Date:\n            table.set_timestamp(column, row, Accessor::to_timestamp(ctx, value), is_default);\n            break;\n        case PropertyType::Object: {\n            table.set_link(column, row, Accessor::to_object_index(ctx, m_realm, value, property.object_type, try_update), is_default);\n            break;\n        }\n        case PropertyType::Array: {\n            LinkViewRef link_view = m_row.get_linklist(column);\n            link_view->clear();\n            if (!Accessor::is_null(ctx, value)) {\n                size_t count = Accessor::list_size(ctx, value);\n                for (size_t i = 0; i < count; i++) {\n                    ValueType element = Accessor::list_value_at_index(ctx, value, i);\n                    link_view->add(Accessor::to_object_index(ctx, m_realm, element, property.object_type, try_update));\n                }\n            }\n            break;\n        }\n        case PropertyType::LinkingObjects:\n            throw ReadOnlyPropertyException(m_object_schema->name, property.name);\n    }\n}\n\ntemplate \nValueType Object::get_property_value_impl(ContextType ctx, const Property &property)\n{\n    verify_attached();\n\n    using Accessor = NativeAccessor;\n\n    size_t column = property.table_column;\n    if (property.is_nullable && m_row.is_null(column)) {\n        return Accessor::null_value(ctx);\n    }\n\n    switch (property.type) {\n        case PropertyType::Bool:\n            return Accessor::from_bool(ctx, m_row.get_bool(column));\n        case PropertyType::Int:\n            return Accessor::from_long(ctx, m_row.get_int(column));\n        case PropertyType::Float:\n            return Accessor::from_float(ctx, m_row.get_float(column));\n        case PropertyType::Double:\n            return Accessor::from_double(ctx, m_row.get_double(column));\n        case PropertyType::String:\n            return Accessor::from_string(ctx, m_row.get_string(column));\n        case PropertyType::Data:\n            return Accessor::from_binary(ctx, m_row.get_binary(column));\n        case PropertyType::Any:\n            throw \"Any not supported\";\n        case PropertyType::Date:\n            return Accessor::from_timestamp(ctx, m_row.get_timestamp(column));\n        case PropertyType::Object: {\n            auto linkObjectSchema = m_realm->schema().find(property.object_type);\n            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), linkObjectSchema->name);\n            return Accessor::from_object(ctx, Object(m_realm, *linkObjectSchema, table->get(m_row.get_link(column))));\n        }\n        case PropertyType::Array:\n            return Accessor::from_list(ctx, List(m_realm, m_row.get_linklist(column)));\n        case PropertyType::LinkingObjects: {\n            auto target_object_schema = m_realm->schema().find(property.object_type);\n            auto link_property = target_object_schema->property_for_name(property.link_origin_property_name);\n            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), target_object_schema->name);\n            auto tv = m_row.get_table()->get_backlink_view(m_row.get_index(), table.get(), link_property->table_column);\n            return Accessor::from_results(ctx, Results(m_realm, std::move(tv)));\n        }\n    }\n    REALM_UNREACHABLE();\n}\n\ntemplate\nObject Object::create(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType value, bool try_update)\n{\n    realm->verify_in_write();\n\n    using Accessor = NativeAccessor;\n\n    \/\/ get or create our accessor\n    bool created = false;\n\n    \/\/ try to get existing row if updating\n    size_t row_index = realm::not_found;\n    realm::TableRef table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name);\n\n    if (auto primary_prop = object_schema.primary_key_property()) {\n        \/\/ search for existing object based on primary key type\n        ValueType primary_value = Accessor::dict_value_for_key(ctx, value, object_schema.primary_key);\n        row_index = get_for_primary_key_impl(ctx, *table, *primary_prop, primary_value);\n\n        if (row_index == realm::not_found) {\n            row_index = table->add_empty_row();\n            created = true;\n            if (primary_prop->type == PropertyType::Int)\n                table->set_int_unique(primary_prop->table_column, row_index, Accessor::to_long(ctx, primary_value));\n            else if (primary_prop->type == PropertyType::String) {\n                auto value = Accessor::to_string(ctx, primary_value);\n                table->set_string_unique(primary_prop->table_column, row_index, value);\n            }\n            else\n                REALM_UNREACHABLE();\n        }\n        else if (!try_update) {\n            throw std::logic_error(util::format(\"Attempting to create an object of type '%1' with an existing primary key value.\", object_schema.name));\n        }\n    }\n    else {\n        row_index = table->add_empty_row();\n        created = true;\n    }\n\n    \/\/ populate\n    Object object(realm, object_schema, table->get(row_index));\n    for (const Property& prop : object_schema.persisted_properties) {\n        if (prop.is_primary)\n            continue;\n\n        if (Accessor::dict_has_value_for_key(ctx, value, prop.name)) {\n            object.set_property_value_impl(ctx, prop, Accessor::dict_value_for_key(ctx, value, prop.name), try_update);\n        }\n        else if (created) {\n            if (Accessor::has_default_value_for_property(ctx, realm.get(), object_schema, prop.name)) {\n                object.set_property_value_impl(ctx, prop, Accessor::default_value_for_property(ctx, realm.get(), object_schema, prop.name), try_update, true);\n            }\n            else if (prop.is_nullable || prop.type == PropertyType::Array) {\n                object.set_property_value_impl(ctx, prop, Accessor::null_value(ctx), try_update);\n            }\n            else {\n                throw MissingPropertyValueException(object_schema.name, prop.name);\n            }\n        }\n    }\n    return object;\n}\n\ntemplate\nObject Object::get_for_primary_key(ContextType ctx, SharedRealm realm, const ObjectSchema &object_schema, ValueType primary_value)\n{\n    auto primary_prop = object_schema.primary_key_property();\n    if (!primary_prop) {\n        throw MissingPrimaryKeyException(object_schema.name);\n    }\n\n    auto table = ObjectStore::table_for_object_type(realm->read_group(), object_schema.name);\n    auto row_index = get_for_primary_key_impl(ctx, *table, *primary_prop, primary_value);\n\n    return Object(realm, object_schema, row_index == realm::not_found ? Row() : Row(table->get(row_index)));\n}\n\ntemplate\nsize_t Object::get_for_primary_key_impl(ContextType ctx, Table const& table, const Property &primary_prop, ValueType primary_value) {\n    using Accessor = NativeAccessor;\n\n    if (primary_prop.type == PropertyType::String) {\n        auto primary_string = Accessor::to_string(ctx, primary_value);\n        return table.find_first_string(primary_prop.table_column, primary_string);\n    }\n    else {\n        return table.find_first_int(primary_prop.table_column, Accessor::to_long(ctx, primary_value));\n    }\n}\n\n\/\/\n\/\/ List implementation\n\/\/\ntemplate\nvoid List::add(ContextType ctx, ValueType value)\n{\n    add(NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n\ntemplate\nvoid List::insert(ContextType ctx, ValueType value, size_t list_ndx)\n{\n    insert(list_ndx, NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n\ntemplate\nvoid List::set(ContextType ctx, ValueType value, size_t list_ndx)\n{\n    set(list_ndx, NativeAccessor::to_object_index(ctx, m_realm, value, get_object_schema().name, false));\n}\n} \/\/ namespace realm\n\n#endif \/* defined(REALM_OS_OBJECT_ACCESSOR_HPP) *\/\n<|endoftext|>"}
{"text":"#include \"spline.hpp\"\n\nnamespace m2\n{\n\nSpline::Spline(vector const & path)\n{\n  ASSERT(path.size() > 1, (\"Wrong path size!\"));\n  m_position.assign(path.begin(), path.end());\n  int cnt = m_position.size() - 1;\n  m_direction = vector(cnt);\n  m_length = vector(cnt);\n\n  for(int i = 0; i < cnt; ++i)\n  {\n    m_direction[i] = path[i+1] - path[i];\n    m_length[i] = m_direction[i].Length();\n    m_direction[i] = m_direction[i].Normalize();\n    m_lengthAll += m_length[i];\n  }\n}\n\nvoid Spline::AddPoint(PointF const & pt)\n{\n  if(m_position.empty())\n    m_position.push_back(pt);\n  else\n  {\n    PointF dir = pt - m_position.back();\n    m_position.push_back(pt);\n    m_direction.push_back(dir.Normalize());\n    m_length.push_back(dir.Length());\n    m_lengthAll += m_length.back();\n  }\n}\n\nSpline const & Spline::operator = (Spline const & spl)\n{\n  if(&spl != this)\n  {\n    m_lengthAll = spl.m_lengthAll;\n    m_position = spl.m_position;\n    m_direction = spl.m_direction;\n    m_length = spl.m_length;\n  }\n  return *this;\n}\n\nSpline::iterator::iterator()\n  : m_checker(false)\n  , m_spl(NULL)\n  , m_index(0)\n  , m_dist(0) {}\n\nvoid Spline::iterator::Attach(Spline const & S)\n{\n  m_spl = &S;\n  m_index = 0;\n  m_dist = 0;\n  m_checker = false;\n  m_dir = m_spl->m_direction[m_index];\n  m_avrDir = m_spl->m_direction[m_index];\n  m_pos = m_spl->m_position[m_index] + m_dir * m_dist;\n}\n\nvoid Spline::iterator::Step(float speed)\n{\n  m_dist += speed;\n  while(m_dist > m_spl->m_length[m_index])\n  {\n    m_dist -= m_spl->m_length[m_index];\n    m_index++;\n    if(m_index >= m_spl->m_direction.size())\n    {\n      m_index = 0;\n      m_checker = true;\n    }\n  }\n  m_dir = m_spl->m_direction[m_index];\n  m_avrDir = -m_pos;\n  m_pos = m_spl->m_position[m_index] + m_dir * m_dist;\n  m_avrDir += m_pos;\n}\n\nbool Spline::iterator::BeginAgain()\n{\n  return m_checker;\n}\n\nSharedSpline::SharedSpline(vector const & path)\n{\n  m_spline.reset(new Spline(path));\n}\n\nSharedSpline::SharedSpline(SharedSpline const & other)\n{\n  if (this != &other)\n    m_spline = other.m_spline;\n}\n\nSharedSpline const & SharedSpline::operator= (SharedSpline const & spl)\n{\n  if (this != &spl)\n    m_spline = spl.m_spline;\n  return *this;\n}\n\nfloat SharedSpline::GetLength() const\n{\n  return m_spline->GetLength();\n}\n\nSpline::iterator SharedSpline::CreateIterator()\n{\n  Spline::iterator result;\n  result.Attach(*m_spline.get());\n  return result;\n}\n\n}\n\nsmall fix#include \"spline.hpp\"\n\nnamespace m2\n{\n\nSpline::Spline(vector const & path) : m_lengthAll(0.0f)\n{\n  ASSERT(path.size() > 1, (\"Wrong path size!\"));\n  m_position.assign(path.begin(), path.end());\n  int cnt = m_position.size() - 1;\n  m_direction = vector(cnt);\n  m_length = vector(cnt);\n\n  for(int i = 0; i < cnt; ++i)\n  {\n    m_direction[i] = path[i+1] - path[i];\n    m_length[i] = m_direction[i].Length();\n    m_direction[i] = m_direction[i].Normalize();\n    m_lengthAll += m_length[i];\n  }\n}\n\nvoid Spline::AddPoint(PointF const & pt)\n{\n  if(m_position.empty())\n    m_position.push_back(pt);\n  else\n  {\n    PointF dir = pt - m_position.back();\n    m_position.push_back(pt);\n    m_length.push_back(dir.Length());\n    m_direction.push_back(dir.Normalize());\n    m_lengthAll += m_length.back();\n  }\n}\n\nSpline const & Spline::operator = (Spline const & spl)\n{\n  if(&spl != this)\n  {\n    m_lengthAll = spl.m_lengthAll;\n    m_position = spl.m_position;\n    m_direction = spl.m_direction;\n    m_length = spl.m_length;\n  }\n  return *this;\n}\n\nSpline::iterator::iterator()\n  : m_checker(false)\n  , m_spl(NULL)\n  , m_index(0)\n  , m_dist(0) {}\n\nvoid Spline::iterator::Attach(Spline const & S)\n{\n  m_spl = &S;\n  m_index = 0;\n  m_dist = 0;\n  m_checker = false;\n  m_dir = m_spl->m_direction[m_index];\n  m_avrDir = m_spl->m_direction[m_index];\n  m_pos = m_spl->m_position[m_index] + m_dir * m_dist;\n}\n\nvoid Spline::iterator::Step(float speed)\n{\n  m_dist += speed;\n  while(m_dist > m_spl->m_length[m_index])\n  {\n    m_dist -= m_spl->m_length[m_index];\n    m_index++;\n    if(m_index >= m_spl->m_direction.size())\n    {\n      m_index = 0;\n      m_checker = true;\n    }\n  }\n  m_dir = m_spl->m_direction[m_index];\n  m_avrDir = -m_pos;\n  m_pos = m_spl->m_position[m_index] + m_dir * m_dist;\n  m_avrDir += m_pos;\n}\n\nbool Spline::iterator::BeginAgain()\n{\n  return m_checker;\n}\n\nSharedSpline::SharedSpline(vector const & path)\n{\n  m_spline.reset(new Spline(path));\n}\n\nSharedSpline::SharedSpline(SharedSpline const & other)\n{\n  if (this != &other)\n    m_spline = other.m_spline;\n}\n\nSharedSpline const & SharedSpline::operator= (SharedSpline const & spl)\n{\n  if (this != &spl)\n    m_spline = spl.m_spline;\n  return *this;\n}\n\nfloat SharedSpline::GetLength() const\n{\n  return m_spline->GetLength();\n}\n\nSpline::iterator SharedSpline::CreateIterator()\n{\n  Spline::iterator result;\n  result.Attach(*m_spline.get());\n  return result;\n}\n\n}\n\n<|endoftext|>"}
{"text":"#pragma once\n\n#include \"threaded_list.hpp\"\n#include \"logging.hpp\"\n#include \"..\/std\/bind.hpp\"\n#include \"..\/std\/scoped_ptr.hpp\"\n\nstruct BasePoolElemFactory\n{\n  string m_resName;\n  size_t m_elemSize;\n  size_t m_batchSize;\n\n  BasePoolElemFactory(char const * resName, size_t elemSize, size_t batchSize);\n\n  size_t BatchSize() const;\n  char const * ResName() const;\n  size_t ElemSize() const;\n};\n\n\/\/\/ basic traits maintains a list of free resources.\ntemplate \nstruct BasePoolTraits\n{\n  TElemFactory m_factory;\n  ThreadedList m_pool;\n  bool m_IsDebugging;\n\n  typedef TElem elem_t;\n\n  BasePoolTraits(TElemFactory const & factory)\n    : m_factory(factory), m_IsDebugging(false)\n  {\n    m_pool.SetName(factory.ResName());\n  }\n\n  virtual ~BasePoolTraits()\n  {}\n\n  virtual void Init()\n  {\n    Free(Reserve());\n  }\n\n  virtual void Free(TElem const & elem)\n  {\n    m_pool.PushBack(elem);\n  }\n\n  virtual TElem const Reserve()\n  {\n    return m_pool.Front(true);\n  }\n\n  virtual size_t Size() const\n  {\n    return m_pool.Size();\n  }\n\n  virtual void Cancel()\n  {\n    m_pool.Cancel();\n  }\n\n  virtual bool IsCancelled() const\n  {\n    return m_pool.IsCancelled();\n  }\n\n  virtual void UpdateState()\n  {\n  }\n};\n\n\/\/\/ This traits stores the free elements in a separate pool and has\n\/\/\/ a separate method to merge them all into a main pool.\n\/\/\/ For example should be used for resources where a certain preparation operation\n\/\/\/ should be performed on main thread before returning resource\n\/\/\/ to a free pool(p.e. @see resource_manager.cpp StorageFactory)\ntemplate \nstruct SeparateFreePoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n\n  ThreadedList m_freePool;\n  int m_maxFreePoolSize;\n\n  SeparateFreePoolTraits(TElemFactory const & factory)\n    : base_t(factory), m_maxFreePoolSize(0)\n  {}\n\n  void Free(elem_t const & elem)\n  {\n    m_freePool.PushBack(elem);\n\/*    if (base_t::m_IsDebugging)\n    {\n      int oldMaxFreePoolSize = m_maxFreePoolSize;\n      m_maxFreePoolSize = max(m_maxFreePoolSize, (int)m_freePool.Size());\n      if (oldMaxFreePoolSize != m_maxFreePoolSize)\n        LOG(LINFO, (base_t::m_pool.GetName(), \"freePool maximum size has reached\", m_maxFreePoolSize, \"elements\"));\n    }*\/\n  }\n\n  void UpdateStateImpl(list & l)\n  {\n    for (typename list::const_iterator it = l.begin();\n         it != l.end();\n         ++it)\n    {\n      base_t::m_factory.BeforeMerge(*it);\n      base_t::m_pool.PushBack(*it);\n    }\n\n\/\/    if ((base_t::m_IsDebugging) && (!base_t::m_pool.GetName().empty()))\n\/\/      LOG(LINFO, (\"pool for\", base_t::m_pool.GetName(), \"has\", base_t::m_pool.Size(), \"elements\"));\n\n    l.clear();\n  }\n\n  void UpdateState()\n  {\n    m_freePool.ProcessList(bind(&SeparateFreePoolTraits::UpdateStateImpl, this, _1));\n  }\n};\n\n\/\/\/ This traits maintains a fixed-size of pre-allocated resources.\ntemplate \nstruct FixedSizePoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n\n  size_t m_count;\n  bool m_isAllocated;\n\n  FixedSizePoolTraits(TElemFactory const & factory, size_t count)\n    : base_t(factory),\n      m_count(count),\n      m_isAllocated(false)\n  {}\n\n  elem_t const Reserve()\n  {\n    if (!m_isAllocated)\n    {\n      m_isAllocated = true;\n\n      LOG(LDEBUG, (\"allocating \", base_t::m_factory.ElemSize() * m_count, \"bytes for \", base_t::m_factory.ResName()));\n\n      for (size_t i = 0; i < m_count; ++i)\n        base_t::m_pool.PushBack(base_t::m_factory.Create());\n    }\n\n    return base_t::Reserve();\n  }\n};\n\n\/\/\/ This traits allocates resources on demand.\ntemplate \nstruct AllocateOnDemandMultiThreadedPoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n  typedef AllocateOnDemandMultiThreadedPoolTraits self_t;\n\n  size_t m_poolSize;\n  AllocateOnDemandMultiThreadedPoolTraits(TElemFactory const & factory, size_t )\n    : base_t(factory),\n      m_poolSize(0)\n  {}\n\n  void AllocateIfNeeded(list & l)\n  {\n    if (l.empty())\n    {\n      m_poolSize += base_t::m_factory.ElemSize() * base_t::m_factory.BatchSize();\n      LOG(LDEBUG, (\"allocating \", base_t::m_factory.ElemSize(), \"bytes for \", base_t::m_factory.ResName(), \" on-demand, poolSize=\", m_poolSize \/ base_t::m_factory.ElemSize(), \", totalMemory=\", m_poolSize));\n      for (unsigned i = 0; i < base_t::m_factory.BatchSize(); ++i)\n        l.push_back(base_t::m_factory.Create());\n    }\n  }\n\n  elem_t const Reserve()\n  {\n    base_t::m_pool.ProcessList(bind(&self_t::AllocateIfNeeded, this, _1));\n    return base_t::Reserve();\n  }\n};\n\ntemplate \nstruct AllocateOnDemandSingleThreadedPoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename TBase::elem_t elem_t;\n  typedef AllocateOnDemandSingleThreadedPoolTraits self_t;\n\n  size_t m_poolSize;\n  AllocateOnDemandSingleThreadedPoolTraits(TElemFactory const & factory, size_t )\n    : base_t(factory),\n      m_poolSize(0)\n  {}\n\n  void Init()\n  {}\n\n  void AllocateIfNeeded(list & l)\n  {\n    if (l.empty())\n    {\n      m_poolSize += base_t::m_factory.ElemSize() * base_t::m_factory.BatchSize();\n      LOG(LDEBUG, (\"allocating\", base_t::m_factory.BatchSize(), \"elements for \", base_t::m_factory.ResName(), \"on-demand, poolSize=\", m_poolSize \/ base_t::m_factory.ElemSize(), \", totalMemory=\", m_poolSize));\n      for (unsigned i = 0; i < base_t::m_factory.BatchSize(); ++i)\n        l.push_back(base_t::m_factory.Create());\n    }\n  }\n\n  void UpdateState()\n  {\n    base_t::UpdateState();\n    base_t::m_pool.ProcessList(bind(&self_t::AllocateIfNeeded, this, _1));\n  }\n};\n\n\/\/\/ resource pool interface\ntemplate \nclass ResourcePool\n{\npublic:\n  virtual ~ResourcePool(){}\n  virtual TElem const Reserve() = 0;\n  virtual void Free(TElem const & elem) = 0;\n  virtual size_t Size() const = 0;\n  virtual void EnterForeground() = 0;\n  virtual void EnterBackground() = 0;\n  virtual void Cancel() = 0;\n  virtual bool IsCancelled() const = 0;\n  virtual void UpdateState() = 0;\n  virtual void SetIsDebugging(bool flag) = 0;\n};\n\n\/\/ This class tracks OpenGL resources allocation in\n\/\/ a multithreaded environment.\ntemplate \nclass ResourcePoolImpl : public ResourcePool\n{\nprivate:\n\n  scoped_ptr m_traits;\n\npublic:\n\n  typedef typename TPoolTraits::elem_t elem_t;\n\n  ResourcePoolImpl(TPoolTraits * traits)\n    : m_traits(traits)\n  {\n    \/\/\/ quick trick to perform lazy initialization\n    \/\/\/ on the same thread the pool was created.\n    m_traits->Init();\n  }\n\n  elem_t const Reserve()\n  {\n    return m_traits->Reserve();\n  }\n\n  void Free(elem_t const & elem)\n  {\n    m_traits->Free(elem);\n  }\n\n  size_t Size() const\n  {\n    return m_traits->Size();\n  }\n\n  void EnterForeground()\n  {}\n\n  void EnterBackground()\n  {}\n\n  void Cancel()\n  {\n    return m_traits->Cancel();\n  }\n\n  bool IsCancelled() const\n  {\n    return m_traits->IsCancelled();\n  }\n\n  void UpdateState()\n  {\n    m_traits->UpdateState();\n  }\n\n  void SetIsDebugging(bool isDebugging)\n  {\n    m_traits->m_IsDebugging = isDebugging;\n  }\n};\nadded ResourcePool::ResName for the purpose of logging.#pragma once\n\n#include \"threaded_list.hpp\"\n#include \"logging.hpp\"\n#include \"..\/std\/bind.hpp\"\n#include \"..\/std\/scoped_ptr.hpp\"\n\nstruct BasePoolElemFactory\n{\n  string m_resName;\n  size_t m_elemSize;\n  size_t m_batchSize;\n\n  BasePoolElemFactory(char const * resName, size_t elemSize, size_t batchSize);\n\n  size_t BatchSize() const;\n  char const * ResName() const;\n  size_t ElemSize() const;\n};\n\n\/\/\/ basic traits maintains a list of free resources.\ntemplate \nstruct BasePoolTraits\n{\n  TElemFactory m_factory;\n  ThreadedList m_pool;\n  bool m_IsDebugging;\n\n  typedef TElem elem_t;\n\n  BasePoolTraits(TElemFactory const & factory)\n    : m_factory(factory), m_IsDebugging(false)\n  {\n    m_pool.SetName(factory.ResName());\n  }\n\n  virtual ~BasePoolTraits()\n  {}\n\n  virtual void Init()\n  {\n    Free(Reserve());\n  }\n\n  virtual void Free(TElem const & elem)\n  {\n    m_pool.PushBack(elem);\n  }\n\n  virtual TElem const Reserve()\n  {\n    return m_pool.Front(true);\n  }\n\n  virtual size_t Size() const\n  {\n    return m_pool.Size();\n  }\n\n  virtual void Cancel()\n  {\n    m_pool.Cancel();\n  }\n\n  virtual bool IsCancelled() const\n  {\n    return m_pool.IsCancelled();\n  }\n\n  virtual void UpdateState()\n  {\n  }\n\n  char const * ResName() const\n  {\n    return m_factory.ResName();\n  }\n};\n\n\/\/\/ This traits stores the free elements in a separate pool and has\n\/\/\/ a separate method to merge them all into a main pool.\n\/\/\/ For example should be used for resources where a certain preparation operation\n\/\/\/ should be performed on main thread before returning resource\n\/\/\/ to a free pool(p.e. @see resource_manager.cpp StorageFactory)\ntemplate \nstruct SeparateFreePoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n\n  ThreadedList m_freePool;\n  int m_maxFreePoolSize;\n\n  SeparateFreePoolTraits(TElemFactory const & factory)\n    : base_t(factory), m_maxFreePoolSize(0)\n  {}\n\n  void Free(elem_t const & elem)\n  {\n    m_freePool.PushBack(elem);\n\/*    if (base_t::m_IsDebugging)\n    {\n      int oldMaxFreePoolSize = m_maxFreePoolSize;\n      m_maxFreePoolSize = max(m_maxFreePoolSize, (int)m_freePool.Size());\n      if (oldMaxFreePoolSize != m_maxFreePoolSize)\n        LOG(LINFO, (base_t::m_pool.GetName(), \"freePool maximum size has reached\", m_maxFreePoolSize, \"elements\"));\n    }*\/\n  }\n\n  void UpdateStateImpl(list & l)\n  {\n    for (typename list::const_iterator it = l.begin();\n         it != l.end();\n         ++it)\n    {\n      base_t::m_factory.BeforeMerge(*it);\n      base_t::m_pool.PushBack(*it);\n    }\n\n\/\/    if ((base_t::m_IsDebugging) && (!base_t::m_pool.GetName().empty()))\n\/\/      LOG(LINFO, (\"pool for\", base_t::m_pool.GetName(), \"has\", base_t::m_pool.Size(), \"elements\"));\n\n    l.clear();\n  }\n\n  void UpdateState()\n  {\n    m_freePool.ProcessList(bind(&SeparateFreePoolTraits::UpdateStateImpl, this, _1));\n  }\n};\n\n\/\/\/ This traits maintains a fixed-size of pre-allocated resources.\ntemplate \nstruct FixedSizePoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n\n  size_t m_count;\n  bool m_isAllocated;\n\n  FixedSizePoolTraits(TElemFactory const & factory, size_t count)\n    : base_t(factory),\n      m_count(count),\n      m_isAllocated(false)\n  {}\n\n  elem_t const Reserve()\n  {\n    if (!m_isAllocated)\n    {\n      m_isAllocated = true;\n\n      LOG(LDEBUG, (\"allocating \", base_t::m_factory.ElemSize() * m_count, \"bytes for \", base_t::m_factory.ResName()));\n\n      for (size_t i = 0; i < m_count; ++i)\n        base_t::m_pool.PushBack(base_t::m_factory.Create());\n    }\n\n    return base_t::Reserve();\n  }\n};\n\n\/\/\/ This traits allocates resources on demand.\ntemplate \nstruct AllocateOnDemandMultiThreadedPoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename base_t::elem_t elem_t;\n  typedef AllocateOnDemandMultiThreadedPoolTraits self_t;\n\n  size_t m_poolSize;\n  AllocateOnDemandMultiThreadedPoolTraits(TElemFactory const & factory, size_t )\n    : base_t(factory),\n      m_poolSize(0)\n  {}\n\n  void AllocateIfNeeded(list & l)\n  {\n    if (l.empty())\n    {\n      m_poolSize += base_t::m_factory.ElemSize() * base_t::m_factory.BatchSize();\n      LOG(LDEBUG, (\"allocating \", base_t::m_factory.ElemSize(), \"bytes for \", base_t::m_factory.ResName(), \" on-demand, poolSize=\", m_poolSize \/ base_t::m_factory.ElemSize(), \", totalMemory=\", m_poolSize));\n      for (unsigned i = 0; i < base_t::m_factory.BatchSize(); ++i)\n        l.push_back(base_t::m_factory.Create());\n    }\n  }\n\n  elem_t const Reserve()\n  {\n    base_t::m_pool.ProcessList(bind(&self_t::AllocateIfNeeded, this, _1));\n    return base_t::Reserve();\n  }\n};\n\ntemplate \nstruct AllocateOnDemandSingleThreadedPoolTraits : TBase\n{\n  typedef TBase base_t;\n  typedef typename TBase::elem_t elem_t;\n  typedef AllocateOnDemandSingleThreadedPoolTraits self_t;\n\n  size_t m_poolSize;\n  AllocateOnDemandSingleThreadedPoolTraits(TElemFactory const & factory, size_t )\n    : base_t(factory),\n      m_poolSize(0)\n  {}\n\n  void Init()\n  {}\n\n  void AllocateIfNeeded(list & l)\n  {\n    if (l.empty())\n    {\n      m_poolSize += base_t::m_factory.ElemSize() * base_t::m_factory.BatchSize();\n      LOG(LDEBUG, (\"allocating\", base_t::m_factory.BatchSize(), \"elements for \", base_t::m_factory.ResName(), \"on-demand, poolSize=\", m_poolSize \/ base_t::m_factory.ElemSize(), \", totalMemory=\", m_poolSize));\n      for (unsigned i = 0; i < base_t::m_factory.BatchSize(); ++i)\n        l.push_back(base_t::m_factory.Create());\n    }\n  }\n\n  void UpdateState()\n  {\n    base_t::UpdateState();\n    base_t::m_pool.ProcessList(bind(&self_t::AllocateIfNeeded, this, _1));\n  }\n};\n\n\/\/\/ resource pool interface\ntemplate \nclass ResourcePool\n{\npublic:\n  virtual ~ResourcePool(){}\n  virtual TElem const Reserve() = 0;\n  virtual void Free(TElem const & elem) = 0;\n  virtual size_t Size() const = 0;\n  virtual void EnterForeground() = 0;\n  virtual void EnterBackground() = 0;\n  virtual void Cancel() = 0;\n  virtual bool IsCancelled() const = 0;\n  virtual void UpdateState() = 0;\n  virtual void SetIsDebugging(bool flag) = 0;\n  virtual char const * ResName() const = 0;\n};\n\n\/\/ This class tracks OpenGL resources allocation in\n\/\/ a multithreaded environment.\ntemplate \nclass ResourcePoolImpl : public ResourcePool\n{\nprivate:\n\n  scoped_ptr m_traits;\n\npublic:\n\n  typedef typename TPoolTraits::elem_t elem_t;\n\n  ResourcePoolImpl(TPoolTraits * traits)\n    : m_traits(traits)\n  {\n    \/\/\/ quick trick to perform lazy initialization\n    \/\/\/ on the same thread the pool was created.\n    m_traits->Init();\n  }\n\n  elem_t const Reserve()\n  {\n    return m_traits->Reserve();\n  }\n\n  void Free(elem_t const & elem)\n  {\n    m_traits->Free(elem);\n  }\n\n  size_t Size() const\n  {\n    return m_traits->Size();\n  }\n\n  void EnterForeground()\n  {}\n\n  void EnterBackground()\n  {}\n\n  void Cancel()\n  {\n    return m_traits->Cancel();\n  }\n\n  bool IsCancelled() const\n  {\n    return m_traits->IsCancelled();\n  }\n\n  void UpdateState()\n  {\n    m_traits->UpdateState();\n  }\n\n  void SetIsDebugging(bool isDebugging)\n  {\n    m_traits->m_IsDebugging = isDebugging;\n  }\n\n  char const * ResName() const\n  {\n    return m_traits->ResName();\n  }\n};\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2010 The Chromium OS 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 \"update_engine\/dbus_service.h\"\n\n#include \n\n#include \n\n#include \"update_engine\/marshal.glibmarshal.h\"\n#include \"update_engine\/omaha_request_params.h\"\n#include \"update_engine\/utils.h\"\n\nusing std::string;\n\nG_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)\n\nstatic void update_engine_service_finalize(GObject* object) {\n  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);\n}\n\nstatic guint status_update_signal = 0;\n\nstatic void update_engine_service_class_init(UpdateEngineServiceClass* klass) {\n  GObjectClass *object_class;\n  object_class = G_OBJECT_CLASS(klass);\n  object_class->finalize = update_engine_service_finalize;\n\n  status_update_signal = g_signal_new(\n      \"status_update\",\n      G_OBJECT_CLASS_TYPE(klass),\n      G_SIGNAL_RUN_LAST,\n      0,  \/\/ 0 == no class method associated\n      NULL,  \/\/ Accumulator\n      NULL,  \/\/ Accumulator data\n      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,\n      G_TYPE_NONE,  \/\/ Return type\n      5,  \/\/ param count:\n      G_TYPE_INT64,\n      G_TYPE_DOUBLE,\n      G_TYPE_STRING,\n      G_TYPE_STRING,\n      G_TYPE_INT64);\n}\n\nstatic void update_engine_service_init(UpdateEngineService* object) {\n}\n\nUpdateEngineService* update_engine_service_new(void) {\n  return reinterpret_cast(\n      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));\n}\n\ngboolean update_engine_service_attempt_update(UpdateEngineService* self,\n                                              gchar* app_version,\n                                              gchar* omaha_url,\n                                              GError **error) {\n  string update_app_version;\n  string update_omaha_url;\n  \/\/ Only non-official (e.g., dev and test) builds can override the current\n  \/\/ version and update server URL over D-Bus.\n  if (!chromeos_update_engine::utils::IsOfficialBuild()) {\n    if (app_version) {\n      update_app_version = app_version;\n    }\n    if (omaha_url) {\n      update_omaha_url = omaha_url;\n    }\n  }\n  LOG(INFO) << \"Attempt update: app_version=\\\"\" << update_app_version << \"\\\" \"\n            << \"omaha_url=\\\"\" << update_omaha_url << \"\\\"\";\n  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);\n  return TRUE;\n}\n\ngboolean update_engine_service_get_status(UpdateEngineService* self,\n                                          int64_t* last_checked_time,\n                                          double* progress,\n                                          gchar** current_operation,\n                                          gchar** new_version,\n                                          int64_t* new_size,\n                                          GError **error) {\n  string current_op;\n  string new_version_str;\n\n  CHECK(self->update_attempter_->GetStatus(last_checked_time,\n                                           progress,\n                                           ¤t_op,\n                                           &new_version_str,\n                                           new_size));\n\n  *current_operation = g_strdup(current_op.c_str());\n  *new_version = g_strdup(new_version_str.c_str());\n  if (!(*current_operation && *new_version)) {\n    *error = NULL;\n    return FALSE;\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_get_track(UpdateEngineService* self,\n                                         gchar** track,\n                                         GError **error) {\n  string track_str =\n      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();\n  *track = g_strdup(track_str.c_str());\n  return TRUE;\n}\n\ngboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,\n                                                GError **error) {\n  if (!self->update_attempter_->RebootIfNeeded()) {\n    *error = NULL;\n    return FALSE;\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_set_track(UpdateEngineService* self,\n                                         gchar* track,\n                                         GError **error) {\n  if (track) {\n    LOG(INFO) << \"Setting track to: \" << track;\n    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(\n            track)) {\n      *error = NULL;\n      return FALSE;\n    }\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_emit_status_update(\n    UpdateEngineService* self,\n    gint64 last_checked_time,\n    gdouble progress,\n    const gchar* current_operation,\n    const gchar* new_version,\n    gint64 new_size) {\n  g_signal_emit(self,\n                status_update_signal,\n                0,\n                last_checked_time,\n                progress,\n                current_operation,\n                new_version,\n                new_size);\n  return TRUE;\n}\nIf the Omaha URL is 'autest', point to the hardcoded test server.\/\/ Copyright (c) 2011 The Chromium OS 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 \"update_engine\/dbus_service.h\"\n\n#include \n\n#include \n\n#include \"update_engine\/marshal.glibmarshal.h\"\n#include \"update_engine\/omaha_request_params.h\"\n#include \"update_engine\/utils.h\"\n\nusing std::string;\n\nstatic const char kAUTestURLRequest[] = \"autest\";\nstatic const char kAUTestURL[] =\n    \"https:\/\/omaha.corp.google.com:8082\/service\/update2\";\n\nG_DEFINE_TYPE(UpdateEngineService, update_engine_service, G_TYPE_OBJECT)\n\nstatic void update_engine_service_finalize(GObject* object) {\n  G_OBJECT_CLASS(update_engine_service_parent_class)->finalize(object);\n}\n\nstatic guint status_update_signal = 0;\n\nstatic void update_engine_service_class_init(UpdateEngineServiceClass* klass) {\n  GObjectClass *object_class;\n  object_class = G_OBJECT_CLASS(klass);\n  object_class->finalize = update_engine_service_finalize;\n\n  status_update_signal = g_signal_new(\n      \"status_update\",\n      G_OBJECT_CLASS_TYPE(klass),\n      G_SIGNAL_RUN_LAST,\n      0,  \/\/ 0 == no class method associated\n      NULL,  \/\/ Accumulator\n      NULL,  \/\/ Accumulator data\n      update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,\n      G_TYPE_NONE,  \/\/ Return type\n      5,  \/\/ param count:\n      G_TYPE_INT64,\n      G_TYPE_DOUBLE,\n      G_TYPE_STRING,\n      G_TYPE_STRING,\n      G_TYPE_INT64);\n}\n\nstatic void update_engine_service_init(UpdateEngineService* object) {\n}\n\nUpdateEngineService* update_engine_service_new(void) {\n  return reinterpret_cast(\n      g_object_new(UPDATE_ENGINE_TYPE_SERVICE, NULL));\n}\n\ngboolean update_engine_service_attempt_update(UpdateEngineService* self,\n                                              gchar* app_version,\n                                              gchar* omaha_url,\n                                              GError **error) {\n  string update_app_version;\n  string update_omaha_url;\n  \/\/ Only non-official (e.g., dev and test) builds can override the current\n  \/\/ version and update server URL over D-Bus. However, pointing to the\n  \/\/ hardcoded test update server URL is always allowed.\n  if (!chromeos_update_engine::utils::IsOfficialBuild()) {\n    if (app_version) {\n      update_app_version = app_version;\n    }\n    if (omaha_url) {\n      update_omaha_url = omaha_url;\n    }\n  }\n  if (omaha_url && strcmp(omaha_url, kAUTestURLRequest) == 0) {\n    update_omaha_url = kAUTestURL;\n  }\n  LOG(INFO) << \"Attempt update: app_version=\\\"\" << update_app_version << \"\\\" \"\n            << \"omaha_url=\\\"\" << update_omaha_url << \"\\\"\";\n  self->update_attempter_->CheckForUpdate(update_app_version, update_omaha_url);\n  return TRUE;\n}\n\ngboolean update_engine_service_get_status(UpdateEngineService* self,\n                                          int64_t* last_checked_time,\n                                          double* progress,\n                                          gchar** current_operation,\n                                          gchar** new_version,\n                                          int64_t* new_size,\n                                          GError **error) {\n  string current_op;\n  string new_version_str;\n\n  CHECK(self->update_attempter_->GetStatus(last_checked_time,\n                                           progress,\n                                           ¤t_op,\n                                           &new_version_str,\n                                           new_size));\n\n  *current_operation = g_strdup(current_op.c_str());\n  *new_version = g_strdup(new_version_str.c_str());\n  if (!(*current_operation && *new_version)) {\n    *error = NULL;\n    return FALSE;\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_get_track(UpdateEngineService* self,\n                                         gchar** track,\n                                         GError **error) {\n  string track_str =\n      chromeos_update_engine::OmahaRequestDeviceParams::GetDeviceTrack();\n  *track = g_strdup(track_str.c_str());\n  return TRUE;\n}\n\ngboolean update_engine_service_reboot_if_needed(UpdateEngineService* self,\n                                                GError **error) {\n  if (!self->update_attempter_->RebootIfNeeded()) {\n    *error = NULL;\n    return FALSE;\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_set_track(UpdateEngineService* self,\n                                         gchar* track,\n                                         GError **error) {\n  if (track) {\n    LOG(INFO) << \"Setting track to: \" << track;\n    if (!chromeos_update_engine::OmahaRequestDeviceParams::SetDeviceTrack(\n            track)) {\n      *error = NULL;\n      return FALSE;\n    }\n  }\n  return TRUE;\n}\n\ngboolean update_engine_service_emit_status_update(\n    UpdateEngineService* self,\n    gint64 last_checked_time,\n    gdouble progress,\n    const gchar* current_operation,\n    const gchar* new_version,\n    gint64 new_size) {\n  g_signal_emit(self,\n                status_update_signal,\n                0,\n                last_checked_time,\n                progress,\n                current_operation,\n                new_version,\n                new_size);\n  return TRUE;\n}\n<|endoftext|>"}
{"text":"Update OrbitLinuxTracing\/TracerThread.cpp<|endoftext|>"}
{"text":"#include \"omnicore\/script.h\"\n\n#include \"amount.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"serialize.h\"\n#include \"utilstrencodings.h\"\n\n#include \n\n#include \n#include \n#include \n\n\/** The minimum transaction relay fee. *\/\nextern CFeeRate minRelayTxFee;\n\n\/**\n * Determines the minimum output amount to be spent by an output, based on the\n * scriptPubKey size in relation to the minimum relay fee.\n *\n * @param scriptPubKey[in]  The scriptPubKey\n * @return The dust threshold value\n *\/\nint64_t GetDustThreshold(const CScript& scriptPubKey)\n{\n    CTxOut txOut(0, scriptPubKey);\n\n    return txOut.GetDustThreshold(minRelayTxFee);\n}\n\n\/**\n * Identifies standard output types based on a scriptPubKey.\n *\n * Note: whichTypeRet is set to TX_NONSTANDARD, if no standard script was found.\n *\n * @param scriptPubKey[in]   The script\n * @param whichTypeRet[out]  The output type\n * @return True if a standard script was found\n *\/\nbool GetOutputType(const CScript& scriptPubKey, txnouttype& whichTypeRet)\n{\n    std::vector > vSolutions;\n\n    if (SafeSolver(scriptPubKey, whichTypeRet, vSolutions)) {\n        return true;\n    }\n    whichTypeRet = TX_NONSTANDARD;\n\n    return false;\n}\n\n\/**\n * Extracts the pushed data as hex-encoded string from a script.\n *\n * @param script[in]      The script\n * @param vstrRet[out]    The extracted pushed data as hex-encoded string\n * @param fSkipFirst[in]  Whether the first push operation should be skipped (default: false)\n * @return True if the extraction was successful (result can be empty)\n *\/\nbool GetScriptPushes(const CScript& script, std::vector& vstrRet, bool fSkipFirst)\n{\n    int count = 0;\n    CScript::const_iterator pc = script.begin();\n\n    while (pc < script.end()) {\n        opcodetype opcode;\n        std::vector data;\n        if (!script.GetOp(pc, opcode, data))\n            return false;\n        if (0x00 <= opcode && opcode <= OP_PUSHDATA4)\n            if (count++ || !fSkipFirst) vstrRet.push_back(HexStr(data));\n    }\n\n    return true;\n}\n\n\/**\n * Returns public keys or hashes from scriptPubKey, for standard transaction types.\n *\n * Note: in contrast to the script\/standard\/Solver, this Solver is not affected by\n * user settings, and in particular any OP_RETURN size is considered as standard.\n *\n * @param scriptPubKey[in]    The script\n * @param typeRet[out]        The output type\n * @param vSolutionsRet[out]  The extracted public keys or hashes\n * @return True if a standard script was found\n *\/\nbool SafeSolver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector >& vSolutionsRet)\n{\n    \/\/ Templates\n    static std::multimap mTemplates;\n    if (mTemplates.empty())\n    {\n        \/\/ Standard tx, sender provides pubkey, receiver adds signature\n        mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));\n\n        \/\/ Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey\n        mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));\n\n        \/\/ Sender provides N pubkeys, receivers provides M signatures\n        mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));\n\n        \/\/ Empty, provably prunable, data-carrying output\n        mTemplates.insert(std::make_pair(TX_NULL_DATA, CScript() << OP_RETURN));\n    }\n\n    vSolutionsRet.clear();\n\n    \/\/ Shortcut for pay-to-script-hash, which are more constrained than the other types:\n    \/\/ it is always OP_HASH160 20 [20 byte hash] OP_EQUAL\n    if (scriptPubKey.IsPayToScriptHash())\n    {\n        typeRet = TX_SCRIPTHASH;\n        std::vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);\n        vSolutionsRet.push_back(hashBytes);\n        return true;\n    }\n\n    \/\/ Provably prunable, data-carrying output\n    \/\/\n    \/\/ So long as script passes the IsUnspendable() test and all but the first\n    \/\/ byte passes the IsPushOnly() test we don't care what exactly is in the\n    \/\/ script.\n    if (scriptPubKey.size() >= 2 && scriptPubKey[0] == OP_RETURN)\n    {\n        CScript script(scriptPubKey.begin()+1, scriptPubKey.end());\n        if (script.IsPushOnly()) {\n            typeRet = TX_NULL_DATA;\n            return true;\n        }\n    }\n\n    \/\/ Scan templates\n    const CScript& script1 = scriptPubKey;\n    BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)\n    {\n        const CScript& script2 = tplate.second;\n        vSolutionsRet.clear();\n\n        opcodetype opcode1, opcode2;\n        std::vector vch1, vch2;\n\n        \/\/ Compare\n        CScript::const_iterator pc1 = script1.begin();\n        CScript::const_iterator pc2 = script2.begin();\n        while (true)\n        {\n            if (pc1 == script1.end() && pc2 == script2.end())\n            {\n                \/\/ Found a match\n                typeRet = tplate.first;\n                if (typeRet == TX_MULTISIG)\n                {\n                    \/\/ Additional checks for TX_MULTISIG:\n                    unsigned char m = vSolutionsRet.front()[0];\n                    unsigned char n = vSolutionsRet.back()[0];\n                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)\n                        return false;\n                }\n                return true;\n            }\n            if (!script1.GetOp(pc1, opcode1, vch1))\n                break;\n            if (!script2.GetOp(pc2, opcode2, vch2))\n                break;\n\n            \/\/ Template matching opcodes:\n            if (opcode2 == OP_PUBKEYS)\n            {\n                while (vch1.size() >= 33 && vch1.size() <= 65)\n                {\n                    vSolutionsRet.push_back(vch1);\n                    if (!script1.GetOp(pc1, opcode1, vch1))\n                        break;\n                }\n                if (!script2.GetOp(pc2, opcode2, vch2))\n                    break;\n                \/\/ Normal situation is to fall through\n                \/\/ to other if\/else statements\n            }\n\n            if (opcode2 == OP_PUBKEY)\n            {\n                if (vch1.size() < 33 || vch1.size() > 65)\n                    break;\n                vSolutionsRet.push_back(vch1);\n            }\n            else if (opcode2 == OP_PUBKEYHASH)\n            {\n                if (vch1.size() != sizeof(uint160))\n                    break;\n                vSolutionsRet.push_back(vch1);\n            }\n            else if (opcode2 == OP_SMALLINTEGER)\n            {   \/\/ Single-byte small integer pushed onto vSolutions\n                if (opcode1 == OP_0 ||\n                    (opcode1 >= OP_1 && opcode1 <= OP_16))\n                {\n                    char n = (char)CScript::DecodeOP_N(opcode1);\n                    vSolutionsRet.push_back(std::vector(1, n));\n                }\n                else\n                    break;\n            }\n            else if (opcode1 != opcode2 || vch1 != vch2)\n            {\n                \/\/ Others must match exactly\n                break;\n            }\n        }\n    }\n\n    vSolutionsRet.clear();\n    typeRet = TX_NONSTANDARD;\n    return false;\n}\nAdd support for native SW to safe solver#include \"omnicore\/script.h\"\n\n#include \"amount.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"serialize.h\"\n#include \"utilstrencodings.h\"\n\n#include \n\n#include \n#include \n#include \n\n\/** The minimum transaction relay fee. *\/\nextern CFeeRate minRelayTxFee;\n\n\/**\n * Determines the minimum output amount to be spent by an output, based on the\n * scriptPubKey size in relation to the minimum relay fee.\n *\n * @param scriptPubKey[in]  The scriptPubKey\n * @return The dust threshold value\n *\/\nint64_t GetDustThreshold(const CScript& scriptPubKey)\n{\n    CTxOut txOut(0, scriptPubKey);\n\n    return txOut.GetDustThreshold(minRelayTxFee);\n}\n\n\/**\n * Identifies standard output types based on a scriptPubKey.\n *\n * Note: whichTypeRet is set to TX_NONSTANDARD, if no standard script was found.\n *\n * @param scriptPubKey[in]   The script\n * @param whichTypeRet[out]  The output type\n * @return True if a standard script was found\n *\/\nbool GetOutputType(const CScript& scriptPubKey, txnouttype& whichTypeRet)\n{\n    std::vector > vSolutions;\n\n    if (SafeSolver(scriptPubKey, whichTypeRet, vSolutions)) {\n        return true;\n    }\n    whichTypeRet = TX_NONSTANDARD;\n\n    return false;\n}\n\n\/**\n * Extracts the pushed data as hex-encoded string from a script.\n *\n * @param script[in]      The script\n * @param vstrRet[out]    The extracted pushed data as hex-encoded string\n * @param fSkipFirst[in]  Whether the first push operation should be skipped (default: false)\n * @return True if the extraction was successful (result can be empty)\n *\/\nbool GetScriptPushes(const CScript& script, std::vector& vstrRet, bool fSkipFirst)\n{\n    int count = 0;\n    CScript::const_iterator pc = script.begin();\n\n    while (pc < script.end()) {\n        opcodetype opcode;\n        std::vector data;\n        if (!script.GetOp(pc, opcode, data))\n            return false;\n        if (0x00 <= opcode && opcode <= OP_PUSHDATA4)\n            if (count++ || !fSkipFirst) vstrRet.push_back(HexStr(data));\n    }\n\n    return true;\n}\n\n\/**\n * Returns public keys or hashes from scriptPubKey, for standard transaction types.\n *\n * Note: in contrast to the script\/standard\/Solver, this Solver is not affected by\n * user settings, and in particular any OP_RETURN size is considered as standard.\n *\n * @param scriptPubKey[in]    The script\n * @param typeRet[out]        The output type\n * @param vSolutionsRet[out]  The extracted public keys or hashes\n * @return True if a standard script was found\n *\/\nbool SafeSolver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector >& vSolutionsRet)\n{\n    \/\/ Templates\n    static std::multimap mTemplates;\n    if (mTemplates.empty())\n    {\n        \/\/ Standard tx, sender provides pubkey, receiver adds signature\n        mTemplates.insert(std::make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));\n\n        \/\/ Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey\n        mTemplates.insert(std::make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));\n\n        \/\/ Sender provides N pubkeys, receivers provides M signatures\n        mTemplates.insert(std::make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));\n\n        \/\/ Empty, provably prunable, data-carrying output\n        mTemplates.insert(std::make_pair(TX_NULL_DATA, CScript() << OP_RETURN));\n    }\n\n    vSolutionsRet.clear();\n\n    \/\/ Shortcut for pay-to-script-hash, which are more constrained than the other types:\n    \/\/ it is always OP_HASH160 20 [20 byte hash] OP_EQUAL\n    if (scriptPubKey.IsPayToScriptHash())\n    {\n        typeRet = TX_SCRIPTHASH;\n        std::vector hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);\n        vSolutionsRet.push_back(hashBytes);\n        return true;\n    }\n\n    int witnessversion;\n    std::vector witnessprogram;\n    if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {\n        if (witnessversion == 0 && witnessprogram.size() == 20) {\n            typeRet = TX_WITNESS_V0_KEYHASH;\n            vSolutionsRet.push_back(witnessprogram);\n            return true;\n        }\n        if (witnessversion == 0 && witnessprogram.size() == 32) {\n            typeRet = TX_WITNESS_V0_SCRIPTHASH;\n            vSolutionsRet.push_back(witnessprogram);\n            return true;\n        }\n        return false;\n    }\n\n    \/\/ Provably prunable, data-carrying output\n    \/\/\n    \/\/ So long as script passes the IsUnspendable() test and all but the first\n    \/\/ byte passes the IsPushOnly() test we don't care what exactly is in the\n    \/\/ script.\n    if (scriptPubKey.size() >= 2 && scriptPubKey[0] == OP_RETURN)\n    {\n        CScript script(scriptPubKey.begin()+1, scriptPubKey.end());\n        if (script.IsPushOnly()) {\n            typeRet = TX_NULL_DATA;\n            return true;\n        }\n    }\n\n    \/\/ Scan templates\n    const CScript& script1 = scriptPubKey;\n    BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)\n    {\n        const CScript& script2 = tplate.second;\n        vSolutionsRet.clear();\n\n        opcodetype opcode1, opcode2;\n        std::vector vch1, vch2;\n\n        \/\/ Compare\n        CScript::const_iterator pc1 = script1.begin();\n        CScript::const_iterator pc2 = script2.begin();\n        while (true)\n        {\n            if (pc1 == script1.end() && pc2 == script2.end())\n            {\n                \/\/ Found a match\n                typeRet = tplate.first;\n                if (typeRet == TX_MULTISIG)\n                {\n                    \/\/ Additional checks for TX_MULTISIG:\n                    unsigned char m = vSolutionsRet.front()[0];\n                    unsigned char n = vSolutionsRet.back()[0];\n                    if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)\n                        return false;\n                }\n                return true;\n            }\n            if (!script1.GetOp(pc1, opcode1, vch1))\n                break;\n            if (!script2.GetOp(pc2, opcode2, vch2))\n                break;\n\n            \/\/ Template matching opcodes:\n            if (opcode2 == OP_PUBKEYS)\n            {\n                while (vch1.size() >= 33 && vch1.size() <= 65)\n                {\n                    vSolutionsRet.push_back(vch1);\n                    if (!script1.GetOp(pc1, opcode1, vch1))\n                        break;\n                }\n                if (!script2.GetOp(pc2, opcode2, vch2))\n                    break;\n                \/\/ Normal situation is to fall through\n                \/\/ to other if\/else statements\n            }\n\n            if (opcode2 == OP_PUBKEY)\n            {\n                if (vch1.size() < 33 || vch1.size() > 65)\n                    break;\n                vSolutionsRet.push_back(vch1);\n            }\n            else if (opcode2 == OP_PUBKEYHASH)\n            {\n                if (vch1.size() != sizeof(uint160))\n                    break;\n                vSolutionsRet.push_back(vch1);\n            }\n            else if (opcode2 == OP_SMALLINTEGER)\n            {   \/\/ Single-byte small integer pushed onto vSolutions\n                if (opcode1 == OP_0 ||\n                    (opcode1 >= OP_1 && opcode1 <= OP_16))\n                {\n                    char n = (char)CScript::DecodeOP_N(opcode1);\n                    vSolutionsRet.push_back(std::vector(1, n));\n                }\n                else\n                    break;\n            }\n            else if (opcode1 != opcode2 || vch1 != vch2)\n            {\n                \/\/ Others must match exactly\n                break;\n            }\n        }\n    }\n\n    vSolutionsRet.clear();\n    typeRet = TX_NONSTANDARD;\n    return false;\n}\n<|endoftext|>"}
{"text":"\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include \n#include \n#include \n#include \n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( XMLNode &node, int level = 0 )\n{\n   XMLString name = node.getName();\n   XMLNodeType type = node.getType();\n   XMLString c_data;\n\n   for(int i=0;ifirst << \": \" << j->second << endl;\n   }\n\n   XMLNodeList& nlist = node.getChildren();\n\n   XMLNodeList::const_iterator iter, stop;\n   iter = nlist.begin();\n   stop = nlist.end();\n\n   while (iter != stop)\n   {\n      XMLNodePtr node = *iter;\n\n      dump_node ( *node, level+1 );\n\n      ++iter;\n   }\n};\n\nvoid process_xml( std::string filename )\n{\n   cout << \"processing [\" << filename << \"] ...\" << endl;\n\n   XMLContextPtr context( new XMLContext );\n   XMLDocument node( context );\n   ifstream istr( filename.c_str() );\n\n   \/\/ Verify that file opened\n   if(!istr)\n   {\n      std::cerr << \"Bad file: \" << filename << std::endl;\n      return;\n   }\n\n   try\n   {\n      clock_t tstart = ::clock();\n\n      node.load( istr, context );\n\n      clock_t tstop = ::clock();\n      cout << \" needed \" <<\n         (tstop-tstart)\/static_cast(CLOCKS_PER_SEC)\n         << \" seconds.\" << endl;\n\n      dump_node( node );\n\n      ofstream ostr( \"parsetest.xml\" );\n      node.save( ostr );\n      ostr.close();\n\n   }\n   catch (xmlerror e)\n   {\n      XMLLocation where( context->get_location() );\n      XMLString errmsg;\n      e.getStrError(errmsg);\n\n      \/\/ print out where the error occured\n      cout << filename << \":\" << where.getLine() << \" \";\n      cout << \"at position \" << where.getPos();\n      cout << \": error: \" << errmsg.c_str();\n      cout << endl;\n\n      \/\/ print out line where the error occured\n      ifstream errfile( filename.c_str() );\n      if(!errfile)\n      {\n         std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n      }\n\n      int linenr = where.get_line();\n      char linebuffer[1024];\n      for(int i=0; i=80)\n         pos %= 80;\n\n      std::string err_line( linebuffer + (where.get_pos()-pos) );\n      if (err_line.length()>=79)\n         err_line.erase(79);\n      cout << err_line << std::flush;\n      cout << err_line.c_str() << std::endl;\n      cout << linebuffer << std::endl;\n      for(int j=2;jupdated to current cppdom api changes\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include \n#include \n#include \n#include \n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( XMLNode &node, int level = 0 )\n{\n   XMLString name = node.getName();\n   XMLNodeType type = node.getType();\n   XMLString c_data;\n\n   for(int i=0;ifirst << \": \" << j->second << endl;\n   }\n\n   XMLNodeList& nlist = node.getChildren();\n\n   XMLNodeList::const_iterator iter, stop;\n   iter = nlist.begin();\n   stop = nlist.end();\n\n   while (iter != stop)\n   {\n      XMLNodePtr node = *iter;\n\n      dump_node ( *node, level+1 );\n\n      ++iter;\n   }\n};\n\nvoid process_xml( std::string filename )\n{\n   cout << \"processing [\" << filename << \"] ...\" << endl;\n\n   XMLContextPtr context( new XMLContext );\n   XMLDocument node( context );\n   ifstream istr( filename.c_str() );\n\n   \/\/ Verify that file opened\n   if(!istr)\n   {\n      std::cerr << \"Bad file: \" << filename << std::endl;\n      return;\n   }\n\n   try\n   {\n      clock_t tstart = ::clock();\n\n      node.load( istr, context );\n\n      clock_t tstop = ::clock();\n      cout << \" needed \" <<\n         (tstop-tstart)\/static_cast(CLOCKS_PER_SEC)\n         << \" seconds.\" << endl;\n\n      dump_node( node );\n\n      ofstream ostr( \"parsetest.xml\" );\n      node.save( ostr );\n      ostr.close();\n\n   }\n   catch (XMLError e)\n   {\n      XMLLocation where( context->getLocation() );\n      XMLString errmsg;\n      e.getStrError(errmsg);\n\n      \/\/ print out where the error occured\n      cout << filename << \":\" << where.getLine() << \" \";\n      cout << \"at position \" << where.getPos();\n      cout << \": error: \" << errmsg.c_str();\n      cout << endl;\n\n      \/\/ print out line where the error occured\n      ifstream errfile( filename.c_str() );\n      if(!errfile)\n      {\n         std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n      }\n\n      int linenr = where.getLine();\n      char linebuffer[1024];\n      for(int i=0; i=80)\n         pos %= 80;\n\n      std::string err_line( linebuffer + (where.getPos()-pos) );\n      if (err_line.length()>=79)\n         err_line.erase(79);\n      cout << err_line << std::flush;\n      cout << err_line.c_str() << std::endl;\n      cout << linebuffer << std::endl;\n      for(int j=2;j"}
{"text":"#include \"..\/picojson.h\"\n\nint main(void)\n{\n  picojson::value v;\n  \n  \/\/ read json value from stream\n  std::cin >> v;\n  if (std::cin.fail()) {\n    std::cerr << picojson::get_last_error() << std::endl;\n    return 1;\n  }\n  \n  \/\/ dump json object\n  std::cout << \"---- dump input ----\" << std::endl;\n  std::cout << v << std::endl;\n\n  \/\/ accessors\n  std::cout << \"---- analyzing input ----\" << std::endl;\n  if (v.is()) {\n    std::cout << \"input is undefined\" << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is null\" << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << (v.get() ? \"true\" : \"false\") << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << v.get() << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << v.get() << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is an array\" << std::endl;\n    const picojson::array& a = v.get();\n    for (picojson::array::const_iterator i = a.begin(); i != a.end(); ++i) {\n      std::cout << \"  \" << *i << std::endl;\n    }\n  } else if (v.is()) {\n    std::cout << \"input is an object\" << std::endl;\n    const picojson::object& o = v.get();\n    for (picojson::object::const_iterator i = o.begin(); i != o.end(); ++i) {\n      std::cout << i->first << \"  \" << i->second << std::endl;\n    }\n  }\n  \n  return 0;\n}\nremove undefined.#include \"..\/picojson.h\"\n\nint main(void)\n{\n  picojson::value v;\n  \n  \/\/ read json value from stream\n  std::cin >> v;\n  if (std::cin.fail()) {\n    std::cerr << picojson::get_last_error() << std::endl;\n    return 1;\n  }\n  \n  \/\/ dump json object\n  std::cout << \"---- dump input ----\" << std::endl;\n  std::cout << v << std::endl;\n\n  \/\/ accessors\n  std::cout << \"---- analyzing input ----\" << std::endl;\n  if (v.is()) {\n    std::cout << \"input is null\" << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << (v.get() ? \"true\" : \"false\") << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << v.get() << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is \" << v.get() << std::endl;\n  } else if (v.is()) {\n    std::cout << \"input is an array\" << std::endl;\n    const picojson::array& a = v.get();\n    for (picojson::array::const_iterator i = a.begin(); i != a.end(); ++i) {\n      std::cout << \"  \" << *i << std::endl;\n    }\n  } else if (v.is()) {\n    std::cout << \"input is an object\" << std::endl;\n    const picojson::object& o = v.get();\n    for (picojson::object::const_iterator i = o.begin(); i != o.end(); ++i) {\n      std::cout << i->first << \"  \" << i->second << std::endl;\n    }\n  }\n  \n  return 0;\n}\n<|endoftext|>"}
{"text":"void sim(Int_t nev=1) {\n  AliSimulation simulator;\n  simulator.SetMakeSDigits(\"TRD TOF PHOS HMPID EMCAL MUON FMD ZDC PMD T0 VZERO\");\n  simulator.SetMakeDigitsFromHits(\"ITS TPC\");\n  simulator.SetWriteRawData(\"ALL\",\"raw.root\",kTRUE);\n\n  simulator.SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n  simulator.SetSpecificStorage(\"GRP\/GRP\/Data\",\n\t\t\t       Form(\"local:\/\/%s\",gSystem->pwd()));\n  simulator.SetRunQA(\"ALL:ALL\") ; \n  AliQA::SetQARefStorage(\"local:\/\/$ALICE_ROOT\") ;\n  \n  for (Int_t det = 0 ; det < AliQA::kNDET ; det++) {\n    simulator.SetQACycles(det, nev+1) ;\n  }\n  \n  TStopwatch timer;\n  timer.Start();\n  simulator.Run(nev);\n  timer.Stop();\n  timer.Print();\n}\nallow to set the number of events throub an env variablevoid sim(Int_t nev=1) {\n  if (gSystem->Getenv(\"EVENT\"))\n   nev = atoi(gSystem->Getenv(\"EVENT\")) ;   \n  AliSimulation simulator;\n  simulator.SetMakeSDigits(\"TRD TOF PHOS HMPID EMCAL MUON FMD ZDC PMD T0 VZERO\");\n  simulator.SetMakeDigitsFromHits(\"ITS TPC\");\n  simulator.SetWriteRawData(\"ALL\",\"raw.root\",kTRUE);\n\n  simulator.SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n  simulator.SetSpecificStorage(\"GRP\/GRP\/Data\",\n\t\t\t       Form(\"local:\/\/%s\",gSystem->pwd()));\n  simulator.SetRunQA(\"ALL:ALL\") ; \n  AliQA::SetQARefStorage(\"local:\/\/$ALICE_ROOT\") ;\n  \n  for (Int_t det = 0 ; det < AliQA::kNDET ; det++) {\n    simulator.SetQACycles(det, nev+1) ;\n  }\n  \n  TStopwatch timer;\n  timer.Start();\n  simulator.Run(nev);\n  timer.Stop();\n  timer.Print();\n}\n<|endoftext|>"}
{"text":"void sim(Int_t nev=1) {\n  if (gSystem->Getenv(\"EVENT\"))\n   nev = atoi(gSystem->Getenv(\"EVENT\")) ;   \n  \n  AliSimulation simulator;\n  simulator.SetMakeSDigits(\"TRD TOF PHOS HMPID EMCAL MUON FMD ZDC PMD T0 VZERO\");\n  simulator.SetMakeDigitsFromHits(\"ITS TPC\");\n  simulator.SetWriteRawData(\"ALL\",\"raw.root\",kTRUE);\n\n  simulator.SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n  simulator.SetSpecificStorage(\"GRP\/GRP\/Data\",\n\t\t\t       Form(\"local:\/\/%s\",gSystem->pwd()));\n  \n  simulator.SetRunQA(\"ALL:ALL\") ; \n  \n  simulator.SetQARefDefaultStorage(\"local:\/\/$ALICE_ROOT\/QAref\") ;\n\n  for (Int_t det = 0 ; det < AliQA::kNDET ; det++) {\n    simulator.SetQACycles(det, nev+1) ;\n  }\n  \n  TStopwatch timer;\n  timer.Start();\n  simulator.Run(nev);\n  timer.Stop();\n  timer.Print();\n}\nRevert commit 32313: back to 20 simulated eventsvoid sim(Int_t nev=20) {\n  if (gSystem->Getenv(\"EVENT\"))\n   nev = atoi(gSystem->Getenv(\"EVENT\")) ;   \n  \n  AliSimulation simulator;\n  simulator.SetMakeSDigits(\"TRD TOF PHOS HMPID EMCAL MUON FMD ZDC PMD T0 VZERO\");\n  simulator.SetMakeDigitsFromHits(\"ITS TPC\");\n  simulator.SetWriteRawData(\"ALL\",\"raw.root\",kTRUE);\n\n  simulator.SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n  simulator.SetSpecificStorage(\"GRP\/GRP\/Data\",\n\t\t\t       Form(\"local:\/\/%s\",gSystem->pwd()));\n  \n  simulator.SetRunQA(\"ALL:ALL\") ; \n  \n  simulator.SetQARefDefaultStorage(\"local:\/\/$ALICE_ROOT\/QAref\") ;\n\n  for (Int_t det = 0 ; det < AliQA::kNDET ; det++) {\n    simulator.SetQACycles(det, nev+1) ;\n  }\n  \n  TStopwatch timer;\n  timer.Start();\n  simulator.Run(nev);\n  timer.Stop();\n  timer.Print();\n}\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n    std::vector data = DecodeBase64(cert_data);\n    assert(data.size() > 0);\n    const unsigned char* dptr = &data[0];\n    X509 *cert = d2i_X509(nullptr, &dptr, data.size());\n    assert(cert);\n    return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n    RecipientCatcher sigCatcher;\n    QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n    \/\/ Write data to a temp file:\n    QTemporaryFile f;\n    f.open();\n    f.write((const char*)&data[0], data.size());\n    f.close();\n\n    \/\/ Create a QObject, install event filter from PaymentServer\n    \/\/ and send a file open event to the object\n    QObject object;\n    object.installEventFilter(server);\n    QFileOpenEvent event(f.fileName());\n    \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n    \/\/ which will lead to a test failure anyway.\n    QCoreApplication::sendEvent(&object, &event);\n\n    QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n    \/\/ Return results from sigCatcher\n    return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n    SelectParams(CBaseChainParams::MAIN);\n    OptionsModel optionsModel;\n    PaymentServer* server = new PaymentServer(nullptr, false);\n    X509_STORE* caStore = X509_STORE_new();\n    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n    PaymentServer::LoadRootCAs(caStore);\n    server->setOptionsModel(&optionsModel);\n    server->uiReady();\n\n    std::vector data;\n    SendCoinsRecipient r;\n    QString merchant;\n\n    \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n    \/\/ This payment request validates directly against the\n    \/\/ caCert1 certificate authority:\n    data = DecodeBase64(paymentrequest1_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n    \/\/ Signed, but expired, merchant cert in the request:\n    data = DecodeBase64(paymentrequest2_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ 10-long certificate chain, all intermediates valid:\n    data = DecodeBase64(paymentrequest3_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n    \/\/ Long certificate chain, with an expired certificate in the middle:\n    data = DecodeBase64(paymentrequest4_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Validly signed, but by a CA not in our root CA list:\n    data = DecodeBase64(paymentrequest5_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n    caStore = X509_STORE_new();\n    PaymentServer::LoadRootCAs(caStore);\n    data = DecodeBase64(paymentrequest1_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Load second root certificate\n    caStore = X509_STORE_new();\n    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n    PaymentServer::LoadRootCAs(caStore);\n\n    QByteArray byteArray;\n\n    \/\/ For the tests below we just need the payment request data from\n    \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n    \/\/\n    \/\/ These tests require us to bypass the following normal client execution flow\n    \/\/ shown below to be able to explicitly just trigger a certain condition!\n    \/\/\n    \/\/ handleRequest()\n    \/\/ -> PaymentServer::eventFilter()\n    \/\/   -> PaymentServer::handleURIOrFile()\n    \/\/     -> PaymentServer::readPaymentRequestFromFile()\n    \/\/       -> PaymentServer::processPaymentRequest()\n\n    \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n    data = DecodeBase64(paymentrequest1_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n    \/\/ uninitialized payment requests and that will fail our test here.\n    QVERIFY(r.paymentRequest.IsInitialized());\n    QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n    \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n    data = DecodeBase64(paymentrequest2_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n    \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n    \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n    \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n    data = DecodeBase64(paymentrequest3_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n    \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n    \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n    \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n    data = DecodeBase64(paymentrequest4_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n    \/\/ Test BIP70 DoS protection:\n    unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];\n    GetRandBytes(randData, sizeof(randData));\n    \/\/ Write data to a temp file:\n    QTemporaryFile tempFile;\n    tempFile.open();\n    tempFile.write((const char*)randData, sizeof(randData));\n    tempFile.close();\n    \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n    QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n\n    \/\/ Payment request with amount overflow (amount is set to 21000001 BTC):\n    data = DecodeBase64(paymentrequest5_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ Extract address and amount from the request\n    QList > sendingTos = r.paymentRequest.getPayTo();\n    for (const std::pair& sendingTo : sendingTos) {\n        CTxDestination dest;\n        if (ExtractDestination(sendingTo.first, dest))\n            QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n    }\n\n    delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n    recipient = r;\n}\nUpdate paymentservertests.cpp\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n    std::vector data = DecodeBase64(cert_data);\n    assert(data.size() > 0);\n    const unsigned char* dptr = &data[0];\n    X509 *cert = d2i_X509(nullptr, &dptr, data.size());\n    assert(cert);\n    return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n    RecipientCatcher sigCatcher;\n    QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n    \/\/ Write data to a temp file:\n    QTemporaryFile f;\n    f.open();\n    f.write((const char*)&data[0], data.size());\n    f.close();\n\n    \/\/ Create a QObject, install event filter from PaymentServer\n    \/\/ and send a file open event to the object\n    QObject object;\n    object.installEventFilter(server);\n    QFileOpenEvent event(f.fileName());\n    \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n    \/\/ which will lead to a test failure anyway.\n    QCoreApplication::sendEvent(&object, &event);\n\n    QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n        &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n    \/\/ Return results from sigCatcher\n    return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n    SelectParams(CBaseChainParams::MAIN);\n    OptionsModel optionsModel;\n    PaymentServer* server = new PaymentServer(nullptr, false);\n    X509_STORE* caStore = X509_STORE_new();\n    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n    PaymentServer::LoadRootCAs(caStore);\n    server->setOptionsModel(&optionsModel);\n    server->uiReady();\n\n    std::vector data;\n    SendCoinsRecipient r;\n    QString merchant;\n\n    \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n    \/\/ This payment request validates directly against the\n    \/\/ caCert1 certificate authority:\n    data = DecodeBase64(paymentrequest1_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n    \/\/ Signed, but expired, merchant cert in the request:\n    data = DecodeBase64(paymentrequest2_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ 10-long certificate chain, all intermediates valid:\n    data = DecodeBase64(paymentrequest3_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n    \/\/ Long certificate chain, with an expired certificate in the middle:\n    data = DecodeBase64(paymentrequest4_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Validly signed, but by a CA not in our root CA list:\n    data = DecodeBase64(paymentrequest5_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n    caStore = X509_STORE_new();\n    PaymentServer::LoadRootCAs(caStore);\n    data = DecodeBase64(paymentrequest1_cert1_BASE64);\n    r = handleRequest(server, data);\n    r.paymentRequest.getMerchant(caStore, merchant);\n    QCOMPARE(merchant, QString(\"\"));\n\n    \/\/ Load second root certificate\n    caStore = X509_STORE_new();\n    X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n    PaymentServer::LoadRootCAs(caStore);\n\n    QByteArray byteArray;\n\n    \/\/ For the tests below we just need the payment request data from\n    \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n    \/\/\n    \/\/ These tests require us to bypass the following normal client execution flow\n    \/\/ shown below to be able to explicitly just trigger a certain condition!\n    \/\/\n    \/\/ handleRequest()\n    \/\/ -> PaymentServer::eventFilter()\n    \/\/   -> PaymentServer::handleURIOrFile()\n    \/\/     -> PaymentServer::readPaymentRequestFromFile()\n    \/\/       -> PaymentServer::processPaymentRequest()\n\n    \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n    data = DecodeBase64(paymentrequest1_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n    \/\/ uninitialized payment requests and that will fail our test here.\n    QVERIFY(r.paymentRequest.IsInitialized());\n    QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n    \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n    data = DecodeBase64(paymentrequest2_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n    \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n    \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n    \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n    data = DecodeBase64(paymentrequest3_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n    \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n    \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n    \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n    data = DecodeBase64(paymentrequest4_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n    QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n    \/\/ Test BIP70 DoS protection:\n    unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];\n    GetRandBytes(randData, sizeof(randData));\n    \/\/ Write data to a temp file:\n    QTemporaryFile tempFile;\n    tempFile.open();\n    tempFile.write((const char*)randData, sizeof(randData));\n    tempFile.close();\n    \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n    QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n\n    \/\/ Payment request with amount overflow (amount is set to 21000001 BTG):\n    data = DecodeBase64(paymentrequest5_cert2_BASE64);\n    byteArray = QByteArray((const char*)&data[0], data.size());\n    r.paymentRequest.parse(byteArray);\n    \/\/ Ensure the request is initialized\n    QVERIFY(r.paymentRequest.IsInitialized());\n    \/\/ Extract address and amount from the request\n    QList > sendingTos = r.paymentRequest.getPayTo();\n    for (const std::pair& sendingTo : sendingTos) {\n        CTxDestination dest;\n        if (ExtractDestination(sendingTo.first, dest))\n            QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n    }\n\n    delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n    recipient = r;\n}\n<|endoftext|>"}
{"text":"Remove repetitive comments from Rational.hpp<|endoftext|>"}
{"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"..\/fv_converter\/converter_config.hpp\"\n\nusing std::string;\nusing std::cout;\nusing std::endl;\n\npid_t fork_process(const char* name, int port = 9199){\n  string cmd(BUILD_DIR);\n  pid_t child;\n  cmd += \"\/src\/server\/juba\";\n  cmd += name;\n  child = fork();\n  string port_str = pfi::lang::lexical_cast(port);\n  if(child == 0){\n    const char *const argv[6] = {cmd.c_str(), \"-p\", port_str.c_str(), \"-d\", \".\", NULL};\n    int ret = execv(cmd.c_str(), (char **const) argv);\n    if(ret < 0){\n      perror(\"execl\");\n      cout << cmd << \" \" << child << endl;\n    }\n  }else if( child < 0 ){\n    perror(\"--\");\n    return -1;\n  }\n  usleep(77777); \/\/ we wanna be lucky!\n  return child;\n}\n\nvoid kill_process(pid_t child){\n  if(kill(child, SIGTERM) != 0){\n    perror(\"\");\n    return;\n  }\n  int status = 0;\n  waitpid(child, &status, 0);\n}\n\nstd::string config_to_string(const jubatus::fv_converter::converter_config& config) {\n  std::stringstream ss;\n  ss << pfi::text::json::to_json(config);\n  return ss.str();\n}\n\n\nwait till client can connect to the server\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"..\/fv_converter\/converter_config.hpp\"\n\nusing std::string;\nusing std::cout;\nusing std::endl;\n\nvoid wait_server(int port) {\n  pfi::network::mprpc::rpc_client cli(\"localhost\", port, 10);\n  long sleep_time = 1000;\n  \/\/ 1000 * \\sum {i=0..9} 2^i = 1024000 micro sec = 1024 ms\n  for (int i = 0; i < 10; ++i) {\n    usleep(sleep_time);\n    try {\n      cli.call(\"dummy\")();\n      throw std::runtime_error(\"dummy rpc successed\");\n    } catch(pfi::network::mprpc::method_not_found& e) {\n      return;\n    } catch(pfi::network::mprpc::rpc_io_error& e) {\n      \/\/ wait until the server bigins to listen\n    }\n    sleep_time *= 2;\n  }\n  throw std::runtime_error(\"cannot connect\");\n}\n\npid_t fork_process(const char* name, int port = 9199){\n  string cmd(BUILD_DIR);\n  pid_t child;\n  cmd += \"\/src\/server\/juba\";\n  cmd += name;\n  child = fork();\n  string port_str = pfi::lang::lexical_cast(port);\n  if(child == 0){\n    const char *const argv[6] = {cmd.c_str(), \"-p\", port_str.c_str(), \"-d\", \".\", NULL};\n    int ret = execv(cmd.c_str(), (char **const) argv);\n    if(ret < 0){\n      perror(\"execl\");\n      cout << cmd << \" \" << child << endl;\n    }\n  }else if( child < 0 ){\n    perror(\"--\");\n    return -1;\n  }\n  wait_server(port);\n  return child;\n}\n\nvoid kill_process(pid_t child){\n  if(kill(child, SIGTERM) != 0){\n    perror(\"\");\n    return;\n  }\n  int status = 0;\n  waitpid(child, &status, 0);\n}\n\nstd::string config_to_string(const jubatus::fv_converter::converter_config& config) {\n  std::stringstream ss;\n  ss << pfi::text::json::to_json(config);\n  return ss.str();\n}\n\n\n<|endoftext|>"}
{"text":"\/*\n* Copyright (c) 2003-2010 Rony Shapiro .\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/**\n * \\file Windows-specific implementation of file.h\n *\/\n\n#ifndef __WX__\n#include \n#endif\n\n#include \n#include  \/\/ for UNLEN definition\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"..\/typedefs.h\"\n#include \"..\/file.h\"\n#include \"..\/dir.h\"\n#include \"..\/env.h\"\n\nconst TCHAR pws_os::PathSeparator = _T('\\\\');\n\nbool pws_os::FileExists(const stringT &filename)\n{\n  struct _stat statbuf;\n  int status;\n\n  status = _tstat(filename.c_str(), &statbuf);\n  return (status == 0);\n}\n\nbool pws_os::FileExists(const stringT &filename, bool &bReadOnly)\n{\n  bool retval;\n  bReadOnly = false;\n\n  retval = (_taccess(filename.c_str(), R_OK) == 0);\n  if (retval) {\n    bReadOnly = (_taccess(filename.c_str(), W_OK) != 0);\n  }\n  return retval;\n}\n\nvoid pws_os::AddDrive(stringT &path)\n{\n  using namespace pws_os;\n  \/\/ Adds a drive letter to the path if not there, unless\n  \/\/ it's a UNC path (\\\\host\\sharename...)\n  if (!(path[0] == '\\\\' && path[1] == '\\\\')) {\n    stringT drive, dir, file, ext;\n    splitpath(path, drive, dir, file, ext);\n\n    if (drive.empty()) {\n      const stringT exedir = getexecdir();\n      stringT exeDrive, dummy;\n      splitpath(exedir, exeDrive, dummy, dummy, dummy);\n      path = makepath(exeDrive, dir, file, ext);\n    }\n  }\n}\n\nstatic bool FileOP(const stringT &src, const stringT &dst,\n                   UINT wFunc)\n{\n  \/\/ wrapper for SHFileOperation() for moving or copying from src to dst\n  \/\/ create any intervening directories as necessary & automatically\n  TCHAR szSource[_MAX_PATH + 1];\n  TCHAR szDestination[_MAX_PATH + 1];\n\n  \/\/ SHFileOperation() acts very oddly if files are missing a drive\n  \/\/ (eg, renames to pwsafeN.psa instead of pwsafe.ibak)\n  \n  stringT srcD(src), dstD(dst);\n  pws_os::AddDrive(srcD);\n  pws_os::AddDrive(dstD);\n\n  if (srcD.length() >= _MAX_PATH || dstD.length() >= _MAX_PATH)\n    return false;\n\n  const TCHAR *lpsz_current = srcD.c_str();\n  const TCHAR *lpsz_new = dstD.c_str();\n\n#if (_MSC_VER >= 1400)\n  _tcscpy_s(szSource, _MAX_PATH, lpsz_current);\n  _tcscpy_s(szDestination, _MAX_PATH, lpsz_new);\n#else\n  _tcscpy(szSource, lpsz_current);\n  _tcscpy(szDestination, lpsz_new);\n#endif\n\n  \/\/ Must end with double NULL\n  szSource[srcD.length() + 1] = TCHAR('\\0');\n  szDestination[dstD.length() + 1] = TCHAR('\\0');\n\n  SHFILEOPSTRUCT sfop;\n  memset(&sfop, 0, sizeof(sfop));\n  sfop.hwnd = GetActiveWindow();\n  sfop.wFunc = wFunc;\n  sfop.pFrom = szSource;\n  sfop.pTo = szDestination;\n  sfop.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_SILENT | FOF_NOERRORUI;\n\n  return (SHFileOperation(&sfop) == 0);\n}\n\nbool pws_os::RenameFile(const stringT &oldname, const stringT &newname)\n{\n  _tremove(newname.c_str()); \/\/ otherwise rename may fail if newname exists\n  return FileOP(oldname, newname, FO_MOVE);\n}\n\nextern bool pws_os::CopyAFile(const stringT &from, const stringT &to)\n{\n  return FileOP(from, to, FO_COPY);\n}\n\nbool pws_os::DeleteAFile(const stringT &filename)\n{\n  return DeleteFile(filename.c_str()) == TRUE;\n}\n\nvoid pws_os::FindFiles(const stringT &filter, std::vector &res)\n{\n  res.clear();\n  _tfinddata_t fileinfo;\n  intptr_t handle = _tfindfirst(filter.c_str(), &fileinfo);\n  if (handle == -1)\n    return;\n\n  do {\n    res.push_back(LPCTSTR(fileinfo.name));\n  } while (_tfindnext(handle, &fileinfo) == 0);\n\n  _findclose(handle);\n}\n\n\/*\n* The file lock\/unlock functions were first implemented (in 2.08)\n* with Posix semantics (using open(_O_CREATE|_O_EXCL) to detect\n* an existing lock.\n* This fails to check liveness of the locker process, specifically,\n* if a user just turns of her PC, the lock file will remain.\n* So, I'm keeping the Posix code under idef POSIX_FILE_LOCK,\n* and re-implementing using the Win32 API, whose semantics\n* supposedly protect against this scenario.\n* Thanks to Frank (xformer) for discussion on the subject.\n*\/\n\nstatic stringT GetLockFileName(const stringT &filename)\n{\n  ASSERT(!filename.empty());\n  \/\/ derive lock filename from filename\n  stringT retval(filename, 0, filename.find_last_of(TCHAR('.')));\n  retval += _T(\".plk\");\n  return retval;\n}\n\nstatic void GetLocker(const stringT &lock_filename, stringT &locker)\n{\n  locker = _T(\"Unable to determine locker\");\n  \/\/ read locker data (\"user@machine:nnnnnnnn\") from file\n  TCHAR lockerStr[UNLEN + MAX_COMPUTERNAME_LENGTH + 11];\n  \/\/ flags here counter (my) intuition, but see\n  \/\/ http:\/\/msdn.microsoft.com\/library\/default.asp?url=\/library\/en-us\/fileio\/base\/creating_and_opening_files.asp\n  HANDLE h2 = ::CreateFile(lock_filename.c_str(),\n                           GENERIC_READ,\n                           FILE_SHARE_WRITE,\n                           NULL,\n                           OPEN_EXISTING,\n                           (FILE_ATTRIBUTE_NORMAL |\n                            \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                            SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION),\n                           NULL);\n  \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n  if (h2 != INVALID_HANDLE_VALUE) {\n    if (::GetFileType( h2 ) != FILE_TYPE_DISK) {\n      ::CloseHandle( h2 );\n      h2 = INVALID_HANDLE_VALUE;\n    }\n  }\n  \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n \n  if (h2 != INVALID_HANDLE_VALUE) {\n    DWORD bytesRead;\n    (void)::ReadFile(h2, lockerStr, sizeof(lockerStr)-1,\n                     &bytesRead, NULL);\n    CloseHandle(h2);\n    if (bytesRead > 0) {\n      lockerStr[bytesRead\/sizeof(TCHAR)] = TCHAR('\\0');\n      locker = lockerStr;\n    } \/\/ read info from lock file\n  }\n}\n\nbool pws_os::LockFile(const stringT &filename, stringT &locker, \n                      HANDLE &lockFileHandle, int &LockCount)\n{\n  const stringT lock_filename = GetLockFileName(filename);\n  stringT s_locker;\n  const stringT user = pws_os::getusername();\n  const stringT host = pws_os::gethostname();\n  const stringT pid = pws_os::getprocessid();\n\n  \/\/ Use Win32 API for locking - supposedly better at\n  \/\/ detecting dead locking processes\n  if (lockFileHandle != INVALID_HANDLE_VALUE) {\n    \/\/ here if we've open another (or same) dbase previously,\n    \/\/ need to unlock it. A bit inelegant...\n    \/\/ If app was minimized and ClearData() called, we've a small\n    \/\/ potential for a TOCTTOU issue here. Worse case, lock\n    \/\/ will fail.\n\n    const stringT cs_me = user + _T(\"@\") + host + _T(\":\") + pid;\n    GetLocker(lock_filename, s_locker);\n\n    if (cs_me == s_locker) {\n      LockCount++;\n      locker.clear();\n      return true;\n    } else {\n      pws_os::UnlockFile(filename, lockFileHandle, LockCount);\n    }\n  }\n\n  \/\/ Since ::CreateFile can't create directories, we need to check it exists\n  \/\/ first and, if not, try and create it.\n  \/\/ This is primarily for the config directory in the local APPDATA directory\n  \/\/ but will also be called for the database lock file - and since the database\n  \/\/ is already there, it is a bit of a redundant check but easier than coding\n  \/\/ for every different situation.\n  stringT sDrive, sDir, sName, sExt;\n  pws_os::splitpath(lock_filename, sDrive, sDir, sName, sExt);\n  stringT sNewDir = sDrive + sDir;\n\tDWORD dwAttrib = GetFileAttributes(sNewDir.c_str());\n  DWORD dwerr(0);\n  if (dwAttrib == INVALID_FILE_ATTRIBUTES)\n    dwerr = GetLastError();\n\n  BOOL brc(TRUE);\n  if (dwerr == ERROR_FILE_NOT_FOUND || \n      (dwAttrib != INVALID_FILE_ATTRIBUTES) &&\n      !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {\n    SECURITY_ATTRIBUTES secatt = {0};\n    secatt.nLength = sizeof(secatt);\n    brc = ::CreateDirectory(sNewDir.c_str(), &secatt);\n  }\n\n  \/\/ Obviously, if we can't create the directory - don't bother trying to\n  \/\/ create the lock file!\n  if (brc) {\n    lockFileHandle = ::CreateFile(lock_filename.c_str(),\n                                  GENERIC_WRITE,\n                                  FILE_SHARE_READ,\n                                  NULL,\n                                  CREATE_ALWAYS, \/\/ rely on share to fail if exists!\n                                  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH | \n                                  \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                                  SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,\n                                  NULL);\n\n    \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n    if (lockFileHandle != INVALID_HANDLE_VALUE) {\n      if (::GetFileType( lockFileHandle ) != FILE_TYPE_DISK) {\n        ::CloseHandle( lockFileHandle );\n        lockFileHandle = INVALID_HANDLE_VALUE;\n      }\n    }\n    \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n  }\n\n  if (lockFileHandle == INVALID_HANDLE_VALUE) {\n    DWORD error = GetLastError();\n    switch (error) {\n    case ERROR_SHARING_VIOLATION: \/\/ already open by a live process\n      GetLocker(lock_filename, s_locker);\n      locker = s_locker.c_str();\n      break;\n    default:\n      locker = _T(\"Cannot create lock file - no permission in directory?\");\n      break;\n    } \/\/ switch (error)\n    return false;\n  } else { \/\/ valid filehandle, write our info\n    DWORD numWrit, sumWrit;\n    BOOL write_status;\n    write_status = ::WriteFile(lockFileHandle,\n                               user.c_str(), user.length() * sizeof(TCHAR),\n                               &sumWrit, NULL);\n    write_status &= ::WriteFile(lockFileHandle,\n                                _T(\"@\"), sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                host.c_str(), host.length() * sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                _T(\":\"), sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                pid.c_str(), pid.length() * sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    ASSERT(sumWrit > 0);\n    LockCount++;\n    return (write_status == TRUE);\n  }\n}\n\nvoid pws_os::UnlockFile(const stringT &filename,\n                        HANDLE &lockFileHandle, int &LockCount)\n{\n  const stringT user = pws_os::getusername();\n  const stringT host = pws_os::gethostname();\n  const stringT pid = pws_os::getprocessid();\n\n  \/\/ Use Win32 API for locking - supposedly better at\n  \/\/ detecting dead locking processes\n  if (lockFileHandle != INVALID_HANDLE_VALUE) {\n    stringT locker;\n    const stringT lock_filename = GetLockFileName(filename);\n    const stringT cs_me = user + _T(\"@\") + host + _T(\":\") + pid;\n    GetLocker(lock_filename, locker);\n\n    if (cs_me == locker && LockCount > 1) {\n      LockCount--;\n    } else {\n      LockCount = 0;\n      CloseHandle(lockFileHandle);\n      lockFileHandle = INVALID_HANDLE_VALUE;\n      DeleteFile(lock_filename.c_str());\n    }\n  }\n}\n\nbool pws_os::IsLockedFile(const stringT &filename)\n{\n  const stringT lock_filename = GetLockFileName(filename);\n  \/\/ under this scheme, we need to actually try to open the file to determine\n  \/\/ if it's locked.\n  HANDLE h = CreateFile(lock_filename.c_str(),\n                        GENERIC_WRITE,\n                        FILE_SHARE_READ,\n                        NULL,\n                        OPEN_EXISTING, \/\/ don't create one!\n                        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH |\n                        \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                        SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,\n                        NULL);\n \n  \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n  if (h != INVALID_HANDLE_VALUE) {\n    if (::GetFileType( h ) != FILE_TYPE_DISK) {\n      ::CloseHandle( h );\n      h = INVALID_HANDLE_VALUE;\n    }\n  }\n  \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n \n  if (h == INVALID_HANDLE_VALUE) {\n    DWORD error = GetLastError();\n    if (error == ERROR_SHARING_VIOLATION)\n      return true;\n    else\n      return false; \/\/ couldn't open it, probably doesn't exist.\n  } else {\n    CloseHandle(h); \/\/ here if exists but lockable.\n    return false;\n  }\n}\n\nstd::FILE *pws_os::FOpen(const stringT &filename, const TCHAR *mode)\n{\n  std::FILE *fd = NULL;\n#if (_MSC_VER >= 1400)\n  _tfopen_s(&fd, filename.c_str(), mode);\n#else\n  fd = _tfopen(m_filename.c_str(), mode);\n#endif\n  return fd;\n}\n\nlong pws_os::fileLength(std::FILE *fp) {\n  if (fp != NULL) {\n    long pos = std::ftell(fp);\n    std::fseek(fp, 0, SEEK_END);\n    long len = ftell(fp);\n    std::fseek(fp, pos, SEEK_SET);\n    return len;\n  } else\n    return 0;\n}\nDon't crash if MRU list not full\/*\n* Copyright (c) 2003-2010 Rony Shapiro .\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/**\n * \\file Windows-specific implementation of file.h\n *\/\n\n#ifndef __WX__\n#include \n#endif\n\n#include \n#include  \/\/ for UNLEN definition\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"..\/typedefs.h\"\n#include \"..\/file.h\"\n#include \"..\/dir.h\"\n#include \"..\/env.h\"\n\nconst TCHAR pws_os::PathSeparator = _T('\\\\');\n\nbool pws_os::FileExists(const stringT &filename)\n{\n  struct _stat statbuf;\n  int status;\n\n  status = _tstat(filename.c_str(), &statbuf);\n  return (status == 0);\n}\n\nbool pws_os::FileExists(const stringT &filename, bool &bReadOnly)\n{\n  bool retval;\n  bReadOnly = false;\n\n  retval = (_taccess(filename.c_str(), R_OK) == 0);\n  if (retval) {\n    bReadOnly = (_taccess(filename.c_str(), W_OK) != 0);\n  }\n  return retval;\n}\n\nvoid pws_os::AddDrive(stringT &path)\n{\n  \/\/ Adds a drive letter to the path if not there, unless\n  \/\/ empty string  or it's a UNC path (\\\\host\\sharename...)\n  using namespace pws_os;\n  if(path.empty())\n    return;\n  if (!(path[0] == '\\\\' && path[1] == '\\\\')) {\n    stringT drive, dir, file, ext;\n    splitpath(path, drive, dir, file, ext);\n\n    if (drive.empty()) {\n      const stringT exedir = getexecdir();\n      stringT exeDrive, dummy;\n      splitpath(exedir, exeDrive, dummy, dummy, dummy);\n      path = makepath(exeDrive, dir, file, ext);\n    }\n  }\n}\n\nstatic bool FileOP(const stringT &src, const stringT &dst,\n                   UINT wFunc)\n{\n  \/\/ wrapper for SHFileOperation() for moving or copying from src to dst\n  \/\/ create any intervening directories as necessary & automatically\n  TCHAR szSource[_MAX_PATH + 1];\n  TCHAR szDestination[_MAX_PATH + 1];\n\n  \/\/ SHFileOperation() acts very oddly if files are missing a drive\n  \/\/ (eg, renames to pwsafeN.psa instead of pwsafe.ibak)\n  \n  stringT srcD(src), dstD(dst);\n  pws_os::AddDrive(srcD);\n  pws_os::AddDrive(dstD);\n\n  if (srcD.length() >= _MAX_PATH || dstD.length() >= _MAX_PATH)\n    return false;\n\n  const TCHAR *lpsz_current = srcD.c_str();\n  const TCHAR *lpsz_new = dstD.c_str();\n\n#if (_MSC_VER >= 1400)\n  _tcscpy_s(szSource, _MAX_PATH, lpsz_current);\n  _tcscpy_s(szDestination, _MAX_PATH, lpsz_new);\n#else\n  _tcscpy(szSource, lpsz_current);\n  _tcscpy(szDestination, lpsz_new);\n#endif\n\n  \/\/ Must end with double NULL\n  szSource[srcD.length() + 1] = TCHAR('\\0');\n  szDestination[dstD.length() + 1] = TCHAR('\\0');\n\n  SHFILEOPSTRUCT sfop;\n  memset(&sfop, 0, sizeof(sfop));\n  sfop.hwnd = GetActiveWindow();\n  sfop.wFunc = wFunc;\n  sfop.pFrom = szSource;\n  sfop.pTo = szDestination;\n  sfop.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_SILENT | FOF_NOERRORUI;\n\n  return (SHFileOperation(&sfop) == 0);\n}\n\nbool pws_os::RenameFile(const stringT &oldname, const stringT &newname)\n{\n  _tremove(newname.c_str()); \/\/ otherwise rename may fail if newname exists\n  return FileOP(oldname, newname, FO_MOVE);\n}\n\nextern bool pws_os::CopyAFile(const stringT &from, const stringT &to)\n{\n  return FileOP(from, to, FO_COPY);\n}\n\nbool pws_os::DeleteAFile(const stringT &filename)\n{\n  return DeleteFile(filename.c_str()) == TRUE;\n}\n\nvoid pws_os::FindFiles(const stringT &filter, std::vector &res)\n{\n  res.clear();\n  _tfinddata_t fileinfo;\n  intptr_t handle = _tfindfirst(filter.c_str(), &fileinfo);\n  if (handle == -1)\n    return;\n\n  do {\n    res.push_back(LPCTSTR(fileinfo.name));\n  } while (_tfindnext(handle, &fileinfo) == 0);\n\n  _findclose(handle);\n}\n\n\/*\n* The file lock\/unlock functions were first implemented (in 2.08)\n* with Posix semantics (using open(_O_CREATE|_O_EXCL) to detect\n* an existing lock.\n* This fails to check liveness of the locker process, specifically,\n* if a user just turns of her PC, the lock file will remain.\n* So, I'm keeping the Posix code under idef POSIX_FILE_LOCK,\n* and re-implementing using the Win32 API, whose semantics\n* supposedly protect against this scenario.\n* Thanks to Frank (xformer) for discussion on the subject.\n*\/\n\nstatic stringT GetLockFileName(const stringT &filename)\n{\n  ASSERT(!filename.empty());\n  \/\/ derive lock filename from filename\n  stringT retval(filename, 0, filename.find_last_of(TCHAR('.')));\n  retval += _T(\".plk\");\n  return retval;\n}\n\nstatic void GetLocker(const stringT &lock_filename, stringT &locker)\n{\n  locker = _T(\"Unable to determine locker\");\n  \/\/ read locker data (\"user@machine:nnnnnnnn\") from file\n  TCHAR lockerStr[UNLEN + MAX_COMPUTERNAME_LENGTH + 11];\n  \/\/ flags here counter (my) intuition, but see\n  \/\/ http:\/\/msdn.microsoft.com\/library\/default.asp?url=\/library\/en-us\/fileio\/base\/creating_and_opening_files.asp\n  HANDLE h2 = ::CreateFile(lock_filename.c_str(),\n                           GENERIC_READ,\n                           FILE_SHARE_WRITE,\n                           NULL,\n                           OPEN_EXISTING,\n                           (FILE_ATTRIBUTE_NORMAL |\n                            \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                            SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION),\n                           NULL);\n  \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n  if (h2 != INVALID_HANDLE_VALUE) {\n    if (::GetFileType( h2 ) != FILE_TYPE_DISK) {\n      ::CloseHandle( h2 );\n      h2 = INVALID_HANDLE_VALUE;\n    }\n  }\n  \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n \n  if (h2 != INVALID_HANDLE_VALUE) {\n    DWORD bytesRead;\n    (void)::ReadFile(h2, lockerStr, sizeof(lockerStr)-1,\n                     &bytesRead, NULL);\n    CloseHandle(h2);\n    if (bytesRead > 0) {\n      lockerStr[bytesRead\/sizeof(TCHAR)] = TCHAR('\\0');\n      locker = lockerStr;\n    } \/\/ read info from lock file\n  }\n}\n\nbool pws_os::LockFile(const stringT &filename, stringT &locker, \n                      HANDLE &lockFileHandle, int &LockCount)\n{\n  const stringT lock_filename = GetLockFileName(filename);\n  stringT s_locker;\n  const stringT user = pws_os::getusername();\n  const stringT host = pws_os::gethostname();\n  const stringT pid = pws_os::getprocessid();\n\n  \/\/ Use Win32 API for locking - supposedly better at\n  \/\/ detecting dead locking processes\n  if (lockFileHandle != INVALID_HANDLE_VALUE) {\n    \/\/ here if we've open another (or same) dbase previously,\n    \/\/ need to unlock it. A bit inelegant...\n    \/\/ If app was minimized and ClearData() called, we've a small\n    \/\/ potential for a TOCTTOU issue here. Worse case, lock\n    \/\/ will fail.\n\n    const stringT cs_me = user + _T(\"@\") + host + _T(\":\") + pid;\n    GetLocker(lock_filename, s_locker);\n\n    if (cs_me == s_locker) {\n      LockCount++;\n      locker.clear();\n      return true;\n    } else {\n      pws_os::UnlockFile(filename, lockFileHandle, LockCount);\n    }\n  }\n\n  \/\/ Since ::CreateFile can't create directories, we need to check it exists\n  \/\/ first and, if not, try and create it.\n  \/\/ This is primarily for the config directory in the local APPDATA directory\n  \/\/ but will also be called for the database lock file - and since the database\n  \/\/ is already there, it is a bit of a redundant check but easier than coding\n  \/\/ for every different situation.\n  stringT sDrive, sDir, sName, sExt;\n  pws_os::splitpath(lock_filename, sDrive, sDir, sName, sExt);\n  stringT sNewDir = sDrive + sDir;\n\tDWORD dwAttrib = GetFileAttributes(sNewDir.c_str());\n  DWORD dwerr(0);\n  if (dwAttrib == INVALID_FILE_ATTRIBUTES)\n    dwerr = GetLastError();\n\n  BOOL brc(TRUE);\n  if (dwerr == ERROR_FILE_NOT_FOUND || \n      (dwAttrib != INVALID_FILE_ATTRIBUTES) &&\n      !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {\n    SECURITY_ATTRIBUTES secatt = {0};\n    secatt.nLength = sizeof(secatt);\n    brc = ::CreateDirectory(sNewDir.c_str(), &secatt);\n  }\n\n  \/\/ Obviously, if we can't create the directory - don't bother trying to\n  \/\/ create the lock file!\n  if (brc) {\n    lockFileHandle = ::CreateFile(lock_filename.c_str(),\n                                  GENERIC_WRITE,\n                                  FILE_SHARE_READ,\n                                  NULL,\n                                  CREATE_ALWAYS, \/\/ rely on share to fail if exists!\n                                  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH | \n                                  \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                                  SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,\n                                  NULL);\n\n    \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n    if (lockFileHandle != INVALID_HANDLE_VALUE) {\n      if (::GetFileType( lockFileHandle ) != FILE_TYPE_DISK) {\n        ::CloseHandle( lockFileHandle );\n        lockFileHandle = INVALID_HANDLE_VALUE;\n      }\n    }\n    \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n  }\n\n  if (lockFileHandle == INVALID_HANDLE_VALUE) {\n    DWORD error = GetLastError();\n    switch (error) {\n    case ERROR_SHARING_VIOLATION: \/\/ already open by a live process\n      GetLocker(lock_filename, s_locker);\n      locker = s_locker.c_str();\n      break;\n    default:\n      locker = _T(\"Cannot create lock file - no permission in directory?\");\n      break;\n    } \/\/ switch (error)\n    return false;\n  } else { \/\/ valid filehandle, write our info\n    DWORD numWrit, sumWrit;\n    BOOL write_status;\n    write_status = ::WriteFile(lockFileHandle,\n                               user.c_str(), user.length() * sizeof(TCHAR),\n                               &sumWrit, NULL);\n    write_status &= ::WriteFile(lockFileHandle,\n                                _T(\"@\"), sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                host.c_str(), host.length() * sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                _T(\":\"), sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    write_status &= ::WriteFile(lockFileHandle,\n                                pid.c_str(), pid.length() * sizeof(TCHAR),\n                                &numWrit, NULL);\n    sumWrit += numWrit;\n    ASSERT(sumWrit > 0);\n    LockCount++;\n    return (write_status == TRUE);\n  }\n}\n\nvoid pws_os::UnlockFile(const stringT &filename,\n                        HANDLE &lockFileHandle, int &LockCount)\n{\n  const stringT user = pws_os::getusername();\n  const stringT host = pws_os::gethostname();\n  const stringT pid = pws_os::getprocessid();\n\n  \/\/ Use Win32 API for locking - supposedly better at\n  \/\/ detecting dead locking processes\n  if (lockFileHandle != INVALID_HANDLE_VALUE) {\n    stringT locker;\n    const stringT lock_filename = GetLockFileName(filename);\n    const stringT cs_me = user + _T(\"@\") + host + _T(\":\") + pid;\n    GetLocker(lock_filename, locker);\n\n    if (cs_me == locker && LockCount > 1) {\n      LockCount--;\n    } else {\n      LockCount = 0;\n      CloseHandle(lockFileHandle);\n      lockFileHandle = INVALID_HANDLE_VALUE;\n      DeleteFile(lock_filename.c_str());\n    }\n  }\n}\n\nbool pws_os::IsLockedFile(const stringT &filename)\n{\n  const stringT lock_filename = GetLockFileName(filename);\n  \/\/ under this scheme, we need to actually try to open the file to determine\n  \/\/ if it's locked.\n  HANDLE h = CreateFile(lock_filename.c_str(),\n                        GENERIC_WRITE,\n                        FILE_SHARE_READ,\n                        NULL,\n                        OPEN_EXISTING, \/\/ don't create one!\n                        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH |\n                        \/\/ (Lockheed Martin) Secure Coding  11-14-2007\n                        SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,\n                        NULL);\n \n  \/\/ Make sure it's a file and not a pipe.  (Lockheed Martin) Secure Coding  11-14-2007\n  if (h != INVALID_HANDLE_VALUE) {\n    if (::GetFileType( h ) != FILE_TYPE_DISK) {\n      ::CloseHandle( h );\n      h = INVALID_HANDLE_VALUE;\n    }\n  }\n  \/\/ End of Change.  (Lockheed Martin) Secure Coding  11-14-2007\n \n  if (h == INVALID_HANDLE_VALUE) {\n    DWORD error = GetLastError();\n    if (error == ERROR_SHARING_VIOLATION)\n      return true;\n    else\n      return false; \/\/ couldn't open it, probably doesn't exist.\n  } else {\n    CloseHandle(h); \/\/ here if exists but lockable.\n    return false;\n  }\n}\n\nstd::FILE *pws_os::FOpen(const stringT &filename, const TCHAR *mode)\n{\n  std::FILE *fd = NULL;\n#if (_MSC_VER >= 1400)\n  _tfopen_s(&fd, filename.c_str(), mode);\n#else\n  fd = _tfopen(m_filename.c_str(), mode);\n#endif\n  return fd;\n}\n\nlong pws_os::fileLength(std::FILE *fp) {\n  if (fp != NULL) {\n    long pos = std::ftell(fp);\n    std::fseek(fp, 0, SEEK_END);\n    long len = ftell(fp);\n    std::fseek(fp, pos, SEEK_SET);\n    return len;\n  } else\n    return 0;\n}\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/shell_integration.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\nusing content::BrowserThread;\n\nShellIntegration::DefaultWebClientSetPermission\n    ShellIntegration::CanSetAsDefaultProtocolClient() {\n  \/\/ Allowed as long as the browser can become the operating system default\n  \/\/ browser.\n  return CanSetAsDefaultBrowser();\n}\n\nShellIntegration::ShortcutInfo::ShortcutInfo()\n    : is_platform_app(false),\n      create_on_desktop(false),\n      create_in_applications_menu(false),\n      create_in_quick_launch_bar(false) {\n}\n\nShellIntegration::ShortcutInfo::~ShortcutInfo() {}\n\nstatic const struct ShellIntegration::AppModeInfo* gAppModeInfo = NULL;\n\n\/\/ static\nvoid ShellIntegration::SetAppModeInfo(const struct AppModeInfo* info) {\n  gAppModeInfo = info;\n}\n\n\/\/ static\nconst struct ShellIntegration::AppModeInfo* ShellIntegration::AppModeInfo() {\n  return gAppModeInfo;\n}\n\n\/\/ static\nbool ShellIntegration::IsRunningInAppMode() {\n  return gAppModeInfo != NULL;\n}\n\n\/\/ static\nCommandLine ShellIntegration::CommandLineArgsForLauncher(\n    const GURL& url,\n    const std::string& extension_app_id,\n    bool is_platform_app,\n    const FilePath& profile_path) {\n  const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n  CommandLine new_cmd_line(CommandLine::NO_PROGRAM);\n\n  \/\/ Use the same UserDataDir for new launches that we currently have set.\n  FilePath user_data_dir = cmd_line.GetSwitchValuePath(switches::kUserDataDir);\n  if (!user_data_dir.empty()) {\n    \/\/ Make sure user_data_dir is an absolute path.\n    if (file_util::AbsolutePath(&user_data_dir) &&\n        file_util::PathExists(user_data_dir)) {\n      new_cmd_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n    }\n  }\n\n#if defined(OS_CHROMEOS)\n  FilePath profile = cmd_line.GetSwitchValuePath(switches::kLoginProfile);\n  if (!profile.empty())\n    new_cmd_line.AppendSwitchPath(switches::kLoginProfile, profile);\n#else\n  if (!profile_path.empty() && !extension_app_id.empty())\n    new_cmd_line.AppendSwitchPath(switches::kProfileDirectory, profile_path);\n#endif\n\n  \/\/ If |extension_app_id| is present, we use the kAppId switch rather than\n  \/\/ the kApp switch (the launch url will be read from the extension app\n  \/\/ during launch.\n  if (!extension_app_id.empty()) {\n    new_cmd_line.AppendSwitchASCII(switches::kAppId, extension_app_id);\n    if (is_platform_app)\n      new_cmd_line.AppendSwitch(switches::kEnableExperimentalExtensionApis);\n  } else {\n    \/\/ Use '--app=url' instead of just 'url' to launch the browser with minimal\n    \/\/ chrome.\n    \/\/ Note: Do not change this flag!  Old Gears shortcuts will break if you do!\n    new_cmd_line.AppendSwitchASCII(switches::kApp, url.spec());\n  }\n  return new_cmd_line;\n}\n\n#if !defined(OS_WIN)\n\/\/ static\nbool ShellIntegration::SetAsDefaultBrowserInteractive() {\n  return false;\n}\n#endif\n\nbool ShellIntegration::DefaultWebClientObserver::IsOwnedByWorker() {\n  return false;\n}\n\nbool ShellIntegration::DefaultWebClientObserver::\n    IsInteractiveSetDefaultPermitted() {\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultWebClientWorker\n\/\/\n\nShellIntegration::DefaultWebClientWorker::DefaultWebClientWorker(\n    DefaultWebClientObserver* observer)\n    : observer_(observer) {\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::StartCheckIsDefault() {\n  if (observer_) {\n    observer_->SetDefaultWebClientUIState(STATE_PROCESSING);\n    BrowserThread::PostTask(\n        BrowserThread::FILE, FROM_HERE,\n        base::Bind(\n            &DefaultWebClientWorker::ExecuteCheckIsDefault, this));\n  }\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::StartSetAsDefault() {\n  bool interactive_permitted = false;\n  if (observer_) {\n    observer_->SetDefaultWebClientUIState(STATE_PROCESSING);\n    interactive_permitted = observer_->IsInteractiveSetDefaultPermitted();\n  }\n  BrowserThread::PostTask(\n      BrowserThread::FILE, FROM_HERE,\n      base::Bind(&DefaultWebClientWorker::ExecuteSetAsDefault, this,\n                 interactive_permitted));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::ObserverDestroyed() {\n  \/\/ Our associated view has gone away, so we shouldn't call back to it if\n  \/\/ our worker thread returns after the view is dead.\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  observer_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultWebClientWorker, private:\n\nvoid ShellIntegration::DefaultWebClientWorker::ExecuteCheckIsDefault() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n  DefaultWebClientState state = CheckIsDefault();\n  BrowserThread::PostTask(\n      BrowserThread::UI, FROM_HERE,\n      base::Bind(\n          &DefaultWebClientWorker::CompleteCheckIsDefault, this, state));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::CompleteCheckIsDefault(\n    DefaultWebClientState state) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  UpdateUI(state);\n  \/\/ The worker has finished everything it needs to do, so free the observer\n  \/\/ if we own it.\n  if (observer_ && observer_->IsOwnedByWorker()) {\n    delete observer_;\n    observer_ = NULL;\n  }\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::ExecuteSetAsDefault(\n    bool interactive_permitted) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n  bool result = SetAsDefault(interactive_permitted);\n  BrowserThread::PostTask(\n      BrowserThread::UI, FROM_HERE,\n      base::Bind(&DefaultWebClientWorker::CompleteSetAsDefault, this, result));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::CompleteSetAsDefault(\n    bool succeeded) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  \/\/ First tell the observer what the SetAsDefault call has returned.\n  if (observer_)\n    observer_->OnSetAsDefaultConcluded(succeeded);\n  \/\/ Set as default completed, check again to make sure it stuck...\n  StartCheckIsDefault();\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::UpdateUI(\n    DefaultWebClientState state) {\n  if (observer_) {\n    switch (state) {\n      case NOT_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_NOT_DEFAULT);\n        break;\n      case IS_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_IS_DEFAULT);\n        break;\n      case UNKNOWN_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_UNKNOWN);\n        break;\n      default:\n        break;\n    }\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultBrowserWorker\n\/\/\n\nShellIntegration::DefaultBrowserWorker::DefaultBrowserWorker(\n    DefaultWebClientObserver* observer)\n    : DefaultWebClientWorker(observer) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultBrowserWorker, private:\n\nShellIntegration::DefaultWebClientState\nShellIntegration::DefaultBrowserWorker::CheckIsDefault() {\n  return ShellIntegration::IsDefaultBrowser();\n}\n\nbool ShellIntegration::DefaultBrowserWorker::SetAsDefault(\n    bool interactive_permitted) {\n  bool result = false;\n  switch (ShellIntegration::CanSetAsDefaultBrowser()) {\n    case ShellIntegration::SET_DEFAULT_UNATTENDED:\n      result = ShellIntegration::SetAsDefaultBrowser();\n      break;\n    case ShellIntegration::SET_DEFAULT_INTERACTIVE:\n      if (interactive_permitted)\n        result = ShellIntegration::SetAsDefaultBrowserInteractive();\n      break;\n    default:\n      NOTREACHED();\n  }\n\n  return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultProtocolClientWorker\n\/\/\n\nShellIntegration::DefaultProtocolClientWorker::DefaultProtocolClientWorker(\n    DefaultWebClientObserver* observer, const std::string& protocol)\n    : DefaultWebClientWorker(observer),\n      protocol_(protocol) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultProtocolClientWorker, private:\n\nShellIntegration::DefaultWebClientState\nShellIntegration::DefaultProtocolClientWorker::CheckIsDefault() {\n  return ShellIntegration::IsDefaultProtocolClient(protocol_);\n}\n\nbool ShellIntegration::DefaultProtocolClientWorker::SetAsDefault(\n    bool interactive_permitted) {\n  return ShellIntegration::SetAsDefaultProtocolClient(protocol_);\n}\nFix command line for app shortcuts\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/shell_integration.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\nusing content::BrowserThread;\n\nShellIntegration::DefaultWebClientSetPermission\n    ShellIntegration::CanSetAsDefaultProtocolClient() {\n  \/\/ Allowed as long as the browser can become the operating system default\n  \/\/ browser.\n  return CanSetAsDefaultBrowser();\n}\n\nShellIntegration::ShortcutInfo::ShortcutInfo()\n    : is_platform_app(false),\n      create_on_desktop(false),\n      create_in_applications_menu(false),\n      create_in_quick_launch_bar(false) {\n}\n\nShellIntegration::ShortcutInfo::~ShortcutInfo() {}\n\nstatic const struct ShellIntegration::AppModeInfo* gAppModeInfo = NULL;\n\n\/\/ static\nvoid ShellIntegration::SetAppModeInfo(const struct AppModeInfo* info) {\n  gAppModeInfo = info;\n}\n\n\/\/ static\nconst struct ShellIntegration::AppModeInfo* ShellIntegration::AppModeInfo() {\n  return gAppModeInfo;\n}\n\n\/\/ static\nbool ShellIntegration::IsRunningInAppMode() {\n  return gAppModeInfo != NULL;\n}\n\n\/\/ static\nCommandLine ShellIntegration::CommandLineArgsForLauncher(\n    const GURL& url,\n    const std::string& extension_app_id,\n    bool is_platform_app,\n    const FilePath& profile_path) {\n  const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n  CommandLine new_cmd_line(CommandLine::NO_PROGRAM);\n\n  \/\/ Use the same UserDataDir for new launches that we currently have set.\n  FilePath user_data_dir = cmd_line.GetSwitchValuePath(switches::kUserDataDir);\n  if (!user_data_dir.empty()) {\n    \/\/ Make sure user_data_dir is an absolute path.\n    if (file_util::AbsolutePath(&user_data_dir) &&\n        file_util::PathExists(user_data_dir)) {\n      new_cmd_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n    }\n  }\n\n#if defined(OS_CHROMEOS)\n  FilePath profile = cmd_line.GetSwitchValuePath(switches::kLoginProfile);\n  if (!profile.empty())\n    new_cmd_line.AppendSwitchPath(switches::kLoginProfile, profile);\n#else\n  if (!profile_path.empty() && !extension_app_id.empty())\n    new_cmd_line.AppendSwitchPath(switches::kProfileDirectory,\n                                  profile_path.BaseName());\n#endif\n\n  \/\/ If |extension_app_id| is present, we use the kAppId switch rather than\n  \/\/ the kApp switch (the launch url will be read from the extension app\n  \/\/ during launch.\n  if (!extension_app_id.empty()) {\n    new_cmd_line.AppendSwitchASCII(switches::kAppId, extension_app_id);\n    if (is_platform_app)\n      new_cmd_line.AppendSwitch(switches::kEnableExperimentalExtensionApis);\n  } else {\n    \/\/ Use '--app=url' instead of just 'url' to launch the browser with minimal\n    \/\/ chrome.\n    \/\/ Note: Do not change this flag!  Old Gears shortcuts will break if you do!\n    new_cmd_line.AppendSwitchASCII(switches::kApp, url.spec());\n  }\n  return new_cmd_line;\n}\n\n#if !defined(OS_WIN)\n\/\/ static\nbool ShellIntegration::SetAsDefaultBrowserInteractive() {\n  return false;\n}\n#endif\n\nbool ShellIntegration::DefaultWebClientObserver::IsOwnedByWorker() {\n  return false;\n}\n\nbool ShellIntegration::DefaultWebClientObserver::\n    IsInteractiveSetDefaultPermitted() {\n  return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultWebClientWorker\n\/\/\n\nShellIntegration::DefaultWebClientWorker::DefaultWebClientWorker(\n    DefaultWebClientObserver* observer)\n    : observer_(observer) {\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::StartCheckIsDefault() {\n  if (observer_) {\n    observer_->SetDefaultWebClientUIState(STATE_PROCESSING);\n    BrowserThread::PostTask(\n        BrowserThread::FILE, FROM_HERE,\n        base::Bind(\n            &DefaultWebClientWorker::ExecuteCheckIsDefault, this));\n  }\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::StartSetAsDefault() {\n  bool interactive_permitted = false;\n  if (observer_) {\n    observer_->SetDefaultWebClientUIState(STATE_PROCESSING);\n    interactive_permitted = observer_->IsInteractiveSetDefaultPermitted();\n  }\n  BrowserThread::PostTask(\n      BrowserThread::FILE, FROM_HERE,\n      base::Bind(&DefaultWebClientWorker::ExecuteSetAsDefault, this,\n                 interactive_permitted));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::ObserverDestroyed() {\n  \/\/ Our associated view has gone away, so we shouldn't call back to it if\n  \/\/ our worker thread returns after the view is dead.\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  observer_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultWebClientWorker, private:\n\nvoid ShellIntegration::DefaultWebClientWorker::ExecuteCheckIsDefault() {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n  DefaultWebClientState state = CheckIsDefault();\n  BrowserThread::PostTask(\n      BrowserThread::UI, FROM_HERE,\n      base::Bind(\n          &DefaultWebClientWorker::CompleteCheckIsDefault, this, state));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::CompleteCheckIsDefault(\n    DefaultWebClientState state) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  UpdateUI(state);\n  \/\/ The worker has finished everything it needs to do, so free the observer\n  \/\/ if we own it.\n  if (observer_ && observer_->IsOwnedByWorker()) {\n    delete observer_;\n    observer_ = NULL;\n  }\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::ExecuteSetAsDefault(\n    bool interactive_permitted) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n  bool result = SetAsDefault(interactive_permitted);\n  BrowserThread::PostTask(\n      BrowserThread::UI, FROM_HERE,\n      base::Bind(&DefaultWebClientWorker::CompleteSetAsDefault, this, result));\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::CompleteSetAsDefault(\n    bool succeeded) {\n  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n  \/\/ First tell the observer what the SetAsDefault call has returned.\n  if (observer_)\n    observer_->OnSetAsDefaultConcluded(succeeded);\n  \/\/ Set as default completed, check again to make sure it stuck...\n  StartCheckIsDefault();\n}\n\nvoid ShellIntegration::DefaultWebClientWorker::UpdateUI(\n    DefaultWebClientState state) {\n  if (observer_) {\n    switch (state) {\n      case NOT_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_NOT_DEFAULT);\n        break;\n      case IS_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_IS_DEFAULT);\n        break;\n      case UNKNOWN_DEFAULT_WEB_CLIENT:\n        observer_->SetDefaultWebClientUIState(STATE_UNKNOWN);\n        break;\n      default:\n        break;\n    }\n  }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultBrowserWorker\n\/\/\n\nShellIntegration::DefaultBrowserWorker::DefaultBrowserWorker(\n    DefaultWebClientObserver* observer)\n    : DefaultWebClientWorker(observer) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultBrowserWorker, private:\n\nShellIntegration::DefaultWebClientState\nShellIntegration::DefaultBrowserWorker::CheckIsDefault() {\n  return ShellIntegration::IsDefaultBrowser();\n}\n\nbool ShellIntegration::DefaultBrowserWorker::SetAsDefault(\n    bool interactive_permitted) {\n  bool result = false;\n  switch (ShellIntegration::CanSetAsDefaultBrowser()) {\n    case ShellIntegration::SET_DEFAULT_UNATTENDED:\n      result = ShellIntegration::SetAsDefaultBrowser();\n      break;\n    case ShellIntegration::SET_DEFAULT_INTERACTIVE:\n      if (interactive_permitted)\n        result = ShellIntegration::SetAsDefaultBrowserInteractive();\n      break;\n    default:\n      NOTREACHED();\n  }\n\n  return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ShellIntegration::DefaultProtocolClientWorker\n\/\/\n\nShellIntegration::DefaultProtocolClientWorker::DefaultProtocolClientWorker(\n    DefaultWebClientObserver* observer, const std::string& protocol)\n    : DefaultWebClientWorker(observer),\n      protocol_(protocol) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DefaultProtocolClientWorker, private:\n\nShellIntegration::DefaultWebClientState\nShellIntegration::DefaultProtocolClientWorker::CheckIsDefault() {\n  return ShellIntegration::IsDefaultProtocolClient(protocol_);\n}\n\nbool ShellIntegration::DefaultProtocolClientWorker::SetAsDefault(\n    bool interactive_permitted) {\n  return ShellIntegration::SetAsDefaultProtocolClient(protocol_);\n}\n<|endoftext|>"}
{"text":"#include \n#include \n\nusing namespace osg;\n\nColorMatrix::ColorMatrix()\n{\n}\n\n\nColorMatrix::~ColorMatrix()\n{\n}\n\nvoid ColorMatrix::apply(State&) const\n{\n\/\/    std::cout<<\"applying matrix\"<<_matrix<Added check for GL_ARB_imaging extension to osg;:ColorMatrix#include \n#include \n#include \n\nusing namespace osg;\n\nColorMatrix::ColorMatrix()\n{\n}\n\n\nColorMatrix::~ColorMatrix()\n{\n}\n\nvoid ColorMatrix::apply(State&) const\n{\n\/\/    std::cout<<\"applying matrix\"<<_matrix<"}
{"text":"Adding in a constant for hover slide opacity so that the hover is more visible in different windows variations (e.g., aero).<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/flags_ui.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/about_flags.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_web_ui_data_source.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/browser\/web_ui_message_handler.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources_standard.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/cros_settings.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#endif\n\nusing content::WebContents;\nusing content::WebUIMessageHandler;\n\nnamespace {\n\nChromeWebUIDataSource* CreateFlagsUIHTMLSource() {\n  ChromeWebUIDataSource* source =\n      new ChromeWebUIDataSource(chrome::kChromeUIFlagsHost);\n\n  source->AddLocalizedString(\"flagsLongTitle\", IDS_FLAGS_LONG_TITLE);\n  source->AddLocalizedString(\"flagsTableTitle\", IDS_FLAGS_TABLE_TITLE);\n  source->AddLocalizedString(\"flagsNoExperimentsAvailable\",\n                             IDS_FLAGS_NO_EXPERIMENTS_AVAILABLE);\n  source->AddLocalizedString(\"flagsWarningHeader\", IDS_FLAGS_WARNING_HEADER);\n  source->AddLocalizedString(\"flagsBlurb\", IDS_FLAGS_WARNING_TEXT);\n  source->AddLocalizedString(\"flagsNotSupported\", IDS_FLAGS_NOT_AVAILABLE);\n  source->AddLocalizedString(\"flagsRestartNotice\", IDS_FLAGS_RELAUNCH_NOTICE);\n  source->AddLocalizedString(\"flagsRestartButton\", IDS_FLAGS_RELAUNCH_BUTTON);\n  source->AddLocalizedString(\"disable\", IDS_FLAGS_DISABLE);\n  source->AddLocalizedString(\"enable\", IDS_FLAGS_ENABLE);\n#if defined(OS_CHROMEOS)\n  \/\/ Set the strings to show which user can actually change the flags\n  source->AddLocalizedString(\"ownerOnly\", IDS_OPTIONS_ACCOUNTS_OWNER_ONLY);\n  std::string owner;\n  chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner);\n  source->AddString(\"ownerUserId\", UTF8ToUTF16(owner));\n#endif\n\n  source->set_json_path(\"strings.js\");\n  source->add_resource_path(\"flags.js\", IDR_FLAGS_JS);\n\n  int idr = IDR_FLAGS_HTML;\n#if defined (OS_CHROMEOS)\n  if (!chromeos::UserManager::Get()->current_user_is_owner())\n    idr = IDR_FLAGS_HTML_WARNING;\n#endif\n  source->set_default_resource(idr);\n  return source;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ FlagsDOMHandler\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ The handler for Javascript messages for the about:flags page.\nclass FlagsDOMHandler : public WebUIMessageHandler {\n public:\n  FlagsDOMHandler() {}\n  virtual ~FlagsDOMHandler() {}\n\n  \/\/ WebUIMessageHandler implementation.\n  virtual void RegisterMessages() OVERRIDE;\n\n  \/\/ Callback for the \"requestFlagsExperiments\" message.\n  void HandleRequestFlagsExperiments(const ListValue* args);\n\n  \/\/ Callback for the \"enableFlagsExperiment\" message.\n  void HandleEnableFlagsExperimentMessage(const ListValue* args);\n\n  \/\/ Callback for the \"restartBrowser\" message. Restores all tabs on restart.\n  void HandleRestartBrowser(const ListValue* args);\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(FlagsDOMHandler);\n};\n\nvoid FlagsDOMHandler::RegisterMessages() {\n  web_ui()->RegisterMessageCallback(\"requestFlagsExperiments\",\n      base::Bind(&FlagsDOMHandler::HandleRequestFlagsExperiments,\n                 base::Unretained(this)));\n  web_ui()->RegisterMessageCallback(\"enableFlagsExperiment\",\n      base::Bind(&FlagsDOMHandler::HandleEnableFlagsExperimentMessage,\n                 base::Unretained(this)));\n  web_ui()->RegisterMessageCallback(\"restartBrowser\",\n      base::Bind(&FlagsDOMHandler::HandleRestartBrowser,\n                 base::Unretained(this)));\n}\n\nvoid FlagsDOMHandler::HandleRequestFlagsExperiments(const ListValue* args) {\n  DictionaryValue results;\n  results.Set(\"flagsExperiments\",\n              about_flags::GetFlagsExperimentsData(\n                  g_browser_process->local_state()));\n  results.SetBoolean(\"needsRestart\",\n                     about_flags::IsRestartNeededToCommitChanges());\n  web_ui()->CallJavascriptFunction(\"returnFlagsExperiments\", results);\n}\n\nvoid FlagsDOMHandler::HandleEnableFlagsExperimentMessage(\n    const ListValue* args) {\n  DCHECK_EQ(2u, args->GetSize());\n  if (args->GetSize() != 2)\n    return;\n\n  std::string experiment_internal_name;\n  std::string enable_str;\n  if (!args->GetString(0, &experiment_internal_name) ||\n      !args->GetString(1, &enable_str))\n    return;\n\n  about_flags::SetExperimentEnabled(\n      g_browser_process->local_state(),\n      experiment_internal_name,\n      enable_str == \"true\");\n}\n\nvoid FlagsDOMHandler::HandleRestartBrowser(const ListValue* args) {\n  BrowserList::AttemptRestart();\n}\n\n}  \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ FlagsUI\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) {\n  web_ui->AddMessageHandler(new FlagsDOMHandler());\n\n  \/\/ Set up the about:flags source.\n  Profile* profile = Profile::FromWebUI(web_ui);\n  profile->GetChromeURLDataManager()->AddDataSource(CreateFlagsUIHTMLSource());\n}\n\n\/\/ static\nRefCountedMemory* FlagsUI::GetFaviconResourceBytes() {\n  return ResourceBundle::GetSharedInstance().\n      LoadDataResourceBytes(IDR_FLAGS);\n}\n\n\/\/ static\nvoid FlagsUI::RegisterPrefs(PrefService* prefs) {\n  prefs->RegisterListPref(prefs::kEnabledLabsExperiments);\n}\nchromeos: Allow chrome:\/\/flags to show up when running on a linux desktop.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/flags_ui.h\"\n\n#include \n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/about_flags.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/webui\/chrome_web_ui_data_source.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/browser\/web_ui_message_handler.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources_standard.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/cros_settings.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/chromeos\/system\/runtime_environment.h\"\n#endif\n\nusing content::WebContents;\nusing content::WebUIMessageHandler;\n\nnamespace {\n\nChromeWebUIDataSource* CreateFlagsUIHTMLSource() {\n  ChromeWebUIDataSource* source =\n      new ChromeWebUIDataSource(chrome::kChromeUIFlagsHost);\n\n  source->AddLocalizedString(\"flagsLongTitle\", IDS_FLAGS_LONG_TITLE);\n  source->AddLocalizedString(\"flagsTableTitle\", IDS_FLAGS_TABLE_TITLE);\n  source->AddLocalizedString(\"flagsNoExperimentsAvailable\",\n                             IDS_FLAGS_NO_EXPERIMENTS_AVAILABLE);\n  source->AddLocalizedString(\"flagsWarningHeader\", IDS_FLAGS_WARNING_HEADER);\n  source->AddLocalizedString(\"flagsBlurb\", IDS_FLAGS_WARNING_TEXT);\n  source->AddLocalizedString(\"flagsNotSupported\", IDS_FLAGS_NOT_AVAILABLE);\n  source->AddLocalizedString(\"flagsRestartNotice\", IDS_FLAGS_RELAUNCH_NOTICE);\n  source->AddLocalizedString(\"flagsRestartButton\", IDS_FLAGS_RELAUNCH_BUTTON);\n  source->AddLocalizedString(\"disable\", IDS_FLAGS_DISABLE);\n  source->AddLocalizedString(\"enable\", IDS_FLAGS_ENABLE);\n#if defined(OS_CHROMEOS)\n  \/\/ Set the strings to show which user can actually change the flags\n  source->AddLocalizedString(\"ownerOnly\", IDS_OPTIONS_ACCOUNTS_OWNER_ONLY);\n  std::string owner;\n  chromeos::CrosSettings::Get()->GetString(chromeos::kDeviceOwner, &owner);\n  source->AddString(\"ownerUserId\", UTF8ToUTF16(owner));\n#endif\n\n  source->set_json_path(\"strings.js\");\n  source->add_resource_path(\"flags.js\", IDR_FLAGS_JS);\n\n  int idr = IDR_FLAGS_HTML;\n#if defined (OS_CHROMEOS)\n  if (!chromeos::UserManager::Get()->current_user_is_owner() &&\n      chromeos::system::runtime_environment::IsRunningOnChromeOS())\n    idr = IDR_FLAGS_HTML_WARNING;\n#endif\n  source->set_default_resource(idr);\n  return source;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ FlagsDOMHandler\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ The handler for Javascript messages for the about:flags page.\nclass FlagsDOMHandler : public WebUIMessageHandler {\n public:\n  FlagsDOMHandler() {}\n  virtual ~FlagsDOMHandler() {}\n\n  \/\/ WebUIMessageHandler implementation.\n  virtual void RegisterMessages() OVERRIDE;\n\n  \/\/ Callback for the \"requestFlagsExperiments\" message.\n  void HandleRequestFlagsExperiments(const ListValue* args);\n\n  \/\/ Callback for the \"enableFlagsExperiment\" message.\n  void HandleEnableFlagsExperimentMessage(const ListValue* args);\n\n  \/\/ Callback for the \"restartBrowser\" message. Restores all tabs on restart.\n  void HandleRestartBrowser(const ListValue* args);\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(FlagsDOMHandler);\n};\n\nvoid FlagsDOMHandler::RegisterMessages() {\n  web_ui()->RegisterMessageCallback(\"requestFlagsExperiments\",\n      base::Bind(&FlagsDOMHandler::HandleRequestFlagsExperiments,\n                 base::Unretained(this)));\n  web_ui()->RegisterMessageCallback(\"enableFlagsExperiment\",\n      base::Bind(&FlagsDOMHandler::HandleEnableFlagsExperimentMessage,\n                 base::Unretained(this)));\n  web_ui()->RegisterMessageCallback(\"restartBrowser\",\n      base::Bind(&FlagsDOMHandler::HandleRestartBrowser,\n                 base::Unretained(this)));\n}\n\nvoid FlagsDOMHandler::HandleRequestFlagsExperiments(const ListValue* args) {\n  DictionaryValue results;\n  results.Set(\"flagsExperiments\",\n              about_flags::GetFlagsExperimentsData(\n                  g_browser_process->local_state()));\n  results.SetBoolean(\"needsRestart\",\n                     about_flags::IsRestartNeededToCommitChanges());\n  web_ui()->CallJavascriptFunction(\"returnFlagsExperiments\", results);\n}\n\nvoid FlagsDOMHandler::HandleEnableFlagsExperimentMessage(\n    const ListValue* args) {\n  DCHECK_EQ(2u, args->GetSize());\n  if (args->GetSize() != 2)\n    return;\n\n  std::string experiment_internal_name;\n  std::string enable_str;\n  if (!args->GetString(0, &experiment_internal_name) ||\n      !args->GetString(1, &enable_str))\n    return;\n\n  about_flags::SetExperimentEnabled(\n      g_browser_process->local_state(),\n      experiment_internal_name,\n      enable_str == \"true\");\n}\n\nvoid FlagsDOMHandler::HandleRestartBrowser(const ListValue* args) {\n  BrowserList::AttemptRestart();\n}\n\n}  \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ FlagsUI\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFlagsUI::FlagsUI(content::WebUI* web_ui) : WebUIController(web_ui) {\n  web_ui->AddMessageHandler(new FlagsDOMHandler());\n\n  \/\/ Set up the about:flags source.\n  Profile* profile = Profile::FromWebUI(web_ui);\n  profile->GetChromeURLDataManager()->AddDataSource(CreateFlagsUIHTMLSource());\n}\n\n\/\/ static\nRefCountedMemory* FlagsUI::GetFaviconResourceBytes() {\n  return ResourceBundle::GetSharedInstance().\n      LoadDataResourceBytes(IDR_FLAGS);\n}\n\n\/\/ static\nvoid FlagsUI::RegisterPrefs(PrefService* prefs) {\n  prefs->RegisterListPref(prefs::kEnabledLabsExperiments);\n}\n<|endoftext|>"}
{"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace osgDB;\n\nXmlNode* osgDB::readXmlFile(const std::string& filename,const Options* options)\n{\n    std::string foundFile = osgDB::findDataFile(filename, options);\n    if (!foundFile.empty())\n    {\n        XmlNode::Input input;\n        input.open(foundFile);\n        input.readAllDataIntoBuffer();\n\n        if (!input)\n        {\n            OSG_NOTICE<<\"Could not open XML file: \"< root = new XmlNode;\n        root->read(input);\n\n        return root.release();\n    }\n    else\n    {\n        OSG_NOTICE<<\"Could not find XML file: \"< root = new XmlNode;\n    root->read(input);\n\n    return root.release();\n}\n\nXmlNode::ControlMap::ControlMap()\n{\n    setUpControlMappings();\n}\n\nvoid XmlNode::ControlMap::addControlToCharacter(const std::string& control, int c)\n{\n    _controlToCharacterMap[control] = c;\n    _characterToControlMap[c] = control;\n}\n\nvoid XmlNode::ControlMap::setUpControlMappings()\n{\n    addControlToCharacter(\"&\",'&');\n    addControlToCharacter(\"<\",'<');\n    addControlToCharacter(\">\",'>');\n    addControlToCharacter(\""\",'\"');\n    addControlToCharacter(\"'\",'\\'');\n}\n\nXmlNode::Input::Input():\n    _currentPos(0)\n{\n}\n\nXmlNode::Input::Input(const Input&):\n    ControlMap(),\n    _currentPos(0)\n{\n}\n\nXmlNode::Input::~Input()\n{\n}\nvoid XmlNode::Input::open(const std::string& filename)\n{\n    _fin.open(filename.c_str());\n}\n\nvoid XmlNode::Input::attach(std::istream& fin)\n{\n    std::ios &fios = _fin;\n    fios.rdbuf(fin.rdbuf());\n}\n\nvoid XmlNode::Input::readAllDataIntoBuffer()\n{\n    while(_fin)\n    {\n        int c = _fin.get();\n        if (c>=0 && c<=255)\n        {\n            _buffer.push_back(c);\n        }\n    }\n}\n\nvoid XmlNode::Input::skipWhiteSpace()\n{\n    while(_currentPos<_buffer.size() && (_buffer[_currentPos]==' ' || _buffer[_currentPos]=='\\t' || _buffer[_currentPos]=='\\n' || _buffer[_currentPos]=='\\r'))\n    {\n        \/\/OSG_NOTICE<<\"_currentPos=\"<<_currentPos<<\"_buffer.size()=\"<<_buffer.size()<<\" v=\"<type = XmlNode::COMMENT;\n            children.push_back(commentNode);\n\n            input += 4;\n            XmlNode::Input::size_type end = input.find(\"-->\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid Comment record [\"<contents<<\"]\"<contents<<\"]\"<\");\n            std::string comment = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid end tag [\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            ++input;\n            XmlNode::Input::size_type end = input.find(\">\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 9;\n            XmlNode::Input::size_type end = input.find(\"]]>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 2;\n            XmlNode::Input::size_type end = input.find(\"?>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::NODE;\n            children.push_back(childNode);\n\n            input += 1;\n\n            input.skipWhiteSpace();\n\n            int c = 0;\n            while ((c=input[0])>=0 && c!=' ' && c!='\\n' && c!='\\r' && c!='>' && c!='\/')\n            {\n                childNode->name.push_back(c);\n                ++input;\n            }\n\n            while ((c=input[0])>=0 && c!='>' && c!='\/')\n            {\n                Input::size_type prev_pos = input.currentPosition();\n\n                input.skipWhiteSpace();\n                std::string option;\n                std::string value;\n\n                if (input[0]=='\"')\n                {\n                    option.push_back(input[0]);\n                    ++input;\n                    while((c=input[0])>=0 && c!='\"')\n                    {\n                        if (c=='&')\n                            readAndReplaceControl(option, input);\n                        else\n                        {\n                            option.push_back(c);\n                            ++input;\n                        }\n                    }\n                    option.push_back(input[0]);\n                    ++input;\n                }\n                else\n                {\n                    while((c=input[0])>=0 && c!='>' && c!='\/' && c!='\"' && c!='\\'' && c!='=' && c!=' ' && c!='\\n' && c!='\\r')\n                    {\n                        option.push_back(c);\n                        ++input;\n                    }\n                }\n\n                input.skipWhiteSpace();\n                if (input[0]=='=')\n                {\n                    ++input;\n\n                    input.skipWhiteSpace();\n\n                    if (input[0]=='\"')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\"')\n                        {\n                            if (c=='&')\n                                readAndReplaceControl(value, input);\n                            else\n                            {\n                                value.push_back(c);\n                                ++input;\n                            }\n                        }\n                        ++input;\n                    }\n                    else if (input[0]=='\\'')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\\'')\n                        {\n                            if (c=='&')\n                                readAndReplaceControl(value, input);\n                            else\n                            {\n                                value.push_back(c);\n                                ++input;\n                            }\n                        }\n                        ++input;\n                    }\n                    else\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!=' ' && c!='\\n' && c!='\\r' && c!='\"' && c!='\\'' && c!='>')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                    }\n                }\n\n                if (prev_pos == input.currentPosition())\n                {\n                    OSG_NOTICE<<\"Error, parser iterator not advanced, position: \"<properties[option] = value;\n                }\n            }\n\n            if ((c=input[0])>=0 && (c=='>' || c=='\/'))\n            {\n                ++input;\n\n                OSG_INFO<<\"Valid tag [\"<name<<\"]\"<=0 && c=='>')\n                    {\n                        ++input;\n                        OSG_INFO<<\"tag is closed correctly\"<type = ATOM;\n                    }\n                    else\n                        OSG_NOTICE<<\"Error: tag is not closed correctly\"<read(input);\n                    if (!result) return false;\n                }\n\n                if (type==NODE && !children.empty()) type = GROUP;\n            }\n            else\n            {\n                OSG_NOTICE<<\"Unclosed tag [\"<name<<\"]\"<\"<\"; writeString(controlMap, fout, contents); fout<<\"<\/\"<\"<\"<\"<\"<\"<second;\n        else fout.put(c);\n    }\n    return true;\n}\n\nbool XmlNode::writeChildren(const ControlMap& \/*controlMap*\/, std::ostream& fout, const std::string& indent) const\n{\n    for(Children::const_iterator citr = children.begin();\n        citr != children.end();\n        ++citr)\n    {\n        if (!(*citr)->write(fout, indent))\n            return false;\n    }\n\n    return true;\n}\n\nbool XmlNode::writeProperties(const ControlMap& controlMap, std::ostream& fout) const\n{\n    for(Properties::const_iterator oitr = properties.begin();\n        oitr != properties.end();\n        ++oitr)\n    {\n        fout<<\" \"<first<<\"=\\\"\";\n        if (!writeString(controlMap,fout,oitr->second))\n            return false;\n        fout<<\"\\\"\";\n    }\n\n    return true;\n}\n\nbool XmlNode::readAndReplaceControl(std::string& contents, XmlNode::Input& input)\n{\n    int c = 0;\n    std::string value;\n    while(input && (c=input.get())!=';') { value.push_back(c); }\n    value.push_back(c);\n\n    if (input._controlToCharacterMap.count(value)!=0)\n    {\n        c = input._controlToCharacterMap[value];\n        OSG_INFO<<\"Read control character \"<Added &nl; xml control character to allow one to put newlines into a single text string in Present3D presentations\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace osgDB;\n\nXmlNode* osgDB::readXmlFile(const std::string& filename,const Options* options)\n{\n    std::string foundFile = osgDB::findDataFile(filename, options);\n    if (!foundFile.empty())\n    {\n        XmlNode::Input input;\n        input.open(foundFile);\n        input.readAllDataIntoBuffer();\n\n        if (!input)\n        {\n            OSG_NOTICE<<\"Could not open XML file: \"< root = new XmlNode;\n        root->read(input);\n\n        return root.release();\n    }\n    else\n    {\n        OSG_NOTICE<<\"Could not find XML file: \"< root = new XmlNode;\n    root->read(input);\n\n    return root.release();\n}\n\nXmlNode::ControlMap::ControlMap()\n{\n    setUpControlMappings();\n}\n\nvoid XmlNode::ControlMap::addControlToCharacter(const std::string& control, int c)\n{\n    _controlToCharacterMap[control] = c;\n    _characterToControlMap[c] = control;\n}\n\nvoid XmlNode::ControlMap::setUpControlMappings()\n{\n    addControlToCharacter(\"&\",'&');\n    addControlToCharacter(\"<\",'<');\n    addControlToCharacter(\">\",'>');\n    addControlToCharacter(\""\",'\"');\n    addControlToCharacter(\"'\",'\\'');\n    addControlToCharacter(\"&nl;\",'\\n');\n}\n\nXmlNode::Input::Input():\n    _currentPos(0)\n{\n}\n\nXmlNode::Input::Input(const Input&):\n    ControlMap(),\n    _currentPos(0)\n{\n}\n\nXmlNode::Input::~Input()\n{\n}\nvoid XmlNode::Input::open(const std::string& filename)\n{\n    _fin.open(filename.c_str());\n}\n\nvoid XmlNode::Input::attach(std::istream& fin)\n{\n    std::ios &fios = _fin;\n    fios.rdbuf(fin.rdbuf());\n}\n\nvoid XmlNode::Input::readAllDataIntoBuffer()\n{\n    while(_fin)\n    {\n        int c = _fin.get();\n        if (c>=0 && c<=255)\n        {\n            _buffer.push_back(c);\n        }\n    }\n}\n\nvoid XmlNode::Input::skipWhiteSpace()\n{\n    while(_currentPos<_buffer.size() && (_buffer[_currentPos]==' ' || _buffer[_currentPos]=='\\t' || _buffer[_currentPos]=='\\n' || _buffer[_currentPos]=='\\r'))\n    {\n        \/\/OSG_NOTICE<<\"_currentPos=\"<<_currentPos<<\"_buffer.size()=\"<<_buffer.size()<<\" v=\"<type = XmlNode::COMMENT;\n            children.push_back(commentNode);\n\n            input += 4;\n            XmlNode::Input::size_type end = input.find(\"-->\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid Comment record [\"<contents<<\"]\"<contents<<\"]\"<\");\n            std::string comment = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid end tag [\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            ++input;\n            XmlNode::Input::size_type end = input.find(\">\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 9;\n            XmlNode::Input::size_type end = input.find(\"]]>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 2;\n            XmlNode::Input::size_type end = input.find(\"?>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                OSG_INFO<<\"Valid information record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::NODE;\n            children.push_back(childNode);\n\n            input += 1;\n\n            input.skipWhiteSpace();\n\n            int c = 0;\n            while ((c=input[0])>=0 && c!=' ' && c!='\\n' && c!='\\r' && c!='>' && c!='\/')\n            {\n                childNode->name.push_back(c);\n                ++input;\n            }\n\n            while ((c=input[0])>=0 && c!='>' && c!='\/')\n            {\n                Input::size_type prev_pos = input.currentPosition();\n\n                input.skipWhiteSpace();\n                std::string option;\n                std::string value;\n\n                if (input[0]=='\"')\n                {\n                    option.push_back(input[0]);\n                    ++input;\n                    while((c=input[0])>=0 && c!='\"')\n                    {\n                        if (c=='&')\n                            readAndReplaceControl(option, input);\n                        else\n                        {\n                            option.push_back(c);\n                            ++input;\n                        }\n                    }\n                    option.push_back(input[0]);\n                    ++input;\n                }\n                else\n                {\n                    while((c=input[0])>=0 && c!='>' && c!='\/' && c!='\"' && c!='\\'' && c!='=' && c!=' ' && c!='\\n' && c!='\\r')\n                    {\n                        option.push_back(c);\n                        ++input;\n                    }\n                }\n\n                input.skipWhiteSpace();\n                if (input[0]=='=')\n                {\n                    ++input;\n\n                    input.skipWhiteSpace();\n\n                    if (input[0]=='\"')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\"')\n                        {\n                            if (c=='&')\n                                readAndReplaceControl(value, input);\n                            else\n                            {\n                                value.push_back(c);\n                                ++input;\n                            }\n                        }\n                        ++input;\n                    }\n                    else if (input[0]=='\\'')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\\'')\n                        {\n                            if (c=='&')\n                                readAndReplaceControl(value, input);\n                            else\n                            {\n                                value.push_back(c);\n                                ++input;\n                            }\n                        }\n                        ++input;\n                    }\n                    else\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!=' ' && c!='\\n' && c!='\\r' && c!='\"' && c!='\\'' && c!='>')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                    }\n                }\n\n                if (prev_pos == input.currentPosition())\n                {\n                    OSG_NOTICE<<\"Error, parser iterator not advanced, position: \"<properties[option] = value;\n                }\n            }\n\n            if ((c=input[0])>=0 && (c=='>' || c=='\/'))\n            {\n                ++input;\n\n                OSG_INFO<<\"Valid tag [\"<name<<\"]\"<=0 && c=='>')\n                    {\n                        ++input;\n                        OSG_INFO<<\"tag is closed correctly\"<type = ATOM;\n                    }\n                    else\n                        OSG_NOTICE<<\"Error: tag is not closed correctly\"<read(input);\n                    if (!result) return false;\n                }\n\n                if (type==NODE && !children.empty()) type = GROUP;\n            }\n            else\n            {\n                OSG_NOTICE<<\"Unclosed tag [\"<name<<\"]\"<\"<\"; writeString(controlMap, fout, contents); fout<<\"<\/\"<\"<\"<\"<\"<\"<second;\n        else fout.put(c);\n    }\n    return true;\n}\n\nbool XmlNode::writeChildren(const ControlMap& \/*controlMap*\/, std::ostream& fout, const std::string& indent) const\n{\n    for(Children::const_iterator citr = children.begin();\n        citr != children.end();\n        ++citr)\n    {\n        if (!(*citr)->write(fout, indent))\n            return false;\n    }\n\n    return true;\n}\n\nbool XmlNode::writeProperties(const ControlMap& controlMap, std::ostream& fout) const\n{\n    for(Properties::const_iterator oitr = properties.begin();\n        oitr != properties.end();\n        ++oitr)\n    {\n        fout<<\" \"<first<<\"=\\\"\";\n        if (!writeString(controlMap,fout,oitr->second))\n            return false;\n        fout<<\"\\\"\";\n    }\n\n    return true;\n}\n\nbool XmlNode::readAndReplaceControl(std::string& contents, XmlNode::Input& input)\n{\n    int c = 0;\n    std::string value;\n    while(input && (c=input.get())!=';') { value.push_back(c); }\n    value.push_back(c);\n\n    if (input._controlToCharacterMap.count(value)!=0)\n    {\n        c = input._controlToCharacterMap[value];\n        OSG_INFO<<\"Read control character \"<"}
{"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace osgDB;\n\nXmlNode* osgDB::readXmlFile(const std::string& filename,const Options* options)\n{\n    std::string foundFile = osgDB::findDataFile(filename, options);\n    if (!foundFile.empty())\n    {\n        XmlNode::Input input;\n        input.open(foundFile);\n        if (!input)\n        {\n            osg::notify(osg::NOTICE)<<\"Could not open XML file: \"< root = new XmlNode;\n        root->read(input);\n\n        return root.release();\n    }\n    else\n    {\n        osg::notify(osg::NOTICE)<<\"Could not find XML file: \"< root = new XmlNode;\n    root->read(input);\n\n    return root.release();\n}\n\n\nXmlNode::Input::Input():\n    _currentPos(0)\n{\n    setUpControlMappings();\n}\n\nXmlNode::Input::Input(const Input&):\n    _currentPos(0)\n{\n    setUpControlMappings();\n}\n\nXmlNode::Input::~Input()\n{\n}\n\nvoid XmlNode::Input::setUpControlMappings()\n{\n    addControlToCharacter(\"&\",'&');\n    addControlToCharacter(\"<\",'<');\n    addControlToCharacter(\">\",'>');\n    addControlToCharacter(\""\",'\"');\n    addControlToCharacter(\"'\",'\\'');\n}\n\nvoid XmlNode::Input::addControlToCharacter(const std::string& control, int c)\n{\n    _controlToCharacterMap[control] = c;\n    _characterToControlMap[c] = control;\n}\n\nvoid XmlNode::Input::open(const std::string& filename)\n{\n    _fin.open(filename.c_str());\n}\n\nvoid XmlNode::Input::attach(std::istream& fin)\n{\n    std::ios &fios = _fin;\n    fios.rdbuf(fin.rdbuf());\n}\n\nvoid XmlNode::Input::readAllDataIntoBuffer()\n{\n    while(_fin)\n    {\n        int c = _fin.get();\n        if (c>=0 && c<=255)\n        {\n            _buffer.push_back(c);\n        }\n    }\n}\n\nvoid XmlNode::Input::skipWhiteSpace()\n{\n    while(_currentPos<_buffer.size() && _buffer[_currentPos]==' ')\n    {\n        \/\/ osg::notify(osg::NOTICE)<<\"_currentPos=\"<<_currentPos<<\"_buffer.size()=\"<<_buffer.size()<<\" v=\"<<_buffer[_currentPos]<type = XmlNode::COMMENT;\n            children.push_back(commentNode);\n\n            input += 4;\n            XmlNode::Input::size_type end = input.find(\"-->\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid Comment record [\"<contents<<\"]\"<contents<<\"]\"<\");\n            std::string comment = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid end tag [\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 2;\n            XmlNode::Input::size_type end = input.find(\"?>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid infomation record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::NODE;\n            children.push_back(childNode);\n\n            input += 1;\n\n            input.skipWhiteSpace();\n\n            int c = 0;\n            while ((c=input[0])>=0 && c!=' ' && c!='>' )\n            {\n                childNode->name.push_back(c);\n                ++input;\n            }\n\n            while ((c=input[0])>=0 && c!='>')\n            {\n                Input::size_type prev_pos = input.currentPosition();\n\n                input.skipWhiteSpace();\n                std::string option;\n                std::string value;\n                while((c=input[0])>=0 && c!='>' && c!='\"' && c!='\\'' && c!='=' && c!=' ')\n                {\n                    option.push_back(c);\n                    ++input;\n                }\n                input.skipWhiteSpace();\n                if (input[0]=='=')\n                {\n                    ++input;\n\n                    input.skipWhiteSpace();\n\n                    if (input[0]=='\"')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\"')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                        ++input;\n                    }\n                    else if (input[0]=='\\'')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\\'')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                        ++input;\n                    }\n                    else\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!=' ' && c!='\"' && c!='\\'' && c!='>')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                    }\n                }\n\n                if (prev_pos == input.currentPosition())\n                {\n                    osg::notify(osg::NOTICE)<<\"Error, parser iterator note advanced, position: \"<properties[option] = value;\n                }\n            }\n\n            if ((c=input[0])>=0 && c=='>' )\n            {\n                ++input;\n\n                osg::notify(osg::INFO)<<\"Valid tag [\"<name<<\"]\"<read(input);\n                if (!result) return false;\n\n                if (type==NODE && !children.empty()) type = GROUP;\n            }\n            else\n            {\n                osg::notify(osg::NOTICE)<<\"Unclosed tag [\"<name<<\"]\"<first<<\"\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\"<write(fout);\n            }\n            return true;\n        }\n        case(NODE):\n        {\n            fout<<\"<\"<first<<\"=\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\";\n            }\n            fout<<\">\";\n\n            for(Children::const_iterator citr = children.begin();\n                citr != children.end();\n                ++citr)\n            {\n                (*citr)->write(fout);\n            }\n\n            if (!contents.empty()) writeString(fout,contents);\n\n            fout<<\"<\/\"<\"<first<<\"=\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\";\n            }\n            fout<<\">\"<write(fout);\n            }\n\n            fout<<\"<\/\"<\"<\"<\"<Added tabs to treatment as white space to skyWhiteSpace()\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2009 Robert Osfield\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version.  The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\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\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\n#include \n\nusing namespace osgDB;\n\nXmlNode* osgDB::readXmlFile(const std::string& filename,const Options* options)\n{\n    std::string foundFile = osgDB::findDataFile(filename, options);\n    if (!foundFile.empty())\n    {\n        XmlNode::Input input;\n        input.open(foundFile);\n        if (!input)\n        {\n            osg::notify(osg::NOTICE)<<\"Could not open XML file: \"< root = new XmlNode;\n        root->read(input);\n\n        return root.release();\n    }\n    else\n    {\n        osg::notify(osg::NOTICE)<<\"Could not find XML file: \"< root = new XmlNode;\n    root->read(input);\n\n    return root.release();\n}\n\n\nXmlNode::Input::Input():\n    _currentPos(0)\n{\n    setUpControlMappings();\n}\n\nXmlNode::Input::Input(const Input&):\n    _currentPos(0)\n{\n    setUpControlMappings();\n}\n\nXmlNode::Input::~Input()\n{\n}\n\nvoid XmlNode::Input::setUpControlMappings()\n{\n    addControlToCharacter(\"&\",'&');\n    addControlToCharacter(\"<\",'<');\n    addControlToCharacter(\">\",'>');\n    addControlToCharacter(\""\",'\"');\n    addControlToCharacter(\"'\",'\\'');\n}\n\nvoid XmlNode::Input::addControlToCharacter(const std::string& control, int c)\n{\n    _controlToCharacterMap[control] = c;\n    _characterToControlMap[c] = control;\n}\n\nvoid XmlNode::Input::open(const std::string& filename)\n{\n    _fin.open(filename.c_str());\n}\n\nvoid XmlNode::Input::attach(std::istream& fin)\n{\n    std::ios &fios = _fin;\n    fios.rdbuf(fin.rdbuf());\n}\n\nvoid XmlNode::Input::readAllDataIntoBuffer()\n{\n    while(_fin)\n    {\n        int c = _fin.get();\n        if (c>=0 && c<=255)\n        {\n            _buffer.push_back(c);\n        }\n    }\n}\n\nvoid XmlNode::Input::skipWhiteSpace()\n{\n    while(_currentPos<_buffer.size() && _buffer[_currentPos]==' ' || _buffer[_currentPos]=='\\t' )\n    {\n        \/\/ osg::notify(osg::NOTICE)<<\"_currentPos=\"<<_currentPos<<\"_buffer.size()=\"<<_buffer.size()<<\" v=\"<<_buffer[_currentPos]<type = XmlNode::COMMENT;\n            children.push_back(commentNode);\n\n            input += 4;\n            XmlNode::Input::size_type end = input.find(\"-->\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid Comment record [\"<contents<<\"]\"<contents<<\"]\"<\");\n            std::string comment = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid end tag [\"<type = XmlNode::INFORMATION;\n            children.push_back(commentNode);\n\n            input += 2;\n            XmlNode::Input::size_type end = input.find(\"?>\");\n            commentNode->contents = input.substr(0, end);\n            if (end!=std::string::npos)\n            {\n                osg::notify(osg::INFO)<<\"Valid infomation record [\"<contents<<\"]\"<contents<<\"]\"<type = XmlNode::NODE;\n            children.push_back(childNode);\n\n            input += 1;\n\n            input.skipWhiteSpace();\n\n            int c = 0;\n            while ((c=input[0])>=0 && c!=' ' && c!='>' )\n            {\n                childNode->name.push_back(c);\n                ++input;\n            }\n\n            while ((c=input[0])>=0 && c!='>')\n            {\n                Input::size_type prev_pos = input.currentPosition();\n\n                input.skipWhiteSpace();\n                std::string option;\n                std::string value;\n                while((c=input[0])>=0 && c!='>' && c!='\"' && c!='\\'' && c!='=' && c!=' ')\n                {\n                    option.push_back(c);\n                    ++input;\n                }\n                input.skipWhiteSpace();\n                if (input[0]=='=')\n                {\n                    ++input;\n\n                    input.skipWhiteSpace();\n\n                    if (input[0]=='\"')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\"')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                        ++input;\n                    }\n                    else if (input[0]=='\\'')\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!='\\'')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                        ++input;\n                    }\n                    else\n                    {\n                        ++input;\n                        while((c=input[0])>=0 && c!=' ' && c!='\"' && c!='\\'' && c!='>')\n                        {\n                            value.push_back(c);\n                            ++input;\n                        }\n                    }\n                }\n\n                if (prev_pos == input.currentPosition())\n                {\n                    osg::notify(osg::NOTICE)<<\"Error, parser iterator note advanced, position: \"<properties[option] = value;\n                }\n            }\n\n            if ((c=input[0])>=0 && c=='>' )\n            {\n                ++input;\n\n                osg::notify(osg::INFO)<<\"Valid tag [\"<name<<\"]\"<read(input);\n                if (!result) return false;\n\n                if (type==NODE && !children.empty()) type = GROUP;\n            }\n            else\n            {\n                osg::notify(osg::NOTICE)<<\"Unclosed tag [\"<name<<\"]\"<first<<\"\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\"<write(fout);\n            }\n            return true;\n        }\n        case(NODE):\n        {\n            fout<<\"<\"<first<<\"=\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\";\n            }\n            fout<<\">\";\n\n            for(Children::const_iterator citr = children.begin();\n                citr != children.end();\n                ++citr)\n            {\n                (*citr)->write(fout);\n            }\n\n            if (!contents.empty()) writeString(fout,contents);\n\n            fout<<\"<\/\"<\"<first<<\"=\\\"\";\n                writeString(fout,oitr->second);\n                fout<<\"\\\"\";\n            }\n            fout<<\">\"<write(fout);\n            }\n\n            fout<<\"<\/\"<\"<\"<\"<"}
{"text":"\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n\/*\n * Ordered alphabetically using scriptname.\n * Scriptnames of files in this file should be prefixed with \"npc_pet_dk_\".\n *\/\n\n#include \"Cell.h\"\n#include \"CellImpl.h\"\n#include \"CombatAI.h\"\n#include \"GridNotifiers.h\"\n#include \"PassiveAI.h\"\n#include \"ScriptMgr.h\"\n#include \"ScriptedCreature.h\"\n#include \"SpellAuraEffects.h\"\n#include \"SpellScript.h\"\n\n\/\/ TODO: this import is not necessary for compilation and marked as unused by the IDE\n\/\/  however, for some reasons removing it would cause a damn linking issue\n\/\/  there is probably some underlying problem with imports which should properly addressed\n\/\/  see: https:\/\/github.com\/azerothcore\/azerothcore-wotlk\/issues\/9766\n#include \"GridNotifiersImpl.h\"\n\nenum DeathKnightSpells\n{\n    SPELL_DK_SUMMON_GARGOYLE_1      = 49206,\n    SPELL_DK_SUMMON_GARGOYLE_2      = 50514,\n    SPELL_DK_DISMISS_GARGOYLE       = 50515,\n    SPELL_DK_SANCTUARY              = 54661,\n    SPELL_DK_NIGHT_OF_THE_DEAD      = 62137,\n    SPELL_DK_PET_SCALING            = 61017\n};\n\nclass npc_pet_dk_ebon_gargoyle : public CreatureScript\n{\npublic:\n    npc_pet_dk_ebon_gargoyle() : CreatureScript(\"npc_pet_dk_ebon_gargoyle\") { }\n\n    struct npc_pet_dk_ebon_gargoyleAI : ScriptedAI\n    {\n        npc_pet_dk_ebon_gargoyleAI(Creature* creature) : ScriptedAI(creature)\n        {\n            _despawnTimer = 36000; \/\/ 30 secs + 4 fly out + 2 initial attack timer\n            _despawning = false;\n            _initialSelection = true;\n            _targetGUID.Clear();\n        }\n\n        void MovementInform(uint32 type, uint32 point) override\n        {\n            if (type == POINT_MOTION_TYPE && point == 1)\n            {\n                me->SetCanFly(false);\n                me->SetDisableGravity(false);\n            }\n        }\n\n        void InitializeAI() override\n        {\n            ScriptedAI::InitializeAI();\n            Unit* owner = me->GetOwner();\n            if (!owner)\n                return;\n\n            \/\/ Xinef: Night of the Dead avoidance\n            if (Aura* aur = me->GetAura(SPELL_DK_NIGHT_OF_THE_DEAD))\n                if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2718, 0))\n                {\n                    if (aur->GetEffect(0))\n                    {\n                        aur->GetEffect(0)->SetAmount(-aurEff->GetSpellInfo()->Effects[EFFECT_2].CalcValue());\n                    }\n                }\n\n            me->SetCanFly(true);\n            me->SetDisableGravity(true);\n\n            float tz = me->GetMapHeight(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), true, MAX_FALL_DISTANCE);\n            me->GetMotionMaster()->MoveCharge(me->GetPositionX(), me->GetPositionY(), tz, 7.0f, 1);\n            me->AddUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD);\n            _selectionTimer = 2000;\n            _initialCastTimer = 0;\n        }\n\n        void MySelectNextTarget()\n        {\n            Unit* owner = me->GetOwner();\n            if (owner && owner->GetTypeId() == TYPEID_PLAYER && (!me->GetVictim() || me->GetVictim()->IsImmunedToSpell(sSpellMgr->GetSpellInfo(51963)) || !me->IsValidAttackTarget(me->GetVictim()) || !owner->CanSeeOrDetect(me->GetVictim())))\n            {\n                Unit* selection = owner->ToPlayer()->GetSelectedUnit();\n                if (selection && selection != me->GetVictim() && me->IsValidAttackTarget(selection))\n                {\n                    me->GetMotionMaster()->Clear(false);\n                    SetGazeOn(selection);\n                }\n\n                else if (!me->GetVictim() || !owner->CanSeeOrDetect(me->GetVictim()))\n                {\n                    me->CombatStop(true);\n                    me->GetMotionMaster()->Clear(false);\n                    me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, 0.0f);\n                    RemoveTargetAura();\n                }\n            }\n        }\n\n        void AttackStart(Unit* who) override\n        {\n            RemoveTargetAura();\n            _targetGUID = who->GetGUID();\n            me->AddAura(SPELL_DK_SUMMON_GARGOYLE_1, who);\n            ScriptedAI::AttackStart(who);\n        }\n\n        void RemoveTargetAura()\n        {\n            if (Unit* target = ObjectAccessor::GetUnit(*me, _targetGUID))\n                target->RemoveAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetGUID());\n        }\n\n        void Reset() override\n        {\n            _selectionTimer = 0;\n            me->SetReactState(REACT_PASSIVE);\n            MySelectNextTarget();\n        }\n\n        \/\/ Fly away when dismissed\n        void FlyAway()\n        {\n            RemoveTargetAura();\n\n            \/\/ Stop Fighting\n            me->CombatStop(true);\n            me->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, true);\n\n            \/\/ Sanctuary\n            me->CastSpell(me, SPELL_DK_SANCTUARY, true);\n            me->SetReactState(REACT_PASSIVE);\n\n            me->SetSpeed(MOVE_FLIGHT, 1.0f, true);\n            me->SetSpeed(MOVE_RUN, 1.0f, true);\n            float x = me->GetPositionX() + 20 * cos(me->GetOrientation());\n            float y = me->GetPositionY() + 20 * std::sin(me->GetOrientation());\n            float z = me->GetPositionZ() + 40;\n            me->DisableSpline();\n            me->GetMotionMaster()->Clear(false);\n\n            me->GetMotionMaster()->MoveCharge(x, y, z, 7.0f, 1);\n            me->SetCanFly(true);\n            me->SetDisableGravity(true);\n\n            _despawning = true;\n        }\n\n        void UpdateAI(uint32 diff) override\n        {\n            if (_initialSelection)\n            {\n                _initialSelection = false;\n                \/\/ Find victim of Summon Gargoyle spell\n                std::list targets;\n                Acore::AnyUnfriendlyUnitInObjectRangeCheck u_check(me, me, 50.0f);\n                Acore::UnitListSearcher searcher(me, targets, u_check);\n                Cell::VisitAllObjects(me, searcher, 50.0f);\n                for (std::list::const_iterator iter = targets.begin(); iter != targets.end(); ++iter)\n                    if ((*iter)->GetAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetOwnerGUID()))\n                    {\n                        (*iter)->RemoveAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetOwnerGUID());\n                        SetGazeOn(*iter);\n                        _targetGUID = (*iter)->GetGUID();\n                        break;\n                    }\n            }\n            if (_despawnTimer > 4000)\n            {\n                _despawnTimer -= diff;\n                if (!UpdateVictimWithGaze())\n                {\n                    MySelectNextTarget();\n                    return;\n                }\n\n                _initialCastTimer += diff;\n                _selectionTimer += diff;\n                if (_selectionTimer >= 1000)\n                {\n                    MySelectNextTarget();\n                    _selectionTimer = 0;\n                }\n                if (_initialCastTimer >= 2000 && !me->HasUnitState(UNIT_STATE_CASTING | UNIT_STATE_LOST_CONTROL) && me->GetMotionMaster()->GetMotionSlotType(MOTION_SLOT_CONTROLLED) == NULL_MOTION_TYPE)\n                    me->CastSpell(me->GetVictim(), 51963, false);\n            }\n            else\n            {\n                if (!_despawning)\n                    FlyAway();\n\n                if (_despawnTimer > diff)\n                    _despawnTimer -= diff;\n                else\n                    me->DespawnOrUnsummon();\n            }\n        }\n\n    private:\n        ObjectGuid _targetGUID;\n        uint32 _despawnTimer;\n        uint32 _selectionTimer;\n        uint32 _initialCastTimer;\n        bool _despawning;\n        bool _initialSelection;\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_ebon_gargoyleAI(creature);\n    }\n};\n\nclass npc_pet_dk_ghoul : public CreatureScript\n{\npublic:\n    npc_pet_dk_ghoul() : CreatureScript(\"npc_pet_dk_ghoul\") { }\n\n    struct npc_pet_dk_ghoulAI : public CombatAI\n    {\n        npc_pet_dk_ghoulAI(Creature* c) : CombatAI(c) { }\n\n        void JustDied(Unit* \/*who*\/) override\n        {\n            if (me->IsGuardian() || me->IsSummon())\n                me->ToTempSummon()->UnSummon();\n        }\n    };\n\n    CreatureAI* GetAI(Creature* pCreature) const override\n    {\n        return new npc_pet_dk_ghoulAI (pCreature);\n    }\n};\n\nclass npc_pet_dk_army_of_the_dead : public CreatureScript\n{\npublic:\n    npc_pet_dk_army_of_the_dead() : CreatureScript(\"npc_pet_dk_army_of_the_dead\") { }\n\n    struct npc_pet_dk_army_of_the_deadAI : public CombatAI\n    {\n        npc_pet_dk_army_of_the_deadAI(Creature* creature) : CombatAI(creature) { }\n\n        void InitializeAI() override\n        {\n            CombatAI::InitializeAI();\n            ((Minion*)me)->SetFollowAngle(rand_norm() * 2 * M_PI);\n\n            \/\/ Heroism \/ Bloodlust immunity\n            me->ApplySpellImmune(0, IMMUNITY_ID, 32182, true);\n            me->ApplySpellImmune(0, IMMUNITY_ID, 2825, true);\n        }\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_army_of_the_deadAI (creature);\n    }\n};\n\nclass npc_pet_dk_dancing_rune_weapon : public CreatureScript\n{\npublic:\n    npc_pet_dk_dancing_rune_weapon() : CreatureScript(\"npc_pet_dk_dancing_rune_weapon\") { }\n\n    struct npc_pet_dk_dancing_rune_weaponAI : public NullCreatureAI\n    {\n        npc_pet_dk_dancing_rune_weaponAI(Creature* creature) : NullCreatureAI(creature) { }\n\n        void InitializeAI() override\n        {\n            \/\/ Xinef: Hit \/ Expertise scaling\n            me->AddAura(61017, me);\n            if (Unit* owner = me->GetOwner())\n                me->GetMotionMaster()->MoveFollow(owner, 0.01f, me->GetFollowAngle(), MOTION_SLOT_CONTROLLED);\n\n            NullCreatureAI::InitializeAI();\n        }\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_dancing_rune_weaponAI (creature);\n    }\n};\n\nclass spell_pet_dk_gargoyle_strike : public SpellScript\n{\n    PrepareSpellScript(spell_pet_dk_gargoyle_strike);\n\n    void HandleDamageCalc(SpellEffIndex \/*effIndex*\/)\n    {\n        int32 damage = 60;\n        if (Unit* caster = GetCaster())\n        {\n            if (caster->getLevel() >= 60)\n            {\n                damage += (caster->getLevel() - 60) * 4;\n            }\n        }\n\n        SetHitDamage(damage);\n    }\n\n    void Register() override\n    {\n        OnEffectHitTarget += SpellEffectFn(spell_pet_dk_gargoyle_strike::HandleDamageCalc, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);\n    }\n};\n\nvoid AddSC_deathknight_pet_scripts()\n{\n    new npc_pet_dk_ebon_gargoyle();\n    new npc_pet_dk_ghoul();\n    new npc_pet_dk_army_of_the_dead();\n    new npc_pet_dk_dancing_rune_weapon();\n    RegisterSpellScript(spell_pet_dk_gargoyle_strike);\n}\nfix(Scripts\/Spell): Gargoyle's damage (#11389)\/*\n * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Affero General Public License as published by the\n * Free Software Foundation; either version 3 of the License, or (at your\n * option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program. If not, see .\n *\/\n\n\/*\n * Ordered alphabetically using scriptname.\n * Scriptnames of files in this file should be prefixed with \"npc_pet_dk_\".\n *\/\n\n#include \"Cell.h\"\n#include \"CellImpl.h\"\n#include \"CombatAI.h\"\n#include \"GridNotifiers.h\"\n#include \"PassiveAI.h\"\n#include \"ScriptMgr.h\"\n#include \"ScriptedCreature.h\"\n#include \"SpellAuraEffects.h\"\n#include \"SpellScript.h\"\n\n\/\/ TODO: this import is not necessary for compilation and marked as unused by the IDE\n\/\/  however, for some reasons removing it would cause a damn linking issue\n\/\/  there is probably some underlying problem with imports which should properly addressed\n\/\/  see: https:\/\/github.com\/azerothcore\/azerothcore-wotlk\/issues\/9766\n#include \"GridNotifiersImpl.h\"\n\nenum DeathKnightSpells\n{\n    SPELL_DK_SUMMON_GARGOYLE_1      = 49206,\n    SPELL_DK_SUMMON_GARGOYLE_2      = 50514,\n    SPELL_DK_DISMISS_GARGOYLE       = 50515,\n    SPELL_DK_SANCTUARY              = 54661,\n    SPELL_DK_NIGHT_OF_THE_DEAD      = 62137,\n    SPELL_DK_PET_SCALING            = 61017\n};\n\nclass npc_pet_dk_ebon_gargoyle : public CreatureScript\n{\npublic:\n    npc_pet_dk_ebon_gargoyle() : CreatureScript(\"npc_pet_dk_ebon_gargoyle\") { }\n\n    struct npc_pet_dk_ebon_gargoyleAI : ScriptedAI\n    {\n        npc_pet_dk_ebon_gargoyleAI(Creature* creature) : ScriptedAI(creature)\n        {\n            _despawnTimer = 36000; \/\/ 30 secs + 4 fly out + 2 initial attack timer\n            _despawning = false;\n            _initialSelection = true;\n            _targetGUID.Clear();\n        }\n\n        void MovementInform(uint32 type, uint32 point) override\n        {\n            if (type == POINT_MOTION_TYPE && point == 1)\n            {\n                me->SetCanFly(false);\n                me->SetDisableGravity(false);\n            }\n        }\n\n        void InitializeAI() override\n        {\n            ScriptedAI::InitializeAI();\n            Unit* owner = me->GetOwner();\n            if (!owner)\n                return;\n\n            \/\/ Xinef: Night of the Dead avoidance\n            if (Aura* aur = me->GetAura(SPELL_DK_NIGHT_OF_THE_DEAD))\n                if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2718, 0))\n                {\n                    if (aur->GetEffect(0))\n                    {\n                        aur->GetEffect(0)->SetAmount(-aurEff->GetSpellInfo()->Effects[EFFECT_2].CalcValue());\n                    }\n                }\n\n            me->SetCanFly(true);\n            me->SetDisableGravity(true);\n\n            float tz = me->GetMapHeight(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), true, MAX_FALL_DISTANCE);\n            me->GetMotionMaster()->MoveCharge(me->GetPositionX(), me->GetPositionY(), tz, 7.0f, 1);\n            me->AddUnitState(UNIT_STATE_NO_ENVIRONMENT_UPD);\n            _selectionTimer = 2000;\n            _initialCastTimer = 0;\n        }\n\n        void MySelectNextTarget()\n        {\n            Unit* owner = me->GetOwner();\n            if (owner && owner->GetTypeId() == TYPEID_PLAYER && (!me->GetVictim() || me->GetVictim()->IsImmunedToSpell(sSpellMgr->GetSpellInfo(51963)) || !me->IsValidAttackTarget(me->GetVictim()) || !owner->CanSeeOrDetect(me->GetVictim())))\n            {\n                Unit* selection = owner->ToPlayer()->GetSelectedUnit();\n                if (selection && selection != me->GetVictim() && me->IsValidAttackTarget(selection))\n                {\n                    me->GetMotionMaster()->Clear(false);\n                    SetGazeOn(selection);\n                }\n\n                else if (!me->GetVictim() || !owner->CanSeeOrDetect(me->GetVictim()))\n                {\n                    me->CombatStop(true);\n                    me->GetMotionMaster()->Clear(false);\n                    me->GetMotionMaster()->MoveFollow(owner, PET_FOLLOW_DIST, 0.0f);\n                    RemoveTargetAura();\n                }\n            }\n        }\n\n        void AttackStart(Unit* who) override\n        {\n            RemoveTargetAura();\n            _targetGUID = who->GetGUID();\n            me->AddAura(SPELL_DK_SUMMON_GARGOYLE_1, who);\n            ScriptedAI::AttackStart(who);\n        }\n\n        void RemoveTargetAura()\n        {\n            if (Unit* target = ObjectAccessor::GetUnit(*me, _targetGUID))\n                target->RemoveAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetGUID());\n        }\n\n        void Reset() override\n        {\n            _selectionTimer = 0;\n            me->SetReactState(REACT_PASSIVE);\n            MySelectNextTarget();\n        }\n\n        \/\/ Fly away when dismissed\n        void FlyAway()\n        {\n            RemoveTargetAura();\n\n            \/\/ Stop Fighting\n            me->CombatStop(true);\n            me->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, true);\n\n            \/\/ Sanctuary\n            me->CastSpell(me, SPELL_DK_SANCTUARY, true);\n            me->SetReactState(REACT_PASSIVE);\n\n            me->SetSpeed(MOVE_FLIGHT, 1.0f, true);\n            me->SetSpeed(MOVE_RUN, 1.0f, true);\n            float x = me->GetPositionX() + 20 * cos(me->GetOrientation());\n            float y = me->GetPositionY() + 20 * std::sin(me->GetOrientation());\n            float z = me->GetPositionZ() + 40;\n            me->DisableSpline();\n            me->GetMotionMaster()->Clear(false);\n\n            me->GetMotionMaster()->MoveCharge(x, y, z, 7.0f, 1);\n            me->SetCanFly(true);\n            me->SetDisableGravity(true);\n\n            _despawning = true;\n        }\n\n        void UpdateAI(uint32 diff) override\n        {\n            if (_initialSelection)\n            {\n                _initialSelection = false;\n                \/\/ Find victim of Summon Gargoyle spell\n                std::list targets;\n                Acore::AnyUnfriendlyUnitInObjectRangeCheck u_check(me, me, 50.0f);\n                Acore::UnitListSearcher searcher(me, targets, u_check);\n                Cell::VisitAllObjects(me, searcher, 50.0f);\n                for (std::list::const_iterator iter = targets.begin(); iter != targets.end(); ++iter)\n                    if ((*iter)->GetAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetOwnerGUID()))\n                    {\n                        (*iter)->RemoveAura(SPELL_DK_SUMMON_GARGOYLE_1, me->GetOwnerGUID());\n                        SetGazeOn(*iter);\n                        _targetGUID = (*iter)->GetGUID();\n                        break;\n                    }\n            }\n            if (_despawnTimer > 4000)\n            {\n                _despawnTimer -= diff;\n                if (!UpdateVictimWithGaze())\n                {\n                    MySelectNextTarget();\n                    return;\n                }\n\n                _initialCastTimer += diff;\n                _selectionTimer += diff;\n                if (_selectionTimer >= 1000)\n                {\n                    MySelectNextTarget();\n                    _selectionTimer = 0;\n                }\n                if (_initialCastTimer >= 2000 && !me->HasUnitState(UNIT_STATE_CASTING | UNIT_STATE_LOST_CONTROL) && me->GetMotionMaster()->GetMotionSlotType(MOTION_SLOT_CONTROLLED) == NULL_MOTION_TYPE)\n                    me->CastSpell(me->GetVictim(), 51963, false);\n            }\n            else\n            {\n                if (!_despawning)\n                    FlyAway();\n\n                if (_despawnTimer > diff)\n                    _despawnTimer -= diff;\n                else\n                    me->DespawnOrUnsummon();\n            }\n        }\n\n    private:\n        ObjectGuid _targetGUID;\n        uint32 _despawnTimer;\n        uint32 _selectionTimer;\n        uint32 _initialCastTimer;\n        bool _despawning;\n        bool _initialSelection;\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_ebon_gargoyleAI(creature);\n    }\n};\n\nclass npc_pet_dk_ghoul : public CreatureScript\n{\npublic:\n    npc_pet_dk_ghoul() : CreatureScript(\"npc_pet_dk_ghoul\") { }\n\n    struct npc_pet_dk_ghoulAI : public CombatAI\n    {\n        npc_pet_dk_ghoulAI(Creature* c) : CombatAI(c) { }\n\n        void JustDied(Unit* \/*who*\/) override\n        {\n            if (me->IsGuardian() || me->IsSummon())\n                me->ToTempSummon()->UnSummon();\n        }\n    };\n\n    CreatureAI* GetAI(Creature* pCreature) const override\n    {\n        return new npc_pet_dk_ghoulAI (pCreature);\n    }\n};\n\nclass npc_pet_dk_army_of_the_dead : public CreatureScript\n{\npublic:\n    npc_pet_dk_army_of_the_dead() : CreatureScript(\"npc_pet_dk_army_of_the_dead\") { }\n\n    struct npc_pet_dk_army_of_the_deadAI : public CombatAI\n    {\n        npc_pet_dk_army_of_the_deadAI(Creature* creature) : CombatAI(creature) { }\n\n        void InitializeAI() override\n        {\n            CombatAI::InitializeAI();\n            ((Minion*)me)->SetFollowAngle(rand_norm() * 2 * M_PI);\n\n            \/\/ Heroism \/ Bloodlust immunity\n            me->ApplySpellImmune(0, IMMUNITY_ID, 32182, true);\n            me->ApplySpellImmune(0, IMMUNITY_ID, 2825, true);\n        }\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_army_of_the_deadAI (creature);\n    }\n};\n\nclass npc_pet_dk_dancing_rune_weapon : public CreatureScript\n{\npublic:\n    npc_pet_dk_dancing_rune_weapon() : CreatureScript(\"npc_pet_dk_dancing_rune_weapon\") { }\n\n    struct npc_pet_dk_dancing_rune_weaponAI : public NullCreatureAI\n    {\n        npc_pet_dk_dancing_rune_weaponAI(Creature* creature) : NullCreatureAI(creature) { }\n\n        void InitializeAI() override\n        {\n            \/\/ Xinef: Hit \/ Expertise scaling\n            me->AddAura(61017, me);\n            if (Unit* owner = me->GetOwner())\n                me->GetMotionMaster()->MoveFollow(owner, 0.01f, me->GetFollowAngle(), MOTION_SLOT_CONTROLLED);\n\n            NullCreatureAI::InitializeAI();\n        }\n    };\n\n    CreatureAI* GetAI(Creature* creature) const override\n    {\n        return new npc_pet_dk_dancing_rune_weaponAI (creature);\n    }\n};\n\nclass spell_pet_dk_gargoyle_strike : public SpellScript\n{\n    PrepareSpellScript(spell_pet_dk_gargoyle_strike);\n\n    void HandleDamageCalc(SpellEffIndex \/*effIndex*\/)\n    {\n        int32 damage = 60;\n        if (Unit* caster = GetCaster())\n        {\n            if (caster->getLevel() >= 60)\n            {\n                damage += (caster->getLevel() - 60) * 4;\n            }\n        }\n\n        SetEffectValue(damage);\n    }\n\n    void Register() override\n    {\n        OnEffectHitTarget += SpellEffectFn(spell_pet_dk_gargoyle_strike::HandleDamageCalc, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);\n    }\n};\n\nvoid AddSC_deathknight_pet_scripts()\n{\n    new npc_pet_dk_ebon_gargoyle();\n    new npc_pet_dk_ghoul();\n    new npc_pet_dk_army_of_the_dead();\n    new npc_pet_dk_dancing_rune_weapon();\n    RegisterSpellScript(spell_pet_dk_gargoyle_strike);\n}\n<|endoftext|>"}
{"text":"Linux: reap the sandbox helper process.<|endoftext|>"}
{"text":"Remove stray semicolon<|endoftext|>"}
{"text":"cf-fbx skin processing<|endoftext|>"}
{"text":"\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ 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\/test\/ui\/npapi_test_helper.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#if defined(OS_WIN)\nstatic const char kNpapiTestPluginName[] = \"npapi_test_plugin.dll\";\n#elif defined(OS_MACOSX)\nstatic const char kNpapiTestPluginName[] = \"npapi_test_plugin.plugin\";\nstatic const char kLayoutPluginName[] = \"TestNetscapePlugIn.plugin\";\n#elif defined(OS_LINUX)\nstatic const char kNpapiTestPluginName[] = \"libnpapi_test_plugin.so\";\n#endif\n\nnamespace npapi_test {\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\n}  \/\/ namespace npapi_test.\n\nNPAPITesterBase::NPAPITesterBase(const std::string& test_plugin_name)\n  : test_plugin_name_(test_plugin_name) {\n}\n\nvoid NPAPITesterBase::SetUp() {\n  \/\/ We need to copy our test-plugin into the plugins directory so that\n  \/\/ the browser can load it.\n  \/\/ TODO(tc): We should copy the plugins as a build step, not during\n  \/\/ the tests.  Then we don't have to clean up after the copy in the test.\n  FilePath plugins_directory = GetPluginsDirectory();\n  FilePath plugin_src = browser_directory_.AppendASCII(test_plugin_name_);\n  ASSERT_TRUE(file_util::PathExists(plugin_src));\n  test_plugin_path_ = plugins_directory.AppendASCII(test_plugin_name_);\n\n  file_util::CreateDirectory(plugins_directory);\n  ASSERT_TRUE(file_util::CopyDirectory(plugin_src, test_plugin_path_, true))\n      << \"Copy failed from \" << plugin_src.value()\n      << \" to \" << test_plugin_path_.value();\n#if defined(OS_MACOSX)\n  \/\/ The plugins directory isn't read by default on the Mac, so it needs to be\n  \/\/ explicitly registered.\n  launch_arguments_.AppendSwitchPath(switches::kExtraPluginDir,\n                                     plugins_directory);\n#endif\n\n  UITest::SetUp();\n}\n\nvoid NPAPITesterBase::TearDown() {\n  \/\/ Tear down the UI test first so that the browser stops using the plugin\n  \/\/ files.\n  UITest::TearDown();\n}\n\nFilePath NPAPITesterBase::GetPluginsDirectory() {\n  FilePath plugins_directory = browser_directory_.AppendASCII(\"plugins\");\n  return plugins_directory;\n}\n\nNPAPITester::NPAPITester() : NPAPITesterBase(kNpapiTestPluginName) {\n}\n\nvoid NPAPITester::SetUp() {\n#if defined(OS_MACOSX)\n  \/\/ TODO(stuartmorgan): Remove this whole subclass once the WebKit build is\n  \/\/ changed to copy the plugin into a plugins directory next to the app as\n  \/\/ is done on Linux and Windows.\n  FilePath layout_src = browser_directory_.AppendASCII(kLayoutPluginName);\n  ASSERT_TRUE(file_util::PathExists(layout_src));\n  FilePath plugins_directory = GetPluginsDirectory();\n  layout_plugin_path_ = plugins_directory.AppendASCII(kLayoutPluginName);\n  file_util::CreateDirectory(plugins_directory);\n  ASSERT_TRUE(file_util::CopyDirectory(layout_src, layout_plugin_path_, true));\n#endif\n\n  NPAPITesterBase::SetUp();\n}\n\nvoid NPAPITester::TearDown() {\n  \/\/ Tear down the base class first so that the browser stops using the plugin\n  \/\/ files.\n  NPAPITesterBase::TearDown();\n}\n\n\/\/ NPAPIVisiblePluginTester members.\nvoid NPAPIVisiblePluginTester::SetUp() {\n  show_window_ = true;\n  NPAPITester::SetUp();\n}\n\n\/\/ NPAPIIncognitoTester members.\nvoid NPAPIIncognitoTester::SetUp() {\n  launch_arguments_.AppendSwitch(switches::kIncognito);\n  NPAPITester::SetUp();\n}\nOnly copy the plugin if it doesn't already exist.\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ 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\/test\/ui\/npapi_test_helper.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n\n#if defined(OS_WIN)\nstatic const char kNpapiTestPluginName[] = \"npapi_test_plugin.dll\";\n#elif defined(OS_MACOSX)\nstatic const char kNpapiTestPluginName[] = \"npapi_test_plugin.plugin\";\nstatic const char kLayoutPluginName[] = \"TestNetscapePlugIn.plugin\";\n#elif defined(OS_LINUX)\nstatic const char kNpapiTestPluginName[] = \"libnpapi_test_plugin.so\";\n#endif\n\nnamespace npapi_test {\nconst char kTestCompleteCookie[] = \"status\";\nconst char kTestCompleteSuccess[] = \"OK\";\n}  \/\/ namespace npapi_test.\n\nNPAPITesterBase::NPAPITesterBase(const std::string& test_plugin_name)\n  : test_plugin_name_(test_plugin_name) {\n}\n\nvoid NPAPITesterBase::SetUp() {\n  \/\/ We need to copy our test-plugin into the plugins directory so that\n  \/\/ the browser can load it.\n  \/\/ TODO(tc): We should copy the plugins as a build step, not during\n  \/\/ the tests.  Then we don't have to clean up after the copy in the test.\n  FilePath plugins_directory = GetPluginsDirectory();\n  FilePath plugin_src = browser_directory_.AppendASCII(test_plugin_name_);\n  ASSERT_TRUE(file_util::PathExists(plugin_src));\n  test_plugin_path_ = plugins_directory.AppendASCII(test_plugin_name_);\n\n  file_util::CreateDirectory(plugins_directory);\n  if (!file_util::PathExists(test_plugin_path_)) {\n    ASSERT_TRUE(file_util::CopyDirectory(plugin_src, test_plugin_path_, true))\n        << \"Copy failed from \" << plugin_src.value()\n        << \" to \" << test_plugin_path_.value();\n  }\n#if defined(OS_MACOSX)\n  \/\/ The plugins directory isn't read by default on the Mac, so it needs to be\n  \/\/ explicitly registered.\n  launch_arguments_.AppendSwitchPath(switches::kExtraPluginDir,\n                                     plugins_directory);\n#endif\n\n  UITest::SetUp();\n}\n\nvoid NPAPITesterBase::TearDown() {\n  \/\/ Tear down the UI test first so that the browser stops using the plugin\n  \/\/ files.\n  UITest::TearDown();\n}\n\nFilePath NPAPITesterBase::GetPluginsDirectory() {\n  FilePath plugins_directory = browser_directory_.AppendASCII(\"plugins\");\n  return plugins_directory;\n}\n\nNPAPITester::NPAPITester() : NPAPITesterBase(kNpapiTestPluginName) {\n}\n\nvoid NPAPITester::SetUp() {\n#if defined(OS_MACOSX)\n  \/\/ TODO(stuartmorgan): Remove this whole subclass once the WebKit build is\n  \/\/ changed to copy the plugin into a plugins directory next to the app as\n  \/\/ is done on Linux and Windows.\n  FilePath layout_src = browser_directory_.AppendASCII(kLayoutPluginName);\n  ASSERT_TRUE(file_util::PathExists(layout_src));\n  FilePath plugins_directory = GetPluginsDirectory();\n  layout_plugin_path_ = plugins_directory.AppendASCII(kLayoutPluginName);\n  file_util::CreateDirectory(plugins_directory);\n  ASSERT_TRUE(file_util::CopyDirectory(layout_src, layout_plugin_path_, true));\n#endif\n\n  NPAPITesterBase::SetUp();\n}\n\nvoid NPAPITester::TearDown() {\n  \/\/ Tear down the base class first so that the browser stops using the plugin\n  \/\/ files.\n  NPAPITesterBase::TearDown();\n}\n\n\/\/ NPAPIVisiblePluginTester members.\nvoid NPAPIVisiblePluginTester::SetUp() {\n  show_window_ = true;\n  NPAPITester::SetUp();\n}\n\n\/\/ NPAPIIncognitoTester members.\nvoid NPAPIIncognitoTester::SetUp() {\n  launch_arguments_.AppendSwitch(switches::kIncognito);\n  NPAPITester::SetUp();\n}\n<|endoftext|>"}
{"text":"\/\/ Petter Strandmark 2013\n\/\/ petter.strandmark@gmail.com\n\n#include \n#include \n#include \nusing std::vector;\nusing std::size_t;\n\n#include \n\nclass MyIP : \n\tpublic IP\n{\npublic:\n\tvoid add_connected_constraint(const vector>& grid)\n\t{\n\t\tauto m = grid.size();\n\t\tif (m == 0) return;\n\t\tauto n = grid[0].size();\n\n\t\t\/\/ Pad grid with zeroes to be able to add constraints everywhere.\n\t\tvector> padded_grid;\n\t\tfor (int i = 0; i < m + 2; ++i) {\n\t\t\tpadded_grid.push_back(vector());\n\t\t\tfor (int j = 0; j < n + 2; ++j) {\n\t\t\t\tif (i == 0 || i == m + 1 || j == 0 || j == n + 1) {\n\t\t\t\t\tauto zero_var = add_boolean();\n\t\t\t\t\tset_bounds(0, zero_var, 0);\n\t\t\t\t\tpadded_grid.back().push_back(zero_var);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpadded_grid.back().push_back(grid[i-1][j-1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tSum turn_sum;\n\n\t\tauto add_triple_constraints = \n\t\t\t[&]\n\t\t\t(const BooleanVariable& x1, const BooleanVariable& x2, const BooleanVariable& y)\n\t\t\t{\n\t\t\t\tauto v1 = add_boolean();\n\t\t\t\t\/\/ v1  <=>  y && !x1 && !x2.\n\t\t\t\t\/\/ <=\n\t\t\t\tadd_constraint( y + (1-x1) + (1-x2) <= 2 + v1 ); \n\t\t\t\t\/\/ =>\n\t\t\t\tadd_constraint( implication(v1, !x1) );\n\t\t\t\tadd_constraint( implication(v1, !x2) );\n\t\t\t\tadd_constraint( implication(v1, y) );\n\t\t\t\tturn_sum += v1;\n\n\t\t\t\tauto v2 = add_boolean();\n\t\t\t\t\/\/ v2  <=>  !y && x1 && x2.\n\t\t\t\t\/\/ <=\n\t\t\t\tadd_constraint( (1-y) + x1 + x2 <= 2 + v2 );\n\t\t\t\t\/\/ =>\n\t\t\t\tadd_constraint( implication(v2, x1) );\n\t\t\t\tadd_constraint( implication(v2, x2) );\n\t\t\t\tadd_constraint( implication(v2, !y) );\n\t\t\t\tturn_sum -= v2;\n\t\t\t};\n\n\t\tfor (int i = 0; i < m + 1; ++i) {\n\t\t\tfor (int j = 0; j < n + 1; ++j) {\n\n\t\t\t\t\/\/  X\n\t\t\t\t\/\/  YX\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i][j];\n\t\t\t\t\tauto& x2 = padded_grid[i+1][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i][j+1];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/ XY\n\t\t\t\t\/\/  X\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i][j];\n\t\t\t\t\tauto& x2 = padded_grid[i+1][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i+1][j];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/ YX\n\t\t\t\t\/\/ X\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i+1][j];\n\t\t\t\t\tauto& x2 = padded_grid[i][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i][j];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/  X\n\t\t\t\t\/\/ XY\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i+1][j];\n\t\t\t\t\tauto& x2 = padded_grid[i][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i+1][j+1];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tadd_constraint(4, turn_sum, 4);\n\n\t\t\/\/ Forbid the two configurations\n\t\t\/\/\n \t\t\/\/  01     10\n\t\t\/\/  10 and 01\n\t\t\/\/\n\t\t\/\/ This is not completely correct, but the code\n\t\t\/\/ above can not handle them.\n\t\tfor (int i = 0; i < m + 1; ++i) {\n\t\t\tfor (int j = 0; j < n + 1; ++j) {\n\t\t\t\tadd_constraint(padded_grid[i][i] + (1 - padded_grid[i+1][j]) +\n\t\t\t\t               (1 - padded_grid[i][j+1]) + padded_grid[i+1][j+1] <= 3);\n\t\t\t\tadd_constraint((1 - padded_grid[i][i]) + padded_grid[i+1][j] +\n\t\t\t\t               padded_grid[i][j+1] + (1 - padded_grid[i+1][j+1]) <= 3);\n\t\t\t}\n\t\t}\n\t}\n};\n\nint main_program()\n{\n\tusing namespace std;\n\n\tint n = 6;\n\n\tMyIP ip;\n\n\t\/\/ Parking spots. We want to maximize the number of these.\n\tauto P = ip.add_boolean_grid(n, n, -1.0);\n\t\/\/ Transporation to parking spots.\n\tauto T = ip.add_boolean_grid(n, n);\n\n\t\/\/ Entrance to the parking lot.\n\tip.add_constraint( T[0][1] );\n\n\t\/\/ T[0][0] == 1\n\t\/\/. P P P P P\n\t\/\/. . . . . .\n\t\/\/. P P P P P\n\t\/\/. P P P P P\n\t\/\/. . . . . .\n\t\/\/P P P P P P\n\t\/\/ 21\n\n\t\/\/ T[0][1] == 1\n\t\/\/P . P P P P\n\t\/\/P . . . . .\n\t\/\/P . P P P P\n\t\/\/P . P P P P\n\t\/\/P . . . . .\n\t\/\/  P P P P P\n\t\/\/ 22\n\n\t\/\/ T[0][2] == 1\n\t\/\/P . . . . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/ 22\n\n\n\t\/\/ We can not have both parking and transportation.\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tip.add_constraint(P[i][j] + T[i][j] <= 1);\n\t\t}\n\t}\n\n\t\/\/ Every parking lot needs to be adjacent to a transport square.\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tSum neighborhood;\n\t\t\tif (i > 0) {\n\t\t\t\tneighborhood += T[i-1][j];\n\t\t\t}\n\t\t\tif (i < n - 1) {\n\t\t\t\tneighborhood += T[i+1][j];\n\t\t\t}\n\t\t\tif (j > 0) {\n\t\t\t\tneighborhood += T[i][j-1];\n\t\t\t}\n\t\t\tif (j < n - 1) {\n\t\t\t\tneighborhood += T[i][j+1];\n\t\t\t}\n\n\t\t\tip.add_constraint( P[i][j] <= neighborhood );\n\t\t\tip.add_constraint( T[i][j] <= neighborhood + P[i][j] );\n\t\t}\n\t}\n\n\t\/\/ The hardest part: the transport squares need to be\n\t\/\/ connected to each other.\n\tip.add_connected_constraint(T);\n\n\tauto print_solution = [&] () \n\t{\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tauto p = ip.get_solution(P[i][j]);\n\t\t\t\tauto t = ip.get_solution(T[i][j]);\n\t\t\t\tif (p && t) {\n\t\t\t\t\t\/\/ Infeasible.\n\t\t\t\t\tcout << '#';\n\t\t\t\t}\n\t\t\t\telse if (!p && !t) {\n\t\t\t\t\tcout << ' ';\n\t\t\t\t}\n\t\t\t\telse if (p) {\n\t\t\t\t\tcout << 'P';\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcout << '.';\n\t\t\t\t}\n\t\t\t\tcout << ' ';\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\tcout << endl;\n\t};\n\n\t\/\/ip.set_external_solver(IP::MOSEK);\n\tattest(ip.solve());\n\n\tdo {\n\t\tprint_solution();\n\t} while (false \/*ip.next_solution()*\/);\n\n\n\treturn 0;\n}\n\nint main()\n{\n\ttry {\n\t\treturn main_program();\n\t}\n\tcatch (std::exception& err) {\n\t\tstd::cerr << \"ERROR: \" << err.what() << std::endl;\n\t}\n}\nNew connectivity constraint.\/\/ Petter Strandmark 2013\n\/\/ petter.strandmark@gmail.com\n\n#include \n#include \n#include \nusing std::vector;\nusing std::size_t;\n\n#include \n\n\/\/\n\/\/ This class adds connectivity constraints to the IP class.\n\/\/ It does so in two different ways, but they both result in\n\/\/ problems that are quite difficult to solve.\n\/\/\nclass MyIP : \n\tpublic IP\n{\npublic:\n\n\t\/\/ The first way is based on following the perimeter around the \n\t\/\/ area and counting left and right turns.\n\tvoid add_connected_constraint_perimeter(const vector>& grid)\n\t{\n\t\tauto m = grid.size();\n\t\tif (m == 0) return;\n\t\tauto n = grid[0].size();\n\n\t\t\/\/ Pad grid with zeroes to be able to add constraints everywhere.\n\t\tvector> padded_grid;\n\t\tfor (int i = 0; i < m + 2; ++i) {\n\t\t\tpadded_grid.push_back(vector());\n\t\t\tfor (int j = 0; j < n + 2; ++j) {\n\t\t\t\tif (i == 0 || i == m + 1 || j == 0 || j == n + 1) {\n\t\t\t\t\tauto zero_var = add_boolean();\n\t\t\t\t\tset_bounds(0, zero_var, 0);\n\t\t\t\t\tpadded_grid.back().push_back(zero_var);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpadded_grid.back().push_back(grid[i-1][j-1]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tSum turn_sum;\n\n\t\tauto add_triple_constraints = \n\t\t\t[&]\n\t\t\t(const BooleanVariable& x1, const BooleanVariable& x2, const BooleanVariable& y)\n\t\t\t{\n\t\t\t\tauto v1 = add_boolean();\n\t\t\t\t\/\/ v1  <=>  y && !x1 && !x2.\n\t\t\t\t\/\/ <=\n\t\t\t\tadd_constraint( y + (1-x1) + (1-x2) <= 2 + v1 ); \n\t\t\t\t\/\/ =>\n\t\t\t\tadd_constraint( implication(v1, !x1) );\n\t\t\t\tadd_constraint( implication(v1, !x2) );\n\t\t\t\tadd_constraint( implication(v1, y) );\n\t\t\t\tturn_sum += v1;\n\n\t\t\t\tauto v2 = add_boolean();\n\t\t\t\t\/\/ v2  <=>  !y && x1 && x2.\n\t\t\t\t\/\/ <=\n\t\t\t\tadd_constraint( (1-y) + x1 + x2 <= 2 + v2 );\n\t\t\t\t\/\/ =>\n\t\t\t\tadd_constraint( implication(v2, x1) );\n\t\t\t\tadd_constraint( implication(v2, x2) );\n\t\t\t\tadd_constraint( implication(v2, !y) );\n\t\t\t\tturn_sum -= v2;\n\t\t\t};\n\n\t\tfor (size_t i = 0; i < m + 1; ++i) {\n\t\t\tfor (size_t j = 0; j < n + 1; ++j) {\n\n\t\t\t\t\/\/  X\n\t\t\t\t\/\/  YX\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i][j];\n\t\t\t\t\tauto& x2 = padded_grid[i+1][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i][j+1];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/ XY\n\t\t\t\t\/\/  X\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i][j];\n\t\t\t\t\tauto& x2 = padded_grid[i+1][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i+1][j];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/ YX\n\t\t\t\t\/\/ X\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i+1][j];\n\t\t\t\t\tauto& x2 = padded_grid[i][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i][j];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\n\t\t\t\t\/\/  X\n\t\t\t\t\/\/ XY\n\t\t\t\t{\n\t\t\t\t\tauto& x1 = padded_grid[i+1][j];\n\t\t\t\t\tauto& x2 = padded_grid[i][j+1];\n\t\t\t\t\tauto& y  = padded_grid[i+1][j+1];\n\t\t\t\t\tadd_triple_constraints(x1, x2, y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tadd_constraint(4, turn_sum, 4);\n\n\t\t\/\/ Forbid the two configurations\n\t\t\/\/\n\t\t\/\/  01     10\n\t\t\/\/  10 and 01\n\t\t\/\/\n\t\t\/\/ This is not completely correct, but the code\n\t\t\/\/ above can not handle them.\n\t\tfor (int i = 0; i < m + 1; ++i) {\n\t\t\tfor (int j = 0; j < n + 1; ++j) {\n\t\t\t\tadd_constraint(padded_grid[i][i] + (1 - padded_grid[i+1][j]) +\n\t\t\t\t               (1 - padded_grid[i][j+1]) + padded_grid[i+1][j+1] <= 3);\n\t\t\t\tadd_constraint((1 - padded_grid[i][i]) + padded_grid[i+1][j] +\n\t\t\t\t               padded_grid[i][j+1] + (1 - padded_grid[i+1][j+1]) <= 3);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ The second way is based on adding flow to one square and\n\t\/\/ requiring it to dissipate through the grid.\n\tvoid add_connected_constraint_flow(const vector>& grid,\n\t                                   int start_i, int start_j)\n\t{\n\t\tauto m = grid.size();\n\t\tif (m == 0) return;\n\t\tauto n = grid[0].size();\n\n\t\tauto num_elements = double(m * n);\n\n\t\tvector> node_balance(m, vector(n, 0.0));\n\t\tSum number_of_active_nodes = 0;\n\n\t\tfor (size_t i = 0; i < m; ++i) {\n\t\t\tfor (size_t j = 0; j < n; ++j) {\n\n\t\t\t\tnumber_of_active_nodes += grid[i][j];\n\n\t\t\t\tif (i < m - 1) {\n\t\t\t\t\tauto fij = add_variable(Real);\n\t\t\t\t\tnode_balance[i][j]   += fij;\n\t\t\t\t\tnode_balance[i+1][j] -= fij;\n\n\t\t\t\t\tadd_constraint( fij >= 0 );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j] );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i+1][j] );\n\t\t\t\t}\n\n\t\t\t\tif (i > 0) {\n\t\t\t\t\tauto fij = add_variable(Real);\n\t\t\t\t\tnode_balance[i][j]   += fij;\n\t\t\t\t\tnode_balance[i-1][j] -= fij;\n\n\t\t\t\t\tadd_constraint( fij >= 0 );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j] );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i-1][j] );\n\t\t\t\t}\n\n\t\t\t\tif (j < n - 1) {\n\t\t\t\t\tauto fij = add_variable(Real);\n\t\t\t\t\tnode_balance[i][j]   += fij;\n\t\t\t\t\tnode_balance[i][j+1] -= fij;\n\n\t\t\t\t\tadd_constraint( fij >= 0 );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j] );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j+1] );\n\t\t\t\t}\n\n\t\t\t\tif (j > 0) {\n\t\t\t\t\tauto fij = add_variable(Real);\n\t\t\t\t\tnode_balance[i][j]   += fij;\n\t\t\t\t\tnode_balance[i][j-1] -= fij;\n\n\t\t\t\t\tadd_constraint( fij >= 0 );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j] );\n\t\t\t\t\tadd_constraint( fij <= num_elements*grid[i][j-1] );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tauto total_flow = add_variable(Real);\n\t\tset_bounds(0, total_flow, num_elements);\n\t\tadd_constraint(total_flow == number_of_active_nodes);\n\n\t\tnode_balance[start_i][start_j] += total_flow;\n\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tauto f_it = add_variable(Real);\n\t\t\t\tset_bounds(0, f_it, 1);\n\t\t\t\tnode_balance[i][j] -= f_it;\n\n\t\t\t\tadd_constraint(node_balance[i][j] == 0);\n\t\t\t}\n\t\t}\n\t}\n\n};\n\nint main_program()\n{\n\tusing namespace std;\n\n\tint n = 6;\n\n\tMyIP ip;\n\n\t\/\/ Parking spots. We want to maximize the number of these.\n\tauto P = ip.add_boolean_grid(n, n, -1.0);\n\t\/\/ Transporation to parking spots.\n\tauto T = ip.add_boolean_grid(n, n);\n\n\tint starti = 0;\n\tint startj = 1;\n\n\t\/\/ Entrance to the parking lot.\n\tip.add_constraint( T[starti][startj] );\n\n\t\/\/ T[0][0] == 1\n\t\/\/. P P P P P\n\t\/\/. . . . . .\n\t\/\/. P P P P P\n\t\/\/. P P P P P\n\t\/\/. . . . . .\n\t\/\/P P P P P P\n\t\/\/ 21\n\n\t\/\/ T[0][1] == 1\n\t\/\/P . P P P P\n\t\/\/P . . . . .\n\t\/\/P . P P P P\n\t\/\/P . P P P P\n\t\/\/P . . . . .\n\t\/\/  P P P P P\n\t\/\/ 22\n\n\t\/\/ T[0][2] == 1\n\t\/\/P . . . . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/P . P P . P\n\t\/\/ 22\n\n\t\/\/ T[0][1] == 1\n\t\/\/ P . P P P P P P . P\n\t\/\/ P . P . . . . . . P\n\t\/\/ P . P P P P P P . P\n\t\/\/ P . P   P P P P . P\n\t\/\/ P . P P . . . . . P\n\t\/\/ P . P P . P . P . P\n\t\/\/ P . P P . P P P . P\n\t\/\/ P . P P . P P P P P\n\t\/\/ . . . . . . . . . .\n\t\/\/ P P P P P P P P P P\n\t\/\/ 61\n\n\t\/\/ Border\n\t\/*\n\tSum above_border = 0;\n\tfor (int i = 0; i < n; ++i) {\n\t\tabove_border += T[0][i];\n\t}\n\t\/\/ There has to be an entrance.\n\tip.add_constraint(above_border >= 1);\n\t*\/\n\n\t\/\/ We can not have both parking and transportation.\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\/\/ Not allowing both to be zero seems to give a slightly\n\t\t\t\/\/ stronger formulation.\n\t\t\tip.add_constraint(P[i][j] + T[i][j] == 1);\n\t\t}\n\t}\n\n\t\/\/ Every parking lot needs to be adjacent to a transport square.\n\tfor (int i = 0; i < n; ++i) {\n\t\tfor (int j = 0; j < n; ++j) {\n\t\t\tSum neighborhood;\n\t\t\tif (i > 0) {\n\t\t\t\tneighborhood += T[i-1][j];\n\t\t\t}\n\t\t\tif (i < n - 1) {\n\t\t\t\tneighborhood += T[i+1][j];\n\t\t\t}\n\t\t\tif (j > 0) {\n\t\t\t\tneighborhood += T[i][j-1];\n\t\t\t}\n\t\t\tif (j < n - 1) {\n\t\t\t\tneighborhood += T[i][j+1];\n\t\t\t}\n\n\t\t\tip.add_constraint( P[i][j] <= neighborhood );\n\t\t\tip.add_constraint( T[i][j] <= neighborhood + P[i][j] );\n\t\t}\n\t}\n\n\t\/\/ The hardest part: the transport squares need to be\n\t\/\/ connected to each other.\n\tip.add_connected_constraint_perimeter(T);\n\t\/\/ip.add_connected_constraint_flow(T, starti, startj);\n\n\tauto print_solution = [&] () \n\t{\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tfor (int j = 0; j < n; ++j) {\n\t\t\t\tauto p = ip.get_solution(P[i][j]);\n\t\t\t\tauto t = ip.get_solution(T[i][j]);\n\t\t\t\tif (p && t) {\n\t\t\t\t\t\/\/ Infeasible.\n\t\t\t\t\tcout << '#';\n\t\t\t\t}\n\t\t\t\telse if (!p && !t) {\n\t\t\t\t\tcout << ' ';\n\t\t\t\t}\n\t\t\t\telse if (p) {\n\t\t\t\t\tcout << 'P';\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcout << '.';\n\t\t\t\t}\n\t\t\t\tcout << ' ';\n\t\t\t}\n\t\t\tcout << endl;\n\t\t}\n\t\tcout << endl;\n\t};\n\n\t\/\/ip.set_external_solver(IP::MOSEK);\n\tattest(ip.solve(print_solution));\n\n\tdo {\n\t\tprint_solution();\n\t} while (false \/*ip.next_solution()*\/);\n\n\n\treturn 0;\n}\n\nint main()\n{\n\ttry {\n\t\treturn main_program();\n\t}\n\tcatch (std::exception& err) {\n\t\tstd::cerr << \"ERROR: \" << err.what() << std::endl;\n\t}\n}\n<|endoftext|>"}
{"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \n#include \"main.h\"\n#include \n\ntemplate\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n  std::vector v(10, MatrixType(rows,cols)), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  MatrixType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i\nvoid check_stdvector_transform(const TransformType&)\n{\n  typedef typename TransformType::MatrixType MatrixType;\n  TransformType x(MatrixType::Random()), y(MatrixType::Random());\n  std::vector v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  TransformType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n  typedef typename QuaternionType::Coefficients Coefficients;\n  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n  std::vector v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  QuaternionType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i\"forgot to commit the required changes in stdvector unit test\"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \n#include \"main.h\"\n#include \n\ntemplate\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n  int rows = m.rows();\n  int cols = m.cols();\n  MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n  std::vector > v(10, MatrixType(rows,cols)), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  MatrixType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i\nvoid check_stdvector_transform(const TransformType&)\n{\n  typedef typename TransformType::MatrixType MatrixType;\n  TransformType x(MatrixType::Random()), y(MatrixType::Random());\n  std::vector > v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  TransformType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n  typedef typename QuaternionType::Coefficients Coefficients;\n  QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n  std::vector > v(10), w(20, y);\n  v[5] = x;\n  w[6] = v[5];\n  VERIFY_IS_APPROX(w[6], v[5]);\n  v = w;\n  for(int i = 0; i < 20; i++)\n  {\n    VERIFY_IS_APPROX(w[i], v[i]);\n  }\n\n  v.resize(21);\n  v[20] = x;\n  VERIFY_IS_APPROX(v[20], x);\n  v.resize(22,y);\n  VERIFY_IS_APPROX(v[21], y);\n  v.push_back(x);\n  VERIFY_IS_APPROX(v[22], x);\n  VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n  \/\/ do a lot of push_back such that the vector gets internally resized\n  \/\/ (with memory reallocation)\n  QuaternionType* ref = &w[0];\n  for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n    v.push_back(w[i%w.size()]);\n  for(unsigned int i=23; i"}
{"text":"\/*\nCopyright (c) 2016, oasi-adamay\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\n* Neither the name of glsCV nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"stdafx.h\"\n\n\/*-----------------------------------------------------------------------------\ninclude\n*\/\n#include \"glsMacro.h\"\n#include \"GlsMat.h\"\n#include \"glsShader.h\"\n\n#include \"glsResize.h\"\n\nnamespace gls\n{\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResize\nclass glsShaderResizeBase : public glsShaderBase\n{\nprotected:\n\tlist UniformNameList(void){\n\t\tlist lst;\n\t\tlst.push_back(\"texSrc\");\n\t\tlst.push_back(\"fx\");\n\t\tlst.push_back(\"fy\");\n\t\tlst.push_back(\"flag\");\n\t\treturn lst;\n\t}\npublic:\n\tglsShaderResizeBase(const string& _name) :glsShaderBase(_name){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResize\nclass glsShaderResize : public glsShaderResizeBase\n{\nprotected:\n\tstring FragmentShaderCode(void);\npublic:\n\tglsShaderResize(void) :glsShaderResizeBase(__FUNCTION__){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/glsShaderResize\nstring glsShaderResize::FragmentShaderCode(void){\n\tconst char fragmentShaderCode[] = TO_STR(\n#version 330 core\\n\nprecision highp float; \\n\nuniform sampler2D\ttexSrc; \\n\nuniform float fx; \\n\nuniform float fy; \\n\nuniform int flag; \\n\nlayout(location = 0) out vec4 dst; \\n\n#define BOUND_PVT(x,pl,pr) ((x)<(pl)?2*(pl)-(x) :(x)>(pr)? 2*(pr)-(x): (x))\\n\nvec4 cubic(float x){\n\tfloat A = -0.75;\n\tvec4 coeffs;\n\tcoeffs[0] = ((A*(x + 1) - 5 * A)*(x + 1) + 8 * A)*(x + 1) - 4 * A;\n\tcoeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1;\n\tcoeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;\n\tcoeffs[3] = 1.0 - coeffs[0] - coeffs[1] - coeffs[2];\n\treturn coeffs; \\n\n} \\n\nvec4 textureBicubic(sampler2D sampler, vec2 texCoords){\t\\n\n\tivec2 texSize = textureSize(sampler, 0); \\n\n\ttexCoords = texCoords * vec2(texSize) - vec2(0.5);  \\n\n\tvec2 fxy = fract(texCoords);  \\n\n\tvec4 xcubic = cubic(fxy.x);  \\n\n\tvec4 ycubic = cubic(fxy.y); \\n\n\ttexCoords -= fxy; \\n\n\tvec4 sum = vec4(0.0);\n\tfor (int i = -1; i < 3; i++){\n\t\tvec4 xsum = vec4(0.0);\n\t\tfor (int j = -1; j < 3; j++){\n\t\t\tivec2 coord = ivec2(texCoords.x + j, texCoords.y + i);\n\t\t\t\/\/TODO: 画像外周部の扱いをCVと合わせる。\n\/\/\t\t\tcoord.x = BOUND_PVT(coord.x, 0, texSize.x -1);\n\/\/\t\t\tcoord.y = BOUND_PVT(coord.y, 0, texSize.y -1);\n\t\t\tif (coord.x < 0) coord.x = 0;\n\t\t\tif (coord.x > texSize.x - 1) coord.x = texSize.x - 1;\n\t\t\tif (coord.y < 0) coord.y = 0;\n\t\t\tif (coord.y > texSize.y - 1) coord.y = texSize.y - 1;\n\t\t\tvec4  sample = texelFetch(sampler, coord, 0); \n\t\t\txsum += sample * vec4(xcubic[j + 1]);\n\t\t}\n\t\tsum += xsum * vec4(ycubic[i + 1]);\n\t}\n\treturn sum; \\n\n} \\n\nvoid main(void)\\n\n{ \\n\n\tivec2 texSize = textureSize(texSrc, 0); \\n\n\tvec2 coord = gl_FragCoord.xy; \\n\n\tcoord = vec2(coord.x \/ (float(texSize.x)*fx), coord.y \/ (float(texSize.y)*fy)); \\n\n\tif (flag == 0){\n\t\\n\n\t\tdst = texture(texSrc, coord); \\n\n\t}\\n\n\telse{ \\n\n\t\tdst = textureBicubic(texSrc, coord); \\n\n\t} \\n\n}\\n\n);\n\treturn fragmentShaderCode;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResizeU\nclass glsShaderResizeU : public glsShaderResizeBase\n{\nprotected:\n\tstring FragmentShaderCode(void);\npublic:\n\tglsShaderResizeU(void) :glsShaderResizeBase(__FUNCTION__){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/glsShaderResizeU\nstring glsShaderResizeU::FragmentShaderCode(void){\n\tconst char fragmentShaderCode[] = TO_STR(\n#version 330 core\\n\nprecision highp float; \\n\nuniform usampler2D\ttexSrc; \\n\nuniform float fx; \\n\nuniform float fy; \\n\nuniform int flag; \\n\nlayout(location = 0) out uvec4 dst; \\n\nvec4 cubic(float x){\n\tfloat A = -0.75;\n\tvec4 coeffs;\n\tcoeffs[0] = ((A*(x + 1) - 5 * A)*(x + 1) + 8 * A)*(x + 1) - 4 * A;\n\tcoeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1;\n\tcoeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;\n\tcoeffs[3] = 1.0 - coeffs[0] - coeffs[1] - coeffs[2];\n\treturn coeffs; \\n\n} \\n\nuvec4 textureBicubic(usampler2D sampler, vec2 texCoords){\t\\n\n\tivec2 texSize = textureSize(sampler, 0); \\n\n\ttexCoords = texCoords * vec2(texSize) - vec2(0.5);  \\n\n\tvec2 fxy = fract(texCoords);  \\n\n\tvec4 xcubic = cubic(fxy.x);  \\n\n\tvec4 ycubic = cubic(fxy.y); \\n\n\ttexCoords -= fxy; \\n\n\tvec4 sum = vec4(0.0);\n\tfor (int i = -1; i < 3; i++){\n\t\tvec4 xsum = vec4(0.0);\n\t\tfor (int j = -1; j < 3; j++){\n\t\t\tivec2 coord = ivec2(texCoords.x + j, texCoords.y + i);\n\t\t\tif (coord.x < 0) coord.x = 0;\n\t\t\tif (coord.x > texSize.x - 1) coord.x = texSize.x - 1;\n\t\t\tif (coord.y < 0) coord.y = 0;\n\t\t\tif (coord.y > texSize.y - 1) coord.y = texSize.y - 1;\n\t\t\tvec4  sample = vec4(texelFetch(sampler, coord, 0)); \n\t\t\txsum += sample * vec4(xcubic[j + 1]);\n\t\t}\n\t\tsum += xsum * vec4(ycubic[i + 1]);\n\t}\n\treturn uvec4(sum); \\n\n} \\n\nvoid main(void)\\n\n{ \\n\n\tivec2 texSize = textureSize(texSrc, 0); \\n\n\tvec2 coord = gl_FragCoord.xy; \\n\n\tcoord = vec2(coord.x \/ (float(texSize.x)*fx), coord.y \/ (float(texSize.y)*fy)); \\n\n\tif (flag == 0){\t\\n\n\t\tdst = uvec4(texture(texSrc, coord)); \\n\n\/\/\t\tdst = uvec4(128); \\n\n\t}\\n\n\telse{ \\n\n\tdst = textureBicubic(texSrc, coord); \\n\n\t} \\n\n}\\n\n);\n\treturn fragmentShaderCode;\n}\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/global \nglsShaderResize ShaderResize;\nglsShaderResizeU ShaderResizeU;\n\n\n\nstatic \nglsShaderBase* selectShader(int type){\n\tglsShaderBase* shader = 0;\n\tswitch (CV_MAT_DEPTH(type)){\n\tcase(CV_32F) : shader = &ShaderResize; break;\n\tcase(CV_8U) :\n\tcase(CV_16U) : shader = &ShaderResizeU; break;\n\t\/\/case(CV_8S) :\n\t\/\/case(CV_16S) :\n\t\/\/case(CV_32S) : shader = &ShaderResizeI; break;\n\tdefault: GLS_Assert(0);\t\t\/\/not implement\n\t}\n\treturn shader;\n}\n\nvoid resize(const GlsMat& src, GlsMat& dst, Size dsize, double fx, double fy, int interpolation){\n\tGLS_Assert(src.depth() == CV_32F \n\t\t\t|| src.depth() == CV_8U\n\t\t\t|| src.depth() == CV_16U);\n\tGLS_Assert(interpolation == INTER_NEAREST \n\t\t\t|| interpolation == INTER_LINEAR\n\t\t\t|| interpolation == INTER_CUBIC);\n\tGLS_Assert((fx == 0 && fy == 0 && dsize != Size(0, 0))\n\t\t|| (fx > 0 && fy > 0 && dsize == Size(0, 0)));\n\n\tif (fx == 0 && fy == 0){\n\t\tfx = dsize.width \/ (double)src.cols;\n\t\tfy = dsize.height \/ (double)src.rows;\n\t}\n\telse{\n\t\tdsize = Size((int)round(fx*src.cols), (int)round(fy*src.rows));\n\t}\n\n\tint flag;\n\t\t\n\tGlsMat _dst = getDstMat(dsize, src.type(), dst);\n\tglsShaderBase* shader = selectShader(src.type());\n\tswitch (interpolation){\n\tcase(INTER_NEAREST) : {\n\t\tsrc.setInterpolation(GL_NEAREST);\n\t\tflag = 0;\n\t}break;\n\tcase(INTER_LINEAR) : {\n\t\tsrc.setInterpolation(GL_LINEAR);\n\t\tflag = 0;\n\t}break;\n\tcase(INTER_CUBIC) : {\n\/\/\t\tsrc.setInterpolation(GL_LINEAR);\n\t\tsrc.setInterpolation(GL_NEAREST);\n\t\tflag = 1;\n\t}break;\n\tdefault: GLS_Assert(0);\n\t}\n\n\tshader->Execute(src, fx, fy, flag, _dst);\n\tdst = _dst;\n}\n\n\n}\/\/namespace gls\n\n\n\n\n\nglsResize 8U Bilinear の出力が全黒なのを修正\/*\nCopyright (c) 2016, oasi-adamay\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\n* Neither the name of glsCV nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"stdafx.h\"\n\n\/*-----------------------------------------------------------------------------\ninclude\n*\/\n#include \"glsMacro.h\"\n#include \"GlsMat.h\"\n#include \"glsShader.h\"\n\n#include \"glsResize.h\"\n\nnamespace gls\n{\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResize\nclass glsShaderResizeBase : public glsShaderBase\n{\nprotected:\n\tlist UniformNameList(void){\n\t\tlist lst;\n\t\tlst.push_back(\"texSrc\");\n\t\tlst.push_back(\"fx\");\n\t\tlst.push_back(\"fy\");\n\t\tlst.push_back(\"flag\");\n\t\treturn lst;\n\t}\npublic:\n\tglsShaderResizeBase(const string& _name) :glsShaderBase(_name){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResize\nclass glsShaderResize : public glsShaderResizeBase\n{\nprotected:\n\tstring FragmentShaderCode(void);\npublic:\n\tglsShaderResize(void) :glsShaderResizeBase(__FUNCTION__){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/glsShaderResize\nstring glsShaderResize::FragmentShaderCode(void){\n\tconst char fragmentShaderCode[] = TO_STR(\n#version 330 core\\n\nprecision highp float; \\n\nuniform sampler2D\ttexSrc; \\n\nuniform float fx; \\n\nuniform float fy; \\n\nuniform int flag; \\n\nlayout(location = 0) out vec4 dst; \\n\n#define BOUND_PVT(x,pl,pr) ((x)<(pl)?2*(pl)-(x) :(x)>(pr)? 2*(pr)-(x): (x))\\n\nvec4 cubic(float x){\n\tfloat A = -0.75;\n\tvec4 coeffs;\n\tcoeffs[0] = ((A*(x + 1) - 5 * A)*(x + 1) + 8 * A)*(x + 1) - 4 * A;\n\tcoeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1;\n\tcoeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;\n\tcoeffs[3] = 1.0 - coeffs[0] - coeffs[1] - coeffs[2];\n\treturn coeffs; \\n\n} \\n\nvec4 textureBicubic(sampler2D sampler, vec2 texCoords){\t\\n\n\tivec2 texSize = textureSize(sampler, 0); \\n\n\ttexCoords = texCoords * vec2(texSize) - vec2(0.5);  \\n\n\tvec2 fxy = fract(texCoords);  \\n\n\tvec4 xcubic = cubic(fxy.x);  \\n\n\tvec4 ycubic = cubic(fxy.y); \\n\n\ttexCoords -= fxy; \\n\n\tvec4 sum = vec4(0.0);\n\tfor (int i = -1; i < 3; i++){\n\t\tvec4 xsum = vec4(0.0);\n\t\tfor (int j = -1; j < 3; j++){\n\t\t\tivec2 coord = ivec2(texCoords.x + j, texCoords.y + i);\n\t\t\t\/\/TODO: 画像外周部の扱いをCVと合わせる。\n\/\/\t\t\tcoord.x = BOUND_PVT(coord.x, 0, texSize.x -1);\n\/\/\t\t\tcoord.y = BOUND_PVT(coord.y, 0, texSize.y -1);\n\t\t\tif (coord.x < 0) coord.x = 0;\n\t\t\tif (coord.x > texSize.x - 1) coord.x = texSize.x - 1;\n\t\t\tif (coord.y < 0) coord.y = 0;\n\t\t\tif (coord.y > texSize.y - 1) coord.y = texSize.y - 1;\n\t\t\tvec4  sample = texelFetch(sampler, coord, 0); \n\t\t\txsum += sample * vec4(xcubic[j + 1]);\n\t\t}\n\t\tsum += xsum * vec4(ycubic[i + 1]);\n\t}\n\treturn sum; \\n\n} \\n\nvoid main(void)\\n\n{ \\n\n\tivec2 texSize = textureSize(texSrc, 0); \\n\n\tvec2 coord = gl_FragCoord.xy; \\n\n\tcoord = vec2(coord.x \/ (float(texSize.x)*fx), coord.y \/ (float(texSize.y)*fy)); \\n\n\tif (flag == 0){\n\t\\n\n\t\tdst = texture(texSrc, coord); \\n\n\t}\\n\n\telse{ \\n\n\t\tdst = textureBicubic(texSrc, coord); \\n\n\t} \\n\n}\\n\n);\n\treturn fragmentShaderCode;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ glsShaderResizeU\nclass glsShaderResizeU : public glsShaderResizeBase\n{\nprotected:\n\tstring FragmentShaderCode(void);\npublic:\n\tglsShaderResizeU(void) :glsShaderResizeBase(__FUNCTION__){}\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/glsShaderResizeU\nstring glsShaderResizeU::FragmentShaderCode(void){\n\tconst char fragmentShaderCode[] = TO_STR(\n#version 330 core\\n\nprecision highp float; \\n\nuniform usampler2D\ttexSrc; \\n\nuniform float fx; \\n\nuniform float fy; \\n\nuniform int flag; \\n\nlayout(location = 0) out uvec4 dst; \\n\nvec4 cubic(float x){\n\tfloat A = -0.75;\n\tvec4 coeffs;\n\tcoeffs[0] = ((A*(x + 1) - 5 * A)*(x + 1) + 8 * A)*(x + 1) - 4 * A;\n\tcoeffs[1] = ((A + 2)*x - (A + 3))*x*x + 1;\n\tcoeffs[2] = ((A + 2)*(1 - x) - (A + 3))*(1 - x)*(1 - x) + 1;\n\tcoeffs[3] = 1.0 - coeffs[0] - coeffs[1] - coeffs[2];\n\treturn coeffs; \\n\n} \\n\nuvec4 textureBicubic(usampler2D sampler, vec2 texCoords){\t\\n\n\tivec2 texSize = textureSize(sampler, 0); \\n\n\ttexCoords = texCoords * vec2(texSize) - vec2(0.5);  \\n\n\tvec2 fxy = fract(texCoords);  \\n\n\tvec4 xcubic = cubic(fxy.x);  \\n\n\tvec4 ycubic = cubic(fxy.y); \\n\n\ttexCoords -= fxy; \\n\n\tvec4 sum = vec4(0.0);\n\tfor (int i = -1; i < 3; i++){\n\t\tvec4 xsum = vec4(0.0);\n\t\tfor (int j = -1; j < 3; j++){\n\t\t\tivec2 coord = ivec2(texCoords.x + j, texCoords.y + i);\n\t\t\tif (coord.x < 0) coord.x = 0;\n\t\t\tif (coord.x > texSize.x - 1) coord.x = texSize.x - 1;\n\t\t\tif (coord.y < 0) coord.y = 0;\n\t\t\tif (coord.y > texSize.y - 1) coord.y = texSize.y - 1;\n\t\t\tvec4  sample = vec4(texelFetch(sampler, coord, 0)); \n\t\t\txsum += sample * vec4(xcubic[j + 1]);\n\t\t}\n\t\tsum += xsum * vec4(ycubic[i + 1]);\n\t}\n\treturn uvec4(sum); \\n\n} \\n\nvec2 linear(float x){\n\tvec2 coeffs;\n\tcoeffs[0] = 1.0-x;\n\tcoeffs[1] = x;\n\treturn coeffs; \\n\n} \\n\nuvec4 textureBilinear(usampler2D sampler, vec2 texCoords){\t\\n\n\tivec2 texSize = textureSize(sampler, 0); \\n\n\ttexCoords = texCoords * vec2(texSize) - vec2(0.5);  \\n\n\tvec2 fxy = fract(texCoords);  \\n\n\tvec2 xlinear = linear(fxy.x);  \\n\n\tvec2 ylinear = linear(fxy.y); \\n\n\ttexCoords -= fxy; \\n\n\tvec4 sum = vec4(0.0);\n\tfor (int i = 0; i < 2; i++){\n\t\tvec4 xsum = vec4(0.0);\n\t\tfor (int j = 0; j < 2; j++){\n\t\t\tivec2 coord = ivec2(texCoords.x + j, texCoords.y + i);\n\t\t\tif (coord.x < 0) coord.x = 0;\n\t\t\tif (coord.x > texSize.x - 1) coord.x = texSize.x - 1;\n\t\t\tif (coord.y < 0) coord.y = 0;\n\t\t\tif (coord.y > texSize.y - 1) coord.y = texSize.y - 1;\n\t\t\tvec4  sample = vec4(texelFetch(sampler, coord, 0)); \n\t\t\txsum += sample * vec4(xlinear[j]);\n\t\t}\n\t\tsum += xsum * vec4(ylinear[i]);\n\t}\n\treturn uvec4(sum); \\n\n} \\n\n\n\n\nvoid main(void)\\n\n{ \\n\n\tivec2 texSize = textureSize(texSrc, 0); \\n\n\tvec2 coord = gl_FragCoord.xy; \\n\n\tcoord = vec2(coord.x \/ (float(texSize.x)*fx), coord.y \/ (float(texSize.y)*fy)); \\n\n\tif (flag == 0){\t\\n\n\t\tdst = uvec4(texture(texSrc, coord)); \\n\n\/\/\t\tdst = uvec4(128); \\n\n\t}\\n\n\telse if (flag == 1){\t\\n\n\t\tdst = textureBicubic(texSrc, coord); \\n\n\t} \\n\n\telse{\\n\n\t\tdst = textureBilinear(texSrc, coord); \\n\n\t} \\n\n}\\n\n);\n\treturn fragmentShaderCode;\n}\n\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/global \nglsShaderResize ShaderResize;\nglsShaderResizeU ShaderResizeU;\n\n\n\nstatic \nglsShaderBase* selectShader(int type){\n\tglsShaderBase* shader = 0;\n\tswitch (CV_MAT_DEPTH(type)){\n\tcase(CV_32F) : shader = &ShaderResize; break;\n\tcase(CV_8U) :\n\tcase(CV_16U) : shader = &ShaderResizeU; break;\n\t\/\/case(CV_8S) :\n\t\/\/case(CV_16S) :\n\t\/\/case(CV_32S) : shader = &ShaderResizeI; break;\n\tdefault: GLS_Assert(0);\t\t\/\/not implement\n\t}\n\treturn shader;\n}\n\nvoid resize(const GlsMat& src, GlsMat& dst, Size dsize, double fx, double fy, int interpolation){\n\tGLS_Assert(src.depth() == CV_32F \n\t\t\t|| src.depth() == CV_8U\n\t\t\t|| src.depth() == CV_16U);\n\tGLS_Assert(interpolation == INTER_NEAREST \n\t\t\t|| interpolation == INTER_LINEAR\n\t\t\t|| interpolation == INTER_CUBIC);\n\tGLS_Assert((fx == 0 && fy == 0 && dsize != Size(0, 0))\n\t\t|| (fx > 0 && fy > 0 && dsize == Size(0, 0)));\n\n\tif (fx == 0 && fy == 0){\n\t\tfx = dsize.width \/ (double)src.cols;\n\t\tfy = dsize.height \/ (double)src.rows;\n\t}\n\telse{\n\t\tdsize = Size((int)round(fx*src.cols), (int)round(fy*src.rows));\n\t}\n\n\tint flag;\n\t\t\n\tGlsMat _dst = getDstMat(dsize, src.type(), dst);\n\tglsShaderBase* shader = selectShader(src.type());\n\tswitch (interpolation){\n\tcase(INTER_NEAREST) : {\n\t\tsrc.setInterpolation(GL_NEAREST);\n\t\tflag = 0;\n\t}break;\n\tcase(INTER_LINEAR) : {\n\t\tif (src.depth() == CV_32F){\n\t\t\tsrc.setInterpolation(GL_LINEAR);\n\t\t\tflag = 0;\n\t\t}\n\t\telse{\n\t\t\tsrc.setInterpolation(GL_NEAREST);\n\t\t\tflag = 2;\n\t\t}\n\t}break;\n\tcase(INTER_CUBIC) : {\n\/\/\t\tsrc.setInterpolation(GL_LINEAR);\n\t\tsrc.setInterpolation(GL_NEAREST);\n\t\tflag = 1;\n\t}break;\n\tdefault: GLS_Assert(0);\n\t}\n\n\tshader->Execute(src, fx, fy, flag, _dst);\n\tdst = _dst;\n}\n\n\n}\/\/namespace gls\n\n\n\n\n\n<|endoftext|>"}
{"text":"\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"runtime\/core\/sequencetypes.h\"\n#include \"runtime\/util\/iterator_impl.h\"\n#include \"system\/globalenv.h\"\n#include \"zorbaerrors\/error_manager.h\"\n#include \"types\/casting.h\"\n#include \"types\/typeops.h\"\n#include \"store\/api\/item_factory.h\"\n#include \"context\/static_context.h\"\n\nusing namespace std;\n\nnamespace zorba\n{\n\n\/*******************************************************************************\n\n********************************************************************************\/\nInstanceOfIterator::InstanceOfIterator(\n   const QueryLoc& loc,\n   PlanIter_t& aTreatExpr,\n   xqtref_t aSequenceType)\n  :\n  UnaryBaseIterator ( loc, aTreatExpr ),\n  theSequenceType (aSequenceType)\n{ \n}\n\n\nInstanceOfIterator::~InstanceOfIterator() \n{\n}\n\n\nbool\nInstanceOfIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t lTreatItem;\n  xqtref_t lTreatType;\n  TypeConstants::quantifier_t lQuantifier;\n  bool lResult;\n  RootTypeManager& ts = GENV_TYPESYSTEM;\n\n  PlanIteratorState* state;\n  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);\n  \n  lQuantifier = TypeOps::quantifier(*theSequenceType);\n  if (consumeNext(lTreatItem, theChild.getp(), planState))\n  {\n    if (TypeOps::is_treatable(lTreatItem, *theSequenceType))\n    {\n      if (consumeNext(lTreatItem, theChild.getp(), planState))\n      {\n        if (lQuantifier == TypeConstants::QUANT_ONE ||\n            lQuantifier == TypeConstants::QUANT_QUESTION)\n        {\n          lResult = false;\n        }\n        else\n        {\n          lResult = true;\n          do\n          {\n            if (!TypeOps::is_treatable(lTreatItem, *theSequenceType))\n            {\n              lResult = false;\n            }\n          } while (consumeNext(lTreatItem, theChild.getp(), planState));\n        }\n      }\n      else\n      {\n        lResult = true;\n      }\n    }\n    else\n    {\n      lResult = false;\n    }\n  }\n  else\n  {\n    if ((lQuantifier == TypeConstants::QUANT_ONE ||\n         lQuantifier == TypeConstants::QUANT_PLUS) &&\n        !TypeOps::is_equal(*ts.EMPTY_TYPE, *theSequenceType))\n    {\n      lResult = false;\n    }\n    else\n    {\n      lResult = true;\n    }\n  }\n    \n  STACK_PUSH(GENV_ITEMFACTORY->createBoolean(result, lResult), state);\n  STACK_END (state);\n}\n\n  \n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid\nCastIteratorState::init(PlanState& aPlanState)\n{\n  PlanIteratorState::init(aPlanState);\n  theIndex = 0;\n}\n\nvoid\nCastIteratorState::reset(PlanState& aPlanState)\n{\n  PlanIteratorState::reset(aPlanState);\n  theSimpleParseItems.clear();\n  theIndex = 0;\n}\n\nCastIterator::CastIterator(\n    const QueryLoc& loc,\n    PlanIter_t& aChild,\n    const xqtref_t& aCastType)\n  : UnaryBaseIterator(loc, aChild)\n{\n  theCastType = TypeOps::prime_type (*aCastType);\n  theQuantifier = TypeOps::quantifier(*aCastType);\n  if (aCastType->type_kind() == XQType::USER_DEFINED_KIND)\n  {\n    const UserDefinedXQType* lType = static_cast(aCastType.getp());\n    theIsSimpleType = !lType->isComplex();\n  }\n  else\n    theIsSimpleType = false;\n}\n\nCastIterator::~CastIterator(){}\n\n\nbool CastIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t lItem;\n  bool valid = false;\n  \n  CastIteratorState* state;\n  DEFAULT_STACK_INIT(CastIteratorState, state, planState);\n\n  if (!consumeNext(lItem, theChild.getp(), planState))\n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS ||\n        theQuantifier == TypeConstants::QUANT_ONE)\n    {\n      ZORBA_ERROR_LOC_DESC( XPTY0004, loc, \n        \"Empty sequences cannot be casted to a type with quantifier ONE or PLUS!\"\n      );\n    }\n  }\n  else if (theQuantifier == TypeConstants::QUANT_ONE ||\n          theQuantifier == TypeConstants::QUANT_QUESTION)\n  {\n    \/\/--\n    if (theIsSimpleType) {\n      state->reset(planState); \n      valid = GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                            theCastType,\n                                            state->theSimpleParseItems);\n    }\n    else\n      valid = GenericCast::instance()->castToAtomic(result, lItem, theCastType);\n    \/\/--\n    if (consumeNext(lItem, theChild.getp(), planState))\n    {\n      ZORBA_ERROR_LOC_DESC( XPTY0004, loc, \n                        \"Sequence with more than one item cannot be casted to a type with quantifier ONE or QUESTION!\");\n    }\n    \n    if (theIsSimpleType) {\n      while(state->theIndex < state->theSimpleParseItems.size()) {\n        result = state->theSimpleParseItems[state->theIndex++];\n        STACK_PUSH(true, state);\n      }\n    } \n    else\n      STACK_PUSH(valid, state);\n  }\n  else\n  {\n    \/\/--\n    if (theIsSimpleType) {\n      state->reset(planState); \n      GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                            theCastType,\n                                            state->theSimpleParseItems);\n      while(state->theIndex < state->theSimpleParseItems.size()) {\n        result = state->theSimpleParseItems[state->theIndex++];\n        STACK_PUSH(true, state);\n      }\n    }\n    else\n      STACK_PUSH(GenericCast::instance()->castToAtomic(result, lItem, theCastType), state);\n    \/\/--\n\n    while (consumeNext(lItem, theChild.getp(), planState))\n    {\n      \/\/--\n      if (theIsSimpleType) {\n        state->reset(planState); \n        GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                              theCastType,\n                                              state->theSimpleParseItems);\n        while(state->theIndex < state->theSimpleParseItems.size()) {\n          result = state->theSimpleParseItems[state->theIndex++];\n          STACK_PUSH(true, state);\n        }\n      }\n      else\n        STACK_PUSH(GenericCast::instance()->castToAtomic(result, lItem, theCastType), state);\n      \/\/--\n    }\n  }\n\n  STACK_END (state);\n}\n\n\/*******************************************************************************\n\n********************************************************************************\/\n\nCastableIterator::CastableIterator(\n  const QueryLoc& aLoc,\n  PlanIter_t& aChild,\n  const xqtref_t& aCastType)\n:\n  UnaryBaseIterator(aLoc, aChild)\n{\n  theCastType = TypeOps::prime_type (*aCastType);\n  theQuantifier = TypeOps::quantifier(*aCastType);\n}\n\nCastableIterator::~CastableIterator(){}\n\nbool CastableIterator::nextImpl(store::Item_t& result, PlanState& planState) const \n{\n  bool lBool;\n  store::Item_t lItem;\n\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n  if (!consumeNext(lItem, theChild.getp(), planState)) {\n    if (theQuantifier == TypeConstants::QUANT_PLUS || theQuantifier == TypeConstants::QUANT_ONE) {\n      lBool = false;\n    } else {\n      lBool = true;\n    }\n  } else {\n    lBool = GenericCast::instance()->isCastable(lItem, theCastType);\n    if (lBool) {\n      if (consumeNext(lItem, theChild.getp(), planState)) {\n        if (theQuantifier == TypeConstants::QUANT_ONE || theQuantifier == TypeConstants::QUANT_QUESTION) {\n          lBool = false;\n        } else {\n          do {\n            lBool = GenericCast::instance()->isCastable(lItem, theCastType);\n          } while (lBool && consumeNext(lItem, theChild.getp(), planState));\n        }\n      }\n    }\n  }\n  STACK_PUSH(GENV_ITEMFACTORY->createBoolean(result, lBool), lState);\n  STACK_END (lState);\n}\n\nPromoteIterator::PromoteIterator(const QueryLoc& aLoc, PlanIter_t& aChild, const xqtref_t& aPromoteType)\n  : UnaryBaseIterator(aLoc, aChild)\n{\n  thePromoteType = TypeOps::prime_type (*aPromoteType);\n  theQuantifier = TypeOps::quantifier(*aPromoteType);\n}\n\nPromoteIterator::~PromoteIterator(){}\n\nbool PromoteIterator::nextImpl(store::Item_t& result, PlanState& planState) const \n{\n  store::Item_t lItem;\n  store::Item_t temp;\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n\n  if (!consumeNext(lItem, theChild.getp(), planState)) \n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS || theQuantifier == TypeConstants::QUANT_ONE) {\n      ZORBA_ERROR_LOC_DESC(  XPTY0004, loc,  \n      \"Empty seq cannot be promoted to QUANT_ONE or QUANT_PLUS type.\");\n    }\n  } \n  else if(theQuantifier == TypeConstants::QUANT_QUESTION \n         || theQuantifier == TypeConstants::QUANT_ONE) \n  {\n    if (! GenericCast::instance()->promote(result, lItem, thePromoteType))\n      ZORBA_ERROR_LOC_DESC(XPTY0004, loc,\n                           \"Type promotion not possible: \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (lItem)) + \" -> \" + TypeOps::toString (*thePromoteType) );\n\n    if(consumeNext(temp, theChild.getp(), planState)) \n    {\n      ZORBA_ERROR_LOC_DESC(  XPTY0004, loc,  \n      \"Seq with 2 or more items cannot be promoted to a QUANT_QUESTION or QUANT_ONE type.\");\n    }\n    STACK_PUSH(true, lState);\n  }\n  else\n  {\n    do \n    {\n      if (! GenericCast::instance()->promote(result, lItem, thePromoteType))\n        ZORBA_ERROR_LOC_DESC( XPTY0004, loc,  \"Type promotion not possible: \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (lItem)) + \" -> \" + TypeOps::toString (*thePromoteType) );\n      else\n        STACK_PUSH(true, lState);\n    } while (consumeNext(lItem, theChild.getp(), planState));\n  }\n  STACK_END (lState);\n}\n\nTreatIterator::TreatIterator(const QueryLoc& aLoc, std::vector& aChildren, const xqtref_t& aTreatType, bool check_prime_, XQUERY_ERROR aErrorCode)\n  : NaryBaseIterator(aLoc, aChildren),\n    check_prime (check_prime_), theErrorCode (aErrorCode)\n{\n  theTreatType = TypeOps::prime_type (*aTreatType);\n  theQuantifier = TypeOps::quantifier(*aTreatType);\n}\n\n\nbool TreatIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t temp;\n\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n\n  if (!CONSUME (result, 0)) \n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS ||\n        theQuantifier == TypeConstants::QUANT_ONE) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \n      \"Cannot treat empty sequence as + or .\");\n    }\n  }\n  else if(theQuantifier == TypeConstants::QUANT_QUESTION \n         || theQuantifier == TypeConstants::QUANT_ONE) \n  {\n    if (CONSUME (temp, 0)) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc, \n      \"Cannot treat sequence with 2 or more items as ? or .\");\n    }\n\n    if ( check_prime && !TypeOps::is_treatable(result, *theTreatType)) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \"Cannot treat \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (result)) + \" as \" + TypeOps::toString (*theTreatType) );\n    }\n    else \n    {\n      STACK_PUSH(true, lState);\n    }\n  }\n  else \n  {\n    do \n    {\n      if ( check_prime && !TypeOps::is_treatable(result, *theTreatType)) \n      {\n        ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \"Cannot treat \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (result)) + \" as \" + TypeOps::toString (*theTreatType) );\n      }\n      else\n      {\n        STACK_PUSH(true, lState);\n      }\n    } while (CONSUME (result, 0));\n  }\n  STACK_END (lState);\n}\n\nbool EitherNodesOrAtomicsIterator::nextImpl(store::Item_t& result, PlanState& planState) const {\n  store::Item_t item;\n\n  EitherNodesOrAtomicsIteratorState *lState;\n  DEFAULT_STACK_INIT(EitherNodesOrAtomicsIteratorState, lState, planState);\n\n  if (CONSUME (result, 0)) {\n    lState->atomics = item->isAtomic ();\n    STACK_PUSH (true, lState);\n    \n    while (CONSUME (result, 0)) {\n      if (lState->atomics != item->isAtomic ())\n        ZORBA_ERROR_LOC (XPTY0018, loc);\n      STACK_PUSH (true, lState);\n    }\n  }\n  \n  STACK_END (lState);\n}\n\n\/*******************************************************************************\n\n********************************************************************************\/\n\n\n} \/* namespace zorba *\/\n\nfixed bug in EitherNodesOrAtomicsIterator\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"runtime\/core\/sequencetypes.h\"\n#include \"runtime\/util\/iterator_impl.h\"\n#include \"system\/globalenv.h\"\n#include \"zorbaerrors\/error_manager.h\"\n#include \"types\/casting.h\"\n#include \"types\/typeops.h\"\n#include \"store\/api\/item_factory.h\"\n#include \"context\/static_context.h\"\n\nusing namespace std;\n\nnamespace zorba\n{\n\n\/*******************************************************************************\n\n********************************************************************************\/\nInstanceOfIterator::InstanceOfIterator(\n   const QueryLoc& loc,\n   PlanIter_t& aTreatExpr,\n   xqtref_t aSequenceType)\n  :\n  UnaryBaseIterator ( loc, aTreatExpr ),\n  theSequenceType (aSequenceType)\n{ \n}\n\n\nInstanceOfIterator::~InstanceOfIterator() \n{\n}\n\n\nbool\nInstanceOfIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t lTreatItem;\n  xqtref_t lTreatType;\n  TypeConstants::quantifier_t lQuantifier;\n  bool lResult;\n  RootTypeManager& ts = GENV_TYPESYSTEM;\n\n  PlanIteratorState* state;\n  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);\n  \n  lQuantifier = TypeOps::quantifier(*theSequenceType);\n  if (consumeNext(lTreatItem, theChild.getp(), planState))\n  {\n    if (TypeOps::is_treatable(lTreatItem, *theSequenceType))\n    {\n      if (consumeNext(lTreatItem, theChild.getp(), planState))\n      {\n        if (lQuantifier == TypeConstants::QUANT_ONE ||\n            lQuantifier == TypeConstants::QUANT_QUESTION)\n        {\n          lResult = false;\n        }\n        else\n        {\n          lResult = true;\n          do\n          {\n            if (!TypeOps::is_treatable(lTreatItem, *theSequenceType))\n            {\n              lResult = false;\n            }\n          } while (consumeNext(lTreatItem, theChild.getp(), planState));\n        }\n      }\n      else\n      {\n        lResult = true;\n      }\n    }\n    else\n    {\n      lResult = false;\n    }\n  }\n  else\n  {\n    if ((lQuantifier == TypeConstants::QUANT_ONE ||\n         lQuantifier == TypeConstants::QUANT_PLUS) &&\n        !TypeOps::is_equal(*ts.EMPTY_TYPE, *theSequenceType))\n    {\n      lResult = false;\n    }\n    else\n    {\n      lResult = true;\n    }\n  }\n    \n  STACK_PUSH(GENV_ITEMFACTORY->createBoolean(result, lResult), state);\n  STACK_END (state);\n}\n\n  \n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid\nCastIteratorState::init(PlanState& aPlanState)\n{\n  PlanIteratorState::init(aPlanState);\n  theIndex = 0;\n}\n\nvoid\nCastIteratorState::reset(PlanState& aPlanState)\n{\n  PlanIteratorState::reset(aPlanState);\n  theSimpleParseItems.clear();\n  theIndex = 0;\n}\n\nCastIterator::CastIterator(\n    const QueryLoc& loc,\n    PlanIter_t& aChild,\n    const xqtref_t& aCastType)\n  : UnaryBaseIterator(loc, aChild)\n{\n  theCastType = TypeOps::prime_type (*aCastType);\n  theQuantifier = TypeOps::quantifier(*aCastType);\n  if (aCastType->type_kind() == XQType::USER_DEFINED_KIND)\n  {\n    const UserDefinedXQType* lType = static_cast(aCastType.getp());\n    theIsSimpleType = !lType->isComplex();\n  }\n  else\n    theIsSimpleType = false;\n}\n\nCastIterator::~CastIterator(){}\n\n\nbool CastIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t lItem;\n  bool valid = false;\n  \n  CastIteratorState* state;\n  DEFAULT_STACK_INIT(CastIteratorState, state, planState);\n\n  if (!consumeNext(lItem, theChild.getp(), planState))\n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS ||\n        theQuantifier == TypeConstants::QUANT_ONE)\n    {\n      ZORBA_ERROR_LOC_DESC( XPTY0004, loc, \n        \"Empty sequences cannot be casted to a type with quantifier ONE or PLUS!\"\n      );\n    }\n  }\n  else if (theQuantifier == TypeConstants::QUANT_ONE ||\n          theQuantifier == TypeConstants::QUANT_QUESTION)\n  {\n    \/\/--\n    if (theIsSimpleType) {\n      state->reset(planState); \n      valid = GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                            theCastType,\n                                            state->theSimpleParseItems);\n    }\n    else\n      valid = GenericCast::instance()->castToAtomic(result, lItem, theCastType);\n    \/\/--\n    if (consumeNext(lItem, theChild.getp(), planState))\n    {\n      ZORBA_ERROR_LOC_DESC( XPTY0004, loc, \n                        \"Sequence with more than one item cannot be casted to a type with quantifier ONE or QUESTION!\");\n    }\n    \n    if (theIsSimpleType) {\n      while(state->theIndex < state->theSimpleParseItems.size()) {\n        result = state->theSimpleParseItems[state->theIndex++];\n        STACK_PUSH(true, state);\n      }\n    } \n    else\n      STACK_PUSH(valid, state);\n  }\n  else\n  {\n    \/\/--\n    if (theIsSimpleType) {\n      state->reset(planState); \n      GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                            theCastType,\n                                            state->theSimpleParseItems);\n      while(state->theIndex < state->theSimpleParseItems.size()) {\n        result = state->theSimpleParseItems[state->theIndex++];\n        STACK_PUSH(true, state);\n      }\n    }\n    else\n      STACK_PUSH(GenericCast::instance()->castToAtomic(result, lItem, theCastType), state);\n    \/\/--\n\n    while (consumeNext(lItem, theChild.getp(), planState))\n    {\n      \/\/--\n      if (theIsSimpleType) {\n        state->reset(planState); \n        GenericCast::instance()->castToSimple(xqpString(lItem->getStringValue().getp()),\n                                              theCastType,\n                                              state->theSimpleParseItems);\n        while(state->theIndex < state->theSimpleParseItems.size()) {\n          result = state->theSimpleParseItems[state->theIndex++];\n          STACK_PUSH(true, state);\n        }\n      }\n      else\n        STACK_PUSH(GenericCast::instance()->castToAtomic(result, lItem, theCastType), state);\n      \/\/--\n    }\n  }\n\n  STACK_END (state);\n}\n\n\/*******************************************************************************\n\n********************************************************************************\/\n\nCastableIterator::CastableIterator(\n  const QueryLoc& aLoc,\n  PlanIter_t& aChild,\n  const xqtref_t& aCastType)\n:\n  UnaryBaseIterator(aLoc, aChild)\n{\n  theCastType = TypeOps::prime_type (*aCastType);\n  theQuantifier = TypeOps::quantifier(*aCastType);\n}\n\nCastableIterator::~CastableIterator(){}\n\nbool CastableIterator::nextImpl(store::Item_t& result, PlanState& planState) const \n{\n  bool lBool;\n  store::Item_t lItem;\n\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n  if (!consumeNext(lItem, theChild.getp(), planState)) {\n    if (theQuantifier == TypeConstants::QUANT_PLUS || theQuantifier == TypeConstants::QUANT_ONE) {\n      lBool = false;\n    } else {\n      lBool = true;\n    }\n  } else {\n    lBool = GenericCast::instance()->isCastable(lItem, theCastType);\n    if (lBool) {\n      if (consumeNext(lItem, theChild.getp(), planState)) {\n        if (theQuantifier == TypeConstants::QUANT_ONE || theQuantifier == TypeConstants::QUANT_QUESTION) {\n          lBool = false;\n        } else {\n          do {\n            lBool = GenericCast::instance()->isCastable(lItem, theCastType);\n          } while (lBool && consumeNext(lItem, theChild.getp(), planState));\n        }\n      }\n    }\n  }\n  STACK_PUSH(GENV_ITEMFACTORY->createBoolean(result, lBool), lState);\n  STACK_END (lState);\n}\n\nPromoteIterator::PromoteIterator(const QueryLoc& aLoc, PlanIter_t& aChild, const xqtref_t& aPromoteType)\n  : UnaryBaseIterator(aLoc, aChild)\n{\n  thePromoteType = TypeOps::prime_type (*aPromoteType);\n  theQuantifier = TypeOps::quantifier(*aPromoteType);\n}\n\nPromoteIterator::~PromoteIterator(){}\n\nbool PromoteIterator::nextImpl(store::Item_t& result, PlanState& planState) const \n{\n  store::Item_t lItem;\n  store::Item_t temp;\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n\n  if (!consumeNext(lItem, theChild.getp(), planState)) \n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS || theQuantifier == TypeConstants::QUANT_ONE) {\n      ZORBA_ERROR_LOC_DESC(  XPTY0004, loc,  \n      \"Empty seq cannot be promoted to QUANT_ONE or QUANT_PLUS type.\");\n    }\n  } \n  else if(theQuantifier == TypeConstants::QUANT_QUESTION \n         || theQuantifier == TypeConstants::QUANT_ONE) \n  {\n    if (! GenericCast::instance()->promote(result, lItem, thePromoteType))\n      ZORBA_ERROR_LOC_DESC(XPTY0004, loc,\n                           \"Type promotion not possible: \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (lItem)) + \" -> \" + TypeOps::toString (*thePromoteType) );\n\n    if(consumeNext(temp, theChild.getp(), planState)) \n    {\n      ZORBA_ERROR_LOC_DESC(  XPTY0004, loc,  \n      \"Seq with 2 or more items cannot be promoted to a QUANT_QUESTION or QUANT_ONE type.\");\n    }\n    STACK_PUSH(true, lState);\n  }\n  else\n  {\n    do \n    {\n      if (! GenericCast::instance()->promote(result, lItem, thePromoteType))\n        ZORBA_ERROR_LOC_DESC( XPTY0004, loc,  \"Type promotion not possible: \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (lItem)) + \" -> \" + TypeOps::toString (*thePromoteType) );\n      else\n        STACK_PUSH(true, lState);\n    } while (consumeNext(lItem, theChild.getp(), planState));\n  }\n  STACK_END (lState);\n}\n\nTreatIterator::TreatIterator(const QueryLoc& aLoc, std::vector& aChildren, const xqtref_t& aTreatType, bool check_prime_, XQUERY_ERROR aErrorCode)\n  : NaryBaseIterator(aLoc, aChildren),\n    check_prime (check_prime_), theErrorCode (aErrorCode)\n{\n  theTreatType = TypeOps::prime_type (*aTreatType);\n  theQuantifier = TypeOps::quantifier(*aTreatType);\n}\n\n\nbool TreatIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n  store::Item_t temp;\n\n  PlanIteratorState* lState;\n  DEFAULT_STACK_INIT(PlanIteratorState, lState, planState);\n\n  if (!CONSUME (result, 0)) \n  {\n    if (theQuantifier == TypeConstants::QUANT_PLUS ||\n        theQuantifier == TypeConstants::QUANT_ONE) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \n      \"Cannot treat empty sequence as + or .\");\n    }\n  }\n  else if(theQuantifier == TypeConstants::QUANT_QUESTION \n         || theQuantifier == TypeConstants::QUANT_ONE) \n  {\n    if (CONSUME (temp, 0)) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc, \n      \"Cannot treat sequence with 2 or more items as ? or .\");\n    }\n\n    if ( check_prime && !TypeOps::is_treatable(result, *theTreatType)) \n    {\n      ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \"Cannot treat \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (result)) + \" as \" + TypeOps::toString (*theTreatType) );\n    }\n    else \n    {\n      STACK_PUSH(true, lState);\n    }\n  }\n  else \n  {\n    do \n    {\n      if ( check_prime && !TypeOps::is_treatable(result, *theTreatType)) \n      {\n        ZORBA_ERROR_LOC_DESC( theErrorCode, loc,  \"Cannot treat \" + TypeOps::toString (*planState.theCompilerCB->m_sctx->get_typemanager()->create_value_type (result)) + \" as \" + TypeOps::toString (*theTreatType) );\n      }\n      else\n      {\n        STACK_PUSH(true, lState);\n      }\n    } while (CONSUME (result, 0));\n  }\n  STACK_END (lState);\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nbool EitherNodesOrAtomicsIterator::nextImpl(\n    store::Item_t& result,\n    PlanState& planState) const \n{\n  EitherNodesOrAtomicsIteratorState *lState;\n  DEFAULT_STACK_INIT(EitherNodesOrAtomicsIteratorState, lState, planState);\n\n  if (CONSUME (result, 0)) \n  {\n    lState->atomics = result->isAtomic ();\n    STACK_PUSH (true, lState);\n    \n    while (CONSUME (result, 0)) \n    {\n      if (lState->atomics != result->isAtomic ())\n        ZORBA_ERROR_LOC (XPTY0018, loc);\n      STACK_PUSH (true, lState);\n    }\n  }\n  \n  STACK_END (lState);\n}\n\n\/*******************************************************************************\n\n********************************************************************************\/\n\n\n} \/* namespace zorba *\/\n\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n\n#include \"world.h\"\n#include \"logging.h\"\n#include \"utils.h\"\n\nusing std::ifstream;\nusing std::ofstream;\nusing std::ios;\n\n\/\/ -----------------  WORLD CLASS STATIC INITIALIZATION  ----------------------------\n\nunsigned char world::car_pixels[360][CAR_HEIGHT][CAR_WIDTH];\nshort world::get_view_dx_tbl[360][MAX_GET_VIEW_XY][MAX_GET_VIEW_XY];\nshort world::get_view_dy_tbl[360][MAX_GET_VIEW_XY][MAX_GET_VIEW_XY];  \/\/ xxx make these tables bigger\n\nvoid world::static_init(void)\n{\n    \/\/\n    \/\/ init car_pixels ...\n    \/\/\n\n    \/\/ create car at 0 degree rotation\n    unsigned char (&car)[CAR_HEIGHT][CAR_WIDTH] = car_pixels[0];\n    memset(car, display::TRANSPARENT, sizeof(car));\n    for (int h = 5; h <= 11; h++) {\n        for (int w = 1; w <= 15; w++) {\n            car[h][w] = display::BLUE;\n        }\n    }\n    car[5][15]  = display::WHITE;   \/\/ head lights\n    car[6][15]  = display::WHITE;\n    car[10][15] = display::WHITE;\n    car[11][15] = display::WHITE;\n    car[5][14]  = display::WHITE;\n    car[6][14]  = display::WHITE;\n    car[10][14] = display::WHITE;\n    car[11][14] = display::WHITE;\n    car[5][1]   = display::RED;     \/\/ tail lights\n    car[6][1]   = display::RED;\n    car[10][1]  = display::RED;\n    car[11][1]  = display::RED;\n    car[5][2]   = display::RED;\n    car[6][2]   = display::RED;\n    car[10][2]  = display::RED;\n    car[11][2]  = display::RED;\n\n    \/\/ create cars at 1 to 359 degrees rotation, \n    \/\/ using the car created above at 0 degrees as a template\n    for (int dir = 1; dir <= 359; dir++) {\n        double sin_dir = sin(dir *  M_PI\/180.0);\n        double cos_dir = cos(dir *  M_PI\/180.0);\n        unsigned char (&carprime)[CAR_HEIGHT][CAR_WIDTH] = car_pixels[dir];\n        int x,y,xprime,yprime;\n\n        #define OVSF 2  \/\/ Over Sample Factor\n        memset(carprime, display::TRANSPARENT, sizeof(car));\n        for (y = 0; y < CAR_HEIGHT*OVSF; y++) {\n            for (x = 0; x < CAR_WIDTH*OVSF; x++) {\n                xprime = (x-CAR_WIDTH*OVSF\/2) * cos_dir - (y-CAR_HEIGHT*OVSF\/2) * sin_dir + CAR_WIDTH*OVSF\/2 + 0.0001;\n                yprime = (x-CAR_WIDTH*OVSF\/2) * sin_dir + (y-CAR_HEIGHT*OVSF\/2) * cos_dir + CAR_HEIGHT*OVSF\/2 + 0.0001;\n                if (xprime < 0 || xprime >= CAR_WIDTH*OVSF || yprime < 0 || yprime >= CAR_HEIGHT*OVSF) {\n                    continue;\n                }\n                carprime[yprime\/OVSF][xprime\/OVSF] = car[y\/OVSF][x\/OVSF];\n            }\n        }\n    }\n\n    \/\/\n    \/\/ init get_view rotation tables\n    \/\/ \n\n    int d1,h1,w1;\n    INFO(\"sizeof of tables \" << \n           (sizeof(get_view_dx_tbl) + sizeof(get_view_dy_tbl)) \/ 0x100000 << \" MB\" << endl);\n    for (d1 = 0; d1 < 360; d1++) {\n        double sindir = sin(d1 * (M_PI\/180.0));\n        double cosdir = cos(d1 * (M_PI\/180.0));\n        for (h1 = 0; h1 < MAX_GET_VIEW_XY; h1++) {\n            for (w1 = -MAX_GET_VIEW_XY\/2; w1 < -MAX_GET_VIEW_XY\/2 + MAX_GET_VIEW_XY; w1++) {\n                get_view_dx_tbl[d1][h1][w1+(MAX_GET_VIEW_XY\/2)] = w1 * cosdir + h1 * sindir;\n                get_view_dy_tbl[d1][h1][w1+(MAX_GET_VIEW_XY\/2)] = w1 * sindir - h1 * cosdir;\n            }\n        }\n    }\n}\n\n\/\/ -----------------  CONSTRUCTOR \/ DESTRUCTOR  -------------------------------------\n\nworld::world(display &display, string fn) : d(display)\n{\n    static_pixels           = new unsigned char [WORLD_HEIGHT] [WORLD_WIDTH];\n    memset(static_pixels, 0, WORLD_HEIGHT*WORLD_WIDTH);\n    pixels                  = new unsigned char [WORLD_HEIGHT] [WORLD_WIDTH];\n    memset(pixels, 0, WORLD_HEIGHT*WORLD_WIDTH);\n    texture                 = NULL;\n    memset(placed_car_list, 0, sizeof(placed_car_list));\n    max_placed_car_list     = 0;\n    filename                = \"\";\n    read_ok_flag            = false;\n    write_ok_flag           = false;\n\n    filename = fn;\n    read();\n    if (!read_ok_flag) {\n        clear();\n    }\n    assert(texture);\n}\n\nworld::~world()\n{\n    d.texture_destroy(texture);\n    delete [] static_pixels;\n    delete [] pixels;\n}\n\n\/\/ -----------------  CAR SUPPORT  --------------------------------------------------\n\nvoid world::place_car_init()\n{\n    for (int i = 0; i < max_placed_car_list; i++) {\n        struct rect &rect = placed_car_list[i];\n\n        \/\/ restores pixels from static_pixels\n        \/\/ XXX check for y or x out of bouncds\n        for (int y = rect.y; y < rect.y+rect.h; y++) {\n            memcpy(&pixels[y][rect.x], &static_pixels[y][rect.x], CAR_WIDTH);\n        }\n\n        \/\/ restores the texture\n        d.texture_set_rect(texture, \n                           rect.x, rect.y, rect.w, rect.h, \n                           &pixels[rect.y][rect.x], \n                           WORLD_WIDTH);\n    }\n    max_placed_car_list = 0;\n}\n\nvoid world::place_car(double x_arg, double y_arg, double dir_arg)\n{\n    \/\/ convert dir to integer, and adjust so 0 degrees is up\n    int dir = (dir_arg + 0.5);\n    dir = ((dir + 270) % 360);\n    if (dir < 0) dir += 360;\n\n    \/\/ convert x,y to integer, and adjust to the top left corner of the car rect\n    int x  = (x_arg + 0.5);\n    int y  = (y_arg + 0.5);\n    x -= CAR_WIDTH \/ 2;\n    y -= CAR_HEIGHT \/ 2;\n\n    \/\/ save the location of the car being placed on placed_car_list\n    struct rect &rect = placed_car_list[max_placed_car_list];\n    rect.x = x;\n    rect.y = y;\n    rect.w = CAR_WIDTH;\n    rect.h = CAR_HEIGHT;\n    max_placed_car_list++;\n\n    \/\/ copy non transparent car pixels to pixels\n    unsigned char * cp = reinterpret_cast(car_pixels[dir]);  \/\/xxx cast\n    for (y = rect.y; y < rect.y+rect.h; y++) {\n        for (x = rect.x; x < rect.x+rect.w; x++) {\n            if (*cp != display::TRANSPARENT) {\n                pixels[y][x] = *cp;\n            }\n            cp++;\n        }\n    }\n\n    \/\/ update the texture\n    d.texture_set_rect(texture, \n                       rect.x, rect.y, rect.w, rect.h, \n                       &pixels[rect.y][rect.x], \n                       WORLD_WIDTH);\n}\n\n\/\/ -----------------  GET VIEW OF THE WORLD  ----------------------------------------\n\nvoid world::get_view(double x_arg, double y_arg, double dir_arg, int w_arg, int h_arg, unsigned char * p_arg)\n{\n    int x = x_arg + 0.5;\n    int y = y_arg + 0.5;\n    int d = dir_arg + 0.5;\n\n    if (d == 360) d = 0;  \/\/ XXX\n\n    assert(d >= 0 && d <= 359);\n\n    \/\/ XXX check size and bounds\n\n    for (int h = h_arg-1; h >= 0; h--) {\n        for (int w = -w_arg\/2; w < -w_arg\/2+w_arg; w++) {\n            int dx = get_view_dx_tbl[d][h][w+(MAX_GET_VIEW_XY\/2)];\n            int dy = get_view_dy_tbl[d][h][w+(MAX_GET_VIEW_XY\/2)];\n            *p_arg++ = pixels[y+dy][x+dx];\n        }\n    }\n}\n\n\/\/ -----------------  DRAW THE WORLD  -----------------------------------------------\n\nvoid world::draw(int pid, double center_x, double center_y, double zoom)\n{\n    int w, h, x, y;\n\n    w = WORLD_WIDTH \/ zoom;\n    h = WORLD_HEIGHT \/ zoom;\n    x = center_x - w\/2;\n    y = center_y - h\/2;\n\n    d.texture_draw(texture, x, y, w, h, pid);\n}\n\n\/\/ -----------------  EDIT STATIC PIXELS SUPPORT  -----------------------------------\n\nvoid world::create_road_slice(double &x, double &y, double dir)\n{\n    double dx, dy, dpx, dpy, tmpx, tmpy;\n\n    dir += 270;\n\n    dy  = .5 * sin(dir * (M_PI\/180.0));\n    dx  = .5 * cos(dir * (M_PI\/180.0));\n    dpy = .5 * sin((dir+90) * (M_PI\/180.0));\n    dpx = .5 * cos((dir+90) * (M_PI\/180.0));\n\n    set_static_pixel(x,y,display::YELLOW);\n\n    tmpx = x;\n    tmpy = y;\n    for (int i = 1; i <= 24; i++) {\n        tmpx += dpx;\n        tmpy += dpy;\n        if (get_static_pixel(tmpx,tmpy) == display::GREEN) {\n            set_static_pixel(tmpx,tmpy,display::BLACK);\n        }\n    }\n\n    tmpx = x;\n    tmpy = y;\n    for (int i = 1; i <= 24; i++) {\n        tmpx -= dpx;\n        tmpy -= dpy;\n        if (get_static_pixel(tmpx,tmpy) == display::GREEN) {\n            set_static_pixel(tmpx,tmpy,display::BLACK);\n        }\n    }\n\n    x += dx;\n    y += dy;\n}\n        \nvoid world::set_static_pixel(double x, double y, unsigned char p) \n{\n    int ix = x + .5;\n    int iy = y + .5;\n\n    if (ix < 0 || ix >= WORLD_WIDTH || iy < 0 || iy >= WORLD_HEIGHT) {\n        return;\n    }\n\n    static_pixels[iy][ix] = p;\n    d.texture_set_pixel(texture, ix, iy, p);\n}\n\nunsigned char world::get_static_pixel(double x, double y)\n{\n    int ix = x + .5;\n    int iy = y + .5;\n\n    if (ix < 0 || ix >= WORLD_WIDTH || iy < 0 || iy >= WORLD_HEIGHT) {\n        ERROR(\"ix \" << ix << \" iy \" << iy << endl);\n        return display::GREEN;\n    }\n\n    return static_pixels[iy][ix];\n}\n\nvoid world::clear()\n{\n    memset(static_pixels, display::GREEN, WORLD_WIDTH*WORLD_HEIGHT); \n    d.texture_destroy(texture);\n    texture = d.texture_create(reinterpret_cast(static_pixels), \n                                             WORLD_WIDTH, WORLD_HEIGHT);\n}\n\nvoid world::read()\n{\n    ifstream ifs;\n\n    read_ok_flag = false;\n    ifs.open(filename, ios::in|ios::ate|ios::binary);\n    if (!ifs.is_open()) {\n        ERROR(filename << \" does not exist\" << endl);\n        return;\n    }\n    if (ifs.tellg() != WORLD_WIDTH*WORLD_HEIGHT) {\n        ERROR(filename << \" has incorrect size\" << endl);\n        return;\n    }\n    ifs.seekg(0,ios::beg);\n    ifs.read(reinterpret_cast(static_pixels), WORLD_WIDTH*WORLD_HEIGHT); \n    if (!ifs.good()) {\n        ERROR(filename << \" read failed\" << endl);\n        return;\n    }\n    read_ok_flag = true;\n\n    memcpy(pixels, static_pixels, WORLD_WIDTH*WORLD_HEIGHT);\n\n    d.texture_destroy(texture);\n    texture = d.texture_create(reinterpret_cast(static_pixels), \n                               WORLD_WIDTH, WORLD_HEIGHT);\n}\n\nvoid world::write()\n{\n    ofstream ofs;\n\n    write_ok_flag = false;\n    ofs.open(filename, ios::out|ios::binary|ios::trunc);\n    if (!ofs.is_open()) {\n        ERROR(filename << \" create failed\" << endl);\n        return;\n    }\n    ofs.write(reinterpret_cast(static_pixels), WORLD_WIDTH*WORLD_HEIGHT);  \n    if (!ofs.good()) {\n        ERROR(filename << \" write failed\" << endl);\n        return;\n    }\n    write_ok_flag = true;\n}\ncheck bounds in world.cpp#include \n#include \n#include \n#include \n\n#include \"world.h\"\n#include \"logging.h\"\n#include \"utils.h\"\n\nusing std::ifstream;\nusing std::ofstream;\nusing std::ios;\n\n\/\/ -----------------  WORLD CLASS STATIC INITIALIZATION  ----------------------------\n\nunsigned char world::car_pixels[360][CAR_HEIGHT][CAR_WIDTH];\nshort world::get_view_dx_tbl[360][MAX_GET_VIEW_XY][MAX_GET_VIEW_XY];\nshort world::get_view_dy_tbl[360][MAX_GET_VIEW_XY][MAX_GET_VIEW_XY];  \/\/ xxx make these tables bigger\n\nvoid world::static_init(void)\n{\n    \/\/\n    \/\/ init car_pixels ...\n    \/\/\n\n    \/\/ create car at 0 degree rotation\n    unsigned char (&car)[CAR_HEIGHT][CAR_WIDTH] = car_pixels[0];\n    memset(car, display::TRANSPARENT, sizeof(car));\n    for (int h = 5; h <= 11; h++) {\n        for (int w = 1; w <= 15; w++) {\n            car[h][w] = display::BLUE;\n        }\n    }\n    car[5][15]  = display::WHITE;   \/\/ head lights\n    car[6][15]  = display::WHITE;\n    car[10][15] = display::WHITE;\n    car[11][15] = display::WHITE;\n    car[5][14]  = display::WHITE;\n    car[6][14]  = display::WHITE;\n    car[10][14] = display::WHITE;\n    car[11][14] = display::WHITE;\n    car[5][1]   = display::RED;     \/\/ tail lights\n    car[6][1]   = display::RED;\n    car[10][1]  = display::RED;\n    car[11][1]  = display::RED;\n    car[5][2]   = display::RED;\n    car[6][2]   = display::RED;\n    car[10][2]  = display::RED;\n    car[11][2]  = display::RED;\n\n    \/\/ create cars at 1 to 359 degrees rotation, \n    \/\/ using the car created above at 0 degrees as a template\n    for (int dir = 1; dir <= 359; dir++) {\n        double sin_dir = sin(dir *  M_PI\/180.0);\n        double cos_dir = cos(dir *  M_PI\/180.0);\n        unsigned char (&carprime)[CAR_HEIGHT][CAR_WIDTH] = car_pixels[dir];\n        int x,y,xprime,yprime;\n\n        #define OVSF 3  \/\/ Over Sample Factor\n        memset(carprime, display::TRANSPARENT, sizeof(car));\n        for (y = 0; y < CAR_HEIGHT*OVSF; y++) {\n            for (x = 0; x < CAR_WIDTH*OVSF; x++) {\n                xprime = (x-CAR_WIDTH*OVSF\/2) * cos_dir - (y-CAR_HEIGHT*OVSF\/2) * sin_dir + CAR_WIDTH*OVSF\/2 + 0.001;\n                yprime = (x-CAR_WIDTH*OVSF\/2) * sin_dir + (y-CAR_HEIGHT*OVSF\/2) * cos_dir + CAR_HEIGHT*OVSF\/2 + 0.001;\n                if (xprime < 0 || xprime >= CAR_WIDTH*OVSF || yprime < 0 || yprime >= CAR_HEIGHT*OVSF) {\n                    continue;\n                }\n                carprime[yprime\/OVSF][xprime\/OVSF] = car[y\/OVSF][x\/OVSF];\n            }\n        }\n    }\n\n    \/\/\n    \/\/ init get_view rotation tables\n    \/\/ \n\n    int d1,h1,w1;\n    INFO(\"sizeof of tables \" << \n           (sizeof(get_view_dx_tbl) + sizeof(get_view_dy_tbl)) \/ 0x100000 << \" MB\" << endl);\n    for (d1 = 0; d1 < 360; d1++) {\n        double sindir = sin(d1 * (M_PI\/180.0));\n        double cosdir = cos(d1 * (M_PI\/180.0));\n        for (h1 = 0; h1 < MAX_GET_VIEW_XY; h1++) {\n            for (w1 = -MAX_GET_VIEW_XY\/2; w1 < -MAX_GET_VIEW_XY\/2 + MAX_GET_VIEW_XY; w1++) {\n                get_view_dx_tbl[d1][h1][w1+(MAX_GET_VIEW_XY\/2)] = w1 * cosdir + h1 * sindir;\n                get_view_dy_tbl[d1][h1][w1+(MAX_GET_VIEW_XY\/2)] = w1 * sindir - h1 * cosdir;\n            }\n        }\n    }\n}\n\n\/\/ -----------------  CONSTRUCTOR \/ DESTRUCTOR  -------------------------------------\n\nworld::world(display &display, string fn) : d(display)\n{\n    static_pixels           = new unsigned char [WORLD_HEIGHT] [WORLD_WIDTH];\n    memset(static_pixels, 0, WORLD_HEIGHT*WORLD_WIDTH);\n    pixels                  = new unsigned char [WORLD_HEIGHT] [WORLD_WIDTH];\n    memset(pixels, 0, WORLD_HEIGHT*WORLD_WIDTH);\n    texture                 = NULL;\n    memset(placed_car_list, 0, sizeof(placed_car_list));\n    max_placed_car_list     = 0;\n    filename                = \"\";\n    read_ok_flag            = false;\n    write_ok_flag           = false;\n\n    filename = fn;\n    read();\n    if (!read_ok_flag) {\n        clear();\n    }\n    assert(texture);\n}\n\nworld::~world()\n{\n    d.texture_destroy(texture);\n    delete [] static_pixels;\n    delete [] pixels;\n}\n\n\/\/ -----------------  CAR SUPPORT  --------------------------------------------------\n\nvoid world::place_car_init()\n{\n    for (int i = 0; i < max_placed_car_list; i++) {\n        struct rect &rect = placed_car_list[i];\n\n        \/\/ restores pixels from static_pixels\n        for (int y = rect.y; y < rect.y+rect.h; y++) {\n            memcpy(&pixels[y][rect.x], &static_pixels[y][rect.x], CAR_WIDTH);\n        }\n\n        \/\/ restores the texture\n        d.texture_set_rect(texture, \n                           rect.x, rect.y, rect.w, rect.h, \n                           &pixels[rect.y][rect.x], \n                           WORLD_WIDTH);\n    }\n    max_placed_car_list = 0;\n}\n\nvoid world::place_car(double x_arg, double y_arg, double dir_arg)\n{\n    \/\/ convert dir to integer, and adjust so 0 degrees is up\n    int dir = (dir_arg + 0.5);\n    dir = ((dir + 270) % 360);\n    if (dir < 0) dir += 360;\n\n    \/\/ convert x,y to integer, and adjust to the top left corner of the car rect\n    int x  = (x_arg + 0.5);\n    int y  = (y_arg + 0.5);\n    x -= CAR_WIDTH \/ 2;\n    y -= CAR_HEIGHT \/ 2;\n\n    \/\/ if car is off an edge of the world then skip\n    if (x < 0 || x+CAR_WIDTH >= WORLD_WIDTH ||\n        y < 0 || y+CAR_HEIGHT >= WORLD_HEIGHT) \n    {\n        return;\n    }\n\n    \/\/ save the location of the car being placed on placed_car_list\n    struct rect &rect = placed_car_list[max_placed_car_list];\n    rect.x = x;\n    rect.y = y;\n    rect.w = CAR_WIDTH;\n    rect.h = CAR_HEIGHT;\n    max_placed_car_list++;\n\n    \/\/ copy non transparent car pixels to pixels\n    unsigned char * cp = reinterpret_cast(car_pixels[dir]);  \/\/xxx cast\n    for (y = rect.y; y < rect.y+rect.h; y++) {\n        for (x = rect.x; x < rect.x+rect.w; x++) {\n            if (*cp != display::TRANSPARENT) {\n                pixels[y][x] = *cp;\n            }\n            cp++;\n        }\n    }\n\n    \/\/ update the texture\n    d.texture_set_rect(texture, \n                       rect.x, rect.y, rect.w, rect.h, \n                       &pixels[rect.y][rect.x], \n                       WORLD_WIDTH);\n}\n\n\/\/ -----------------  GET VIEW OF THE WORLD  ----------------------------------------\n\nvoid world::get_view(double x_arg, double y_arg, double dir_arg, int w_arg, int h_arg, unsigned char * p_arg)\n{\n    int x = x_arg + 0.5;\n    int y = y_arg + 0.5;\n    int d = dir_arg + 0.5;\n\n    if (d == 360) d = 0;  \/\/ xxx\n\n    assert(d >= 0 && d <= 359);\n\n    for (int h = h_arg-1; h >= 0; h--) {\n        for (int w = -w_arg\/2; w < -w_arg\/2+w_arg; w++) {\n            int dx = get_view_dx_tbl[d][h][w+(MAX_GET_VIEW_XY\/2)];\n            int dy = get_view_dy_tbl[d][h][w+(MAX_GET_VIEW_XY\/2)];\n            if (y+dy >= 0 && y+dy < WORLD_HEIGHT && x+dx >= 0 && x+dx < WORLD_WIDTH) {\n                *p_arg++ = pixels[y+dy][x+dx];\n            } else {\n                *p_arg++ = display::PURPLE;\n            }\n        }\n    }\n}\n\n\/\/ -----------------  DRAW THE WORLD  -----------------------------------------------\n\nvoid world::draw(int pid, double center_x, double center_y, double zoom)\n{\n    int w, h, x, y;\n\n    w = WORLD_WIDTH \/ zoom;\n    h = WORLD_HEIGHT \/ zoom;\n    x = center_x - w\/2;\n    y = center_y - h\/2;\n\n    d.texture_draw(texture, x, y, w, h, pid);\n}\n\n\/\/ -----------------  EDIT STATIC PIXELS SUPPORT  -----------------------------------\n\nvoid world::create_road_slice(double &x, double &y, double dir)\n{\n    double dpx, dpy, tmpx, tmpy;\n    const double distance = 0.5;\n\n    dir += 270;\n\n    dpy = distance * sin((dir+90) * (M_PI\/180.0));\n    dpx = distance * cos((dir+90) * (M_PI\/180.0));\n\n    set_static_pixel(x,y,display::YELLOW);\n\n    tmpx = x;\n    tmpy = y;\n    for (int i = 1; i <= 24; i++) {\n        tmpx += dpx;\n        tmpy += dpy;\n        if (get_static_pixel(tmpx,tmpy) == display::GREEN) {\n            set_static_pixel(tmpx,tmpy,display::BLACK);\n        }\n    }\n\n    tmpx = x;\n    tmpy = y;\n    for (int i = 1; i <= 24; i++) {\n        tmpx -= dpx;\n        tmpy -= dpy;\n        if (get_static_pixel(tmpx,tmpy) == display::GREEN) {\n            set_static_pixel(tmpx,tmpy,display::BLACK);\n        }\n    }\n}\n        \nvoid world::set_static_pixel(double x, double y, unsigned char p) \n{\n    int ix = x + .5;\n    int iy = y + .5;\n\n    if (ix < 0 || ix >= WORLD_WIDTH || iy < 0 || iy >= WORLD_HEIGHT) {\n        return;\n    }\n\n    static_pixels[iy][ix] = p;\n    pixels[iy][ix] = p;\n    d.texture_set_pixel(texture, ix, iy, p);\n}\n\nunsigned char world::get_static_pixel(double x, double y)\n{\n    int ix = x + .5;\n    int iy = y + .5;\n\n    if (ix < 0 || ix >= WORLD_WIDTH || iy < 0 || iy >= WORLD_HEIGHT) {\n        ERROR(\"ix \" << ix << \" iy \" << iy << endl);\n        return display::GREEN;\n    }\n\n    return static_pixels[iy][ix];\n}\n\nvoid world::clear()\n{\n    memset(static_pixels, display::GREEN, WORLD_WIDTH*WORLD_HEIGHT); \n    memcpy(pixels, static_pixels, WORLD_WIDTH*WORLD_HEIGHT);\n    d.texture_destroy(texture);\n    texture = d.texture_create(reinterpret_cast(static_pixels), \n                                             WORLD_WIDTH, WORLD_HEIGHT);\n}\n\nvoid world::read()\n{\n    ifstream ifs;\n\n    read_ok_flag = false;\n    ifs.open(filename, ios::in|ios::ate|ios::binary);\n    if (!ifs.is_open()) {\n        ERROR(filename << \" does not exist\" << endl);\n        return;\n    }\n    if (ifs.tellg() != WORLD_WIDTH*WORLD_HEIGHT) {\n        ERROR(filename << \" has incorrect size\" << endl);\n        return;\n    }\n    ifs.seekg(0,ios::beg);\n    ifs.read(reinterpret_cast(static_pixels), WORLD_WIDTH*WORLD_HEIGHT); \n    if (!ifs.good()) {\n        ERROR(filename << \" read failed\" << endl);\n        return;\n    }\n    read_ok_flag = true;\n\n    memcpy(pixels, static_pixels, WORLD_WIDTH*WORLD_HEIGHT);\n\n    d.texture_destroy(texture);\n    texture = d.texture_create(reinterpret_cast(static_pixels), \n                               WORLD_WIDTH, WORLD_HEIGHT);\n}\n\nvoid world::write()\n{\n    ofstream ofs;\n\n    write_ok_flag = false;\n    ofs.open(filename, ios::out|ios::binary|ios::trunc);\n    if (!ofs.is_open()) {\n        ERROR(filename << \" create failed\" << endl);\n        return;\n    }\n    ofs.write(reinterpret_cast(static_pixels), WORLD_WIDTH*WORLD_HEIGHT);  \n    if (!ofs.good()) {\n        ERROR(filename << \" write failed\" << endl);\n        return;\n    }\n    write_ok_flag = true;\n}\n<|endoftext|>"}
{"text":"#pragma once\n\n#include  \/\/ find\n#include \n#include     \/\/ unique_ptr\n#include   \/\/ typeid\n\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/hom\/definition_fwd.hh\"\n#include \"sdd\/util\/packed.hh\"\n#include \"sdd\/order\/carrier.hh\"\n#include \"sdd\/order\/order.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct function_base\n{\n  \/\/\/ @brief The type of a set of values.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief Destructor.\n  virtual\n  ~function_base()\n  {}\n\n  \/\/\/ @brief Tell if the user's function is a selector.\n  virtual\n  bool\n  selector() const noexcept = 0;\n\n  \/\/\/ @brief Tell if the user's function is a shifter.\n  virtual\n  bool\n  shifter() const noexcept = 0;\n\n  \/\/\/ @brief Apply the user function.\n  virtual\n  values_type\n  operator()(const values_type&) const = 0;\n\n  \/\/\/ @brief Compare values_base.\n  virtual\n  bool\n  operator==(const function_base&) const noexcept = 0;\n\n  \/\/\/ @brief Get the user's function hash value.\n  virtual\n  std::size_t\n  hash() const noexcept = 0;\n\n  \/\/\/ @brief Get the user's function textual representation.\n  virtual\n  void\n  print(std::ostream&) const = 0;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct function_derived\n  : public function_base\n{\n  \/\/\/ @brief The user's values function.\n  const User fun;\n\n  \/\/\/ @brief The type of a set of values.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief Constructor.\n  function_derived(const User& f)\n    : fun(f)\n  {}\n\n  \/\/\/ @brief Tell if the user's function is a selector.\n  bool\n  selector()\n  const noexcept override\n  {\n    return selector_impl(fun, 0);\n  }\n\n  \/\/\/ @brief Tell if the user's function is a shifter.\n  bool\n  shifter()\n  const noexcept override\n  {\n    return shifter_impl(fun, 0);\n  }\n\n  \/\/\/ @brief Apply the user function.\n  values_type\n  operator()(const values_type& val)\n  const override\n  {\n    return fun(val);\n  }\n\n  \/\/\/ @brief Compare values_derived.\n  bool\n  operator==(const function_base& other)\n  const noexcept override\n  {\n    return typeid(*this) == typeid(other)\n         ? fun == reinterpret_cast(other).fun\n         : false;\n  }\n\n  \/\/\/ @brief Get the user's function hash value.\n  std::size_t\n  hash()\n  const noexcept override\n  {\n    return std::hash()(fun);\n  }\n\n  \/\/\/ @brief Get the user's values function textual representation.\n  void\n  print(std::ostream& os)\n  const override\n  {\n    print_impl(os, fun, 0);\n  }\n\nprivate:\n\n  \/\/\/ @brief Called when the user's function has selector().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  selector_impl(const T& x, int)\n  noexcept\n  -> decltype(x.selector())\n  {\n    return x.selector();\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have selector().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  selector_impl(const T&, long)\n  noexcept\n  -> decltype(false)\n  {\n    return false;\n  }\n\n  \/\/\/ @brief Called when the user's function has shifter().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  shifter_impl(const T& x, int)\n  noexcept\n  -> decltype(x.shifter())\n  {\n    return x.shifter();\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have shifter().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  shifter_impl(const T&, long)\n  noexcept\n  -> decltype(false)\n  {\n    return false;\n  }\n\n  \/\/\/ @brief Called when the user's function has operator<<(ostream&).\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  print_impl(std::ostream& os, const T& x, int)\n  -> decltype(operator<<(os, x))\n  {\n    return os << x;\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have operator<<(ostream&).\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  print_impl(std::ostream& os, const T& x, long)\n  -> decltype(void())\n  {\n    os << \"function(\" << &x << \")\";\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct LIBSDD_ATTRIBUTE_PACKED _function\n{\n  \/\/\/ @brief The type of a valuation on a flat node.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief The identifier on which the user function is applied.\n  const order_position_type target;\n\n  \/\/\/ @brief Ownership of the user's values function.\n  const std::unique_ptr> fun_ptr;\n\n  \/\/\/ @brief Dispatch the Values homomorphism evaluation.\n  struct helper\n  {\n    \/\/\/ @brief |0| case, should never happen.\n    SDD\n    operator()(const zero_terminal&, const function_base&, context&, const order&)\n    const noexcept\n    {\n      assert(false);\n      __builtin_unreachable();\n    }\n\n    \/\/\/ @brief |1| case.\n    SDD\n    operator()(const one_terminal&, const function_base&, context&, const order&)\n    const\n    {\n      return one();\n    }\n\n    \/\/\/ @brief A function can't be applied on an hierarchical node.\n    SDD\n    operator()(const hierarchical_node&, const function_base&, context&, const order&)\n    const\n    {\n      assert(false && \"Apply function on an hierarchical node\");\n      __builtin_unreachable();\n    }\n\n    \/\/\/ @brief Evaluation on a flat node.\n    SDD\n    operator()( const flat_node& node, const function_base& fun, context& cxt\n              , const order& o)\n    const\n    {\n      if (fun.selector() or fun.shifter())\n      {\n        dd::alpha_builder alpha_builder(cxt.sdd_context());\n        alpha_builder.reserve(node.size());\n        for (const auto& arc : node)\n        {\n          values_type val = fun(arc.valuation());\n          if (not val.empty())\n          {\n            alpha_builder.add(std::move(val), arc.successor());\n          }\n        }\n        return {o.variable(), std::move(alpha_builder)};\n      }\n      else\n      {\n        dd::sum_builder> sum_operands(cxt.sdd_context());\n        sum_operands.reserve(node.size());\n        for (const auto& arc : node)\n        {\n          sum_operands.add(SDD(o.variable(), fun(arc.valuation()), arc.successor()));\n        }\n        return dd::sum(cxt.sdd_context(), std::move(sum_operands));\n      }\n    }\n  };\n\n  \/\/\/ @brief Constructor.\n  _function(order_position_type pos, std::unique_ptr> f)\n    : target(pos), fun_ptr(std::move(f))\n  {}\n\n  \/\/\/ @brief Skip variable predicate.\n  bool\n  skip(const order& o)\n  const noexcept\n  {\n    return target != o.position();\n  }\n\n  \/\/\/ @brief Selector predicate\n  bool\n  selector()\n  const noexcept\n  {\n    return fun_ptr->selector();\n  }\n\n  \/\/\/ @brief Evaluation.\n  SDD\n  operator()(context& cxt, const order& o, const SDD& x)\n  const\n  {\n    return visit(helper(), x, *fun_ptr, cxt, o);\n  }\n\n  friend\n  bool\n  operator==(const _function& lhs, const _function& rhs)\n  noexcept\n  {\n    return lhs.target == rhs.target and *lhs.fun_ptr == *rhs.fun_ptr;\n  }\n\n  friend\n  std::ostream&\n  operator<<(std::ostream& os, const _function& x)\n  {\n    os << \"fun(\" << x.target << \", \";\n    x.fun_ptr->print(os);\n    return os << \")\";\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace hom\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Create the Function homomorphism.\n\/\/\/ @related homomorphism\ntemplate \nhomomorphism\nfunction(order_position_type pos, const User& u)\n{\n  return homomorphism::create( mem::construct>()\n                                , pos, std::make_unique>(u));\n}\n\n\/\/\/ @brief Create the Function homomorphism.\n\/\/\/ @param i The target identifier, must belong to o.\n\/\/\/ @related homomorphism\n\/\/\/\n\/\/\/ If the target is in a nested hierarchy, the succession of Local to access it is automatically\n\/\/\/ created.\ntemplate \nhomomorphism\nfunction(const order& o, const typename C::Identifier& id, const User& u)\n{\n  \/\/\/ @todo Check that id is a flat identifier.\n  return carrier(o, id, function(o.node(id).position(), u));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::_function.\ntemplate \nstruct hash>\n{\n  std::size_t\n  operator()(const sdd::hom::_function& x)\n  const noexcept\n  {\n    using namespace sdd::hash;\n    return seed(x.fun_ptr->hash()) (val(x.target));\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\nMaximize sharing of function#pragma once\n\n#include  \/\/ find\n#include \n#include     \/\/ unique_ptr\n#include   \/\/ typeid\n\n#include \"sdd\/dd\/definition.hh\"\n#include \"sdd\/hom\/context_fwd.hh\"\n#include \"sdd\/hom\/definition_fwd.hh\"\n#include \"sdd\/util\/packed.hh\"\n#include \"sdd\/order\/carrier.hh\"\n#include \"sdd\/order\/order.hh\"\n#include \"sdd\/order\/order_node.hh\"\n\nnamespace sdd { namespace hom {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct function_base\n{\n  \/\/\/ @brief The type of a set of values.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief Destructor.\n  virtual\n  ~function_base()\n  {}\n\n  \/\/\/ @brief Tell if the user's function is a selector.\n  virtual\n  bool\n  selector() const noexcept = 0;\n\n  \/\/\/ @brief Tell if the user's function is a shifter.\n  virtual\n  bool\n  shifter() const noexcept = 0;\n\n  \/\/\/ @brief Apply the user function.\n  virtual\n  values_type\n  operator()(const values_type&) const = 0;\n\n  \/\/\/ @brief Compare values_base.\n  virtual\n  bool\n  operator==(const function_base&) const noexcept = 0;\n\n  \/\/\/ @brief Get the user's function hash value.\n  virtual\n  std::size_t\n  hash() const noexcept = 0;\n\n  \/\/\/ @brief Get the user's function textual representation.\n  virtual\n  void\n  print(std::ostream&) const = 0;\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct function_derived\n  : public function_base\n{\n  \/\/\/ @brief The user's values function.\n  const User fun;\n\n  \/\/\/ @brief The type of a set of values.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief Constructor.\n  function_derived(const User& f)\n    : fun(f)\n  {}\n\n  \/\/\/ @brief Tell if the user's function is a selector.\n  bool\n  selector()\n  const noexcept override\n  {\n    return selector_impl(fun, 0);\n  }\n\n  \/\/\/ @brief Tell if the user's function is a shifter.\n  bool\n  shifter()\n  const noexcept override\n  {\n    return shifter_impl(fun, 0);\n  }\n\n  \/\/\/ @brief Apply the user function.\n  values_type\n  operator()(const values_type& val)\n  const override\n  {\n    return fun(val);\n  }\n\n  \/\/\/ @brief Compare values_derived.\n  bool\n  operator==(const function_base& other)\n  const noexcept override\n  {\n    return typeid(*this) == typeid(other)\n         ? fun == reinterpret_cast(other).fun\n         : false;\n  }\n\n  \/\/\/ @brief Get the user's function hash value.\n  std::size_t\n  hash()\n  const noexcept override\n  {\n    return std::hash()(fun);\n  }\n\n  \/\/\/ @brief Get the user's values function textual representation.\n  void\n  print(std::ostream& os)\n  const override\n  {\n    print_impl(os, fun, 0);\n  }\n\nprivate:\n\n  \/\/\/ @brief Called when the user's function has selector().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  selector_impl(const T& x, int)\n  noexcept\n  -> decltype(x.selector())\n  {\n    return x.selector();\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have selector().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  selector_impl(const T&, long)\n  noexcept\n  -> decltype(false)\n  {\n    return false;\n  }\n\n  \/\/\/ @brief Called when the user's function has shifter().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  shifter_impl(const T& x, int)\n  noexcept\n  -> decltype(x.shifter())\n  {\n    return x.shifter();\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have shifter().\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  shifter_impl(const T&, long)\n  noexcept\n  -> decltype(false)\n  {\n    return false;\n  }\n\n  \/\/\/ @brief Called when the user's function has operator<<(ostream&).\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  print_impl(std::ostream& os, const T& x, int)\n  -> decltype(operator<<(os, x))\n  {\n    return os << x;\n  }\n\n  \/\/\/ @brief Called when the user's function doesn't have operator<<(ostream&).\n  \/\/\/\n  \/\/\/ Compile-time dispatch.\n  template \n  static auto\n  print_impl(std::ostream& os, const T& x, long)\n  -> decltype(void())\n  {\n    os << \"function(\" << &x << \")\";\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\ntemplate \nstruct LIBSDD_ATTRIBUTE_PACKED _function\n{\n  \/\/\/ @brief The type of a valuation on a flat node.\n  using values_type = typename C::Values;\n\n  \/\/\/ @brief The identifier on which the user function is applied.\n  const order_node& o_node;\n\n  \/\/\/ @brief Ownership of the user's values function.\n  const std::unique_ptr> fun_ptr;\n\n  \/\/\/ @brief Dispatch the Values homomorphism evaluation.\n  struct helper\n  {\n    \/\/\/ @brief |0| case, should never happen.\n    SDD\n    operator()(const zero_terminal&, const function_base&, context&, const order&)\n    const noexcept\n    {\n      assert(false);\n      __builtin_unreachable();\n    }\n\n    \/\/\/ @brief |1| case.\n    SDD\n    operator()(const one_terminal&, const function_base&, context&, const order&)\n    const\n    {\n      return one();\n    }\n\n    \/\/\/ @brief A function can't be applied on an hierarchical node.\n    SDD\n    operator()(const hierarchical_node&, const function_base&, context&, const order&)\n    const\n    {\n      assert(false && \"Apply function on an hierarchical node\");\n      __builtin_unreachable();\n    }\n\n    \/\/\/ @brief Evaluation on a flat node.\n    SDD\n    operator()( const flat_node& node, const function_base& fun, context& cxt\n              , const order& o)\n    const\n    {\n      if (fun.selector() or fun.shifter())\n      {\n        dd::alpha_builder alpha_builder(cxt.sdd_context());\n        alpha_builder.reserve(node.size());\n        for (const auto& arc : node)\n        {\n          values_type val = fun(arc.valuation());\n          if (not val.empty())\n          {\n            alpha_builder.add(std::move(val), arc.successor());\n          }\n        }\n        return {o.variable(), std::move(alpha_builder)};\n      }\n      else\n      {\n        dd::sum_builder> sum_operands(cxt.sdd_context());\n        sum_operands.reserve(node.size());\n        for (const auto& arc : node)\n        {\n          sum_operands.add(SDD(o.variable(), fun(arc.valuation()), arc.successor()));\n        }\n        return dd::sum(cxt.sdd_context(), std::move(sum_operands));\n      }\n    }\n  };\n\n  \/\/\/ @brief Constructor.\n  _function(const order_node& n, std::unique_ptr> f)\n    : o_node(n), fun_ptr(std::move(f))\n  {}\n\n  \/\/\/ @brief Skip variable predicate.\n  bool\n  skip(const order& o)\n  const noexcept\n  {\n    return o_node.variable() != o.variable();\n  }\n\n  \/\/\/ @brief Selector predicate\n  bool\n  selector()\n  const noexcept\n  {\n    return fun_ptr->selector();\n  }\n\n  \/\/\/ @brief Evaluation.\n  SDD\n  operator()(context& cxt, const order& o, const SDD& x)\n  const\n  {\n    return visit(helper(), x, *fun_ptr, cxt, o);\n  }\n\n  friend\n  bool\n  operator==(const _function& lhs, const _function& rhs)\n  noexcept\n  {\n    return lhs.o_node.variable() == rhs.o_node.variable() and *lhs.fun_ptr == *rhs.fun_ptr;\n  }\n\n  friend\n  std::ostream&\n  operator<<(std::ostream& os, const _function& x)\n  {\n    os << \"fun(\" << x.o_node.identifier() << \", \";\n    x.fun_ptr->print(os);\n    return os << \")\";\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace hom\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Create the Function homomorphism.\n\/\/\/ @related homomorphism\ntemplate \nhomomorphism\nfunction(const order_node& n, const User& u)\n{\n  return homomorphism::create( mem::construct>()\n                                , n, std::make_unique>(u));\n}\n\n\/\/\/ @brief Create the Function homomorphism.\n\/\/\/ @param i The target identifier, must belong to o.\n\/\/\/ @related homomorphism\n\/\/\/\n\/\/\/ If the target is in a nested hierarchy, the succession of Local to access it is automatically\n\/\/\/ created.\ntemplate \nhomomorphism\nfunction(const order& o, const typename C::Identifier& id, const User& u)\n{\n  \/\/\/ @todo Check that id is a flat identifier.\n  return carrier(o, id, function(o.node(id), u));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace sdd\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::hom::_function.\ntemplate \nstruct hash>\n{\n  std::size_t\n  operator()(const sdd::hom::_function& x)\n  const noexcept\n  {\n    using namespace sdd::hash;\n    return seed(x.fun_ptr->hash()) (val(x.o_node.variable()));\n  }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n<|endoftext|>"}
{"text":"\/* \n * File:   ScanCache.h\n * \n * Copyright 2013 Heinrich Schuchardt \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/**\n * @file ScanCache.h\n * @brief Cache for virus scanning results.\n *\/\n#include \n#include \n#include \n#include \"Messaging.h\"\n#include \"ScanCache.h\"\n\nScanCache::ScanCache(Environment *env) {\n    e = env;\n    s = new std::set();\n    hits = 0;\n    misses = 0;\n    root.left = &root;\n    root.right = &root;\n    pthread_mutex_init(&mutex, NULL);\n}\n\n\/**\n * @brief Adds scan result to cache.\n * @param stat File status as returned by fstat()\n * @param response Response to be used for fanotify (FAN_ALLOW, FAN_DENY)\n *\/\nvoid ScanCache::add(const struct stat *stat, const unsigned int response) {\n    std::set::iterator it;\n    std::pair < std::set::iterator, bool> pair;\n\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n    scr->mtime = stat->st_mtime;\n    scr->response = response;\n    gmtime(&(scr->age));\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    if (it != s->end()) {\n        \/\/ Old matching entry found. Remove from linked list and delete.\n        (*it)->left->right = (*it)->right;\n        (*it)->right->left = (*it)->left;\n        delete *it;\n        s->erase(it);\n    } else while (s->size() >= e->getCacheMaxSize()) {\n            \/\/ Cache size too big. Get last element.\n            it = s->find(root.left);\n            if (it != s->end()) {\n                \/\/ Remove from linked list and delete.\n                (*it)->left->right = (*it)->right;\n                (*it)->right->left = (*it)->left;\n                delete *it;\n                s->erase(it);\n            } else {\n                break;\n            }\n        }\n    pair = s->insert(scr);\n    if (pair.second) {\n        \/\/ Successful insertion. Introduce leftmost in linked list.\n        root.right->left = scr;\n        scr->right = root.right;\n        scr->left = &root;\n        root.right = scr;\n    } else {\n        \/\/ element already existed\n        delete scr;\n    }\n    pthread_mutex_unlock(&mutex);\n}\n\nvoid ScanCache::clear() {\n    pthread_mutex_lock(&mutex);\n    std::set::iterator pos;\n    for (pos = s->begin(); pos != s->end(); pos++) {\n        delete *pos;\n    }\n    s->clear();\n    Messaging::message(Messaging::DEBUG, \"Cache cleared.\");\n    pthread_mutex_unlock(&mutex);\n}\n\n\/**\n * @brief Adds scan result to cache.\n * @param stat file status as returned by fstat()\n * @return response to be used for fanotify (FAN_ALLOW, FAN_DENY) or CACHE_MISS\n *\/\nint ScanCache::get(const struct stat *stat) {\n    int ret;\n    std::set::iterator it;\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    delete scr;\n    if (it == s->end()) {\n        ret = CACHE_MISS;\n        misses++;\n    } else {\n        scr = *it;\n        \/\/ Check modification time.\n        if (scr->mtime == stat->st_mtime) {\n            \/\/ Element is valid. Remove it from linked list.\n            scr->left->right = scr->right;\n            scr->right->left = scr->left;\n            \/\/ Insert it leftmost.\n            root.right->left = scr;\n            scr->right = root.right;\n            scr->left = &root;\n            root.right = scr;\n            ret = scr->response;\n            hits++;\n        } else {\n            \/\/ Remove outdated element from linked list and delete it.\n            (*it)->left->right = (*it)->right;\n            (*it)->right->left = (*it)->left;\n            delete *it;\n            s->erase(it);\n            ret = CACHE_MISS;\n            misses++;\n        }\n    }\n    pthread_mutex_unlock(&mutex);\n    return ret;\n}\n\n\/**\n * @brief Remove scan result from cache.\n * @param stat file status as returned by fstat()\n *\/\nvoid ScanCache::remove(const struct stat *stat) {\n    std::set::iterator it;\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    if (it != s->end()) {\n        \/\/ Remove from linked list and delete.\n        (*it)->left->right = (*it)->right;\n        (*it)->right->left = (*it)->left;\n        delete *it;\n        s->erase(it);\n    }\n    pthread_mutex_unlock(&mutex);\n    delete scr;\n}\n\nScanCache::~ScanCache() {\n    std::stringstream msg;\n    msg << \"Cache size \" << s->size() <<\n            \", cache hits \" << hits << \", cache misses \" << misses << \".\";\n    clear();\n    pthread_mutex_destroy(&mutex);\n    Messaging::message(Messaging::INFORMATION, msg.str());\n}\nScanCache: Observe cache size 0.\/* \n * File:   ScanCache.h\n * \n * Copyright 2013 Heinrich Schuchardt \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/**\n * @file ScanCache.h\n * @brief Cache for virus scanning results.\n *\/\n#include \n#include \n#include \n#include \"Messaging.h\"\n#include \"ScanCache.h\"\n\nScanCache::ScanCache(Environment *env) {\n    e = env;\n    s = new std::set();\n    hits = 0;\n    misses = 0;\n    root.left = &root;\n    root.right = &root;\n    pthread_mutex_init(&mutex, NULL);\n}\n\n\/**\n * @brief Adds scan result to cache.\n * @param stat File status as returned by fstat()\n * @param response Response to be used for fanotify (FAN_ALLOW, FAN_DENY)\n *\/\nvoid ScanCache::add(const struct stat *stat, const unsigned int response) {\n    std::set::iterator it;\n    std::pair < std::set::iterator, bool> pair;\n    unsigned int cacheMaxSize = e->getCacheMaxSize();\n    \n    if (0 == cacheMaxSize) {\n        return;\n    }\n\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n    scr->mtime = stat->st_mtime;\n    scr->response = response;\n    gmtime(&(scr->age));\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    if (it != s->end()) {\n        \/\/ Old matching entry found. Remove from linked list and delete.\n        (*it)->left->right = (*it)->right;\n        (*it)->right->left = (*it)->left;\n        delete *it;\n        s->erase(it);\n    } else while (s->size() >= cacheMaxSize) {\n            \/\/ Cache size too big. Get last element.\n            it = s->find(root.left);\n            if (it != s->end()) {\n                \/\/ Remove from linked list and delete.\n                (*it)->left->right = (*it)->right;\n                (*it)->right->left = (*it)->left;\n                delete *it;\n                s->erase(it);\n            } else {\n                break;\n            }\n        }\n    pair = s->insert(scr);\n    if (pair.second) {\n        \/\/ Successful insertion. Introduce leftmost in linked list.\n        root.right->left = scr;\n        scr->right = root.right;\n        scr->left = &root;\n        root.right = scr;\n    } else {\n        \/\/ element already existed\n        delete scr;\n    }\n    pthread_mutex_unlock(&mutex);\n}\n\nvoid ScanCache::clear() {\n    pthread_mutex_lock(&mutex);\n    std::set::iterator pos;\n    for (pos = s->begin(); pos != s->end(); pos++) {\n        delete *pos;\n    }\n    s->clear();\n    Messaging::message(Messaging::DEBUG, \"Cache cleared.\");\n    pthread_mutex_unlock(&mutex);\n}\n\n\/**\n * @brief Adds scan result to cache.\n * @param stat file status as returned by fstat()\n * @return response to be used for fanotify (FAN_ALLOW, FAN_DENY) or CACHE_MISS\n *\/\nint ScanCache::get(const struct stat *stat) {\n    int ret;\n    std::set::iterator it;\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    delete scr;\n    if (it == s->end()) {\n        ret = CACHE_MISS;\n        misses++;\n    } else {\n        scr = *it;\n        \/\/ Check modification time.\n        if (scr->mtime == stat->st_mtime) {\n            \/\/ Element is valid. Remove it from linked list.\n            scr->left->right = scr->right;\n            scr->right->left = scr->left;\n            \/\/ Insert it leftmost.\n            root.right->left = scr;\n            scr->right = root.right;\n            scr->left = &root;\n            root.right = scr;\n            ret = scr->response;\n            hits++;\n        } else {\n            \/\/ Remove outdated element from linked list and delete it.\n            (*it)->left->right = (*it)->right;\n            (*it)->right->left = (*it)->left;\n            delete *it;\n            s->erase(it);\n            ret = CACHE_MISS;\n            misses++;\n        }\n    }\n    pthread_mutex_unlock(&mutex);\n    return ret;\n}\n\n\/**\n * @brief Remove scan result from cache.\n * @param stat file status as returned by fstat()\n *\/\nvoid ScanCache::remove(const struct stat *stat) {\n    std::set::iterator it;\n    ScanResult *scr = new ScanResult();\n    scr->dev = stat->st_dev;\n    scr->ino = stat->st_ino;\n\n    pthread_mutex_lock(&mutex);\n    it = s->find(scr);\n    if (it != s->end()) {\n        \/\/ Remove from linked list and delete.\n        (*it)->left->right = (*it)->right;\n        (*it)->right->left = (*it)->left;\n        delete *it;\n        s->erase(it);\n    }\n    pthread_mutex_unlock(&mutex);\n    delete scr;\n}\n\nScanCache::~ScanCache() {\n    std::stringstream msg;\n    msg << \"Cache size \" << s->size() <<\n            \", cache hits \" << hits << \", cache misses \" << misses << \".\";\n    clear();\n    pthread_mutex_destroy(&mutex);\n    Messaging::message(Messaging::INFORMATION, msg.str());\n}\n<|endoftext|>"}
{"text":"\/*\n * Worldvisions Weaver Software:\n *   Copyright (C) 1997-2003 Net Integration Technologies, Inc.\n *\n * Standalone WvDial program, for testing the WvDialer class.\n *\n * Created:\tSept 30 1997\t\tD. Coombs\n *\/\n\n#include \"wvdialer.h\"\n#include \"wvver.h\"\n#include \"wvlog.h\"\n#include \"wvlogrcv.h\"\n#include \"wvlogfile.h\"\n#include \"wvsyslog.h\"\n#include \"wvcrash.h\"\n\n#include \n#include \n#include \n\nvolatile bool want_to_die = false;\n\n\n\/\/ use no prefix string for app \"Modem\", and an arrow for everything else.\n\/\/ This makes the output of the wvdial application look nicer.\nclass WvDialLogger : public WvLogConsole\n\/**************************************\/\n{\npublic:\n    WvDialLogger() : WvLogConsole(dup(2)) \/\/ log to stderr (fd 2)\n        { }\n\nprotected:\n    virtual void _make_prefix();\n};\n\n\nvoid WvDialLogger::_make_prefix()\n\/*******************************\/\n{\n    WvString name = appname(last_source);\n    if(name == \"WvDial Modem\") \n    {\n\tprefix = \"\";\n\tprelen = 0;\n    } \n    else \n    {\n\tprefix = \"--> \";\n\tprelen = 4;\n    }\n}\n\nstatic void print_version()\n\/*************************\/\n{\n    printf( \"%s\", wvdial_version_text );\n}\n\nstatic void print_help()\n\/**********************\/\n{\n    print_version();\n    printf( \"\\n%s\", wvdial_help_text );\n}\n\nstatic void signalhandler(int sig)\n\/***********************************\/\n{\n    fprintf(stderr, \"Caught signal %d:  Attempting to exit gracefully...\\n\", sig);\n    want_to_die = true;\n    signal(sig, SIG_DFL);\n}\n\n\nint main(int argc, char **argv)\n\/********************************\/\n{\n#if DEBUG\n    free( malloc( 1 ) ); \/\/ for electric fence\n#endif\n    \n    WvDialLogger \trc;\n    WvSyslog\t\t*syslog = NULL;\n    WvLogFile           *filelog = NULL;\n    UniConfRoot         uniconf(\"temp:\");\n    WvConf              cfg(uniconf);\n    WvStringList\tsections;\n    WvStringList\tcmdlineopts;\n    WvLog\t\tlog( \"WvDial\", WvLog::Debug );\n    WvString\t\thomedir = getenv(\"HOME\");\n    int\t\t\thaveconfig = 0;\n    int\t\t\thavecmdlineopts = 0;\n    \n    bool chat_mode = false;\n    bool write_syslog = true;\n    \n    signal(SIGTERM, signalhandler);\n    signal(SIGINT, signalhandler);\n    signal(SIGHUP, signalhandler);\n\n    if(argc > 1) \n    {\n\tfor(int i=1; i < argc; i++) \n\t{\n\t    if(!strcmp(argv[i], \"--config\" )) \n\t    {\t\n\t\tif (!access(argv[++i < argc ? i : i - 1], F_OK)) \n\t\t{\n\t\t    haveconfig = 1;\n\t\t    cfg.load_file(WvString(argv[i]));\n\t\t    continue;\n\t\t} \n\t\telse \n\t\t{\n\t\t    log(\"Error: --config requires a valid argument\\n\");\n\t\t    print_help();\n\t\t    return 1;\t\t\t    \n\t\t}\n\t    }\n            if(strchr(argv[i], '=' )) \n\t    {\n                havecmdlineopts = 1;\n                cmdlineopts.append(new WvString(argv[i]),true);\n                continue;\n            }\n\t    if(!strcmp(argv[i], \"--chat\" )) \n\t    {\n\t\tchat_mode = true;\n\t\tcontinue;\n\t    }\n\t    if(!strcmp( argv[i], \"--no-syslog\" )) \n\t    {\n\t\twrite_syslog = false;\n\t\tcontinue;\n\t    }\n\t    if( !strcmp(argv[i], \"--help\")) \n\t    {\n\t\tprint_help();\n\t\treturn 1;\n\t    }\n\t    else if(!strcmp(argv[i], \"--version\")) \n\t    {\n\t\tprint_version();\n\t\treturn 1;\n\t    }\n\t    else if(argv[i][0] == '-') \n\t    {\n\t\tprint_help();\n\t\treturn 1;\n\t    }\n\t    sections.append(new WvString(\"Dialer %s\", argv[i]), true);\n\t}\n    } \n    else \n    {\n\tsections.append(new WvString(\"Dialer Defaults\"), true);\n    }\n    \n    if( !haveconfig)\n    {\n\t\/\/ Load the system file first...\n\tWvString stdconfig(\"\/etc\/wvdial.conf\");\n\t\t\n\tif (!access(stdconfig, F_OK))\n\t    cfg.load_file(stdconfig);\n\t\n\t\/\/ Then the user specific one...\n\tif (homedir)\n        {\n\t    WvString rcfile(\"%s\/.wvdialrc\", homedir);\n\t\t\t\n\t    if (!access(rcfile, F_OK))\n\t\tcfg.load_file(rcfile);\n\t}\n    }\n    \n    \/\/ Inject all of the command line options on into the cfg file in a new\n    \/\/ section called Command-Line if there are command line options.\n    if (havecmdlineopts == 1) \n    {\n        WvStringList::Iter i(cmdlineopts);\n        for (i.rewind();i.next();)\n        {\n            char *name = i().edit();\n            char *value = strchr(name,'=');\n\t    \n            \/\/ Value should never be null since it can't get into the list\n            \/\/ if it doesn't have an = in i()\n            \/\/ \n            *value = 0;\n\t    value++;\n            name = trim_string(name);\n            value = trim_string(value);\n            cfg.set(\"Command-Line\", name, value);\n        }\n        sections.append(new WvString(\"Command-Line\"), true);\n    }\n    \n    if(!cfg.isok()) \n    {\n\treturn 1;\n    }\n    \n    if (chat_mode) \n    { \n\tif (write_syslog) \n\t{ \n\t    WvString buf(\"wvdial[%s]\", getpid()); \n\t    syslog = new WvSyslog( buf, false, WvLog::Debug2, \n\t\t\t\t   WvLog::Debug2 ); \n\t} \n\telse \n\t{ \n\t    \/\/ Direct logging to \/dev\/null as otherwise WvLog hasn't any \n\t    \/\/ receivers and thus will use WvLogConsole to log to stderr. \n\t    \/\/ That can disturb the communication with the modem on \n\t    \/\/ stdin\/stdout. - Fixes a bug reported by SUSE on 04\/05\/04\n\t    filelog = new WvLogFile( \"\/dev\/null\", WvLog::Debug2 ); \n\t} \n    }\n    \n    WvDialer dialer(cfg, §ions, chat_mode);\n    \n    if (!chat_mode)\n\tif (dialer.isok() && dialer.options.ask_password)\n\t    dialer.ask_password();\n    \n    if (dialer.dial() == false)\n\treturn  1;\n    \n    while (!want_to_die && dialer.isok() \n\t   && dialer.status() != WvDialer::Idle) \n    {\n\tdialer.select(100);\n\tdialer.callback();\n    }\n    \n    int retval;\n    \n    if (want_to_die)\n    {\n\t\/\/ Probably dieing from a user signal\n        retval = 2;\n    }\n    \n    if ((dialer.status() != WvDialer::Idle) || !dialer.isok()) \n    {\n\tretval = 1;\n    } \n    else \n    {\n\tretval = 0;\n    }\n    \n    dialer.hangup();\n    \n    RELEASE(filelog);\n    if (syslog) delete syslog;\n\n    return(retval);\n}\nHEAD: Make WvMapi\/WvTnef and the Evolution Connector compile again after Pierre's futzing.\/*\n * Worldvisions Weaver Software:\n *   Copyright (C) 1997-2003 Net Integration Technologies, Inc.\n *\n * Standalone WvDial program, for testing the WvDialer class.\n *\n * Created:\tSept 30 1997\t\tD. Coombs\n *\/\n\n#include \"wvdialer.h\"\n#include \"wvver.h\"\n#include \"wvlog.h\"\n#include \"wvlogrcv.h\"\n#include \"wvlogfile.h\"\n#include \"wvsyslog.h\"\n#include \"wvcrash.h\"\n\n#include \n#include \n#include \n\nvolatile bool want_to_die = false;\n\n\n\/\/ use no prefix string for app \"Modem\", and an arrow for everything else.\n\/\/ This makes the output of the wvdial application look nicer.\nclass WvDialLogger : public WvLogConsole\n\/**************************************\/\n{\npublic:\n    WvDialLogger() : WvLogConsole(dup(2)) \/\/ log to stderr (fd 2)\n        { }\n\nprotected:\n    virtual void _make_prefix();\n};\n\n\nvoid WvDialLogger::_make_prefix()\n\/*******************************\/\n{\n    WvString name = appname(last_source);\n    if(name == \"WvDial Modem\") \n    {\n\tprefix = \"\";\n\tprelen = 0;\n    } \n    else \n    {\n\tprefix = \"--> \";\n\tprelen = 4;\n    }\n}\n\nstatic void print_version()\n\/*************************\/\n{\n    printf( \"%s\", wvdial_version_text );\n}\n\nstatic void print_help()\n\/**********************\/\n{\n    print_version();\n    printf( \"\\n%s\", wvdial_help_text );\n}\n\nstatic void signalhandler(int sig)\n\/***********************************\/\n{\n    fprintf(stderr, \"Caught signal %d:  Attempting to exit gracefully...\\n\", sig);\n    want_to_die = true;\n    signal(sig, SIG_DFL);\n}\n\n\nint main(int argc, char **argv)\n\/********************************\/\n{\n#if DEBUG\n    free( malloc( 1 ) ); \/\/ for electric fence\n#endif\n    \n    WvDialLogger \trc;\n    WvSyslog\t\t*syslog = NULL;\n    WvLogFile           *filelog = NULL;\n    UniConfRoot         uniconf(\"temp:\");\n    WvConf              cfg(uniconf);\n    WvStringList\tsections;\n    WvStringList\tcmdlineopts;\n    WvLog\t\tlog( \"WvDial\", WvLog::Debug );\n    WvString\t\thomedir = getenv(\"HOME\");\n    int\t\t\thaveconfig = 0;\n    int\t\t\thavecmdlineopts = 0;\n    \n    bool chat_mode = false;\n    bool write_syslog = true;\n    \n    signal(SIGTERM, signalhandler);\n    signal(SIGINT, signalhandler);\n    signal(SIGHUP, signalhandler);\n\n    if(argc > 1) \n    {\n\tfor(int i=1; i < argc; i++) \n\t{\n\t    if(!strcmp(argv[i], \"--config\" )) \n\t    {\t\n\t\tif (!access(argv[++i < argc ? i : i - 1], F_OK)) \n\t\t{\n\t\t    haveconfig = 1;\n\t\t    cfg.load_file(WvString(argv[i]));\n\t\t    continue;\n\t\t} \n\t\telse \n\t\t{\n\t\t    log(\"Error: --config requires a valid argument\\n\");\n\t\t    print_help();\n\t\t    return 1;\t\t\t    \n\t\t}\n\t    }\n            if(strchr(argv[i], '=' )) \n\t    {\n                havecmdlineopts = 1;\n                cmdlineopts.append(new WvString(argv[i]),true);\n                continue;\n            }\n\t    if(!strcmp(argv[i], \"--chat\" )) \n\t    {\n\t\tchat_mode = true;\n\t\tcontinue;\n\t    }\n\t    if(!strcmp( argv[i], \"--no-syslog\" )) \n\t    {\n\t\twrite_syslog = false;\n\t\tcontinue;\n\t    }\n\t    if( !strcmp(argv[i], \"--help\")) \n\t    {\n\t\tprint_help();\n\t\treturn 1;\n\t    }\n\t    else if(!strcmp(argv[i], \"--version\")) \n\t    {\n\t\tprint_version();\n\t\treturn 1;\n\t    }\n\t    else if(argv[i][0] == '-') \n\t    {\n\t\tprint_help();\n\t\treturn 1;\n\t    }\n\t    sections.append(new WvString(\"Dialer %s\", argv[i]), true);\n\t}\n    } \n    else \n    {\n\tsections.append(new WvString(\"Dialer Defaults\"), true);\n    }\n    \n    if( !haveconfig)\n    {\n\t\/\/ Load the system file first...\n\tWvString stdconfig(\"\/etc\/wvdial.conf\");\n\t\t\n\tif (!access(stdconfig, F_OK))\n\t    cfg.load_file(stdconfig);\n\t\n\t\/\/ Then the user specific one...\n\tif (homedir)\n        {\n\t    WvString rcfile(\"%s\/.wvdialrc\", homedir);\n\t\t\t\n\t    if (!access(rcfile, F_OK))\n\t\tcfg.load_file(rcfile);\n\t}\n    }\n    \n    \/\/ Inject all of the command line options on into the cfg file in a new\n    \/\/ section called Command-Line if there are command line options.\n    if (havecmdlineopts == 1) \n    {\n        WvStringList::Iter i(cmdlineopts);\n        for (i.rewind();i.next();)\n        {\n            char *name = i().edit();\n            char *value = strchr(name,'=');\n\t    \n            \/\/ Value should never be null since it can't get into the list\n            \/\/ if it doesn't have an = in i()\n            \/\/ \n            *value = 0;\n\t    value++;\n            name = trim_string(name);\n            value = trim_string(value);\n            cfg.set(\"Command-Line\", name, value);\n        }\n        sections.append(new WvString(\"Command-Line\"), true);\n    }\n    \n    if(!cfg.isok()) \n    {\n\treturn 1;\n    }\n    \n    if (chat_mode) \n    { \n\tif (write_syslog) \n\t{ \n\t    WvString buf(\"wvdial[%s]\", getpid()); \n\t    syslog = new WvSyslog( buf, false, WvLog::Debug2, \n\t\t\t\t   WvLog::Debug2 ); \n\t} \n\telse \n\t{ \n\t    \/\/ Direct logging to \/dev\/null as otherwise WvLog hasn't any \n\t    \/\/ receivers and thus will use WvLogConsole to log to stderr. \n\t    \/\/ That can disturb the communication with the modem on \n\t    \/\/ stdin\/stdout. - Fixes a bug reported by SUSE on 04\/05\/04\n\t    filelog = new WvLogFile( \"\/dev\/null\", WvLog::Debug2 ); \n\t} \n    }\n    \n    WvDialer dialer(cfg, §ions, chat_mode);\n    \n    if (!chat_mode)\n\tif (dialer.isok() && dialer.options.ask_password)\n\t    dialer.ask_password();\n    \n    if (dialer.dial() == false)\n\treturn  1;\n    \n    while (!want_to_die && dialer.isok() \n\t   && dialer.status() != WvDialer::Idle) \n    {\n\tdialer.select(100);\n\tdialer.callback();\n    }\n    \n    int retval;\n    \n    if (want_to_die)\n    {\n\t\/\/ Probably dieing from a user signal\n        retval = 2;\n    }\n    \n    if ((dialer.status() != WvDialer::Idle) || !dialer.isok()) \n    {\n\tretval = 1;\n    } \n    else \n    {\n\tretval = 0;\n    }\n    \n    dialer.hangup();\n    \n    RELEASE(filelog);\n    delete syslog;\n\n    return(retval);\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n\nclass MultipartParser {\npublic:\n\ttypedef void (*Callback)(const char *buffer, size_t start, size_t end, void *userData);\n\t\nprivate:\n\tstatic const char CR     = 13;\n\tstatic const char LF     = 10;\n\tstatic const char SPACE  = 32;\n\tstatic const char HYPHEN = 45;\n\tstatic const char COLON  = 58;\n\tstatic const char A      = 97;\n\tstatic const char Z      = 122;\n\tstatic const size_t UNMARKED = (size_t) -1;\n\t\n\tenum State {\n\t\tERROR,\n\t\tSTART,\n\t\tSTART_BOUNDARY,\n\t\tHEADER_FIELD_START,\n\t\tHEADER_FIELD,\n\t\tHEADER_VALUE_START,\n\t\tHEADER_VALUE,\n\t\tHEADER_VALUE_ALMOST_DONE,\n\t\tHEADERS_ALMOST_DONE,\n\t\tPART_DATA_START,\n\t\tPART_DATA,\n\t\tPART_END,\n\t\tEND\n\t};\n\t\n\tenum Flags {\n\t\tPART_BOUNDARY = 1,\n\t\tLAST_BOUNDARY = 2\n\t};\n\t\n\tstd::string boundary;\n\tchar *lookbehind;\n\tsize_t lookbehindSize;\n\tState state;\n\tint flags;\n\tsize_t index;\n\tsize_t headerFieldMark;\n\tsize_t headerValueMark;\n\tsize_t partDataMark;\n\tconst char *errorReason;\n\t\n\tvoid callback(Callback cb, const char *buffer = NULL, size_t start = UNMARKED, size_t end = UNMARKED) {\n\t\tif (start != UNMARKED && start == end) {\n\t\t\treturn;\n\t\t}\n\t\tif (cb != NULL) {\n\t\t\tcb(buffer, start, end, userData);\n\t\t}\n\t}\n\t\n\tvoid dataCallback(Callback cb, size_t &mark, const char *buffer, size_t i, size_t bufferLen, bool clear) {\n\t\tif (mark == UNMARKED) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!clear) {\n\t\t\tcallback(cb, buffer, mark, bufferLen);\n\t\t\tmark = 0;\n\t\t} else {\n\t\t\tcallback(cb, buffer, mark, i);\n\t\t\tmark = UNMARKED;\n\t\t}\n\t}\n\t\n\tchar lower(char c) const {\n\t\treturn c | 0x20;\n\t}\n\t\n\tbool isBoundaryChar(char c) const {\n\t\tconst char *current = boundary.c_str();\n\t\tconst char *end = current + boundary.size();\n\t\t\n\t\twhile (current < end) {\n\t\t\tif (*current == c) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcurrent++;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tvoid setError(const char *message) {\n\t\tstate = ERROR;\n\t\terrorReason = message;\n\t}\n\t\npublic:\n\tCallback onPartBegin;\n\tCallback onHeaderField;\n\tCallback onHeaderValue;\n\tCallback onPartData;\n\tCallback onPartEnd;\n\tCallback onEnd;\n\tvoid *userData;\n\t\n\tMultipartParser() {\n\t\tlookbehind = NULL;\n\t\treset();\n\t}\n\t\n\tMultipartParser(const std::string &boundary) {\n\t\tlookbehind = NULL;\n\t\tsetBoundary(boundary);\n\t}\n\t\n\t~MultipartParser() {\n\t\tdelete[] lookbehind;\n\t}\n\t\n\tvoid reset() {\n\t\tdelete[] lookbehind;\n\t\tstate = ERROR;\n\t\tlookbehind = NULL;\n\t\tlookbehindSize = 0;\n\t\tflags = 0;\n\t\tindex = 0;\n\t\theaderFieldMark = UNMARKED;\n\t\theaderValueMark = UNMARKED;\n\t\tpartDataMark    = UNMARKED;\n\t\terrorReason = NULL;\n\t\t\n\t\tonPartBegin   = NULL;\n\t\tonHeaderField = NULL;\n\t\tonHeaderValue = NULL;\n\t\tonPartData    = NULL;\n\t\tonPartEnd     = NULL;\n\t\tonEnd         = NULL;\n\t\tuserData      = NULL;\n\t}\n\t\n\tvoid setBoundary(const std::string &boundary) {\n\t\treset();\n\t\tthis->boundary = \"\\r\\n--\" + boundary;\n\t\tlookbehind = new char[this->boundary.size() + 8];\n\t\tlookbehindSize = this->boundary.size() + 8;\n\t\tstate = START;\n\t}\n\t\n\tsize_t feed(const char *buffer, size_t len) {\n\t\tState state         = this->state;\n\t\tint flags           = this->flags;\n\t\tsize_t prevIndex    = this->index;\n\t\tsize_t index        = this->index;\n\t\tsize_t boundarySize = boundary.size();\n\t\tsize_t boundaryEnd  = boundarySize - 1;\n\t\tsize_t i;\n\t\tchar c, cl;\n\t\t\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tc = buffer[i];\n\t\t\t\n\t\t\tswitch (state) {\n\t\t\tcase ERROR:\n\t\t\t\treturn i;\n\t\t\tcase START:\n\t\t\t\tindex = 0;\n\t\t\t\tstate = START_BOUNDARY;\n\t\t\tcase START_BOUNDARY:\n\t\t\t\tif (index == boundarySize - 2) {\n\t\t\t\t\tif (c != CR) {\n\t\t\t\t\t\treturn i;\n\t\t\t\t\t}\n\t\t\t\t\tindex++;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (index - 1 == boundarySize - 2) {\n\t\t\t\t\tif (c != LF) {\n\t\t\t\t\t\treturn i;\n\t\t\t\t\t}\n\t\t\t\t\tindex = 0;\n\t\t\t\t\tcallback(onPartBegin);\n\t\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (c != boundary[index + 2]) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tbreak;\n\t\t\tcase HEADER_FIELD_START:\n\t\t\t\tstate = HEADER_FIELD;\n\t\t\t\theaderFieldMark = i;\n\t\t\tcase HEADER_FIELD:\n\t\t\t\tif (c == CR) {\n\t\t\t\t\theaderFieldMark = UNMARKED;\n\t\t\t\t\tstate = HEADERS_ALMOST_DONE;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (c == HYPHEN) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (c == COLON) {\n\t\t\t\t\tdataCallback(onHeaderField, headerFieldMark, buffer, i, len, true);\n\t\t\t\t\tstate = HEADER_VALUE_START;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcl = lower(c);\n\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\tsetError(\"Malformed header name.\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEADER_VALUE_START:\n\t\t\t\tif (c == SPACE) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\theaderValueMark = i;\n\t\t\t\tstate = HEADER_VALUE;\n\t\t\tcase HEADER_VALUE:\n\t\t\t\tif (c == CR) {\n\t\t\t\t\tdataCallback(onHeaderValue, headerValueMark, buffer, i, len, true);\n\t\t\t\t\tstate = HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEADER_VALUE_ALMOST_DONE:\n\t\t\t\tif (c != LF) {\n\t\t\t\t\tsetError(\"Malformed header value: LF expected after CR\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\tbreak;\n\t\t\tcase HEADERS_ALMOST_DONE:\n\t\t\t\tif (c != LF) {\n\t\t\t\t\tsetError(\"Malformed header ending: LF expected after CR\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstate = PART_DATA_START;\n\t\t\t\tbreak;\n\t\t\tcase PART_DATA_START:\n\t\t\t\tstate = PART_DATA;\n\t\t\t\tpartDataMark = i;\n\t\t\tcase PART_DATA:\n\t\t\t\tprevIndex = index;\n\t\t\t\t\n\t\t\t\tif (index == 0) {\n\t\t\t\t\t\/\/ boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\twhile (i + boundary.size() <= len) {\n\t\t\t\t\t\tif (isBoundaryChar(buffer[i + boundaryEnd])) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\ti += boundary.size();\n\t\t\t\t\t}\n\t\t\t\t\tc = buffer[i];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (index < boundary.size()) {\n\t\t\t\t\tif (boundary[index] == c) {\n\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\tdataCallback(onPartData, partDataMark, buffer, i, len, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index == boundary.size()) {\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c == CR) {\n\t\t\t\t\t\t\/\/ CR = part boundary\n\t\t\t\t\t\tflags |= PART_BOUNDARY;\n\t\t\t\t\t} else if (c == HYPHEN) {\n\t\t\t\t\t\t\/\/ HYPHEN = end boundary\n\t\t\t\t\t\tflags |= LAST_BOUNDARY;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - 1 == boundary.size()) {\n\t\t\t\t\tif (flags & PART_BOUNDARY) {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\tif (c == LF) {\n\t\t\t\t\t\t\t\/\/ unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\tflags &= ~PART_BOUNDARY;\n\t\t\t\t\t\t\tcallback(onPartEnd);\n\t\t\t\t\t\t\tcallback(onPartBegin);\n\t\t\t\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (flags & LAST_BOUNDARY) {\n\t\t\t\t\t\tif (c == HYPHEN) {\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - 2 == boundary.size()) {\n\t\t\t\t\tif (c == CR) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - boundary.size() == 3) {\n\t\t\t\t\tindex = 0;\n\t\t\t\t\tif (c == LF) {\n\t\t\t\t\t\tcallback(onPartEnd);\n\t\t\t\t\t\tcallback(onEnd);\n\t\t\t\t\t\tstate = END;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (index > 0) {\n\t\t\t\t\t\/\/ when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\/\/ in case it turns out to be a false lead\n\t\t\t\t\tif (index - 1 >= lookbehindSize) {\n\t\t\t\t\t\tthrow std::out_of_range(\"index overflows lookbehind buffer\");\n\t\t\t\t\t}\n\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t} else if (prevIndex > 0) {\n\t\t\t\t\t\/\/ if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\/\/ belongs to partData\n\t\t\t\t\tcallback(onPartData, lookbehind, 0, prevIndex);\n\t\t\t\t\tprevIndex = 0;\n\t\t\t\t\tpartDataMark = i;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\tdataCallback(onHeaderField, headerFieldMark, buffer, i, len, false);\n\t\tdataCallback(onHeaderValue, headerValueMark, buffer, i, len, false);\n\t\tdataCallback(onPartData, partDataMark, buffer, i, len, false);\n\t\t\n\t\tthis->index = index;\n\t\tthis->state = state;\n\t\tthis->flags = flags;\n\t\t\n\t\treturn len;\n\t}\n\t\n\tbool succeeded() const {\n\t\treturn state == END;\n\t}\n\t\n\tbool hasError() const {\n\t\treturn state == ERROR;\n\t}\n\t\n\tbool stopped() const {\n\t\treturn state == ERROR || state == END;\n\t}\n\t\n\tconst char *getErrorMessage() const {\n\t\treturn errorReason;\n\t}\n};\n\n#include \nusing namespace std;\n\nstatic void\nonPartBegin(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartBegin\\n\");\n}\n\nstatic void\nonHeaderField(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onHeaderField: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonHeaderValue(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onHeaderValue: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonPartData(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartData: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonPartEnd(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartEnd\\n\");\n}\n\nstatic void\nonEnd(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onEnd\\n\");\n}\n\nint\nmain() {\n\tMultipartParser parser(\"abcd\");\n\tparser.onPartBegin = onPartBegin;\n\tparser.onHeaderField = onHeaderField;\n\tparser.onHeaderValue = onHeaderValue;\n\tparser.onPartData = onPartData;\n\tparser.onPartEnd = onPartEnd;\n\tparser.onEnd = onEnd;\n\t\n\twhile (!parser.stopped() && !feof(stdin)) {\n\t\tchar buf[5];\n\t\tsize_t len = fread(buf, 1, sizeof(buf), stdin);\n\t\tsize_t fed = 0;\n\t\tdo {\n\t\t\tsize_t ret = parser.feed(buf + fed, len - fed);\n\t\t\tfed += ret;\n\t\t\tprintf(\"accepted %d bytes\\n\", (int) ret);\n\t\t} while (fed < len && !parser.stopped());\n\t}\n\tprintf(\"%s\\n\", parser.getErrorMessage());\n\treturn 0;\n}\nProperly abort on error state.#include \n#include \n#include \n\nclass MultipartParser {\npublic:\n\ttypedef void (*Callback)(const char *buffer, size_t start, size_t end, void *userData);\n\t\nprivate:\n\tstatic const char CR     = 13;\n\tstatic const char LF     = 10;\n\tstatic const char SPACE  = 32;\n\tstatic const char HYPHEN = 45;\n\tstatic const char COLON  = 58;\n\tstatic const char A      = 97;\n\tstatic const char Z      = 122;\n\tstatic const size_t UNMARKED = (size_t) -1;\n\t\n\tenum State {\n\t\tERROR,\n\t\tSTART,\n\t\tSTART_BOUNDARY,\n\t\tHEADER_FIELD_START,\n\t\tHEADER_FIELD,\n\t\tHEADER_VALUE_START,\n\t\tHEADER_VALUE,\n\t\tHEADER_VALUE_ALMOST_DONE,\n\t\tHEADERS_ALMOST_DONE,\n\t\tPART_DATA_START,\n\t\tPART_DATA,\n\t\tPART_END,\n\t\tEND\n\t};\n\t\n\tenum Flags {\n\t\tPART_BOUNDARY = 1,\n\t\tLAST_BOUNDARY = 2\n\t};\n\t\n\tstd::string boundary;\n\tchar *lookbehind;\n\tsize_t lookbehindSize;\n\tState state;\n\tint flags;\n\tsize_t index;\n\tsize_t headerFieldMark;\n\tsize_t headerValueMark;\n\tsize_t partDataMark;\n\tconst char *errorReason;\n\t\n\tvoid callback(Callback cb, const char *buffer = NULL, size_t start = UNMARKED, size_t end = UNMARKED) {\n\t\tif (start != UNMARKED && start == end) {\n\t\t\treturn;\n\t\t}\n\t\tif (cb != NULL) {\n\t\t\tcb(buffer, start, end, userData);\n\t\t}\n\t}\n\t\n\tvoid dataCallback(Callback cb, size_t &mark, const char *buffer, size_t i, size_t bufferLen, bool clear) {\n\t\tif (mark == UNMARKED) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!clear) {\n\t\t\tcallback(cb, buffer, mark, bufferLen);\n\t\t\tmark = 0;\n\t\t} else {\n\t\t\tcallback(cb, buffer, mark, i);\n\t\t\tmark = UNMARKED;\n\t\t}\n\t}\n\t\n\tchar lower(char c) const {\n\t\treturn c | 0x20;\n\t}\n\t\n\tbool isBoundaryChar(char c) const {\n\t\tconst char *current = boundary.c_str();\n\t\tconst char *end = current + boundary.size();\n\t\t\n\t\twhile (current < end) {\n\t\t\tif (*current == c) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcurrent++;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tvoid setError(const char *message) {\n\t\tstate = ERROR;\n\t\terrorReason = message;\n\t}\n\t\npublic:\n\tCallback onPartBegin;\n\tCallback onHeaderField;\n\tCallback onHeaderValue;\n\tCallback onPartData;\n\tCallback onPartEnd;\n\tCallback onEnd;\n\tvoid *userData;\n\t\n\tMultipartParser() {\n\t\tlookbehind = NULL;\n\t\treset();\n\t}\n\t\n\tMultipartParser(const std::string &boundary) {\n\t\tlookbehind = NULL;\n\t\tsetBoundary(boundary);\n\t}\n\t\n\t~MultipartParser() {\n\t\tdelete[] lookbehind;\n\t}\n\t\n\tvoid reset() {\n\t\tdelete[] lookbehind;\n\t\tstate = ERROR;\n\t\tlookbehind = NULL;\n\t\tlookbehindSize = 0;\n\t\tflags = 0;\n\t\tindex = 0;\n\t\theaderFieldMark = UNMARKED;\n\t\theaderValueMark = UNMARKED;\n\t\tpartDataMark    = UNMARKED;\n\t\terrorReason = NULL;\n\t\t\n\t\tonPartBegin   = NULL;\n\t\tonHeaderField = NULL;\n\t\tonHeaderValue = NULL;\n\t\tonPartData    = NULL;\n\t\tonPartEnd     = NULL;\n\t\tonEnd         = NULL;\n\t\tuserData      = NULL;\n\t}\n\t\n\tvoid setBoundary(const std::string &boundary) {\n\t\treset();\n\t\tthis->boundary = \"\\r\\n--\" + boundary;\n\t\tlookbehind = new char[this->boundary.size() + 8];\n\t\tlookbehindSize = this->boundary.size() + 8;\n\t\tstate = START;\n\t}\n\t\n\tsize_t feed(const char *buffer, size_t len) {\n\t\tif (state == ERROR) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tState state         = this->state;\n\t\tint flags           = this->flags;\n\t\tsize_t prevIndex    = this->index;\n\t\tsize_t index        = this->index;\n\t\tsize_t boundarySize = boundary.size();\n\t\tsize_t boundaryEnd  = boundarySize - 1;\n\t\tsize_t i;\n\t\tchar c, cl;\n\t\t\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tc = buffer[i];\n\t\t\t\n\t\t\tswitch (state) {\n\t\t\tcase ERROR:\n\t\t\t\treturn i;\n\t\t\tcase START:\n\t\t\t\tindex = 0;\n\t\t\t\tstate = START_BOUNDARY;\n\t\t\tcase START_BOUNDARY:\n\t\t\t\tif (index == boundarySize - 2) {\n\t\t\t\t\tif (c != CR) {\n\t\t\t\t\t\treturn i;\n\t\t\t\t\t}\n\t\t\t\t\tindex++;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (index - 1 == boundarySize - 2) {\n\t\t\t\t\tif (c != LF) {\n\t\t\t\t\t\treturn i;\n\t\t\t\t\t}\n\t\t\t\t\tindex = 0;\n\t\t\t\t\tcallback(onPartBegin);\n\t\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (c != boundary[index + 2]) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tbreak;\n\t\t\tcase HEADER_FIELD_START:\n\t\t\t\tstate = HEADER_FIELD;\n\t\t\t\theaderFieldMark = i;\n\t\t\tcase HEADER_FIELD:\n\t\t\t\tif (c == CR) {\n\t\t\t\t\theaderFieldMark = UNMARKED;\n\t\t\t\t\tstate = HEADERS_ALMOST_DONE;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (c == HYPHEN) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (c == COLON) {\n\t\t\t\t\tdataCallback(onHeaderField, headerFieldMark, buffer, i, len, true);\n\t\t\t\t\tstate = HEADER_VALUE_START;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcl = lower(c);\n\t\t\t\tif (cl < A || cl > Z) {\n\t\t\t\t\tsetError(\"Malformed header name.\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEADER_VALUE_START:\n\t\t\t\tif (c == SPACE) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\theaderValueMark = i;\n\t\t\t\tstate = HEADER_VALUE;\n\t\t\tcase HEADER_VALUE:\n\t\t\t\tif (c == CR) {\n\t\t\t\t\tdataCallback(onHeaderValue, headerValueMark, buffer, i, len, true);\n\t\t\t\t\tstate = HEADER_VALUE_ALMOST_DONE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase HEADER_VALUE_ALMOST_DONE:\n\t\t\t\tif (c != LF) {\n\t\t\t\t\tsetError(\"Malformed header value: LF expected after CR\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\tbreak;\n\t\t\tcase HEADERS_ALMOST_DONE:\n\t\t\t\tif (c != LF) {\n\t\t\t\t\tsetError(\"Malformed header ending: LF expected after CR\");\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstate = PART_DATA_START;\n\t\t\t\tbreak;\n\t\t\tcase PART_DATA_START:\n\t\t\t\tstate = PART_DATA;\n\t\t\t\tpartDataMark = i;\n\t\t\tcase PART_DATA:\n\t\t\t\tprevIndex = index;\n\t\t\t\t\n\t\t\t\tif (index == 0) {\n\t\t\t\t\t\/\/ boyer-moore derrived algorithm to safely skip non-boundary data\n\t\t\t\t\twhile (i + boundary.size() <= len) {\n\t\t\t\t\t\tif (isBoundaryChar(buffer[i + boundaryEnd])) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\ti += boundary.size();\n\t\t\t\t\t}\n\t\t\t\t\tc = buffer[i];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (index < boundary.size()) {\n\t\t\t\t\tif (boundary[index] == c) {\n\t\t\t\t\t\tif (index == 0) {\n\t\t\t\t\t\t\tdataCallback(onPartData, partDataMark, buffer, i, len, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index == boundary.size()) {\n\t\t\t\t\tindex++;\n\t\t\t\t\tif (c == CR) {\n\t\t\t\t\t\t\/\/ CR = part boundary\n\t\t\t\t\t\tflags |= PART_BOUNDARY;\n\t\t\t\t\t} else if (c == HYPHEN) {\n\t\t\t\t\t\t\/\/ HYPHEN = end boundary\n\t\t\t\t\t\tflags |= LAST_BOUNDARY;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - 1 == boundary.size()) {\n\t\t\t\t\tif (flags & PART_BOUNDARY) {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\tif (c == LF) {\n\t\t\t\t\t\t\t\/\/ unset the PART_BOUNDARY flag\n\t\t\t\t\t\t\tflags &= ~PART_BOUNDARY;\n\t\t\t\t\t\t\tcallback(onPartEnd);\n\t\t\t\t\t\t\tcallback(onPartBegin);\n\t\t\t\t\t\t\tstate = HEADER_FIELD_START;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (flags & LAST_BOUNDARY) {\n\t\t\t\t\t\tif (c == HYPHEN) {\n\t\t\t\t\t\t\tindex++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - 2 == boundary.size()) {\n\t\t\t\t\tif (c == CR) {\n\t\t\t\t\t\tindex++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tindex = 0;\n\t\t\t\t\t}\n\t\t\t\t} else if (index - boundary.size() == 3) {\n\t\t\t\t\tindex = 0;\n\t\t\t\t\tif (c == LF) {\n\t\t\t\t\t\tcallback(onPartEnd);\n\t\t\t\t\t\tcallback(onEnd);\n\t\t\t\t\t\tstate = END;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (index > 0) {\n\t\t\t\t\t\/\/ when matching a possible boundary, keep a lookbehind reference\n\t\t\t\t\t\/\/ in case it turns out to be a false lead\n\t\t\t\t\tif (index - 1 >= lookbehindSize) {\n\t\t\t\t\t\tthrow std::out_of_range(\"index overflows lookbehind buffer\");\n\t\t\t\t\t}\n\t\t\t\t\tlookbehind[index - 1] = c;\n\t\t\t\t} else if (prevIndex > 0) {\n\t\t\t\t\t\/\/ if our boundary turned out to be rubbish, the captured lookbehind\n\t\t\t\t\t\/\/ belongs to partData\n\t\t\t\t\tcallback(onPartData, lookbehind, 0, prevIndex);\n\t\t\t\t\tprevIndex = 0;\n\t\t\t\t\tpartDataMark = i;\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t\n\t\tdataCallback(onHeaderField, headerFieldMark, buffer, i, len, false);\n\t\tdataCallback(onHeaderValue, headerValueMark, buffer, i, len, false);\n\t\tdataCallback(onPartData, partDataMark, buffer, i, len, false);\n\t\t\n\t\tthis->index = index;\n\t\tthis->state = state;\n\t\tthis->flags = flags;\n\t\t\n\t\treturn len;\n\t}\n\t\n\tbool succeeded() const {\n\t\treturn state == END;\n\t}\n\t\n\tbool hasError() const {\n\t\treturn state == ERROR;\n\t}\n\t\n\tbool stopped() const {\n\t\treturn state == ERROR || state == END;\n\t}\n\t\n\tconst char *getErrorMessage() const {\n\t\treturn errorReason;\n\t}\n};\n\n#include \nusing namespace std;\n\nstatic void\nonPartBegin(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartBegin\\n\");\n}\n\nstatic void\nonHeaderField(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onHeaderField: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonHeaderValue(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onHeaderValue: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonPartData(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartData: (%s)\\n\", string(buffer + start, end - start).c_str());\n}\n\nstatic void\nonPartEnd(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onPartEnd\\n\");\n}\n\nstatic void\nonEnd(const char *buffer, size_t start, size_t end, void *userData) {\n\tprintf(\"onEnd\\n\");\n}\n\nint\nmain() {\n\tMultipartParser parser(\"abcd\");\n\tparser.onPartBegin = onPartBegin;\n\tparser.onHeaderField = onHeaderField;\n\tparser.onHeaderValue = onHeaderValue;\n\tparser.onPartData = onPartData;\n\tparser.onPartEnd = onPartEnd;\n\tparser.onEnd = onEnd;\n\t\n\twhile (!parser.stopped() && !feof(stdin)) {\n\t\tchar buf[5];\n\t\tsize_t len = fread(buf, 1, sizeof(buf), stdin);\n\t\tsize_t fed = 0;\n\t\tdo {\n\t\t\tsize_t ret = parser.feed(buf + fed, len - fed);\n\t\t\tfed += ret;\n\t\t\tprintf(\"accepted %d bytes\\n\", (int) ret);\n\t\t} while (fed < len && !parser.stopped());\n\t}\n\tprintf(\"%s\\n\", parser.getErrorMessage());\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/     * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Disable exception handler warnings.\n#pragma warning( disable : 4530 )\n\n#include \"client\/windows\/sender\/crash_report_sender.h\"\n#include \"common\/windows\/http_upload.h\"\n\n#if _MSC_VER < 1400  \/\/ MSVC 2005\/8\n\/\/ Older MSVC doesn't have fscanf_s, but they are compatible as long as\n\/\/ we don't use the string conversions (%s\/%c\/%S\/%C).\n#define fscanf_s fscanf\n#endif\n\nnamespace google_breakpad {\n\nstatic const char kCheckpointSignature[] = \"GBP1\\n\";\n\nCrashReportSender::CrashReportSender(const wstring &checkpoint_file)\n    : checkpoint_file_(checkpoint_file),\n      max_reports_per_day_(-1),\n      last_sent_date_(-1),\n      reports_sent_(0) {\n  FILE *fd;\n  if (OpenCheckpointFile(L\"r\", &fd) == 0) {\n    ReadCheckpoint(fd);\n    fclose(fd);\n  }\n}\n\nReportResult CrashReportSender::SendCrashReport(\n    const wstring &url, const map ¶meters,\n    const wstring &dump_file_name, wstring *report_code) {\n  int today = GetCurrentDate();\n  if (today == last_sent_date_ &&\n      max_reports_per_day_ != -1 &&\n      reports_sent_ >= max_reports_per_day_) {\n    return RESULT_THROTTLED;\n  }\n\n  int http_response = 0;\n  bool result = HTTPUpload::SendRequest(\n    url, parameters, dump_file_name, L\"upload_file_minidump\", report_code,\n    &http_response);\n  ReportSent(today);\n\n  if (result) {\n    return RESULT_SUCCEEDED;\n  } else if (http_response == 400) {  \/\/ TODO: update if\/when the server\n                                      \/\/       switches to a different code\n    return RESULT_REJECTED;\n  } else {\n    return RESULT_FAILED;\n  }\n}\n\nvoid CrashReportSender::ReadCheckpoint(FILE *fd) {\n  char buf[128];\n  if (!fgets(buf, sizeof(buf), fd) ||\n      strcmp(buf, kCheckpointSignature) != 0) {\n    return;\n  }\n\n  if (fscanf_s(fd, \"%d\\n\", &last_sent_date_) != 1) {\n    last_sent_date_ = -1;\n    return;\n  }\n  if (fscanf_s(fd, \"%d\\n\", &reports_sent_) != 1) {\n    reports_sent_ = 0;\n    return;\n  }\n}\n\nvoid CrashReportSender::ReportSent(int today) {\n  \/\/ Update the report stats\n  if (today != last_sent_date_) {\n    last_sent_date_ = today;\n    reports_sent_ = 0;\n  }\n  ++reports_sent_;\n\n  \/\/ Update the checkpoint file\n  FILE *fd;\n  if (OpenCheckpointFile(L\"w\", &fd) == 0) {\n    fputs(kCheckpointSignature, fd);\n    fprintf(fd, \"%d\\n\", last_sent_date_);\n    fprintf(fd, \"%d\\n\", reports_sent_);\n    fclose(fd);\n  }\n}\n\nint CrashReportSender::GetCurrentDate() const {\n  SYSTEMTIME system_time;\n  GetSystemTime(&system_time);\n  return (system_time.wYear * 10000) + (system_time.wMonth * 100) +\n      system_time.wDay;\n}\n\nint CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) {\n#if _MSC_VER >= 1400  \/\/ MSVC 2005\/8\n  return _wfopen_s(fd, checkpoint_file_.c_str(), mode);\n#else\n  *fd = _wfopen(checkpoint_file_.c_str(), mode);\n  if (*fd == NULL) {\n    return errno;\n  }\n  return 0;\n#endif\n}\n\n}  \/\/ namespace google_breakpad\nAssertion in CrashReportSender (windows) when no checkpoint file is desired (#216).  Patch by Ben Turner .  r=me.\/\/ Copyright (c) 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/     * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Disable exception handler warnings.\n#pragma warning( disable : 4530 )\n\n#include \"client\/windows\/sender\/crash_report_sender.h\"\n#include \"common\/windows\/http_upload.h\"\n\n#if _MSC_VER < 1400  \/\/ MSVC 2005\/8\n\/\/ Older MSVC doesn't have fscanf_s, but they are compatible as long as\n\/\/ we don't use the string conversions (%s\/%c\/%S\/%C).\n#define fscanf_s fscanf\n#endif\n\nnamespace google_breakpad {\n\nstatic const char kCheckpointSignature[] = \"GBP1\\n\";\n\nCrashReportSender::CrashReportSender(const wstring &checkpoint_file)\n    : checkpoint_file_(checkpoint_file),\n      max_reports_per_day_(-1),\n      last_sent_date_(-1),\n      reports_sent_(0) {\n  FILE *fd;\n  if (OpenCheckpointFile(L\"r\", &fd) == 0) {\n    ReadCheckpoint(fd);\n    fclose(fd);\n  }\n}\n\nReportResult CrashReportSender::SendCrashReport(\n    const wstring &url, const map ¶meters,\n    const wstring &dump_file_name, wstring *report_code) {\n  int today = GetCurrentDate();\n  if (today == last_sent_date_ &&\n      max_reports_per_day_ != -1 &&\n      reports_sent_ >= max_reports_per_day_) {\n    return RESULT_THROTTLED;\n  }\n\n  int http_response = 0;\n  bool result = HTTPUpload::SendRequest(\n    url, parameters, dump_file_name, L\"upload_file_minidump\", report_code,\n    &http_response);\n  ReportSent(today);\n\n  if (result) {\n    return RESULT_SUCCEEDED;\n  } else if (http_response == 400) {  \/\/ TODO: update if\/when the server\n                                      \/\/       switches to a different code\n    return RESULT_REJECTED;\n  } else {\n    return RESULT_FAILED;\n  }\n}\n\nvoid CrashReportSender::ReadCheckpoint(FILE *fd) {\n  char buf[128];\n  if (!fgets(buf, sizeof(buf), fd) ||\n      strcmp(buf, kCheckpointSignature) != 0) {\n    return;\n  }\n\n  if (fscanf_s(fd, \"%d\\n\", &last_sent_date_) != 1) {\n    last_sent_date_ = -1;\n    return;\n  }\n  if (fscanf_s(fd, \"%d\\n\", &reports_sent_) != 1) {\n    reports_sent_ = 0;\n    return;\n  }\n}\n\nvoid CrashReportSender::ReportSent(int today) {\n  \/\/ Update the report stats\n  if (today != last_sent_date_) {\n    last_sent_date_ = today;\n    reports_sent_ = 0;\n  }\n  ++reports_sent_;\n\n  \/\/ Update the checkpoint file\n  FILE *fd;\n  if (OpenCheckpointFile(L\"w\", &fd) == 0) {\n    fputs(kCheckpointSignature, fd);\n    fprintf(fd, \"%d\\n\", last_sent_date_);\n    fprintf(fd, \"%d\\n\", reports_sent_);\n    fclose(fd);\n  }\n}\n\nint CrashReportSender::GetCurrentDate() const {\n  SYSTEMTIME system_time;\n  GetSystemTime(&system_time);\n  return (system_time.wYear * 10000) + (system_time.wMonth * 100) +\n      system_time.wDay;\n}\n\nint CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) {\n  if (checkpoint_file_.empty()) {\n    return ENOENT;\n  }\n#if _MSC_VER >= 1400  \/\/ MSVC 2005\/8\n  return _wfopen_s(fd, checkpoint_file_.c_str(), mode);\n#else\n  *fd = _wfopen(checkpoint_file_.c_str(), mode);\n  if (*fd == NULL) {\n    return errno;\n  }\n  return 0;\n#endif\n}\n\n}  \/\/ namespace google_breakpad\n<|endoftext|>"}
{"text":"Why did I have that four times?<|endoftext|>"}
{"text":"#ifdef _MSC_VER\n\/\/fixes \"fatal error C1189: #error :  WinSock.h has already been included\"\n#\tinclude \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fileserver\n{\n\tusing response_part = Si::memory_range;\n\n\ttypedef Si::fast_variant any_reference;\n\n\tstruct get_request\n\t{\n\t\tany_reference what;\n\t};\n\n\tstruct browse_request\n\t{\n\t\tany_reference what;\n\t};\n\n\ttypedef Si::fast_variant parsed_request;\n\n\ttemplate \n\tSi::optional parse_any_reference(PathElementRange const &path)\n\t{\n\t\tif (path.empty())\n\t\t{\n\t\t\treturn any_reference{Si::noexcept_string{}};\n\t\t}\n\t\tif (boost::range::equal(path.front(), Si::make_c_str_range(\"name\")))\n\t\t{\n\t\t\tauto name_begin = path.begin() + 1;\n\t\t\tif (name_begin == path.end())\n\t\t\t{\n\t\t\t\treturn any_reference{Si::noexcept_string{}};\n\t\t\t}\n\t\t\treturn any_reference{Si::noexcept_string(name_begin->begin(), name_begin->end())};\n\t\t}\n\t\tif (boost::range::equal(path.front(), Si::make_c_str_range(\"hash\")))\n\t\t{\n\t\t\tauto hash_begin = path.begin() + 1;\n\t\t\tif (hash_begin == path.end())\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\tauto digest = parse_digest(*hash_begin);\n\t\t\tif (!digest)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn any_reference{std::move(*digest)};\n\t\t}\n\t\treturn Si::none;\n\t}\n\n\tSi::optional parse_request_path(Si::memory_range const &path)\n\t{\n\t\tboost::optional const parsed_path = Si::http::parse_uri(path);\n\t\tif (!parsed_path || parsed_path->path.empty())\n\t\t{\n\t\t\treturn Si::none;\n\t\t}\n\n\t\tif (boost::range::equal(parsed_path->path.front(), Si::make_c_str_range(\"browse\")))\n\t\t{\n\t\t\tSi::optional ref = parse_any_reference(Si::make_iterator_range(parsed_path->path.begin() + 1, parsed_path->path.end()));\n\t\t\tif (!ref)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn parsed_request{browse_request{std::move(*ref)}};\n\t\t}\n\n\t\tif (boost::range::equal(parsed_path->path.front(), Si::make_c_str_range(\"get\")))\n\t\t{\n\t\t\tSi::optional ref = parse_any_reference(Si::make_iterator_range(parsed_path->path.begin() + 1, parsed_path->path.end()));\n\t\t\tif (!ref)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn parsed_request{get_request{std::move(*ref)}};\n\t\t}\n\n\t\treturn Si::none;\n\t}\n\n\tSi::http::response make_not_found_response()\n\t{\n\t\tSi::http::response header;\n\t\theader.http_version = \"HTTP\/1.0\";\n\t\theader.status = 404;\n\t\theader.status_text = \"Not Found\";\n\t\theader.arguments = Si::make_unique();\n\t\t(*header.arguments)[\"Connection\"] = \"close\";\n\t\treturn header;\n\t}\n\n\tstd::vector serialize_response(Si::http::response const &header)\n\t{\n\t\tstd::vector serialized;\n\t\tauto sink = Si::make_container_sink(serialized);\n\t\tSi::http::generate_response(sink, header);\n\t\treturn serialized;\n\t}\n\n\tenum class request_type\n\t{\n\t\tget,\n\t\thead\n\t};\n\n\ttemplate \n\trequest_type determine_request_type(String const &method)\n\t{\n\t\tif (boost::algorithm::iequals(\"HEAD\", method))\n\t\t{\n\t\t\treturn request_type::head;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn request_type::get;\n\t\t}\n\t}\n\n\ttemplate \n\tvoid respond(\n\t\tYieldContext &yield,\n\t\tMakeSender const &make_sender,\n\t\tSi::http::request const &header,\n\t\tfile_repository const &repository,\n\t\tdigest const &root)\n\t{\n\t\tauto const try_send = [&yield, &make_sender](std::vector const &data)\n\t\t{\n\t\t\tchar const * const begin = data.data();\n\t\t\tauto sender = make_sender(Si::make_memory_range(begin, begin + data.size()));\n\t\t\tauto result = yield.get_one(sender);\n\t\t\tassert(result);\n\t\t\treturn !*result;\n\t\t};\n\n\t\tauto const request = parse_request_path(Si::make_memory_range(header.path));\n\t\tif (!request)\n\t\t{\n\t\t\ttry_send(serialize_response(make_not_found_response()));\n\t\t\treturn;\n\t\t}\n\n\t\tstd::vector const * const found_file_locations = repository.find_location(\n\t\t\tSi::visit(\n\t\t\t\tSi::visit(\n\t\t\t\t\t*request,\n\t\t\t\t\t[](get_request const &request) -> any_reference const & { return request.what; },\n\t\t\t\t\t[](browse_request const &request) -> any_reference const & { return request.what; }\n\t\t\t\t),\n\t\t\t\t[](unknown_digest const &digest) { return digest; },\n\t\t\t\t[&root](Si::noexcept_string const &name)\n\t\t\t\t{\n\t\t\t\t\t\/\/TODO: resolve the name\n\t\t\t\t\tboost::ignore_unused(name);\n\t\t\t\t\treturn to_unknown_digest(root);\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t\tif (!found_file_locations)\n\t\t{\n\t\t\ttry_send(serialize_response(make_not_found_response()));\n\t\t\treturn;\n\t\t}\n\t\tassert(!found_file_locations->empty());\n\n\t\t\/\/just try the first entry for now\n\t\tauto &found_file = (*found_file_locations)[0];\n\n\t\t{\n\t\t\tSi::http::response response;\n\t\t\tresponse.arguments = Si::make_unique>();\n\t\t\tresponse.http_version = \"HTTP\/1.0\";\n\t\t\tresponse.status_text = \"OK\";\n\t\t\tresponse.status = 200;\n\t\t\t(*response.arguments)[\"Content-Length\"] = boost::lexical_cast(location_file_size(found_file));\n\t\t\t(*response.arguments)[\"Connection\"] = \"close\";\n\n\t\t\tstd::vector response_header = serialize_response(response);\n\t\t\tif (!try_send(response_header))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tswitch (determine_request_type(header.method))\n\t\t{\n\t\tcase request_type::get:\n\t\t\t{\n\t\t\t\tSi::visit(\n\t\t\t\t\t*request,\n\t\t\t\t\t[&try_send, &found_file, &yield](get_request const &) -> Si::nothing\n\t\t\t\t\t{\n\t\t\t\t\t\tauto reading = Si::make_thread_generator, Si::std_threading>([&](Si::push_context> &yield) -> Si::nothing\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tyield(Si::visit>(\n\t\t\t\t\t\t\t\tfound_file,\n\t\t\t\t\t\t\t\t[](file_system_location const &location)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\treturn Si::read_file(location.where.to_boost_path());\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t[](in_memory_location const &location)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\treturn location.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\treturn {};\n\t\t\t\t\t\t});\n\t\t\t\t\t\tauto const &body = yield.get_one(Si::ref(reading));\n\t\t\t\t\t\tif (!body)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn Si::nothing();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (body->size() != location_file_size(found_file))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn Si::nothing();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!try_send(*body))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn Si::nothing();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn Si::nothing();\n\t\t\t\t\t},\n\t\t\t\t\t[](browse_request const &)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/TODO\n\t\t\t\t\t\treturn Si::nothing();\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcase request_type::head:\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate \n\tvoid serve_client(\n\t\tYieldContext &yield,\n\t\tReceiveObservable &receive,\n\t\tMakeSender const &make_sender,\n\t\tShutdown const &shutdown,\n\t\tfile_repository const &repository,\n\t\tdigest const &root)\n\t{\n\t\tauto receive_sync = Si::virtualize_source(Si::make_observable_source(Si::ref(receive), yield));\n\t\tSi::received_from_socket_source receive_bytes(receive_sync);\n\t\tauto header = Si::http::parse_request(receive_bytes);\n\t\tif (!header)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\trespond(yield, make_sender, *header, repository, root);\n\t\tshutdown();\n\n\t\twhile (Si::get(receive_bytes))\n\t\t{\n\t\t}\n\t}\n\n\t\/\/TODO: use unique_observable\n\tusing session_handle = Si::shared_observable;\n\n\tstd::pair, content_type> directory_listing_to_json_bytes(directory_listing const &listing)\n\t{\n\t\tstd::vector bytes;\n\t\tserialize_json(Si::make_container_sink(bytes), listing);\n\t\treturn std::make_pair(std::move(bytes), json_listing_content_type);\n\t}\n\n\tvoid serve_directory(boost::filesystem::path const &served_dir)\n\t{\n\t\tboost::asio::io_service io;\n\t\tboost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080));\n\t\tauto clients = Si::asio::make_tcp_acceptor(&acceptor);\n\n\t\tstd::pair const scanned = scan_directory(served_dir, directory_listing_to_json_bytes, detail::hash_file);\n\t\tstd::cerr << \"Scan complete. Tree hash value \";\n\t\ttyped_reference const &root = scanned.second;\n\t\tprint(std::cerr, root);\n\t\tstd::cerr << \"\\n\";\n\t\tfile_repository const &files = scanned.first;\n\t\tdigest const &root_digest = root.referenced;\n\n\t\tSi::spawn_coroutine([&clients, &files, &root_digest](Si::spawn_context &yield)\n\t\t{\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tauto accepted = yield.get_one(Si::ref(clients));\n\t\t\t\tif (!accepted)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstd::shared_ptr socket = accepted->get(); \/\/TODO handle error\n\t\t\t\tauto prepare_socket = [socket, &files, &root_digest](Si::spawn_context &yield)\n\t\t\t\t{\n\t\t\t\t\tstd::array receive_buffer;\n\t\t\t\t\tauto received = Si::asio::make_reading_observable(*socket, Si::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size()));\n\t\t\t\t\tauto make_sender = [socket](Si::memory_range sent)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto sender = Si::asio::make_writing_observable(*socket);\n\t\t\t\t\t\tsender.set_buffer(sent);\n\t\t\t\t\t\treturn sender;\n\t\t\t\t\t};\n\t\t\t\t\tauto shutdown = [socket]()\n\t\t\t\t\t{\n\t\t\t\t\t\tboost::system::error_code ec; \/\/ignored\n\t\t\t\t\t\tsocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n\t\t\t\t\t};\n\t\t\t\t\tserve_client(yield, received, make_sender, shutdown, files, root_digest);\n\t\t\t\t};\n\t\t\t\tSi::spawn_coroutine(prepare_socket);\n\t\t\t}\n\t\t});\n\n\t\tio.run();\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tstd::string verb;\n\tboost::filesystem::path where = boost::filesystem::current_path();\n\n\tboost::program_options::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t    (\"help\", \"produce help message\")\n\t\t(\"verb\", boost::program_options::value(&verb), \"what to do (serve)\")\n\t\t(\"where\", boost::program_options::value(&where), \"which filesystem directory to use\")\n\t;\n\n\tboost::program_options::positional_options_description positional;\n\tpositional.add(\"verb\", 1);\n\tpositional.add(\"where\", 1);\n\tboost::program_options::variables_map vm;\n\ttry\n\t{\n\t\tboost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);\n\t}\n\tcatch (boost::program_options::error const &ex)\n\t{\n\t\tstd::cerr\n\t\t\t<< ex.what() << '\\n'\n\t\t\t<< desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tboost::program_options::notify(vm);\n\n\tif (vm.count(\"help\"))\n\t{\n\t    std::cerr << desc << \"\\n\";\n\t    return 1;\n\t}\n\n\tif (verb == \"serve\")\n\t{\n\t\tfileserver::serve_directory(where);\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tstd::cerr\n\t\t\t<< \"Unknown verb\\n\"\n\t\t\t<< desc << \"\\n\";\n\t    return 1;\n\t}\n}\nSi::visit can return void#ifdef _MSC_VER\n\/\/fixes \"fatal error C1189: #error :  WinSock.h has already been included\"\n#\tinclude \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fileserver\n{\n\tusing response_part = Si::memory_range;\n\n\ttypedef Si::fast_variant any_reference;\n\n\tstruct get_request\n\t{\n\t\tany_reference what;\n\t};\n\n\tstruct browse_request\n\t{\n\t\tany_reference what;\n\t};\n\n\ttypedef Si::fast_variant parsed_request;\n\n\ttemplate \n\tSi::optional parse_any_reference(PathElementRange const &path)\n\t{\n\t\tif (path.empty())\n\t\t{\n\t\t\treturn any_reference{Si::noexcept_string{}};\n\t\t}\n\t\tif (boost::range::equal(path.front(), Si::make_c_str_range(\"name\")))\n\t\t{\n\t\t\tauto name_begin = path.begin() + 1;\n\t\t\tif (name_begin == path.end())\n\t\t\t{\n\t\t\t\treturn any_reference{Si::noexcept_string{}};\n\t\t\t}\n\t\t\treturn any_reference{Si::noexcept_string(name_begin->begin(), name_begin->end())};\n\t\t}\n\t\tif (boost::range::equal(path.front(), Si::make_c_str_range(\"hash\")))\n\t\t{\n\t\t\tauto hash_begin = path.begin() + 1;\n\t\t\tif (hash_begin == path.end())\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\tauto digest = parse_digest(*hash_begin);\n\t\t\tif (!digest)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn any_reference{std::move(*digest)};\n\t\t}\n\t\treturn Si::none;\n\t}\n\n\tSi::optional parse_request_path(Si::memory_range const &path)\n\t{\n\t\tboost::optional const parsed_path = Si::http::parse_uri(path);\n\t\tif (!parsed_path || parsed_path->path.empty())\n\t\t{\n\t\t\treturn Si::none;\n\t\t}\n\n\t\tif (boost::range::equal(parsed_path->path.front(), Si::make_c_str_range(\"browse\")))\n\t\t{\n\t\t\tSi::optional ref = parse_any_reference(Si::make_iterator_range(parsed_path->path.begin() + 1, parsed_path->path.end()));\n\t\t\tif (!ref)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn parsed_request{browse_request{std::move(*ref)}};\n\t\t}\n\n\t\tif (boost::range::equal(parsed_path->path.front(), Si::make_c_str_range(\"get\")))\n\t\t{\n\t\t\tSi::optional ref = parse_any_reference(Si::make_iterator_range(parsed_path->path.begin() + 1, parsed_path->path.end()));\n\t\t\tif (!ref)\n\t\t\t{\n\t\t\t\treturn Si::none;\n\t\t\t}\n\t\t\treturn parsed_request{get_request{std::move(*ref)}};\n\t\t}\n\n\t\treturn Si::none;\n\t}\n\n\tSi::http::response make_not_found_response()\n\t{\n\t\tSi::http::response header;\n\t\theader.http_version = \"HTTP\/1.0\";\n\t\theader.status = 404;\n\t\theader.status_text = \"Not Found\";\n\t\theader.arguments = Si::make_unique();\n\t\t(*header.arguments)[\"Connection\"] = \"close\";\n\t\treturn header;\n\t}\n\n\tstd::vector serialize_response(Si::http::response const &header)\n\t{\n\t\tstd::vector serialized;\n\t\tauto sink = Si::make_container_sink(serialized);\n\t\tSi::http::generate_response(sink, header);\n\t\treturn serialized;\n\t}\n\n\tenum class request_type\n\t{\n\t\tget,\n\t\thead\n\t};\n\n\ttemplate \n\trequest_type determine_request_type(String const &method)\n\t{\n\t\tif (boost::algorithm::iequals(\"HEAD\", method))\n\t\t{\n\t\t\treturn request_type::head;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn request_type::get;\n\t\t}\n\t}\n\n\ttemplate \n\tvoid respond(\n\t\tYieldContext &yield,\n\t\tMakeSender const &make_sender,\n\t\tSi::http::request const &header,\n\t\tfile_repository const &repository,\n\t\tdigest const &root)\n\t{\n\t\tauto const try_send = [&yield, &make_sender](std::vector const &data)\n\t\t{\n\t\t\tchar const * const begin = data.data();\n\t\t\tauto sender = make_sender(Si::make_memory_range(begin, begin + data.size()));\n\t\t\tauto result = yield.get_one(sender);\n\t\t\tassert(result);\n\t\t\treturn !*result;\n\t\t};\n\n\t\tauto const request = parse_request_path(Si::make_memory_range(header.path));\n\t\tif (!request)\n\t\t{\n\t\t\ttry_send(serialize_response(make_not_found_response()));\n\t\t\treturn;\n\t\t}\n\n\t\tstd::vector const * const found_file_locations = repository.find_location(\n\t\t\tSi::visit(\n\t\t\t\tSi::visit(\n\t\t\t\t\t*request,\n\t\t\t\t\t[](get_request const &request) -> any_reference const & { return request.what; },\n\t\t\t\t\t[](browse_request const &request) -> any_reference const & { return request.what; }\n\t\t\t\t),\n\t\t\t\t[](unknown_digest const &digest) { return digest; },\n\t\t\t\t[&root](Si::noexcept_string const &name)\n\t\t\t\t{\n\t\t\t\t\t\/\/TODO: resolve the name\n\t\t\t\t\tboost::ignore_unused(name);\n\t\t\t\t\treturn to_unknown_digest(root);\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t\tif (!found_file_locations)\n\t\t{\n\t\t\ttry_send(serialize_response(make_not_found_response()));\n\t\t\treturn;\n\t\t}\n\t\tassert(!found_file_locations->empty());\n\n\t\t\/\/just try the first entry for now\n\t\tauto &found_file = (*found_file_locations)[0];\n\n\t\t{\n\t\t\tSi::http::response response;\n\t\t\tresponse.arguments = Si::make_unique>();\n\t\t\tresponse.http_version = \"HTTP\/1.0\";\n\t\t\tresponse.status_text = \"OK\";\n\t\t\tresponse.status = 200;\n\t\t\t(*response.arguments)[\"Content-Length\"] = boost::lexical_cast(location_file_size(found_file));\n\t\t\t(*response.arguments)[\"Connection\"] = \"close\";\n\n\t\t\tstd::vector response_header = serialize_response(response);\n\t\t\tif (!try_send(response_header))\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tswitch (determine_request_type(header.method))\n\t\t{\n\t\tcase request_type::get:\n\t\t\t{\n\t\t\t\tSi::visit(\n\t\t\t\t\t*request,\n\t\t\t\t\t[&try_send, &found_file, &yield](get_request const &)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto reading = Si::make_thread_generator, Si::std_threading>([&](Si::push_context> &yield) -> Si::nothing\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tyield(Si::visit>(\n\t\t\t\t\t\t\t\tfound_file,\n\t\t\t\t\t\t\t\t[](file_system_location const &location)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\treturn Si::read_file(location.where.to_boost_path());\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t[](in_memory_location const &location)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\treturn location.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t));\n\t\t\t\t\t\t\treturn {};\n\t\t\t\t\t\t});\n\t\t\t\t\t\tauto const &body = yield.get_one(Si::ref(reading));\n\t\t\t\t\t\tif (!body)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (body->size() != location_file_size(found_file))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttry_send(*body);\n\t\t\t\t\t},\n\t\t\t\t\t[](browse_request const &)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/TODO\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tcase request_type::head:\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate \n\tvoid serve_client(\n\t\tYieldContext &yield,\n\t\tReceiveObservable &receive,\n\t\tMakeSender const &make_sender,\n\t\tShutdown const &shutdown,\n\t\tfile_repository const &repository,\n\t\tdigest const &root)\n\t{\n\t\tauto receive_sync = Si::virtualize_source(Si::make_observable_source(Si::ref(receive), yield));\n\t\tSi::received_from_socket_source receive_bytes(receive_sync);\n\t\tauto header = Si::http::parse_request(receive_bytes);\n\t\tif (!header)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\trespond(yield, make_sender, *header, repository, root);\n\t\tshutdown();\n\n\t\twhile (Si::get(receive_bytes))\n\t\t{\n\t\t}\n\t}\n\n\t\/\/TODO: use unique_observable\n\tusing session_handle = Si::shared_observable;\n\n\tstd::pair, content_type> directory_listing_to_json_bytes(directory_listing const &listing)\n\t{\n\t\tstd::vector bytes;\n\t\tserialize_json(Si::make_container_sink(bytes), listing);\n\t\treturn std::make_pair(std::move(bytes), json_listing_content_type);\n\t}\n\n\tvoid serve_directory(boost::filesystem::path const &served_dir)\n\t{\n\t\tboost::asio::io_service io;\n\t\tboost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080));\n\t\tauto clients = Si::asio::make_tcp_acceptor(&acceptor);\n\n\t\tstd::pair const scanned = scan_directory(served_dir, directory_listing_to_json_bytes, detail::hash_file);\n\t\tstd::cerr << \"Scan complete. Tree hash value \";\n\t\ttyped_reference const &root = scanned.second;\n\t\tprint(std::cerr, root);\n\t\tstd::cerr << \"\\n\";\n\t\tfile_repository const &files = scanned.first;\n\t\tdigest const &root_digest = root.referenced;\n\n\t\tSi::spawn_coroutine([&clients, &files, &root_digest](Si::spawn_context &yield)\n\t\t{\n\t\t\tfor (;;)\n\t\t\t{\n\t\t\t\tauto accepted = yield.get_one(Si::ref(clients));\n\t\t\t\tif (!accepted)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstd::shared_ptr socket = accepted->get(); \/\/TODO handle error\n\t\t\t\tauto prepare_socket = [socket, &files, &root_digest](Si::spawn_context &yield)\n\t\t\t\t{\n\t\t\t\t\tstd::array receive_buffer;\n\t\t\t\t\tauto received = Si::asio::make_reading_observable(*socket, Si::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size()));\n\t\t\t\t\tauto make_sender = [socket](Si::memory_range sent)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto sender = Si::asio::make_writing_observable(*socket);\n\t\t\t\t\t\tsender.set_buffer(sent);\n\t\t\t\t\t\treturn sender;\n\t\t\t\t\t};\n\t\t\t\t\tauto shutdown = [socket]()\n\t\t\t\t\t{\n\t\t\t\t\t\tboost::system::error_code ec; \/\/ignored\n\t\t\t\t\t\tsocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);\n\t\t\t\t\t};\n\t\t\t\t\tserve_client(yield, received, make_sender, shutdown, files, root_digest);\n\t\t\t\t};\n\t\t\t\tSi::spawn_coroutine(prepare_socket);\n\t\t\t}\n\t\t});\n\n\t\tio.run();\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tstd::string verb;\n\tboost::filesystem::path where = boost::filesystem::current_path();\n\n\tboost::program_options::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t    (\"help\", \"produce help message\")\n\t\t(\"verb\", boost::program_options::value(&verb), \"what to do (serve)\")\n\t\t(\"where\", boost::program_options::value(&where), \"which filesystem directory to use\")\n\t;\n\n\tboost::program_options::positional_options_description positional;\n\tpositional.add(\"verb\", 1);\n\tpositional.add(\"where\", 1);\n\tboost::program_options::variables_map vm;\n\ttry\n\t{\n\t\tboost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(positional).run(), vm);\n\t}\n\tcatch (boost::program_options::error const &ex)\n\t{\n\t\tstd::cerr\n\t\t\t<< ex.what() << '\\n'\n\t\t\t<< desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tboost::program_options::notify(vm);\n\n\tif (vm.count(\"help\"))\n\t{\n\t    std::cerr << desc << \"\\n\";\n\t    return 1;\n\t}\n\n\tif (verb == \"serve\")\n\t{\n\t\tfileserver::serve_directory(where);\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\tstd::cerr\n\t\t\t<< \"Unknown verb\\n\"\n\t\t\t<< desc << \"\\n\";\n\t    return 1;\n\t}\n}\n<|endoftext|>"}
{"text":"\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU 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\n#include \n#include \n#include \n#include \n#include \n\nnamespace libbitcoin {\nnamespace server {\n\nstatic const auto domain = \"heartbeat\";\n\nusing namespace bc::config;\nusing namespace bc::protocol;\n\nstatic uint32_t to_milliseconds(uint16_t seconds)\n{\n    const auto milliseconds = static_cast(seconds) * 1000;\n    return std::min(milliseconds, max_uint32);\n};\n\n\/\/ Heartbeat is capped at ~ 25 days by signed\/millsecond conversions.\nheartbeat_service::heartbeat_service(zmq::authenticator& authenticator,\n    server_node& node, bool secure)\n  : worker(node.thread_pool()),\n    settings_(node.server_settings()),\n    period_(to_milliseconds(settings_.heartbeat_interval_seconds)),\n    authenticator_(authenticator),\n    secure_(secure)\n{\n}\n\n\/\/ Implement service as a publisher.\n\/\/ The publisher does not block if there are no subscribers or at high water.\nvoid heartbeat_service::work()\n{\n    zmq::socket publisher(authenticator_, zmq::socket::role::publisher);\n\n    \/\/ Bind socket to the worker endpoint.\n    if (!started(bind(publisher)))\n        return;\n\n    zmq::poller poller;\n    poller.add(publisher);\n\n    \/\/ Pick a random counter start, will wrap around at overflow.\n    auto count = static_cast(pseudo_random());\n\n    \/\/ We will not receive on the poller, we use its timer and context stop.\n    while (!poller.terminated() && !stopped())\n    {\n        poller.wait(period_);\n        publish(count++, publisher);\n    }\n\n    \/\/ Unbind the socket and exit this thread.\n    finished(unbind(publisher));\n}\n\n\/\/ Bind\/Unbind.\n\/\/-----------------------------------------------------------------------------\n\nbool heartbeat_service::bind(zmq::socket& publisher)\n{\n    const auto security = secure_ ? \"secure\" : \"public\";\n    const auto& endpoint = secure_ ? settings_.secure_heartbeat_endpoint :\n        settings_.public_heartbeat_endpoint;\n\n    if (!authenticator_.apply(publisher, domain, secure_))\n        return false;\n\n    const auto ec = publisher.bind(endpoint);\n\n    if (ec)\n    {\n        LOG_ERROR(LOG_SERVER)\n            << \"Failed to bind \" << security << \" heartbeat service to \"\n            << endpoint << \" : \" << ec.message();\n        return false;\n    }\n\n    LOG_INFO(LOG_SERVER)\n        << \"Bound \" << security << \" heartbeat service to \" << endpoint;\n    return true;\n}\n\nbool heartbeat_service::unbind(zmq::socket& publisher)\n{\n    const auto security = secure_ ? \"secure\" : \"public\";\n\n    \/\/ Don't log stop success.\n    if (publisher.stop())\n        return true;\n\n    LOG_ERROR(LOG_SERVER)\n        << \"Failed to disconnect \" << security << \" heartbeat worker.\";\n    return false;\n}\n\n\/\/ Publish Execution (integral worker).\n\/\/-----------------------------------------------------------------------------\n\nvoid heartbeat_service::publish(uint32_t count, zmq::socket& publisher)\n{\n    if (stopped())\n        return;\n\n    const auto security = secure_ ? \"secure\" : \"public\";\n\n    zmq::message message;\n    message.enqueue_little_endian(count);\n    auto ec = publisher.send(message);\n\n    if (ec == error::service_stopped)\n        return;\n\n    if (ec)\n    {\n        LOG_WARNING(LOG_SERVER)\n            << \"Failed to publish \" << security << \" heartbeat: \"\n            << ec.message();\n        return;\n    }\n\n    \/\/ This isn't actually a request, should probably update settings.\n    if (settings_.log_requests)\n        LOG_DEBUG(LOG_SERVER)\n            << \"Published \" << security << \" heartbeat [\" << count << \"].\";\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\nAdapt to bc prng changes.\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU 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\n#include \n#include \n#include \n#include \n#include \n\nnamespace libbitcoin {\nnamespace server {\n\nstatic const auto domain = \"heartbeat\";\n\nusing namespace bc::config;\nusing namespace bc::protocol;\n\nstatic uint32_t to_milliseconds(uint16_t seconds)\n{\n    const auto milliseconds = static_cast(seconds) * 1000;\n    return std::min(milliseconds, max_uint32);\n};\n\n\/\/ Heartbeat is capped at ~ 25 days by signed\/millsecond conversions.\nheartbeat_service::heartbeat_service(zmq::authenticator& authenticator,\n    server_node& node, bool secure)\n  : worker(node.thread_pool()),\n    settings_(node.server_settings()),\n    period_(to_milliseconds(settings_.heartbeat_interval_seconds)),\n    authenticator_(authenticator),\n    secure_(secure)\n{\n}\n\n\/\/ Implement service as a publisher.\n\/\/ The publisher does not block if there are no subscribers or at high water.\nvoid heartbeat_service::work()\n{\n    zmq::socket publisher(authenticator_, zmq::socket::role::publisher);\n\n    \/\/ Bind socket to the worker endpoint.\n    if (!started(bind(publisher)))\n        return;\n\n    zmq::poller poller;\n    poller.add(publisher);\n\n    \/\/ Pick a random counter start, will wrap around at overflow.\n    auto count = static_cast(pseudo_random(0, max_uint32));\n\n    \/\/ We will not receive on the poller, we use its timer and context stop.\n    while (!poller.terminated() && !stopped())\n    {\n        poller.wait(period_);\n        publish(count++, publisher);\n    }\n\n    \/\/ Unbind the socket and exit this thread.\n    finished(unbind(publisher));\n}\n\n\/\/ Bind\/Unbind.\n\/\/-----------------------------------------------------------------------------\n\nbool heartbeat_service::bind(zmq::socket& publisher)\n{\n    const auto security = secure_ ? \"secure\" : \"public\";\n    const auto& endpoint = secure_ ? settings_.secure_heartbeat_endpoint :\n        settings_.public_heartbeat_endpoint;\n\n    if (!authenticator_.apply(publisher, domain, secure_))\n        return false;\n\n    const auto ec = publisher.bind(endpoint);\n\n    if (ec)\n    {\n        LOG_ERROR(LOG_SERVER)\n            << \"Failed to bind \" << security << \" heartbeat service to \"\n            << endpoint << \" : \" << ec.message();\n        return false;\n    }\n\n    LOG_INFO(LOG_SERVER)\n        << \"Bound \" << security << \" heartbeat service to \" << endpoint;\n    return true;\n}\n\nbool heartbeat_service::unbind(zmq::socket& publisher)\n{\n    const auto security = secure_ ? \"secure\" : \"public\";\n\n    \/\/ Don't log stop success.\n    if (publisher.stop())\n        return true;\n\n    LOG_ERROR(LOG_SERVER)\n        << \"Failed to disconnect \" << security << \" heartbeat worker.\";\n    return false;\n}\n\n\/\/ Publish Execution (integral worker).\n\/\/-----------------------------------------------------------------------------\n\nvoid heartbeat_service::publish(uint32_t count, zmq::socket& publisher)\n{\n    if (stopped())\n        return;\n\n    const auto security = secure_ ? \"secure\" : \"public\";\n\n    zmq::message message;\n    message.enqueue_little_endian(count);\n    auto ec = publisher.send(message);\n\n    if (ec == error::service_stopped)\n        return;\n\n    if (ec)\n    {\n        LOG_WARNING(LOG_SERVER)\n            << \"Failed to publish \" << security << \" heartbeat: \"\n            << ec.message();\n        return;\n    }\n\n    \/\/ This isn't actually a request, should probably update settings.\n    if (settings_.log_requests)\n        LOG_DEBUG(LOG_SERVER)\n            << \"Published \" << security << \" heartbeat [\" << count << \"].\";\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<|endoftext|>"}
{"text":"\/\/\n\/\/ Created by salmon on 17-9-3.\n\/\/\n\n#include \"EngineObject.h\"\nnamespace simpla {\nnamespace engine {\nstruct EngineObject::pimpl_s {\n    std::mutex m_mutex_;\n    size_type m_click_ = 0;\n    size_type m_click_tag_ = 0;\n    bool m_is_initialized_ = false;\n    bool m_is_setup_ = false;\n};\nEngineObject::EngineObject() : m_pimpl_(new pimpl_s) {}\nEngineObject::~EngineObject() { Finalize(); }\nstd::shared_ptr EngineObject::Serialize() const { return base_type::Serialize(); }\nvoid EngineObject::Deserialize(std::shared_ptr const &cfg) {\n    ASSERT(!isSetUp());\n    Initialize();\n    base_type::Deserialize(cfg);\n};\nvoid EngineObject::lock() { m_pimpl_->m_mutex_.lock(); }\nvoid EngineObject::unlock() { m_pimpl_->m_mutex_.unlock(); }\nbool EngineObject::try_lock() { return m_pimpl_->m_mutex_.try_lock(); }\n\nsize_type EngineObject::GetTagCount() const { return m_pimpl_->m_click_tag_; }\nsize_type EngineObject::GetClickCount() const { return m_pimpl_->m_click_; }\n\nvoid EngineObject::Click() { ++m_pimpl_->m_click_; }\nvoid EngineObject::Tag() { m_pimpl_->m_click_tag_ = m_pimpl_->m_click_; }\nvoid EngineObject::ResetTag() { m_pimpl_->m_click_tag_ = (m_pimpl_->m_click_ = 0); }\n\nbool EngineObject::isModified() const { return m_pimpl_->m_click_tag_ != m_pimpl_->m_click_; }\nbool EngineObject::isInitialized() const { return m_pimpl_->m_is_initialized_; }\nbool EngineObject::isSetUp() const { return m_pimpl_->m_is_setup_; }\n\nvoid EngineObject::Push(std::shared_ptr const &data) {\n    ASSERT(isSetUp());\n    base_type::Push(data);\n    Click();\n}\nstd::shared_ptr EngineObject::Pop() {\n    Click();\n    return base_type::Pop();\n}\n\nvoid EngineObject::DoInitialize() {}\nvoid EngineObject::DoSetUp() {}\nvoid EngineObject::DoUpdate() {}\nvoid EngineObject::DoTearDown() { db()->Clear(); }\nvoid EngineObject::DoFinalize() {}\n\nvoid EngineObject::Initialize() {\n    if (!isInitialized()) {\n        DoInitialize();\n        Click();\n        m_pimpl_->m_is_initialized_ = true;\n    }\n}\nvoid EngineObject::SetUp() {\n    if (!isSetUp()) {\n        VERBOSE << std::setw(15) << \" Set Up : \" << std::setw(20) << std::left << GetName() << \" [ \" << TypeName()\n                << \" ]\";\n        PreSetUp(this);\n        DoSetUp();\n        PostSetUp(this);\n        Click();\n        m_pimpl_->m_is_setup_ = true;\n    }\n}\nvoid EngineObject::Update() {\n    SetUp();\n    if (isModified()) {\n        PreUpdate(this);\n        DoUpdate();\n        PostUpdate(this);\n        Tag();\n    }\n}\nvoid EngineObject::TearDown() {\n    if (isSetUp()) {\n        PreTearDown(this);\n        DoTearDown();\n        PostTearDown(this);\n        Click();\n        m_pimpl_->m_is_setup_ = false;\n        VERBOSE << std::setw(15) << \" Tear Down : \" << std::setw(20) << std::left << GetName() << \" [ \" << TypeName()\n                << \" ]\";\n    }\n};\nvoid EngineObject::Finalize() {\n    if (isInitialized()) {\n        TearDown();\n        DoFinalize();\n        ResetTag();\n        m_pimpl_->m_is_initialized_ = false;\n    }\n};\n}\n}  \/\/ namespace simplaengine test\/\/\n\/\/ Created by salmon on 17-9-3.\n\/\/\n\n#include \"EngineObject.h\"\nnamespace simpla {\nnamespace engine {\nstruct EngineObject::pimpl_s {\n    std::mutex m_mutex_;\n    size_type m_click_ = 0;\n    size_type m_click_tag_ = 0;\n    bool m_is_initialized_ = false;\n    bool m_is_setup_ = false;\n};\nEngineObject::EngineObject() : m_pimpl_(new pimpl_s) {}\nEngineObject::~EngineObject() { Finalize(); }\nstd::shared_ptr EngineObject::Serialize() const { return base_type::Serialize(); }\nvoid EngineObject::Deserialize(std::shared_ptr const &cfg) {\n    ASSERT(!isSetUp());\n    Initialize();\n    base_type::Deserialize(cfg);\n};\nvoid EngineObject::lock() { m_pimpl_->m_mutex_.lock(); }\nvoid EngineObject::unlock() { m_pimpl_->m_mutex_.unlock(); }\nbool EngineObject::try_lock() { return m_pimpl_->m_mutex_.try_lock(); }\n\nsize_type EngineObject::GetTagCount() const { return m_pimpl_->m_click_tag_; }\nsize_type EngineObject::GetClickCount() const { return m_pimpl_->m_click_; }\n\nvoid EngineObject::Click() { ++m_pimpl_->m_click_; }\nvoid EngineObject::Tag() { m_pimpl_->m_click_tag_ = m_pimpl_->m_click_; }\nvoid EngineObject::ResetTag() { m_pimpl_->m_click_tag_ = (m_pimpl_->m_click_ = 0); }\n\nbool EngineObject::isModified() const { return m_pimpl_->m_click_tag_ != m_pimpl_->m_click_; }\nbool EngineObject::isInitialized() const { return m_pimpl_->m_is_initialized_; }\nbool EngineObject::isSetUp() const { return m_pimpl_->m_is_setup_; }\n\nvoid EngineObject::Push(std::shared_ptr const &data) {\n    ASSERT(isSetUp());\n    base_type::Push(data);\n    Click();\n}\nstd::shared_ptr EngineObject::Pop() {\n    Click();\n    return base_type::Pop();\n}\n\nvoid EngineObject::DoInitialize() {}\nvoid EngineObject::DoSetUp() {}\nvoid EngineObject::DoUpdate() {}\nvoid EngineObject::DoTearDown() { db()->Clear(); }\nvoid EngineObject::DoFinalize() {}\n\nvoid EngineObject::Initialize() {\n    if (!isInitialized()) {\n        DoInitialize();\n        Click();\n        m_pimpl_->m_is_initialized_ = true;\n    }\n}\nvoid EngineObject::SetUp() {\n    if (!isSetUp()) {\n\n        VERBOSE << std::setw(15) << \" Set Up : \" << std::setw(20) << std::left << GetName() << \" [ \" << TypeName()\n                << \" ]\";\n        PreSetUp(this);\n        DoSetUp();\n        PostSetUp(this);\n        Click();\n        m_pimpl_->m_is_setup_ = true;\n    }\n}\nvoid EngineObject::Update() {\n    SetUp();\n    if (isModified()) {\n        PreUpdate(this);\n        DoUpdate();\n        PostUpdate(this);\n        Tag();\n    }\n}\nvoid EngineObject::TearDown() {\n    if (isSetUp()) {\n        PreTearDown(this);\n        DoTearDown();\n        PostTearDown(this);\n        Click();\n        m_pimpl_->m_is_setup_ = false;\n        VERBOSE << std::setw(15) << \" Tear Down : \" << std::setw(20) << std::left << GetName() << \" [ \" << TypeName()\n                << \" ]\";\n    }\n};\nvoid EngineObject::Finalize() {\n    if (isInitialized()) {\n        TearDown();\n        DoFinalize();\n        ResetTag();\n        m_pimpl_->m_is_initialized_ = false;\n    }\n};\n}\n}  \/\/ namespace simpla<|endoftext|>"}
{"text":"use pf for some places, fix docs from random access to possibly unordered access for multi assign<|endoftext|>"}
{"text":"Added test for a given size != 0<|endoftext|>"}
{"text":"\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are  permitted provided that the following conditions are met:\n *\n *  - Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  - Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include \n#include \n#include \n\n#include \"os\/os.h\"\n#include \"can_frame.h\"\n#include \"nmranet_config.h\"\n\n#include \"os\/TempFile.hxx\"\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/SimpleNodeInfoMockUserFile.hxx\"\n#include \"nmranet\/ConfiguredConsumer.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"config.hxx\"\n#include \"definitions.hxx\"\n\n#define SNIFF_ON_SERIAL\n\nextern const nmranet::NodeID NODE_ID;\n\nOVERRIDE_CONST(gc_generate_newlines, 1);\nOVERRIDE_CONST(main_thread_stack_size, 2500);\n\nnmranet::SimpleCanStack stack(NODE_ID);\n\nconst char *const nmranet::CONFIG_FILENAME = \"\/dev\/eeprom\";\nconst char *const nmranet::SNIP_DYNAMIC_FILENAME = nmranet::CONFIG_FILENAME;\n\nstatic_assert(nmranet::ConfigDef::size() <= 256, \"Need to adjust eeprom size\");\n\nGPIO_PIN(LED_GREEN, LedPin, F, 3);\nGPIO_PIN(LED_BLUE, LedPin, F, 2);\n\nGPIO_PIN(SW1, GpioInputPU, F, 4);\nGPIO_PIN(SW2, GpioInputPU, F, 0);\n\nnmranet::ConfigDef cfg(0);\n\nnmranet::ConfiguredConsumer consumer_red(\n    stack.node(), cfg.seg().consumers().entry<0>(), BLINKER_Pin());\nnmranet::ConfiguredConsumer consumer_green(\n    stack.node(), cfg.seg().consumers().entry<1>(), LED_GREEN_Pin());\nnmranet::ConfiguredConsumer consumer_blue(\n    stack.node(), cfg.seg().consumers().entry<2>(), LED_BLUE_Pin());\n\nnmranet::ConfiguredProducer producer_sw1(\n    stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());\nnmranet::ConfiguredProducer producer_sw2(\n    stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());\n\nnmranet::RefreshLoop loop(stack.node(), {producer_sw1.polling(), producer_sw2.polling()});\n\nnmranet::FileMemorySpace config_space(\n    nmranet::CONFIG_FILENAME, cfg.seg().size() + cfg.seg().offset());\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n    stack.memory_config_handler()->registry()->insert(\n        stack.node(), nmranet::MemoryConfigDefs::SPACE_CONFIG, &config_space);\n\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n    stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n\n\/\/ Enable this to add sniffing through the usb or serial port.\n#if defined(SNIFF_ON_USB)\n    stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n    stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n    stack.loop_executor();\n    return 0;\n}\nPrunes includes in main.cxx\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are  permitted provided that the following conditions are met:\n *\n *  - Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  - Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include \"os\/os.h\"\n#include \"nmranet_config.h\"\n\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/ConfiguredConsumer.hxx\"\n#include \"nmranet\/ConfiguredProducer.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"config.hxx\"\n\n#define SNIFF_ON_SERIAL\n\nextern const nmranet::NodeID NODE_ID;\n\nOVERRIDE_CONST(gc_generate_newlines, 1);\nOVERRIDE_CONST(main_thread_stack_size, 2500);\n\nnmranet::SimpleCanStack stack(NODE_ID);\n\nconst char *const nmranet::CONFIG_FILENAME = \"\/dev\/eeprom\";\nconst char *const nmranet::SNIP_DYNAMIC_FILENAME = nmranet::CONFIG_FILENAME;\n\nstatic_assert(nmranet::ConfigDef::size() <= 256, \"Need to adjust eeprom size\");\n\nGPIO_PIN(LED_GREEN, LedPin, F, 3);\nGPIO_PIN(LED_BLUE, LedPin, F, 2);\n\nGPIO_PIN(SW1, GpioInputPU, F, 4);\nGPIO_PIN(SW2, GpioInputPU, F, 0);\n\nnmranet::ConfigDef cfg(0);\n\nnmranet::ConfiguredConsumer consumer_red(\n    stack.node(), cfg.seg().consumers().entry<0>(), BLINKER_Pin());\nnmranet::ConfiguredConsumer consumer_green(\n    stack.node(), cfg.seg().consumers().entry<1>(), LED_GREEN_Pin());\nnmranet::ConfiguredConsumer consumer_blue(\n    stack.node(), cfg.seg().consumers().entry<2>(), LED_BLUE_Pin());\n\nnmranet::ConfiguredProducer producer_sw1(\n    stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());\nnmranet::ConfiguredProducer producer_sw2(\n    stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());\n\nnmranet::RefreshLoop loop(\n    stack.node(), {producer_sw1.polling(), producer_sw2.polling()});\n\nnmranet::FileMemorySpace config_space(\n    nmranet::CONFIG_FILENAME, cfg.seg().size() + cfg.seg().offset());\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n    stack.memory_config_handler()->registry()->insert(\n        stack.node(), nmranet::MemoryConfigDefs::SPACE_CONFIG, &config_space);\n\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n    stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n#if defined(SNIFF_ON_USB)\n    stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n    stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n    stack.loop_executor();\n    return 0;\n}\n<|endoftext|>"}
{"text":"\/***********************************************************************************************************************\n*                                                                                                                      *\n* SPLASH build system v0.2                                                                                             *\n*                                                                                                                      *\n* Copyright (c) 2016-2017 Andrew D. Zonenberg                                                                          *\n* All rights reserved.                                                                                                 *\n*                                                                                                                      *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *\n* following conditions are met:                                                                                        *\n*                                                                                                                      *\n*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *\n*      following disclaimer.                                                                                           *\n*                                                                                                                      *\n*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *\n*      following disclaimer in the documentation and\/or other materials provided with the distribution.                *\n*                                                                                                                      *\n*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *\n*      derived from this software without specific prior written permission.                                           *\n*                                                                                                                      *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *\n* POSSIBILITY OF SUCH DAMAGE.                                                                                          *\n*                                                                                                                      *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nYosysToolchain::YosysToolchain(string basepath)\n\t: FPGAToolchain(basepath, TOOLCHAIN_YOSYS)\n{\n\t\/\/Save version info\n\tstring sver = ShellCommand(basepath + \" -V\");\n\tsscanf(sver.c_str(), \"Yosys %8d.%8d+%8d\", &m_majorVersion, &m_minorVersion, &m_patchVersion);\n\n\tchar tmp[128];\n\tsnprintf(tmp, sizeof(tmp), \"Yosys %d.%d+%d\", m_majorVersion, m_minorVersion, m_patchVersion);\n\tm_stringVersion = tmp;\n\n\t\/\/Set list of target architectures\n\tFindArchitectures();\n\n\t\/\/File format suffixes\n\tm_fixes[\"netlist\"] = stringpair(\"\", \".json\");\n\tm_fixes[\"formal-netlist\"] = stringpair(\"\", \".smt2\");\n\tm_fixes[\"formal\"] = stringpair(\"\", \".txt\");\n\n\t\/\/Generate the hash based on the full git ID etc\n\tm_hash = sha256(sver);\n}\n\nYosysToolchain::~YosysToolchain()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Search for other toolchains\n\nvoid YosysToolchain::FindArchitectures()\n{\n\t\/\/We always support formal targets b\/c those don't need any extra tools\n\tm_triplets.emplace(\"generic-formal\");\n\n\t\/\/Get our search path\n\tvector dirs;\n\tParseSearchPath(dirs);\n\n\t\/\/TODO: IceStorm stuff\n\n\t\/\/Look for gp4par\n\tm_gp4parPath = FindExecutable(\"gp4par\", dirs);\n\tif(m_gp4parPath != \"\")\n\t{\n\t\tm_triplets.emplace(\"greenpak4-slg46140\");\n\t\tm_triplets.emplace(\"greenpak4-slg46620\");\n\t\tm_triplets.emplace(\"greenpak4-slg46621\");\n\t}\n}\n\n\/**\n\t@brief Look for a binary anywhere in the search path\n *\/\nstring YosysToolchain::FindExecutable(string fname, vector& dirs)\n{\n\tfor(auto dir : dirs)\n\t{\n\t\tstring path = dir + \"\/\" + fname;\n\t\tif(DoesFileExist(path))\n\t\t\treturn path;\n\t}\n\n\treturn \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Toolchain properties\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Actual compilation\n\nbool YosysToolchain::Build(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\t\/\/Switch on the triplet to decide how to handle it\n\tif(triplet == \"generic-formal\")\n\t{\n\t\t\/\/If the output file is a .smt2 we're building for the model checker\n\t\tif(fname.find(\".smt2\") != string::npos)\n\t\t\treturn BuildFormal(triplet, sources, fname, flags, outputs, stdout);\n\n\t\t\/\/Otherwise we're running the checker\n\t\telse\n\t\t\treturn CheckModel(triplet, sources, fname, flags, outputs, stdout);\n\t}\n\telse if(triplet.find(\"greenpak4-\") == 0)\n\t\treturn BuildGreenPAK(triplet, sources, fname, flags, outputs, stdout);\n\n\telse\n\t{\n\t\tstdout = string(\"ERROR: YosysToolchain doesn't know how to build for architecture \") + triplet + \"\\n\";\n\t\treturn false;\n\t}\n}\n\n\/**\n\t@brief Synthesize for formal verification\n *\/\nbool YosysToolchain::BuildFormal(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"\";\n\n\tLogDebug(\"YosysToolchain::BuildFormal for %s\\n\", fname.c_str());\n\tstring base = GetBasenameOfFileWithoutExt(fname);\n\n\t\/\/TODO: Flags\n\tfor(auto f : flags)\n\t{\n\t\t\/*\n\t\tif(f.GetType() != BuildFlag::TYPE_DEFINE)\n\t\t\tcontinue;\n\t\tdefines += f.GetFlag() + \"=\" + f.GetArgs() + \" \";\n\t\t*\/\n\t\tstdout += string(\"WARNING: YosysToolchain::BuildFormal: Don't know what to do with flag \") +\n\t\t\tstatic_cast(f) + \"\\n\";\n\t}\n\n\t\/\/Write the synthesis script\n\tstring ys_file = base + \".ys\";\n\tstring smt_file = base + \".smt2\";\n\tFILE* fp = fopen(ys_file.c_str(), \"w\");\n\tif(!fp)\n\t{\n\t\tstdout += string(\"ERROR: Failed to create synthesis script \") + ys_file + \"\\n\";\n\t\treturn false;\n\t}\n\tfor(auto s : sources)\n\t{\n\t\t\/\/Ignore any non-Verilog sources\n\t\tif(s.find(\".v\") != string::npos)\n\t\t\tfprintf(fp, \"read_verilog -formal \\\"%s\\\"\\n\", s.c_str());\n\t}\n\tfprintf(fp, \"prep -nordff -top %s\\n\", base.c_str());\n\tfprintf(fp, \"check -assert\\n\");\n\tfprintf(fp, \"write_smt2 -wires %s\", smt_file.c_str());\n\tfclose(fp);\n\n\t\/\/Run synthesis\n\tstring report_file = base + \".log\";\n\tstring cmdline = m_basepath + \" -t -l \" + report_file + \" \" + ys_file;\n\tstring output;\n\tbool ok = (0 == ShellCommand(cmdline, output));\n\n\t\/\/Crunch the synthesis log\n\tCrunchYosysLog(output, stdout);\n\n\t\/\/Done, return results\n\tif(DoesFileExist(report_file))\n\t\toutputs[report_file] = sha256_file(report_file);\n\tif(DoesFileExist(smt_file))\n\t\toutputs[smt_file] = sha256_file(smt_file);\n\telse\n\t{\n\t\tstdout += \"ERROR: No SMT file produced\\n\";\n\t\treturn false;\n\t}\n\n\treturn ok;\n}\n\n\/**\n\t@brief Synthesize for formal verification\n *\/\nbool YosysToolchain::CheckModel(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"\";\n\n\t\/\/TODO: Separate options to run base case and temporal induction??\n\n\t\/\/Look up the constraints and source file\n\tstring smt_file;\n\tstring constraints_file;\n\tfor(auto s : sources)\n\t{\n\t\tif(s.find(\".smtc\") != string::npos)\n\t\t\tconstraints_file = s;\n\t\telse if(s.find(\".smt2\") != string::npos)\n\t\t\tsmt_file = s;\n\t\telse\n\t\t{\n\t\t\tstdout = \"ERROR: YosysToolchain::CheckModel: Don't know what to do with \" + s  + \"\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif(smt_file == \"\")\n\t{\n\t\tstdout = \"ERROR: YosysToolchain: no SMT file specified\\n\";\n\t\treturn false;\n\t}\n\n\tstring report_file = GetBasenameOfFile(fname);\n\n\t\/\/Format the bulk of the command line (beginning and end vary)\n\tstring num_steps = \"20\";\n\tfor(auto f : flags)\n\t{\n\t\t\/\/TODO: Flags\n\n\t\t\/*\n\t\tif(f.GetType() != BuildFlag::TYPE_DEFINE)\n\t\t\tcontinue;\n\t\tdefines += f.GetFlag() + \"=\" + f.GetArgs() + \" \";\n\t\t*\/\n\t\tstdout += string(\"WARNING: YosysToolchain::BuildFormal: Don't know what to do with flag \") +\n\t\t\tstatic_cast(f) + \"\\n\";\n\t}\n\tstring basename = GetBasenameOfFileWithoutExt(fname);\n\tstring vcd_file = basename + \".vcd\";\n\tstring cmdline_meat = \"-t \" + num_steps + \" --dump-vcd \" + vcd_file + \" \";\n\tif(constraints_file != \"\")\n\t\tcmdline_meat += string(\"--smtc \") + constraints_file + \" \";\n\tcmdline_meat += smt_file + \" \";\n\n\t\/\/Run the inductive step first. Counterintuitive since it's meaningless w\/o the base case!\n\t\/\/But it usually runs a lot faster than the base case, and the vast majority of errors can be caught here.\n\t\/\/This means we can skip the time-consuming base case and iterate faster during verification.\n\tstring cmdline = m_basepath + \"-smtbmc -i \" + cmdline_meat;\n\tstring report_induction;\n\tbool ok = (0 == ShellCommand(cmdline, report_induction));\n\n\t\/\/Run the base case (append to the existing report)\n\tcmdline = m_basepath + \"-smtbmc \" + cmdline_meat;\n\tstring report_base;\n\tok &= (0 == ShellCommand(cmdline, report_base));\n\n\t\/\/Write to the report file (TODO: be able to upload this directly?)\n\tstring report = report_induction + \"\\n\\n\\n\\n\\n\" + report_base;\n\tPutFileContents(report_file, report);\n\n\t\/\/Filter the results and print to stdout clientside\n\tCrunchSMTLog(report, stdout);\n\n\t\/\/Upload the report\n\toutputs[report_file] = sha256_file(report_file);\n\tif(DoesFileExist(vcd_file))\n\t\toutputs[vcd_file] = sha256_file(vcd_file);\n\n\t\/\/Done\n\treturn ok;\n}\n\nbool YosysToolchain::BuildGreenPAK(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"ERROR: YosysToolchain::BuildGreenPAK() not implemented\\n\";\n\treturn false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Reporting helpers\n\n\/**\n\t@brief Read through the report and figure out what's interesting\n *\/\nvoid YosysToolchain::CrunchYosysLog(const string& log, string& stdout)\n{\n\t\/\/Split the report up into lines\n\tvector lines;\n\tParseLines(log, lines);\n\n\tfor(auto line : lines)\n\t{\n\t\t\/\/TODO: Blacklist messages of no importance\n\n\t\t\/\/Filter out errors and warnings\n\t\tif(line.find(\"Warning:\") == 0)\n\t\t\tstdout += line + \"\\n\";\n\t\tif(line.find(\"Error:\") == 0)\n\t\t\tstdout += line + \"\\n\";\n\t}\n}\n\nvoid YosysToolchain::CrunchSMTLog(const string& log, string& stdout)\n{\n\t\/\/Split the report up into lines\n\tvector lines;\n\tParseLines(log, lines);\n\n\tbool unfilter = false;\n\tfor(auto line : lines)\n\t{\n\t\tif(line.find(\"Assert failed\") != string::npos)\n\t\t\tstdout += string(\"ERROR: \") + line + \"\\n\";\n\n\t\tif(line.find(\"Traceback (most recent call last)\") != string::npos)\n\t\t{\n\t\t\tstdout += \"ERROR: Something went wrong (got a stack trace)\\n\";\n\t\t\tunfilter = true;\n\t\t}\n\n\t\t\/\/If we stopped filtering, copy everything\n\t\tif(unfilter)\n\t\t\tstdout += line + \"\\n\";\n\t}\n}\nsplashcore: Yosys toolchain now has extension for bitstream. TODO: make this depend on architecture?\/***********************************************************************************************************************\n*                                                                                                                      *\n* SPLASH build system v0.2                                                                                             *\n*                                                                                                                      *\n* Copyright (c) 2016-2017 Andrew D. Zonenberg                                                                          *\n* All rights reserved.                                                                                                 *\n*                                                                                                                      *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *\n* following conditions are met:                                                                                        *\n*                                                                                                                      *\n*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *\n*      following disclaimer.                                                                                           *\n*                                                                                                                      *\n*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *\n*      following disclaimer in the documentation and\/or other materials provided with the distribution.                *\n*                                                                                                                      *\n*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *\n*      derived from this software without specific prior written permission.                                           *\n*                                                                                                                      *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *\n* POSSIBILITY OF SUCH DAMAGE.                                                                                          *\n*                                                                                                                      *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nYosysToolchain::YosysToolchain(string basepath)\n\t: FPGAToolchain(basepath, TOOLCHAIN_YOSYS)\n{\n\t\/\/Save version info\n\tstring sver = ShellCommand(basepath + \" -V\");\n\tsscanf(sver.c_str(), \"Yosys %8d.%8d+%8d\", &m_majorVersion, &m_minorVersion, &m_patchVersion);\n\n\tchar tmp[128];\n\tsnprintf(tmp, sizeof(tmp), \"Yosys %d.%d+%d\", m_majorVersion, m_minorVersion, m_patchVersion);\n\tm_stringVersion = tmp;\n\n\t\/\/Set list of target architectures\n\tFindArchitectures();\n\n\t\/\/File format suffixes\n\tm_fixes[\"netlist\"] = stringpair(\"\", \".json\");\n\tm_fixes[\"formal-netlist\"] = stringpair(\"\", \".smt2\");\n\tm_fixes[\"formal\"] = stringpair(\"\", \".txt\");\n\tm_fixes[\"bitstream\"] = stringpair(\"\", \".txt\");\n\n\t\/\/Generate the hash based on the full git ID etc\n\tm_hash = sha256(sver);\n}\n\nYosysToolchain::~YosysToolchain()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Search for other toolchains\n\nvoid YosysToolchain::FindArchitectures()\n{\n\t\/\/We always support formal targets b\/c those don't need any extra tools\n\tm_triplets.emplace(\"generic-formal\");\n\n\t\/\/Get our search path\n\tvector dirs;\n\tParseSearchPath(dirs);\n\n\t\/\/TODO: IceStorm stuff\n\n\t\/\/Look for gp4par\n\tm_gp4parPath = FindExecutable(\"gp4par\", dirs);\n\tif(m_gp4parPath != \"\")\n\t{\n\t\tm_triplets.emplace(\"greenpak4-slg46140\");\n\t\tm_triplets.emplace(\"greenpak4-slg46620\");\n\t\tm_triplets.emplace(\"greenpak4-slg46621\");\n\t}\n}\n\n\/**\n\t@brief Look for a binary anywhere in the search path\n *\/\nstring YosysToolchain::FindExecutable(string fname, vector& dirs)\n{\n\tfor(auto dir : dirs)\n\t{\n\t\tstring path = dir + \"\/\" + fname;\n\t\tif(DoesFileExist(path))\n\t\t\treturn path;\n\t}\n\n\treturn \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Toolchain properties\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Actual compilation\n\nbool YosysToolchain::Build(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\t\/\/Switch on the triplet to decide how to handle it\n\tif(triplet == \"generic-formal\")\n\t{\n\t\t\/\/If the output file is a .smt2 we're building for the model checker\n\t\tif(fname.find(\".smt2\") != string::npos)\n\t\t\treturn BuildFormal(triplet, sources, fname, flags, outputs, stdout);\n\n\t\t\/\/Otherwise we're running the checker\n\t\telse\n\t\t\treturn CheckModel(triplet, sources, fname, flags, outputs, stdout);\n\t}\n\telse if(triplet.find(\"greenpak4-\") == 0)\n\t\treturn BuildGreenPAK(triplet, sources, fname, flags, outputs, stdout);\n\n\telse\n\t{\n\t\tstdout = string(\"ERROR: YosysToolchain doesn't know how to build for architecture \") + triplet + \"\\n\";\n\t\treturn false;\n\t}\n}\n\n\/**\n\t@brief Synthesize for formal verification\n *\/\nbool YosysToolchain::BuildFormal(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"\";\n\n\tLogDebug(\"YosysToolchain::BuildFormal for %s\\n\", fname.c_str());\n\tstring base = GetBasenameOfFileWithoutExt(fname);\n\n\t\/\/TODO: Flags\n\tfor(auto f : flags)\n\t{\n\t\t\/*\n\t\tif(f.GetType() != BuildFlag::TYPE_DEFINE)\n\t\t\tcontinue;\n\t\tdefines += f.GetFlag() + \"=\" + f.GetArgs() + \" \";\n\t\t*\/\n\t\tstdout += string(\"WARNING: YosysToolchain::BuildFormal: Don't know what to do with flag \") +\n\t\t\tstatic_cast(f) + \"\\n\";\n\t}\n\n\t\/\/Write the synthesis script\n\tstring ys_file = base + \".ys\";\n\tstring smt_file = base + \".smt2\";\n\tFILE* fp = fopen(ys_file.c_str(), \"w\");\n\tif(!fp)\n\t{\n\t\tstdout += string(\"ERROR: Failed to create synthesis script \") + ys_file + \"\\n\";\n\t\treturn false;\n\t}\n\tfor(auto s : sources)\n\t{\n\t\t\/\/Ignore any non-Verilog sources\n\t\tif(s.find(\".v\") != string::npos)\n\t\t\tfprintf(fp, \"read_verilog -formal \\\"%s\\\"\\n\", s.c_str());\n\t}\n\tfprintf(fp, \"prep -nordff -top %s\\n\", base.c_str());\n\tfprintf(fp, \"check -assert\\n\");\n\tfprintf(fp, \"write_smt2 -wires %s\", smt_file.c_str());\n\tfclose(fp);\n\n\t\/\/Run synthesis\n\tstring report_file = base + \".log\";\n\tstring cmdline = m_basepath + \" -t -l \" + report_file + \" \" + ys_file;\n\tstring output;\n\tbool ok = (0 == ShellCommand(cmdline, output));\n\n\t\/\/Crunch the synthesis log\n\tCrunchYosysLog(output, stdout);\n\n\t\/\/Done, return results\n\tif(DoesFileExist(report_file))\n\t\toutputs[report_file] = sha256_file(report_file);\n\tif(DoesFileExist(smt_file))\n\t\toutputs[smt_file] = sha256_file(smt_file);\n\telse\n\t{\n\t\tstdout += \"ERROR: No SMT file produced\\n\";\n\t\treturn false;\n\t}\n\n\treturn ok;\n}\n\n\/**\n\t@brief Synthesize for formal verification\n *\/\nbool YosysToolchain::CheckModel(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"\";\n\n\t\/\/TODO: Separate options to run base case and temporal induction??\n\n\t\/\/Look up the constraints and source file\n\tstring smt_file;\n\tstring constraints_file;\n\tfor(auto s : sources)\n\t{\n\t\tif(s.find(\".smtc\") != string::npos)\n\t\t\tconstraints_file = s;\n\t\telse if(s.find(\".smt2\") != string::npos)\n\t\t\tsmt_file = s;\n\t\telse\n\t\t{\n\t\t\tstdout = \"ERROR: YosysToolchain::CheckModel: Don't know what to do with \" + s  + \"\\n\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tif(smt_file == \"\")\n\t{\n\t\tstdout = \"ERROR: YosysToolchain: no SMT file specified\\n\";\n\t\treturn false;\n\t}\n\n\tstring report_file = GetBasenameOfFile(fname);\n\n\t\/\/Format the bulk of the command line (beginning and end vary)\n\tstring num_steps = \"20\";\n\tfor(auto f : flags)\n\t{\n\t\t\/\/TODO: Flags\n\n\t\t\/*\n\t\tif(f.GetType() != BuildFlag::TYPE_DEFINE)\n\t\t\tcontinue;\n\t\tdefines += f.GetFlag() + \"=\" + f.GetArgs() + \" \";\n\t\t*\/\n\t\tstdout += string(\"WARNING: YosysToolchain::BuildFormal: Don't know what to do with flag \") +\n\t\t\tstatic_cast(f) + \"\\n\";\n\t}\n\tstring basename = GetBasenameOfFileWithoutExt(fname);\n\tstring vcd_file = basename + \".vcd\";\n\tstring cmdline_meat = \"-t \" + num_steps + \" --dump-vcd \" + vcd_file + \" \";\n\tif(constraints_file != \"\")\n\t\tcmdline_meat += string(\"--smtc \") + constraints_file + \" \";\n\tcmdline_meat += smt_file + \" \";\n\n\t\/\/Run the inductive step first. Counterintuitive since it's meaningless w\/o the base case!\n\t\/\/But it usually runs a lot faster than the base case, and the vast majority of errors can be caught here.\n\t\/\/This means we can skip the time-consuming base case and iterate faster during verification.\n\tstring cmdline = m_basepath + \"-smtbmc -i \" + cmdline_meat;\n\tstring report_induction;\n\tbool ok = (0 == ShellCommand(cmdline, report_induction));\n\n\t\/\/Run the base case (append to the existing report)\n\tcmdline = m_basepath + \"-smtbmc \" + cmdline_meat;\n\tstring report_base;\n\tok &= (0 == ShellCommand(cmdline, report_base));\n\n\t\/\/Write to the report file (TODO: be able to upload this directly?)\n\tstring report = report_induction + \"\\n\\n\\n\\n\\n\" + report_base;\n\tPutFileContents(report_file, report);\n\n\t\/\/Filter the results and print to stdout clientside\n\tCrunchSMTLog(report, stdout);\n\n\t\/\/Upload the report\n\toutputs[report_file] = sha256_file(report_file);\n\tif(DoesFileExist(vcd_file))\n\t\toutputs[vcd_file] = sha256_file(vcd_file);\n\n\t\/\/Done\n\treturn ok;\n}\n\nbool YosysToolchain::BuildGreenPAK(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& stdout)\n{\n\tstdout = \"ERROR: YosysToolchain::BuildGreenPAK() not implemented\\n\";\n\treturn false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Reporting helpers\n\n\/**\n\t@brief Read through the report and figure out what's interesting\n *\/\nvoid YosysToolchain::CrunchYosysLog(const string& log, string& stdout)\n{\n\t\/\/Split the report up into lines\n\tvector lines;\n\tParseLines(log, lines);\n\n\tfor(auto line : lines)\n\t{\n\t\t\/\/TODO: Blacklist messages of no importance\n\n\t\t\/\/Filter out errors and warnings\n\t\tif(line.find(\"Warning:\") == 0)\n\t\t\tstdout += line + \"\\n\";\n\t\tif(line.find(\"Error:\") == 0)\n\t\t\tstdout += line + \"\\n\";\n\t}\n}\n\nvoid YosysToolchain::CrunchSMTLog(const string& log, string& stdout)\n{\n\t\/\/Split the report up into lines\n\tvector lines;\n\tParseLines(log, lines);\n\n\tbool unfilter = false;\n\tfor(auto line : lines)\n\t{\n\t\tif(line.find(\"Assert failed\") != string::npos)\n\t\t\tstdout += string(\"ERROR: \") + line + \"\\n\";\n\n\t\tif(line.find(\"Traceback (most recent call last)\") != string::npos)\n\t\t{\n\t\t\tstdout += \"ERROR: Something went wrong (got a stack trace)\\n\";\n\t\t\tunfilter = true;\n\t\t}\n\n\t\t\/\/If we stopped filtering, copy everything\n\t\tif(unfilter)\n\t\t\tstdout += line + \"\\n\";\n\t}\n}\n<|endoftext|>"}
{"text":"\/*-\n * Copyright (c) 2016 Frederic Culot \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer\n *    in this position and unchanged.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"window.h\"\n\n\nnamespace portal {\nnamespace gfx {\n\nclass Window::Impl {\n public:\n  WINDOW* win {nullptr};\n\n  Size  size;\n  Point pos, posStatus;\n  Style style;\n\n  \/\/ XXX Add a Point posCursor to allow for text spanning multi lines\n\n  bool initialized() const;\n  void create();\n  void resize();\n  void move();\n  void destroy();\n  void draw() const;\n  void drawBorders() const;\n  void print(const std::string& msg);\n};\n\n\nWindow::Window() : impl_{new Impl} {\n  impl_->create();\n}\n\nWindow::Window(const Size& size, const Point& pos, const Style& style)\n  : impl_{new Impl} {\n  impl_->size = size;\n  impl_->pos = pos;\n  impl_->style = style;\n  impl_->create();\n  impl_->draw();\n}\n\nWindow::~Window() {\n  impl_->destroy();\n}\n\nvoid Window::setSize(const Size& size) {\n  if (impl_->size != size) {\n    impl_->size = size;\n    impl_->resize();\n  }\n}\n\nvoid Window::setPosition(const Point& pos) {\n  if (impl_->pos != pos) {\n    impl_->pos = pos;\n    impl_->move();\n  }\n}\n\nvoid Window::setStyle(const Style& style) {\n  impl_->style = style;\n  impl_->drawBorders();\n}\n\nSize Window::size() const {\n  return impl_->size;\n}\n\nPoint Window::position() const {\n  return impl_->pos;\n}\n\nStyle Window::style() const {\n  return impl_->style;\n}\n\n  \/\/ XXX use provided style instead of class one\nvoid Window::print(const std::string& msg, const Style& style) {\n  if (impl_->style.color != Style::Color::none) {\n    wattron(impl_->win, COLOR_PAIR(impl_->style.color));\n  }\n  impl_->print(msg);\n  if (impl_->style.color != Style::Color::none) {\n    wattroff(impl_->win, COLOR_PAIR(impl_->style.color));\n  }\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::print(int c, const Point& pos, const Style& style) const {\n  int color =\n    style.color != Style::Color::none ? style.color : impl_->style.color;\n  wattron(impl_->win, COLOR_PAIR(color));\n  if (!pos.isNull()) {\n    wmove(impl_->win, pos.y(), pos.x());\n  }\n  waddch(impl_->win, c);\n  wattroff(impl_->win, COLOR_PAIR(color));\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::printStatus(const std::string& status, const Style& style) const {\n  int statusLength = status.length();\n  int xpos = impl_->size.width() - statusLength - 8;\n  int ypos = impl_->size.height() - 1;\n  impl_->posStatus.setX(xpos);\n  impl_->posStatus.setY(ypos);\n  mvwaddch(impl_->win, ypos, xpos++, ACS_RTEE);\n  mvwaddch(impl_->win, ypos, xpos++, ' ');\n  wattron(impl_->win, COLOR_PAIR(style.color) | style.cursesAttrs());\n  mvwaddstr(impl_->win, ypos, xpos, status.c_str());\n  wattroff(impl_->win, COLOR_PAIR(style.color) | style.cursesAttrs());\n  xpos += statusLength;\n  mvwaddch(impl_->win, ypos, xpos++, ' ');\n  mvwaddch(impl_->win, ypos, xpos, ACS_LTEE);\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::setStatusStyle(int xpos, int len, const Style& style) const {\n  mvwchgat(impl_->win,\n           impl_->posStatus.y(),\n           impl_->posStatus.x() + xpos + 2,\n           len,\n           style.cursesAttrs(),\n           style.color,\n           nullptr);\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::clearStatus() const {\n  impl_->posStatus.reset();\n  impl_->drawBorders();\n}\n\nvoid Window::draw() const {\n  impl_->draw();\n}\n\nvoid Window::clear() {\n  werase(impl_->win);\n  wmove(impl_->win, 0, 0);\n  impl_->draw();\n}\n\nbool Window::Impl::initialized() const {\n  return win != nullptr;\n}\n\nvoid Window::Impl::create() {\n  if (initialized()) {\n    throw std::runtime_error(\"Window::Impl::create() - Object already initialized\");\n  }\n  win = newwin(size.height(), size.width(), pos.y(), pos.x());\n  drawBorders();\n}\n\nvoid Window::Impl::resize() {\n  wresize(win, size.height(), size.width());\n}\n\nvoid Window::Impl::move() {\n  mvwin(win, pos.y(), pos.x());\n}\n\nvoid Window::Impl::destroy() {\n  if (!initialized()) {\n    throw std::runtime_error(\"Window::Impl::destroy() - Object already destroyed\");\n  }\n  delwin(win);\n}\n\nvoid Window::Impl::draw() const {\n  wnoutrefresh(win);\n}\n\nvoid Window::Impl::drawBorders() const {\n  \/\/ If a status is displayed (ie its position is not null), then we\n  \/\/ must not override it by drawing the border, hence the following\n  \/\/ test on posStatus.\n  if (style.borders && posStatus.isNull()) {\n    box(win, 0, 0);\n  }\n}\n\nvoid Window::Impl::print(const std::string& msg) {\n  int offset = style.borders ? 1 : 0;\n  mvwaddstr(win, offset, offset, msg.c_str());\n}\n\n}\n}\nRestore applyStyle method to underline search prompt\/*-\n * Copyright (c) 2016 Frederic Culot \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer\n *    in this position and unchanged.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"window.h\"\n\n\nnamespace portal {\nnamespace gfx {\n\nclass Window::Impl {\n public:\n  WINDOW* win {nullptr};\n\n  Size  size;\n  Point pos, posStatus;\n  Style style;\n\n  \/\/ XXX Add a Point posCursor to allow for text spanning multi lines\n\n  bool initialized() const;\n  void create();\n  void resize();\n  void move();\n  void destroy();\n  void draw() const;\n  void applyStyle() const;\n  void drawBorders() const;\n  void print(const std::string& msg);\n};\n\n\nWindow::Window() : impl_{new Impl} {\n  impl_->create();\n}\n\nWindow::Window(const Size& size, const Point& pos, const Style& style)\n  : impl_{new Impl} {\n  impl_->size = size;\n  impl_->pos = pos;\n  impl_->style = style;\n  impl_->create();\n  impl_->draw();\n}\n\nWindow::~Window() {\n  impl_->destroy();\n}\n\nvoid Window::setSize(const Size& size) {\n  if (impl_->size != size) {\n    impl_->size = size;\n    impl_->resize();\n  }\n}\n\nvoid Window::setPosition(const Point& pos) {\n  if (impl_->pos != pos) {\n    impl_->pos = pos;\n    impl_->move();\n  }\n}\n\nvoid Window::setStyle(const Style& style) {\n  impl_->style = style;\n  impl_->drawBorders();\n}\n\nSize Window::size() const {\n  return impl_->size;\n}\n\nPoint Window::position() const {\n  return impl_->pos;\n}\n\nStyle Window::style() const {\n  return impl_->style;\n}\n\n  \/\/ XXX use provided style instead of class one\nvoid Window::print(const std::string& msg, const Style& style) {\n  if (impl_->style.color != Style::Color::none) {\n    wattron(impl_->win, COLOR_PAIR(impl_->style.color));\n  }\n  impl_->print(msg);\n  if (impl_->style.color != Style::Color::none) {\n    wattroff(impl_->win, COLOR_PAIR(impl_->style.color));\n  }\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::print(int c, const Point& pos, const Style& style) const {\n  int color =\n    style.color != Style::Color::none ? style.color : impl_->style.color;\n  wattron(impl_->win, COLOR_PAIR(color));\n  if (!pos.isNull()) {\n    wmove(impl_->win, pos.y(), pos.x());\n  }\n  waddch(impl_->win, c);\n  wattroff(impl_->win, COLOR_PAIR(color));\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::printStatus(const std::string& status, const Style& style) const {\n  int statusLength = status.length();\n  int xpos = impl_->size.width() - statusLength - 8;\n  int ypos = impl_->size.height() - 1;\n  impl_->posStatus.setX(xpos);\n  impl_->posStatus.setY(ypos);\n  mvwaddch(impl_->win, ypos, xpos++, ACS_RTEE);\n  mvwaddch(impl_->win, ypos, xpos++, ' ');\n  wattron(impl_->win, COLOR_PAIR(style.color) | style.cursesAttrs());\n  mvwaddstr(impl_->win, ypos, xpos, status.c_str());\n  wattroff(impl_->win, COLOR_PAIR(style.color) | style.cursesAttrs());\n  xpos += statusLength;\n  mvwaddch(impl_->win, ypos, xpos++, ' ');\n  mvwaddch(impl_->win, ypos, xpos, ACS_LTEE);\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::setStatusStyle(int xpos, int len, const Style& style) const {\n  mvwchgat(impl_->win,\n           impl_->posStatus.y(),\n           impl_->posStatus.x() + xpos + 2,\n           len,\n           style.cursesAttrs(),\n           style.color,\n           nullptr);\n  wnoutrefresh(impl_->win);\n}\n\nvoid Window::clearStatus() const {\n  impl_->posStatus.reset();\n  impl_->drawBorders();\n}\n\nvoid Window::draw() const {\n  impl_->draw();\n}\n\nvoid Window::clear() {\n  werase(impl_->win);\n  wmove(impl_->win, 0, 0);\n  impl_->draw();\n}\n\nbool Window::Impl::initialized() const {\n  return win != nullptr;\n}\n\nvoid Window::Impl::create() {\n  if (initialized()) {\n    throw std::runtime_error(\"Window::Impl::create() - Object already initialized\");\n  }\n  win = newwin(size.height(), size.width(), pos.y(), pos.x());\n  drawBorders();\n}\n\nvoid Window::Impl::resize() {\n  wresize(win, size.height(), size.width());\n}\n\nvoid Window::Impl::move() {\n  mvwin(win, pos.y(), pos.x());\n}\n\nvoid Window::Impl::destroy() {\n  if (!initialized()) {\n    throw std::runtime_error(\"Window::Impl::destroy() - Object already destroyed\");\n  }\n  delwin(win);\n}\n\nvoid Window::Impl::draw() const {\n  applyStyle();\n  wnoutrefresh(win);\n}\n\nvoid Window::Impl::applyStyle() const {\n  if (style.underline) {\n    mvwchgat(win, 0, 0, size.width(), A_UNDERLINE, 0, nullptr);\n  }\n}\n\nvoid Window::Impl::drawBorders() const {\n  \/\/ If a status is displayed (ie its position is not null), then we\n  \/\/ must not override it by drawing the border, hence the following\n  \/\/ test on posStatus.\n  if (style.borders && posStatus.isNull()) {\n    box(win, 0, 0);\n  }\n}\n\nvoid Window::Impl::print(const std::string& msg) {\n  int offset = style.borders ? 1 : 0;\n  mvwaddstr(win, offset, offset, msg.c_str());\n}\n\n}\n}\n<|endoftext|>"}
{"text":"#include \"xdr++.h\"\n\n#include \n\n#include \n#include \n\nbool xdr(XDR* xdrs, std::string& s)\n{\n\tchar* p;\n\tint32_t size, pad;\n\tchar buf[BUFSIZ], zeros[] = { 0, 0, 0, 0 };\n\tstd::ostringstream ss;\n\n\tswitch (xdrs->x_op) {\n\tcase XDR_ENCODE:\n\t\tp = const_cast(s.c_str());\n\t\tsize = s.length();\n\t\tpad = (size | 0x03) - size + 1;\n\t\treturn\t   xdrs->x_ops->x_putint32(xdrs, &size)\n\t\t\t&& xdrs->x_ops->x_putbytes(xdrs, s.c_str(), size)\n\t\t\t&& xdrs->x_ops->x_putbytes(xdrs, zeros, pad);\n\n\tcase XDR_DECODE:\n\t\tif (!xdrs->x_ops->x_getint32(xdrs, &size))\n\t\t\treturn false;\n\t\tpad = (size | 0x03) - size + 1;\n\t\tp = buf;\n\t\twhile (size) {\n\t\t\tuint32_t sz = size > sizeof (buf) ? sizeof (buf) : size;\n\t\t\tif (!xdrs->x_ops->x_getbytes(xdrs, p, sz))\n\t\t\t\treturn false;\n\t\t\tss.write(p, sz);\n\t\t\tsize -= sz;\n\t\t}\n\t\tif (!xdrs->x_ops->x_getbytes(xdrs, p, pad))\n\t\t\treturn false;\n\t\ts = ss.str();\n\t\treturn true;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn false;\n}\n\nnamespace {\n\n\tbool_t xdr_getlong_callback(XDR* xdrs, long* lp)\n\t{\n\t\tint32_t v;\n\t\tbool ret = static_cast(xdrs)->get(v);\n\t\tif (ret)\n\t\t\t*lp = v;\n\t\treturn ret;\n\t}\n\n\tbool_t xdr_putlong_callback(XDR* xdrs, const long* lp)\n\t{\n\t\tint32_t v = *lp;\n\t\treturn static_cast(xdrs)->put(v);\n\t}\n\n\tbool_t xdr_getbytes_callback(XDR* xdrs, caddr_t addr, u_int len)\n\t{\n\t\treturn static_cast(xdrs)->get(addr, len);\n\t}\n\n\tbool_t xdr_putbytes_callback(XDR* xdrs, const char* addr, u_int len)\n\t{\n\t\treturn static_cast(xdrs)->put(addr, len);\n\t}\n\n\tu_int xdr_getpostn_callback(const XDR* xdrs)\n\t{\n\t\treturn static_cast(xdrs)->get_position();\n\t}\n\n\tbool_t xdr_setpostn_callback(XDR* xdrs, u_int pos)\n\t{\n\t\treturn static_cast(xdrs)->set_position(pos);\n\t}\n\n\tint32_t* xdr_inline_callback(XDR* xdrs, u_int len)\n\t{\n\t\treturn reinterpret_cast(static_cast(xdrs)->get_inline(len));\n\t}\n\n\tvoid xdr_destroy_callback(XDR* xdrs)\n\t{\n\t}\n\n\tbool_t xdr_getint32_callback(XDR* xdrs, int32_t* ip)\n\t{\n\t\treturn static_cast(xdrs)->get(*ip);\n\t}\n\n\tbool_t xdr_putint32_callback(XDR* xdrs, const int32_t* ip)\n\t{\n\t\treturn static_cast(xdrs)->put(*ip);\n\t}\n\n\tstruct XDR::xdr_ops xdr_base_ops = {\n\t\t&xdr_getlong_callback,\n\t\t&xdr_putlong_callback,\n\t\t&xdr_getbytes_callback,\n\t\t&xdr_putbytes_callback,\n\t\t&xdr_getpostn_callback,\n\t\t&xdr_setpostn_callback,\n\t\t&xdr_inline_callback,\n\t\t&xdr_destroy_callback,\n\t\t&xdr_getint32_callback,\n\t\t&xdr_putint32_callback\n\t};\n\n}\n\nXDR_Base::\nXDR_Base(xdr_op op)\n{\n\tx_op = op;\n\tx_ops = &xdr_base_ops;\n\tx_public = 0;\n\tx_private = 0;\n\tx_base = 0;\n\tx_handy = 0;\n}\n\nbool XDR_Base::\nget(int32_t& v)\n{\n\tint32_t tmp;\n\tbool ret = get(reinterpret_cast(&tmp), sizeof (tmp));\n\tif (ret)\n\t\tv = htonl(tmp);\n\treturn ret;\n}\n\nbool XDR_Base::\nput(int32_t v)\n{\n\tv = htonl(v);\n\treturn put(reinterpret_cast(&v), sizeof (v));\n}\nInclude  instead of #include \"xdr++.h\"\n\n#include \n\n#include \n#include \n#include \n\nbool xdr(XDR* xdrs, std::string& s)\n{\n\tchar* p;\n\tint32_t size, pad;\n\tchar buf[BUFSIZ], zeros[] = { 0, 0, 0, 0 };\n\tstd::ostringstream ss;\n\n\tswitch (xdrs->x_op) {\n\tcase XDR_ENCODE:\n\t\tp = const_cast(s.c_str());\n\t\tsize = s.length();\n\t\tpad = (size | 0x03) - size + 1;\n\t\treturn\t   xdrs->x_ops->x_putint32(xdrs, &size)\n\t\t\t&& xdrs->x_ops->x_putbytes(xdrs, s.c_str(), size)\n\t\t\t&& xdrs->x_ops->x_putbytes(xdrs, zeros, pad);\n\n\tcase XDR_DECODE:\n\t\tif (!xdrs->x_ops->x_getint32(xdrs, &size))\n\t\t\treturn false;\n\t\tpad = (size | 0x03) - size + 1;\n\t\tp = buf;\n\t\twhile (size) {\n\t\t\tuint32_t sz = size > sizeof (buf) ? sizeof (buf) : size;\n\t\t\tif (!xdrs->x_ops->x_getbytes(xdrs, p, sz))\n\t\t\t\treturn false;\n\t\t\tss.write(p, sz);\n\t\t\tsize -= sz;\n\t\t}\n\t\tif (!xdrs->x_ops->x_getbytes(xdrs, p, pad))\n\t\t\treturn false;\n\t\ts = ss.str();\n\t\treturn true;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn false;\n}\n\nnamespace {\n\n\tbool_t xdr_getlong_callback(XDR* xdrs, long* lp)\n\t{\n\t\tint32_t v;\n\t\tbool ret = static_cast(xdrs)->get(v);\n\t\tif (ret)\n\t\t\t*lp = v;\n\t\treturn ret;\n\t}\n\n\tbool_t xdr_putlong_callback(XDR* xdrs, const long* lp)\n\t{\n\t\tint32_t v = *lp;\n\t\treturn static_cast(xdrs)->put(v);\n\t}\n\n\tbool_t xdr_getbytes_callback(XDR* xdrs, caddr_t addr, u_int len)\n\t{\n\t\treturn static_cast(xdrs)->get(addr, len);\n\t}\n\n\tbool_t xdr_putbytes_callback(XDR* xdrs, const char* addr, u_int len)\n\t{\n\t\treturn static_cast(xdrs)->put(addr, len);\n\t}\n\n\tu_int xdr_getpostn_callback(const XDR* xdrs)\n\t{\n\t\treturn static_cast(xdrs)->get_position();\n\t}\n\n\tbool_t xdr_setpostn_callback(XDR* xdrs, u_int pos)\n\t{\n\t\treturn static_cast(xdrs)->set_position(pos);\n\t}\n\n\tint32_t* xdr_inline_callback(XDR* xdrs, u_int len)\n\t{\n\t\treturn reinterpret_cast(static_cast(xdrs)->get_inline(len));\n\t}\n\n\tvoid xdr_destroy_callback(XDR* xdrs)\n\t{\n\t}\n\n\tbool_t xdr_getint32_callback(XDR* xdrs, int32_t* ip)\n\t{\n\t\treturn static_cast(xdrs)->get(*ip);\n\t}\n\n\tbool_t xdr_putint32_callback(XDR* xdrs, const int32_t* ip)\n\t{\n\t\treturn static_cast(xdrs)->put(*ip);\n\t}\n\n\tstruct XDR::xdr_ops xdr_base_ops = {\n\t\t&xdr_getlong_callback,\n\t\t&xdr_putlong_callback,\n\t\t&xdr_getbytes_callback,\n\t\t&xdr_putbytes_callback,\n\t\t&xdr_getpostn_callback,\n\t\t&xdr_setpostn_callback,\n\t\t&xdr_inline_callback,\n\t\t&xdr_destroy_callback,\n\t\t&xdr_getint32_callback,\n\t\t&xdr_putint32_callback\n\t};\n\n}\n\nXDR_Base::\nXDR_Base(xdr_op op)\n{\n\tx_op = op;\n\tx_ops = &xdr_base_ops;\n\tx_public = 0;\n\tx_private = 0;\n\tx_base = 0;\n\tx_handy = 0;\n}\n\nbool XDR_Base::\nget(int32_t& v)\n{\n\tint32_t tmp;\n\tbool ret = get(reinterpret_cast(&tmp), sizeof (tmp));\n\tif (ret)\n\t\tv = htonl(tmp);\n\treturn ret;\n}\n\nbool XDR_Base::\nput(int32_t v)\n{\n\tv = htonl(v);\n\treturn put(reinterpret_cast(&v), sizeof (v));\n}\n<|endoftext|>"}
{"text":"\/\/ ChangeAliasPswd.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"ChangeAliasPswd.h\"\n\n\/\/ CChangeAliasPswd dialog\n\nIMPLEMENT_DYNAMIC(CChangeAliasPswd, CPWDialog)\n\nCChangeAliasPswd::CChangeAliasPswd(CWnd* pParent \/*=NULL*\/)\n\t: CPWDialog(CChangeAliasPswd::IDD, pParent)\n{\n}\n\nCChangeAliasPswd::~CChangeAliasPswd()\n{\n}\n\nvoid CChangeAliasPswd::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialog::DoDataExchange(pDX);\n\n  DDX_Text(pDX, IDC_STATIC_BASE, m_BaseEntry);\n}\n\nBEGIN_MESSAGE_MAP(CChangeAliasPswd, CDialog)\n  ON_BN_CLICKED(IDC_CHANGEBASEPSWD, OnChangeBasePswd)\n  ON_BN_CLICKED(IDC_CHANGEALIASPSWD, OnChangeAliasPswd)\nEND_MESSAGE_MAP()\n\n\/\/ CChangeAliasPswd message handlers\n\nvoid CChangeAliasPswd::OnChangeBasePswd()\n{\n  CPWDialog::EndDialog(CHANGEBASE);\n}\n\nvoid CChangeAliasPswd::OnChangeAliasPswd()\n{\n  CPWDialog::EndDialog(CHANGEALIAS);\n}\nMissing copyright header - found by finding source not updated during 2010->2011 change\/*\n* Copyright (c) 2003-2011 Rony Shapiro .\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/\/ ChangeAliasPswd.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"ChangeAliasPswd.h\"\n\n\/\/ CChangeAliasPswd dialog\n\nIMPLEMENT_DYNAMIC(CChangeAliasPswd, CPWDialog)\n\nCChangeAliasPswd::CChangeAliasPswd(CWnd* pParent \/*=NULL*\/)\n\t: CPWDialog(CChangeAliasPswd::IDD, pParent)\n{\n}\n\nCChangeAliasPswd::~CChangeAliasPswd()\n{\n}\n\nvoid CChangeAliasPswd::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialog::DoDataExchange(pDX);\n\n  DDX_Text(pDX, IDC_STATIC_BASE, m_BaseEntry);\n}\n\nBEGIN_MESSAGE_MAP(CChangeAliasPswd, CDialog)\n  ON_BN_CLICKED(IDC_CHANGEBASEPSWD, OnChangeBasePswd)\n  ON_BN_CLICKED(IDC_CHANGEALIASPSWD, OnChangeAliasPswd)\nEND_MESSAGE_MAP()\n\n\/\/ CChangeAliasPswd message handlers\n\nvoid CChangeAliasPswd::OnChangeBasePswd()\n{\n  CPWDialog::EndDialog(CHANGEBASE);\n}\n\nvoid CChangeAliasPswd::OnChangeAliasPswd()\n{\n  CPWDialog::EndDialog(CHANGEALIAS);\n}\n<|endoftext|>"}
{"text":"#ifndef NET_INET4_HPP\n#define NET_INET4_HPP\n\n#include  \/\/ panic()\n#include  \/\/ 107: auto& eth0 = Dev::eth(0);\n#include \n#include \n#include \n#include \n#include \n#include \"ip4\/udp.hpp\"\n#include \"dns\/client.hpp\"\n#include \n#include \n#include \n\n#include \n\nnamespace net {\n  \n  \/** A complete IP4 network stack *\/\n  template \n  class Inet4 : public Inet{\n  public:\n    \n    inline const Ethernet::addr& link_addr() override \n    { return eth_.mac(); }\n    \n    inline Ethernet& link() override\n    { return eth_; }    \n    \n    inline const IP4::addr& ip_addr() override \n    { return ip4_addr_; }\n\n    inline const IP4::addr& netmask() override \n    { return netmask_; }\n    \n    inline const IP4::addr& router() override \n    { return router_; }\n    \n    inline IP4& ip_obj() override\n    { return ip4_; }\n    \n    \/** Get the TCP-object belonging to this stack *\/\n    inline TCP& tcp() override { debug(\" Returning tcp-reference to %p \\n\",&tcp_); return tcp_; }\n        \n    \/** Get the UDP-object belonging to this stack *\/\n    inline UDP& udp() override { return udp_; }\n\n    \/** Get the DHCP client (if any) *\/\n    inline std::shared_ptr dhclient() override { return dhcp_;  }\n    \n    \/** Create a Packet, with a preallocated buffer.\n\t@param size : the \"size\" reported by the allocated packet. \n\t@note as of v0.6.3 this has no effect other than to force the size to be\n\tset explicitly by the caller. \n\t@todo make_shared will allocate with new. This is fast in IncludeOS,\n\t(no context switch for sbrk) but consider overloading operator new.\n    *\/\n    inline Packet_ptr createPacket(size_t size) override {\n      \/\/ Create a release delegate, for returning buffers\n      auto release = BufferStore::release_del::from\n\t(nic_.bufstore());\n      \/\/ Create the packet, using  buffer and .\n      return std::make_shared(bufstore_.get_offset_buffer(), \n\t\t\t\t      bufstore_.offset_bufsize(), size, release);\n    }\n    \n    \/\/ We have to ask the Nic for the MTU\n    virtual inline uint16_t MTU() const override\n    { return nic_.MTU(); }\n    \n    \/**\n     * @func  a delegate that provides a hostname and its address, which is 0 if the\n     * name @hostname was not found. Note: Test with INADDR_ANY for a 0-address.\n    **\/\n    inline virtual void\n    resolve(const std::string& hostname,\n            resolve_func  func) override\n    {\n      dns.resolve(this->dns_server, hostname, func);\n    }\n    \n    inline virtual void\n    set_dns_server(IP4::addr server) override\n    {\n      this->dns_server = server;\n    }\n    \n    \/** We don't want to copy or move an IP-stack. It's tied to a device. *\/\n    Inet4(Inet4&) = delete;\n    Inet4(Inet4&&) = delete;\n    Inet4& operator=(Inet4) = delete;\n    Inet4 operator=(Inet4&&) = delete;\n    \n    \/** Initialize with static IP \/ netmask *\/\n    Inet4(Nic& nic, IP4::addr ip, IP4::addr netmask); \n    \n    \/** Initialize with DHCP  *\/\n    Inet4(Nic& nic); \n    \n  private:\n    virtual void\n    network_config(IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns) override\n    {\n      INFO(\"Inet4\", \"Reconfiguring network. New IP: %s\", addr.str().c_str());\n      this->ip4_addr_  = addr;\n      this->netmask_   = nmask;\n      this->router_    = router;\n      this->dns_server = dns;\n    }\n    \n    IP4::addr ip4_addr_;\n    IP4::addr netmask_;\n    IP4::addr router_;\n    IP4::addr dns_server;\n    \n    \/\/ This is the actual stack\n    Nic& nic_;\n    Ethernet eth_;\n    Arp arp_;\n    IP4  ip4_;\n    ICMP icmp_;\n    UDP  udp_;\n    TCP tcp_;\n    \/\/ we need this to store the cache per-stack\n    DNSClient dns;\n    \n    std::shared_ptr dhcp_{};\n    BufferStore& bufstore_;\n  };\n}\n\n#include \"inet4.inc\"\n\n#endif\nInet::network_config made public#ifndef NET_INET4_HPP\n#define NET_INET4_HPP\n\n#include  \/\/ panic()\n#include  \/\/ 107: auto& eth0 = Dev::eth(0);\n#include \n#include \n#include \n#include \n#include \n#include \"ip4\/udp.hpp\"\n#include \"dns\/client.hpp\"\n#include \n#include \n#include \n\n#include \n\nnamespace net {\n  \n  \/** A complete IP4 network stack *\/\n  template \n  class Inet4 : public Inet{\n  public:\n    \n    inline const Ethernet::addr& link_addr() override \n    { return eth_.mac(); }\n    \n    inline Ethernet& link() override\n    { return eth_; }    \n    \n    inline const IP4::addr& ip_addr() override \n    { return ip4_addr_; }\n\n    inline const IP4::addr& netmask() override \n    { return netmask_; }\n    \n    inline const IP4::addr& router() override \n    { return router_; }\n    \n    inline IP4& ip_obj() override\n    { return ip4_; }\n    \n    \/** Get the TCP-object belonging to this stack *\/\n    inline TCP& tcp() override { debug(\" Returning tcp-reference to %p \\n\",&tcp_); return tcp_; }\n        \n    \/** Get the UDP-object belonging to this stack *\/\n    inline UDP& udp() override { return udp_; }\n\n    \/** Get the DHCP client (if any) *\/\n    inline std::shared_ptr dhclient() override { return dhcp_;  }\n    \n    \/** Create a Packet, with a preallocated buffer.\n\t@param size : the \"size\" reported by the allocated packet. \n\t@note as of v0.6.3 this has no effect other than to force the size to be\n\tset explicitly by the caller. \n\t@todo make_shared will allocate with new. This is fast in IncludeOS,\n\t(no context switch for sbrk) but consider overloading operator new.\n    *\/\n    inline Packet_ptr createPacket(size_t size) override {\n      \/\/ Create a release delegate, for returning buffers\n      auto release = BufferStore::release_del::from\n\t(nic_.bufstore());\n      \/\/ Create the packet, using  buffer and .\n      return std::make_shared(bufstore_.get_offset_buffer(), \n\t\t\t\t      bufstore_.offset_bufsize(), size, release);\n    }\n    \n    \/\/ We have to ask the Nic for the MTU\n    virtual inline uint16_t MTU() const override\n    { return nic_.MTU(); }\n    \n    \/**\n     * @func  a delegate that provides a hostname and its address, which is 0 if the\n     * name @hostname was not found. Note: Test with INADDR_ANY for a 0-address.\n    **\/\n    inline virtual void\n    resolve(const std::string& hostname,\n            resolve_func  func) override\n    {\n      dns.resolve(this->dns_server, hostname, func);\n    }\n    \n    inline virtual void\n    set_dns_server(IP4::addr server) override\n    {\n      this->dns_server = server;\n    }\n    \n    \/** We don't want to copy or move an IP-stack. It's tied to a device. *\/\n    Inet4(Inet4&) = delete;\n    Inet4(Inet4&&) = delete;\n    Inet4& operator=(Inet4) = delete;\n    Inet4 operator=(Inet4&&) = delete;\n    \n    \/** Initialize with static IP \/ netmask *\/\n    Inet4(Nic& nic, IP4::addr ip, IP4::addr netmask); \n    \n    \/** Initialize with DHCP  *\/\n    Inet4(Nic& nic); \n    \n    virtual void\n    network_config(IP4::addr addr, IP4::addr nmask, IP4::addr router, IP4::addr dns) override\n    {\n      INFO(\"Inet4\", \"Reconfiguring network. New IP: %s\", addr.str().c_str());\n      this->ip4_addr_  = addr;\n      this->netmask_   = nmask;\n      this->router_    = router;\n      this->dns_server = dns;\n    }\n\n  private:    \n\n    IP4::addr ip4_addr_;\n    IP4::addr netmask_;\n    IP4::addr router_;\n    IP4::addr dns_server;\n    \n    \/\/ This is the actual stack\n    Nic& nic_;\n    Ethernet eth_;\n    Arp arp_;\n    IP4  ip4_;\n    ICMP icmp_;\n    UDP  udp_;\n    TCP tcp_;\n    \/\/ we need this to store the cache per-stack\n    DNSClient dns;\n    \n    std::shared_ptr dhcp_{};\n    BufferStore& bufstore_;\n  };\n}\n\n#include \"inet4.inc\"\n\n#endif\n<|endoftext|>"}
{"text":"#ifndef TEST_UNIT_UTIL_HPP\n#define TEST_UNIT_UTIL_HPP\n\n#include \n#include \n#include \n#include \n\n#define EXPECT_MATRIX_EQ(A, B)                       \\\n  {                                                  \\\n    const Eigen::MatrixXd& A_eval = A;               \\\n    const Eigen::MatrixXd& B_eval = B;               \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows());         \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols());         \\\n    for (int i = 0; i < A_eval.size(); i++)          \\\n        EXPECT_EQ(A_eval(i), B_eval(i));             \\\n  }\n\n#define EXPECT_MATRIX_FLOAT_EQ(A, B)                 \\\n  {                                                  \\\n    const Eigen::MatrixXd& A_eval = A;               \\\n    const Eigen::MatrixXd& B_eval = B;               \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows());         \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols());         \\\n    for (int i = 0; i < A_eval.size(); i++)          \\\n        EXPECT_FLOAT_EQ(A_eval(i), B_eval(i));       \\\n  }\n\n#define EXPECT_STD_VECTOR_FLOAT_EQ(A, B) \\\n  EXPECT_EQ(A.size(), B.size());         \\\n  for (int i = 0; i < A.size(); ++i)     \\\n    EXPECT_FLOAT_EQ(A[i], B[i]);\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA)              \\\n  {                                                  \\\n    const Eigen::MatrixXd& A_eval = A;               \\\n    const Eigen::MatrixXd& B_eval = B;               \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows());         \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols());         \\\n    for (int i = 0; i < A_eval.size(); i++)          \\\n      EXPECT_FLOAT_EQ(A_eval(i), B_eval(i), DELTA);  \\\n  }\n\n#define EXPECT_THROW_MSG_WITH_COUNT(expr, T_e, msg, count) \\\n  EXPECT_THROW(expr, T_e);                                 \\\n  try {                                                    \\\n    expr;                                                  \\\n  } catch (const T_e& e) {                                 \\\n    EXPECT_EQ(count, count_matches(msg, e.what()))         \\\n        << \"expected message: \" << msg << std::endl        \\\n        << \"found message:    \" << e.what();               \\\n  }\n\n#define EXPECT_THROW_MSG(expr, T_e, msg) \\\n  EXPECT_THROW_MSG_WITH_COUNT(expr, T_e, msg, 1)\n\nint count_matches(const std::string& target, const std::string& s) {\n  if (target.size() == 0)\n    return -1;  \/\/ error\n  int count = 0;\n  for (size_t pos = 0; (pos = s.find(target, pos)) != std::string::npos;\n       pos += target.size())\n    ++count;\n  return count;\n}\n\nnamespace test {\ntemplate \nvoid expect_same_type() {\n  bool b = std::is_same::value;\n  EXPECT_TRUE(b);\n}\n}  \/\/ namespace test\n\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef TEST_UNIT_UTIL_HPP\n#define TEST_UNIT_UTIL_HPP\n\n#include \n#include \n#include \n#include \n\n#define EXPECT_MATRIX_EQ(A, B)               \\\n  {                                          \\\n    const Eigen::MatrixXd& A_eval = A;       \\\n    const Eigen::MatrixXd& B_eval = B;       \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows()); \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols()); \\\n    for (int i = 0; i < A_eval.size(); i++)  \\\n      EXPECT_EQ(A_eval(i), B_eval(i));       \\\n  }\n\n#define EXPECT_MATRIX_FLOAT_EQ(A, B)         \\\n  {                                          \\\n    const Eigen::MatrixXd& A_eval = A;       \\\n    const Eigen::MatrixXd& B_eval = B;       \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows()); \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols()); \\\n    for (int i = 0; i < A_eval.size(); i++)  \\\n      EXPECT_FLOAT_EQ(A_eval(i), B_eval(i)); \\\n  }\n\n#define EXPECT_STD_VECTOR_FLOAT_EQ(A, B) \\\n  EXPECT_EQ(A.size(), B.size());         \\\n  for (int i = 0; i < A.size(); ++i)     \\\n    EXPECT_FLOAT_EQ(A[i], B[i]);\n\n#define EXPECT_MATRIX_NEAR(A, B, DELTA)             \\\n  {                                                 \\\n    const Eigen::MatrixXd& A_eval = A;              \\\n    const Eigen::MatrixXd& B_eval = B;              \\\n    EXPECT_EQ(A_eval.rows(), B_eval.rows());        \\\n    EXPECT_EQ(A_eval.cols(), B_eval.cols());        \\\n    for (int i = 0; i < A_eval.size(); i++)         \\\n      EXPECT_FLOAT_EQ(A_eval(i), B_eval(i), DELTA); \\\n  }\n\n#define EXPECT_THROW_MSG_WITH_COUNT(expr, T_e, msg, count) \\\n  EXPECT_THROW(expr, T_e);                                 \\\n  try {                                                    \\\n    expr;                                                  \\\n  } catch (const T_e& e) {                                 \\\n    EXPECT_EQ(count, count_matches(msg, e.what()))         \\\n        << \"expected message: \" << msg << std::endl        \\\n        << \"found message:    \" << e.what();               \\\n  }\n\n#define EXPECT_THROW_MSG(expr, T_e, msg) \\\n  EXPECT_THROW_MSG_WITH_COUNT(expr, T_e, msg, 1)\n\nint count_matches(const std::string& target, const std::string& s) {\n  if (target.size() == 0)\n    return -1;  \/\/ error\n  int count = 0;\n  for (size_t pos = 0; (pos = s.find(target, pos)) != std::string::npos;\n       pos += target.size())\n    ++count;\n  return count;\n}\n\nnamespace test {\ntemplate \nvoid expect_same_type() {\n  bool b = std::is_same::value;\n  EXPECT_TRUE(b);\n}\n}  \/\/ namespace test\n\n#endif\n<|endoftext|>"}
{"text":"#include \"..\/lib\/urireader.cpp\"\n#include \n\nclass URITest : public Util::DataCallback{\npublic:\n  void dump(const char *ptr, size_t size);\n  void dataCallback(const char *ptr, size_t size);\n  int main(int argc, char **argv);\n};\n\nvoid URITest::dataCallback(const char *ptr, size_t size){\n  dump(ptr, size);\n}\n\nvoid URITest::dump(const char *ptr, size_t size){\n  if (fwrite(ptr, sizeof(char), size, stdout) != size){INFO_MSG(\"error: %s\", strerror(errno));}\n}\n\nint URITest::main(int argc, char **argv){\n  Util::redirectLogsIfNeeded();\n  Util::Config cfg(argv[0]);\n  JSON::Value option;\n  option[\"arg_num\"] = 1;\n  option[\"arg\"] = \"string\";\n  option[\"help\"] = \"Name of the input URI or - for stdin\";\n  option[\"value\"].append(\"-\");\n  cfg.addOption(\"input\", option);\n  option.null();\n  option[\"short\"] = \"r\";\n  option[\"long\"] = \"readall\";\n  option[\"help\"] = \"Read all data all at once in blocking mode\";\n  option[\"value\"].append(0);\n  cfg.addOption(\"readall\", option);\n  if (!cfg.parseArgs(argc, argv)){return 1;}\n\n  cfg.activate();\n  HTTP::URIReader R(cfg.getString(\"input\"));\n\n  if (cfg.getBool(\"readall\")){\n    char *dPtr = 0;\n    size_t dLen = 0;\n    R.readAll(dPtr, dLen);\n    dump(dPtr, dLen);\n  }else{\n    while (!R.isEOF() && cfg.is_active){R.readSome(10486, *this);}\n  }\n  return 0;\n}\n\nint main(int argc, char **argv){\n  URITest t;\n  t.main(argc, argv);\n}\nFixed URIReader compile warning#include \"..\/lib\/urireader.cpp\"\n#include \n\nclass URITest : public Util::DataCallback{\npublic:\n  void dump(const char *ptr, size_t size){\n    if (fwrite(ptr, sizeof(char), size, stdout) != size){INFO_MSG(\"error: %s\", strerror(errno));}\n  }\n  void dataCallback(const char *ptr, size_t size){\n    dump(ptr, size);\n  }\n  int main(int argc, char **argv);\n};\n\nint URITest::main(int argc, char **argv){\n  Util::redirectLogsIfNeeded();\n  Util::Config cfg(argv[0]);\n  JSON::Value option;\n  option[\"arg_num\"] = 1;\n  option[\"arg\"] = \"string\";\n  option[\"help\"] = \"Name of the input URI or - for stdin\";\n  option[\"value\"].append(\"-\");\n  cfg.addOption(\"input\", option);\n  option.null();\n  option[\"short\"] = \"r\";\n  option[\"long\"] = \"readall\";\n  option[\"help\"] = \"Read all data all at once in blocking mode\";\n  option[\"value\"].append(0);\n  cfg.addOption(\"readall\", option);\n  if (!cfg.parseArgs(argc, argv)){return 1;}\n\n  cfg.activate();\n  HTTP::URIReader R(cfg.getString(\"input\"));\n\n  if (cfg.getBool(\"readall\")){\n    char *dPtr = 0;\n    size_t dLen = 0;\n    R.readAll(dPtr, dLen);\n    dump(dPtr, dLen);\n  }else{\n    while (!R.isEOF() && cfg.is_active){R.readSome(10486, *this);}\n  }\n  return 0;\n}\n\nint main(int argc, char **argv){\n  URITest t;\n  t.main(argc, argv);\n}\n<|endoftext|>"}
{"text":"vcl::DeleteOnDeinit for static BitmapEx objects<|endoftext|>"}
{"text":"INTEGRATION: CWS changefileheader (1.68.14); FILE MERGED 2008\/04\/01 15:57:37 thb 1.68.14.3: #i85898# Stripping all external header guards 2008\/04\/01 12:54:34 thb 1.68.14.2: #i85898# Stripping all external header guards 2008\/03\/31 16:55:15 rt 1.68.14.1: #i87441# Change license header to LPGL v3.<|endoftext|>"}
{"text":"\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  02\/2018\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT_TDFNODES_UTILS\n#define ROOT_TDFNODES_UTILS\n\n#include \"ROOT\/TVec.hxx\"\n#include \"ROOT\/TDFUtils.hxx\" \/\/ ColumnNames_t\n\nnamespace ROOT {\nnamespace Internal {\nnamespace TDF {\nusing namespace ROOT::Experimental::TDF;\nusing namespace ROOT::Experimental::VecOps;\nusing namespace ROOT::Detail::TDF;\n\n\/\/\/ Choose between TTreeReader{Array,Value} depending on whether the branch type\n\/\/\/ T is a `TVec` or any other type (respectively).\ntemplate \nstruct TReaderValueOrArray {\n   using Proxy_t = TTreeReaderValue;\n};\n\ntemplate \nstruct TReaderValueOrArray> {\n   using Proxy_t = TTreeReaderArray;\n};\n\ntemplate \nusing ReaderValueOrArray_t = typename TReaderValueOrArray::Proxy_t;\n\n\/\/\/ Initialize a tuple of TColumnValues.\n\/\/\/ For real TTree branches a TTreeReader{Array,Value} is built and passed to the\n\/\/\/ TColumnValue. For temporary columns a pointer to the corresponding variable\n\/\/\/ is passed instead.\ntemplate \nvoid InitTDFValues(unsigned int slot, TDFValueTuple &valueTuple, TTreeReader *r, const ColumnNames_t &bn,\n                   const ColumnNames_t &tmpbn,\n                   const std::map> &customCols, StaticSeq)\n{\n   \/\/ isTmpBranch has length bn.size(). Elements are true if the corresponding\n   \/\/ branch is a temporary branch created with Define, false if they are\n   \/\/ actual branches present in the TTree.\n   std::array isTmpColumn;\n   for (auto i = 0u; i < isTmpColumn.size(); ++i)\n      isTmpColumn[i] = std::find(tmpbn.begin(), tmpbn.end(), bn.at(i)) != tmpbn.end();\n\n   \/\/ hack to expand a parameter pack without c++17 fold expressions.\n   \/\/ The statement defines a variable with type std::initializer_list, containing all zeroes, and SetTmpColumn or\n   \/\/ SetProxy are conditionally executed as the braced init list is expanded. The final ... expands S.\n   std::initializer_list expander{(isTmpColumn[S]\n                                           ? std::get(valueTuple).SetTmpColumn(slot, customCols.at(bn.at(S)).get())\n                                           : std::get(valueTuple).MakeProxy(r, bn.at(S)),\n                                        0)...};\n   (void)expander; \/\/ avoid \"unused variable\" warnings for expander on gcc4.9\n   (void)slot;     \/\/ avoid _bogus_ \"unused variable\" warnings for slot on gcc 4.9\n   (void)r;        \/\/ avoid \"unused variable\" warnings for r on gcc5.2\n}\n\ntemplate \nvoid CheckFilter(Filter &)\n{\n   using FilterRet_t = typename TDF::CallableTraits::ret_type;\n   static_assert(std::is_same::value, \"filter functions must return a bool\");\n}\n\n} \/\/ namespace TDF\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n\n#endif\n[TDF] Fix InitTDFValues in the case of zero columns\/\/ Author: Enrico Guiraud, Danilo Piparo CERN  02\/2018\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers.               *\n * All rights reserved.                                                  *\n *                                                                       *\n * For the licensing terms see $ROOTSYS\/LICENSE.                         *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS.             *\n *************************************************************************\/\n\n#ifndef ROOT_TDFNODES_UTILS\n#define ROOT_TDFNODES_UTILS\n\n#include \"ROOT\/TVec.hxx\"\n#include \"ROOT\/TDFUtils.hxx\" \/\/ ColumnNames_t\n\nnamespace ROOT {\nnamespace Internal {\nnamespace TDF {\nusing namespace ROOT::Experimental::TDF;\nusing namespace ROOT::Experimental::VecOps;\nusing namespace ROOT::Detail::TDF;\n\n\/\/\/ Choose between TTreeReader{Array,Value} depending on whether the branch type\n\/\/\/ T is a `TVec` or any other type (respectively).\ntemplate \nstruct TReaderValueOrArray {\n   using Proxy_t = TTreeReaderValue;\n};\n\ntemplate \nstruct TReaderValueOrArray> {\n   using Proxy_t = TTreeReaderArray;\n};\n\ntemplate \nusing ReaderValueOrArray_t = typename TReaderValueOrArray::Proxy_t;\n\n\/\/\/ Initialize a tuple of TColumnValues.\n\/\/\/ For real TTree branches a TTreeReader{Array,Value} is built and passed to the\n\/\/\/ TColumnValue. For temporary columns a pointer to the corresponding variable\n\/\/\/ is passed instead.\ntemplate \nvoid InitTDFValues(unsigned int slot, TDFValueTuple &valueTuple, TTreeReader *r, const ColumnNames_t &bn,\n                   const ColumnNames_t &tmpbn,\n                   const std::map> &customCols, StaticSeq)\n{\n   \/\/ isTmpBranch has length bn.size(). Elements are true if the corresponding\n   \/\/ branch is a temporary branch created with Define, false if they are\n   \/\/ actual branches present in the TTree.\n   std::array isTmpColumn;\n   for (auto i = 0u; i < isTmpColumn.size(); ++i)\n      isTmpColumn[i] = std::find(tmpbn.begin(), tmpbn.end(), bn.at(i)) != tmpbn.end();\n\n   \/\/ hack to expand a parameter pack without c++17 fold expressions.\n   \/\/ The statement defines a variable with type std::initializer_list, containing all zeroes, and SetTmpColumn or\n   \/\/ SetProxy are conditionally executed as the braced init list is expanded. The final ... expands S.\n   int expander[] = {(isTmpColumn[S] ? std::get(valueTuple).SetTmpColumn(slot, customCols.at(bn.at(S)).get())\n                                     : std::get(valueTuple).MakeProxy(r, bn.at(S)),\n                      0)...,\n                     0};\n   (void)expander; \/\/ avoid \"unused variable\" warnings for expander on gcc4.9\n   (void)slot;     \/\/ avoid _bogus_ \"unused variable\" warnings for slot on gcc 4.9\n   (void)r;        \/\/ avoid \"unused variable\" warnings for r on gcc5.2\n}\n\ntemplate \nvoid CheckFilter(Filter &)\n{\n   using FilterRet_t = typename TDF::CallableTraits::ret_type;\n   static_assert(std::is_same::value, \"filter functions must return a bool\");\n}\n\n} \/\/ namespace TDF\n} \/\/ namespace Internal\n} \/\/ namespace ROOT\n\n#endif\n<|endoftext|>"}
{"text":"\/*\n *  Copyright 2008-2013 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace agency\n{\nnamespace cuda\n{\n\n\ntemplate class future;\n\n\ntemplate<>\nclass future\n{\n  public:\n    \/\/ XXX this should be private\n    __host__ __device__\n    future(cudaStream_t s) : future(s, 0) {}\n\n    \/\/ XXX stream_ should default to per-thread default stream\n    __host__ __device__\n    future() : future(0) {}\n\n    __host__ __device__\n    future(future&& other)\n      : future()\n    {\n      future::swap(stream_, other.stream_);\n      future::swap(event_,  other.event_);\n    } \/\/ end future()\n\n    __host__ __device__\n    future &operator=(future&& other)\n    {\n      future::swap(stream_, other.stream_);\n      future::swap(event_,  other.event_);\n      return *this;\n    } \/\/ end operator=()\n\n    __host__ __device__\n    ~future()\n    {\n      if(valid())\n      {\n#if __cuda_lib_has_cudart\n        \/\/ swallow errors\n        cudaError_t e = cudaEventDestroy(event_);\n\n#if __cuda_lib_has_printf\n        if(e)\n        {\n          printf(\"CUDA error after cudaEventDestroy in agency::cuda::future dtor: %s\", cudaGetErrorString(e));\n        } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n      } \/\/ end if\n    } \/\/ end ~future()\n\n    __host__ __device__\n    void wait() const\n    {\n      \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n      \/\/ XXX need to capture the error as an exception and then throw it in .get()\n      detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda::future::wait\");\n#else\n      \/\/ XXX need to capture the error as an exception and then throw it in .get()\n      detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n      detail::terminate_with_message(\"agency::cuda::future::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n    } \/\/ end wait()\n\n    __host__ __device__\n    void get() const\n    {\n      wait();\n    } \/\/ end get()\n\n    \/\/ XXX we can eliminate this I think\n    __host__ __device__\n    future discard_value()\n    {\n      return std::move(*this);\n    } \/\/ end discard_value()\n\n    __host__ __device__\n    bool valid() const\n    {\n      return event_ != 0;\n    } \/\/ end valid()\n\n    __host__ __device__\n    cudaEvent_t event() const\n    {\n      return event_;\n    } \/\/ end event()\n\n    __host__ __device__\n    cudaStream_t stream() const\n    {\n      return stream_;\n    } \/\/ end stream()\n\n    __host__ __device__\n    static future make_ready()\n    {\n      cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n      detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future::make_ready\");\n#else\n      detail::terminate_with_message(\"agency::cuda::future::make_ready() requires CUDART\");\n#endif\n\n      future result;\n      result.set_valid(ready_event);\n\n      return result;\n    }\n\n    \/\/ XXX this is only used by grid_executor::then_execute()\n    __host__ __device__\n    std::nullptr_t ptr()\n    {\n      return nullptr;\n    }\n\n    template\n    __host__ __device__\n    future::type>\n      then(Function f)\n    {\n      void (*kernel_ptr)(detail::my_nullptr_t, Function) = detail::then_kernel;\n      detail::workaround_unused_variable_warning(kernel_ptr);\n\n      using result_type = typename std::result_of::type;\n      \n      using result_future_type = future;\n\n      result_future_type result(stream());\n\n      cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), ptr(), f);\n\n      \/\/ give next_event to the result future\n      result.set_valid(result);\n\n      return result;\n    }\n\n    \/\/ XXX set_valid() should only be available to friends\n    \/\/     such as future and grid_executor\n    __host__ __device__\n    void set_valid(cudaEvent_t e)\n    {\n      event_ = e;\n    }\n\n  private:\n    __host__ __device__\n    future(cudaStream_t s, cudaEvent_t e) : stream_(s), event_(e) {}\n\n    \/\/ implement swap to avoid depending on thrust::swap\n    template\n    __host__ __device__\n    static void swap(T& a, T& b)\n    {\n      T tmp{a};\n      a = b;\n      b = tmp;\n    }\n\n    static const int event_create_flags = cudaEventDisableTiming;\n\n    cudaStream_t stream_;\n    cudaEvent_t event_;\n}; \/\/ end future\n\n\ntemplate\nclass future\n{\n  public:\n    __host__ __device__\n    future()\n      : completion_()\n    {}\n\n    \/\/ XXX this should be private\n    \/\/ XXX this constructor should not even exist\n    \/\/     the ready event should be created in completion_'s initializer\n    template\n    __host__ __device__\n    future(U&& value, future& e)\n      : completion_(std::move(e)),\n        value_(detail::make_unique(completion_.stream(), std::forward(value)))\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future(cudaStream_t s)\n      : completion_(s)\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future(future&& other)\n      : completion_(std::move(other.completion_)),\n        value_(std::move(other.value_))\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future &operator=(future&& other)\n    {\n      completion_ = std::move(other.completion_);\n      value_ = std::move(other.value_);\n      return *this;\n    } \/\/ end operator=()\n\n    __host__ __device__\n    void wait() const\n    {\n      completion_.wait();\n    } \/\/ end wait()\n\n    __host__ __device__\n    T get() const\n    {\n      wait();\n\n      return *value_;\n    } \/\/ end get()\n\n    __host__ __device__\n    future discard_value()\n    {\n      return std::move(completion_);\n    } \/\/ end discard_value()\n\n    __host__ __device__\n    bool valid() const\n    {\n      return completion_.valid();\n    } \/\/ end valid()\n\n    \/\/ XXX only used by grid_executor\n    \/\/     think of a better way to expose this\n    \/\/ XXX the existence of future_cast makes this superfluous i think\n    __host__ __device__\n    future& void_future()\n    {\n      return completion_;\n    } \/\/ end void_future()\n\n    template\n    __host__ __device__\n    static future make_ready(U&& value)\n    {\n      auto event = future::make_ready();\n\n      return future{std::forward(value), event};\n    }\n\n    \/\/ XXX this is only used by grid_executor::then_execute()\n    __host__ __device__\n    T* ptr()\n    {\n      return value_.get();\n    }\n\n    \/\/ XXX set_valid() should only be available to friends\n    \/\/     such as future and grid_executor\n    __host__ __device__\n    void set_valid(cudaEvent_t event)\n    {\n      completion_.set_valid(event);\n    }\n\n  private:\n    future completion_;\n    detail::unique_ptr value_;\n}; \/\/ end future\n\n\ninline __host__ __device__\nfuture make_ready_future()\n{\n  return future::make_ready();\n} \/\/ end make_ready_future()\n\n\ntemplate\ninline __host__ __device__\nfuture::type> make_ready_future(T&& value)\n{\n  return future::type>::make_ready(std::forward(value));\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\nTweak one of future's constructors\/*\n *  Copyright 2008-2013 NVIDIA Corporation\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace agency\n{\nnamespace cuda\n{\n\n\ntemplate class future;\n\n\ntemplate<>\nclass future\n{\n  public:\n    \/\/ XXX this should be private\n    __host__ __device__\n    future(cudaStream_t s) : future(s, 0) {}\n\n    \/\/ XXX stream_ should default to per-thread default stream\n    __host__ __device__\n    future() : future(0) {}\n\n    __host__ __device__\n    future(future&& other)\n      : future()\n    {\n      future::swap(stream_, other.stream_);\n      future::swap(event_,  other.event_);\n    } \/\/ end future()\n\n    __host__ __device__\n    future &operator=(future&& other)\n    {\n      future::swap(stream_, other.stream_);\n      future::swap(event_,  other.event_);\n      return *this;\n    } \/\/ end operator=()\n\n    __host__ __device__\n    ~future()\n    {\n      if(valid())\n      {\n#if __cuda_lib_has_cudart\n        \/\/ swallow errors\n        cudaError_t e = cudaEventDestroy(event_);\n\n#if __cuda_lib_has_printf\n        if(e)\n        {\n          printf(\"CUDA error after cudaEventDestroy in agency::cuda::future dtor: %s\", cudaGetErrorString(e));\n        } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n      } \/\/ end if\n    } \/\/ end ~future()\n\n    __host__ __device__\n    void wait() const\n    {\n      \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n      \/\/ XXX need to capture the error as an exception and then throw it in .get()\n      detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda::future::wait\");\n#else\n      \/\/ XXX need to capture the error as an exception and then throw it in .get()\n      detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n      detail::terminate_with_message(\"agency::cuda::future::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n    } \/\/ end wait()\n\n    __host__ __device__\n    void get() const\n    {\n      wait();\n    } \/\/ end get()\n\n    \/\/ XXX we can eliminate this I think\n    __host__ __device__\n    future discard_value()\n    {\n      return std::move(*this);\n    } \/\/ end discard_value()\n\n    __host__ __device__\n    bool valid() const\n    {\n      return event_ != 0;\n    } \/\/ end valid()\n\n    __host__ __device__\n    cudaEvent_t event() const\n    {\n      return event_;\n    } \/\/ end event()\n\n    __host__ __device__\n    cudaStream_t stream() const\n    {\n      return stream_;\n    } \/\/ end stream()\n\n    __host__ __device__\n    static future make_ready()\n    {\n      cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n      detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future::make_ready\");\n#else\n      detail::terminate_with_message(\"agency::cuda::future::make_ready() requires CUDART\");\n#endif\n\n      future result;\n      result.set_valid(ready_event);\n\n      return result;\n    }\n\n    \/\/ XXX this is only used by grid_executor::then_execute()\n    __host__ __device__\n    std::nullptr_t ptr()\n    {\n      return nullptr;\n    }\n\n    template\n    __host__ __device__\n    future::type>\n      then(Function f)\n    {\n      void (*kernel_ptr)(detail::my_nullptr_t, Function) = detail::then_kernel;\n      detail::workaround_unused_variable_warning(kernel_ptr);\n\n      using result_type = typename std::result_of::type;\n      \n      using result_future_type = future;\n\n      result_future_type result(stream());\n\n      cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), ptr(), f);\n\n      \/\/ give next_event to the result future\n      result.set_valid(result);\n\n      return result;\n    }\n\n    \/\/ XXX set_valid() should only be available to friends\n    \/\/     such as future and grid_executor\n    __host__ __device__\n    void set_valid(cudaEvent_t e)\n    {\n      event_ = e;\n    }\n\n  private:\n    __host__ __device__\n    future(cudaStream_t s, cudaEvent_t e) : stream_(s), event_(e) {}\n\n    \/\/ implement swap to avoid depending on thrust::swap\n    template\n    __host__ __device__\n    static void swap(T& a, T& b)\n    {\n      T tmp{a};\n      a = b;\n      b = tmp;\n    }\n\n    static const int event_create_flags = cudaEventDisableTiming;\n\n    cudaStream_t stream_;\n    cudaEvent_t event_;\n}; \/\/ end future\n\n\ntemplate\nclass future\n{\n  public:\n    __host__ __device__\n    future()\n      : completion_()\n    {}\n\n    template\n    __host__ __device__\n    future(U&& value)\n      : completion_(future::make_ready()),\n        value_(detail::make_unique(completion_.stream(), std::forward(value)))\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future(cudaStream_t s)\n      : completion_(s)\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future(future&& other)\n      : completion_(std::move(other.completion_)),\n        value_(std::move(other.value_))\n    {\n    } \/\/ end future()\n\n    __host__ __device__\n    future &operator=(future&& other)\n    {\n      completion_ = std::move(other.completion_);\n      value_ = std::move(other.value_);\n      return *this;\n    } \/\/ end operator=()\n\n    __host__ __device__\n    void wait() const\n    {\n      completion_.wait();\n    } \/\/ end wait()\n\n    __host__ __device__\n    T get() const\n    {\n      wait();\n\n      return *value_;\n    } \/\/ end get()\n\n    __host__ __device__\n    future discard_value()\n    {\n      return std::move(completion_);\n    } \/\/ end discard_value()\n\n    __host__ __device__\n    bool valid() const\n    {\n      return completion_.valid();\n    } \/\/ end valid()\n\n    \/\/ XXX only used by grid_executor\n    \/\/     think of a better way to expose this\n    \/\/ XXX the existence of future_cast makes this superfluous i think\n    __host__ __device__\n    future& void_future()\n    {\n      return completion_;\n    } \/\/ end void_future()\n\n    template\n    __host__ __device__\n    static future make_ready(U&& value)\n    {\n      return future(std::forward(value));\n    }\n\n    \/\/ XXX this is only used by grid_executor::then_execute()\n    __host__ __device__\n    T* ptr()\n    {\n      return value_.get();\n    }\n\n    \/\/ XXX set_valid() should only be available to friends\n    \/\/     such as future and grid_executor\n    __host__ __device__\n    void set_valid(cudaEvent_t event)\n    {\n      completion_.set_valid(event);\n    }\n\n  private:\n    future completion_;\n    detail::unique_ptr value_;\n}; \/\/ end future\n\n\ninline __host__ __device__\nfuture make_ready_future()\n{\n  return future::make_ready();\n} \/\/ end make_ready_future()\n\n\ntemplate\ninline __host__ __device__\nfuture::type> make_ready_future(T&& value)\n{\n  return future::type>::make_ready(std::forward(value));\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\n<|endoftext|>"}
{"text":"#include \"EnvironmentImpl.h\"\n#include \"Session.h\"\n#include \n\nnamespace SubutaiLauncher \n{\n\n    const std::string EnvironmentImpl::EXTRA_PATH=\"\/usr\/local\/bin:\";\n\n    EnvironmentImpl::EnvironmentImpl() \n    {\n        _logger = &Poco::Logger::get(\"subutai\");\n        _logger->trace(\"Starting new Environment instance\");\n    }\n\n    EnvironmentImpl::~EnvironmentImpl() \n    {\n        _logger->trace(\"Environment::~Environment\");\n    }\n\n    unsigned EnvironmentImpl::processorNum() \n    {\n        _logger->trace(\"Environment: Get CPU number\");\n        return Poco::Environment::processorCount();\n    }\n\n    unsigned EnvironmentImpl::is64() \n    {\n        _logger->trace(\"Environment: Determining architecture\");\n#if ( __WORDSIZE == 64 )\n#define BUILD_64 1\n\n#ifdef BUILD_64\n        return 1;\n#else \n        return 0;\n#endif\n    }\n\n    ULORAMSIZE_T EnvironmentImpl::ramSize() \n    {\n        _logger->debug(\"Environment: Retrieving RAM size\");\n        struct sysinfo info;\n        _logger->trace(\"Running sysinfo\");\n        int rc = sysinfo(&info);\n        if (rc == 0)\n        {\n            _logger->debug(\"Total mem size: %lu\", info.totalram);\n            return info.totalram;\n        }\n        return 0;\n    }\n\n    unsigned EnvironmentImpl::versionVBox() \n    {\n\n#if ( __WORDSIZE == 64 )\n#define BUILD_64 1\n\n#ifdef BUILD_64\n        return 1;\n#else \n        return 0;\n#endif\n    }\n\n    bool EnvironmentImpl::vtxEnabled() \n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"\/proc\/cpuinfo\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/bin\/cat\", pArgs, 0, &pOut, 0);\n        int rc = ph.wait();\n        if (rc != 0)\n        {\n            _logger->error(\"Failed to cat \/proc\/cpuinfo. VTX query failed\");\n            return false;\n        }\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        Poco::StringTokenizer lines(pBuffer, \" \", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        for (auto it = lines.begin(); it != lines.end(); it++)\n        {\n            if ((*it) == \"vme\" || (*it) == \"VME\") return true;\n        }\n        return false;\n    }\n\n    std::string EnvironmentImpl::versionOS() \n    {\n        _logger->trace(\"Environment: Getting operating system information\");\n        std::string os;\n        \/\/os = Poco::Environment::osDisplayName() + \" \" + Poco::Environment::osVersion();\n        os = Poco::Environment::osDisplayName();\n        return os;\n    }\n\n    std::string EnvironmentImpl::versionNumber()\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"\/etc\/lsb-release\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle pH = Poco::Process::launch(\"\/bin\/cat\", pArgs, 0, &pOut, 0);\n        pH.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        Poco::StringTokenizer lines(pBuffer, \"\\n\", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        for (auto it = lines.begin(); it != lines.end(); it++)\n        {\n            if ((*it).substr(0, 15) == \"DISTRIB_RELEASE\")\n            {\n                _logger->trace(\"Found DISTRIB_RELEASE: %s\", (*it));\n                std::string num = (*it).substr(16, 5);\n                _logger->information(\"Extracted version: %s\", num);\n                return num;\n            }\n        }\n        return \"Unknown Version\";\n    }\n\n    std::string EnvironmentImpl::cpuArch() \n    {\n        _logger->trace(\"Environment: Getting OS Architecture\");\n        std::string ar(\"\");\n        ar = Poco::Environment::osArchitecture();\n        return ar;\n    }\n\n    unsigned int EnvironmentImpl::cpuNum() \n    {\n        return Poco::Environment::processorCount();\n    }\n\n    std::string EnvironmentImpl::getVar(const std::string& name, const std::string& defaultValue) \n    {\n        return Poco::Environment::get(name, defaultValue);\n    }\n\n    std::string EnvironmentImpl::setVar(const std::string& name, const std::string& value)\n    {\n        Poco::Environment::set(name, value);\n        return value;\n    }\n\n    std::string EnvironmentImpl::getDefaultGateway()\n    {\n        std::string binary, gatewayName;\n        int elnum;\n        binary = \"\/bin\/netstat\";\n        gatewayName = \"0.0.0.0\";\n        elnum = 8;\n\n        Poco::Process::Args args;\n        args.push_back(\"-rn\");\n\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(binary, args, 0, &pOut, 0);\n        ph.wait();\n\n        Poco::PipeInputStream istr(pOut);\n        std::string netstat;\n        Poco::StreamCopier::copyToString(istr, netstat);\n\n        Poco::StringTokenizer lines(netstat, \"\\n\", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        bool isDefault = false;\n        for (auto line = lines.begin(); line != lines.end(); line++) \n        {\n            Poco::StringTokenizer elements((*line), \" \", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n            int i = 0;\n            for (auto el = elements.begin(); el != elements.end(); el++) \n            {\n                i++;\n                if ((*el) == gatewayName) isDefault = true;\n                if (isDefault && i == elnum) return (*el);\n            }\n        }\n        return \"unknown\";\n    }\n\n    \/\/ Check whether NSSM tool is available\n    bool EnvironmentImpl::isNSSMInstalled()\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::registerService(const std::string& name, const std::string& path, std::vector args)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::unregisterService(const std::string & name)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::startService(const std::string& name)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::stopService(const std::string& name)\n    {\n        return false;\n    }\n\n    void EnvironmentImpl::CreateShortcut(const std::string& source, const std::string& name)\n    {\n\n    }\n\n    int32_t EnvironmentImpl::updatePath(const std::string& path)\n    {\n        return 0;\n    }\n\n    bool EnvironmentImpl::killProcess(const std::string & name)\n    {\n        return false;\n    }\n\n    std::string EnvironmentImpl::getDesktopDirectory()\n    {\n        return \"\";\n    }\n\n    bool EnvironmentImpl::isVBoxInstalled()\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::writeE2ERegistry(const std::string & name)\n    {\n        return false;\n    }\n\n    BOOL EnvironmentImpl::terminateWinProcess(DWORD dwProcessId, UINT uExitCode)\n    {\n        return false;\n    }\n\n    const std::string& EnvironmentImpl::getNetworkConfiguration() const\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"addr\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/usr\/bin\/ip\", pArgs, 0, &pOut, 0);\n        ph.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        return pBuffer;\n    }\n\n    const std::string& EnvironmentImpl::getNetstat() const\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"-rn\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/bin\/netstat\", pArgs, 0, &pOut, 0);\n        ph.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        return pBuffer;\n    }\n\n    const std::string& EnvironmentImpl::getSystemInfo() const\n    {\n        return \"\";\n    }\n\n}\nFixed linux build#include \"EnvironmentImpl.h\"\n#include \"Session.h\"\n#include \n\nnamespace SubutaiLauncher \n{\n\n    const std::string EnvironmentImpl::EXTRA_PATH=\"\/usr\/local\/bin:\";\n\n    EnvironmentImpl::EnvironmentImpl() \n    {\n        _logger = &Poco::Logger::get(\"subutai\");\n        _logger->trace(\"Starting new Environment instance\");\n    }\n\n    EnvironmentImpl::~EnvironmentImpl() \n    {\n        _logger->trace(\"Environment::~Environment\");\n    }\n\n    unsigned EnvironmentImpl::processorNum() \n    {\n        _logger->trace(\"Environment: Get CPU number\");\n        return Poco::Environment::processorCount();\n    }\n\n    unsigned EnvironmentImpl::is64() \n    {\n        _logger->trace(\"Environment: Determining architecture\");\n        return 1;\n    }\n\n    ULORAMSIZE_T EnvironmentImpl::ramSize() \n    {\n        _logger->debug(\"Environment: Retrieving RAM size\");\n        struct sysinfo info;\n        _logger->trace(\"Running sysinfo\");\n        int rc = sysinfo(&info);\n        if (rc == 0)\n        {\n            _logger->debug(\"Total mem size: %lu\", info.totalram);\n            return info.totalram;\n        }\n        return 0;\n    }\n\n    unsigned EnvironmentImpl::versionVBox() \n    {\n        return 1;\n    }\n\n    bool EnvironmentImpl::vtxEnabled() \n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"\/proc\/cpuinfo\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/bin\/cat\", pArgs, 0, &pOut, 0);\n        int rc = ph.wait();\n        if (rc != 0)\n        {\n            _logger->error(\"Failed to cat \/proc\/cpuinfo. VTX query failed\");\n            return false;\n        }\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        Poco::StringTokenizer lines(pBuffer, \" \", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        for (auto it = lines.begin(); it != lines.end(); it++)\n        {\n            if ((*it) == \"vme\" || (*it) == \"VME\") return true;\n        }\n        return false;\n    }\n\n    std::string EnvironmentImpl::versionOS() \n    {\n        _logger->trace(\"Environment: Getting operating system information\");\n        std::string os;\n        \/\/os = Poco::Environment::osDisplayName() + \" \" + Poco::Environment::osVersion();\n        os = Poco::Environment::osDisplayName();\n        return os;\n    }\n\n    std::string EnvironmentImpl::versionNumber()\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"\/etc\/lsb-release\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle pH = Poco::Process::launch(\"\/bin\/cat\", pArgs, 0, &pOut, 0);\n        pH.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        Poco::StringTokenizer lines(pBuffer, \"\\n\", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        for (auto it = lines.begin(); it != lines.end(); it++)\n        {\n            if ((*it).substr(0, 15) == \"DISTRIB_RELEASE\")\n            {\n                _logger->trace(\"Found DISTRIB_RELEASE: %s\", (*it));\n                std::string num = (*it).substr(16, 5);\n                _logger->information(\"Extracted version: %s\", num);\n                return num;\n            }\n        }\n        return \"Unknown Version\";\n    }\n\n    std::string EnvironmentImpl::cpuArch() \n    {\n        _logger->trace(\"Environment: Getting OS Architecture\");\n        std::string ar(\"\");\n        ar = Poco::Environment::osArchitecture();\n        return ar;\n    }\n\n    unsigned int EnvironmentImpl::cpuNum() \n    {\n        return Poco::Environment::processorCount();\n    }\n\n    std::string EnvironmentImpl::getVar(const std::string& name, const std::string& defaultValue) \n    {\n        return Poco::Environment::get(name, defaultValue);\n    }\n\n    std::string EnvironmentImpl::setVar(const std::string& name, const std::string& value)\n    {\n        Poco::Environment::set(name, value);\n        return value;\n    }\n\n    std::string EnvironmentImpl::getDefaultGateway()\n    {\n        std::string binary, gatewayName;\n        int elnum;\n        binary = \"\/bin\/netstat\";\n        gatewayName = \"0.0.0.0\";\n        elnum = 8;\n\n        Poco::Process::Args args;\n        args.push_back(\"-rn\");\n\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(binary, args, 0, &pOut, 0);\n        ph.wait();\n\n        Poco::PipeInputStream istr(pOut);\n        std::string netstat;\n        Poco::StreamCopier::copyToString(istr, netstat);\n\n        Poco::StringTokenizer lines(netstat, \"\\n\", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n        bool isDefault = false;\n        for (auto line = lines.begin(); line != lines.end(); line++) \n        {\n            Poco::StringTokenizer elements((*line), \" \", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);\n            int i = 0;\n            for (auto el = elements.begin(); el != elements.end(); el++) \n            {\n                i++;\n                if ((*el) == gatewayName) isDefault = true;\n                if (isDefault && i == elnum) return (*el);\n            }\n        }\n        return \"unknown\";\n    }\n\n    \/\/ Check whether NSSM tool is available\n    bool EnvironmentImpl::isNSSMInstalled()\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::registerService(const std::string& name, const std::string& path, std::vector args)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::unregisterService(const std::string & name)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::startService(const std::string& name)\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::stopService(const std::string& name)\n    {\n        return false;\n    }\n\n    void EnvironmentImpl::CreateShortcut(const std::string& source, const std::string& name)\n    {\n\n    }\n\n    int32_t EnvironmentImpl::updatePath(const std::string& path)\n    {\n        return 0;\n    }\n\n    bool EnvironmentImpl::killProcess(const std::string & name)\n    {\n        return false;\n    }\n\n    std::string EnvironmentImpl::getDesktopDirectory()\n    {\n        return \"\";\n    }\n\n    bool EnvironmentImpl::isVBoxInstalled()\n    {\n        return false;\n    }\n\n    bool EnvironmentImpl::writeE2ERegistry(const std::string & name)\n    {\n        return false;\n    }\n\n    BOOL EnvironmentImpl::terminateWinProcess(DWORD dwProcessId, UINT uExitCode)\n    {\n        return false;\n    }\n\n    const std::string& EnvironmentImpl::getNetworkConfiguration() const\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"addr\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/usr\/bin\/ip\", pArgs, 0, &pOut, 0);\n        ph.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        return pBuffer;\n    }\n\n    const std::string& EnvironmentImpl::getNetstat() const\n    {\n        Poco::Process::Args pArgs;\n        pArgs.push_back(\"-rn\");\n        Poco::Pipe pOut;\n        Poco::ProcessHandle ph = Poco::Process::launch(\"\/bin\/netstat\", pArgs, 0, &pOut, 0);\n        ph.wait();\n        std::string pBuffer;\n        Poco::PipeInputStream istr(pOut);\n        Poco::StreamCopier::copyToString(istr, pBuffer);\n        return pBuffer;\n    }\n\n    const std::string& EnvironmentImpl::getSystemInfo() const\n    {\n        return \"\";\n    }\n\n}\n<|endoftext|>"}
{"text":"#include \"GarageDoor\/Filesystem.h\"\n\nstd::vector GarageDoor::Filesystem::ListDirectory(tstring path)\n{\n    std::vector dirlist;\n\n    DIR * dir = opendir(path.c_str());\n    struct dirent * entry = readdir(dir);\n\n    while (entry != NULL)\n    {\n        std::stringstream ss;\n        ss << entry->d_name;\n        std::string name = ss.str();\n\n        if ( name == \".\" || name == \"..\" )\n        {\n            continue;\n        }\n\n        dirlist.push_back(name);\n        entry = readdir(dir);\n    }\n\n    closedir(dir);\n    return dirlist;\n}\nSick shit#include \"GarageDoor\/Filesystem.h\"\n\nstd::vector GarageDoor::Filesystem::ListDirectory(tstring path)\n{\n    std::vector dirlist;\n\n    DIR * dir = opendir(path.c_str());\n    struct dirent * entry = readdir(dir);\n\n    while (entry != NULL)\n    {\n        std::stringstream ss;\n        ss << entry->d_name;\n        std::string name = ss.str();\n\n        if ( name != \".\" && name != \"..\" )\n        {\n            dirlist.push_back(name);\n        }\n\n        entry = readdir(dir);\n    }\n\n    closedir(dir);\n    return dirlist;\n}\n<|endoftext|>"}
{"text":"#include \"BootConfig.hpp\"\n\nusing namespace HomieInternals;\n\nBootConfig::BootConfig()\n: Boot(\"config\")\n, _http(80)\n, _ssidCount(0)\n, _wifiScanAvailable(false)\n, _lastWifiScanEnded(true)\n, _jsonWifiNetworks()\n, _flaggedForReboot(false)\n, _flaggedForRebootAt(0)\n{\n  this->_wifiScanTimer.setInterval(CONFIG_SCAN_INTERVAL);\n}\n\nBootConfig::~BootConfig() {\n}\n\nvoid BootConfig::setup() {\n  Boot::setup();\n\n  if (this->_interface->led.enabled) {\n    digitalWrite(this->_interface->led.pin, this->_interface->led.on);\n  }\n\n  const char* deviceId = Helpers::getDeviceId();\n\n  this->_interface->logger->log(F(\"Device ID is \"));\n  this->_interface->logger->logln(deviceId);\n\n  WiFi.mode(WIFI_AP);\n\n  char apName[MAX_WIFI_SSID_LENGTH];\n  strcpy(apName, this->_interface->brand);\n  strcat_P(apName, PSTR(\"-\"));\n  strcat(apName, Helpers::getDeviceId());\n\n  WiFi.softAPConfig(ACCESS_POINT_IP, ACCESS_POINT_IP, IPAddress(255, 255, 255, 0));\n  WiFi.softAP(apName, deviceId);\n\n  this->_interface->logger->log(F(\"AP started as \"));\n  this->_interface->logger->logln(apName);\n\n  this->_dns.setTTL(300);\n  this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure);\n  this->_dns.start(53, F(\"homie.config\"), ACCESS_POINT_IP);\n\n  this->_http.on(\"\/\", HTTP_GET, [this]() {\n    this->_interface->logger->logln(F(\"Received index request\"));\n    this->_http.send(200, F(\"text\/plain\"), F(\"See Configuration API usage: http:\/\/marvinroger.viewdocs.io\/homie-esp8266\/6.-Configuration-API\"));\n  });\n  this->_http.on(\"\/heart\", HTTP_GET, [this]() {\n    this->_interface->logger->logln(F(\"Received heart request\"));\n    this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), F(\"{\\\"heart\\\":\\\"beat\\\"}\"));\n  });\n  this->_http.on(\"\/device-info\", HTTP_GET, std::bind(&BootConfig::_onDeviceInfoRequest, this));\n  this->_http.on(\"\/networks\", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this));\n  this->_http.on(\"\/config\", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this));\n  this->_http.on(\"\/config\", HTTP_OPTIONS, [this]() { \/\/ CORS\n    this->_interface->logger->logln(F(\"Received CORS request for \/config\"));\n    this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS));\n  });\n  this->_http.begin();\n}\n\nvoid BootConfig::_generateNetworksJson() {\n  DynamicJsonBuffer generatedJsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(this->_ssidCount) + (this->_ssidCount * JSON_OBJECT_SIZE(3))); \/\/ 1 at root, 3 in childrend\n  JsonObject& json = generatedJsonBuffer.createObject();\n\n  int jsonLength = 15; \/\/ {\"networks\":[]}\n  JsonArray& networks = json.createNestedArray(\"networks\");\n  for (int network = 0; network < this->_ssidCount; network++) {\n    jsonLength += 36; \/\/ {\"ssid\":\"\",\"rssi\":,\"encryption\":\"\"},\n    JsonObject& jsonNetwork = generatedJsonBuffer.createObject();\n    jsonLength += WiFi.SSID(network).length();\n    jsonNetwork[\"ssid\"] = WiFi.SSID(network);\n    jsonLength += 4;\n    jsonNetwork[\"rssi\"] = WiFi.RSSI(network);\n    jsonLength += 4;\n    switch (WiFi.encryptionType(network)) {\n      case ENC_TYPE_WEP:\n        jsonNetwork[\"encryption\"] = \"wep\";\n        break;\n      case ENC_TYPE_TKIP:\n        jsonNetwork[\"encryption\"] = \"wpa\";\n        break;\n      case ENC_TYPE_CCMP:\n        jsonNetwork[\"encryption\"] = \"wpa2\";\n        break;\n      case ENC_TYPE_NONE:\n        jsonNetwork[\"encryption\"] = \"none\";\n        break;\n      case ENC_TYPE_AUTO:\n        jsonNetwork[\"encryption\"] = \"auto\";\n        break;\n    }\n\n    networks.add(jsonNetwork);\n  }\n\n  jsonLength++; \/\/ \\0\n\n  delete[] this->_jsonWifiNetworks;\n  this->_jsonWifiNetworks = new char[jsonLength];\n  json.printTo(this->_jsonWifiNetworks, jsonLength);\n}\n\nvoid BootConfig::_onDeviceInfoRequest() {\n  this->_interface->logger->logln(F(\"Received device info request\"));\n\n  DynamicJsonBuffer jsonBuffer = DynamicJsonBuffer(JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(2) + JSON_ARRAY_SIZE(this->_interface->registeredNodesCount) + (this->_interface->registeredNodesCount * JSON_OBJECT_SIZE(2)));\n  int jsonLength = 82; \/\/ {\"device_id\":\"\",\"homie_version\":\"\",\"firmware\":{\"name\":\"\",\"version\":\"\"},\"nodes\":[]}\n  JsonObject& json = jsonBuffer.createObject();\n  jsonLength += strlen(Helpers::getDeviceId());\n  json[\"device_id\"] = Helpers::getDeviceId();\n  jsonLength += strlen(VERSION);\n  json[\"homie_version\"] = VERSION;\n  JsonObject& firmware = json.createNestedObject(\"firmware\");\n  jsonLength += strlen(this->_interface->firmware.name);\n  firmware[\"name\"] = this->_interface->firmware.name;\n  jsonLength += strlen(this->_interface->firmware.version);\n  firmware[\"version\"] = this->_interface->firmware.version;\n\n  JsonArray& nodes = json.createNestedArray(\"nodes\");\n  for (int i = 0; i < this->_interface->registeredNodesCount; i++) {\n    jsonLength += 20; \/\/ {\"id\":\"\",\"type\":\"\"},\n    const HomieNode* node = this->_interface->registeredNodes[i];\n    JsonObject& jsonNode = jsonBuffer.createObject();\n    jsonLength += strlen(node->getId());\n    jsonNode[\"id\"] = node->getId();\n    jsonLength += strlen(node->getType());\n    jsonNode[\"type\"] = node->getType();\n\n    nodes.add(jsonNode);\n  }\n\n  jsonLength++; \/\/ \\0\n\n  std::unique_ptr jsonString(new char[jsonLength]);\n  json.printTo(jsonString.get(), jsonLength);\n  this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), jsonString.get());\n}\n\nvoid BootConfig::_onNetworksRequest() {\n  this->_interface->logger->logln(F(\"Received networks request\"));\n  if (this->_wifiScanAvailable) {\n    this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_jsonWifiNetworks);\n  } else {\n    this->_http.send(503, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_NETWORKS_FAILURE));\n  }\n}\n\nvoid BootConfig::_onConfigRequest() {\n  this->_interface->logger->logln(F(\"Received config request\"));\n  if (this->_flaggedForReboot) {\n    this->_interface->logger->logln(F(\"✖ Device already configured\"));\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Device already configured\\\"}\"));\n    this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  StaticJsonBuffer parseJsonBuffer;\n  char* bodyCharArray = strdup(this->_http.arg(\"plain\").c_str());\n  JsonObject& parsedJson = parseJsonBuffer.parseObject(bodyCharArray); \/\/ do not use plain String, else fails\n  if (!parsedJson.success()) {\n    this->_interface->logger->logln(F(\"✖ Invalid or too big JSON\"));\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Invalid or too big JSON\\\"}\"));\n    this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  ConfigValidationResult configValidationResult = Helpers::validateConfig(parsedJson);\n  free(bodyCharArray);\n  if (!configValidationResult.valid) {\n    this->_interface->logger->log(F(\"✖ Config file is not valid, reason: \"));\n    this->_interface->logger->logln(configValidationResult.reason);\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Config file is not valid, reason: \"));\n    errorJson.concat(configValidationResult.reason);\n    errorJson.concat(F(\"\\\"}\"));\n    this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  this->_interface->config->write(this->_http.arg(\"plain\"));\n\n  this->_interface->logger->logln(F(\"✔ Configured\"));\n\n  this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), F(\"{\\\"success\\\":true}\"));\n\n  this->_flaggedForReboot = true; \/\/ We don't reboot immediately, otherwise the response above is not sent\n  this->_flaggedForRebootAt = millis();\n}\n\nvoid BootConfig::loop() {\n  Boot::loop();\n\n  this->_dns.processNextRequest();\n  this->_http.handleClient();\n\n  if (this->_flaggedForReboot) {\n    if (millis() - this->_flaggedForRebootAt >= 3000UL) {\n      this->_interface->logger->logln(F(\"↻ Rebooting into normal mode...\"));\n      ESP.restart();\n    }\n\n    return;\n  }\n\n  if (!this->_lastWifiScanEnded) {\n    int8_t scanResult = WiFi.scanComplete();\n\n    switch (scanResult) {\n      case WIFI_SCAN_RUNNING:\n        return;\n      case WIFI_SCAN_FAILED:\n        this->_interface->logger->logln(F(\"✖ Wi-Fi scan failed\"));\n        this->_ssidCount = 0;\n        this->_wifiScanTimer.reset();\n        break;\n      default:\n        this->_interface->logger->logln(F(\"✔ Wi-Fi scan completed\"));\n        this->_ssidCount = scanResult;\n        this->_generateNetworksJson();\n        this->_wifiScanAvailable = true;\n        break;\n    }\n\n    this->_lastWifiScanEnded = true;\n  }\n\n  if (this->_lastWifiScanEnded && this->_wifiScanTimer.check()) {\n    this->_interface->logger->logln(F(\"Triggering Wi-Fi scan...\"));\n    WiFi.scanNetworks(true);\n    this->_wifiScanTimer.tick();\n    this->_lastWifiScanEnded = false;\n  }\n}\n:bug: Fix compatibility with ArduinoJson 5.11.0 (#362)#include \"BootConfig.hpp\"\n\nusing namespace HomieInternals;\n\nBootConfig::BootConfig()\n: Boot(\"config\")\n, _http(80)\n, _ssidCount(0)\n, _wifiScanAvailable(false)\n, _lastWifiScanEnded(true)\n, _jsonWifiNetworks()\n, _flaggedForReboot(false)\n, _flaggedForRebootAt(0)\n{\n  this->_wifiScanTimer.setInterval(CONFIG_SCAN_INTERVAL);\n}\n\nBootConfig::~BootConfig() {\n}\n\nvoid BootConfig::setup() {\n  Boot::setup();\n\n  if (this->_interface->led.enabled) {\n    digitalWrite(this->_interface->led.pin, this->_interface->led.on);\n  }\n\n  const char* deviceId = Helpers::getDeviceId();\n\n  this->_interface->logger->log(F(\"Device ID is \"));\n  this->_interface->logger->logln(deviceId);\n\n  WiFi.mode(WIFI_AP);\n\n  char apName[MAX_WIFI_SSID_LENGTH];\n  strcpy(apName, this->_interface->brand);\n  strcat_P(apName, PSTR(\"-\"));\n  strcat(apName, Helpers::getDeviceId());\n\n  WiFi.softAPConfig(ACCESS_POINT_IP, ACCESS_POINT_IP, IPAddress(255, 255, 255, 0));\n  WiFi.softAP(apName, deviceId);\n\n  this->_interface->logger->log(F(\"AP started as \"));\n  this->_interface->logger->logln(apName);\n\n  this->_dns.setTTL(300);\n  this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure);\n  this->_dns.start(53, F(\"homie.config\"), ACCESS_POINT_IP);\n\n  this->_http.on(\"\/\", HTTP_GET, [this]() {\n    this->_interface->logger->logln(F(\"Received index request\"));\n    this->_http.send(200, F(\"text\/plain\"), F(\"See Configuration API usage: http:\/\/marvinroger.viewdocs.io\/homie-esp8266\/6.-Configuration-API\"));\n  });\n  this->_http.on(\"\/heart\", HTTP_GET, [this]() {\n    this->_interface->logger->logln(F(\"Received heart request\"));\n    this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), F(\"{\\\"heart\\\":\\\"beat\\\"}\"));\n  });\n  this->_http.on(\"\/device-info\", HTTP_GET, std::bind(&BootConfig::_onDeviceInfoRequest, this));\n  this->_http.on(\"\/networks\", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this));\n  this->_http.on(\"\/config\", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this));\n  this->_http.on(\"\/config\", HTTP_OPTIONS, [this]() { \/\/ CORS\n    this->_interface->logger->logln(F(\"Received CORS request for \/config\"));\n    this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS));\n  });\n  this->_http.begin();\n}\n\nvoid BootConfig::_generateNetworksJson() {\n  DynamicJsonBuffer generatedJsonBuffer(JSON_OBJECT_SIZE(1) + JSON_ARRAY_SIZE(this->_ssidCount) + (this->_ssidCount * JSON_OBJECT_SIZE(3))); \/\/ 1 at root, 3 in childrend\n  JsonObject& json = generatedJsonBuffer.createObject();\n\n  int jsonLength = 15; \/\/ {\"networks\":[]}\n  JsonArray& networks = json.createNestedArray(\"networks\");\n  for (int network = 0; network < this->_ssidCount; network++) {\n    jsonLength += 36; \/\/ {\"ssid\":\"\",\"rssi\":,\"encryption\":\"\"},\n    JsonObject& jsonNetwork = generatedJsonBuffer.createObject();\n    jsonLength += WiFi.SSID(network).length();\n    jsonNetwork[\"ssid\"] = WiFi.SSID(network);\n    jsonLength += 4;\n    jsonNetwork[\"rssi\"] = WiFi.RSSI(network);\n    jsonLength += 4;\n    switch (WiFi.encryptionType(network)) {\n      case ENC_TYPE_WEP:\n        jsonNetwork[\"encryption\"] = \"wep\";\n        break;\n      case ENC_TYPE_TKIP:\n        jsonNetwork[\"encryption\"] = \"wpa\";\n        break;\n      case ENC_TYPE_CCMP:\n        jsonNetwork[\"encryption\"] = \"wpa2\";\n        break;\n      case ENC_TYPE_NONE:\n        jsonNetwork[\"encryption\"] = \"none\";\n        break;\n      case ENC_TYPE_AUTO:\n        jsonNetwork[\"encryption\"] = \"auto\";\n        break;\n    }\n\n    networks.add(jsonNetwork);\n  }\n\n  jsonLength++; \/\/ \\0\n\n  delete[] this->_jsonWifiNetworks;\n  this->_jsonWifiNetworks = new char[jsonLength];\n  json.printTo(this->_jsonWifiNetworks, jsonLength);\n}\n\nvoid BootConfig::_onDeviceInfoRequest() {\n  this->_interface->logger->logln(F(\"Received device info request\"));\n\n  DynamicJsonBuffer jsonBuffer(JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(2) + JSON_ARRAY_SIZE(this->_interface->registeredNodesCount) + (this->_interface->registeredNodesCount * JSON_OBJECT_SIZE(2)));\n  int jsonLength = 82; \/\/ {\"device_id\":\"\",\"homie_version\":\"\",\"firmware\":{\"name\":\"\",\"version\":\"\"},\"nodes\":[]}\n  JsonObject& json = jsonBuffer.createObject();\n  jsonLength += strlen(Helpers::getDeviceId());\n  json[\"device_id\"] = Helpers::getDeviceId();\n  jsonLength += strlen(VERSION);\n  json[\"homie_version\"] = VERSION;\n  JsonObject& firmware = json.createNestedObject(\"firmware\");\n  jsonLength += strlen(this->_interface->firmware.name);\n  firmware[\"name\"] = this->_interface->firmware.name;\n  jsonLength += strlen(this->_interface->firmware.version);\n  firmware[\"version\"] = this->_interface->firmware.version;\n\n  JsonArray& nodes = json.createNestedArray(\"nodes\");\n  for (int i = 0; i < this->_interface->registeredNodesCount; i++) {\n    jsonLength += 20; \/\/ {\"id\":\"\",\"type\":\"\"},\n    const HomieNode* node = this->_interface->registeredNodes[i];\n    JsonObject& jsonNode = jsonBuffer.createObject();\n    jsonLength += strlen(node->getId());\n    jsonNode[\"id\"] = node->getId();\n    jsonLength += strlen(node->getType());\n    jsonNode[\"type\"] = node->getType();\n\n    nodes.add(jsonNode);\n  }\n\n  jsonLength++; \/\/ \\0\n\n  std::unique_ptr jsonString(new char[jsonLength]);\n  json.printTo(jsonString.get(), jsonLength);\n  this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), jsonString.get());\n}\n\nvoid BootConfig::_onNetworksRequest() {\n  this->_interface->logger->logln(F(\"Received networks request\"));\n  if (this->_wifiScanAvailable) {\n    this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_jsonWifiNetworks);\n  } else {\n    this->_http.send(503, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_NETWORKS_FAILURE));\n  }\n}\n\nvoid BootConfig::_onConfigRequest() {\n  this->_interface->logger->logln(F(\"Received config request\"));\n  if (this->_flaggedForReboot) {\n    this->_interface->logger->logln(F(\"✖ Device already configured\"));\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Device already configured\\\"}\"));\n    this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  StaticJsonBuffer parseJsonBuffer;\n  char* bodyCharArray = strdup(this->_http.arg(\"plain\").c_str());\n  JsonObject& parsedJson = parseJsonBuffer.parseObject(bodyCharArray); \/\/ do not use plain String, else fails\n  if (!parsedJson.success()) {\n    this->_interface->logger->logln(F(\"✖ Invalid or too big JSON\"));\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Invalid or too big JSON\\\"}\"));\n    this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  ConfigValidationResult configValidationResult = Helpers::validateConfig(parsedJson);\n  free(bodyCharArray);\n  if (!configValidationResult.valid) {\n    this->_interface->logger->log(F(\"✖ Config file is not valid, reason: \"));\n    this->_interface->logger->logln(configValidationResult.reason);\n    String errorJson = String(FPSTR(PROGMEM_CONFIG_JSON_FAILURE_BEGINNING));\n    errorJson.concat(F(\"Config file is not valid, reason: \"));\n    errorJson.concat(configValidationResult.reason);\n    errorJson.concat(F(\"\\\"}\"));\n    this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), errorJson);\n    return;\n  }\n\n  this->_interface->config->write(this->_http.arg(\"plain\"));\n\n  this->_interface->logger->logln(F(\"✔ Configured\"));\n\n  this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), F(\"{\\\"success\\\":true}\"));\n\n  this->_flaggedForReboot = true; \/\/ We don't reboot immediately, otherwise the response above is not sent\n  this->_flaggedForRebootAt = millis();\n}\n\nvoid BootConfig::loop() {\n  Boot::loop();\n\n  this->_dns.processNextRequest();\n  this->_http.handleClient();\n\n  if (this->_flaggedForReboot) {\n    if (millis() - this->_flaggedForRebootAt >= 3000UL) {\n      this->_interface->logger->logln(F(\"↻ Rebooting into normal mode...\"));\n      ESP.restart();\n    }\n\n    return;\n  }\n\n  if (!this->_lastWifiScanEnded) {\n    int8_t scanResult = WiFi.scanComplete();\n\n    switch (scanResult) {\n      case WIFI_SCAN_RUNNING:\n        return;\n      case WIFI_SCAN_FAILED:\n        this->_interface->logger->logln(F(\"✖ Wi-Fi scan failed\"));\n        this->_ssidCount = 0;\n        this->_wifiScanTimer.reset();\n        break;\n      default:\n        this->_interface->logger->logln(F(\"✔ Wi-Fi scan completed\"));\n        this->_ssidCount = scanResult;\n        this->_generateNetworksJson();\n        this->_wifiScanAvailable = true;\n        break;\n    }\n\n    this->_lastWifiScanEnded = true;\n  }\n\n  if (this->_lastWifiScanEnded && this->_wifiScanTimer.check()) {\n    this->_interface->logger->logln(F(\"Triggering Wi-Fi scan...\"));\n    WiFi.scanNetworks(true);\n    this->_wifiScanTimer.tick();\n    this->_lastWifiScanEnded = false;\n  }\n}\n<|endoftext|>"}
{"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007-2008, Image Engine Design 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 are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/EXRImageWriter.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ByteOrder.h\"\n#include \"IECore\/ImagePrimitive.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/BoxOps.h\"\n\n#include \"boost\/format.hpp\"\n\n#include \n\nusing namespace IECore;\n\nusing std::string;\nusing std::vector;\n\nusing Imath::Box2i;\nusing namespace Imf;\n\nconst Writer::WriterDescription EXRImageWriter::m_writerDescription(\"exr\");\n\nEXRImageWriter::EXRImageWriter()\n\t\t: ImageWriter(\"EXRImageWriter\", \"Serializes images to the OpenEXR HDR image format\")\n{\n}\n\nEXRImageWriter::EXRImageWriter(ObjectPtr image, const string &fileName)\n\t\t: ImageWriter(\"EXRImageWriter\", \"Serializes images to the OpenEXR HDR image format\" )\n{\n\tassert( m_objectParameter );\n\tassert( m_fileNameParameter );\n\n\tm_objectParameter->setValue( image );\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\n\/\/ \\todo \"names\" should be const\nvoid EXRImageWriter::writeImage(vector &names, ConstImagePrimitivePtr image, const Box2i &dataWindow)\n{\n\tassert( image );\n\n\t\/\/ create the header\n\tint width  = 1 + boxSize( dataWindow ).x;\n\tint height = 1 + boxSize( dataWindow ).y;\n\n\ttry\n\t{\n\t\t\/\/\/ \\todo Add parameters for compression, etc\n\t\tHeader header(width, height, 1, Imath::V2f(0.0, 0.0), 1, INCREASING_Y, PIZ_COMPRESSION);\n\t\theader.dataWindow() = dataWindow;\n\t\theader.displayWindow() = image->getDisplayWindow();\n\n\t\t\/\/ create the framebuffer\n\t\tFrameBuffer fb;\n\n\t\t\/\/ add the channels into the header with the appropriate types\n\t\tvector::const_iterator i = names.begin();\n\t\tfor (vector::const_iterator i = names.begin(); i != names.end(); ++i)\n\t\t{\n\t\t\tconst char *name = (*i).c_str();\n\n\t\t\t\/\/ get the image channel\n\t\t\tPrimitiveVariableMap::const_iterator pit = image->variables.find(name);\n\t\t\tif ( pit == image->variables.end() )\n\t\t\t{\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Could not find image channel \\\"%s\\\"\") % name ).str() );\n\t\t\t}\n\n\t\t\tConstDataPtr channelData = pit->second.data;\n\t\t\tif (!channelData)\n\t\t\t{\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Channel \\\"%s\\\" has no data\") % name ).str() );\n\t\t\t}\n\n\t\t\tswitch (channelData->typeId())\n\t\t\t{\n\t\t\tcase FloatVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                         boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                         FLOAT, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tcase UIntVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                                boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                                UINT, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tcase HalfVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                        boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                        HALF, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Invalid data type \\\"%s\\\" for channel \\\"%s\\\"\") % channelData->typeName() % name ).str() );\n\t\t\t}\n\t\t}\n\n\t\t\/\/ create the output file, write, implicitly close\n\t\tOutputFile out(fileName().c_str(), header);\n\n\t\tout.setFrameBuffer(fb);\n\t\tout.writePixels(height);\n\t}\n\tcatch ( Exception &e )\n\t{\n\t\tthrow;\n\t}\n\tcatch ( std::exception &e )\n\t{\n\t\tthrow IOException( ( boost::format(\"EXRImageWriter: %s\") % e.what() ).str() );\n\t}\n\tcatch ( ... )\n\t{\n\t\tthrow IOException( \"EXRImageWriter: Unexpected error\" );\n\t}\n\n}\n\ntemplate\nvoid EXRImageWriter::writeTypedChannel(const char *name, ConstImagePrimitivePtr image, const Box2i &dataWindow,\n                                       const vector &channel, const Imf::PixelType pixelType, Header &header, FrameBuffer &fb)\n{\n\tassert( name );\n\n\t\/\/\/ \\todo Remove this unused parameter\n\t(void) image;\n\n\tint width = 1 + dataWindow.max.x - dataWindow.min.x;\n\n\t\/\/ update the header\n\theader.channels().insert( name, Channel(pixelType) );\n\n\t\/\/ update the framebuffer\n\tchar *offset = (char *) (&channel[0] - (dataWindow.min.x + width * dataWindow.min.y));\n\tfb.insert(name, Slice(pixelType, offset, sizeof(T), sizeof(T) * width));\n}\nRemoved ununsed variable\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  Copyright (c) 2007-2008, Image Engine Design 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 are\n\/\/  met:\n\/\/\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/       notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/     * Redistributions in binary form must reproduce the above copyright\n\/\/       notice, this list of conditions and the following disclaimer in the\n\/\/       documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/     * Neither the name of Image Engine Design nor the names of any\n\/\/       other contributors to this software may be used to endorse or\n\/\/       promote products derived from this software without specific prior\n\/\/       written permission.\n\/\/\n\/\/  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/EXRImageWriter.h\"\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ByteOrder.h\"\n#include \"IECore\/ImagePrimitive.h\"\n#include \"IECore\/FileNameParameter.h\"\n#include \"IECore\/BoxOps.h\"\n\n#include \"boost\/format.hpp\"\n\n#include \n\nusing namespace IECore;\n\nusing std::string;\nusing std::vector;\n\nusing Imath::Box2i;\nusing namespace Imf;\n\nconst Writer::WriterDescription EXRImageWriter::m_writerDescription(\"exr\");\n\nEXRImageWriter::EXRImageWriter()\n\t\t: ImageWriter(\"EXRImageWriter\", \"Serializes images to the OpenEXR HDR image format\")\n{\n}\n\nEXRImageWriter::EXRImageWriter(ObjectPtr image, const string &fileName)\n\t\t: ImageWriter(\"EXRImageWriter\", \"Serializes images to the OpenEXR HDR image format\" )\n{\n\tassert( m_objectParameter );\n\tassert( m_fileNameParameter );\n\n\tm_objectParameter->setValue( image );\n\tm_fileNameParameter->setTypedValue( fileName );\n}\n\n\/\/ \\todo \"names\" should be const\nvoid EXRImageWriter::writeImage(vector &names, ConstImagePrimitivePtr image, const Box2i &dataWindow)\n{\n\tassert( image );\n\n\t\/\/ create the header\n\tint width  = 1 + boxSize( dataWindow ).x;\n\tint height = 1 + boxSize( dataWindow ).y;\n\n\ttry\n\t{\n\t\t\/\/\/ \\todo Add parameters for compression, etc\n\t\tHeader header(width, height, 1, Imath::V2f(0.0, 0.0), 1, INCREASING_Y, PIZ_COMPRESSION);\n\t\theader.dataWindow() = dataWindow;\n\t\theader.displayWindow() = image->getDisplayWindow();\n\n\t\t\/\/ create the framebuffer\n\t\tFrameBuffer fb;\n\n\t\t\/\/ add the channels into the header with the appropriate types\n\t\tfor (vector::const_iterator i = names.begin(); i != names.end(); ++i)\n\t\t{\n\t\t\tconst char *name = (*i).c_str();\n\n\t\t\t\/\/ get the image channel\n\t\t\tPrimitiveVariableMap::const_iterator pit = image->variables.find(name);\n\t\t\tif ( pit == image->variables.end() )\n\t\t\t{\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Could not find image channel \\\"%s\\\"\") % name ).str() );\n\t\t\t}\n\n\t\t\tConstDataPtr channelData = pit->second.data;\n\t\t\tif (!channelData)\n\t\t\t{\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Channel \\\"%s\\\" has no data\") % name ).str() );\n\t\t\t}\n\n\t\t\tswitch (channelData->typeId())\n\t\t\t{\n\t\t\tcase FloatVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                         boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                         FLOAT, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tcase UIntVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                                boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                                UINT, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tcase HalfVectorDataTypeId:\n\t\t\t\twriteTypedChannel(name, image, dataWindow,\n\t\t\t\t                        boost::static_pointer_cast(channelData)->readable(),\n\t\t\t\t                        HALF, header, fb);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow IOException( ( boost::format(\"EXRImageWriter: Invalid data type \\\"%s\\\" for channel \\\"%s\\\"\") % channelData->typeName() % name ).str() );\n\t\t\t}\n\t\t}\n\n\t\t\/\/ create the output file, write, implicitly close\n\t\tOutputFile out(fileName().c_str(), header);\n\n\t\tout.setFrameBuffer(fb);\n\t\tout.writePixels(height);\n\t}\n\tcatch ( Exception &e )\n\t{\n\t\tthrow;\n\t}\n\tcatch ( std::exception &e )\n\t{\n\t\tthrow IOException( ( boost::format(\"EXRImageWriter: %s\") % e.what() ).str() );\n\t}\n\tcatch ( ... )\n\t{\n\t\tthrow IOException( \"EXRImageWriter: Unexpected error\" );\n\t}\n\n}\n\ntemplate\nvoid EXRImageWriter::writeTypedChannel(const char *name, ConstImagePrimitivePtr image, const Box2i &dataWindow,\n                                       const vector &channel, const Imf::PixelType pixelType, Header &header, FrameBuffer &fb)\n{\n\tassert( name );\n\n\t\/\/\/ \\todo Remove this unused parameter\n\t(void) image;\n\n\tint width = 1 + dataWindow.max.x - dataWindow.min.x;\n\n\t\/\/ update the header\n\theader.channels().insert( name, Channel(pixelType) );\n\n\t\/\/ update the framebuffer\n\tchar *offset = (char *) (&channel[0] - (dataWindow.min.x + width * dataWindow.min.y));\n\tfb.insert(name, Slice(pixelType, offset, sizeof(T), sizeof(T) * width));\n}\n<|endoftext|>"}
{"text":"comment<|endoftext|>"}
{"text":"am 8fc5a63d: Merge change 2431 into donut<|endoftext|>"}
{"text":"Core\/Network: [Add] BaseUrlInterceptor class<|endoftext|>"}
{"text":"\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/root_dataset.h\"\n\n#include \n#include \n#include \n\n#include \"tensorflow\/core\/data\/dataset_utils.h\"\n#include \"tensorflow\/core\/data\/name_utils.h\"\n#include \"tensorflow\/core\/data\/rewrite_utils.h\"\n#include \"tensorflow\/core\/framework\/model.pb.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/host_info.h\"\n#include \"tensorflow\/core\/platform\/refcount.h\"\n#include \"tensorflow\/core\/platform\/stringprintf.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nconstexpr char kDatasetType[] = \"Root\";\n\nconstexpr char kAlgorithm[] = \"algorithm\";\nconstexpr char kCpuBudget[] = \"cpu_budget\";\nconstexpr char kExperiments[] = \"experiments\";\nconstexpr char kInjectPrefetchEligibleOpt[] = \"inject_prefetch_eligible\";\nconstexpr char kIntraOpParallelism[] = \"intra_op_parallelism\";\nconstexpr char kMemBandwidth[] = \"mem_bw_used_megabytes_per_sec\";\nconstexpr char kPrivateThreadpoolSize[] = \"threadpool_size\";\nconstexpr char kRamBudget[] = \"ram_budget_megabytes\";\nconstexpr char kRamUsage[] = \"ram_usage_megabytes\";\nconstexpr char kMaxBufferBytes[] = \"max_buffered_megabytes\";\n\n\/\/ If value `x` matches `y`, returns default value `z`. Otherwise, return `x`.\ninline int64_t value_or_default(int64_t x, int64_t y, int64_t z) {\n  return x == y ? z : x;\n}\n\nvoid SetRootDatasetParams(const Options& options, RootDataset::Params* params) {\n  if (ShouldConfigureMaxIntraOpParallelism(options)) {\n    params->max_intra_op_parallelism =\n        options.threading_options().max_intra_op_parallelism();\n  }\n  if (ShouldUsePrivateThreadPool(options)) {\n    params->private_threadpool_size =\n        options.threading_options().private_threadpool_size();\n  }\n  params->autotune = ShouldUseAutotuning(options);\n  if (params->autotune) {\n    params->autotune_algorithm =\n        options.autotune_options().optional_autotune_algorithm_case() ==\n                AutotuneOptions::kAutotuneAlgorithm\n            ? options.autotune_options().autotune_algorithm()\n            : model::AutotuneAlgorithm::DEFAULT;\n    params->autotune_cpu_budget = value_or_default(\n        options.autotune_options().cpu_budget(), 0, GetCpuBudget());\n    params->autotune_ram_budget =\n        value_or_default(options.autotune_options().ram_budget(), 0,\n                         model::kRamBudgetShare * port::AvailableRam());\n  }\n}\n\nvoid AddTraceMetadata(const RootDataset::Params& params,\n                      TraceMeMetadata* trace_metadata) {\n  if (params.autotune) {\n    trace_metadata->push_back(std::make_pair(\n        kAlgorithm, model::AutotuneAlgorithm_Name(params.autotune_algorithm)));\n    trace_metadata->push_back(std::make_pair(\n        kCpuBudget, strings::Printf(\"%lld\", static_cast(\n                                                params.autotune_cpu_budget))));\n    trace_metadata->push_back(std::make_pair(\n        kRamBudget,\n        strings::Printf(\"%lld\", static_cast(\n                                    params.autotune_ram_budget \/ 1.0e6))));\n  }\n  if (params.max_intra_op_parallelism >= 0) {\n    trace_metadata->push_back(std::make_pair(\n        kIntraOpParallelism,\n        strings::Printf(\"%lld\", static_cast(value_or_default(\n                                    params.max_intra_op_parallelism, 0,\n                                    port::MaxParallelism())))));\n  }\n  if (params.private_threadpool_size >= 0) {\n    trace_metadata->push_back(std::make_pair(\n        kPrivateThreadpoolSize,\n        strings::Printf(\"%lld\", static_cast(value_or_default(\n                                    params.private_threadpool_size, 0,\n                                    port::MaxParallelism())))));\n  }\n  auto experiments = GetExperiments();\n  if (!experiments.empty()) {\n    trace_metadata->push_back(\n        std::make_pair(kExperiments, absl::StrJoin(experiments, \" \")));\n  }\n}\n}  \/\/ namespace\n\n\/\/ static\nStatus RootDataset::FromOptions(const DatasetBase* input,\n                                DatasetBase** output) {\n  Params params;\n  SetRootDatasetParams(input->options(), ¶ms);\n  *output = new RootDataset(input, params);\n  (*output)->Initialize(\/*metadata=*\/{});\n  return OkStatus();\n}\n\nStatus RootDataset::FromOptions(core::RefCountPtr input,\n                                DatasetBase** output) {\n  Params params;\n  SetRootDatasetParams(input->options(), ¶ms);\n  *output = new RootDataset(std::move(input), params);\n  (*output)->Initialize(\/*metadata=*\/{});\n  return OkStatus();\n}\n\nclass RootDataset::Iterator : public DatasetIterator {\n public:\n  explicit Iterator(const Params& params)\n      : DatasetIterator(params) {\n    if (dataset()->params_.autotune) {\n      model_ = std::make_shared();\n    }\n    if (dataset()->params_.max_intra_op_parallelism >= 0) {\n      max_intra_op_parallelism_ =\n          value_or_default(dataset()->params_.max_intra_op_parallelism, 0,\n                           port::MaxParallelism());\n    }\n    if (dataset()->params_.private_threadpool_size >= 0) {\n      threadpool_size_ =\n          value_or_default(dataset()->params_.private_threadpool_size, 0,\n                           port::MaxParallelism());\n      thread_pool_ = absl::make_unique(\n          Env::Default(), ThreadOptions{}, \"data_private_threadpool\",\n          threadpool_size_);\n    }\n    cancellation_manager_ = absl::make_unique();\n  }\n\n  ~Iterator() override { cancellation_manager_->StartCancel(); }\n\n  Status Initialize(IteratorContext* ctx) override {\n    return dataset()->input_->MakeIterator(IteratorContext(CreateParams(ctx)),\n                                           this, prefix(), &input_impl_);\n  }\n\n  Status GetNextInternal(IteratorContext* ctx, std::vector* out_tensors,\n                         bool* end_of_sequence) override {\n    if (dataset()->params_.autotune) {\n      TF_RETURN_IF_ERROR(EnsureModelThreadStarted(ctx));\n    }\n    return input_impl_->GetNext(IteratorContext(CreateParams(ctx)), out_tensors,\n                                end_of_sequence);\n  }\n\n protected:\n  std::shared_ptr CreateNode(\n      IteratorContext* ctx, model::Node::Args args) const override {\n    return model::MakeKnownRatioNode(std::move(args), \/*ratio=*\/1);\n  }\n\n  Status SaveInternal(SerializationContext* ctx,\n                      IteratorStateWriter* writer) override {\n    TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));\n    return OkStatus();\n  }\n\n  Status RestoreInternal(IteratorContext* ctx,\n                         IteratorStateReader* reader) override {\n    TF_RETURN_IF_ERROR(\n        RestoreInput(IteratorContext(CreateParams(ctx)), reader, input_impl_));\n    return OkStatus();\n  }\n\n  TraceMeMetadata GetTraceMeMetadata() const override {\n    tensorflow::data::TraceMeMetadata traceme_metadata =\n        dataset()->traceme_metadata_;\n    const int64_t mem_bw = port::GetMemoryBandwidthInfo().bw_used;\n    if (mem_bw != INT64_MAX) {\n      traceme_metadata.push_back(std::make_pair(\n          kMemBandwidth,\n          strings::Printf(\"%lld\", static_cast(mem_bw))));\n    }\n    const auto memory_info = port::GetMemoryInfo();\n    const auto memory_usage = memory_info.total - memory_info.free;\n    traceme_metadata.push_back(std::make_pair(\n        kRamUsage,\n        strings::Printf(\"%lld out of %lld (%.2f%%)\",\n                        static_cast(memory_usage \/ 1.0e6),\n                        static_cast(memory_info.total \/ 1.0e6),\n                        static_cast(memory_usage) \/\n                            static_cast(memory_info.total))));\n    if (model_node() != nullptr) {\n      traceme_metadata.push_back(std::make_pair(\n          kMaxBufferBytes,\n          strings::Printf(\n              \"%lld\", static_cast(\n                          model_node()->TotalMaximumBufferedBytes() \/ 1.0e6))));\n    }\n    return traceme_metadata;\n  }\n\n private:\n  IteratorContext::Params CreateParams(IteratorContext* ctx) {\n    IteratorContext::Params params(ctx);\n    if (dataset()->params_.autotune) {\n      params.model = model_;\n    }\n    if (dataset()->params_.private_threadpool_size >= 0) {\n      params.runner = [pool = thread_pool_.get()](std::function c) {\n        pool->Schedule(std::move(c));\n      };\n      params.runner_threadpool_size = threadpool_size_;\n    }\n    if (dataset()->params_.max_intra_op_parallelism >= 0) {\n      params.runner =\n          RunnerWithMaxParallelism(params.runner, max_intra_op_parallelism_);\n    }\n    params.options = &dataset()->options();\n    return params;\n  }\n\n  Status EnsureModelThreadStarted(IteratorContext* ctx) {\n    mutex_lock l(mu_);\n    if (!model_thread_) {\n      model_thread_ = ctx->StartThread(\"tf_data_model\", [this]() {\n        Status status =\n            model_->OptimizeLoop(dataset()->params_.autotune_algorithm,\n                                 dataset()->params_.autotune_cpu_budget,\n                                 dataset()->params_.autotune_ram_budget,\n                                 cancellation_manager_.get());\n        if (!status.ok()) {\n          LOG(WARNING) << \"Optimization loop failed: \" << status.ToString();\n        }\n      });\n    }\n    return OkStatus();\n  }\n\n  std::shared_ptr model_ = nullptr;\n  \/\/ Controls cancellation of `model_thread_`. Must be ordered before\n  \/\/ `model_thread_` so that `model_thread_` is destroyed first.\n  std::unique_ptr cancellation_manager_;\n  mutex mu_;\n  std::unique_ptr model_thread_ TF_GUARDED_BY(mu_);\n  int64_t max_intra_op_parallelism_;\n  int64_t threadpool_size_;\n  std::unique_ptr thread_pool_;\n\n  \/\/ Must be ordered last as its execution may depend on other members.\n  std::unique_ptr input_impl_;\n};\n\nRootDataset::RootDataset(const DatasetBase* input, const Params& params)\n    : DatasetBase(DatasetContext({name_utils::OpName(kDatasetType),\n                                  name_utils::OpName(kDatasetType)})),\n      input_(input),\n      params_(std::move(params)) {\n  AddTraceMetadata(params_, &traceme_metadata_);\n}\n\nRootDataset::RootDataset(core::RefCountPtr input,\n                         const Params& params)\n    : DatasetBase(DatasetContext({name_utils::OpName(kDatasetType),\n                                  name_utils::OpName(kDatasetType)})),\n      params_(std::move(params)) {\n  owned_input_ = std::move(input);\n  input_ = owned_input_.get();\n  AddTraceMetadata(params_, &traceme_metadata_);\n}\n\nRootDataset::~RootDataset() {}\n\nstd::unique_ptr RootDataset::MakeIteratorInternal(\n    const string& prefix) const {\n  return absl::make_unique(\n      Iterator::Params{this, name_utils::IteratorPrefix(kDatasetType, prefix)});\n}\n\nconst DataTypeVector& RootDataset::output_dtypes() const {\n  return input_->output_dtypes();\n}\n\nconst std::vector& RootDataset::output_shapes() const {\n  return input_->output_shapes();\n}\n\nstring RootDataset::DebugString() const {\n  return name_utils::DatasetDebugString(kDatasetType);\n}\n\nint64_t RootDataset::CardinalityInternal() const {\n  return input_->Cardinality();\n}\n\nint64_t RootDataset::CardinalityInternal(CardinalityOptions options) const {\n  return input_->Cardinality(options);\n}\n\nStatus RootDataset::Get(OpKernelContext* ctx, int64 index,\n                        std::vector* out_tensors) const {\n  std::vector inputs;\n  TF_RETURN_IF_ERROR(this->InputDatasets(&inputs));\n  return inputs[0]->Get(ctx, index, out_tensors);\n}\n\nStatus RootDataset::InputDatasets(\n    std::vector* inputs) const {\n  inputs->push_back(input_);\n  return OkStatus();\n}\n\nStatus RootDataset::CheckExternalState() const {\n  return input_->CheckExternalState();\n}\n\nStatus RootDataset::AsGraphDefInternal(SerializationContext* ctx,\n                                       DatasetGraphDefBuilder* b,\n                                       Node** output) const {\n  return errors::Unimplemented(\"RootDataset does not support serialization.\");\n}\n\n#if !defined(IS_MOBILE_PLATFORM)\nStatus FinalizeDataset(OpKernelContext* ctx, const DatasetBase* input,\n                       DatasetBase** output) {\n  const Options& options = input->options();\n  absl::flat_hash_set optimizations_enabled;\n  absl::flat_hash_set optimizations_disabled;\n  absl::flat_hash_set optimizations_default;\n  GetOptimizations(options, &optimizations_enabled, &optimizations_disabled,\n                   &optimizations_default);\n  \/\/ Disable `enable_gradient_descent` as it assumes presence of ModelDatasetOp.\n  optimizations_disabled.insert(\"enable_gradient_descent\");\n  if (!port::JobName().empty()) {\n    \/\/ Enable kInjectPrefetchEligibleOpt that does not modify the graph and is\n    \/\/ used to check whether the `inject_prefetch` optimization would modify the\n    \/\/ graph.\n    optimizations_enabled.insert(kInjectPrefetchEligibleOpt);\n  }\n\n  auto experiments = GetExperiments();\n  LogAndRecordExperiments(experiments);\n  auto optimizations =\n      SelectOptimizations(experiments, optimizations_enabled,\n                          optimizations_disabled, optimizations_default);\n  if (optimizations.empty()) {\n    return RootDataset::FromOptions(input, output);\n  }\n\n  auto optimization_configs = CreateGraphRewriteConfigs(options);\n  auto config_factory = [&optimizations, &optimization_configs]() {\n    return CreateRewriterConfig(optimizations, optimization_configs);\n  };\n  core::RefCountPtr rewritten_output;\n  Status s = RewriteDataset(ctx, input, std::move(config_factory),\n                            \/*record_fingerprint=*\/true, &rewritten_output);\n\n  *output = rewritten_output.get();\n  bool rewritten = (*output != input);\n  if (errors::IsDeadlineExceeded(s)) {\n    \/\/ Ignore DeadlineExceeded as it implies that the attempted rewrite took too\n    \/\/ long which should not prevent further computation.\n    LOG(WARNING) << s.ToString();\n  } else if (!s.ok()) {\n    return s;\n  }\n  if (!rewritten) {\n    return RootDataset::FromOptions(input, output);\n  } else {\n    return RootDataset::FromOptions(std::move(rewritten_output), output);\n  }\n  return OkStatus();\n}\n\n#else   \/\/ !IS_MOBILE_PLATFORM\nStatus FinalizeDataset(OpKernelContext* ctx, const DatasetBase* input,\n                       DatasetBase** output) {\n  return RootDataset::FromOptions(input, output);\n}\n#endif  \/\/ !IS_MOBILE_PLATFORM\n\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n#tf-data Fix memory usage percentage.\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/data\/root_dataset.h\"\n\n#include \n#include \n#include \n\n#include \"tensorflow\/core\/data\/dataset_utils.h\"\n#include \"tensorflow\/core\/data\/name_utils.h\"\n#include \"tensorflow\/core\/data\/rewrite_utils.h\"\n#include \"tensorflow\/core\/framework\/model.pb.h\"\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/host_info.h\"\n#include \"tensorflow\/core\/platform\/refcount.h\"\n#include \"tensorflow\/core\/platform\/stringprintf.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nconstexpr char kDatasetType[] = \"Root\";\n\nconstexpr char kAlgorithm[] = \"algorithm\";\nconstexpr char kCpuBudget[] = \"cpu_budget\";\nconstexpr char kExperiments[] = \"experiments\";\nconstexpr char kInjectPrefetchEligibleOpt[] = \"inject_prefetch_eligible\";\nconstexpr char kIntraOpParallelism[] = \"intra_op_parallelism\";\nconstexpr char kMemBandwidth[] = \"mem_bw_used_megabytes_per_sec\";\nconstexpr char kPrivateThreadpoolSize[] = \"threadpool_size\";\nconstexpr char kRamBudget[] = \"ram_budget_megabytes\";\nconstexpr char kRamUsage[] = \"ram_usage_megabytes\";\nconstexpr char kMaxBufferBytes[] = \"max_buffered_megabytes\";\n\n\/\/ If value `x` matches `y`, returns default value `z`. Otherwise, return `x`.\ninline int64_t value_or_default(int64_t x, int64_t y, int64_t z) {\n  return x == y ? z : x;\n}\n\nvoid SetRootDatasetParams(const Options& options, RootDataset::Params* params) {\n  if (ShouldConfigureMaxIntraOpParallelism(options)) {\n    params->max_intra_op_parallelism =\n        options.threading_options().max_intra_op_parallelism();\n  }\n  if (ShouldUsePrivateThreadPool(options)) {\n    params->private_threadpool_size =\n        options.threading_options().private_threadpool_size();\n  }\n  params->autotune = ShouldUseAutotuning(options);\n  if (params->autotune) {\n    params->autotune_algorithm =\n        options.autotune_options().optional_autotune_algorithm_case() ==\n                AutotuneOptions::kAutotuneAlgorithm\n            ? options.autotune_options().autotune_algorithm()\n            : model::AutotuneAlgorithm::DEFAULT;\n    params->autotune_cpu_budget = value_or_default(\n        options.autotune_options().cpu_budget(), 0, GetCpuBudget());\n    params->autotune_ram_budget =\n        value_or_default(options.autotune_options().ram_budget(), 0,\n                         model::kRamBudgetShare * port::AvailableRam());\n  }\n}\n\nvoid AddTraceMetadata(const RootDataset::Params& params,\n                      TraceMeMetadata* trace_metadata) {\n  if (params.autotune) {\n    trace_metadata->push_back(std::make_pair(\n        kAlgorithm, model::AutotuneAlgorithm_Name(params.autotune_algorithm)));\n    trace_metadata->push_back(std::make_pair(\n        kCpuBudget, strings::Printf(\"%lld\", static_cast(\n                                                params.autotune_cpu_budget))));\n    trace_metadata->push_back(std::make_pair(\n        kRamBudget,\n        strings::Printf(\"%lld\", static_cast(\n                                    params.autotune_ram_budget \/ 1.0e6))));\n  }\n  if (params.max_intra_op_parallelism >= 0) {\n    trace_metadata->push_back(std::make_pair(\n        kIntraOpParallelism,\n        strings::Printf(\"%lld\", static_cast(value_or_default(\n                                    params.max_intra_op_parallelism, 0,\n                                    port::MaxParallelism())))));\n  }\n  if (params.private_threadpool_size >= 0) {\n    trace_metadata->push_back(std::make_pair(\n        kPrivateThreadpoolSize,\n        strings::Printf(\"%lld\", static_cast(value_or_default(\n                                    params.private_threadpool_size, 0,\n                                    port::MaxParallelism())))));\n  }\n  auto experiments = GetExperiments();\n  if (!experiments.empty()) {\n    trace_metadata->push_back(\n        std::make_pair(kExperiments, absl::StrJoin(experiments, \" \")));\n  }\n}\n}  \/\/ namespace\n\n\/\/ static\nStatus RootDataset::FromOptions(const DatasetBase* input,\n                                DatasetBase** output) {\n  Params params;\n  SetRootDatasetParams(input->options(), ¶ms);\n  *output = new RootDataset(input, params);\n  (*output)->Initialize(\/*metadata=*\/{});\n  return OkStatus();\n}\n\nStatus RootDataset::FromOptions(core::RefCountPtr input,\n                                DatasetBase** output) {\n  Params params;\n  SetRootDatasetParams(input->options(), ¶ms);\n  *output = new RootDataset(std::move(input), params);\n  (*output)->Initialize(\/*metadata=*\/{});\n  return OkStatus();\n}\n\nclass RootDataset::Iterator : public DatasetIterator {\n public:\n  explicit Iterator(const Params& params)\n      : DatasetIterator(params) {\n    if (dataset()->params_.autotune) {\n      model_ = std::make_shared();\n    }\n    if (dataset()->params_.max_intra_op_parallelism >= 0) {\n      max_intra_op_parallelism_ =\n          value_or_default(dataset()->params_.max_intra_op_parallelism, 0,\n                           port::MaxParallelism());\n    }\n    if (dataset()->params_.private_threadpool_size >= 0) {\n      threadpool_size_ =\n          value_or_default(dataset()->params_.private_threadpool_size, 0,\n                           port::MaxParallelism());\n      thread_pool_ = absl::make_unique(\n          Env::Default(), ThreadOptions{}, \"data_private_threadpool\",\n          threadpool_size_);\n    }\n    cancellation_manager_ = absl::make_unique();\n  }\n\n  ~Iterator() override { cancellation_manager_->StartCancel(); }\n\n  Status Initialize(IteratorContext* ctx) override {\n    return dataset()->input_->MakeIterator(IteratorContext(CreateParams(ctx)),\n                                           this, prefix(), &input_impl_);\n  }\n\n  Status GetNextInternal(IteratorContext* ctx, std::vector* out_tensors,\n                         bool* end_of_sequence) override {\n    if (dataset()->params_.autotune) {\n      TF_RETURN_IF_ERROR(EnsureModelThreadStarted(ctx));\n    }\n    return input_impl_->GetNext(IteratorContext(CreateParams(ctx)), out_tensors,\n                                end_of_sequence);\n  }\n\n protected:\n  std::shared_ptr CreateNode(\n      IteratorContext* ctx, model::Node::Args args) const override {\n    return model::MakeKnownRatioNode(std::move(args), \/*ratio=*\/1);\n  }\n\n  Status SaveInternal(SerializationContext* ctx,\n                      IteratorStateWriter* writer) override {\n    TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_));\n    return OkStatus();\n  }\n\n  Status RestoreInternal(IteratorContext* ctx,\n                         IteratorStateReader* reader) override {\n    TF_RETURN_IF_ERROR(\n        RestoreInput(IteratorContext(CreateParams(ctx)), reader, input_impl_));\n    return OkStatus();\n  }\n\n  TraceMeMetadata GetTraceMeMetadata() const override {\n    tensorflow::data::TraceMeMetadata traceme_metadata =\n        dataset()->traceme_metadata_;\n    const int64_t mem_bw = port::GetMemoryBandwidthInfo().bw_used;\n    if (mem_bw != INT64_MAX) {\n      traceme_metadata.push_back(std::make_pair(\n          kMemBandwidth,\n          strings::Printf(\"%lld\", static_cast(mem_bw))));\n    }\n    const auto memory_info = port::GetMemoryInfo();\n    const auto memory_usage = memory_info.total - memory_info.free;\n    traceme_metadata.push_back(std::make_pair(\n        kRamUsage,\n        strings::Printf(\"%lld out of %lld (%.2f%%)\",\n                        static_cast(memory_usage \/ 1.0e6),\n                        static_cast(memory_info.total \/ 1.0e6),\n                        static_cast(100 * memory_usage) \/\n                            static_cast(memory_info.total))));\n    if (model_node() != nullptr) {\n      traceme_metadata.push_back(std::make_pair(\n          kMaxBufferBytes,\n          strings::Printf(\n              \"%lld\", static_cast(\n                          model_node()->TotalMaximumBufferedBytes() \/ 1.0e6))));\n    }\n    return traceme_metadata;\n  }\n\n private:\n  IteratorContext::Params CreateParams(IteratorContext* ctx) {\n    IteratorContext::Params params(ctx);\n    if (dataset()->params_.autotune) {\n      params.model = model_;\n    }\n    if (dataset()->params_.private_threadpool_size >= 0) {\n      params.runner = [pool = thread_pool_.get()](std::function c) {\n        pool->Schedule(std::move(c));\n      };\n      params.runner_threadpool_size = threadpool_size_;\n    }\n    if (dataset()->params_.max_intra_op_parallelism >= 0) {\n      params.runner =\n          RunnerWithMaxParallelism(params.runner, max_intra_op_parallelism_);\n    }\n    params.options = &dataset()->options();\n    return params;\n  }\n\n  Status EnsureModelThreadStarted(IteratorContext* ctx) {\n    mutex_lock l(mu_);\n    if (!model_thread_) {\n      model_thread_ = ctx->StartThread(\"tf_data_model\", [this]() {\n        Status status =\n            model_->OptimizeLoop(dataset()->params_.autotune_algorithm,\n                                 dataset()->params_.autotune_cpu_budget,\n                                 dataset()->params_.autotune_ram_budget,\n                                 cancellation_manager_.get());\n        if (!status.ok()) {\n          LOG(WARNING) << \"Optimization loop failed: \" << status.ToString();\n        }\n      });\n    }\n    return OkStatus();\n  }\n\n  std::shared_ptr model_ = nullptr;\n  \/\/ Controls cancellation of `model_thread_`. Must be ordered before\n  \/\/ `model_thread_` so that `model_thread_` is destroyed first.\n  std::unique_ptr cancellation_manager_;\n  mutex mu_;\n  std::unique_ptr model_thread_ TF_GUARDED_BY(mu_);\n  int64_t max_intra_op_parallelism_;\n  int64_t threadpool_size_;\n  std::unique_ptr thread_pool_;\n\n  \/\/ Must be ordered last as its execution may depend on other members.\n  std::unique_ptr input_impl_;\n};\n\nRootDataset::RootDataset(const DatasetBase* input, const Params& params)\n    : DatasetBase(DatasetContext({name_utils::OpName(kDatasetType),\n                                  name_utils::OpName(kDatasetType)})),\n      input_(input),\n      params_(std::move(params)) {\n  AddTraceMetadata(params_, &traceme_metadata_);\n}\n\nRootDataset::RootDataset(core::RefCountPtr input,\n                         const Params& params)\n    : DatasetBase(DatasetContext({name_utils::OpName(kDatasetType),\n                                  name_utils::OpName(kDatasetType)})),\n      params_(std::move(params)) {\n  owned_input_ = std::move(input);\n  input_ = owned_input_.get();\n  AddTraceMetadata(params_, &traceme_metadata_);\n}\n\nRootDataset::~RootDataset() {}\n\nstd::unique_ptr RootDataset::MakeIteratorInternal(\n    const string& prefix) const {\n  return absl::make_unique(\n      Iterator::Params{this, name_utils::IteratorPrefix(kDatasetType, prefix)});\n}\n\nconst DataTypeVector& RootDataset::output_dtypes() const {\n  return input_->output_dtypes();\n}\n\nconst std::vector& RootDataset::output_shapes() const {\n  return input_->output_shapes();\n}\n\nstring RootDataset::DebugString() const {\n  return name_utils::DatasetDebugString(kDatasetType);\n}\n\nint64_t RootDataset::CardinalityInternal() const {\n  return input_->Cardinality();\n}\n\nint64_t RootDataset::CardinalityInternal(CardinalityOptions options) const {\n  return input_->Cardinality(options);\n}\n\nStatus RootDataset::Get(OpKernelContext* ctx, int64 index,\n                        std::vector* out_tensors) const {\n  std::vector inputs;\n  TF_RETURN_IF_ERROR(this->InputDatasets(&inputs));\n  return inputs[0]->Get(ctx, index, out_tensors);\n}\n\nStatus RootDataset::InputDatasets(\n    std::vector* inputs) const {\n  inputs->push_back(input_);\n  return OkStatus();\n}\n\nStatus RootDataset::CheckExternalState() const {\n  return input_->CheckExternalState();\n}\n\nStatus RootDataset::AsGraphDefInternal(SerializationContext* ctx,\n                                       DatasetGraphDefBuilder* b,\n                                       Node** output) const {\n  return errors::Unimplemented(\"RootDataset does not support serialization.\");\n}\n\n#if !defined(IS_MOBILE_PLATFORM)\nStatus FinalizeDataset(OpKernelContext* ctx, const DatasetBase* input,\n                       DatasetBase** output) {\n  const Options& options = input->options();\n  absl::flat_hash_set optimizations_enabled;\n  absl::flat_hash_set optimizations_disabled;\n  absl::flat_hash_set optimizations_default;\n  GetOptimizations(options, &optimizations_enabled, &optimizations_disabled,\n                   &optimizations_default);\n  \/\/ Disable `enable_gradient_descent` as it assumes presence of ModelDatasetOp.\n  optimizations_disabled.insert(\"enable_gradient_descent\");\n  if (!port::JobName().empty()) {\n    \/\/ Enable kInjectPrefetchEligibleOpt that does not modify the graph and is\n    \/\/ used to check whether the `inject_prefetch` optimization would modify the\n    \/\/ graph.\n    optimizations_enabled.insert(kInjectPrefetchEligibleOpt);\n  }\n\n  auto experiments = GetExperiments();\n  LogAndRecordExperiments(experiments);\n  auto optimizations =\n      SelectOptimizations(experiments, optimizations_enabled,\n                          optimizations_disabled, optimizations_default);\n  if (optimizations.empty()) {\n    return RootDataset::FromOptions(input, output);\n  }\n\n  auto optimization_configs = CreateGraphRewriteConfigs(options);\n  auto config_factory = [&optimizations, &optimization_configs]() {\n    return CreateRewriterConfig(optimizations, optimization_configs);\n  };\n  core::RefCountPtr rewritten_output;\n  Status s = RewriteDataset(ctx, input, std::move(config_factory),\n                            \/*record_fingerprint=*\/true, &rewritten_output);\n\n  *output = rewritten_output.get();\n  bool rewritten = (*output != input);\n  if (errors::IsDeadlineExceeded(s)) {\n    \/\/ Ignore DeadlineExceeded as it implies that the attempted rewrite took too\n    \/\/ long which should not prevent further computation.\n    LOG(WARNING) << s.ToString();\n  } else if (!s.ok()) {\n    return s;\n  }\n  if (!rewritten) {\n    return RootDataset::FromOptions(input, output);\n  } else {\n    return RootDataset::FromOptions(std::move(rewritten_output), output);\n  }\n  return OkStatus();\n}\n\n#else   \/\/ !IS_MOBILE_PLATFORM\nStatus FinalizeDataset(OpKernelContext* ctx, const DatasetBase* input,\n                       DatasetBase** output) {\n  return RootDataset::FromOptions(input, output);\n}\n#endif  \/\/ !IS_MOBILE_PLATFORM\n\n}  \/\/ namespace data\n}  \/\/ namespace tensorflow\n<|endoftext|>"}
{"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/grappler\/op_types.h\"\n\nnamespace tensorflow {\nnamespace grappler {\n\nbool IsAddN(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"AddN\";\n}\n\nbool IsConcat(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Concat\" || op == \"ConcatV2\";\n}\n\nbool IsConstant(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Const\";\n}\n\nbool IsDequeueOp(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"QueueDequeueManyV2\" || op == \"QueueDequeueMany\" ||\n         op == \"QueueDequeueV2\" || op == \"QueueDequeue\" ||\n         op == \"QueueDequeueUpToV2\" || op == \"QueueDequeueUpTo\";\n}\n\nbool IsIdentity(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Identity\" || op == \"RefIdentity\";\n}\n\nbool IsMerge(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Merge\";\n}\n\nbool IsNoOp(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"NoOp\";\n}\n\nbool IsNextIteration(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"NextIteration\" || op == \"RefNextIteration\";\n}\n\nbool IsPlaceholder(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Placeholder\" || op == \"PlaceholderV2\" ||\n         op == \"PlaceholderWithDefault\";\n}\n\nbool IsRecv(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"_Recv\";\n}\n\nbool IsReduction(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Sum\" || op == \"Prod\" || op == \"Min\" || op == \"Max\" ||\n         op == \"Mean\" || op == \"Any\" || op == \"All\";\n}\n\nbool IsReshape(const NodeDef& node) { return (node.op() == \"Reshape\"); }\n\nbool IsSend(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"_Send\";\n}\n\nbool IsStopGradient(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"StopGradient\" || op == \"PreventGradient\";\n}\n\nbool IsSwitch(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Switch\";\n}\n\nbool IsTranspose(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Transpose\";\n}\n\nbool IsVariable(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Variable\" || op == \"VariableV2\" || op == \"AutoReloadVariable\" ||\n         op == \"VarHandleOp\" || op == \"TemporaryVariable\";\n}\n\n}  \/\/ end namespace grappler\n}  \/\/ end namespace tensorflow\nAdded support for RefMerge and RefSwitch to grappler\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/grappler\/op_types.h\"\n\nnamespace tensorflow {\nnamespace grappler {\n\nbool IsAddN(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"AddN\";\n}\n\nbool IsConcat(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Concat\" || op == \"ConcatV2\";\n}\n\nbool IsConstant(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Const\";\n}\n\nbool IsDequeueOp(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"QueueDequeueManyV2\" || op == \"QueueDequeueMany\" ||\n         op == \"QueueDequeueV2\" || op == \"QueueDequeue\" ||\n         op == \"QueueDequeueUpToV2\" || op == \"QueueDequeueUpTo\";\n}\n\nbool IsIdentity(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Identity\" || op == \"RefIdentity\";\n}\n\nbool IsMerge(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Merge\" || op == \"RefMerge\";\n}\n\nbool IsNoOp(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"NoOp\";\n}\n\nbool IsNextIteration(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"NextIteration\" || op == \"RefNextIteration\";\n}\n\nbool IsPlaceholder(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Placeholder\" || op == \"PlaceholderV2\" ||\n         op == \"PlaceholderWithDefault\";\n}\n\nbool IsRecv(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"_Recv\";\n}\n\nbool IsReduction(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Sum\" || op == \"Prod\" || op == \"Min\" || op == \"Max\" ||\n         op == \"Mean\" || op == \"Any\" || op == \"All\";\n}\n\nbool IsReshape(const NodeDef& node) { return (node.op() == \"Reshape\"); }\n\nbool IsSend(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"_Send\";\n}\n\nbool IsStopGradient(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"StopGradient\" || op == \"PreventGradient\";\n}\n\nbool IsSwitch(const NodeDef& node) {\n  const auto& op = node.op();\n  return op == \"Switch\" || op == \"RefSwitch\";\n}\n\nbool IsTranspose(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Transpose\";\n}\n\nbool IsVariable(const NodeDef& node) {\n  const auto op = node.op();\n  return op == \"Variable\" || op == \"VariableV2\" || op == \"AutoReloadVariable\" ||\n         op == \"VarHandleOp\" || op == \"TemporaryVariable\";\n}\n\n}  \/\/ end namespace grappler\n}  \/\/ end namespace tensorflow\n<|endoftext|>"}
{"text":"cf-gltf bone weights renormalization (probably not always necessary!)<|endoftext|>"}
{"text":"\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \n\nnamespace {\nusing namespace Rapicorn;\n\nclass ListStore : public virtual BaseObject, public virtual DataListContainer {\n  vector rows_;\nprotected:\n  typedef Aida::Signal UpdateSignal;\npublic:\n  explicit ListStore ();\n  int      count     () const;                          \/\/\/< Obtain the number of rows provided by this model.\n  Any      row       (int n) const;                     \/\/\/< Read-out row @a n. In-order read outs are generally fastest.\n  void     clear     ();                                \/\/\/< Remove all rows from the ListModel.\n  void     insert    (int n, const Any &aseq);          \/\/\/< Insert row @a n.\n  void     insert    (int n, const AnySeq &aseqseq);    \/\/\/< Insert multiple rows at @a n.\n  void     update    (int n, const Any &aseq);          \/\/\/< Reassign data to row @a n.\n  void     remove    (int n, int length);               \/\/\/< Remove @a length rows starting at @a n.\n  virtual ~ListStore ();\n  UpdateSignal sig_updates; \/\/\/< Notify about insertion, changes and deletion of a specific row range.\n};\n\nListStore::ListStore()\n{}\n\nListStore::~ListStore()\n{\n  clear();\n}\n\nint\nListStore::count () const\n{\n  return rows_.size();\n}\n\nAny\nListStore::row (int r) const\n{\n  return_unless (r >= 0 && r < count(), Any());\n  return rows_[r];\n}\n\nvoid\nListStore::clear ()\n{\n  if (rows_.size())\n    remove (0, rows_.size());\n}\n\nvoid\nListStore::insert (int first, const Any &any)\n{\n  assert_return (first >= 0 && first <= count());\n  rows_.insert (rows_.begin() + first, any);\n  sig_updates.emit (UpdateRequest (UPDATE_INSERTION, UpdateSpan (first, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::insert (int first, const AnySeq &aseq)\n{\n  assert_return (first >= 0 && first <= count());\n  for (size_t i = 0; i < aseq.size(); i++)\n    rows_.insert (rows_.begin() + i, aseq[i]);\n  sig_updates.emit (UpdateRequest (UPDATE_INSERTION, UpdateSpan (first, aseq.size())));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::update (int first, const Any &any)\n{\n  assert_return (first >= 0 && first < count());\n  rows_[first] = any;\n  sig_updates.emit (UpdateRequest (UPDATE_CHANGE, UpdateSpan (first, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::remove (int start, int length)\n{\n  return_unless (start >= 0 && start < count());\n  return_unless (length >= 0);\n  return_unless (start + length <= count());\n  rows_.erase (rows_.begin() + start, rows_.begin() + start + length);\n  sig_updates.emit (UpdateRequest (UPDATE_DELETION, UpdateSpan (start, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\n} \/\/ anon\nTESTS: derive ListStore from just ReferenceCountable and DataListContainer\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \n\nnamespace {\nusing namespace Rapicorn;\n\nclass ListStore : public virtual ReferenceCountable, public virtual DataListContainer {\n  vector rows_;\nprotected:\n  typedef Aida::Signal UpdateSignal;\npublic:\n  explicit ListStore ();\n  int      count     () const;                          \/\/\/< Obtain the number of rows provided by this model.\n  Any      row       (int n) const;                     \/\/\/< Read-out row @a n. In-order read outs are generally fastest.\n  void     clear     ();                                \/\/\/< Remove all rows from the ListModel.\n  void     insert    (int n, const Any &aseq);          \/\/\/< Insert row @a n.\n  void     insert    (int n, const AnySeq &aseqseq);    \/\/\/< Insert multiple rows at @a n.\n  void     update    (int n, const Any &aseq);          \/\/\/< Reassign data to row @a n.\n  void     remove    (int n, int length);               \/\/\/< Remove @a length rows starting at @a n.\n  virtual ~ListStore ();\n  UpdateSignal sig_updates; \/\/\/< Notify about insertion, changes and deletion of a specific row range.\n};\n\nListStore::ListStore()\n{}\n\nListStore::~ListStore()\n{\n  clear();\n}\n\nint\nListStore::count () const\n{\n  return rows_.size();\n}\n\nAny\nListStore::row (int r) const\n{\n  return_unless (r >= 0 && r < count(), Any());\n  return rows_[r];\n}\n\nvoid\nListStore::clear ()\n{\n  if (rows_.size())\n    remove (0, rows_.size());\n}\n\nvoid\nListStore::insert (int first, const Any &any)\n{\n  assert_return (first >= 0 && first <= count());\n  rows_.insert (rows_.begin() + first, any);\n  sig_updates.emit (UpdateRequest (UPDATE_INSERTION, UpdateSpan (first, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::insert (int first, const AnySeq &aseq)\n{\n  assert_return (first >= 0 && first <= count());\n  for (size_t i = 0; i < aseq.size(); i++)\n    rows_.insert (rows_.begin() + i, aseq[i]);\n  sig_updates.emit (UpdateRequest (UPDATE_INSERTION, UpdateSpan (first, aseq.size())));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::update (int first, const Any &any)\n{\n  assert_return (first >= 0 && first < count());\n  rows_[first] = any;\n  sig_updates.emit (UpdateRequest (UPDATE_CHANGE, UpdateSpan (first, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\nvoid\nListStore::remove (int start, int length)\n{\n  return_unless (start >= 0 && start < count());\n  return_unless (length >= 0);\n  return_unless (start + length <= count());\n  rows_.erase (rows_.begin() + start, rows_.begin() + start + length);\n  sig_updates.emit (UpdateRequest (UPDATE_DELETION, UpdateSpan (start, 1)));\n  ApplicationH::the().test_counter_get();\n}\n\n} \/\/ anon\n<|endoftext|>"}
{"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2006-2012, Paul Beckingham, Federico Hernandez.\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\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char** argv)\n{\n  UnitTest t (6);\n\n  std::string ascii_text = \"This is a test\";\n  std::string utf8_text  = \"más sábado miércoles\";\n\n  std::string ascii_text_color = \"This \u001b[1mis\u001b[0m a test\";\n  std::string utf8_text_color  = \"más \u001b[1msábado\u001b[0m miércoles\";\n\n  \/\/ TODO unsigned int utf8_codepoint (const std::string&);\n  \/\/ TODO unsigned int utf8_next_char (const std::string&, std::string::size_type&);\n  \/\/ TODO std::string utf8_character (unsigned int);\n  \/\/ TODO int utf8_sequence (unsigned int);\n\n  \/\/ unsigned int utf8_length (const std::string&);\n  t.is (utf8_length (ascii_text), 14, \"ASCII utf8_length\");\n  t.is (utf8_length (utf8_text),  20, \"UTF8 utf8_length\");\n\n  \/\/ unsigned int utf8_text_length (const std::string&);\n  t.is (utf8_text_length (ascii_text_color), 14, \"ASCII utf8_text_length\");\n  t.is (utf8_text_length (utf8_text_color),  20, \"UTF8 utf8_text_length\");\n\n  \/\/ const std::string utf8_substr (const std::string&, unsigned int, unsigned int length = 0);\n  t.is (utf8_substr (ascii_text, 0, 2), \"Th\", \"ASCII utf8_substr\");\n  t.is (utf8_substr (utf8_text, 0, 2),  \"má\", \"UTF8 utf8_substr\");\n\n  return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPortability\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2006-2012, Paul Beckingham, Federico Hernandez.\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\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char** argv)\n{\n  UnitTest t (6);\n\n  std::string ascii_text = \"This is a test\";\n  std::string utf8_text  = \"más sábado miércoles\";\n\n  std::string ascii_text_color = \"This \u001b[1mis\u001b[0m a test\";\n  std::string utf8_text_color  = \"más \u001b[1msábado\u001b[0m miércoles\";\n\n  \/\/ TODO unsigned int utf8_codepoint (const std::string&);\n  \/\/ TODO unsigned int utf8_next_char (const std::string&, std::string::size_type&);\n  \/\/ TODO std::string utf8_character (unsigned int);\n  \/\/ TODO int utf8_sequence (unsigned int);\n\n  \/\/ unsigned int utf8_length (const std::string&);\n  t.is ((int) utf8_length (ascii_text), 14, \"ASCII utf8_length\");\n  t.is ((int) utf8_length (utf8_text),  20, \"UTF8 utf8_length\");\n\n  \/\/ unsigned int utf8_text_length (const std::string&);\n  t.is ((int) utf8_text_length (ascii_text_color), 14, \"ASCII utf8_text_length\");\n  t.is ((int) utf8_text_length (utf8_text_color),  20, \"UTF8 utf8_text_length\");\n\n  \/\/ const std::string utf8_substr (const std::string&, unsigned int, unsigned int length = 0);\n  t.is (utf8_substr (ascii_text, 0, 2), \"Th\", \"ASCII utf8_substr\");\n  t.is (utf8_substr (utf8_text, 0, 2),  \"má\", \"UTF8 utf8_substr\");\n\n  return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"}
{"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/base\/models\/tree_node_model.h\"\n\nnamespace ui {\n\nclass TreeNodeModelTest : public testing::Test, public TreeModelObserver {\n public:\n  TreeNodeModelTest()\n      : added_count_(0),\n        removed_count_(0),\n        changed_count_(0) {}\n\n  void AssertObserverCount(int added_count,\n                           int removed_count,\n                           int changed_count) {\n    ASSERT_EQ(added_count, added_count_);\n    ASSERT_EQ(removed_count, removed_count_);\n    ASSERT_EQ(changed_count, changed_count_);\n  }\n\n  void ClearCounts() {\n    added_count_ = removed_count_ = changed_count_ = 0;\n  }\n\n  \/\/ Begin TreeModelObserver implementation.\n  virtual void TreeNodesAdded(TreeModel* model,\n                              TreeModelNode* parent,\n                              int start,\n                              int count) OVERRIDE {\n    added_count_++;\n  }\n  virtual void TreeNodesRemoved(TreeModel* model,\n                                TreeModelNode* parent,\n                                int start,\n                                int count) OVERRIDE {\n    removed_count_++;\n  }\n  virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) OVERRIDE {\n    changed_count_++;\n  }\n  \/\/ End TreeModelObserver implementation.\n\n private:\n  int added_count_;\n  int removed_count_;\n  int changed_count_;\n\n  DISALLOW_COPY_AND_ASSIGN(TreeNodeModelTest);\n};\n\n\/\/ Verify if the model is properly adding a new node in the tree and\n\/\/ notifying the observers.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo1\n\/\/ |   |-- foo2\n\/\/ +-- child2\nTEST_F(TreeNodeModelTest, AddNode) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  \/\/ Create the first root child.\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 1\"), 1);\n  model.Add(root, child1, 0);\n\n  AssertObserverCount(1, 0, 0);\n\n  \/\/ Add two nodes under the |child1|.\n  TreeNodeWithValue* foo1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo1\"), 3);\n  TreeNodeWithValue* foo2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo2\"), 4);\n  child1->Add(foo1, 0);\n  child1->Add(foo2, 1);\n\n  \/\/ Create the second root child.\n  TreeNodeWithValue* child2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 2\"), 2);\n  root->Add(child2, 1);\n\n  \/\/ Check if there is two nodes under the root.\n  ASSERT_EQ(2, model.GetChildCount(root));\n\n  \/\/ Check if there is two nodes under |child1|.\n  ASSERT_EQ(2, model.GetChildCount(child1));\n\n  \/\/ Check if there is none nodes under |child2|.\n  ASSERT_EQ(0, model.GetChildCount(child2));\n}\n\n\/\/ Verify if the model is properly removing a node from the tree\n\/\/ and notifying the observers.\nTEST_F(TreeNodeModelTest, RemoveNode) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  \/\/ Create the first child node.\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 1\"), 1);\n\n  \/\/ And add it to the root node.\n  root->Add(child1, 0);\n\n  ASSERT_EQ(1, model.GetChildCount(root));\n\n  \/\/ Now remove the |child1| from root and release the memory.\n  delete model.Remove(root, child1);\n\n  AssertObserverCount(0, 1, 0);\n\n  ASSERT_EQ(0, model.GetChildCount(root));\n}\n\n\/\/ Verify if the nodes added under the root are all deleted when calling\n\/\/ RemoveAll. Note that is responsability of the caller to free the memory\n\/\/ of the nodes removed after RemoveAll is called.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo\n\/\/ |       |-- bar0\n\/\/ |       |-- bar1\n\/\/ |       |-- bar2\n\/\/ |-- child2\n\/\/ +-- child3\nTEST_F(TreeNodeModelTest, RemoveAllNodes) {\n  TreeNodeWithValue root;\n\n  TreeNodeWithValue child1;\n  TreeNodeWithValue child2;\n  TreeNodeWithValue child3;\n\n  root.Add(&child1, 0);\n  root.Add(&child2, 1);\n  root.Add(&child3, 2);\n\n  TreeNodeWithValue* foo = new TreeNodeWithValue(2);\n  child1.Add(foo, 0);\n\n  \/\/ Add some nodes to |foo|.\n  for (int i = 0; i < 3; ++i)\n    foo->Add(new TreeNodeWithValue(i), i);\n\n  ASSERT_EQ(3, root.child_count());\n  ASSERT_EQ(1, child1.child_count());\n  ASSERT_EQ(3, foo->child_count());\n\n  \/\/ Now remove the child nodes from root.\n  root.RemoveAll();\n\n  ASSERT_EQ(0, root.child_count());\n  ASSERT_TRUE(root.empty());\n\n  ASSERT_EQ(1, child1.child_count());\n  ASSERT_EQ(3, foo->child_count());\n}\n\n\/\/ Verify if the model returns correct indexes for the specified nodes.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo1\n\/\/ +-- child2\nTEST_F(TreeNodeModelTest, GetIndexOf) {\n  TreeNodeWithValue root;\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root.Add(child1, 0);\n\n  TreeNodeWithValue* child2 = new TreeNodeWithValue(2);\n  root.Add(child2, 1);\n\n  TreeNodeWithValue* foo1 = new TreeNodeWithValue(0);\n  child1->Add(foo1, 0);\n\n  ASSERT_EQ(-1, root.GetIndexOf(&root));\n  ASSERT_EQ(0, root.GetIndexOf(child1));\n  ASSERT_EQ(1, root.GetIndexOf(child2));\n  ASSERT_EQ(-1, root.GetIndexOf(foo1));\n\n  ASSERT_EQ(-1, child1->GetIndexOf(&root));\n  ASSERT_EQ(-1, child1->GetIndexOf(child1));\n  ASSERT_EQ(-1, child1->GetIndexOf(child2));\n  ASSERT_EQ(0, child1->GetIndexOf(foo1));\n\n  ASSERT_EQ(-1, child2->GetIndexOf(&root));\n  ASSERT_EQ(-1, child2->GetIndexOf(child2));\n  ASSERT_EQ(-1, child2->GetIndexOf(child1));\n  ASSERT_EQ(-1, child2->GetIndexOf(foo1));\n}\n\n\/\/ Verify whether a specified node has or not an ancestor.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |-- child2\nTEST_F(TreeNodeModelTest, HasAncestor) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 1\"), 0);\n  model.Add(root, child1, 0);\n\n  TreeNodeWithValue* child2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 2\"), 1);\n  model.Add(root, child2, 1);\n\n  ASSERT_TRUE(root->HasAncestor(root));\n  ASSERT_FALSE(root->HasAncestor(child1));\n  ASSERT_TRUE(child1->HasAncestor(root));\n  ASSERT_FALSE(child1->HasAncestor(child2));\n  ASSERT_FALSE(child2->HasAncestor(child1));\n}\n\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- child2\n\/\/ |       |-- child3\n\/\/ |-- foo1\n\/\/ |   |-- foo2\n\/\/ |       |-- foo3\n\/\/ |   |-- foo4\n\/\/ +-- bar1\n\/\/\n\/\/ The TotalNodeCount of root is:   9\n\/\/ The TotalNodeCount of child1 is: 3\n\/\/ The TotalNodeCount of bar1 is:   1\n\/\/ And so on...\n\/\/ The purpose here is to verify if the function returns the total of nodes\n\/\/ under the specifed node correctly. The count should include the node it self.\nTEST_F(TreeNodeModelTest, GetTotalNodeCount) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child1\"), 1);\n  TreeNodeWithValue* child2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child2\"), 2);\n  TreeNodeWithValue* child3 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child3\"), 3);\n  TreeNodeWithValue* foo1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo1\"), 4);\n  TreeNodeWithValue* foo2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo2\"), 5);\n  TreeNodeWithValue* foo3 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo3\"), 6);\n  TreeNodeWithValue* foo4 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo4\"), 7);\n  TreeNodeWithValue* bar1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"bar1\"), 8);\n\n  model.Add(root, child1, 0);\n  model.Add(child1, child2, 0);\n  model.Add(child2, child3, 0);\n\n  model.Add(root, foo1, 1);\n  model.Add(foo1, foo2, 0);\n  model.Add(foo1, foo4, 1);\n  model.Add(foo2, foo3, 0);\n\n  model.Add(root, bar1, 0);\n\n  ASSERT_EQ(9, root->GetTotalNodeCount());\n  ASSERT_EQ(3, child1->GetTotalNodeCount());\n  ASSERT_EQ(1, bar1->GetTotalNodeCount());\n  ASSERT_EQ(2, foo2->GetTotalNodeCount());\n}\n\n\/\/ Makes sure that we are notified when the node is renamed,\n\/\/ also makes sure the node is properly renamed.\nTEST_F(TreeNodeModelTest, SetTitle) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  const string16 title(ASCIIToUTF16(\"root2\"));\n  model.SetTitle(root, title);\n  AssertObserverCount(0, 0, 1);\n  EXPECT_EQ(title, root->GetTitle());\n}\n\nTEST_F(TreeNodeModelTest, BasicOperations) {\n  TreeNodeWithValue* root = new TreeNodeWithValue(0);\n  EXPECT_EQ(0, root->child_count());\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root->Add(child1, root->child_count());\n  EXPECT_EQ(1, root->child_count());\n  EXPECT_EQ(root, child1->parent());\n\n  TreeNodeWithValue* child2 = new TreeNodeWithValue(1);\n  root->Add(child2, root->child_count());\n  EXPECT_EQ(2, root->child_count());\n  EXPECT_EQ(child1->parent(), child2->parent());\n\n  root->Remove(child2);\n  EXPECT_EQ(1, root->child_count());\n  EXPECT_EQ(NULL, child2->parent());\n  delete child2;\n\n  delete root->Remove(child1);\n  EXPECT_EQ(0, root->child_count());\n\n  delete root;\n}\n\nTEST_F(TreeNodeModelTest, IsRoot) {\n  TreeNodeWithValue root;\n  EXPECT_TRUE(root.is_root());\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root.Add(child1, root.child_count());\n  EXPECT_FALSE(child1->is_root());\n}\n\n}  \/\/ namespace ui\nui\/base\/models: Rewrite the TreeNodeModelTest.HasAncestor unittest.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/base\/models\/tree_node_model.h\"\n\nnamespace ui {\n\nclass TreeNodeModelTest : public testing::Test, public TreeModelObserver {\n public:\n  TreeNodeModelTest()\n      : added_count_(0),\n        removed_count_(0),\n        changed_count_(0) {}\n\n  void AssertObserverCount(int added_count,\n                           int removed_count,\n                           int changed_count) {\n    ASSERT_EQ(added_count, added_count_);\n    ASSERT_EQ(removed_count, removed_count_);\n    ASSERT_EQ(changed_count, changed_count_);\n  }\n\n  void ClearCounts() {\n    added_count_ = removed_count_ = changed_count_ = 0;\n  }\n\n  \/\/ Begin TreeModelObserver implementation.\n  virtual void TreeNodesAdded(TreeModel* model,\n                              TreeModelNode* parent,\n                              int start,\n                              int count) OVERRIDE {\n    added_count_++;\n  }\n  virtual void TreeNodesRemoved(TreeModel* model,\n                                TreeModelNode* parent,\n                                int start,\n                                int count) OVERRIDE {\n    removed_count_++;\n  }\n  virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) OVERRIDE {\n    changed_count_++;\n  }\n  \/\/ End TreeModelObserver implementation.\n\n private:\n  int added_count_;\n  int removed_count_;\n  int changed_count_;\n\n  DISALLOW_COPY_AND_ASSIGN(TreeNodeModelTest);\n};\n\n\/\/ Verify if the model is properly adding a new node in the tree and\n\/\/ notifying the observers.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo1\n\/\/ |   |-- foo2\n\/\/ +-- child2\nTEST_F(TreeNodeModelTest, AddNode) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  \/\/ Create the first root child.\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 1\"), 1);\n  model.Add(root, child1, 0);\n\n  AssertObserverCount(1, 0, 0);\n\n  \/\/ Add two nodes under the |child1|.\n  TreeNodeWithValue* foo1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo1\"), 3);\n  TreeNodeWithValue* foo2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo2\"), 4);\n  child1->Add(foo1, 0);\n  child1->Add(foo2, 1);\n\n  \/\/ Create the second root child.\n  TreeNodeWithValue* child2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 2\"), 2);\n  root->Add(child2, 1);\n\n  \/\/ Check if there is two nodes under the root.\n  ASSERT_EQ(2, model.GetChildCount(root));\n\n  \/\/ Check if there is two nodes under |child1|.\n  ASSERT_EQ(2, model.GetChildCount(child1));\n\n  \/\/ Check if there is none nodes under |child2|.\n  ASSERT_EQ(0, model.GetChildCount(child2));\n}\n\n\/\/ Verify if the model is properly removing a node from the tree\n\/\/ and notifying the observers.\nTEST_F(TreeNodeModelTest, RemoveNode) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  \/\/ Create the first child node.\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child 1\"), 1);\n\n  \/\/ And add it to the root node.\n  root->Add(child1, 0);\n\n  ASSERT_EQ(1, model.GetChildCount(root));\n\n  \/\/ Now remove the |child1| from root and release the memory.\n  delete model.Remove(root, child1);\n\n  AssertObserverCount(0, 1, 0);\n\n  ASSERT_EQ(0, model.GetChildCount(root));\n}\n\n\/\/ Verify if the nodes added under the root are all deleted when calling\n\/\/ RemoveAll. Note that is responsability of the caller to free the memory\n\/\/ of the nodes removed after RemoveAll is called.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo\n\/\/ |       |-- bar0\n\/\/ |       |-- bar1\n\/\/ |       |-- bar2\n\/\/ |-- child2\n\/\/ +-- child3\nTEST_F(TreeNodeModelTest, RemoveAllNodes) {\n  TreeNodeWithValue root;\n\n  TreeNodeWithValue child1;\n  TreeNodeWithValue child2;\n  TreeNodeWithValue child3;\n\n  root.Add(&child1, 0);\n  root.Add(&child2, 1);\n  root.Add(&child3, 2);\n\n  TreeNodeWithValue* foo = new TreeNodeWithValue(2);\n  child1.Add(foo, 0);\n\n  \/\/ Add some nodes to |foo|.\n  for (int i = 0; i < 3; ++i)\n    foo->Add(new TreeNodeWithValue(i), i);\n\n  ASSERT_EQ(3, root.child_count());\n  ASSERT_EQ(1, child1.child_count());\n  ASSERT_EQ(3, foo->child_count());\n\n  \/\/ Now remove the child nodes from root.\n  root.RemoveAll();\n\n  ASSERT_EQ(0, root.child_count());\n  ASSERT_TRUE(root.empty());\n\n  ASSERT_EQ(1, child1.child_count());\n  ASSERT_EQ(3, foo->child_count());\n}\n\n\/\/ Verify if the model returns correct indexes for the specified nodes.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo1\n\/\/ +-- child2\nTEST_F(TreeNodeModelTest, GetIndexOf) {\n  TreeNodeWithValue root;\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root.Add(child1, 0);\n\n  TreeNodeWithValue* child2 = new TreeNodeWithValue(2);\n  root.Add(child2, 1);\n\n  TreeNodeWithValue* foo1 = new TreeNodeWithValue(0);\n  child1->Add(foo1, 0);\n\n  ASSERT_EQ(-1, root.GetIndexOf(&root));\n  ASSERT_EQ(0, root.GetIndexOf(child1));\n  ASSERT_EQ(1, root.GetIndexOf(child2));\n  ASSERT_EQ(-1, root.GetIndexOf(foo1));\n\n  ASSERT_EQ(-1, child1->GetIndexOf(&root));\n  ASSERT_EQ(-1, child1->GetIndexOf(child1));\n  ASSERT_EQ(-1, child1->GetIndexOf(child2));\n  ASSERT_EQ(0, child1->GetIndexOf(foo1));\n\n  ASSERT_EQ(-1, child2->GetIndexOf(&root));\n  ASSERT_EQ(-1, child2->GetIndexOf(child2));\n  ASSERT_EQ(-1, child2->GetIndexOf(child1));\n  ASSERT_EQ(-1, child2->GetIndexOf(foo1));\n}\n\n\/\/ Verify whether a specified node has or not an ancestor.\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- foo1\n\/\/ +-- child2\nTEST_F(TreeNodeModelTest, HasAncestor) {\n  TreeNodeWithValue root;\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(0);\n  TreeNodeWithValue* child2 = new TreeNodeWithValue(0);\n\n  root.Add(child1, 0);\n  root.Add(child2, 1);\n\n  TreeNodeWithValue* foo1 = new TreeNodeWithValue(0);\n  child1->Add(foo1, 0);\n\n  ASSERT_TRUE(root.HasAncestor(&root));\n  ASSERT_FALSE(root.HasAncestor(child1));\n  ASSERT_FALSE(root.HasAncestor(child2));\n  ASSERT_FALSE(root.HasAncestor(foo1));\n\n  ASSERT_TRUE(child1->HasAncestor(child1));\n  ASSERT_TRUE(child1->HasAncestor(&root));\n  ASSERT_FALSE(child1->HasAncestor(child2));\n  ASSERT_FALSE(child1->HasAncestor(foo1));\n\n  ASSERT_TRUE(child2->HasAncestor(child2));\n  ASSERT_TRUE(child2->HasAncestor(&root));\n  ASSERT_FALSE(child2->HasAncestor(child1));\n  ASSERT_FALSE(child2->HasAncestor(foo1));\n\n  ASSERT_TRUE(foo1->HasAncestor(foo1));\n  ASSERT_TRUE(foo1->HasAncestor(child1));\n  ASSERT_TRUE(foo1->HasAncestor(&root));\n  ASSERT_FALSE(foo1->HasAncestor(child2));\n}\n\n\/\/ The tree looks like this:\n\/\/ root\n\/\/ |-- child1\n\/\/ |   |-- child2\n\/\/ |       |-- child3\n\/\/ |-- foo1\n\/\/ |   |-- foo2\n\/\/ |       |-- foo3\n\/\/ |   |-- foo4\n\/\/ +-- bar1\n\/\/\n\/\/ The TotalNodeCount of root is:   9\n\/\/ The TotalNodeCount of child1 is: 3\n\/\/ The TotalNodeCount of bar1 is:   1\n\/\/ And so on...\n\/\/ The purpose here is to verify if the function returns the total of nodes\n\/\/ under the specifed node correctly. The count should include the node it self.\nTEST_F(TreeNodeModelTest, GetTotalNodeCount) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n\n  TreeNodeWithValue* child1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child1\"), 1);\n  TreeNodeWithValue* child2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child2\"), 2);\n  TreeNodeWithValue* child3 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"child3\"), 3);\n  TreeNodeWithValue* foo1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo1\"), 4);\n  TreeNodeWithValue* foo2 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo2\"), 5);\n  TreeNodeWithValue* foo3 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo3\"), 6);\n  TreeNodeWithValue* foo4 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"foo4\"), 7);\n  TreeNodeWithValue* bar1 =\n      new TreeNodeWithValue(ASCIIToUTF16(\"bar1\"), 8);\n\n  model.Add(root, child1, 0);\n  model.Add(child1, child2, 0);\n  model.Add(child2, child3, 0);\n\n  model.Add(root, foo1, 1);\n  model.Add(foo1, foo2, 0);\n  model.Add(foo1, foo4, 1);\n  model.Add(foo2, foo3, 0);\n\n  model.Add(root, bar1, 0);\n\n  ASSERT_EQ(9, root->GetTotalNodeCount());\n  ASSERT_EQ(3, child1->GetTotalNodeCount());\n  ASSERT_EQ(1, bar1->GetTotalNodeCount());\n  ASSERT_EQ(2, foo2->GetTotalNodeCount());\n}\n\n\/\/ Makes sure that we are notified when the node is renamed,\n\/\/ also makes sure the node is properly renamed.\nTEST_F(TreeNodeModelTest, SetTitle) {\n  TreeNodeWithValue* root =\n      new TreeNodeWithValue(ASCIIToUTF16(\"root\"), 0);\n  TreeNodeModel > model(root);\n  model.AddObserver(this);\n  ClearCounts();\n\n  const string16 title(ASCIIToUTF16(\"root2\"));\n  model.SetTitle(root, title);\n  AssertObserverCount(0, 0, 1);\n  EXPECT_EQ(title, root->GetTitle());\n}\n\nTEST_F(TreeNodeModelTest, BasicOperations) {\n  TreeNodeWithValue* root = new TreeNodeWithValue(0);\n  EXPECT_EQ(0, root->child_count());\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root->Add(child1, root->child_count());\n  EXPECT_EQ(1, root->child_count());\n  EXPECT_EQ(root, child1->parent());\n\n  TreeNodeWithValue* child2 = new TreeNodeWithValue(1);\n  root->Add(child2, root->child_count());\n  EXPECT_EQ(2, root->child_count());\n  EXPECT_EQ(child1->parent(), child2->parent());\n\n  root->Remove(child2);\n  EXPECT_EQ(1, root->child_count());\n  EXPECT_EQ(NULL, child2->parent());\n  delete child2;\n\n  delete root->Remove(child1);\n  EXPECT_EQ(0, root->child_count());\n\n  delete root;\n}\n\nTEST_F(TreeNodeModelTest, IsRoot) {\n  TreeNodeWithValue root;\n  EXPECT_TRUE(root.is_root());\n\n  TreeNodeWithValue* child1 = new TreeNodeWithValue(1);\n  root.Add(child1, root.child_count());\n  EXPECT_FALSE(child1->is_root());\n}\n\n}  \/\/ namespace ui\n<|endoftext|>"}
{"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n#include \n#include \n\nvoid export_raster_symbolizer()\n{\n    using namespace boost::python;\n    using mapnik::raster_symbolizer;\n    \n    class_(\"RasterSymbolizer\",\n\t\t\t\t    init<>(\"Default ctor\"))\n\t;    \n}\n+ reflect raster symbolizer options in python (may need to eventually switch to ENUMS)\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n#include \n#include \n\nvoid export_raster_symbolizer()\n{\n    using namespace boost::python;\n    using mapnik::raster_symbolizer;\n\n    class_(\"RasterSymbolizer\",\n\t\t\t\t    init<>(\"Default ctor\"))\n    \n    .add_property(\"mode\",\n            make_function(&raster_symbolizer::get_mode,return_value_policy()),\n            &raster_symbolizer::set_mode,\n            \"Get\/Set merging mode.\\n\"\n            \"Possible values are:\\n\"\n            \"normal, grain_merge, grain_merge2, multiply,\\n\"\n            \"multiply2, divide, divide2, screen, and hard_light\\n\"\n            \"\\n\"\n            \"Usage:\\n\"\n            \"\\n\"\n            \">>> from mapnik import RasterSymbolizer\\n\"\n            \">>> r = RasterSymbolizer()\\n\"\n            \">>> r.mode = 'grain_merge2'\\n\"\n            )\n            \n    .add_property(\"scaling\",\n            make_function(&raster_symbolizer::get_scaling,return_value_policy()),\n            &raster_symbolizer::set_scaling,\n            \"Get\/Set scaling algorithm.\\n\"\n            \"Possible values are:\\n\"\n            \"fast, bilinear, and bilinear8\\n\"\n            \"\\n\"\n            \"Usage:\\n\"\n            \"\\n\"\n            \">>> from mapnik import RasterSymbolizer\\n\"\n            \">>> r = RasterSymbolizer()\\n\"\n            \">>> r.scaling = 'bilinear8'\\n\"\n            )\n            \n    .add_property(\"opacity\",\n            &raster_symbolizer::get_opacity,\n            &raster_symbolizer::set_opacity,\n            \"Get\/Set opacity.\\n\"\n            \"\\n\"\n            \"Usage:\\n\"\n            \"\\n\"\n            \">>> from mapnik import RasterSymbolizer\\n\"\n            \">>> r = RasterSymbolizer()\\n\"\n            \">>> r.opacity = .5\\n\"\n            )\n\t;    \n}\n<|endoftext|>"}
{"text":"#include \n#include \"debug_lldb.h\"\n#include \n#include \n#include \n\nint main() {\n  auto build_path=boost::filesystem::canonical(JUCI_BUILD_PATH);\n  auto exec_path=build_path\/\"tests\"\/\"lldb_test_files\"\/\"lldb_test_executable\";\n  g_assert(boost::filesystem::exists(exec_path));\n  \n  auto tests_path=boost::filesystem::canonical(JUCI_TESTS_PATH);\n  auto source_path=tests_path\/\"lldb_test_files\"\/\"main.cpp\";\n  g_assert(boost::filesystem::exists(source_path));\n  \n  std::vector > breakpoints;\n  breakpoints.emplace_back(source_path, 2);\n  \n  std::atomic exited(false);\n  int exit_status;\n  std::atomic line_nr(0);\n  std::thread debug_thread([&] {\n    Debug::LLDB::get().start(exec_path.string(), \"\", breakpoints, [&](int exit_status_){\n      exit_status=exit_status_;\n      exited=true;\n    }, [](const std::string &status) {\n      \n    }, [&](const boost::filesystem::path &file_path, int line_nr_, int line_index) {\n      line_nr=line_nr_;\n    });\n  });\n  debug_thread.detach();\n  \n  for(;;) {\n    if(exited) {\n      g_assert_cmpint(exit_status, ==, 0);\n      break;\n    }\n    else if(line_nr>0) {\n      for(;;) {\n        if(Debug::LLDB::get().is_stopped())\n          break;\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n      }\n      g_assert_cmpint(line_nr, ==, 2);\n      g_assert(Debug::LLDB::get().get_backtrace().size()>0);\n      auto variables=Debug::LLDB::get().get_variables();\n      g_assert_cmpstr(variables.at(0).name.c_str(), ==, \"an_int\");\n      line_nr=0;\n      Debug::LLDB::get().step_over();\n      for(;;) {\n        if(line_nr>0 && Debug::LLDB::get().is_stopped())\n          break;\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n      }\n      g_assert_cmpint(line_nr, ==, 3);\n      g_assert(Debug::LLDB::get().get_backtrace().size()>0);\n      variables=Debug::LLDB::get().get_variables();\n      g_assert_cmpstr(variables.at(0).name.c_str(), ==, \"an_int\");\n      auto value=Debug::LLDB::get().get_value(\"an_int\", source_path, 2, 7);\n      g_assert_cmpuint(value.size(), >, 16);\n      auto value_substr=value.substr(0, 16);\n      g_assert_cmpstr(value_substr.c_str(), ==, \"(int) an_int = 1\");\n      line_nr=0;\n      Debug::LLDB::get().continue_debug();\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(10));\n  }\n  \n  Debug::LLDB::get().cancel();\n}\nNow joins debug_thread in lldb_test#include \n#include \"debug_lldb.h\"\n#include \n#include \n#include \n\nint main() {\n  auto build_path=boost::filesystem::canonical(JUCI_BUILD_PATH);\n  auto exec_path=build_path\/\"tests\"\/\"lldb_test_files\"\/\"lldb_test_executable\";\n  g_assert(boost::filesystem::exists(exec_path));\n  \n  auto tests_path=boost::filesystem::canonical(JUCI_TESTS_PATH);\n  auto source_path=tests_path\/\"lldb_test_files\"\/\"main.cpp\";\n  g_assert(boost::filesystem::exists(source_path));\n  \n  std::vector > breakpoints;\n  breakpoints.emplace_back(source_path, 2);\n  \n  std::atomic exited(false);\n  int exit_status;\n  std::atomic line_nr(0);\n  std::thread debug_thread([&] {\n    Debug::LLDB::get().start(exec_path.string(), \"\", breakpoints, [&](int exit_status_){\n      exit_status=exit_status_;\n      exited=true;\n    }, [](const std::string &status) {\n      \n    }, [&](const boost::filesystem::path &file_path, int line_nr_, int line_index) {\n      line_nr=line_nr_;\n    });\n  });\n  \n  for(;;) {\n    if(exited) {\n      g_assert_cmpint(exit_status, ==, 0);\n      break;\n    }\n    else if(line_nr>0) {\n      for(;;) {\n        if(Debug::LLDB::get().is_stopped())\n          break;\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n      }\n      g_assert_cmpint(line_nr, ==, 2);\n      g_assert(Debug::LLDB::get().get_backtrace().size()>0);\n      auto variables=Debug::LLDB::get().get_variables();\n      g_assert_cmpstr(variables.at(0).name.c_str(), ==, \"an_int\");\n      line_nr=0;\n      Debug::LLDB::get().step_over();\n      for(;;) {\n        if(line_nr>0 && Debug::LLDB::get().is_stopped())\n          break;\n        std::this_thread::sleep_for(std::chrono::milliseconds(100));\n      }\n      g_assert_cmpint(line_nr, ==, 3);\n      g_assert(Debug::LLDB::get().get_backtrace().size()>0);\n      variables=Debug::LLDB::get().get_variables();\n      g_assert_cmpstr(variables.at(0).name.c_str(), ==, \"an_int\");\n      auto value=Debug::LLDB::get().get_value(\"an_int\", source_path, 2, 7);\n      g_assert_cmpuint(value.size(), >, 16);\n      auto value_substr=value.substr(0, 16);\n      g_assert_cmpstr(value_substr.c_str(), ==, \"(int) an_int = 1\");\n      line_nr=0;\n      Debug::LLDB::get().continue_debug();\n    }\n    std::this_thread::sleep_for(std::chrono::milliseconds(10));\n  }\n  \n  Debug::LLDB::get().cancel();\n  \n  debug_thread.join();\n}\n<|endoftext|>"}
{"text":"#include \"game_state.hpp\"\n\n#include \"start_game_state.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstatic std::vector colors = {\"red\", \"green\", \"blue\", \"yellow\"};\nstd::string GameState::name_(\"Game State\");\n\nGameState::GameState(std::shared_ptr stm,\n        const std::vector &player_types) : stm_(stm), anim_(),\n    game_(new Game(9, 9)), pf_(), players_(), pawn_list_(), cur_pawn_(),\n    drag_list_(), pawn_wins_(), wall_wins_(), pawn_path_(),\n    added_wall_(Wall::kInvalid, 0, 0, 0), wall_idx_(0),\n    status_(kWaitingForMove),\n    pos_utils_(9, 52, 50)\n{\n    lg.add_attribute(\"Tag\", blattrs::constant(\"game state\"));\n\n    init_gui_();\n    subscribe_for_events_();\n\n    if ((player_types.size() != 2) && (player_types.size() != 4)) {\n        throw Exception(\"Invalid number of players\");\n    }\n\n    for (size_t i = 0; i < player_types.size(); ++i) {\n        std::shared_ptr pawn(new Pawn(colors[i]));\n        pawn_list_.push_back(pawn);\n    }\n\n    try {\n        game_->set_pawns(pawn_list_);\n    }\n    catch (Exception &e) {\n        BOOST_LOG_ERROR(lg) << \"failed to create game: \" << e.what();\n        throw;\n    }\n\n    int i = 0;\n    for (auto player_type : player_types) {\n        BOOST_LOG_INFO(lg) << \"adding player \" << player_type << \" (\" << colors[i] << \")\";\n        players_[pawn_list_[i]] = pf_.make_player(player_type, game_, pawn_list_[i]);\n        ++i;\n    }\n\n    set_pawns_();\n    init_walls_();\n    switch_cur_pawn_();\n\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_[cur_pawn_]->enable_drag();\n    }\n}\n\nGameState::~GameState()\n{\n}\n\nvoid GameState::update()\n{\n    switch (status_) {\n    case kPreparingMove:\n        pre_process_move_();\n        status_ = kWaitingForMove;\n        break;\n    case kWaitingForMove:\n        make_move_();\n        break;\n    case kPerformedMove:\n        post_process_move_();\n        if (is_finished_()) {\n            BOOST_LOG_INFO(lg) << cur_pawn_->color() << \" win\";\n            status_ = kFinished;\n        }\n        else {\n            switch_cur_pawn_();\n            status_ = kPreparingMove;\n        }\n        break;\n    case kNeedPawnRedraw:\n        redraw_pawn_();\n        status_ = kWaitingForAnimationEnd;\n        break;\n    case kNeedDrawWall:\n        draw_wall_();\n        status_ = kPerformedMove;\n        break;\n    case kWaitingForAnimationEnd:\n        break;\n    case kFinished:\n        break;\n    default:\n        break;\n    }\n}\n\nstd::shared_ptr GameState::window() const\n{\n    return win_;\n}\n\nconst std::string &GameState::name() const\n{\n    return name_;\n}\n\nvoid GameState::init_gui_()\n{\n    CEGUI::ImageManager::getSingleton().loadImageset(\"pawn.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"board.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"wall.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"wall_repr.imageset\");\n\n    win_ = std::shared_ptr(\n            CEGUI::WindowManager::getSingleton().\n                    loadLayoutFromFile(\"game.layout\"),\n            [=](CEGUI::Window *w) {\n                CEGUI::WindowManager::getSingleton().destroyWindow(w);\n            }\n    );\n\n    anim_ = std::shared_ptr(\n            CEGUI::AnimationManager::getSingleton().\n                    createAnimation(\"movePawn\"),\n            [=](CEGUI::Animation *anim) {\n                CEGUI::AnimationManager::getSingleton().destroyAnimation(anim);\n            }\n    );\n    anim_->setDuration(0.5);\n    anim_->setReplayMode(CEGUI::Animation::RM_Once);\n}\n\nvoid GameState::set_pawns_()\n{\n    auto board_win = static_cast(win_->getChild(\"boardWindow\"));\n\n    board_win->subscribeEvent(\n            CEGUI_Ext::DraggableWindow::EventDraggableWindowDropped,\n            CEGUI::Event::Subscriber(&GameState::handle_window_dropped_, this));\n\n    CEGUI::Window *drag_win;\n    for (auto pawn_data : game_->pawn_data_list()) {\n        if (players_[pawn_data.pawn]->is_interactive()) {\n            drag_win = new CEGUI_Ext::DraggableWindow(\"DefaultWindow\", pawn_data.pawn->color());\n            drag_list_[pawn_data.pawn] = static_cast(drag_win);\n            drag_list_[pawn_data.pawn]->disable_drag();\n            pawn_wins_[drag_win] = pawn_data.pawn;\n        }\n        else {\n            drag_win = CEGUI::WindowManager::getSingleton().\n                createWindow(\"DefaultWindow\", pawn_data.pawn->color());\n            drag_win->subscribeEvent(\n                    CEGUI::AnimationInstance::EventAnimationEnded,\n                    CEGUI::Event::Subscriber(&GameState::handle_end_anim_, this));\n        }\n\n        drag_win->setSize(CEGUI::USize({0.1, 0}, {0.1, 0}));\n        CEGUI::UVector2 pos = pos_utils_.node_to_pos(pawn_data.node);\n        drag_win->setPosition(pos);\n\n        auto pawn_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n        drag_win->addChild(pawn_win);\n        board_win->addChild(drag_win);\n    }\n}\n\nvoid GameState::init_walls_()\n{\n    auto ws1 = static_cast(win_->getChild(\"boardWindow\"));\n    for (int i = 0; i < 10; ++i) {\n        auto w1 = new CEGUI_Ext::DraggableWindow(\"DefaultWindow\", \"wall_1_\" + std::to_string(i));\n        w1->setPosition(CEGUI::UVector2({{0.0f, 25.0f * i + 4.0f}, {0.0f, 4.0f}}));\n        w1->setSize(CEGUI::USize({{0.0, 21.0}, {0.0, 42.0}}));\n\n        auto wall_img = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"wall_repr.layout\");\n        w1->addChild(wall_img);\n        ws1->addChild(w1);\n\n        wall_wins_[w1] = 1;\n    }\n}\n\nvoid GameState::redraw_pawn_()\n{\n    Node old_node = pawn_path_[0];\n    Node new_node = pawn_path_[1];\n\n    pawn_path_.clear();\n\n    CEGUI::UVector2 old_pos = pos_utils_.node_to_pos(old_node);\n    CEGUI::UVector2 new_pos = pos_utils_.node_to_pos(new_node);\n    std::string old_pos_str = \"{{\" + std::to_string(old_pos.d_x.d_scale) + \", \"\n        + std::to_string(old_pos.d_x.d_offset) + \"}, {\"\n        + std::to_string(old_pos.d_y.d_scale) + \", \"\n        + std::to_string(old_pos.d_y.d_offset)+ \"}}\";\n    std::string new_pos_str = \"{{\" + std::to_string(new_pos.d_x.d_scale) + \", \"\n        + std::to_string(new_pos.d_x.d_offset) + \"}, {\"\n        + std::to_string(new_pos.d_y.d_scale) + \", \"\n        + std::to_string(new_pos.d_y.d_offset)+ \"}}\";\n\n    CEGUI::Affector *affector = anim_->createAffector(\"Position\", \"UVector2\");\n    affector->setApplicationMethod(CEGUI::Affector::AM_Absolute);\n    affector->createKeyFrame(0.0, old_pos_str);\n    affector->createKeyFrame(0.5, new_pos_str);\n\n    auto pawn_win = win_->getChild(\"boardWindow\/\" + cur_pawn_->color());\n    CEGUI::AnimationInstance *instance = CEGUI::AnimationManager::\n            getSingleton().instantiateAnimation(anim_.get());\n    instance->setTargetWindow(pawn_win);\n    instance->start();\n}\n\nvoid GameState::draw_wall_()\n{\n    auto board_win = static_cast(win_->getChild(\"boardWindow\"));\n    Node node;\n    CEGUI::UVector2 pos;\n\n    if (added_wall_.orientation() == Wall::kHorizontal) {\n        for (int i = 0; i < added_wall_.cnt(); ++i) {\n            node.set_row(added_wall_.row() - 1);\n            node.set_col(added_wall_.col() + i);\n            pos = pos_utils_.node_to_pos(node);\n            pos.d_y.d_offset = -2.0;\n            auto wall_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"horizontal_wall.layout\");\n            wall_win->setPosition(pos);\n            wall_win->setName(\"wallWindow\" + std::to_string(wall_idx_));\n            ++wall_idx_;\n            board_win->addChild(wall_win);\n        }\n    }\n    else if (added_wall_.orientation() == Wall::kVertical) {\n        for (int i = 0; i < added_wall_.cnt(); ++i) {\n            node.set_row(added_wall_.row() + i);\n            node.set_col(added_wall_.col());\n            pos = pos_utils_.node_to_pos(node);\n            pos.d_x.d_offset = -2.0;\n            auto wall_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"vertical_wall.layout\");\n            wall_win->setPosition(pos);\n            wall_win->setName(\"wallWindow\" + std::to_string(wall_idx_));\n            ++wall_idx_;\n            board_win->addChild(wall_win);\n        }\n    }\n}\n\nvoid GameState::pre_process_move_()\n{\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_.at(cur_pawn_)->enable_drag();\n    }\n}\n\nvoid GameState::post_process_move_()\n{\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_.at(cur_pawn_)->disable_drag();\n    }\n}\n\nvoid GameState::switch_cur_pawn_()\n{\n    game_->switch_pawn();\n    cur_pawn_ = game_->cur_pawn_data().pawn;\n}\n\nvoid GameState::make_move_()\n{\n    \/\/ human's turn, handle it in one of event handlers\n    if (players_[cur_pawn_]->is_interactive()) {\n        return;\n    }\n\n    move_t move = players_[cur_pawn_]->get_move();\n    if (Node *node = boost::get(&move)) {\n        Node cur_node = game_->cur_pawn_data().node;\n        if (move_pawn_(*node) == 0) {\n            pawn_path_.push_back(cur_node);\n            pawn_path_.push_back(*node);\n            status_ = kNeedPawnRedraw;\n        }\n    }\n    else if (Wall *wall = boost::get(&move)) {\n        if (add_wall_(*wall) == 0) {\n            status_ = kNeedDrawWall;\n        }\n    }\n}\n\nint GameState::move_pawn_(const Node &node)\n{\n    Node cur_node = game_->cur_pawn_data().node;\n    int rc = game_->move_pawn(node);\n    if (rc == 0) {\n        BOOST_LOG_INFO(lg) << cur_pawn_->color() << \": \" << cur_node << \" -> \"\n            << node;\n    }\n    return rc;\n}\n\nint GameState::add_wall_(const Wall &wall)\n{\n    int rc = game_->add_wall(wall);\n    if (rc == 0) {\n        BOOST_LOG_INFO(lg) << cur_pawn_->color() << \": \" << wall;\n        added_wall_ = wall;\n    }\n    return rc;\n}\n\nbool GameState::is_finished_() const\n{\n    return game_->is_finished();\n}\n\nvoid GameState::subscribe_for_events_()\n{\n    win_->getChild(\"back\")->subscribeEvent(\n            CEGUI::Window::EventMouseClick,\n            CEGUI::Event::Subscriber(\n                    &GameState::handle_back_, this\n            )\n    );\n}\n\nbool GameState::handle_back_(const CEGUI::EventArgs &\/* e *\/)\n{\n    BOOST_LOG_DEBUG(lg) << \"returning to start game menu\";\n    stm_->change_state(std::shared_ptr(new StartGameState(stm_)));\n    return true;\n}\n\nbool GameState::handle_end_anim_(const CEGUI::EventArgs &\/* e *\/)\n{\n    status_ = kPerformedMove;\n    return true;\n}\n\nbool GameState::handle_window_dropped_(const CEGUI::EventArgs &e)\n{\n    auto de = static_cast(e);\n    if (pawn_wins_.count(de.window())) {\n        return handle_pawn_dropped_(de);\n    }\n    else if (wall_wins_.count(de.window())) {\n        return handle_wall_dropped_(de);\n    }\n    else {\n        return false;\n    }\n}\n\nbool GameState::handle_pawn_dropped_(const CEGUI_Ext::DragEvent &de)\n{\n    CEGUI::Vector2f rel_pos = CEGUI::CoordConverter::asRelative(\n            de.window()->getPosition() + de.pos(),\n            {568, 568}  \/\/ @fixme get parent size\n    );\n    Node node = normalize_pawn_pos_(rel_pos);\n\n    CEGUI::UVector2 pos;\n    int rc = move_pawn_(node);\n    if (rc == 0) {\n        pos = pos_utils_.node_to_pos(node);\n        status_ = kPerformedMove;\n    }\n    else {\n        Node cur_node = game_->cur_pawn_data().node;\n        pos = pos_utils_.node_to_pos(cur_node);\n    }\n\n    de.window()->setPosition(pos);\n\n    return true;\n}\n\nbool GameState::handle_wall_dropped_(const CEGUI_Ext::DragEvent &de)\n{\n    CEGUI::Vector2f rel_pos = CEGUI::CoordConverter::asRelative(\n            de.window()->getPosition() + de.pos(),\n            {568, 568}  \/\/ @fixme get parent size\n    );\n    Wall wall = normalize_wall_pos_(rel_pos);\n    int rc = add_wall_(wall);\n    if (rc == 0) {\n        status_ = kNeedDrawWall;\n        de.window()->setVisible(false);\n    }\n\n    return true;\n}\n\nNode GameState::normalize_pawn_pos_(const CEGUI::Vector2f &rel_pos)\n{\n    CEGUI::UVector2 pos({rel_pos.d_x, 0.0}, {rel_pos.d_y, 0.0});\n    return pos_utils_.pos_to_node(pos);\n}\n\nWall GameState::normalize_wall_pos_(const CEGUI::Vector2f &rel_pos)\n{\n    CEGUI::UVector2 pos({rel_pos.d_x, 0.0}, {rel_pos.d_y, 0.0});\n    Wall wall = pos_utils_.pos_to_wall(pos, 2);\n    return wall;\n}\n\n}  \/* namespace Quoridor *\/\nCheck move validness in GameState::make_move_#include \"game_state.hpp\"\n\n#include \"start_game_state.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstatic std::vector colors = {\"red\", \"green\", \"blue\", \"yellow\"};\nstd::string GameState::name_(\"Game State\");\n\nGameState::GameState(std::shared_ptr stm,\n        const std::vector &player_types) : stm_(stm), anim_(),\n    game_(new Game(9, 9)), pf_(), players_(), pawn_list_(), cur_pawn_(),\n    drag_list_(), pawn_wins_(), wall_wins_(), pawn_path_(),\n    added_wall_(Wall::kInvalid, 0, 0, 0), wall_idx_(0),\n    status_(kWaitingForMove),\n    pos_utils_(9, 52, 50)\n{\n    lg.add_attribute(\"Tag\", blattrs::constant(\"game state\"));\n\n    init_gui_();\n    subscribe_for_events_();\n\n    if ((player_types.size() != 2) && (player_types.size() != 4)) {\n        throw Exception(\"Invalid number of players\");\n    }\n\n    for (size_t i = 0; i < player_types.size(); ++i) {\n        std::shared_ptr pawn(new Pawn(colors[i]));\n        pawn_list_.push_back(pawn);\n    }\n\n    try {\n        game_->set_pawns(pawn_list_);\n    }\n    catch (Exception &e) {\n        BOOST_LOG_ERROR(lg) << \"failed to create game: \" << e.what();\n        throw;\n    }\n\n    int i = 0;\n    for (auto player_type : player_types) {\n        BOOST_LOG_INFO(lg) << \"adding player \" << player_type << \" (\" << colors[i] << \")\";\n        players_[pawn_list_[i]] = pf_.make_player(player_type, game_, pawn_list_[i]);\n        ++i;\n    }\n\n    set_pawns_();\n    init_walls_();\n    switch_cur_pawn_();\n\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_[cur_pawn_]->enable_drag();\n    }\n}\n\nGameState::~GameState()\n{\n}\n\nvoid GameState::update()\n{\n    switch (status_) {\n    case kPreparingMove:\n        pre_process_move_();\n        status_ = kWaitingForMove;\n        break;\n    case kWaitingForMove:\n        make_move_();\n        break;\n    case kPerformedMove:\n        post_process_move_();\n        if (is_finished_()) {\n            BOOST_LOG_INFO(lg) << cur_pawn_->color() << \" win\";\n            status_ = kFinished;\n        }\n        else {\n            switch_cur_pawn_();\n            status_ = kPreparingMove;\n        }\n        break;\n    case kNeedPawnRedraw:\n        redraw_pawn_();\n        status_ = kWaitingForAnimationEnd;\n        break;\n    case kNeedDrawWall:\n        draw_wall_();\n        status_ = kPerformedMove;\n        break;\n    case kWaitingForAnimationEnd:\n        break;\n    case kFinished:\n        break;\n    default:\n        break;\n    }\n}\n\nstd::shared_ptr GameState::window() const\n{\n    return win_;\n}\n\nconst std::string &GameState::name() const\n{\n    return name_;\n}\n\nvoid GameState::init_gui_()\n{\n    CEGUI::ImageManager::getSingleton().loadImageset(\"pawn.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"board.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"wall.imageset\");\n    CEGUI::ImageManager::getSingleton().loadImageset(\"wall_repr.imageset\");\n\n    win_ = std::shared_ptr(\n            CEGUI::WindowManager::getSingleton().\n                    loadLayoutFromFile(\"game.layout\"),\n            [=](CEGUI::Window *w) {\n                CEGUI::WindowManager::getSingleton().destroyWindow(w);\n            }\n    );\n\n    anim_ = std::shared_ptr(\n            CEGUI::AnimationManager::getSingleton().\n                    createAnimation(\"movePawn\"),\n            [=](CEGUI::Animation *anim) {\n                CEGUI::AnimationManager::getSingleton().destroyAnimation(anim);\n            }\n    );\n    anim_->setDuration(0.5);\n    anim_->setReplayMode(CEGUI::Animation::RM_Once);\n}\n\nvoid GameState::set_pawns_()\n{\n    auto board_win = static_cast(win_->getChild(\"boardWindow\"));\n\n    board_win->subscribeEvent(\n            CEGUI_Ext::DraggableWindow::EventDraggableWindowDropped,\n            CEGUI::Event::Subscriber(&GameState::handle_window_dropped_, this));\n\n    CEGUI::Window *drag_win;\n    for (auto pawn_data : game_->pawn_data_list()) {\n        if (players_[pawn_data.pawn]->is_interactive()) {\n            drag_win = new CEGUI_Ext::DraggableWindow(\"DefaultWindow\", pawn_data.pawn->color());\n            drag_list_[pawn_data.pawn] = static_cast(drag_win);\n            drag_list_[pawn_data.pawn]->disable_drag();\n            pawn_wins_[drag_win] = pawn_data.pawn;\n        }\n        else {\n            drag_win = CEGUI::WindowManager::getSingleton().\n                createWindow(\"DefaultWindow\", pawn_data.pawn->color());\n            drag_win->subscribeEvent(\n                    CEGUI::AnimationInstance::EventAnimationEnded,\n                    CEGUI::Event::Subscriber(&GameState::handle_end_anim_, this));\n        }\n\n        drag_win->setSize(CEGUI::USize({0.1, 0}, {0.1, 0}));\n        CEGUI::UVector2 pos = pos_utils_.node_to_pos(pawn_data.node);\n        drag_win->setPosition(pos);\n\n        auto pawn_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"pawn_anim.layout\");\n        drag_win->addChild(pawn_win);\n        board_win->addChild(drag_win);\n    }\n}\n\nvoid GameState::init_walls_()\n{\n    auto ws1 = static_cast(win_->getChild(\"boardWindow\"));\n    for (int i = 0; i < 10; ++i) {\n        auto w1 = new CEGUI_Ext::DraggableWindow(\"DefaultWindow\", \"wall_1_\" + std::to_string(i));\n        w1->setPosition(CEGUI::UVector2({{0.0f, 25.0f * i + 4.0f}, {0.0f, 4.0f}}));\n        w1->setSize(CEGUI::USize({{0.0, 21.0}, {0.0, 42.0}}));\n\n        auto wall_img = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"wall_repr.layout\");\n        w1->addChild(wall_img);\n        ws1->addChild(w1);\n\n        wall_wins_[w1] = 1;\n    }\n}\n\nvoid GameState::redraw_pawn_()\n{\n    Node old_node = pawn_path_[0];\n    Node new_node = pawn_path_[1];\n\n    pawn_path_.clear();\n\n    CEGUI::UVector2 old_pos = pos_utils_.node_to_pos(old_node);\n    CEGUI::UVector2 new_pos = pos_utils_.node_to_pos(new_node);\n    std::string old_pos_str = \"{{\" + std::to_string(old_pos.d_x.d_scale) + \", \"\n        + std::to_string(old_pos.d_x.d_offset) + \"}, {\"\n        + std::to_string(old_pos.d_y.d_scale) + \", \"\n        + std::to_string(old_pos.d_y.d_offset)+ \"}}\";\n    std::string new_pos_str = \"{{\" + std::to_string(new_pos.d_x.d_scale) + \", \"\n        + std::to_string(new_pos.d_x.d_offset) + \"}, {\"\n        + std::to_string(new_pos.d_y.d_scale) + \", \"\n        + std::to_string(new_pos.d_y.d_offset)+ \"}}\";\n\n    CEGUI::Affector *affector = anim_->createAffector(\"Position\", \"UVector2\");\n    affector->setApplicationMethod(CEGUI::Affector::AM_Absolute);\n    affector->createKeyFrame(0.0, old_pos_str);\n    affector->createKeyFrame(0.5, new_pos_str);\n\n    auto pawn_win = win_->getChild(\"boardWindow\/\" + cur_pawn_->color());\n    CEGUI::AnimationInstance *instance = CEGUI::AnimationManager::\n            getSingleton().instantiateAnimation(anim_.get());\n    instance->setTargetWindow(pawn_win);\n    instance->start();\n}\n\nvoid GameState::draw_wall_()\n{\n    auto board_win = static_cast(win_->getChild(\"boardWindow\"));\n    Node node;\n    CEGUI::UVector2 pos;\n\n    if (added_wall_.orientation() == Wall::kHorizontal) {\n        for (int i = 0; i < added_wall_.cnt(); ++i) {\n            node.set_row(added_wall_.row() - 1);\n            node.set_col(added_wall_.col() + i);\n            pos = pos_utils_.node_to_pos(node);\n            pos.d_y.d_offset = -2.0;\n            auto wall_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"horizontal_wall.layout\");\n            wall_win->setPosition(pos);\n            wall_win->setName(\"wallWindow\" + std::to_string(wall_idx_));\n            ++wall_idx_;\n            board_win->addChild(wall_win);\n        }\n    }\n    else if (added_wall_.orientation() == Wall::kVertical) {\n        for (int i = 0; i < added_wall_.cnt(); ++i) {\n            node.set_row(added_wall_.row() + i);\n            node.set_col(added_wall_.col());\n            pos = pos_utils_.node_to_pos(node);\n            pos.d_x.d_offset = -2.0;\n            auto wall_win = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(\"vertical_wall.layout\");\n            wall_win->setPosition(pos);\n            wall_win->setName(\"wallWindow\" + std::to_string(wall_idx_));\n            ++wall_idx_;\n            board_win->addChild(wall_win);\n        }\n    }\n}\n\nvoid GameState::pre_process_move_()\n{\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_.at(cur_pawn_)->enable_drag();\n    }\n}\n\nvoid GameState::post_process_move_()\n{\n    if (drag_list_.count(cur_pawn_)) {\n        drag_list_.at(cur_pawn_)->disable_drag();\n    }\n}\n\nvoid GameState::switch_cur_pawn_()\n{\n    game_->switch_pawn();\n    cur_pawn_ = game_->cur_pawn_data().pawn;\n}\n\nvoid GameState::make_move_()\n{\n    \/\/ human's turn, handle it in one of event handlers\n    if (players_[cur_pawn_]->is_interactive()) {\n        return;\n    }\n\n    move_t move = players_[cur_pawn_]->get_move();\n    if (move.which() == 0) {\n        throw Exception(\"invalid move\");\n    }\n\n    if (Node *node = boost::get(&move)) {\n        Node cur_node = game_->cur_pawn_data().node;\n        if (move_pawn_(*node) == 0) {\n            pawn_path_.push_back(cur_node);\n            pawn_path_.push_back(*node);\n            status_ = kNeedPawnRedraw;\n        }\n    }\n    else if (Wall *wall = boost::get(&move)) {\n        if (add_wall_(*wall) == 0) {\n            status_ = kNeedDrawWall;\n        }\n    }\n}\n\nint GameState::move_pawn_(const Node &node)\n{\n    Node cur_node = game_->cur_pawn_data().node;\n    int rc = game_->move_pawn(node);\n    if (rc == 0) {\n        BOOST_LOG_INFO(lg) << cur_pawn_->color() << \": \" << cur_node << \" -> \"\n            << node;\n    }\n    return rc;\n}\n\nint GameState::add_wall_(const Wall &wall)\n{\n    int rc = game_->add_wall(wall);\n    if (rc == 0) {\n        BOOST_LOG_INFO(lg) << cur_pawn_->color() << \": \" << wall;\n        added_wall_ = wall;\n    }\n    return rc;\n}\n\nbool GameState::is_finished_() const\n{\n    return game_->is_finished();\n}\n\nvoid GameState::subscribe_for_events_()\n{\n    win_->getChild(\"back\")->subscribeEvent(\n            CEGUI::Window::EventMouseClick,\n            CEGUI::Event::Subscriber(\n                    &GameState::handle_back_, this\n            )\n    );\n}\n\nbool GameState::handle_back_(const CEGUI::EventArgs &\/* e *\/)\n{\n    BOOST_LOG_DEBUG(lg) << \"returning to start game menu\";\n    stm_->change_state(std::shared_ptr(new StartGameState(stm_)));\n    return true;\n}\n\nbool GameState::handle_end_anim_(const CEGUI::EventArgs &\/* e *\/)\n{\n    status_ = kPerformedMove;\n    return true;\n}\n\nbool GameState::handle_window_dropped_(const CEGUI::EventArgs &e)\n{\n    auto de = static_cast(e);\n    if (pawn_wins_.count(de.window())) {\n        return handle_pawn_dropped_(de);\n    }\n    else if (wall_wins_.count(de.window())) {\n        return handle_wall_dropped_(de);\n    }\n    else {\n        return false;\n    }\n}\n\nbool GameState::handle_pawn_dropped_(const CEGUI_Ext::DragEvent &de)\n{\n    CEGUI::Vector2f rel_pos = CEGUI::CoordConverter::asRelative(\n            de.window()->getPosition() + de.pos(),\n            {568, 568}  \/\/ @fixme get parent size\n    );\n    Node node = normalize_pawn_pos_(rel_pos);\n\n    CEGUI::UVector2 pos;\n    int rc = move_pawn_(node);\n    if (rc == 0) {\n        pos = pos_utils_.node_to_pos(node);\n        status_ = kPerformedMove;\n    }\n    else {\n        Node cur_node = game_->cur_pawn_data().node;\n        pos = pos_utils_.node_to_pos(cur_node);\n    }\n\n    de.window()->setPosition(pos);\n\n    return true;\n}\n\nbool GameState::handle_wall_dropped_(const CEGUI_Ext::DragEvent &de)\n{\n    CEGUI::Vector2f rel_pos = CEGUI::CoordConverter::asRelative(\n            de.window()->getPosition() + de.pos(),\n            {568, 568}  \/\/ @fixme get parent size\n    );\n    Wall wall = normalize_wall_pos_(rel_pos);\n    int rc = add_wall_(wall);\n    if (rc == 0) {\n        status_ = kNeedDrawWall;\n        de.window()->setVisible(false);\n    }\n\n    return true;\n}\n\nNode GameState::normalize_pawn_pos_(const CEGUI::Vector2f &rel_pos)\n{\n    CEGUI::UVector2 pos({rel_pos.d_x, 0.0}, {rel_pos.d_y, 0.0});\n    return pos_utils_.pos_to_node(pos);\n}\n\nWall GameState::normalize_wall_pos_(const CEGUI::Vector2f &rel_pos)\n{\n    CEGUI::UVector2 pos({rel_pos.d_x, 0.0}, {rel_pos.d_y, 0.0});\n    Wall wall = pos_utils_.pos_to_wall(pos, 2);\n    return wall;\n}\n\n}  \/* namespace Quoridor *\/\n<|endoftext|>"}
{"text":"\/\/ Copyright 2022 The gRPC Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"src\/core\/lib\/gprpp\/notification.h\"\n\n#include \n\n#include \"gtest\/gtest.h\"\n\nnamespace grpc_core {\nnamespace testing {\nnamespace {\n\nTEST(Notification, Works) {\n  Notification n;\n  EXPECT_FALSE(n.HasBeenNotified());\n  n.Notify();\n  EXPECT_TRUE(n.HasBeenNotified());\n  n.WaitForNotification();\n  EXPECT_TRUE(n.HasBeenNotified());\n}\n\nTEST(Notification, Waits) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(5));\n    n.Notify();\n  });\n  n.WaitForNotification();\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  t.join();\n}\n\nTEST(Notification, WaitsWithTimeout) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(5));\n    n.Notify();\n  });\n  EXPECT_TRUE(n.WaitForNotificationWithTimeout(absl::Seconds(10)));\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  EXPECT_LE(end - start, absl::Seconds(10));\n  t.join();\n}\n\nTEST(Notification, WaitWithTimeoutCanFinishEarly) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(5));\n    n.Notify();\n  });\n  EXPECT_FALSE(n.WaitForNotificationWithTimeout(absl::Seconds(1)));\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(1));\n  EXPECT_LE(end - start, absl::Seconds(5));\n  n.WaitForNotification();\n  end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  t.join();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace testing\n}  \/\/ namespace grpc_core\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n[notification] sloppier tests (#31422)\/\/ Copyright 2022 The gRPC Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"src\/core\/lib\/gprpp\/notification.h\"\n\n#include \n\n#include \"gtest\/gtest.h\"\n\nnamespace grpc_core {\nnamespace testing {\nnamespace {\n\nTEST(Notification, Works) {\n  Notification n;\n  EXPECT_FALSE(n.HasBeenNotified());\n  n.Notify();\n  EXPECT_TRUE(n.HasBeenNotified());\n  n.WaitForNotification();\n  EXPECT_TRUE(n.HasBeenNotified());\n}\n\nTEST(Notification, Waits) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(6));\n    n.Notify();\n  });\n  n.WaitForNotification();\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  t.join();\n}\n\nTEST(Notification, WaitsWithTimeout) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(6));\n    n.Notify();\n  });\n  EXPECT_TRUE(n.WaitForNotificationWithTimeout(absl::Seconds(10)));\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  EXPECT_LE(end - start, absl::Seconds(10));\n  t.join();\n}\n\nTEST(Notification, WaitWithTimeoutCanFinishEarly) {\n  Notification n;\n  auto start = absl::Now();\n  std::thread t([&n] {\n    absl::SleepFor(absl::Seconds(6));\n    n.Notify();\n  });\n  EXPECT_FALSE(n.WaitForNotificationWithTimeout(absl::Seconds(1)));\n  auto end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(1));\n  EXPECT_LE(end - start, absl::Seconds(5));\n  n.WaitForNotification();\n  end = absl::Now();\n  EXPECT_GE(end - start, absl::Seconds(5));\n  t.join();\n}\n\n}  \/\/ namespace\n}  \/\/ namespace testing\n}  \/\/ namespace grpc_core\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n<|endoftext|>"}
{"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \"test\/core\/util\/test_config.h\"\n\n#ifdef GRPC_TEST_PICK_PORT\n#include \"test\/core\/util\/port_server_client.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/http\/httpcli.h\"\n\ntypedef struct freereq {\n  gpr_mu* mu;\n  grpc_polling_entity pops;\n  int done;\n} freereq;\n\nstatic void destroy_pops_and_shutdown(void* p, grpc_error* error) {\n  grpc_pollset* pollset =\n      grpc_polling_entity_pollset(static_cast(p));\n  grpc_pollset_destroy(pollset);\n  gpr_free(pollset);\n}\n\nstatic void freed_port_from_server(void* arg, grpc_error* error) {\n  freereq* pr = static_cast(arg);\n  gpr_mu_lock(pr->mu);\n  pr->done = 1;\n  GRPC_LOG_IF_ERROR(\n      \"pollset_kick\",\n      grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n  gpr_mu_unlock(pr->mu);\n}\n\nvoid grpc_free_port_using_server(int port) {\n  grpc_httpcli_context context;\n  grpc_httpcli_request req;\n  grpc_httpcli_response rsp;\n  freereq pr;\n  char* path;\n  grpc_core::ExecCtx exec_ctx;\n  grpc_closure* shutdown_closure;\n\n  grpc_init();\n\n  memset(&pr, 0, sizeof(pr));\n  memset(&req, 0, sizeof(req));\n  memset(&rsp, 0, sizeof(rsp));\n\n  grpc_pollset* pollset =\n      static_cast(gpr_zalloc(grpc_pollset_size()));\n  grpc_pollset_init(pollset, &pr.mu);\n  pr.pops = grpc_polling_entity_create_from_pollset(pollset);\n  shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,\n                                         grpc_schedule_on_exec_ctx);\n\n  req.host = const_cast(GRPC_PORT_SERVER_ADDRESS);\n  gpr_asprintf(&path, \"\/drop\/%d\", port);\n  req.http.path = path;\n\n  grpc_httpcli_context_init(&context);\n  grpc_resource_quota* resource_quota =\n      grpc_resource_quota_create(\"port_server_client\/free\");\n  grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,\n                   grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                   GRPC_CLOSURE_CREATE(freed_port_from_server, &pr,\n                                       grpc_schedule_on_exec_ctx),\n                   &rsp);\n  grpc_resource_quota_unref_internal(resource_quota);\n  grpc_core::ExecCtx::Get()->Flush();\n  gpr_mu_lock(pr.mu);\n  while (!pr.done) {\n    grpc_pollset_worker* worker = nullptr;\n    if (!GRPC_LOG_IF_ERROR(\n            \"pollset_work\",\n            grpc_pollset_work(\n                grpc_polling_entity_pollset(&pr.pops), &worker,\n                grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {\n      pr.done = 1;\n    }\n  }\n  gpr_mu_unlock(pr.mu);\n\n  grpc_httpcli_context_destroy(&context);\n  grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),\n                        shutdown_closure);\n\n  gpr_free(path);\n  grpc_http_response_destroy(&rsp);\n\n  grpc_shutdown();\n}\n\ntypedef struct portreq {\n  gpr_mu* mu;\n  grpc_polling_entity pops;\n  int port;\n  int retries;\n  char* server;\n  grpc_httpcli_context* ctx;\n  grpc_httpcli_response response;\n} portreq;\n\nstatic void got_port_from_server(void* arg, grpc_error* error) {\n  size_t i;\n  int port = 0;\n  portreq* pr = static_cast(arg);\n  int failed = 0;\n  grpc_httpcli_response* response = &pr->response;\n\n  if (error != GRPC_ERROR_NONE) {\n    failed = 1;\n    const char* msg = grpc_error_string(error);\n    gpr_log(GPR_DEBUG, \"failed port pick from server: retrying [%s]\", msg);\n\n  } else if (response->status != 200) {\n    failed = 1;\n    gpr_log(GPR_DEBUG, \"failed port pick from server: status=%d\",\n            response->status);\n  }\n\n  if (failed) {\n    grpc_httpcli_request req;\n    memset(&req, 0, sizeof(req));\n    if (pr->retries >= 5) {\n      gpr_mu_lock(pr->mu);\n      pr->port = 0;\n      GRPC_LOG_IF_ERROR(\n          \"pollset_kick\",\n          grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n      gpr_mu_unlock(pr->mu);\n      return;\n    }\n    GPR_ASSERT(pr->retries < 10);\n    gpr_sleep_until(gpr_time_add(\n        gpr_now(GPR_CLOCK_REALTIME),\n        gpr_time_from_millis(\n            static_cast(\n                1000.0 * (1 + pow(1.3, pr->retries) * rand() \/ RAND_MAX)),\n            GPR_TIMESPAN)));\n    pr->retries++;\n    req.host = pr->server;\n    req.http.path = const_cast(\"\/get\");\n    grpc_http_response_destroy(&pr->response);\n    memset(&pr->response, 0, sizeof(pr->response));\n    grpc_resource_quota* resource_quota =\n        grpc_resource_quota_create(\"port_server_client\/pick_retry\");\n    grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req,\n                     grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                     GRPC_CLOSURE_CREATE(got_port_from_server, pr,\n                                         grpc_schedule_on_exec_ctx),\n                     &pr->response);\n    grpc_resource_quota_unref_internal(resource_quota);\n    return;\n  }\n  GPR_ASSERT(response);\n  GPR_ASSERT(response->status == 200);\n  for (i = 0; i < response->body_length; i++) {\n    GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9');\n    port = port * 10 + response->body[i] - '0';\n  }\n  GPR_ASSERT(port > 1024);\n  gpr_mu_lock(pr->mu);\n  pr->port = port;\n  GRPC_LOG_IF_ERROR(\n      \"pollset_kick\",\n      grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n  gpr_mu_unlock(pr->mu);\n}\n\nint grpc_pick_port_using_server(void) {\n  grpc_httpcli_context context;\n  grpc_httpcli_request req;\n  portreq pr;\n  grpc_closure* shutdown_closure;\n\n  grpc_init();\n  {\n    grpc_core::ExecCtx exec_ctx;\n    memset(&pr, 0, sizeof(pr));\n    memset(&req, 0, sizeof(req));\n    grpc_pollset* pollset =\n        static_cast(gpr_zalloc(grpc_pollset_size()));\n    grpc_pollset_init(pollset, &pr.mu);\n    pr.pops = grpc_polling_entity_create_from_pollset(pollset);\n    shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,\n                                           grpc_schedule_on_exec_ctx);\n    pr.port = -1;\n    pr.server = const_cast(GRPC_PORT_SERVER_ADDRESS);\n    pr.ctx = &context;\n\n    req.host = const_cast(GRPC_PORT_SERVER_ADDRESS);\n    req.http.path = const_cast(\"\/get\");\n\n    grpc_httpcli_context_init(&context);\n    grpc_resource_quota* resource_quota =\n        grpc_resource_quota_create(\"port_server_client\/pick\");\n    grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,\n                     grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                     GRPC_CLOSURE_CREATE(got_port_from_server, &pr,\n                                         grpc_schedule_on_exec_ctx),\n                     &pr.response);\n    grpc_resource_quota_unref_internal(resource_quota);\n    grpc_core::ExecCtx::Get()->Flush();\n    gpr_mu_lock(pr.mu);\n    while (pr.port == -1) {\n      grpc_pollset_worker* worker = nullptr;\n      if (!GRPC_LOG_IF_ERROR(\n              \"pollset_work\",\n              grpc_pollset_work(\n                  grpc_polling_entity_pollset(&pr.pops), &worker,\n                  grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {\n        pr.port = 0;\n      }\n    }\n    gpr_mu_unlock(pr.mu);\n\n    grpc_http_response_destroy(&pr.response);\n    grpc_httpcli_context_destroy(&context);\n    grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),\n                          shutdown_closure);\n\n    grpc_core::ExecCtx::Get()->Flush();\n  }\n  grpc_shutdown();\n\n  return pr.port;\n}\n\n#endif  \/\/ GRPC_TEST_PICK_PORT\nUse struct-defined initialization when available\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n#include \"test\/core\/util\/test_config.h\"\n\n#ifdef GRPC_TEST_PICK_PORT\n#include \"test\/core\/util\/port_server_client.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/http\/httpcli.h\"\n\ntypedef struct freereq {\n  gpr_mu* mu = nullptr;\n  grpc_polling_entity pops = {};\n  int done = 0;\n} freereq;\n\nstatic void destroy_pops_and_shutdown(void* p, grpc_error* error) {\n  grpc_pollset* pollset =\n      grpc_polling_entity_pollset(static_cast(p));\n  grpc_pollset_destroy(pollset);\n  gpr_free(pollset);\n}\n\nstatic void freed_port_from_server(void* arg, grpc_error* error) {\n  freereq* pr = static_cast(arg);\n  gpr_mu_lock(pr->mu);\n  pr->done = 1;\n  GRPC_LOG_IF_ERROR(\n      \"pollset_kick\",\n      grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n  gpr_mu_unlock(pr->mu);\n}\n\nvoid grpc_free_port_using_server(int port) {\n  grpc_httpcli_context context;\n  grpc_httpcli_request req;\n  grpc_httpcli_response rsp;\n  freereq pr;\n  char* path;\n  grpc_core::ExecCtx exec_ctx;\n  grpc_closure* shutdown_closure;\n\n  grpc_init();\n\n  pr = {};\n  memset(&req, 0, sizeof(req));\n  rsp = {};\n\n  grpc_pollset* pollset =\n      static_cast(gpr_zalloc(grpc_pollset_size()));\n  grpc_pollset_init(pollset, &pr.mu);\n  pr.pops = grpc_polling_entity_create_from_pollset(pollset);\n  shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,\n                                         grpc_schedule_on_exec_ctx);\n\n  req.host = const_cast(GRPC_PORT_SERVER_ADDRESS);\n  gpr_asprintf(&path, \"\/drop\/%d\", port);\n  req.http.path = path;\n\n  grpc_httpcli_context_init(&context);\n  grpc_resource_quota* resource_quota =\n      grpc_resource_quota_create(\"port_server_client\/free\");\n  grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,\n                   grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                   GRPC_CLOSURE_CREATE(freed_port_from_server, &pr,\n                                       grpc_schedule_on_exec_ctx),\n                   &rsp);\n  grpc_resource_quota_unref_internal(resource_quota);\n  grpc_core::ExecCtx::Get()->Flush();\n  gpr_mu_lock(pr.mu);\n  while (!pr.done) {\n    grpc_pollset_worker* worker = nullptr;\n    if (!GRPC_LOG_IF_ERROR(\n            \"pollset_work\",\n            grpc_pollset_work(\n                grpc_polling_entity_pollset(&pr.pops), &worker,\n                grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {\n      pr.done = 1;\n    }\n  }\n  gpr_mu_unlock(pr.mu);\n\n  grpc_httpcli_context_destroy(&context);\n  grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),\n                        shutdown_closure);\n\n  gpr_free(path);\n  grpc_http_response_destroy(&rsp);\n\n  grpc_shutdown();\n}\n\ntypedef struct portreq {\n  gpr_mu* mu = nullptr;\n  grpc_polling_entity pops = {};\n  int port = 0;\n  int retries = 0;\n  char* server = nullptr;\n  grpc_httpcli_context* ctx = nullptr;\n  grpc_httpcli_response response = {};\n} portreq;\n\nstatic void got_port_from_server(void* arg, grpc_error* error) {\n  size_t i;\n  int port = 0;\n  portreq* pr = static_cast(arg);\n  int failed = 0;\n  grpc_httpcli_response* response = &pr->response;\n\n  if (error != GRPC_ERROR_NONE) {\n    failed = 1;\n    const char* msg = grpc_error_string(error);\n    gpr_log(GPR_DEBUG, \"failed port pick from server: retrying [%s]\", msg);\n\n  } else if (response->status != 200) {\n    failed = 1;\n    gpr_log(GPR_DEBUG, \"failed port pick from server: status=%d\",\n            response->status);\n  }\n\n  if (failed) {\n    grpc_httpcli_request req;\n    memset(&req, 0, sizeof(req));\n    if (pr->retries >= 5) {\n      gpr_mu_lock(pr->mu);\n      pr->port = 0;\n      GRPC_LOG_IF_ERROR(\n          \"pollset_kick\",\n          grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n      gpr_mu_unlock(pr->mu);\n      return;\n    }\n    GPR_ASSERT(pr->retries < 10);\n    gpr_sleep_until(gpr_time_add(\n        gpr_now(GPR_CLOCK_REALTIME),\n        gpr_time_from_millis(\n            static_cast(\n                1000.0 * (1 + pow(1.3, pr->retries) * rand() \/ RAND_MAX)),\n            GPR_TIMESPAN)));\n    pr->retries++;\n    req.host = pr->server;\n    req.http.path = const_cast(\"\/get\");\n    grpc_http_response_destroy(&pr->response);\n    pr->response = {};\n    grpc_resource_quota* resource_quota =\n        grpc_resource_quota_create(\"port_server_client\/pick_retry\");\n    grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req,\n                     grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                     GRPC_CLOSURE_CREATE(got_port_from_server, pr,\n                                         grpc_schedule_on_exec_ctx),\n                     &pr->response);\n    grpc_resource_quota_unref_internal(resource_quota);\n    return;\n  }\n  GPR_ASSERT(response);\n  GPR_ASSERT(response->status == 200);\n  for (i = 0; i < response->body_length; i++) {\n    GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9');\n    port = port * 10 + response->body[i] - '0';\n  }\n  GPR_ASSERT(port > 1024);\n  gpr_mu_lock(pr->mu);\n  pr->port = port;\n  GRPC_LOG_IF_ERROR(\n      \"pollset_kick\",\n      grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr));\n  gpr_mu_unlock(pr->mu);\n}\n\nint grpc_pick_port_using_server(void) {\n  grpc_httpcli_context context;\n  grpc_httpcli_request req;\n  portreq pr;\n  grpc_closure* shutdown_closure;\n\n  grpc_init();\n  {\n    grpc_core::ExecCtx exec_ctx;\n    pr = {};\n    memset(&req, 0, sizeof(req));\n    grpc_pollset* pollset =\n        static_cast(gpr_zalloc(grpc_pollset_size()));\n    grpc_pollset_init(pollset, &pr.mu);\n    pr.pops = grpc_polling_entity_create_from_pollset(pollset);\n    shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops,\n                                           grpc_schedule_on_exec_ctx);\n    pr.port = -1;\n    pr.server = const_cast(GRPC_PORT_SERVER_ADDRESS);\n    pr.ctx = &context;\n\n    req.host = const_cast(GRPC_PORT_SERVER_ADDRESS);\n    req.http.path = const_cast(\"\/get\");\n\n    grpc_httpcli_context_init(&context);\n    grpc_resource_quota* resource_quota =\n        grpc_resource_quota_create(\"port_server_client\/pick\");\n    grpc_httpcli_get(&context, &pr.pops, resource_quota, &req,\n                     grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC,\n                     GRPC_CLOSURE_CREATE(got_port_from_server, &pr,\n                                         grpc_schedule_on_exec_ctx),\n                     &pr.response);\n    grpc_resource_quota_unref_internal(resource_quota);\n    grpc_core::ExecCtx::Get()->Flush();\n    gpr_mu_lock(pr.mu);\n    while (pr.port == -1) {\n      grpc_pollset_worker* worker = nullptr;\n      if (!GRPC_LOG_IF_ERROR(\n              \"pollset_work\",\n              grpc_pollset_work(\n                  grpc_polling_entity_pollset(&pr.pops), &worker,\n                  grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) {\n        pr.port = 0;\n      }\n    }\n    gpr_mu_unlock(pr.mu);\n\n    grpc_http_response_destroy(&pr.response);\n    grpc_httpcli_context_destroy(&context);\n    grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops),\n                          shutdown_closure);\n\n    grpc_core::ExecCtx::Get()->Flush();\n  }\n  grpc_shutdown();\n\n  return pr.port;\n}\n\n#endif  \/\/ GRPC_TEST_PICK_PORT\n<|endoftext|>"}
{"text":"\n\n#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING 1\n#define ELPP_DEFAULT_LOG_FILE \"logs\/swgchat.log\"\n\n#include \"easylogging++.h\"\n\n#include \"StationChatApp.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#include \n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]);\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig);\n#endif\n\nint main(int argc, const char* argv[]) {\n#ifdef __GNUC__\n    signal(SIGSEGV, SignalHandler);\n#endif\n\n    auto config = BuildConfiguration(argc, argv);\n\n    el::Loggers::setDefaultConfigurations(config.loggerConfig, true);\n    START_EASYLOGGINGPP(argc, argv);\n\n    StationChatApp app{config};\n\n    while (app.IsRunning()) {\n        app.Tick();\n        std::this_thread::sleep_for(std::chrono::milliseconds(1));\n    }\n\n    return 0;\n}\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]) {\n    namespace po = boost::program_options;\n    StationChatConfig config;\n    std::string configFile;\n\n    \/\/ Declare a group of options that will be \n    \/\/ allowed only on command line\n    po::options_description generic(\"Generic options\");\n    generic.add_options()\n        (\"help,h\", \"produces help message\")\n        (\"config,c\", po::value(&configFile)->default_value(\"swgchat.cfg\"),\n            \"sets path to the configuration file\")\n        (\"logger_config\", po::value(&config.loggerConfig)->default_value(\"logger.cfg\"),\n            \"sets path to the logger configuration file\")\n        ;\n\n    po::options_description options(\"Configuration\");\n    options.add_options()\n        (\"gateway_address\", po::value(&config.gatewayAddress)->default_value(\"127.0.0.1\"),\n            \"address for gateway connections\")\n        (\"gateway_port\", po::value(&config.gatewayPort)->default_value(5001),\n            \"port for gateway connections\")\n        (\"registrar_address\", po::value(&config.registrarAddress)->default_value(\"127.0.0.1\"),\n            \"address for registrar connections\")\n        (\"registrar_port\", po::value(&config.registrarPort)->default_value(5000),\n            \"port for registrar connections\")\n        (\"bind_to_ip\", po::value(&config.bindToIp)->default_value(false),\n            \"when set to true, binds to the config address; otherwise, binds on any interface\")\n        (\"database_path\", po::value(&config.chatDatabasePath)->default_value(\"var\/stationapi\/stationchat.db\"),\n            \"path to the sqlite3 database file\")\n        ;\n\n    po::options_description cmdline_options;\n    cmdline_options.add(generic).add(options);\n\n    po::options_description config_file_options;\n    config_file_options.add(options);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(cmdline_options).allow_unregistered().run(), vm);\n    po::notify(vm);\n\n    std::ifstream ifs(configFile.c_str());\n    if (!ifs) {\n        throw std::runtime_error(\"Cannot open configuration file: \" + configFile);\n    }\n\n    po::store(po::parse_config_file(ifs, config_file_options), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << cmdline_options << \"\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    return config;\n}\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig) {\n    const int BACKTRACE_LIMIT = 10;\n    void *arr[BACKTRACE_LIMIT];\n    auto size = backtrace(arr, BACKTRACE_LIMIT);\n\n    fprintf(stderr, \"Error: signal %d:\\n\", sig);\n    backtrace_symbols_fd(arr, size, STDERR_FILENO);\n    exit(1);\n}\n#endif\nChange runtime locations of config files\n\n#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING 1\n#define ELPP_DEFAULT_LOG_FILE \"logs\/swgchat.log\"\n\n#include \"easylogging++.h\"\n\n#include \"StationChatApp.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#include \n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]);\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig);\n#endif\n\nint main(int argc, const char* argv[]) {\n#ifdef __GNUC__\n    signal(SIGSEGV, SignalHandler);\n#endif\n\n    auto config = BuildConfiguration(argc, argv);\n\n    el::Loggers::setDefaultConfigurations(config.loggerConfig, true);\n    START_EASYLOGGINGPP(argc, argv);\n\n    StationChatApp app{config};\n\n    while (app.IsRunning()) {\n        app.Tick();\n        std::this_thread::sleep_for(std::chrono::milliseconds(1));\n    }\n\n    return 0;\n}\n\nStationChatConfig BuildConfiguration(int argc, const char* argv[]) {\n    namespace po = boost::program_options;\n    StationChatConfig config;\n    std::string configFile;\n\n    \/\/ Declare a group of options that will be \n    \/\/ allowed only on command line\n    po::options_description generic(\"Generic options\");\n    generic.add_options()\n        (\"help,h\", \"produces help message\")\n        (\"config,c\", po::value(&configFile)->default_value(\"etc\/stationapi\/swgchat.cfg\"),\n            \"sets path to the configuration file\")\n        (\"logger_config\", po::value(&config.loggerConfig)->default_value(\"etc\/stationapi\/logger.cfg\"),\n            \"sets path to the logger configuration file\")\n        ;\n\n    po::options_description options(\"Configuration\");\n    options.add_options()\n        (\"gateway_address\", po::value(&config.gatewayAddress)->default_value(\"127.0.0.1\"),\n            \"address for gateway connections\")\n        (\"gateway_port\", po::value(&config.gatewayPort)->default_value(5001),\n            \"port for gateway connections\")\n        (\"registrar_address\", po::value(&config.registrarAddress)->default_value(\"127.0.0.1\"),\n            \"address for registrar connections\")\n        (\"registrar_port\", po::value(&config.registrarPort)->default_value(5000),\n            \"port for registrar connections\")\n        (\"bind_to_ip\", po::value(&config.bindToIp)->default_value(false),\n            \"when set to true, binds to the config address; otherwise, binds on any interface\")\n        (\"database_path\", po::value(&config.chatDatabasePath)->default_value(\"var\/stationapi\/stationchat.db\"),\n            \"path to the sqlite3 database file\")\n        ;\n\n    po::options_description cmdline_options;\n    cmdline_options.add(generic).add(options);\n\n    po::options_description config_file_options;\n    config_file_options.add(options);\n\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(cmdline_options).allow_unregistered().run(), vm);\n    po::notify(vm);\n\n    std::ifstream ifs(configFile.c_str());\n    if (!ifs) {\n        throw std::runtime_error(\"Cannot open configuration file: \" + configFile);\n    }\n\n    po::store(po::parse_config_file(ifs, config_file_options), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << cmdline_options << \"\\n\";\n        exit(EXIT_SUCCESS);\n    }\n\n    return config;\n}\n\n#ifdef __GNUC__\nvoid SignalHandler(int sig) {\n    const int BACKTRACE_LIMIT = 10;\n    void *arr[BACKTRACE_LIMIT];\n    auto size = backtrace(arr, BACKTRACE_LIMIT);\n\n    fprintf(stderr, \"Error: signal %d:\\n\", sig);\n    backtrace_symbols_fd(arr, size, STDERR_FILENO);\n    exit(1);\n}\n#endif\n<|endoftext|>"}
{"text":"#include \"gtest\/gtest.h\"\n#include \"ray.hpp\"\n\nTEST(ray_test, test_construction)\n{\n  \/\/ Default constructor.\n  Ray r1;\n  EXPECT_FLOAT_EQ(r1.origin().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.origin().y(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().y(), 0.0f);\n\n  \/\/ Constructor with parameters.\n  Ray r2(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  EXPECT_FLOAT_EQ(r2.origin().x(), 1.0f);\n  EXPECT_FLOAT_EQ(r2.origin().y(), 1.0f);\n  EXPECT_FLOAT_EQ(r2.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r2.direction().y(), 1.0f);\n\n  \/\/ Copy constructor.\n  Ray r3 = r2;\n\n  EXPECT_EQ(r3 == r2, true);\n}\n\nTEST(ray_test, test_assignment)\n{\n  Ray r1;\n\n  r1 = Ray(Point2D(1.0f, 1.0f),\n           Point2D(0.0f, 1.0f));\n\n  EXPECT_FLOAT_EQ(r1.origin().x(), 1.0f);\n  EXPECT_FLOAT_EQ(r1.origin().y(), 1.0f);\n  EXPECT_FLOAT_EQ(r1.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().y(), 1.0f);\n}\n\nTEST(ray_test, test_equality)\n{\n  Ray r1(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  Ray r2(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  Ray r3(Point2D(1.0f, 1.0f),\n         Point2D(1.0f, 1.0f));\n\n  EXPECT_EQ(r1, r2);\n  EXPECT_NE(r1, r3);\n}\n\nTEST(ray_test, test_intersection_outside)\n{\n  \/\/ Send a ray to the right.\n  Ray r1(Point2D(0.0f, 0.0f),\n         Point2D(1.0f, 0.0f));\n\n  Box2D box1 = { Point2D(1.0f, -1.0f), Point2D(4.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r1, box1), true);\n\n  \/\/ Send a ray to the left.\n  Ray r2(Point2D(0.0f, 0.0f),\n         Point2D(-1.0f, 0.0f));\n\n  Box2D box2 = { Point2D(-1.0f, -1.0f), Point2D(-4.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r2, box2), true);\n\n  \/\/ Send a ray to the upwards.\n  Ray r3(Point2D(0.0f, 0.0f),\n         Point2D(0.0f, 1.0f));\n\n  Box2D box3 = { Point2D(-1.0f, 1.0f), Point2D(1.0f, 4.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r3, box3), true);\n\n  \/\/ Send a ray to the bottom.\n  Ray r4(Point2D(0.0f, 0.0f),\n         Point2D(0.0f, -1.0f));\n\n  Box2D box4 = { Point2D(-1.0f, -1.0f), Point2D(1.0f, -4.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r4, box4), true);\n}\n\nTEST(ray_test, test_radian_to_degree)\n{\n  EXPECT_FLOAT_EQ(Ray::convertRadianToDegrees(Constants::PI), 180);\n  EXPECT_FLOAT_EQ(Ray::convertRadianToDegrees(0.5 * Constants::PI), 90);\n}\n\nTEST(ray_test, test_intersection_inside)\n{\n  \/\/ Ray origin is inside a box.\n  Ray r1(Point2D(0.0f, 0.0f),\n         Point2D(1.0f, 0.0f));\n\n  Box2D box1 = { Point2D(-1.0f, -1.0f), Point2D(1.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r1, box1), true);\n}\nreformat code#include \"gtest\/gtest.h\"\n#include \"ray.hpp\"\n\nTEST(ray_test, test_construction)\n{\n  \/\/ Default constructor.\n  Ray r1;\n  EXPECT_FLOAT_EQ(r1.origin().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.origin().y(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().y(), 0.0f);\n\n  \/\/ Constructor with parameters.\n  Ray r2(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  EXPECT_FLOAT_EQ(r2.origin().x(), 1.0f);\n  EXPECT_FLOAT_EQ(r2.origin().y(), 1.0f);\n  EXPECT_FLOAT_EQ(r2.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r2.direction().y(), 1.0f);\n\n  \/\/ Copy constructor.\n  Ray r3 = r2;\n\n  EXPECT_EQ(r3 == r2, true);\n}\n\nTEST(ray_test, test_assignment)\n{\n  Ray r1;\n\n  r1 = Ray(Point2D(1.0f, 1.0f),\n           Point2D(0.0f, 1.0f));\n\n  EXPECT_FLOAT_EQ(r1.origin().x(), 1.0f);\n  EXPECT_FLOAT_EQ(r1.origin().y(), 1.0f);\n  EXPECT_FLOAT_EQ(r1.direction().x(), 0.0f);\n  EXPECT_FLOAT_EQ(r1.direction().y(), 1.0f);\n}\n\nTEST(ray_test, test_equality)\n{\n  Ray r1(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  Ray r2(Point2D(1.0f, 1.0f),\n         Point2D(0.0f, 1.0f));\n\n  Ray r3(Point2D(1.0f, 1.0f),\n         Point2D(1.0f, 1.0f));\n\n  EXPECT_EQ(r1, r2);\n  EXPECT_NE(r1, r3);\n}\n\nTEST(ray_test, test_intersection_outside)\n{\n  \/\/ Send a ray to the right.\n  Ray r1(Point2D(0.0f, 0.0f),\n         Point2D(1.0f, 0.0f));\n\n  Box2D box1 = { Point2D(1.0f, -1.0f),\n                 Point2D(4.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r1, box1), true);\n\n  \/\/ Send a ray to the left.\n  Ray r2(Point2D(0.0f, 0.0f),\n         Point2D(-1.0f, 0.0f));\n\n  Box2D box2 = { Point2D(-1.0f, -1.0f),\n                 Point2D(-4.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r2, box2), true);\n\n  \/\/ Send a ray to the upwards.\n  Ray r3(Point2D(0.0f, 0.0f),\n         Point2D(0.0f, 1.0f));\n\n  Box2D box3 = { Point2D(-1.0f, 1.0f),\n                 Point2D(1.0f, 4.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r3, box3), true);\n\n  \/\/ Send a ray to the bottom.\n  Ray r4(Point2D(0.0f, 0.0f),\n         Point2D(0.0f, -1.0f));\n\n  Box2D box4 = { Point2D(-1.0f, -1.0f),\n                 Point2D(1.0f, -4.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r4, box4), true);\n}\n\nTEST(ray_test, test_radian_to_degree)\n{\n  EXPECT_FLOAT_EQ(Ray::convertRadianToDegrees(Constants::PI), 180);\n  EXPECT_FLOAT_EQ(Ray::convertRadianToDegrees(0.5 * Constants::PI), 90);\n}\n\nTEST(ray_test, test_intersection_inside)\n{\n  \/\/ Ray origin is inside a box.\n  Ray r1(Point2D(0.0f, 0.0f),\n         Point2D(1.0f, 0.0f));\n\n  Box2D box1 = { Point2D(-1.0f, -1.0f),\n                 Point2D(1.0f, 1.0f) };\n\n  EXPECT_EQ(Ray::checkIntersection(r1, box1), true);\n}\n<|endoftext|>"}
{"text":"#include \"rtpsession.h\"\n#include \"rtpipv4address.h\"\n#include \"rtpsessionparams.h\"\n#include \"rtpudpv4transmitter.h\"\n#include \"rtperrors.h\"\n#include \"rtcpcompoundpacket.h\"\n#include \"rtcpsrpacket.h\"\n#include \"rtcprrpacket.h\"\n#include \"rtcpbyepacket.h\"\n#include \"rtprawpacket.h\"\n#include \n#include \n\nusing namespace jrtplib;\n\nvoid checkError(int status)\n{\n\tif (status >= 0)\n\t\treturn;\n\t\n\tstd::cerr << \"An error occured in the RTP component: \" << std::endl;\n\tstd::cerr << \"Error description: \" << RTPGetErrorString(status) << std::endl;\n\t\n\texit(-1);\n}\n\nclass MyRTPSession : public RTPSession\n{\nprivate:\n\tFILE *pLogFile;\npublic:\n\tMyRTPSession()\n\t{\n\t\tSetChangeIncomingData(true);\n\t\t\n\t\tpLogFile = fopen(\"logfile.dat\", \"wb\");\n\t}\n\n\t~MyRTPSession()\n\t{\n\t\tif (pLogFile)\n\t\t\tfclose(pLogFile);\n\t}\nprotected:\n\tbool OnChangeIncomingData(RTPRawPacket *pPack)\n\t{\n\t\tif (pLogFile)\n\t\t{\n\t\t\tdouble t = pPack->GetReceiveTime().GetDouble();\n\t\t\tbool isRTP = pPack->IsRTP();\n\t\t\tuint32_t dataLength = (uint32_t)pPack->GetDataLength();\n\n\t\t\tif (isRTP)\n\t\t\t\tfwrite(\"RTP \", 1, 4, pLogFile);\n\t\t\telse\n\t\t\t\tfwrite(\"RTCP\", 1, 4, pLogFile);\n\n\t\t\tfwrite(&t, 1, sizeof(double), pLogFile);\n\t\t\tfwrite(&dataLength, 1, sizeof(uint32_t),pLogFile);\n\t\t\tfwrite(pPack->GetData(), 1, dataLength, pLogFile);\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid OnRTCPCompoundPacket(RTCPCompoundPacket *p, const RTPTime &receivetime, const RTPAddress *senderaddress)\n\t{\t\n\t\tprintf(\"%u.%06u RECEIVED\\n\",receivetime.GetSeconds(),receivetime.GetMicroSeconds());\n\t\t\n\t\tDumpCompoundPacket(stdout,p);\n\t}\n\n\tvoid OnSendRTCPCompoundPacket(RTCPCompoundPacket *p)\n\t{\t\n\t\tRTPTime t = RTPTime::CurrentTime();\n\t\t\n\t\tprintf(\"%u.%06u SENDING\\n\",t.GetSeconds(),t.GetMicroSeconds());\n\t\t\n\t\tDumpCompoundPacket(stdout,p);\n\t}\n\t\n\tvoid DumpCompoundPacket(FILE *f, RTCPCompoundPacket *p)\n\t{\n\t\tRTCPPacket *pack;\n\n\t\tp->GotoFirstPacket();\n\t\twhile ((pack = p->GetNextPacket()) != 0)\n\t\t{\n\t\t\tif (pack->GetPacketType() == RTCPPacket::SR)\n\t\t\t{\n\t\t\t\tRTCPSRPacket *p = (RTCPSRPacket *)pack;\n\n\t\t\t\tRTPTime t(p->GetNTPTimestamp());\n\t\t\t\t\n\t\t\t\tfprintf(f,\"  SR packet\\n    SSRC %27u\\n\",p->GetSenderSSRC());\n\t\t\t\tfprintf(f,\"    NTP timestamp: %10u.%06u\\n    RTP timestamp: %17u\\n    Packets sent: %18u\\n    Octets sent: %19u\\n\",t.GetSeconds(),t.GetMicroSeconds(),p->GetRTPTimestamp(),p->GetSenderPacketCount(),p->GetSenderOctetCount());\n\t\t\t\t\t\n\t\t\t\tfor (int i = 0 ; i < p->GetReceptionReportCount() ; i++)\n\t\t\t\t\tfprintf(f,\"    RR block %d\\n      SSRC %25u\\n      Fraction lost: %15d\\n      Packets lost: %16d\\n      Ext. high. seq. nr: %10u\\n      Jitter: %22u\\n      LSR: %25u\\n      DLSR: %24u\\n\",(i+1),\n\t\t\t\t\t\t\tp->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),\n\t\t\t\t\t\t\tp->GetDLSR(i));\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::RR)\n\t\t\t{\n\t\t\t\tRTCPRRPacket *p = (RTCPRRPacket *)pack;\n\n\t\t\t\tfprintf(f,\"  RR packet\\n    SSRC %27u\\n\",p->GetSenderSSRC());\n\t\t\t\t\t\n\t\t\t\tfor (int i = 0 ; i < p->GetReceptionReportCount() ; i++)\n\t\t\t\t\tfprintf(f,\"    RR block %d\\n      SSRC %25u\\n      Fraction lost: %15d\\n      Packets lost: %16d\\n      Ext. high. seq. nr: %10u\\n      Jitter: %22u\\n      LSR: %25u\\n      DLSR: %24u\\n\",(i+1),\n\t\t\t\t\t\t\tp->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),\n\t\t\t\t\t\t\tp->GetDLSR(i));\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::SDES)\n\t\t\t{\n\t\t\t\tRTCPSDESPacket *p = (RTCPSDESPacket *)pack;\n\t\t\t\tchar str[1024];\n\t\t\t\t\n\t\t\t\tif (!p->GotoFirstChunk())\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tfprintf(f,\"  SDES Chunk:\\n\");\n\t\t\t\t\tfprintf(f,\"    SSRC: %26u\\n\",p->GetChunkSSRC());\n\t\t\t\t\tif (p->GotoFirstItem())\n\t\t\t\t\t{\n\t\t\t\t\t\tdo\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tswitch (p->GetItemType())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase RTCPSDESPacket::None:\n\t\t\t\t\t\t\t\tstrcpy(str,\"None    \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::CNAME:\n\t\t\t\t\t\t\t\tstrcpy(str,\"CNAME:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::NAME:\n\t\t\t\t\t\t\t\tstrcpy(str,\"NAME:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::EMAIL:\n\t\t\t\t\t\t\t\tstrcpy(str,\"EMAIL:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::PHONE:\n\t\t\t\t\t\t\t\tstrcpy(str,\"PHONE:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::LOC:\n\t\t\t\t\t\t\t\tstrcpy(str,\"LOC:    \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::TOOL:\n\t\t\t\t\t\t\t\tstrcpy(str,\"TOOL:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::NOTE:\n\t\t\t\t\t\t\t\tstrcpy(str,\"NOTE:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::PRIV:\n\t\t\t\t\t\t\t\tstrcpy(str,\"PRIV:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::Unknown:\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tstrcpy(str,\"Unknown \");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfprintf(f,\"    %s\",str);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (p->GetItemType() != RTCPSDESPacket::PRIV)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tchar str[1024];\n\t\t\t\t\t\t\t\tmemcpy(str,p->GetItemData(),p->GetItemLength());\n\t\t\t\t\t\t\t\tstr[p->GetItemLength()] = 0;\n\t\t\t\t\t\t\t\tfprintf(f,\"%24s\\n\",str);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} while (p->GotoNextItem());\n\t\t\t\t\t}\n\t\t\t\t} while (p->GotoNextChunk());\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::BYE)\n\t\t\t{\n\t\t\t\tfprintf(f,\"  BYE packet:\\n\");\n\t\t\t\t\n\t\t\t\tRTCPBYEPacket *p = (RTCPBYEPacket *)pack;\n\t\t\t\t\n\t\t\t\tint num = p->GetSSRCCount();\n\t\t\t\tint i;\n\t\t\t\n\t\t\t\tfor (i = 0 ; i < num ; i++)\n\t\t\t\t\tfprintf(f,\"    SSRC: %26u\\n\",p->GetSSRC(i));\n\t\t\t\tif (p->HasReasonForLeaving())\n\t\t\t\t{\n\t\t\t\t\tchar str[1024];\n\t\t\t\t\tmemcpy(str,p->GetReasonData(),p->GetReasonLength());\n\t\t\t\t\tstr[p->GetReasonLength()] = 0;\n\t\t\t\t\tfprintf(f,\"    Reason: %24s\\n\",str);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(f,\"\\n\");\n\t}\n};\n\nint main(int argc, char *argv[])\n{\n\tif (argc != 4)\n\t{\n\t\tfprintf(stderr, \"Usage: rtcpdump portbase destIP destport\\n\");\n\t\treturn -1;\n\t}\n\n\tint portBase = atoi(argv[1]);\n\tint destPort = atoi(argv[3]);\n\tstd::string destIP(argv[2]);\n\n\tRTPIPv4Address dest;\n\tRTPUDPv4TransmissionParams transParams;\n\tRTPSessionParams sessParams;\n\tMyRTPSession session;\n\n\tdest.SetIP(ntohl(inet_addr(destIP.c_str())));\n\tdest.SetPort((uint16_t)destPort);\n\n\ttransParams.SetPortbase((uint16_t)portBase);\n\ttransParams.SetRTPReceiveBuffer(1024*1024);\n\ttransParams.SetRTCPReceiveBuffer(1024*1024);\n\tsessParams.SetOwnTimestampUnit(1.0\/5.0);\n\tsessParams.SetProbationType(RTPSources::NoProbation);\n\n\tint status;\n\n\tstatus = session.Create(sessParams, &transParams);\n\tcheckError(status);\n\n\tstatus = session.AddDestination(dest);\n\tcheckError(status);\n\n\tint i = 0;\n\n\tgetchar();\n\n\treturn 0;\n}\nAdded OnValidatedRTPPacket to discard (the unused) incoming RTP data#include \"rtpsession.h\"\n#include \"rtpipv4address.h\"\n#include \"rtpsessionparams.h\"\n#include \"rtpudpv4transmitter.h\"\n#include \"rtperrors.h\"\n#include \"rtcpcompoundpacket.h\"\n#include \"rtcpsrpacket.h\"\n#include \"rtcprrpacket.h\"\n#include \"rtcpbyepacket.h\"\n#include \"rtprawpacket.h\"\n#include \n#include \n\nusing namespace jrtplib;\n\nvoid checkError(int status)\n{\n\tif (status >= 0)\n\t\treturn;\n\t\n\tstd::cerr << \"An error occured in the RTP component: \" << std::endl;\n\tstd::cerr << \"Error description: \" << RTPGetErrorString(status) << std::endl;\n\t\n\texit(-1);\n}\n\nclass MyRTPSession : public RTPSession\n{\nprivate:\n\tFILE *pLogFile;\npublic:\n\tMyRTPSession()\n\t{\n\t\tSetChangeIncomingData(true);\n\t\t\n\t\tpLogFile = fopen(\"logfile.dat\", \"wb\");\n\t}\n\n\t~MyRTPSession()\n\t{\n\t\tif (pLogFile)\n\t\t\tfclose(pLogFile);\n\t}\nprotected:\n\tvoid OnValidatedRTPPacket(RTPSourceData *srcdat, RTPPacket *rtppack, bool isonprobation, bool *ispackethandled)\n\t{\n\t\t\/\/ Make sure no RTP packets are stored internally, we'd just be wasting memory\n\t\tDeletePacket(rtppack);\n\t\t*ispackethandled = true;\n\t}\n\n\tbool OnChangeIncomingData(RTPRawPacket *pPack)\n\t{\n\t\tif (pLogFile)\n\t\t{\n\t\t\tdouble t = pPack->GetReceiveTime().GetDouble();\n\t\t\tbool isRTP = pPack->IsRTP();\n\t\t\tuint32_t dataLength = (uint32_t)pPack->GetDataLength();\n\n\t\t\tif (isRTP)\n\t\t\t\tfwrite(\"RTP \", 1, 4, pLogFile);\n\t\t\telse\n\t\t\t\tfwrite(\"RTCP\", 1, 4, pLogFile);\n\n\t\t\tfwrite(&t, 1, sizeof(double), pLogFile);\n\t\t\tfwrite(&dataLength, 1, sizeof(uint32_t),pLogFile);\n\t\t\tfwrite(pPack->GetData(), 1, dataLength, pLogFile);\n\t\t}\n\t\treturn true;\n\t}\n\n\tvoid OnRTCPCompoundPacket(RTCPCompoundPacket *p, const RTPTime &receivetime, const RTPAddress *senderaddress)\n\t{\t\n\t\tprintf(\"%u.%06u RECEIVED\\n\",receivetime.GetSeconds(),receivetime.GetMicroSeconds());\n\t\t\n\t\tDumpCompoundPacket(stdout,p);\n\t}\n\n\tvoid OnSendRTCPCompoundPacket(RTCPCompoundPacket *p)\n\t{\t\n\t\tRTPTime t = RTPTime::CurrentTime();\n\t\t\n\t\tprintf(\"%u.%06u SENDING\\n\",t.GetSeconds(),t.GetMicroSeconds());\n\t\t\n\t\tDumpCompoundPacket(stdout,p);\n\t}\n\t\n\tvoid DumpCompoundPacket(FILE *f, RTCPCompoundPacket *p)\n\t{\n\t\tRTCPPacket *pack;\n\n\t\tp->GotoFirstPacket();\n\t\twhile ((pack = p->GetNextPacket()) != 0)\n\t\t{\n\t\t\tif (pack->GetPacketType() == RTCPPacket::SR)\n\t\t\t{\n\t\t\t\tRTCPSRPacket *p = (RTCPSRPacket *)pack;\n\n\t\t\t\tRTPTime t(p->GetNTPTimestamp());\n\t\t\t\t\n\t\t\t\tfprintf(f,\"  SR packet\\n    SSRC %27u\\n\",p->GetSenderSSRC());\n\t\t\t\tfprintf(f,\"    NTP timestamp: %10u.%06u\\n    RTP timestamp: %17u\\n    Packets sent: %18u\\n    Octets sent: %19u\\n\",t.GetSeconds(),t.GetMicroSeconds(),p->GetRTPTimestamp(),p->GetSenderPacketCount(),p->GetSenderOctetCount());\n\t\t\t\t\t\n\t\t\t\tfor (int i = 0 ; i < p->GetReceptionReportCount() ; i++)\n\t\t\t\t\tfprintf(f,\"    RR block %d\\n      SSRC %25u\\n      Fraction lost: %15d\\n      Packets lost: %16d\\n      Ext. high. seq. nr: %10u\\n      Jitter: %22u\\n      LSR: %25u\\n      DLSR: %24u\\n\",(i+1),\n\t\t\t\t\t\t\tp->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),\n\t\t\t\t\t\t\tp->GetDLSR(i));\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::RR)\n\t\t\t{\n\t\t\t\tRTCPRRPacket *p = (RTCPRRPacket *)pack;\n\n\t\t\t\tfprintf(f,\"  RR packet\\n    SSRC %27u\\n\",p->GetSenderSSRC());\n\t\t\t\t\t\n\t\t\t\tfor (int i = 0 ; i < p->GetReceptionReportCount() ; i++)\n\t\t\t\t\tfprintf(f,\"    RR block %d\\n      SSRC %25u\\n      Fraction lost: %15d\\n      Packets lost: %16d\\n      Ext. high. seq. nr: %10u\\n      Jitter: %22u\\n      LSR: %25u\\n      DLSR: %24u\\n\",(i+1),\n\t\t\t\t\t\t\tp->GetSSRC(i),(int)p->GetFractionLost(i),p->GetLostPacketCount(i),p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),\n\t\t\t\t\t\t\tp->GetDLSR(i));\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::SDES)\n\t\t\t{\n\t\t\t\tRTCPSDESPacket *p = (RTCPSDESPacket *)pack;\n\t\t\t\tchar str[1024];\n\t\t\t\t\n\t\t\t\tif (!p->GotoFirstChunk())\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tfprintf(f,\"  SDES Chunk:\\n\");\n\t\t\t\t\tfprintf(f,\"    SSRC: %26u\\n\",p->GetChunkSSRC());\n\t\t\t\t\tif (p->GotoFirstItem())\n\t\t\t\t\t{\n\t\t\t\t\t\tdo\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tswitch (p->GetItemType())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase RTCPSDESPacket::None:\n\t\t\t\t\t\t\t\tstrcpy(str,\"None    \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::CNAME:\n\t\t\t\t\t\t\t\tstrcpy(str,\"CNAME:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::NAME:\n\t\t\t\t\t\t\t\tstrcpy(str,\"NAME:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::EMAIL:\n\t\t\t\t\t\t\t\tstrcpy(str,\"EMAIL:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::PHONE:\n\t\t\t\t\t\t\t\tstrcpy(str,\"PHONE:  \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::LOC:\n\t\t\t\t\t\t\t\tstrcpy(str,\"LOC:    \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::TOOL:\n\t\t\t\t\t\t\t\tstrcpy(str,\"TOOL:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::NOTE:\n\t\t\t\t\t\t\t\tstrcpy(str,\"NOTE:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::PRIV:\n\t\t\t\t\t\t\t\tstrcpy(str,\"PRIV:   \");\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase RTCPSDESPacket::Unknown:\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tstrcpy(str,\"Unknown \");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfprintf(f,\"    %s\",str);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif (p->GetItemType() != RTCPSDESPacket::PRIV)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tchar str[1024];\n\t\t\t\t\t\t\t\tmemcpy(str,p->GetItemData(),p->GetItemLength());\n\t\t\t\t\t\t\t\tstr[p->GetItemLength()] = 0;\n\t\t\t\t\t\t\t\tfprintf(f,\"%24s\\n\",str);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} while (p->GotoNextItem());\n\t\t\t\t\t}\n\t\t\t\t} while (p->GotoNextChunk());\n\t\t\t}\n\t\t\telse if (pack->GetPacketType() == RTCPPacket::BYE)\n\t\t\t{\n\t\t\t\tfprintf(f,\"  BYE packet:\\n\");\n\t\t\t\t\n\t\t\t\tRTCPBYEPacket *p = (RTCPBYEPacket *)pack;\n\t\t\t\t\n\t\t\t\tint num = p->GetSSRCCount();\n\t\t\t\tint i;\n\t\t\t\n\t\t\t\tfor (i = 0 ; i < num ; i++)\n\t\t\t\t\tfprintf(f,\"    SSRC: %26u\\n\",p->GetSSRC(i));\n\t\t\t\tif (p->HasReasonForLeaving())\n\t\t\t\t{\n\t\t\t\t\tchar str[1024];\n\t\t\t\t\tmemcpy(str,p->GetReasonData(),p->GetReasonLength());\n\t\t\t\t\tstr[p->GetReasonLength()] = 0;\n\t\t\t\t\tfprintf(f,\"    Reason: %24s\\n\",str);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfprintf(f,\"\\n\");\n\t}\n};\n\nint main(int argc, char *argv[])\n{\n\tif (argc != 4)\n\t{\n\t\tfprintf(stderr, \"Usage: rtcpdump portbase destIP destport\\n\");\n\t\treturn -1;\n\t}\n\n\tint portBase = atoi(argv[1]);\n\tint destPort = atoi(argv[3]);\n\tstd::string destIP(argv[2]);\n\n\tRTPIPv4Address dest;\n\tRTPUDPv4TransmissionParams transParams;\n\tRTPSessionParams sessParams;\n\tMyRTPSession session;\n\n\tdest.SetIP(ntohl(inet_addr(destIP.c_str())));\n\tdest.SetPort((uint16_t)destPort);\n\n\ttransParams.SetPortbase((uint16_t)portBase);\n\ttransParams.SetRTPReceiveBuffer(1024*1024);\n\ttransParams.SetRTCPReceiveBuffer(1024*1024);\n\tsessParams.SetOwnTimestampUnit(1.0\/5.0);\n\tsessParams.SetProbationType(RTPSources::NoProbation);\n\n\tint status;\n\n\tstatus = session.Create(sessParams, &transParams);\n\tcheckError(status);\n\n\tstatus = session.AddDestination(dest);\n\tcheckError(status);\n\n\tint i = 0;\n\n\tgetchar();\n\n\treturn 0;\n}\n<|endoftext|>"}
{"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/  By downloading, copying, installing or using the software you agree to this license.\n\/\/  If you do not agree to this license, do not download, install,\n\/\/  copy or use the software.\n\/\/\n\/\/\n\/\/                        Intel License Agreement\n\/\/                For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright( C) 2000, Intel Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/   * Redistribution's of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/\n\/\/   * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/\n\/\/   * The name of Intel Corporation may not 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 disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ 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\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort(including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n\/*\n  definition of the current version of OpenCV\n  Usefull to test in user programs\n*\/\n\n#ifndef __OPENCV_VERSION_HPP__\n#define __OPENCV_VERSION_HPP__\n\n#define CV_VERSION_EPOCH    2\n#define CV_VERSION_MAJOR    4\n#define CV_VERSION_MINOR    9\n#define CV_VERSION_REVISION 0\n\n#define CVAUX_STR_EXP(__A)  #__A\n#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)\n\n#if CV_VERSION_REVISION\n#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) \".\" CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR) \".\" CVAUX_STR(CV_VERSION_REVISION)\n#else\n#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) \".\" CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR)\n#endif\n\n\/* old  style version constants*\/\n#define CV_MAJOR_VERSION    CV_VERSION_EPOCH\n#define CV_MINOR_VERSION    CV_VERSION_MAJOR\n#define CV_SUBMINOR_VERSION CV_VERSION_MINOR\n\n#endif\nmoving version to 2.9.0, also adding NVidia copyright\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/  By downloading, copying, installing or using the software you agree to this license.\n\/\/  If you do not agree to this license, do not download, install,\n\/\/  copy or use the software.\n\/\/\n\/\/\n\/\/                        Intel License Agreement\n\/\/                For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright( C) 2000, Intel Corporation, all rights reserved.\n\/\/ Copyright (C) 2011-2013, NVIDIA Corporation, all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/   * Redistribution's of source code must retain the above copyright notice,\n\/\/     this list of conditions and the following disclaimer.\n\/\/\n\/\/   * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/     this list of conditions and the following disclaimer in the documentation\n\/\/     and\/or other materials provided with the distribution.\n\/\/\n\/\/   * The name of Intel Corporation may not 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 disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ 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\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort(including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n\/*\n  definition of the current version of OpenCV\n  Usefull to test in user programs\n*\/\n\n#ifndef __OPENCV_VERSION_HPP__\n#define __OPENCV_VERSION_HPP__\n\n#define CV_VERSION_EPOCH    2\n#define CV_VERSION_MAJOR    9\n#define CV_VERSION_MINOR    0\n#define CV_VERSION_REVISION 0\n\n#define CVAUX_STR_EXP(__A)  #__A\n#define CVAUX_STR(__A)      CVAUX_STR_EXP(__A)\n\n#if CV_VERSION_REVISION\n#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) \".\" CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR) \".\" CVAUX_STR(CV_VERSION_REVISION)\n#else\n#  define CV_VERSION        CVAUX_STR(CV_VERSION_EPOCH) \".\" CVAUX_STR(CV_VERSION_MAJOR) \".\" CVAUX_STR(CV_VERSION_MINOR)\n#endif\n\n\/* old  style version constants*\/\n#define CV_MAJOR_VERSION    CV_VERSION_EPOCH\n#define CV_MINOR_VERSION    CV_VERSION_MAJOR\n#define CV_SUBMINOR_VERSION CV_VERSION_MINOR\n\n#endif\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace sf1r;\nusing namespace boost;\nusing namespace boost::lambda;\n\nvoid callback_on_consumed(bool isSuccess)\n{\n    cout <<\"--> callback on consume finished: \"< callback on produced: \"<watchProducer(callback_on_produced, true);\n}\n\nBOOST_AUTO_TEST_SUITE( t_zookeeper )\n\nBOOST_AUTO_TEST_CASE( node_manager_synchro )\n{\n    return;\n    \/\/ set default config\n    DistributedTopologyConfig dsTopologyConfig;\n    dsTopologyConfig.clusterId_ = \"zhongxia\";\n    dsTopologyConfig.nodeNum_ = 2;\n    dsTopologyConfig.curSF1Node_.host_ = \"172.16.0.36\";\n    dsTopologyConfig.curSF1Node_.nodeId_ = 1;\n    dsTopologyConfig.curSF1Node_.replicaId_ = 1;\n    DistributedUtilConfig dsUtilConfig;\n    dsUtilConfig.zkConfig_.zkHosts_ = \"172.16.0.161:2181,172.16.0.162:2181,172.16.0.163:2181\";\n    dsUtilConfig.zkConfig_.zkRecvTimeout_ = 2000;\n\n    NodeManagerSingleton::get()->initWithConfig(dsTopologyConfig, dsUtilConfig);\n\n    \/\/ Consumer\n    boost::thread consumer_thread(thread_consumer_run);\n\n    \/\/ Producer\n    {\n    SynchroProducerPtr spd =\n        DistributedSynchroFactory::makeProcuder(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);\n    spd->produce(\"\/data\/scd\", callback_on_consumed);\n    bool ret;\n    spd->waitConsumers(ret);\n    cout << \"Producer: wait consumers ended \" <produce(\"\/data\/scd2\", callback_on_consumed);\n\n    \/\/while (true)\n        sleep(6);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\nadjust unitest#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace sf1r;\nusing namespace boost;\nusing namespace boost::lambda;\n\nvoid callback_on_consumed(bool isSuccess)\n{\n    cout <<\"--> callback on consume finished: \"< callback on produced: \"<watchProducer(callback_on_produced, true);\n}\n\nBOOST_AUTO_TEST_SUITE( t_zookeeper )\n\nBOOST_AUTO_TEST_CASE( node_manager_synchro )\n{\n    \/\/ set default config\n    DistributedTopologyConfig dsTopologyConfig;\n    dsTopologyConfig.clusterId_ = \"zhongxia\";\n    dsTopologyConfig.nodeNum_ = 2;\n    dsTopologyConfig.curSF1Node_.host_ = \"172.16.0.36\";\n    dsTopologyConfig.curSF1Node_.nodeId_ = 1;\n    dsTopologyConfig.curSF1Node_.replicaId_ = 1;\n    DistributedUtilConfig dsUtilConfig;\n    dsUtilConfig.zkConfig_.zkHosts_ = \"172.16.0.161:2181,172.16.0.162:2181,172.16.0.163:2181\";\n    dsUtilConfig.zkConfig_.zkRecvTimeout_ = 2000;\n\n    NodeManagerSingleton::get()->initWithConfig(dsTopologyConfig, dsUtilConfig);\n\n    \/\/ Consumer\n    boost::thread consumer_thread(thread_consumer_run);\n\n    \/\/ Producer\n    {\n    SynchroProducerPtr spd =\n        DistributedSynchroFactory::makeProcuder(DistributedSynchroFactory::SYNCHRO_TYPE_PRODUCT_MANAGER);\n    spd->produce(\"\/data\/scd\", callback_on_consumed);\n    bool ret;\n    spd->waitConsumers(ret);\n    cout << \"Producer: wait consumers ended \" <produce(\"\/data\/scd2\", callback_on_consumed);\n\n    \/\/while (true)\n    \/\/    sleep(4);\n    }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<|endoftext|>"}
{"text":"#include \"support.h\"\n\n#include \n#include \n#include \n\n#include \n\n#include \"lexer.h\"\n#include \"parser.h\"\n#include \"compiler.h\"\n\nbool CompilerSupport::loadBytecode(const std::string &name, Bytecode &object)\n{\n    std::pair names = findModule(name);\n    if (names.first.empty() && names.second.empty()) {\n        return false;\n    }\n\n    std::ifstream obj(names.second, std::ios::binary);\n    std::ifstream src(names.first);\n\n    std::string source;\n    if (src.good()) {\n        std::stringstream buf;\n        buf << src.rdbuf();\n        source = buf.str();\n    }\n\n    if (obj.good() && not source.empty()) {\n        SHA256 sha256;\n        sha256(source);\n        unsigned char h[SHA256::HashBytes];\n        sha256.getHash(h);\n        std::string hash = std::string(h, h+sizeof(h));\n\n        std::stringstream buf;\n        buf << obj.rdbuf();\n        std::vector bytecode;\n        std::string s = buf.str();\n        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n        object = Bytecode(bytecode);\n\n        if (object.source_hash == hash) {\n            return true;\n        }\n    }\n\n    if (not source.empty()) {\n        {\n            std::ofstream outf(names.first+\"x\", std::ios::binary);\n            auto tokens = tokenize(source);\n            auto parsetree = parse(tokens);\n            auto ast = analyze(this, parsetree);\n            auto bytecode = compile(ast, nullptr);\n            outf.write(reinterpret_cast(bytecode.data()), bytecode.size());\n        }\n        obj.open(names.first+\"x\", std::ios::binary);\n        if (not obj.good()) {\n            return false;\n        }\n    }\n\n    std::stringstream buf;\n    buf << obj.rdbuf();\n    std::vector bytecode;\n    std::string s = buf.str();\n    std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n    object = Bytecode(bytecode);\n    return true;\n}\nFix another compile problem on import#include \"support.h\"\n\n#include \n#include \n#include \n\n#include \n\n#include \"lexer.h\"\n#include \"parser.h\"\n#include \"compiler.h\"\n\nbool CompilerSupport::loadBytecode(const std::string &name, Bytecode &object)\n{\n    std::pair names = findModule(name);\n    if (names.first.empty() && names.second.empty()) {\n        return false;\n    }\n\n    std::ifstream obj(names.second, std::ios::binary);\n    std::ifstream src(names.first);\n\n    std::string source;\n    if (src.good()) {\n        std::stringstream buf;\n        buf << src.rdbuf();\n        source = buf.str();\n    }\n\n    if (obj.good() && not source.empty()) {\n        SHA256 sha256;\n        sha256(source);\n        unsigned char h[SHA256::HashBytes];\n        sha256.getHash(h);\n        std::string hash = std::string(h, h+sizeof(h));\n\n        std::stringstream buf;\n        buf << obj.rdbuf();\n        std::vector bytecode;\n        std::string s = buf.str();\n        std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n        object = Bytecode(bytecode);\n\n        if (object.source_hash == hash) {\n            return true;\n        }\n    }\n\n    if (not source.empty()) {\n        {\n            std::ofstream outf(names.first+\"x\", std::ios::binary);\n            auto tokens = tokenize(source);\n            auto parsetree = parse(tokens);\n            auto ast = analyze(this, parsetree);\n            auto bytecode = compile(ast, nullptr);\n            outf.write(reinterpret_cast(bytecode.data()), bytecode.size());\n        }\n        obj.close();\n        obj.open(names.first+\"x\", std::ios::binary);\n        if (not obj.good()) {\n            return false;\n        }\n    }\n\n    std::stringstream buf;\n    buf << obj.rdbuf();\n    std::vector bytecode;\n    std::string s = buf.str();\n    std::copy(s.begin(), s.end(), std::back_inserter(bytecode));\n    object = Bytecode(bytecode);\n    return true;\n}\n<|endoftext|>"}
{"text":"\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\/*\n * Copyright (C) FFLAS-FFPACK\n * Written by Hongguang ZHU \n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * 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 * ========LICENCE========\n *.\n *\/\n#define  __FFLASFFPACK_SEQUENTIAL\n\n\/\/#define ENABLE_ALL_CHECKINGS 1\n\n\/\/#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \n\n#include \n#include \n\n#include \"fflas-ffpack\/utils\/timer.h\"\n#include \"fflas-ffpack\/fflas\/fflas.h\"\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"fflas-ffpack\/utils\/test-utils.h\"\n#include \n#include \n\n\nusing namespace std;\nusing namespace FFPACK;\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\n\ntemplate\nbool check_solve(const Field &F, size_t m, RandIter& Rand){\n\ntypedef typename Field::Element_ptr A, A2, B, B2, x;\n\n\tsize_t lda,incb,incx;\n\tlda=m;  \n\tincb=1;  \n\tincx=1;\n\tA  = FFLAS::fflas_new(F,m,lda);\n\tA2 = FFLAS::fflas_new(F,m,lda);\n\tB  = FFLAS::fflas_new(F,m,incb);\n\tB2 = FFLAS::fflas_new(F,m,incb);\n\tx  = FFLAS::fflas_new(F,m,incx);\n\n\tRandomMatrixWithRank (F,  m,  m, m, A, lda, Rand);\n\n\tRandomMatrix (F, m, 1, B, incb, Rand);\n\n\tFFLAS::fassign (F, m, B, incb, B2, incb);\n\tFFLAS::fassign (F, m, m, A, lda, A2, lda);\n\t#ifdef DEBUG\n\tFFLAS::WriteMatrix(std::cout<<\"b:=\"<\nbool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){\n\tbool ok = true ;\n\tint nbit=(int)iters;\n\n\twhile (ok &&  nbit){\n\t\t\/\/typedef typename Field::Element Element ;\n\t\t\/\/ choose Field\n\t\tField* F= chooseField(q,b);\n\t\ttypename Field::RandIter G(*F,0,seed);\n\t\tif (F==nullptr)\n\t\t\treturn true;\n\n\t\tcout<<\"Checking with \";F->write(cout)< >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok &&run_with_field > (q,5,m\/6,iters,seed);\n\t\tok = ok &&run_with_field > (q,(b?b:512),m\/6,iters,seed); \n\n\t} while (loop && ok);\n\n\treturn !ok ;\n}\nfix typo\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\/*\n * Copyright (C) FFLAS-FFPACK\n * Written by Hongguang ZHU \n * This file is Free Software and part of FFLAS-FFPACK.\n *\n * ========LICENCE========\n * This file is part of the library FFLAS-FFPACK.\n *\n * FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n * 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 * ========LICENCE========\n *.\n *\/\n#define  __FFLASFFPACK_SEQUENTIAL\n\n\/\/#define ENABLE_ALL_CHECKINGS 1\n\n\/\/#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \n\n#include \n#include \n\n#include \"fflas-ffpack\/utils\/timer.h\"\n#include \"fflas-ffpack\/fflas\/fflas.h\"\n#include \"fflas-ffpack\/utils\/args-parser.h\"\n#include \"fflas-ffpack\/utils\/test-utils.h\"\n#include \n#include \n\n\nusing namespace std;\nusing namespace FFPACK;\nusing Givaro::Modular;\nusing Givaro::ModularBalanced;\n\n\ntemplate\nbool check_solve(const Field &F, size_t m, RandIter& Rand){\n\n\ttypename Field::Element_ptr A, A2, B, B2, x;\n\n\tsize_t lda,incb,incx;\n\tlda=m;  \n\tincb=1;  \n\tincx=1;\n\tA  = FFLAS::fflas_new(F,m,lda);\n\tA2 = FFLAS::fflas_new(F,m,lda);\n\tB  = FFLAS::fflas_new(F,m,incb);\n\tB2 = FFLAS::fflas_new(F,m,incb);\n\tx  = FFLAS::fflas_new(F,m,incx);\n\n\tRandomMatrixWithRank (F,  m,  m, m, A, lda, Rand);\n\n\tRandomMatrix (F, m, 1, B, incb, Rand);\n\n\tFFLAS::fassign (F, m, B, incb, B2, incb);\n\tFFLAS::fassign (F, m, m, A, lda, A2, lda);\n\t#ifdef DEBUG\n\tFFLAS::WriteMatrix(std::cout<<\"b:=\"<\nbool run_with_field (Givaro::Integer q, size_t b, size_t m, size_t iters, uint64_t seed){\n\tbool ok = true ;\n\tint nbit=(int)iters;\n\n\twhile (ok &&  nbit){\n\t\t\/\/typedef typename Field::Element Element ;\n\t\t\/\/ choose Field\n\t\tField* F= chooseField(q,b);\n\t\ttypename Field::RandIter G(*F,0,seed);\n\t\tif (F==nullptr)\n\t\t\treturn true;\n\n\t\tcout<<\"Checking with \";F->write(cout)< >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok && run_with_field >(q,b,m,iters,seed);\n\t\tok = ok && run_with_field >(q,b,m,iters,seed); \n\t\tok = ok &&run_with_field > (q,5,m\/6,iters,seed);\n\t\tok = ok &&run_with_field > (q,(b?b:512),m\/6,iters,seed); \n\n\t} while (loop && ok);\n\n\treturn !ok ;\n}\n<|endoftext|>"}
{"text":"Newton and AMR in a loop<|endoftext|>"}
{"text":"#include \n\nusing namespace tiramisu;\n\nvoid gen(std::string name, int size, int val0, int val1)\n{\n    tiramisu::init(name);\n\n    tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0);\n\n    tiramisu::var i(\"i\", 0, N), j(\"j\", 0, N);\n    tiramisu::var i0(\"i0\"), j0(\"j0\"), i1(\"i1\"), j1(\"j1\");\n\n    tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);\n\n    S0.tile(i, j, 2, 2, i0, j0, i1, j1);\n    S0.tag_parallel_level(i0);\n\n    tiramisu::buffer buf0(\"buf0\", {size, size}, tiramisu::p_uint8, a_output);\n    S0.store_in(&buf0, {i ,j});\n\n    tiramisu::codegen({&buf0}, \"build\/generated_fct_test_119.o\");\n}\n\nint main(int argc, char **argv)\n{\n    gen(\"func\", 10, 3, 4);\n\n    return 0;\n}\nFix test#include \n\nusing namespace tiramisu;\n\nvoid gen(std::string name, int size, int val0, int val1)\n{\n    tiramisu::init(name);\n\n    tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0);\n\n    tiramisu::var i(\"i\", 0, N), j(\"j\", 0, N);\n    tiramisu::var i0(\"i0\"), j0(\"j0\"), i1(\"i1\"), j1(\"j1\");\n\n    tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));\n\n    S0.tile(i, j, 2, 2, i0, j0, i1, j1);\n    S0.tag_parallel_level(i0);\n\n    tiramisu::buffer buf0(\"buf0\", {size, size}, tiramisu::p_uint8, a_output);\n    S0.store_in(&buf0, {i ,j});\n\n    tiramisu::codegen({&buf0}, \"build\/generated_fct_test_119.o\");\n}\n\nint main(int argc, char **argv)\n{\n    gen(\"func\", 10, 3, 4);\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\nclass WaypointsNavigation{\npublic:\n    WaypointsNavigation() :\n        has_activate_(false),\n        move_base_action_(\"move_base\", true),\n        rate_(10)\n    {\n        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))\n        {\n            ROS_INFO(\"Waiting...\");\n        }\n        \n        ros::NodeHandle private_nh(\"~\");\n        private_nh.param(\"robot_frame\", robot_frame_, std::string(\"\/base_link\"));\n        private_nh.param(\"world_frame\", world_frame_, std::string(\"\/map\"));\n        \n        double max_update_rate;\n        private_nh.param(\"max_update_rate\", max_update_rate, 10.0);\n        rate_ = ros::Rate(max_update_rate);\n        std::string filename = \"\";\n        private_nh.param(\"filename\", filename, filename);\n        if(filename != \"\"){\n            ROS_INFO_STREAM(\"Read waypoints data from \" << filename);\n            readFile(filename);\n        }\n        \n        ros::NodeHandle nh;\n        syscommand_sub_ = nh.subscribe(\"syscommand\", 1, &WaypointsNavigation::syscommandCallback, this);\n        marker_pub_ = nh.advertise(\"visualization_marker\", 10);\n    }\n\n    void syscommandCallback(const std_msgs::String &msg){\n        if(msg.data == \"start\"){\n            has_activate_ = true;\n        }\n    }\n\n    bool readFile(const std::string &filename){\n        waypoints_.clear();\n        try{\n            std::ifstream ifs(filename.c_str(), std::ifstream::in);\n            if(ifs.good() == false){\n                return false;\n            }\n\n            YAML::Node node;\n            node = YAML::Load(ifs);\n            const YAML::Node &wp_node_tmp = node[\"waypoints\"];\n            const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;\n            if(wp_node != NULL){\n                for(int i=0; i < wp_node->size(); i++){\n                    geometry_msgs::PointStamped point;\n\n                    point.point.x = (*wp_node)[i][\"point\"][\"x\"].as();\n                    point.point.y = (*wp_node)[i][\"point\"][\"y\"].as();\n                    point.point.z = (*wp_node)[i][\"point\"][\"z\"].as();\n\n                    waypoints_.push_back(point);\n\n                }\n            }else{\n                return false;\n            }\n\n            const YAML::Node &fp_node_tmp = node[\"finish_pose\"];\n            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;\n\n            if(fp_node != NULL){\n                finish_pose_.position.x = (*fp_node)[\"pose\"][\"position\"][\"x\"].as();\n                finish_pose_.position.y = (*fp_node)[\"pose\"][\"position\"][\"y\"].as();\n                finish_pose_.position.z = (*fp_node)[\"pose\"][\"position\"][\"z\"].as();\n\n                finish_pose_.orientation.x = (*fp_node)[\"pose\"][\"orientation\"][\"x\"].as();\n                finish_pose_.orientation.y = (*fp_node)[\"pose\"][\"orientation\"][\"y\"].as();\n                finish_pose_.orientation.z = (*fp_node)[\"pose\"][\"orientation\"][\"z\"].as();\n                finish_pose_.orientation.w = (*fp_node)[\"pose\"][\"orientation\"][\"w\"].as();\n            }else{\n                return false;\n            }\n\n        }catch(YAML::ParserException &e){\n            return false;\n\n        }catch(YAML::RepresentationException &e){\n            return false;\n        }\n\n        return true;\n    }\n\n    bool shouldSendGoal(){\n        bool ret = true;\n        actionlib::SimpleClientGoalState state = move_base_action_.getState();\n        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&\n           (state != actionlib::SimpleClientGoalState::PENDING) && \n           (state != actionlib::SimpleClientGoalState::RECALLED) &&\n           (state != actionlib::SimpleClientGoalState::PREEMPTED))\n        {\n            ret = false;\n        }\n\n        if(waypoints_.empty()){\n            ret = false;\n        }\n\n        return ret;\n    }\n\n    bool navigationFinished(){\n        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;\n    }\n\n    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){\n        tf::StampedTransform robot_gl;\n        try{\n            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n        }catch(tf::TransformException &e){\n            ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n        }\n        const double wx = dest.x;\n        const double wy = dest.y;\n        const double rx = robot_gl.getOrigin().x();\n        const double ry = robot_gl.getOrigin().y();\n        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));\n\n        return dist < dist_err;\n    }\n\n    void sleep(){\n        rate_.sleep();\n        ros::spinOnce();\n        publishMarkers();\n    }\n\n    void startNavigationGL(const geometry_msgs::Point &dest){\n        geometry_msgs::Pose pose;\n        pose.position = dest;\n        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);\n        startNavigationGL(pose);\n    }\n\n    void startNavigationGL(const geometry_msgs::Pose &dest){\n        move_base_msgs::MoveBaseGoal move_base_goal;\n        move_base_goal.target_pose.header.stamp = ros::Time::now();\n        move_base_goal.target_pose.header.frame_id = world_frame_;\n        move_base_goal.target_pose.pose.position = dest.position;\n        move_base_goal.target_pose.pose.orientation = dest.orientation;\n        \n        move_base_action_.sendGoal(move_base_goal);\n    }\n\n    void publishMarkers(){\n        visualization_msgs::MarkerArray markers_array;\n        for(int i=0; i < waypoints_.size(); i++){\n            visualization_msgs::Marker marker, label;\n            marker.header.frame_id = world_frame_;\n            marker.header.stamp = ros::Time::now();\n            marker.scale.x = 0.2;\n            marker.scale.y = 0.2;\n            marker.scale.z = 0.2;\n            marker.pose.position.z = marker.scale.z \/ 2.0;\n            marker.color.r = 0.8f;\n            marker.color.g = 0.2f;\n            marker.color.b = 0.2f;\n            \n            std::stringstream name;\n            name << \"waypoint \" << i;\n            marker.ns = name.str();\n            marker.id = i;\n            marker.pose.position.x = waypoints_[i].point.x;\n            marker.pose.position.y = waypoints_[i].point.y;\n            marker.type = visualization_msgs::Marker::SPHERE;\n            marker.action = visualization_msgs::Marker::ADD;\n            marker.color.a = 1.0f;\n            markers_array.markers.push_back(marker);\n\n            \/\/ROS_INFO_STREAM(\"waypoints \\n\" << waypoints_[i]);\n        }\n        marker_pub_.publish(markers_array);\n    }\n\n    void run(){\n        while(ros::ok()){\n            if(has_activate_){\n                for(int i=0; i < waypoints_.size(); i++){\n                    ROS_INFO_STREAM(\"waypoint = \" << waypoints_[i]);\n                    if(!ros::ok()) break;\n                    \n                    startNavigationGL(waypoints_[i].point);\n                    double start_nav_time = ros::Time::now().toSec();\n                    while(!onNavigationPoint(waypoints_[i].point)){\n                        if(ros::Time::now().toSec() - start_nav_time > 10.0){\n                            ROS_INFO(\"Resend the navigation goal.\");\n                            startNavigationGL(waypoints_[i].point);\n                            start_nav_time = ros::Time::now().toSec();\n                        }\n                        actionlib::SimpleClientGoalState state = move_base_action_.getState();\n                        sleep();\n                    }\n                    ROS_INFO(\"waypoint goal\");\n                }\n                ROS_INFO(\"waypoints clear\");\n                waypoints_.clear();\n                startNavigationGL(finish_pose_);\n                while(!navigationFinished() && ros::ok()) sleep();\n                has_activate_ = false;\n            }\n\n            sleep();\n        }\n    }\n\nprivate:\n    actionlib::SimpleActionClient move_base_action_;\n    std::vector waypoints_;\n    geometry_msgs::Pose finish_pose_;\n    bool has_activate_;\n    std::string robot_frame_, world_frame_;\n    tf::TransformListener tf_listener_;\n    ros::Rate rate_;\n    ros::Subscriber syscommand_sub_;\n    ros::Publisher marker_pub_;\n};\n\nint main(int argc, char *argv[]){\n    ros::init(argc, argv, ROS_PACKAGE_NAME);\n    WaypointsNavigation w_nav;\n    w_nav.run();\n\n    return 0;\n}\nAdd a service to clear costmaps#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\nclass WaypointsNavigation{\npublic:\n    WaypointsNavigation() :\n        has_activate_(false),\n        move_base_action_(\"move_base\", true),\n        rate_(10)\n    {\n        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))\n        {\n            ROS_INFO(\"Waiting...\");\n        }\n        \n        ros::NodeHandle private_nh(\"~\");\n        private_nh.param(\"robot_frame\", robot_frame_, std::string(\"\/base_link\"));\n        private_nh.param(\"world_frame\", world_frame_, std::string(\"\/map\"));\n        \n        double max_update_rate;\n        private_nh.param(\"max_update_rate\", max_update_rate, 10.0);\n        rate_ = ros::Rate(max_update_rate);\n        std::string filename = \"\";\n        private_nh.param(\"filename\", filename, filename);\n        if(filename != \"\"){\n            ROS_INFO_STREAM(\"Read waypoints data from \" << filename);\n            readFile(filename);\n        }\n        \n        ros::NodeHandle nh;\n        syscommand_sub_ = nh.subscribe(\"syscommand\", 1, &WaypointsNavigation::syscommandCallback, this);\n        marker_pub_ = nh.advertise(\"visualization_marker\", 10);\n        clear_costmaps_srv_ = nh.serviceClient(\"\/move_base\/clear_costmaps\");\n    }\n\n    void syscommandCallback(const std_msgs::String &msg){\n        if(msg.data == \"start\"){\n            has_activate_ = true;\n        }\n    }\n\n    bool readFile(const std::string &filename){\n        waypoints_.clear();\n        try{\n            std::ifstream ifs(filename.c_str(), std::ifstream::in);\n            if(ifs.good() == false){\n                return false;\n            }\n\n            YAML::Node node;\n            node = YAML::Load(ifs);\n            const YAML::Node &wp_node_tmp = node[\"waypoints\"];\n            const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;\n            if(wp_node != NULL){\n                for(int i=0; i < wp_node->size(); i++){\n                    geometry_msgs::PointStamped point;\n\n                    point.point.x = (*wp_node)[i][\"point\"][\"x\"].as();\n                    point.point.y = (*wp_node)[i][\"point\"][\"y\"].as();\n                    point.point.z = (*wp_node)[i][\"point\"][\"z\"].as();\n\n                    waypoints_.push_back(point);\n\n                }\n            }else{\n                return false;\n            }\n\n            const YAML::Node &fp_node_tmp = node[\"finish_pose\"];\n            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;\n\n            if(fp_node != NULL){\n                finish_pose_.position.x = (*fp_node)[\"pose\"][\"position\"][\"x\"].as();\n                finish_pose_.position.y = (*fp_node)[\"pose\"][\"position\"][\"y\"].as();\n                finish_pose_.position.z = (*fp_node)[\"pose\"][\"position\"][\"z\"].as();\n\n                finish_pose_.orientation.x = (*fp_node)[\"pose\"][\"orientation\"][\"x\"].as();\n                finish_pose_.orientation.y = (*fp_node)[\"pose\"][\"orientation\"][\"y\"].as();\n                finish_pose_.orientation.z = (*fp_node)[\"pose\"][\"orientation\"][\"z\"].as();\n                finish_pose_.orientation.w = (*fp_node)[\"pose\"][\"orientation\"][\"w\"].as();\n            }else{\n                return false;\n            }\n\n        }catch(YAML::ParserException &e){\n            return false;\n\n        }catch(YAML::RepresentationException &e){\n            return false;\n        }\n\n        return true;\n    }\n\n    bool shouldSendGoal(){\n        bool ret = true;\n        actionlib::SimpleClientGoalState state = move_base_action_.getState();\n        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&\n           (state != actionlib::SimpleClientGoalState::PENDING) && \n           (state != actionlib::SimpleClientGoalState::RECALLED) &&\n           (state != actionlib::SimpleClientGoalState::PREEMPTED))\n        {\n            ret = false;\n        }\n\n        if(waypoints_.empty()){\n            ret = false;\n        }\n\n        return ret;\n    }\n\n    bool navigationFinished(){\n        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;\n    }\n\n    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){\n        tf::StampedTransform robot_gl = getRobotPosGL();\n\n        const double wx = dest.x;\n        const double wy = dest.y;\n        const double rx = robot_gl.getOrigin().x();\n        const double ry = robot_gl.getOrigin().y();\n        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));\n\n        return dist < dist_err;\n    }\n\n    tf::StampedTransform getRobotPosGL(){\n        tf::StampedTransform robot_gl;\n        try{\n            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);\n        }catch(tf::TransformException &e){\n            ROS_WARN_STREAM(\"tf::TransformException: \" << e.what());\n        }\n\n        return robot_gl;\n    }\n\n    void sleep(){\n        rate_.sleep();\n        ros::spinOnce();\n        publishMarkers();\n    }\n\n    void startNavigationGL(const geometry_msgs::Point &dest){\n        geometry_msgs::Pose pose;\n        pose.position = dest;\n        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);\n        startNavigationGL(pose);\n    }\n\n    void startNavigationGL(const geometry_msgs::Pose &dest){\n        move_base_msgs::MoveBaseGoal move_base_goal;\n        move_base_goal.target_pose.header.stamp = ros::Time::now();\n        move_base_goal.target_pose.header.frame_id = world_frame_;\n        move_base_goal.target_pose.pose.position = dest.position;\n        move_base_goal.target_pose.pose.orientation = dest.orientation;\n        \n        move_base_action_.sendGoal(move_base_goal);\n    }\n\n    void publishMarkers(){\n        visualization_msgs::MarkerArray markers_array;\n        for(int i=0; i < waypoints_.size(); i++){\n            visualization_msgs::Marker marker, label;\n            marker.header.frame_id = world_frame_;\n            marker.header.stamp = ros::Time::now();\n            marker.scale.x = 0.2;\n            marker.scale.y = 0.2;\n            marker.scale.z = 0.2;\n            marker.pose.position.z = marker.scale.z \/ 2.0;\n            marker.color.r = 0.8f;\n            marker.color.g = 0.2f;\n            marker.color.b = 0.2f;\n            \n            std::stringstream name;\n            name << \"waypoint \" << i;\n            marker.ns = name.str();\n            marker.id = i;\n            marker.pose.position.x = waypoints_[i].point.x;\n            marker.pose.position.y = waypoints_[i].point.y;\n            marker.type = visualization_msgs::Marker::SPHERE;\n            marker.action = visualization_msgs::Marker::ADD;\n            marker.color.a = 1.0f;\n            markers_array.markers.push_back(marker);\n\n            \/\/ROS_INFO_STREAM(\"waypoints \\n\" << waypoints_[i]);\n        }\n        marker_pub_.publish(markers_array);\n    }\n\n    void run(){\n        while(ros::ok()){\n            if(has_activate_){\n                for(int i=0; i < waypoints_.size(); i++){\n                    ROS_INFO_STREAM(\"waypoint = \" << waypoints_[i]);\n                    if(!ros::ok()) break;\n                    \n                    startNavigationGL(waypoints_[i].point);\n                    double old_time = ros::Time::now().toSec();\n                    tf::StampedTransform old_robot_gl = getRobotPosGL();\n                    while(!onNavigationPoint(waypoints_[i].point)){\n                        if(ros::Time::now().toSec() - old_time > 10.0){\n                            tf::StampedTransform robot_gl = getRobotPosGL();\n\n                            const double old_x = old_robot_gl.getOrigin().x();\n                            const double old_y = old_robot_gl.getOrigin().y();\n                            const double x = robot_gl.getOrigin().x();\n                            const double y = robot_gl.getOrigin().y();\n                            const double dist = std::sqrt(std::pow(old_x - x, 2) + std::pow(old_y - y, 2));\n                            if(dist < 0.5){\n                                ROS_WARN(\"Resend the navigation goal.\");\n                                std_srvs::Empty empty;\n                                clear_costmaps_srv_.call(empty);\n                                \/\/startNavigationGL(waypoints_[i].point);\n                            }\n                            old_time = ros::Time::now().toSec();\n                            old_robot_gl = robot_gl;\n                        }\n                        actionlib::SimpleClientGoalState state = move_base_action_.getState();\n                        sleep();\n                    }\n                    ROS_INFO(\"waypoint goal\");\n                }\n                ROS_INFO(\"waypoints clear\");\n                waypoints_.clear();\n                startNavigationGL(finish_pose_);\n                while(!navigationFinished() && ros::ok()) sleep();\n                has_activate_ = false;\n            }\n\n            sleep();\n        }\n    }\n\nprivate:\n    actionlib::SimpleActionClient move_base_action_;\n    std::vector waypoints_;\n    geometry_msgs::Pose finish_pose_;\n    bool has_activate_;\n    std::string robot_frame_, world_frame_;\n    tf::TransformListener tf_listener_;\n    ros::Rate rate_;\n    ros::Subscriber syscommand_sub_;\n    ros::Publisher marker_pub_;\n    ros::ServiceClient clear_costmaps_srv_;\n};\n\nint main(int argc, char *argv[]){\n    ros::init(argc, argv, ROS_PACKAGE_NAME);\n    WaypointsNavigation w_nav;\n    w_nav.run();\n\n    return 0;\n}\n<|endoftext|>"}
{"text":"\/\/===-- MachineFunction.cpp -----------------------------------------------===\/\/\n\/\/ \n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ \n\/\/ Collect native machine code information for a function.  This allows\n\/\/ target-specific information about the generated code to be stored with each\n\/\/ function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/CodeGen\/MachineFunctionInfo.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Type.h\"\n#include \"Support\/LeakDetector.h\"\n\nusing namespace llvm;\n\nstatic AnnotationID MF_AID(\n                 AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\nnamespace {\n  struct Printer : public MachineFunctionPass {\n    std::ostream *OS;\n    const std::string Banner;\n\n    Printer (std::ostream *_OS, const std::string &_Banner) :\n      OS (_OS), Banner (_Banner) { }\n\n    const char *getPassName() const { return \"MachineFunction Printer\"; }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.setPreservesAll();\n    }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      (*OS) << Banner;\n      MF.print (*OS);\n      return false;\n    }\n  };\n}\n\n\/\/\/ Returns a newly-created MachineFunction Printer pass. The default output\n\/\/\/ stream is std::cerr; the default banner is empty.\n\/\/\/\nFunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,\n                                                     const std::string &Banner) {\n  return new Printer(OS, Banner);\n}\n\nnamespace {\n  struct Deleter : public MachineFunctionPass {\n    const char *getPassName() const { return \"Machine Code Deleter\"; }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      \/\/ Delete the annotation from the function now.\n      MachineFunction::destruct(MF.getFunction());\n      return true;\n    }\n  };\n}\n\n\/\/\/ MachineCodeDeletion Pass - This pass deletes all of the machine code for\n\/\/\/ the current function, which should happen after the function has been\n\/\/\/ emitted to a .s file or to memory.\nFunctionPass *llvm::createMachineCodeDeleter() {\n  return new Deleter();\n}\n\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ MachineFunction implementation\n\/\/===---------------------------------------------------------------------===\/\/\nMachineBasicBlock* ilist_traits::createNode()\n{\n    MachineBasicBlock* dummy = new MachineBasicBlock();\n    LeakDetector::removeGarbageObject(dummy);\n    return dummy;\n}\n\nvoid ilist_traits::transferNodesFromList(\n    iplist >& toList,\n    ilist_iterator first,\n    ilist_iterator last)\n{\n    if (Parent != toList.Parent)\n        for (; first != last; ++first)\n            first->Parent = toList.Parent;\n}\n\nMachineFunction::MachineFunction(const Function *F,\n                                 const TargetMachine &TM)\n  : Annotation(MF_AID), Fn(F), Target(TM), NextMBBNumber(0) {\n  SSARegMapping = new SSARegMap();\n  MFInfo = new MachineFunctionInfo(*this);\n  FrameInfo = new MachineFrameInfo();\n  ConstantPool = new MachineConstantPool();\n  BasicBlocks.Parent = this;\n}\n\nMachineFunction::~MachineFunction() { \n  delete SSARegMapping;\n  delete MFInfo;\n  delete FrameInfo;\n  delete ConstantPool;\n}\n\nvoid MachineFunction::dump() const { print(std::cerr); }\n\nvoid MachineFunction::print(std::ostream &OS) const {\n  OS << \"# Machine code for \" << Fn->getName () << \"():\\n\";\n\n  \/\/ Print Frame Information\n  getFrameInfo()->print(*this, OS);\n\n  \/\/ Print Constant Pool\n  getConstantPool()->print(OS);\n  \n  for (const_iterator BB = begin(); BB != end(); ++BB)\n    BB->print(OS);\n\n  OS << \"\\n# End machine code for \" << Fn->getName () << \"().\\n\\n\";\n}\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/ \nMachineFunction&\nMachineFunction::construct(const Function *Fn, const TargetMachine &Tar)\n{\n  assert(Fn->getAnnotation(MF_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);\n  Fn->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid MachineFunction::destruct(const Function *Fn) {\n  bool Deleted = Fn->deleteAnnotation(MF_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineFunction& MachineFunction::get(const Function *F)\n{\n  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nvoid MachineFunction::clearSSARegMap() {\n  delete SSARegMapping;\n  SSARegMapping = 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFrameInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ CreateStackObject - Create a stack object for a value of the specified type.\n\/\/\/\nint MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {\n  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));\n}\n\nint MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {\n  return CreateStackObject(RC->getSize(), RC->getAlignment());\n}\n\n\nvoid MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{\n  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();\n\n  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {\n    const StackObject &SO = Objects[i];\n    OS << \"   is \";\n    if (SO.Size == 0)\n      OS << \"variable sized\";\n    else\n      OS << SO.Size << \" byte\" << (SO.Size != 1 ? \"s\" : \" \");\n    \n    if (i < NumFixedObjects)\n      OS << \" fixed\";\n    if (i < NumFixedObjects || SO.SPOffset != -1) {\n      int Off = SO.SPOffset - ValOffset;\n      OS << \" at location [SP\";\n      if (Off > 0)\n\tOS << \"+\" << Off;\n      else if (Off < 0)\n\tOS << Off;\n      OS << \"]\";\n    }\n    OS << \"\\n\";\n  }\n\n  if (HasVarSizedObjects)\n    OS << \"  Stack frame contains variable sized objects\\n\";\n}\n\nvoid MachineFrameInfo::dump(const MachineFunction &MF) const {\n  print(MF, std::cerr);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineConstantPool implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MachineConstantPool::print(std::ostream &OS) const {\n  for (unsigned i = 0, e = Constants.size(); i != e; ++i)\n    OS << \"   is\" << *(Value*)Constants[i] << \"\\n\";\n}\n\nvoid MachineConstantPool::dump() const { print(std::cerr); }\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFunctionInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic unsigned\nComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,\n                           unsigned &maxOptionalNumArgs)\n{\n  const TargetFrameInfo &frameInfo = *target.getFrameInfo();\n  \n  unsigned maxSize = 0;\n  \n  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)\n    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n      if (const CallInst *callInst = dyn_cast(I))\n        {\n          unsigned numOperands = callInst->getNumOperands() - 1;\n          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();\n          if (numExtra <= 0)\n            continue;\n          \n          unsigned sizeForThisCall;\n          if (frameInfo.argsOnStackHaveFixedSize())\n            {\n              int argSize = frameInfo.getSizeOfEachArgOnStack(); \n              sizeForThisCall = numExtra * (unsigned) argSize;\n            }\n          else\n            {\n              assert(0 && \"UNTESTED CODE: Size per stack argument is not \"\n                     \"fixed on this architecture: use actual arg sizes to \"\n                     \"compute MaxOptionalArgsSize\");\n              sizeForThisCall = 0;\n              for (unsigned i = 0; i < numOperands; ++i)\n                sizeForThisCall += target.getTargetData().getTypeSize(callInst->\n                                              getOperand(i)->getType());\n            }\n          \n          if (maxSize < sizeForThisCall)\n            maxSize = sizeForThisCall;\n          \n          if ((int)maxOptionalNumArgs < numExtra)\n            maxOptionalNumArgs = (unsigned) numExtra;\n        }\n  \n  return maxSize;\n}\n\n\/\/ Align data larger than one L1 cache line on L1 cache line boundaries.\n\/\/ Align all smaller data on the next higher 2^x boundary (4, 8, ...),\n\/\/ but not higher than the alignment of the largest type we support\n\/\/ (currently a double word). -- see class TargetData).\n\/\/\n\/\/ This function is similar to the corresponding function in EmitAssembly.cpp\n\/\/ but they are unrelated.  This one does not align at more than a\n\/\/ double-word boundary whereas that one might.\n\/\/ \ninline unsigned\nSizeToAlignment(unsigned size, const TargetMachine& target)\n{\n  const unsigned short cacheLineSize = 16;\n  if (size > (unsigned) cacheLineSize \/ 2)\n    return cacheLineSize;\n  else\n    for (unsigned sz=1; \/*no condition*\/; sz *= 2)\n      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())\n        return sz;\n}\n\n\nvoid MachineFunctionInfo::CalculateArgSize() {\n  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),\n\t\t\t\t\t\t   MF.getFunction(),\n                                                   maxOptionalNumArgs);\n  staticStackSize = maxOptionalArgsSize\n    + MF.getTarget().getFrameInfo()->getMinStackFrameSize();\n}\n\nint\nMachineFunctionInfo::computeOffsetforLocalVar(const Value* val,\n\t\t\t\t\t      unsigned &getPaddedSize,\n\t\t\t\t\t      unsigned  sizeToUse)\n{\n  if (sizeToUse == 0) {\n    \/\/ All integer types smaller than ints promote to 4 byte integers.\n    if (val->getType()->isIntegral() && val->getType()->getPrimitiveSize() < 4)\n      sizeToUse = 4;\n    else\n      sizeToUse = MF.getTarget().getTargetData().getTypeSize(val->getType());\n  }\n  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());\n\n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getFirstAutomaticVarOffset(MF,\n\t\t\t\t\t\t \t\t\t     growUp);\n  int offset = growUp? firstOffset + getAutomaticVarsSize()\n                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);\n  getPaddedSize = sizeToUse + abs(aligned - offset);\n\n  return aligned;\n}\n\n\nint MachineFunctionInfo::allocateLocalVar(const Value* val,\n                                          unsigned sizeToUse) {\n  assert(! automaticVarsAreaFrozen &&\n         \"Size of auto vars area has been used to compute an offset so \"\n         \"no more automatic vars should be allocated!\");\n  \n  \/\/ Check if we've allocated a stack slot for this value already\n  \/\/ \n  hash_map::const_iterator pair = offsets.find(val);\n  if (pair != offsets.end())\n    return pair->second;\n\n  unsigned getPaddedSize;\n  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);\n  offsets[val] = offset;\n  incrementAutomaticVarsSize(getPaddedSize);\n  return offset;\n}\n\nint\nMachineFunctionInfo::allocateSpilledValue(const Type* type)\n{\n  assert(! spillsAreaFrozen &&\n         \"Size of reg spills area has been used to compute an offset so \"\n         \"no more register spill slots should be allocated!\");\n  \n  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);\n  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);\n  \n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getRegSpillAreaOffset(MF, growUp);\n  \n  int offset = growUp? firstOffset + getRegSpillsSize()\n                     : firstOffset - (getRegSpillsSize() + size);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n  \n  incrementRegSpillsSize(size);  \/\/ update size of reg. spills area\n\n  return aligned;\n}\n\nint\nMachineFunctionInfo::pushTempValue(unsigned size)\n{\n  unsigned align = SizeToAlignment(size, MF.getTarget());\n\n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getTmpAreaOffset(MF, growUp);\n\n  int offset = growUp? firstOffset + currentTmpValuesSize\n                     : firstOffset - (currentTmpValuesSize + size);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp,\n\t\t\t\t\t\t\t      align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n\n  incrementTmpAreaSize(size);    \/\/ update \"current\" size of tmp area\n\n  return aligned;\n}\n\nvoid MachineFunctionInfo::popAllTempValues() {\n  resetTmpAreaSize();            \/\/ clear tmp area to reuse\n}\n\nInstance var no longer exists\/\/===-- MachineFunction.cpp -----------------------------------------------===\/\/\n\/\/ \n\/\/                     The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ \n\/\/ Collect native machine code information for a function.  This allows\n\/\/ target-specific information about the generated code to be stored with each\n\/\/ function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/CodeGen\/MachineFunctionInfo.h\"\n#include \"llvm\/CodeGen\/MachineFrameInfo.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetFrameInfo.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Type.h\"\n#include \"Support\/LeakDetector.h\"\n\nusing namespace llvm;\n\nstatic AnnotationID MF_AID(\n                 AnnotationManager::getID(\"CodeGen::MachineCodeForFunction\"));\n\n\nnamespace {\n  struct Printer : public MachineFunctionPass {\n    std::ostream *OS;\n    const std::string Banner;\n\n    Printer (std::ostream *_OS, const std::string &_Banner) :\n      OS (_OS), Banner (_Banner) { }\n\n    const char *getPassName() const { return \"MachineFunction Printer\"; }\n\n    virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n      AU.setPreservesAll();\n    }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      (*OS) << Banner;\n      MF.print (*OS);\n      return false;\n    }\n  };\n}\n\n\/\/\/ Returns a newly-created MachineFunction Printer pass. The default output\n\/\/\/ stream is std::cerr; the default banner is empty.\n\/\/\/\nFunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,\n                                                     const std::string &Banner) {\n  return new Printer(OS, Banner);\n}\n\nnamespace {\n  struct Deleter : public MachineFunctionPass {\n    const char *getPassName() const { return \"Machine Code Deleter\"; }\n\n    bool runOnMachineFunction(MachineFunction &MF) {\n      \/\/ Delete the annotation from the function now.\n      MachineFunction::destruct(MF.getFunction());\n      return true;\n    }\n  };\n}\n\n\/\/\/ MachineCodeDeletion Pass - This pass deletes all of the machine code for\n\/\/\/ the current function, which should happen after the function has been\n\/\/\/ emitted to a .s file or to memory.\nFunctionPass *llvm::createMachineCodeDeleter() {\n  return new Deleter();\n}\n\n\n\n\/\/===---------------------------------------------------------------------===\/\/\n\/\/ MachineFunction implementation\n\/\/===---------------------------------------------------------------------===\/\/\nMachineBasicBlock* ilist_traits::createNode()\n{\n    MachineBasicBlock* dummy = new MachineBasicBlock();\n    LeakDetector::removeGarbageObject(dummy);\n    return dummy;\n}\n\nvoid ilist_traits::transferNodesFromList(\n    iplist >& toList,\n    ilist_iterator first,\n    ilist_iterator last)\n{\n    if (Parent != toList.Parent)\n        for (; first != last; ++first)\n            first->Parent = toList.Parent;\n}\n\nMachineFunction::MachineFunction(const Function *F,\n                                 const TargetMachine &TM)\n  : Annotation(MF_AID), Fn(F), Target(TM) {\n  SSARegMapping = new SSARegMap();\n  MFInfo = new MachineFunctionInfo(*this);\n  FrameInfo = new MachineFrameInfo();\n  ConstantPool = new MachineConstantPool();\n  BasicBlocks.Parent = this;\n}\n\nMachineFunction::~MachineFunction() { \n  delete SSARegMapping;\n  delete MFInfo;\n  delete FrameInfo;\n  delete ConstantPool;\n}\n\nvoid MachineFunction::dump() const { print(std::cerr); }\n\nvoid MachineFunction::print(std::ostream &OS) const {\n  OS << \"# Machine code for \" << Fn->getName () << \"():\\n\";\n\n  \/\/ Print Frame Information\n  getFrameInfo()->print(*this, OS);\n\n  \/\/ Print Constant Pool\n  getConstantPool()->print(OS);\n  \n  for (const_iterator BB = begin(); BB != end(); ++BB)\n    BB->print(OS);\n\n  OS << \"\\n# End machine code for \" << Fn->getName () << \"().\\n\\n\";\n}\n\n\/\/ The next two methods are used to construct and to retrieve\n\/\/ the MachineCodeForFunction object for the given function.\n\/\/ construct() -- Allocates and initializes for a given function and target\n\/\/ get()       -- Returns a handle to the object.\n\/\/                This should not be called before \"construct()\"\n\/\/                for a given Function.\n\/\/ \nMachineFunction&\nMachineFunction::construct(const Function *Fn, const TargetMachine &Tar)\n{\n  assert(Fn->getAnnotation(MF_AID) == 0 &&\n         \"Object already exists for this function!\");\n  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);\n  Fn->addAnnotation(mcInfo);\n  return *mcInfo;\n}\n\nvoid MachineFunction::destruct(const Function *Fn) {\n  bool Deleted = Fn->deleteAnnotation(MF_AID);\n  assert(Deleted && \"Machine code did not exist for function!\");\n}\n\nMachineFunction& MachineFunction::get(const Function *F)\n{\n  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);\n  assert(mc && \"Call construct() method first to allocate the object\");\n  return *mc;\n}\n\nvoid MachineFunction::clearSSARegMap() {\n  delete SSARegMapping;\n  SSARegMapping = 0;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFrameInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/\/ CreateStackObject - Create a stack object for a value of the specified type.\n\/\/\/\nint MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {\n  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));\n}\n\nint MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {\n  return CreateStackObject(RC->getSize(), RC->getAlignment());\n}\n\n\nvoid MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{\n  int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();\n\n  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {\n    const StackObject &SO = Objects[i];\n    OS << \"   is \";\n    if (SO.Size == 0)\n      OS << \"variable sized\";\n    else\n      OS << SO.Size << \" byte\" << (SO.Size != 1 ? \"s\" : \" \");\n    \n    if (i < NumFixedObjects)\n      OS << \" fixed\";\n    if (i < NumFixedObjects || SO.SPOffset != -1) {\n      int Off = SO.SPOffset - ValOffset;\n      OS << \" at location [SP\";\n      if (Off > 0)\n\tOS << \"+\" << Off;\n      else if (Off < 0)\n\tOS << Off;\n      OS << \"]\";\n    }\n    OS << \"\\n\";\n  }\n\n  if (HasVarSizedObjects)\n    OS << \"  Stack frame contains variable sized objects\\n\";\n}\n\nvoid MachineFrameInfo::dump(const MachineFunction &MF) const {\n  print(MF, std::cerr);\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineConstantPool implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid MachineConstantPool::print(std::ostream &OS) const {\n  for (unsigned i = 0, e = Constants.size(); i != e; ++i)\n    OS << \"   is\" << *(Value*)Constants[i] << \"\\n\";\n}\n\nvoid MachineConstantPool::dump() const { print(std::cerr); }\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/  MachineFunctionInfo implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic unsigned\nComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,\n                           unsigned &maxOptionalNumArgs)\n{\n  const TargetFrameInfo &frameInfo = *target.getFrameInfo();\n  \n  unsigned maxSize = 0;\n  \n  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)\n    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n      if (const CallInst *callInst = dyn_cast(I))\n        {\n          unsigned numOperands = callInst->getNumOperands() - 1;\n          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();\n          if (numExtra <= 0)\n            continue;\n          \n          unsigned sizeForThisCall;\n          if (frameInfo.argsOnStackHaveFixedSize())\n            {\n              int argSize = frameInfo.getSizeOfEachArgOnStack(); \n              sizeForThisCall = numExtra * (unsigned) argSize;\n            }\n          else\n            {\n              assert(0 && \"UNTESTED CODE: Size per stack argument is not \"\n                     \"fixed on this architecture: use actual arg sizes to \"\n                     \"compute MaxOptionalArgsSize\");\n              sizeForThisCall = 0;\n              for (unsigned i = 0; i < numOperands; ++i)\n                sizeForThisCall += target.getTargetData().getTypeSize(callInst->\n                                              getOperand(i)->getType());\n            }\n          \n          if (maxSize < sizeForThisCall)\n            maxSize = sizeForThisCall;\n          \n          if ((int)maxOptionalNumArgs < numExtra)\n            maxOptionalNumArgs = (unsigned) numExtra;\n        }\n  \n  return maxSize;\n}\n\n\/\/ Align data larger than one L1 cache line on L1 cache line boundaries.\n\/\/ Align all smaller data on the next higher 2^x boundary (4, 8, ...),\n\/\/ but not higher than the alignment of the largest type we support\n\/\/ (currently a double word). -- see class TargetData).\n\/\/\n\/\/ This function is similar to the corresponding function in EmitAssembly.cpp\n\/\/ but they are unrelated.  This one does not align at more than a\n\/\/ double-word boundary whereas that one might.\n\/\/ \ninline unsigned\nSizeToAlignment(unsigned size, const TargetMachine& target)\n{\n  const unsigned short cacheLineSize = 16;\n  if (size > (unsigned) cacheLineSize \/ 2)\n    return cacheLineSize;\n  else\n    for (unsigned sz=1; \/*no condition*\/; sz *= 2)\n      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())\n        return sz;\n}\n\n\nvoid MachineFunctionInfo::CalculateArgSize() {\n  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),\n\t\t\t\t\t\t   MF.getFunction(),\n                                                   maxOptionalNumArgs);\n  staticStackSize = maxOptionalArgsSize\n    + MF.getTarget().getFrameInfo()->getMinStackFrameSize();\n}\n\nint\nMachineFunctionInfo::computeOffsetforLocalVar(const Value* val,\n\t\t\t\t\t      unsigned &getPaddedSize,\n\t\t\t\t\t      unsigned  sizeToUse)\n{\n  if (sizeToUse == 0) {\n    \/\/ All integer types smaller than ints promote to 4 byte integers.\n    if (val->getType()->isIntegral() && val->getType()->getPrimitiveSize() < 4)\n      sizeToUse = 4;\n    else\n      sizeToUse = MF.getTarget().getTargetData().getTypeSize(val->getType());\n  }\n  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());\n\n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getFirstAutomaticVarOffset(MF,\n\t\t\t\t\t\t \t\t\t     growUp);\n  int offset = growUp? firstOffset + getAutomaticVarsSize()\n                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);\n  getPaddedSize = sizeToUse + abs(aligned - offset);\n\n  return aligned;\n}\n\n\nint MachineFunctionInfo::allocateLocalVar(const Value* val,\n                                          unsigned sizeToUse) {\n  assert(! automaticVarsAreaFrozen &&\n         \"Size of auto vars area has been used to compute an offset so \"\n         \"no more automatic vars should be allocated!\");\n  \n  \/\/ Check if we've allocated a stack slot for this value already\n  \/\/ \n  hash_map::const_iterator pair = offsets.find(val);\n  if (pair != offsets.end())\n    return pair->second;\n\n  unsigned getPaddedSize;\n  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);\n  offsets[val] = offset;\n  incrementAutomaticVarsSize(getPaddedSize);\n  return offset;\n}\n\nint\nMachineFunctionInfo::allocateSpilledValue(const Type* type)\n{\n  assert(! spillsAreaFrozen &&\n         \"Size of reg spills area has been used to compute an offset so \"\n         \"no more register spill slots should be allocated!\");\n  \n  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);\n  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);\n  \n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getRegSpillAreaOffset(MF, growUp);\n  \n  int offset = growUp? firstOffset + getRegSpillsSize()\n                     : firstOffset - (getRegSpillsSize() + size);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp, align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n  \n  incrementRegSpillsSize(size);  \/\/ update size of reg. spills area\n\n  return aligned;\n}\n\nint\nMachineFunctionInfo::pushTempValue(unsigned size)\n{\n  unsigned align = SizeToAlignment(size, MF.getTarget());\n\n  bool growUp;\n  int firstOffset = MF.getTarget().getFrameInfo()->getTmpAreaOffset(MF, growUp);\n\n  int offset = growUp? firstOffset + currentTmpValuesSize\n                     : firstOffset - (currentTmpValuesSize + size);\n\n  int aligned = MF.getTarget().getFrameInfo()->adjustAlignment(offset, growUp,\n\t\t\t\t\t\t\t      align);\n  size += abs(aligned - offset); \/\/ include alignment padding in size\n\n  incrementTmpAreaSize(size);    \/\/ update \"current\" size of tmp area\n\n  return aligned;\n}\n\nvoid MachineFunctionInfo::popAllTempValues() {\n  resetTmpAreaSize();            \/\/ clear tmp area to reuse\n}\n\n<|endoftext|>"}
{"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\n\nPerturbNormalBlock::PerturbNormalBlock(const std::string& iName)\n    : NodeMaterialBlock{iName, NodeMaterialBlockTargets::Fragment}\n    , invertX{false}\n    , invertY{false}\n    , worldPosition{this, &PerturbNormalBlock::get_worldPosition}\n    , worldNormal{this, &PerturbNormalBlock::get_worldNormal}\n    , worldTangent{this, &PerturbNormalBlock::get_worldTangent}\n    , uv{this, &PerturbNormalBlock::get_uv}\n    , normalMapColor{this, &PerturbNormalBlock::get_normalMapColor}\n    , strength{this, &PerturbNormalBlock::get_strength}\n    , output{this, &PerturbNormalBlock::get_output}\n{\n  _isUnique = true;\n\n  \/\/ Vertex\n  registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes::Vector4, false);\n  registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes::Vector4, false);\n  registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes::Vector4, true);\n  registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes::Vector2, false);\n  registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes::Color3, false);\n  registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes::Float, false);\n\n  \/\/ Fragment\n  registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes::Vector4);\n}\n\nPerturbNormalBlock::~PerturbNormalBlock() = default;\n\nstd::string PerturbNormalBlock::getClassName() const\n{\n  return \"PerturbNormalBlock\";\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldPosition()\n{\n  return _inputs[0];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldNormal()\n{\n  return _inputs[1];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldTangent()\n{\n  return _inputs[2];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_uv()\n{\n  return _inputs[3];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_normalMapColor()\n{\n  return _inputs[4];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_strength()\n{\n  return _inputs[5];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_output()\n{\n  return _outputs[0];\n}\n\nvoid PerturbNormalBlock::prepareDefines(AbstractMesh* \/*mesh*\/,\n                                        const NodeMaterialPtr& \/*nodeMaterial*\/,\n                                        NodeMaterialDefines& defines, bool \/*useInstances*\/,\n                                        SubMesh* \/*subMesh*\/)\n{\n  defines.setValue(\"BUMP\", true);\n}\n\nvoid PerturbNormalBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* \/*mesh*\/,\n                              SubMesh* \/*subMesh*\/)\n{\n  if (nodeMaterial->getScene()->_mirroredCameraPosition) {\n    effect->setFloat2(_tangentSpaceParameterName, invertX ? 1.f : -1.f, invertY ? 1.f : -1.f);\n  }\n  else {\n    effect->setFloat2(_tangentSpaceParameterName, invertX ? -1.f : 1.f, invertY ? -1.f : 1.f);\n  }\n}\n\nvoid PerturbNormalBlock::autoConfigure(const NodeMaterialPtr& material)\n{\n  if (!uv()->isConnected()) {\n    auto uvInput = material->getInputBlockByPredicate(\n      [](const InputBlockPtr& b) -> bool { return b->isAttribute() && b->name() == \"uv\"; });\n\n    if (!uvInput) {\n      uvInput = InputBlock::New(\"uv\");\n      uvInput->setAsAttribute();\n    }\n    uvInput->output()->connectTo(uv);\n  }\n\n  if (!strength()->isConnected()) {\n    auto strengthInput   = InputBlock::New(\"strength\");\n    strengthInput->value = std::make_shared(1.f);\n    strengthInput->output()->connectTo(strength);\n  }\n}\n\nPerturbNormalBlock& PerturbNormalBlock::_buildBlock(NodeMaterialBuildState& state)\n{\n  NodeMaterialBlock::_buildBlock(state);\n\n  const auto iComments       = StringTools::printf(\"\/\/%s\", name().c_str());\n  const auto& _uv            = uv();\n  const auto& _worldPosition = worldPosition();\n  const auto& _worldNormal   = worldNormal();\n  const auto& _worldTangent  = worldTangent();\n\n  state.sharedData->blocksWithDefines.emplace_back(shared_from_this());\n  state.sharedData->bindableBlocks.emplace_back(shared_from_this());\n\n  _tangentSpaceParameterName = state._getFreeDefineName(\"tangentSpaceParameter\");\n\n  state._emitUniformFromString(_tangentSpaceParameterName, \"vec2\");\n\n  const auto replaceForBumpInfos\n    = strength()->isConnectedToInputBlock() && strength()->connectInputBlock()->isConstant ?\n        StringTools::printf(\n          \"\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0\/\\r\\n#endif\\r\\n%s\",\n          state._emitFloat(strength()->connectInputBlock()->value()->get())) :\n        StringTools::printf(\"\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0\/\\r\\n#endif\\r\\n%s\",\n                            strength()->associatedVariableName().c_str());\n\n  state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n\n  StringsReplacement tangentReplaceString{\n    \"defined\\\\(TANGENT\\\\)\",                                               \/\/ search\n    _worldTangent->isConnected() ? \"defined(TANGENT)\" : \"defined(IGNORE)\" \/\/ replace\n  };\n\n  if (_worldTangent->isConnected()) {\n    state.compilationString += StringTools::printf(\"vec3 tbnNormal = normalize(%s.xyz);\\r\\n\",\n                                                   _worldNormal->associatedVariableName().c_str());\n    state.compilationString += StringTools::printf(\"vec3 tbnTangent = normalize(%s.xyz);\\r\\n\",\n                                                   _worldTangent->associatedVariableName().c_str());\n    state.compilationString += \"vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\\r\\n\";\n    state.compilationString += \"mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n\";\n  }\n\n  {\n    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;\n    emitFunctionFromIncludeOptions.replaceStrings = {tangentReplaceString};\n    state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", iComments,\n                                   emitFunctionFromIncludeOptions);\n  }\n\n  {\n    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;\n    emitFunctionFromIncludeOptions.replaceStrings\n      = {{\"vBumpInfos.y\", replaceForBumpInfos},\n         {\"vTangentSpaceParams\", _tangentSpaceParameterName},\n         {\"vPositionW\", _worldPosition->associatedVariableName() + \".xyz\"},\n         {\"varying vec2 vBumpUV;\", \"\"},\n         {R\"(uniform sampler2D bumpSampler;[\\s\\S]*?\\})\", \"\"}};\n    state._emitFunctionFromInclude(\"bumpFragmentFunctions\", iComments,\n                                   emitFunctionFromIncludeOptions);\n  }\n\n  state.compilationString += _declareOutput(output, state) + \" = vec4(0.);\\r\\n\";\n  EmitCodeFromIncludeOptions emitCodeFromIncludeOptions;\n  emitCodeFromIncludeOptions.replaceStrings\n    = {{\"perturbNormal\\\\(TBN,vBumpUV\\\\+uvOffset\\\\)\",\n        StringTools::printf(\"perturbNormal(TBN, %s)\",\n                            normalMapColor()->associatedVariableName().c_str())},\n       {\"vBumpInfos.y\", replaceForBumpInfos},\n       {\"vBumpUV\", _uv->associatedVariableName()},\n       {\"vPositionW\", _worldPosition->associatedVariableName() + \".xyz\"},\n       {\"normalW=\", output()->associatedVariableName() + \".xyz = \"},\n       {R\"(mat3\\(normalMatrix\\)\\*normalW)\",\n        \"mat3(normalMatrix) * \" + output()->associatedVariableName() + \".xyz\"},\n       {\"normalW\", _worldNormal->associatedVariableName() + \".xyz\"},\n       tangentReplaceString};\n  state.compilationString\n    += state._emitCodeFromInclude(\"bumpFragment\", iComments, emitCodeFromIncludeOptions);\n\n  return *this;\n}\n\nstd::string PerturbNormalBlock::_dumpPropertiesCode()\n{\n  auto codeString = StringTools::printf(\"%s.invertX = %s;\\r\\n\", _codeVariableName.c_str(),\n                                        invertX ? \"true\" : \"false\");\n\n  codeString += StringTools::printf(\"%s.invertY = %s;\\r\\n\", _codeVariableName.c_str(),\n                                    invertY ? \"true\" : \"false\");\n\n  return codeString;\n}\n\njson PerturbNormalBlock::serialize() const\n{\n  return nullptr;\n}\n\nvoid PerturbNormalBlock::_deserialize(const json& \/*serializationObject*\/, Scene* \/*scene*\/,\n                                      const std::string& \/*rootUrl*\/)\n{\n}\n\n} \/\/ end of namespace BABYLON\nAdded missing c_str() function call#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace BABYLON {\n\nPerturbNormalBlock::PerturbNormalBlock(const std::string& iName)\n    : NodeMaterialBlock{iName, NodeMaterialBlockTargets::Fragment}\n    , invertX{false}\n    , invertY{false}\n    , worldPosition{this, &PerturbNormalBlock::get_worldPosition}\n    , worldNormal{this, &PerturbNormalBlock::get_worldNormal}\n    , worldTangent{this, &PerturbNormalBlock::get_worldTangent}\n    , uv{this, &PerturbNormalBlock::get_uv}\n    , normalMapColor{this, &PerturbNormalBlock::get_normalMapColor}\n    , strength{this, &PerturbNormalBlock::get_strength}\n    , output{this, &PerturbNormalBlock::get_output}\n{\n  _isUnique = true;\n\n  \/\/ Vertex\n  registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes::Vector4, false);\n  registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes::Vector4, false);\n  registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes::Vector4, true);\n  registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes::Vector2, false);\n  registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes::Color3, false);\n  registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes::Float, false);\n\n  \/\/ Fragment\n  registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes::Vector4);\n}\n\nPerturbNormalBlock::~PerturbNormalBlock() = default;\n\nstd::string PerturbNormalBlock::getClassName() const\n{\n  return \"PerturbNormalBlock\";\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldPosition()\n{\n  return _inputs[0];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldNormal()\n{\n  return _inputs[1];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_worldTangent()\n{\n  return _inputs[2];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_uv()\n{\n  return _inputs[3];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_normalMapColor()\n{\n  return _inputs[4];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_strength()\n{\n  return _inputs[5];\n}\n\nNodeMaterialConnectionPointPtr& PerturbNormalBlock::get_output()\n{\n  return _outputs[0];\n}\n\nvoid PerturbNormalBlock::prepareDefines(AbstractMesh* \/*mesh*\/,\n                                        const NodeMaterialPtr& \/*nodeMaterial*\/,\n                                        NodeMaterialDefines& defines, bool \/*useInstances*\/,\n                                        SubMesh* \/*subMesh*\/)\n{\n  defines.setValue(\"BUMP\", true);\n}\n\nvoid PerturbNormalBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* \/*mesh*\/,\n                              SubMesh* \/*subMesh*\/)\n{\n  if (nodeMaterial->getScene()->_mirroredCameraPosition) {\n    effect->setFloat2(_tangentSpaceParameterName, invertX ? 1.f : -1.f, invertY ? 1.f : -1.f);\n  }\n  else {\n    effect->setFloat2(_tangentSpaceParameterName, invertX ? -1.f : 1.f, invertY ? -1.f : 1.f);\n  }\n}\n\nvoid PerturbNormalBlock::autoConfigure(const NodeMaterialPtr& material)\n{\n  if (!uv()->isConnected()) {\n    auto uvInput = material->getInputBlockByPredicate(\n      [](const InputBlockPtr& b) -> bool { return b->isAttribute() && b->name() == \"uv\"; });\n\n    if (!uvInput) {\n      uvInput = InputBlock::New(\"uv\");\n      uvInput->setAsAttribute();\n    }\n    uvInput->output()->connectTo(uv);\n  }\n\n  if (!strength()->isConnected()) {\n    auto strengthInput   = InputBlock::New(\"strength\");\n    strengthInput->value = std::make_shared(1.f);\n    strengthInput->output()->connectTo(strength);\n  }\n}\n\nPerturbNormalBlock& PerturbNormalBlock::_buildBlock(NodeMaterialBuildState& state)\n{\n  NodeMaterialBlock::_buildBlock(state);\n\n  const auto iComments       = StringTools::printf(\"\/\/%s\", name().c_str());\n  const auto& _uv            = uv();\n  const auto& _worldPosition = worldPosition();\n  const auto& _worldNormal   = worldNormal();\n  const auto& _worldTangent  = worldTangent();\n\n  state.sharedData->blocksWithDefines.emplace_back(shared_from_this());\n  state.sharedData->bindableBlocks.emplace_back(shared_from_this());\n\n  _tangentSpaceParameterName = state._getFreeDefineName(\"tangentSpaceParameter\");\n\n  state._emitUniformFromString(_tangentSpaceParameterName, \"vec2\");\n\n  const auto replaceForBumpInfos\n    = strength()->isConnectedToInputBlock() && strength()->connectInputBlock()->isConstant ?\n        StringTools::printf(\n          \"\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0\/\\r\\n#endif\\r\\n%s\",\n          state._emitFloat(strength()->connectInputBlock()->value()->get()).c_str()) :\n        StringTools::printf(\"\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0\/\\r\\n#endif\\r\\n%s\",\n                            strength()->associatedVariableName().c_str());\n\n  state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n\n  StringsReplacement tangentReplaceString{\n    \"defined\\\\(TANGENT\\\\)\",                                               \/\/ search\n    _worldTangent->isConnected() ? \"defined(TANGENT)\" : \"defined(IGNORE)\" \/\/ replace\n  };\n\n  if (_worldTangent->isConnected()) {\n    state.compilationString += StringTools::printf(\"vec3 tbnNormal = normalize(%s.xyz);\\r\\n\",\n                                                   _worldNormal->associatedVariableName().c_str());\n    state.compilationString += StringTools::printf(\"vec3 tbnTangent = normalize(%s.xyz);\\r\\n\",\n                                                   _worldTangent->associatedVariableName().c_str());\n    state.compilationString += \"vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\\r\\n\";\n    state.compilationString += \"mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n\";\n  }\n\n  {\n    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;\n    emitFunctionFromIncludeOptions.replaceStrings = {tangentReplaceString};\n    state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", iComments,\n                                   emitFunctionFromIncludeOptions);\n  }\n\n  {\n    EmitFunctionFromIncludeOptions emitFunctionFromIncludeOptions;\n    emitFunctionFromIncludeOptions.replaceStrings\n      = {{\"vBumpInfos.y\", replaceForBumpInfos},\n         {\"vTangentSpaceParams\", _tangentSpaceParameterName},\n         {\"vPositionW\", _worldPosition->associatedVariableName() + \".xyz\"},\n         {\"varying vec2 vBumpUV;\", \"\"},\n         {R\"(uniform sampler2D bumpSampler;[\\s\\S]*?\\})\", \"\"}};\n    state._emitFunctionFromInclude(\"bumpFragmentFunctions\", iComments,\n                                   emitFunctionFromIncludeOptions);\n  }\n\n  state.compilationString += _declareOutput(output, state) + \" = vec4(0.);\\r\\n\";\n  EmitCodeFromIncludeOptions emitCodeFromIncludeOptions;\n  emitCodeFromIncludeOptions.replaceStrings\n    = {{\"perturbNormal\\\\(TBN,vBumpUV\\\\+uvOffset\\\\)\",\n        StringTools::printf(\"perturbNormal(TBN, %s)\",\n                            normalMapColor()->associatedVariableName().c_str())},\n       {\"vBumpInfos.y\", replaceForBumpInfos},\n       {\"vBumpUV\", _uv->associatedVariableName()},\n       {\"vPositionW\", _worldPosition->associatedVariableName() + \".xyz\"},\n       {\"normalW=\", output()->associatedVariableName() + \".xyz = \"},\n       {R\"(mat3\\(normalMatrix\\)\\*normalW)\",\n        \"mat3(normalMatrix) * \" + output()->associatedVariableName() + \".xyz\"},\n       {\"normalW\", _worldNormal->associatedVariableName() + \".xyz\"},\n       tangentReplaceString};\n  state.compilationString\n    += state._emitCodeFromInclude(\"bumpFragment\", iComments, emitCodeFromIncludeOptions);\n\n  return *this;\n}\n\nstd::string PerturbNormalBlock::_dumpPropertiesCode()\n{\n  auto codeString = StringTools::printf(\"%s.invertX = %s;\\r\\n\", _codeVariableName.c_str(),\n                                        invertX ? \"true\" : \"false\");\n\n  codeString += StringTools::printf(\"%s.invertY = %s;\\r\\n\", _codeVariableName.c_str(),\n                                    invertY ? \"true\" : \"false\");\n\n  return codeString;\n}\n\njson PerturbNormalBlock::serialize() const\n{\n  return nullptr;\n}\n\nvoid PerturbNormalBlock::_deserialize(const json& \/*serializationObject*\/, Scene* \/*scene*\/,\n                                      const std::string& \/*rootUrl*\/)\n{\n}\n\n} \/\/ end of namespace BABYLON\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\/chromeos\/boot_times_loader.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/process_util.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/chromeos\/login\/authentication_notification_details.h\"\n#include \"chrome\/browser\/chromeos\/network_state_notifier.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace chromeos {\n\n\/\/ File uptime logs are located in.\nstatic const char kLogPath[] = \"\/tmp\";\n\/\/ Prefix for the time measurement files.\nstatic const char kUptimePrefix[] = \"uptime-\";\n\/\/ Prefix for the disk usage files.\nstatic const char kDiskPrefix[] = \"disk-\";\n\/\/ Name of the time that Chrome's main() is called.\nstatic const char kChromeMain[] = \"chrome-main\";\n\/\/ Delay in milliseconds between file read attempts.\nstatic const int64 kReadAttemptDelayMs = 250;\n\/\/ Delay in milliseconds before writing the login times to disk.\nstatic const int64 kLoginTimeWriteDelayMs = 3000;\n\n\/\/ Names of login stats files.\nstatic const char kLoginSuccess[] = \"login-success\";\nstatic const char kChromeFirstRender[] = \"chrome-first-render\";\n\n\/\/ Names of login UMA values.\nstatic const char kUmaAuthenticate[] = \"BootTime.Authenticate\";\nstatic const char kUmaLogin[] = \"BootTime.Login\";\n\n\/\/ Name of file collecting login times.\nstatic const char kLoginTimes[] = \"login-times-sent\";\n\nBootTimesLoader::BootTimesLoader()\n    : backend_(new Backend()),\n      have_registered_(false) {\n  login_time_markers_.reserve(30);\n}\n\n\/\/ static\nBootTimesLoader* BootTimesLoader::Get() {\n  return Singleton::get();\n}\n\nBootTimesLoader::Handle BootTimesLoader::GetBootTimes(\n    CancelableRequestConsumerBase* consumer,\n    BootTimesLoader::GetBootTimesCallback* callback) {\n  if (!g_browser_process->file_thread()) {\n    \/\/ This should only happen if Chrome is shutting down, so we don't do\n    \/\/ anything.\n    return 0;\n  }\n\n  const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n  if (command_line.HasSwitch(switches::kTestType)) {\n    \/\/ TODO(davemoore) This avoids boottimes for tests. This needs to be\n    \/\/ replaced with a mock of BootTimesLoader.\n    return 0;\n  }\n\n  scoped_refptr > request(\n      new CancelableRequest(callback));\n  AddRequest(request, consumer);\n\n  BrowserThread::PostTask(\n      BrowserThread::FILE,\n      FROM_HERE,\n      NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request));\n  return request->handle();\n}\n\n\/\/ Extracts the uptime value from files located in \/tmp, returning the\n\/\/ value as a double in value.\nstatic bool GetTime(const std::string& log, double* value) {\n  FilePath log_dir(kLogPath);\n  FilePath log_file = log_dir.Append(log);\n  std::string contents;\n  *value = 0.0;\n  if (file_util::ReadFileToString(log_file, &contents)) {\n    size_t space_index = contents.find(' ');\n    size_t chars_left =\n        space_index != std::string::npos ? space_index : std::string::npos;\n    std::string value_string = contents.substr(0, chars_left);\n    return base::StringToDouble(value_string, value);\n  }\n  return false;\n}\n\n\/\/ Converts double seconds to a TimeDelta object.\nstatic base::TimeDelta SecondsToTimeDelta(double seconds) {\n  double ms = seconds * base::Time::kMillisecondsPerSecond;\n  return base::TimeDelta::FromMilliseconds(static_cast(ms));\n}\n\n\/\/ Reports the collected boot times to UMA if they haven't been\n\/\/ reported yet and if metrics collection is enabled.\nstatic void SendBootTimesToUMA(const BootTimesLoader::BootTimes& boot_times) {\n  \/\/ Checks if the times for the most recent boot event have been\n  \/\/ reported already to avoid sending boot time histogram samples\n  \/\/ every time the user logs out.\n  static const char kBootTimesSent[] = \"\/tmp\/boot-times-sent\";\n  FilePath sent(kBootTimesSent);\n  if (file_util::PathExists(sent))\n    return;\n\n  UMA_HISTOGRAM_TIMES(\"BootTime.Total\",\n                      SecondsToTimeDelta(boot_times.total));\n  UMA_HISTOGRAM_TIMES(\"BootTime.Firmware\",\n                      SecondsToTimeDelta(boot_times.firmware));\n  UMA_HISTOGRAM_TIMES(\"BootTime.Kernel\",\n                      SecondsToTimeDelta(boot_times.pre_startup));\n  UMA_HISTOGRAM_TIMES(\"BootTime.System\",\n                      SecondsToTimeDelta(boot_times.system));\n  if (boot_times.chrome > 0) {\n    UMA_HISTOGRAM_TIMES(\"BootTime.Chrome\",\n                        SecondsToTimeDelta(boot_times.chrome));\n  }\n\n  \/\/ Stores the boot times to a file in \/tmp to indicate that the\n  \/\/ times for the most recent boot event have been reported\n  \/\/ already. The file will be deleted at system shutdown\/reboot.\n  std::string boot_times_text = base::StringPrintf(\"total: %.2f\\n\"\n                                                   \"firmware: %.2f\\n\"\n                                                   \"kernel: %.2f\\n\"\n                                                   \"system: %.2f\\n\"\n                                                   \"chrome: %.2f\\n\",\n                                                   boot_times.total,\n                                                   boot_times.firmware,\n                                                   boot_times.pre_startup,\n                                                   boot_times.system,\n                                                   boot_times.chrome);\n  file_util::WriteFile(sent, boot_times_text.data(), boot_times_text.size());\n  DCHECK(file_util::PathExists(sent));\n}\n\nvoid BootTimesLoader::Backend::GetBootTimes(\n    scoped_refptr request) {\n  const char* kFirmwareBootTime = \"firmware-boot-time\";\n  const char* kPreStartup = \"pre-startup\";\n  const char* kChromeExec = \"chrome-exec\";\n  const char* kChromeMain = \"chrome-main\";\n  const char* kXStarted = \"x-started\";\n  const char* kLoginPromptReady = \"login-prompt-ready\";\n  std::string uptime_prefix = kUptimePrefix;\n\n  if (request->canceled())\n    return;\n\n  \/\/ Wait until login_prompt_ready is output by reposting.\n  FilePath log_dir(kLogPath);\n  FilePath log_file = log_dir.Append(uptime_prefix + kLoginPromptReady);\n  if (!file_util::PathExists(log_file)) {\n    BrowserThread::PostDelayedTask(\n        BrowserThread::FILE,\n        FROM_HERE,\n        NewRunnableMethod(this, &Backend::GetBootTimes, request),\n        kReadAttemptDelayMs);\n    return;\n  }\n\n  BootTimes boot_times;\n\n  GetTime(kFirmwareBootTime, &boot_times.firmware);\n  GetTime(uptime_prefix + kPreStartup, &boot_times.pre_startup);\n  GetTime(uptime_prefix + kXStarted, &boot_times.x_started);\n  GetTime(uptime_prefix + kChromeExec, &boot_times.chrome_exec);\n  GetTime(uptime_prefix + kChromeMain, &boot_times.chrome_main);\n  GetTime(uptime_prefix + kLoginPromptReady, &boot_times.login_prompt_ready);\n\n  boot_times.total = boot_times.firmware + boot_times.login_prompt_ready;\n  if (boot_times.chrome_exec > 0) {\n    boot_times.system = boot_times.chrome_exec - boot_times.pre_startup;\n    boot_times.chrome = boot_times.login_prompt_ready - boot_times.chrome_exec;\n  } else {\n    boot_times.system = boot_times.login_prompt_ready - boot_times.pre_startup;\n  }\n\n  SendBootTimesToUMA(boot_times);\n\n  request->ForwardResult(\n      GetBootTimesCallback::TupleType(request->handle(), boot_times));\n}\n\nstatic void RecordStatsDelayed(\n    const std::string& name,\n    const std::string& uptime,\n    const std::string& disk) {\n  const FilePath log_path(kLogPath);\n  std::string disk_prefix = kDiskPrefix;\n  const FilePath uptime_output =\n      log_path.Append(FilePath(kUptimePrefix + name));\n  const FilePath disk_output = log_path.Append(FilePath(kDiskPrefix + name));\n\n  \/\/ Write out the files, ensuring that they don't exist already.\n  if (!file_util::PathExists(uptime_output))\n    file_util::WriteFile(uptime_output, uptime.data(), uptime.size());\n  if (!file_util::PathExists(disk_output))\n    file_util::WriteFile(disk_output, disk.data(), disk.size());\n}\n\n\/\/ static\nvoid BootTimesLoader::WriteLoginTimes(\n    const std::vector login_times) {\n  const int kMinTimeMillis = 1;\n  const int kMaxTimeMillis = 30;\n  const int kNumBuckets = 100;\n  const char kUmaPrefix[] = \"BootTime.\";\n  const FilePath log_path(kLogPath);\n\n  base::Time first = login_times.front().time();\n  base::Time last = login_times.back().time();\n  base::TimeDelta total = last - first;\n  scoped_refptrtotal_hist = base::Histogram::FactoryTimeGet(\n      kUmaLogin,\n      base::TimeDelta::FromMilliseconds(kMinTimeMillis),\n      base::TimeDelta::FromMilliseconds(kMaxTimeMillis),\n      kNumBuckets,\n      base::Histogram::kUmaTargetedHistogramFlag);\n  total_hist->AddTime(total);\n  std::string output =\n      base::StringPrintf(\"%s: %.2f\", kUmaLogin, total.InSecondsF());\n  base::Time prev = first;\n  for (unsigned int i = 0; i < login_times.size(); ++i) {\n    TimeMarker tm = login_times[i];\n    base::TimeDelta since_first = tm.time() - first;\n    base::TimeDelta since_prev = tm.time() - prev;\n    std::string name;\n\n    if (tm.send_to_uma()) {\n      name = kUmaPrefix + tm.name();\n      scoped_refptrprev_hist = base::Histogram::FactoryTimeGet(\n          name,\n          base::TimeDelta::FromMilliseconds(kMinTimeMillis),\n          base::TimeDelta::FromMilliseconds(kMaxTimeMillis),\n          kNumBuckets,\n          base::Histogram::kUmaTargetedHistogramFlag);\n      prev_hist->AddTime(since_prev);\n    } else {\n      name = tm.name();\n    }\n    output +=\n        StringPrintf(\n            \"\\n%.2f +%.2f %s\",\n            since_first.InSecondsF(),\n            since_prev.InSecondsF(),\n            name.data());\n    prev = tm.time();\n  }\n  file_util::WriteFile(\n      log_path.Append(kLoginTimes), output.data(), output.size());\n}\n\nvoid BootTimesLoader::RecordStats(const std::string& name, const Stats& stats) {\n  BrowserThread::PostTask(\n      BrowserThread::FILE, FROM_HERE,\n      NewRunnableFunction(\n          RecordStatsDelayed, name, stats.uptime, stats.disk));\n}\n\nBootTimesLoader::Stats BootTimesLoader::GetCurrentStats() {\n  const FilePath kProcUptime(\"\/proc\/uptime\");\n  const FilePath kDiskStat(\"\/sys\/block\/sda\/stat\");\n  Stats stats;\n\n  file_util::ReadFileToString(kProcUptime, &stats.uptime);\n  file_util::ReadFileToString(kDiskStat, &stats.disk);\n  return stats;\n}\n\nvoid BootTimesLoader::RecordCurrentStats(const std::string& name) {\n  RecordStats(name, GetCurrentStats());\n}\n\nvoid BootTimesLoader::SaveChromeMainStats() {\n  chrome_main_stats_ = GetCurrentStats();\n}\n\nvoid BootTimesLoader::RecordChromeMainStats() {\n  RecordStats(kChromeMain, chrome_main_stats_);\n}\n\nvoid BootTimesLoader::RecordLoginAttempted() {\n  login_time_markers_.clear();\n  AddLoginTimeMarker(\"LoginStarted\", false);\n  if (!have_registered_) {\n    have_registered_ = true;\n    registrar_.Add(this, NotificationType::LOAD_START,\n                   NotificationService::AllSources());\n    registrar_.Add(this, NotificationType::LOGIN_AUTHENTICATION,\n                   NotificationService::AllSources());\n  }\n}\n\nvoid BootTimesLoader::AddLoginTimeMarker(\n    const std::string& marker_name, bool send_to_uma) {\n  login_time_markers_.push_back(TimeMarker(marker_name, send_to_uma));\n}\n\nvoid BootTimesLoader::Observe(\n    NotificationType type,\n    const NotificationSource& source,\n    const NotificationDetails& details) {\n  if (type == NotificationType::LOGIN_AUTHENTICATION) {\n    Details auth_details(details);\n    if (auth_details->success()) {\n      AddLoginTimeMarker(\"Authenticate\", true);\n      RecordCurrentStats(kLoginSuccess);\n      registrar_.Remove(this, NotificationType::LOGIN_AUTHENTICATION,\n                        NotificationService::AllSources());\n    }\n  } else if (type == NotificationType::LOAD_START) {\n    \/\/ Only log for first tab to render.  Make sure this is only done once.\n    \/\/ If the network isn't connected we'll get a second LOAD_START once it is\n    \/\/ and the page is reloaded.\n    if (NetworkStateNotifier::Get()->is_connected()) {\n      \/\/ Post difference between first tab and login success time.\n      AddLoginTimeMarker(\"LoginDone\", true);\n      RecordCurrentStats(kChromeFirstRender);\n      \/\/ Post chrome first render stat.\n      registrar_.Remove(this, NotificationType::LOAD_START,\n                        NotificationService::AllSources());\n      \/\/ Don't swamp the FILE thread right away.\n      BrowserThread::PostDelayedTask(\n          BrowserThread::FILE, FROM_HERE,\n          NewRunnableFunction(WriteLoginTimes, login_time_markers_),\n          kLoginTimeWriteDelayMs);\n      have_registered_ = false;\n    } else {\n      AddLoginTimeMarker(\"LoginRenderNoNetwork\", false);\n    }\n  }\n}\n\n}  \/\/ namespace chromeos\nCorrected constant value from seconds to milliseconds. Fixed DCHECK this way.\/\/ 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\/chromeos\/boot_times_loader.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/process_util.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/thread.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/chromeos\/login\/authentication_notification_details.h\"\n#include \"chrome\/browser\/chromeos\/network_state_notifier.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace chromeos {\n\n\/\/ File uptime logs are located in.\nstatic const char kLogPath[] = \"\/tmp\";\n\/\/ Prefix for the time measurement files.\nstatic const char kUptimePrefix[] = \"uptime-\";\n\/\/ Prefix for the disk usage files.\nstatic const char kDiskPrefix[] = \"disk-\";\n\/\/ Name of the time that Chrome's main() is called.\nstatic const char kChromeMain[] = \"chrome-main\";\n\/\/ Delay in milliseconds between file read attempts.\nstatic const int64 kReadAttemptDelayMs = 250;\n\/\/ Delay in milliseconds before writing the login times to disk.\nstatic const int64 kLoginTimeWriteDelayMs = 3000;\n\n\/\/ Names of login stats files.\nstatic const char kLoginSuccess[] = \"login-success\";\nstatic const char kChromeFirstRender[] = \"chrome-first-render\";\n\n\/\/ Names of login UMA values.\nstatic const char kUmaAuthenticate[] = \"BootTime.Authenticate\";\nstatic const char kUmaLogin[] = \"BootTime.Login\";\n\n\/\/ Name of file collecting login times.\nstatic const char kLoginTimes[] = \"login-times-sent\";\n\nBootTimesLoader::BootTimesLoader()\n    : backend_(new Backend()),\n      have_registered_(false) {\n  login_time_markers_.reserve(30);\n}\n\n\/\/ static\nBootTimesLoader* BootTimesLoader::Get() {\n  return Singleton::get();\n}\n\nBootTimesLoader::Handle BootTimesLoader::GetBootTimes(\n    CancelableRequestConsumerBase* consumer,\n    BootTimesLoader::GetBootTimesCallback* callback) {\n  if (!g_browser_process->file_thread()) {\n    \/\/ This should only happen if Chrome is shutting down, so we don't do\n    \/\/ anything.\n    return 0;\n  }\n\n  const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n  if (command_line.HasSwitch(switches::kTestType)) {\n    \/\/ TODO(davemoore) This avoids boottimes for tests. This needs to be\n    \/\/ replaced with a mock of BootTimesLoader.\n    return 0;\n  }\n\n  scoped_refptr > request(\n      new CancelableRequest(callback));\n  AddRequest(request, consumer);\n\n  BrowserThread::PostTask(\n      BrowserThread::FILE,\n      FROM_HERE,\n      NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request));\n  return request->handle();\n}\n\n\/\/ Extracts the uptime value from files located in \/tmp, returning the\n\/\/ value as a double in value.\nstatic bool GetTime(const std::string& log, double* value) {\n  FilePath log_dir(kLogPath);\n  FilePath log_file = log_dir.Append(log);\n  std::string contents;\n  *value = 0.0;\n  if (file_util::ReadFileToString(log_file, &contents)) {\n    size_t space_index = contents.find(' ');\n    size_t chars_left =\n        space_index != std::string::npos ? space_index : std::string::npos;\n    std::string value_string = contents.substr(0, chars_left);\n    return base::StringToDouble(value_string, value);\n  }\n  return false;\n}\n\n\/\/ Converts double seconds to a TimeDelta object.\nstatic base::TimeDelta SecondsToTimeDelta(double seconds) {\n  double ms = seconds * base::Time::kMillisecondsPerSecond;\n  return base::TimeDelta::FromMilliseconds(static_cast(ms));\n}\n\n\/\/ Reports the collected boot times to UMA if they haven't been\n\/\/ reported yet and if metrics collection is enabled.\nstatic void SendBootTimesToUMA(const BootTimesLoader::BootTimes& boot_times) {\n  \/\/ Checks if the times for the most recent boot event have been\n  \/\/ reported already to avoid sending boot time histogram samples\n  \/\/ every time the user logs out.\n  static const char kBootTimesSent[] = \"\/tmp\/boot-times-sent\";\n  FilePath sent(kBootTimesSent);\n  if (file_util::PathExists(sent))\n    return;\n\n  UMA_HISTOGRAM_TIMES(\"BootTime.Total\",\n                      SecondsToTimeDelta(boot_times.total));\n  UMA_HISTOGRAM_TIMES(\"BootTime.Firmware\",\n                      SecondsToTimeDelta(boot_times.firmware));\n  UMA_HISTOGRAM_TIMES(\"BootTime.Kernel\",\n                      SecondsToTimeDelta(boot_times.pre_startup));\n  UMA_HISTOGRAM_TIMES(\"BootTime.System\",\n                      SecondsToTimeDelta(boot_times.system));\n  if (boot_times.chrome > 0) {\n    UMA_HISTOGRAM_TIMES(\"BootTime.Chrome\",\n                        SecondsToTimeDelta(boot_times.chrome));\n  }\n\n  \/\/ Stores the boot times to a file in \/tmp to indicate that the\n  \/\/ times for the most recent boot event have been reported\n  \/\/ already. The file will be deleted at system shutdown\/reboot.\n  std::string boot_times_text = base::StringPrintf(\"total: %.2f\\n\"\n                                                   \"firmware: %.2f\\n\"\n                                                   \"kernel: %.2f\\n\"\n                                                   \"system: %.2f\\n\"\n                                                   \"chrome: %.2f\\n\",\n                                                   boot_times.total,\n                                                   boot_times.firmware,\n                                                   boot_times.pre_startup,\n                                                   boot_times.system,\n                                                   boot_times.chrome);\n  file_util::WriteFile(sent, boot_times_text.data(), boot_times_text.size());\n  DCHECK(file_util::PathExists(sent));\n}\n\nvoid BootTimesLoader::Backend::GetBootTimes(\n    scoped_refptr request) {\n  const char* kFirmwareBootTime = \"firmware-boot-time\";\n  const char* kPreStartup = \"pre-startup\";\n  const char* kChromeExec = \"chrome-exec\";\n  const char* kChromeMain = \"chrome-main\";\n  const char* kXStarted = \"x-started\";\n  const char* kLoginPromptReady = \"login-prompt-ready\";\n  std::string uptime_prefix = kUptimePrefix;\n\n  if (request->canceled())\n    return;\n\n  \/\/ Wait until login_prompt_ready is output by reposting.\n  FilePath log_dir(kLogPath);\n  FilePath log_file = log_dir.Append(uptime_prefix + kLoginPromptReady);\n  if (!file_util::PathExists(log_file)) {\n    BrowserThread::PostDelayedTask(\n        BrowserThread::FILE,\n        FROM_HERE,\n        NewRunnableMethod(this, &Backend::GetBootTimes, request),\n        kReadAttemptDelayMs);\n    return;\n  }\n\n  BootTimes boot_times;\n\n  GetTime(kFirmwareBootTime, &boot_times.firmware);\n  GetTime(uptime_prefix + kPreStartup, &boot_times.pre_startup);\n  GetTime(uptime_prefix + kXStarted, &boot_times.x_started);\n  GetTime(uptime_prefix + kChromeExec, &boot_times.chrome_exec);\n  GetTime(uptime_prefix + kChromeMain, &boot_times.chrome_main);\n  GetTime(uptime_prefix + kLoginPromptReady, &boot_times.login_prompt_ready);\n\n  boot_times.total = boot_times.firmware + boot_times.login_prompt_ready;\n  if (boot_times.chrome_exec > 0) {\n    boot_times.system = boot_times.chrome_exec - boot_times.pre_startup;\n    boot_times.chrome = boot_times.login_prompt_ready - boot_times.chrome_exec;\n  } else {\n    boot_times.system = boot_times.login_prompt_ready - boot_times.pre_startup;\n  }\n\n  SendBootTimesToUMA(boot_times);\n\n  request->ForwardResult(\n      GetBootTimesCallback::TupleType(request->handle(), boot_times));\n}\n\nstatic void RecordStatsDelayed(\n    const std::string& name,\n    const std::string& uptime,\n    const std::string& disk) {\n  const FilePath log_path(kLogPath);\n  std::string disk_prefix = kDiskPrefix;\n  const FilePath uptime_output =\n      log_path.Append(FilePath(kUptimePrefix + name));\n  const FilePath disk_output = log_path.Append(FilePath(kDiskPrefix + name));\n\n  \/\/ Write out the files, ensuring that they don't exist already.\n  if (!file_util::PathExists(uptime_output))\n    file_util::WriteFile(uptime_output, uptime.data(), uptime.size());\n  if (!file_util::PathExists(disk_output))\n    file_util::WriteFile(disk_output, disk.data(), disk.size());\n}\n\n\/\/ static\nvoid BootTimesLoader::WriteLoginTimes(\n    const std::vector login_times) {\n  const int kMinTimeMillis = 1;\n  const int kMaxTimeMillis = 30000;\n  const int kNumBuckets = 100;\n  const char kUmaPrefix[] = \"BootTime.\";\n  const FilePath log_path(kLogPath);\n\n  base::Time first = login_times.front().time();\n  base::Time last = login_times.back().time();\n  base::TimeDelta total = last - first;\n  scoped_refptrtotal_hist = base::Histogram::FactoryTimeGet(\n      kUmaLogin,\n      base::TimeDelta::FromMilliseconds(kMinTimeMillis),\n      base::TimeDelta::FromMilliseconds(kMaxTimeMillis),\n      kNumBuckets,\n      base::Histogram::kUmaTargetedHistogramFlag);\n  total_hist->AddTime(total);\n  std::string output =\n      base::StringPrintf(\"%s: %.2f\", kUmaLogin, total.InSecondsF());\n  base::Time prev = first;\n  for (unsigned int i = 0; i < login_times.size(); ++i) {\n    TimeMarker tm = login_times[i];\n    base::TimeDelta since_first = tm.time() - first;\n    base::TimeDelta since_prev = tm.time() - prev;\n    std::string name;\n\n    if (tm.send_to_uma()) {\n      name = kUmaPrefix + tm.name();\n      scoped_refptrprev_hist = base::Histogram::FactoryTimeGet(\n          name,\n          base::TimeDelta::FromMilliseconds(kMinTimeMillis),\n          base::TimeDelta::FromMilliseconds(kMaxTimeMillis),\n          kNumBuckets,\n          base::Histogram::kUmaTargetedHistogramFlag);\n      prev_hist->AddTime(since_prev);\n    } else {\n      name = tm.name();\n    }\n    output +=\n        StringPrintf(\n            \"\\n%.2f +%.2f %s\",\n            since_first.InSecondsF(),\n            since_prev.InSecondsF(),\n            name.data());\n    prev = tm.time();\n  }\n  file_util::WriteFile(\n      log_path.Append(kLoginTimes), output.data(), output.size());\n}\n\nvoid BootTimesLoader::RecordStats(const std::string& name, const Stats& stats) {\n  BrowserThread::PostTask(\n      BrowserThread::FILE, FROM_HERE,\n      NewRunnableFunction(\n          RecordStatsDelayed, name, stats.uptime, stats.disk));\n}\n\nBootTimesLoader::Stats BootTimesLoader::GetCurrentStats() {\n  const FilePath kProcUptime(\"\/proc\/uptime\");\n  const FilePath kDiskStat(\"\/sys\/block\/sda\/stat\");\n  Stats stats;\n\n  file_util::ReadFileToString(kProcUptime, &stats.uptime);\n  file_util::ReadFileToString(kDiskStat, &stats.disk);\n  return stats;\n}\n\nvoid BootTimesLoader::RecordCurrentStats(const std::string& name) {\n  RecordStats(name, GetCurrentStats());\n}\n\nvoid BootTimesLoader::SaveChromeMainStats() {\n  chrome_main_stats_ = GetCurrentStats();\n}\n\nvoid BootTimesLoader::RecordChromeMainStats() {\n  RecordStats(kChromeMain, chrome_main_stats_);\n}\n\nvoid BootTimesLoader::RecordLoginAttempted() {\n  login_time_markers_.clear();\n  AddLoginTimeMarker(\"LoginStarted\", false);\n  if (!have_registered_) {\n    have_registered_ = true;\n    registrar_.Add(this, NotificationType::LOAD_START,\n                   NotificationService::AllSources());\n    registrar_.Add(this, NotificationType::LOGIN_AUTHENTICATION,\n                   NotificationService::AllSources());\n  }\n}\n\nvoid BootTimesLoader::AddLoginTimeMarker(\n    const std::string& marker_name, bool send_to_uma) {\n  login_time_markers_.push_back(TimeMarker(marker_name, send_to_uma));\n}\n\nvoid BootTimesLoader::Observe(\n    NotificationType type,\n    const NotificationSource& source,\n    const NotificationDetails& details) {\n  if (type == NotificationType::LOGIN_AUTHENTICATION) {\n    Details auth_details(details);\n    if (auth_details->success()) {\n      AddLoginTimeMarker(\"Authenticate\", true);\n      RecordCurrentStats(kLoginSuccess);\n      registrar_.Remove(this, NotificationType::LOGIN_AUTHENTICATION,\n                        NotificationService::AllSources());\n    }\n  } else if (type == NotificationType::LOAD_START) {\n    \/\/ Only log for first tab to render.  Make sure this is only done once.\n    \/\/ If the network isn't connected we'll get a second LOAD_START once it is\n    \/\/ and the page is reloaded.\n    if (NetworkStateNotifier::Get()->is_connected()) {\n      \/\/ Post difference between first tab and login success time.\n      AddLoginTimeMarker(\"LoginDone\", true);\n      RecordCurrentStats(kChromeFirstRender);\n      \/\/ Post chrome first render stat.\n      registrar_.Remove(this, NotificationType::LOAD_START,\n                        NotificationService::AllSources());\n      \/\/ Don't swamp the FILE thread right away.\n      BrowserThread::PostDelayedTask(\n          BrowserThread::FILE, FROM_HERE,\n          NewRunnableFunction(WriteLoginTimes, login_time_markers_),\n          kLoginTimeWriteDelayMs);\n      have_registered_ = false;\n    } else {\n      AddLoginTimeMarker(\"LoginRenderNoNetwork\", false);\n    }\n  }\n}\n\n}  \/\/ namespace chromeos\n<|endoftext|>"}
{"text":"INTEGRATION: CWS ooo19126 (1.9.146); FILE MERGED 2005\/09\/05 15:03:07 rt 1.9.146.1: #i54170# Change license header: remove SISSL<|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\/tab_contents\/site_instance.h\"\n\n#include \"chrome\/browser\/renderer_host\/browser_render_process_host.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"net\/base\/registry_controlled_domain.h\"\n\nSiteInstance::SiteInstance(BrowsingInstance* browsing_instance)\n    : browsing_instance_(browsing_instance),\n      render_process_host_factory_(NULL),\n      process_(NULL),\n      max_page_id_(-1),\n      has_site_(false) {\n  DCHECK(browsing_instance);\n\n  NotificationService::current()->AddObserver(this,\n      NotificationType::RENDERER_PROCESS_TERMINATED,\n      NotificationService::AllSources());\n}\n\nSiteInstance::~SiteInstance() {\n  \/\/ Now that no one is referencing us, we can safely remove ourselves from\n  \/\/ the BrowsingInstance.  Any future visits to a page from this site\n  \/\/ (within the same BrowsingInstance) can safely create a new SiteInstance.\n  if (has_site_)\n    browsing_instance_->UnregisterSiteInstance(this);\n\n  NotificationService::current()->RemoveObserver(this,\n      NotificationType::RENDERER_PROCESS_TERMINATED,\n      NotificationService::AllSources());\n}\n\nRenderProcessHost* SiteInstance::GetProcess() {\n  \/\/ Create a new process if ours went away or was reused.\n  if (!process_) {\n    \/\/ See if we should reuse an old process\n    if (RenderProcessHost::ShouldTryToUseExistingProcessHost())\n      process_ = RenderProcessHost::GetExistingProcessHost(\n          browsing_instance_->profile());\n\n    \/\/ Otherwise (or if that fails), create a new one.\n    if (!process_) {\n      if (render_process_host_factory_) {\n        process_ = render_process_host_factory_->CreateRenderProcessHost(\n            browsing_instance_->profile());\n      } else {\n        process_ = new BrowserRenderProcessHost(browsing_instance_->profile());\n      }\n    }\n\n    \/\/ Make sure the process starts at the right max_page_id\n    process_->UpdateMaxPageID(max_page_id_);\n  }\n  DCHECK(process_);\n\n  return process_;\n}\n\nvoid SiteInstance::SetSite(const GURL& url) {\n  \/\/ A SiteInstance's site should not change.\n  \/\/ TODO(creis): When following links or script navigations, we can currently\n  \/\/ render pages from other sites in this SiteInstance.  This will eventually\n  \/\/ be fixed, but until then, we should still not set the site of a\n  \/\/ SiteInstance more than once.\n  DCHECK(!has_site_);\n\n  \/\/ Remember that this SiteInstance has been used to load a URL, even if the\n  \/\/ URL is invalid.\n  has_site_ = true;\n  site_ = GetSiteForURL(url);\n\n  \/\/ Now that we have a site, register it with the BrowsingInstance.  This\n  \/\/ ensures that we won't create another SiteInstance for this site within\n  \/\/ the same BrowsingInstance, because all same-site pages within a\n  \/\/ BrowsingInstance can script each other.\n  browsing_instance_->RegisterSiteInstance(this);\n}\n\nbool SiteInstance::HasRelatedSiteInstance(const GURL& url) {\n  return browsing_instance_->HasSiteInstance(url);\n}\n\nSiteInstance* SiteInstance::GetRelatedSiteInstance(const GURL& url) {\n  return browsing_instance_->GetSiteInstanceForURL(url);\n}\n\n\/*static*\/\nSiteInstance* SiteInstance::CreateSiteInstance(Profile* profile) {\n  return new SiteInstance(new BrowsingInstance(profile));\n}\n\n\/*static*\/\nSiteInstance* SiteInstance::CreateSiteInstanceForURL(Profile* profile,\n                                                     const GURL& url) {\n  return (new BrowsingInstance(profile))->GetSiteInstanceForURL(url);\n}\n\n\/*static*\/\nGURL SiteInstance::GetSiteForURL(const GURL& url) {\n  \/\/ URLs with no host should have an empty site.\n  GURL site;\n\n  \/\/ TODO(creis): For many protocols, we should just treat the scheme as the\n  \/\/ site, since there is no host.  e.g., file:, about:, chrome:\n\n  \/\/ If the url has a host, then determine the site.\n  if (url.has_host()) {\n    \/\/ Only keep the scheme and registered domain as given by GetOrigin.  This\n    \/\/ may also include a port, which we need to drop.\n    site = url.GetOrigin();\n\n    \/\/ Remove port, if any.\n    if (site.has_port()) {\n      GURL::Replacements rep;\n      rep.ClearPort();\n      site = site.ReplaceComponents(rep);\n    }\n\n    \/\/ If this URL has a registered domain, we only want to remember that part.\n    std::string domain =\n        net::RegistryControlledDomainService::GetDomainAndRegistry(url);\n    if (!domain.empty()) {\n      GURL::Replacements rep;\n      rep.SetHostStr(domain);\n      site = site.ReplaceComponents(rep);\n    }\n  }\n  return site;\n}\n\n\/*static*\/\nbool SiteInstance::IsSameWebSite(const GURL& url1, const GURL& url2) {\n  \/\/ We infer web site boundaries based on the registered domain name of the\n  \/\/ top-level page and the scheme.  We do not pay attention to the port if\n  \/\/ one is present, because pages served from different ports can still\n  \/\/ access each other if they change their document.domain variable.\n\n  \/\/ We must treat javascript: URLs as part of the same site, regardless of\n  \/\/ the site.\n  if (url1.SchemeIs(chrome::kJavaScriptScheme) ||\n      url2.SchemeIs(chrome::kJavaScriptScheme))\n    return true;\n\n  \/\/ We treat about:crash, about:hang, and about:shorthang as the same site as\n  \/\/ any URL, since they are used as demos for crashing\/hanging a process.\n  GURL about_crash = GURL(\"about:crash\");\n  GURL about_hang = GURL(\"about:hang\");\n  GURL about_shorthang = GURL(\"about:shorthang\");\n  if (url1 == about_crash || url2 == about_crash ||\n    url1 == about_hang || url2 == about_hang ||\n    url1 == about_shorthang || url2 == about_shorthang)\n    return true;\n\n  \/\/ If either URL is invalid, they aren't part of the same site.\n  if (!url1.is_valid() || !url2.is_valid()) {\n    return false;\n  }\n\n  \/\/ If the schemes differ, they aren't part of the same site.\n  if (url1.scheme() != url2.scheme()) {\n    return false;\n  }\n\n  return net::RegistryControlledDomainService::SameDomainOrHost(url1, url2);\n}\n\nvoid SiteInstance::Observe(NotificationType type,\n                           const NotificationSource& source,\n                           const NotificationDetails& details) {\n  DCHECK(type == NotificationType::RENDERER_PROCESS_TERMINATED);\n  RenderProcessHost* rph = Source(source).ptr();\n  if (rph == process_)\n    process_ = NULL;\n}\nFix memory leak in SiteInstance::CreateSiteInstanceForURL.\/\/ 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\/tab_contents\/site_instance.h\"\n\n#include \"chrome\/browser\/renderer_host\/browser_render_process_host.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"net\/base\/registry_controlled_domain.h\"\n\nSiteInstance::SiteInstance(BrowsingInstance* browsing_instance)\n    : browsing_instance_(browsing_instance),\n      render_process_host_factory_(NULL),\n      process_(NULL),\n      max_page_id_(-1),\n      has_site_(false) {\n  DCHECK(browsing_instance);\n\n  NotificationService::current()->AddObserver(this,\n      NotificationType::RENDERER_PROCESS_TERMINATED,\n      NotificationService::AllSources());\n}\n\nSiteInstance::~SiteInstance() {\n  \/\/ Now that no one is referencing us, we can safely remove ourselves from\n  \/\/ the BrowsingInstance.  Any future visits to a page from this site\n  \/\/ (within the same BrowsingInstance) can safely create a new SiteInstance.\n  if (has_site_)\n    browsing_instance_->UnregisterSiteInstance(this);\n\n  NotificationService::current()->RemoveObserver(this,\n      NotificationType::RENDERER_PROCESS_TERMINATED,\n      NotificationService::AllSources());\n}\n\nRenderProcessHost* SiteInstance::GetProcess() {\n  \/\/ Create a new process if ours went away or was reused.\n  if (!process_) {\n    \/\/ See if we should reuse an old process\n    if (RenderProcessHost::ShouldTryToUseExistingProcessHost())\n      process_ = RenderProcessHost::GetExistingProcessHost(\n          browsing_instance_->profile());\n\n    \/\/ Otherwise (or if that fails), create a new one.\n    if (!process_) {\n      if (render_process_host_factory_) {\n        process_ = render_process_host_factory_->CreateRenderProcessHost(\n            browsing_instance_->profile());\n      } else {\n        process_ = new BrowserRenderProcessHost(browsing_instance_->profile());\n      }\n    }\n\n    \/\/ Make sure the process starts at the right max_page_id\n    process_->UpdateMaxPageID(max_page_id_);\n  }\n  DCHECK(process_);\n\n  return process_;\n}\n\nvoid SiteInstance::SetSite(const GURL& url) {\n  \/\/ A SiteInstance's site should not change.\n  \/\/ TODO(creis): When following links or script navigations, we can currently\n  \/\/ render pages from other sites in this SiteInstance.  This will eventually\n  \/\/ be fixed, but until then, we should still not set the site of a\n  \/\/ SiteInstance more than once.\n  DCHECK(!has_site_);\n\n  \/\/ Remember that this SiteInstance has been used to load a URL, even if the\n  \/\/ URL is invalid.\n  has_site_ = true;\n  site_ = GetSiteForURL(url);\n\n  \/\/ Now that we have a site, register it with the BrowsingInstance.  This\n  \/\/ ensures that we won't create another SiteInstance for this site within\n  \/\/ the same BrowsingInstance, because all same-site pages within a\n  \/\/ BrowsingInstance can script each other.\n  browsing_instance_->RegisterSiteInstance(this);\n}\n\nbool SiteInstance::HasRelatedSiteInstance(const GURL& url) {\n  return browsing_instance_->HasSiteInstance(url);\n}\n\nSiteInstance* SiteInstance::GetRelatedSiteInstance(const GURL& url) {\n  return browsing_instance_->GetSiteInstanceForURL(url);\n}\n\n\/*static*\/\nSiteInstance* SiteInstance::CreateSiteInstance(Profile* profile) {\n  return new SiteInstance(new BrowsingInstance(profile));\n}\n\n\/*static*\/\nSiteInstance* SiteInstance::CreateSiteInstanceForURL(Profile* profile,\n                                                     const GURL& url) {\n  \/\/ This BrowsingInstance may be deleted if it returns an existing\n  \/\/ SiteInstance.\n  scoped_refptr instance(new BrowsingInstance(profile));\n  return instance->GetSiteInstanceForURL(url);\n}\n\n\/*static*\/\nGURL SiteInstance::GetSiteForURL(const GURL& url) {\n  \/\/ URLs with no host should have an empty site.\n  GURL site;\n\n  \/\/ TODO(creis): For many protocols, we should just treat the scheme as the\n  \/\/ site, since there is no host.  e.g., file:, about:, chrome:\n\n  \/\/ If the url has a host, then determine the site.\n  if (url.has_host()) {\n    \/\/ Only keep the scheme and registered domain as given by GetOrigin.  This\n    \/\/ may also include a port, which we need to drop.\n    site = url.GetOrigin();\n\n    \/\/ Remove port, if any.\n    if (site.has_port()) {\n      GURL::Replacements rep;\n      rep.ClearPort();\n      site = site.ReplaceComponents(rep);\n    }\n\n    \/\/ If this URL has a registered domain, we only want to remember that part.\n    std::string domain =\n        net::RegistryControlledDomainService::GetDomainAndRegistry(url);\n    if (!domain.empty()) {\n      GURL::Replacements rep;\n      rep.SetHostStr(domain);\n      site = site.ReplaceComponents(rep);\n    }\n  }\n  return site;\n}\n\n\/*static*\/\nbool SiteInstance::IsSameWebSite(const GURL& url1, const GURL& url2) {\n  \/\/ We infer web site boundaries based on the registered domain name of the\n  \/\/ top-level page and the scheme.  We do not pay attention to the port if\n  \/\/ one is present, because pages served from different ports can still\n  \/\/ access each other if they change their document.domain variable.\n\n  \/\/ We must treat javascript: URLs as part of the same site, regardless of\n  \/\/ the site.\n  if (url1.SchemeIs(chrome::kJavaScriptScheme) ||\n      url2.SchemeIs(chrome::kJavaScriptScheme))\n    return true;\n\n  \/\/ We treat about:crash, about:hang, and about:shorthang as the same site as\n  \/\/ any URL, since they are used as demos for crashing\/hanging a process.\n  GURL about_crash = GURL(\"about:crash\");\n  GURL about_hang = GURL(\"about:hang\");\n  GURL about_shorthang = GURL(\"about:shorthang\");\n  if (url1 == about_crash || url2 == about_crash ||\n    url1 == about_hang || url2 == about_hang ||\n    url1 == about_shorthang || url2 == about_shorthang)\n    return true;\n\n  \/\/ If either URL is invalid, they aren't part of the same site.\n  if (!url1.is_valid() || !url2.is_valid()) {\n    return false;\n  }\n\n  \/\/ If the schemes differ, they aren't part of the same site.\n  if (url1.scheme() != url2.scheme()) {\n    return false;\n  }\n\n  return net::RegistryControlledDomainService::SameDomainOrHost(url1, url2);\n}\n\nvoid SiteInstance::Observe(NotificationType type,\n                           const NotificationSource& source,\n                           const NotificationDetails& details) {\n  DCHECK(type == NotificationType::RENDERER_PROCESS_TERMINATED);\n  RenderProcessHost* rph = Source(source).ptr();\n  if (rph == process_)\n    process_ = NULL;\n}\n<|endoftext|>"}
{"text":"INTEGRATION: CWS qpro03 (1.1.2); FILE ADDED 2005\/10\/17 18:25:26 er 1.1.2.5: #i41688# identifier mismatch in initialization; remove superfluous array of String init 2005\/10\/14 15:11:09 mmeeks 1.1.2.4: Issue i#41688#<|endoftext|>"}
{"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ApplicationServer.h\"\n\n#include \"ApplicationFeatures\/ApplicationFeature.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"ProgramOptions\/ArgumentParser.h\"\n#include \"Logger\/Logger.h\"\n\nusing namespace arangodb::application_features;\nusing namespace arangodb::basics;\nusing namespace arangodb::options;\n\nApplicationServer* ApplicationServer::server = nullptr;\n\nApplicationServer::ApplicationServer(std::shared_ptr options)\n    : _options(options),\n      _stopping(false),\n      _privilegesDropped(false),\n      _dumpDependencies(false) {\n  if (ApplicationServer::server != nullptr) {\n    LOG(ERR) << \"ApplicationServer initialized twice\";\n  }\n\n  ApplicationServer::server = this;\n}\n\nApplicationServer::~ApplicationServer() {\n  for (auto& it : _features) {\n    delete it.second;\n  }\n\n  ApplicationServer::server = nullptr;\n}\n\nApplicationFeature* ApplicationServer::lookupFeature(std::string const& name) {\n  if (ApplicationServer::server == nullptr) {\n    return nullptr;\n  }\n\n  try {\n    return ApplicationServer::server->feature(name);\n  } catch (...) {\n  }\n\n  return nullptr;\n}\n\nvoid ApplicationServer::disableFeatures(std::vector const& names) {\n  for (auto name : names) {\n    auto feature = ApplicationServer::lookupFeature(name);\n\n    if (feature != nullptr) {\n      feature->disable();\n    }\n  }\n}\n\n\/\/ adds a feature to the application server. the application server\n\/\/ will take ownership of the feature object and destroy it in its\n\/\/ destructor\nvoid ApplicationServer::addFeature(ApplicationFeature* feature) {\n  _features.emplace(feature->name(), feature);\n}\n\n\/\/ checks for the existence of a named feature. will not throw when used for\n\/\/ a non-existing feature\nbool ApplicationServer::exists(std::string const& name) const {\n  return (_features.find(name) != _features.end());\n}\n\n\/\/ returns a pointer to a named feature. will throw when used for\n\/\/ a non-existing feature\nApplicationFeature* ApplicationServer::feature(std::string const& name) const {\n  auto it = _features.find(name);\n\n  if (it == _features.end()) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,\n                                   \"unknown feature '\" + name + \"'\");\n  }\n  return (*it).second;\n}\n\n\/\/ return whether or not a feature is enabled\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isEnabled(std::string const& name) const {\n  return feature(name)->isEnabled();\n}\n\n\/\/ return whether or not a feature is optional\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isOptional(std::string const& name) const {\n  return feature(name)->isOptional();\n}\n\n\/\/ return whether or not a feature is required\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isRequired(std::string const& name) const {\n  return feature(name)->isRequired();\n}\n\n\/\/ this method will initialize and validate options\n\/\/ of all feature, start them and wait for a shutdown\n\/\/ signal. after that, it will shutdown all features\nvoid ApplicationServer::run(int argc, char* argv[]) {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::run\";\n\n  \/\/ collect options from all features\n  \/\/ in this phase, all features are order-independent\n  collectOptions();\n\n  \/\/ setup dependency, but ignore any failure for now\n  setupDependencies(false);\n\n  \/\/ parse the command line parameters and load any configuration\n  \/\/ file(s)\n  parseOptions(argc, argv);\n\n  \/\/ seal the options\n  _options->seal();\n\n  \/\/ validate options of all features\n  validateOptions();\n\n  \/\/ enable automatic features\n  enableAutomaticFeatures();\n\n  \/\/ setup and validate all feature dependencies\n  setupDependencies(true);\n\n  \/\/ allows process control\n  daemonize();\n\n  \/\/ now the features will actually do some preparation work\n  \/\/ in the preparation phase, the features must not start any threads\n  \/\/ furthermore, they must not write any files under elevated privileges\n  \/\/ if they want other features to access them, or if they want to access\n  \/\/ these files with dropped privileges\n  prepare();\n\n  \/\/ permanently drop the privileges\n  dropPrivilegesPermanently();\n\n  \/\/ start features. now features are allowed to start threads, write files etc.\n  start();\n\n  \/\/ wait until we get signaled the shutdown request\n  wait();\n\n  \/\/ stop all features\n  stop();\n}\n\n\/\/ signal the server to shut down\nvoid ApplicationServer::beginShutdown() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::beginShutdown\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ fowards the begin shutdown signal to all features\n  for (auto it = _orderedFeatures.rbegin(); it != _orderedFeatures.rend();\n       ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->beginShutdown();\n    }\n  }\n\n  _stopping = true;\n  \/\/ TODO: use condition variable for signaling shutdown\n  \/\/ to run method\n}\n\nVPackBuilder ApplicationServer::options(\n    std::unordered_set const& excludes) const {\n  return _options->toVPack(false, excludes);\n}\n\n\/\/ fail and abort with the specified message\nvoid ApplicationServer::fail(std::string const& message) {\n  LOG(FATAL) << \"error. cannot proceed. reason: \" << message;\n  FATAL_ERROR_EXIT();\n}\n\n\/\/ walks over all features and runs a callback function for them\n\/\/ the order in which features are visited is unspecified\nvoid ApplicationServer::apply(std::function callback,\n                              bool enabledOnly) {\n  for (auto& it : _features) {\n    if (!enabledOnly || it.second->isEnabled()) {\n      callback(it.second);\n    }\n  }\n}\n\nvoid ApplicationServer::collectOptions() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::collectOptions\";\n\n  _options->addSection(\n      Section(\"\", \"Global configuration\", \"global options\", false, false));\n\n  _options->addHiddenOption(\"--dump-dependencies\", \"dump dependency graph\",\n                            new BooleanParameter(&_dumpDependencies, false));\n\n  apply([this](ApplicationFeature* feature) {\n    feature->collectOptions(_options);\n  }, true);\n}\n\nvoid ApplicationServer::parseOptions(int argc, char* argv[]) {\n  ArgumentParser parser(_options.get());\n\n  std::string helpSection = parser.helpSection(argc, argv);\n\n  if (!helpSection.empty()) {\n    \/\/ user asked for \"--help\"\n    _options->printHelp(helpSection);\n    exit(EXIT_SUCCESS);\n  }\n\n  if (!parser.parse(argc, argv)) {\n    \/\/ command-line option parsing failed. an error was already printed\n    \/\/ by now, so we can exit\n    exit(EXIT_FAILURE);\n  }\n\n  if (_dumpDependencies) {\n    std::cout << \"digraph dependencies\\n\"\n              << \"{\\n\"\n              << \"  overlap = false;\\n\";\n    for (auto feature : _features) {\n      for (auto before : feature.second->startsAfter()) {\n        std::cout << \"  \" << feature.first << \" -> \" << before << \";\\n\";\n      }\n    }\n    std::cout << \"}\\n\";\n    exit(EXIT_SUCCESS);\n  }\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->loadOptions(_options);\n    }\n  }\n}\n\nvoid ApplicationServer::validateOptions() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::validateOptions\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->validateOptions(_options);\n    }\n  }\n}\n\nvoid ApplicationServer::enableAutomaticFeatures() {\n  bool changed;\n  do {\n    changed = false;\n    for (auto& it : _features) {\n      auto other = it.second->enableWith();\n      if (other.empty()) {\n        continue;\n      }\n      if (!this->exists(other)) {\n        fail(\"feature '\" + it.second->name() +\n             \"' depends on unknown feature '\" + other + \"'\");\n      }\n      bool otherIsEnabled = this->feature(other)->isEnabled();\n      if (otherIsEnabled != it.second->isEnabled()) {\n        it.second->setEnabled(otherIsEnabled);\n        changed = true;\n      }\n    }\n  } while (changed);\n}\n\n\/\/ setup and validate all feature dependencies, determine feature order\nvoid ApplicationServer::setupDependencies(bool failOnMissing) {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"ApplicationServer::validateDependencies\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ first check if a feature references an unknown other feature\n  if (failOnMissing) {\n    apply([this](ApplicationFeature* feature) {\n      for (auto& other : feature->requires()) {\n        if (!this->exists(other)) {\n          fail(\"feature '\" + feature->name() +\n               \"' depends on unknown feature '\" + other + \"'\");\n        }\n        if (!this->feature(other)->isEnabled()) {\n          fail(\"enabled feature '\" + feature->name() +\n               \"' depends on other feature '\" + other + \"', which is disabled\");\n        }\n      }\n    }, true);\n  }\n\n  \/\/ first insert all features, even the inactive ones\n  std::vector features;\n  for (auto& it : _features) {\n    auto insertPosition = features.end();\n\n    if (!features.empty()) {\n      for (size_t i = features.size(); i > 0; --i) {\n        if (it.second->doesStartBefore(features[i - 1]->name())) {\n          insertPosition = features.begin() + (i - 1);\n        }\n      }\n    }\n    features.insert(insertPosition, it.second);\n  }\n\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ordered features:\";\n\n  for (auto feature : features) {\n    LOG_TOPIC(TRACE, Logger::STARTUP)\n        << \"  \" << feature->name()\n        << (feature->isEnabled() ? \"\" : \"(disabled)\");\n\n    auto startsAfter = feature->startsAfter();\n\n    if (!startsAfter.empty()) {\n      LOG_TOPIC(TRACE, Logger::STARTUP)\n          << \"    \" << StringUtils::join(feature->startsAfter(), \", \");\n    }\n  }\n\n  \/\/ remove all inactive features\n  for (auto it = features.begin(); it != features.end(); \/* no hoisting *\/) {\n    if ((*it)->isEnabled()) {\n      \/\/ keep feature\n      ++it;\n    } else {\n      \/\/ remove feature\n      it = features.erase(it);\n    }\n  }\n\n  _orderedFeatures = features;\n}\n\nvoid ApplicationServer::daemonize() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::daemonize\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->daemonize();\n    }\n  }\n}\n\nvoid ApplicationServer::prepare() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::prepare\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ we start with elevated privileges\n  bool privilegesElevated = true;\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      bool const requiresElevated = (*it)->requiresElevatedPrivileges();\n\n      if (requiresElevated != privilegesElevated) {\n        \/\/ must change privileges for the feature\n        if (requiresElevated) {\n          raisePrivilegesTemporarily();\n          privilegesElevated = true;\n        } else {\n          dropPrivilegesTemporarily();\n          privilegesElevated = false;\n        }\n      }\n\n      try {\n        (*it)->prepare();\n      } catch (...) {\n        \/\/ restore original privileges\n        if (!privilegesElevated) {\n          raisePrivilegesTemporarily();\n        }\n        throw;\n      }\n    }\n  }\n}\n\nvoid ApplicationServer::start() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::start\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    (*it)->start();\n  }\n}\n\nvoid ApplicationServer::stop() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::stop\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.rbegin(); it != _orderedFeatures.rend();\n       ++it) {\n    (*it)->stop();\n  }\n}\n\nvoid ApplicationServer::wait() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::wait\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  while (!_stopping) {\n    \/\/ TODO: use condition variable for waiting for shutdown\n    ::usleep(100000);\n  }\n}\n\n\/\/ temporarily raise privileges\nvoid ApplicationServer::raisePrivilegesTemporarily() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL, \"must not raise privileges after dropping them\");\n  }\n\n  \/\/ TODO\n}\n\n\/\/ temporarily drop privileges\nvoid ApplicationServer::dropPrivilegesTemporarily() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL,\n        \"must not try to drop privileges after dropping them\");\n  }\n\n  \/\/ TODO\n}\n\n\/\/ permanently dropped privileges\nvoid ApplicationServer::dropPrivilegesPermanently() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL,\n        \"must not try to drop privileges after dropping them\");\n  }\n  _privilegesDropped = true;\n\n  \/\/ TODO\n}\nre-added \"--help-all\"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ApplicationServer.h\"\n\n#include \"ApplicationFeatures\/ApplicationFeature.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"ProgramOptions\/ArgumentParser.h\"\n#include \"Logger\/Logger.h\"\n\nusing namespace arangodb::application_features;\nusing namespace arangodb::basics;\nusing namespace arangodb::options;\n\nApplicationServer* ApplicationServer::server = nullptr;\n\nApplicationServer::ApplicationServer(std::shared_ptr options)\n    : _options(options),\n      _stopping(false),\n      _privilegesDropped(false),\n      _dumpDependencies(false) {\n  if (ApplicationServer::server != nullptr) {\n    LOG(ERR) << \"ApplicationServer initialized twice\";\n  }\n\n  ApplicationServer::server = this;\n}\n\nApplicationServer::~ApplicationServer() {\n  for (auto& it : _features) {\n    delete it.second;\n  }\n\n  ApplicationServer::server = nullptr;\n}\n\nApplicationFeature* ApplicationServer::lookupFeature(std::string const& name) {\n  if (ApplicationServer::server == nullptr) {\n    return nullptr;\n  }\n\n  try {\n    return ApplicationServer::server->feature(name);\n  } catch (...) {\n  }\n\n  return nullptr;\n}\n\nvoid ApplicationServer::disableFeatures(std::vector const& names) {\n  for (auto name : names) {\n    auto feature = ApplicationServer::lookupFeature(name);\n\n    if (feature != nullptr) {\n      feature->disable();\n    }\n  }\n}\n\n\/\/ adds a feature to the application server. the application server\n\/\/ will take ownership of the feature object and destroy it in its\n\/\/ destructor\nvoid ApplicationServer::addFeature(ApplicationFeature* feature) {\n  _features.emplace(feature->name(), feature);\n}\n\n\/\/ checks for the existence of a named feature. will not throw when used for\n\/\/ a non-existing feature\nbool ApplicationServer::exists(std::string const& name) const {\n  return (_features.find(name) != _features.end());\n}\n\n\/\/ returns a pointer to a named feature. will throw when used for\n\/\/ a non-existing feature\nApplicationFeature* ApplicationServer::feature(std::string const& name) const {\n  auto it = _features.find(name);\n\n  if (it == _features.end()) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,\n                                   \"unknown feature '\" + name + \"'\");\n  }\n  return (*it).second;\n}\n\n\/\/ return whether or not a feature is enabled\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isEnabled(std::string const& name) const {\n  return feature(name)->isEnabled();\n}\n\n\/\/ return whether or not a feature is optional\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isOptional(std::string const& name) const {\n  return feature(name)->isOptional();\n}\n\n\/\/ return whether or not a feature is required\n\/\/ will throw when called for a non-existing feature\nbool ApplicationServer::isRequired(std::string const& name) const {\n  return feature(name)->isRequired();\n}\n\n\/\/ this method will initialize and validate options\n\/\/ of all feature, start them and wait for a shutdown\n\/\/ signal. after that, it will shutdown all features\nvoid ApplicationServer::run(int argc, char* argv[]) {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::run\";\n\n  \/\/ collect options from all features\n  \/\/ in this phase, all features are order-independent\n  collectOptions();\n\n  \/\/ setup dependency, but ignore any failure for now\n  setupDependencies(false);\n\n  \/\/ parse the command line parameters and load any configuration\n  \/\/ file(s)\n  parseOptions(argc, argv);\n\n  \/\/ seal the options\n  _options->seal();\n\n  \/\/ validate options of all features\n  validateOptions();\n\n  \/\/ enable automatic features\n  enableAutomaticFeatures();\n\n  \/\/ setup and validate all feature dependencies\n  setupDependencies(true);\n\n  \/\/ allows process control\n  daemonize();\n\n  \/\/ now the features will actually do some preparation work\n  \/\/ in the preparation phase, the features must not start any threads\n  \/\/ furthermore, they must not write any files under elevated privileges\n  \/\/ if they want other features to access them, or if they want to access\n  \/\/ these files with dropped privileges\n  prepare();\n\n  \/\/ permanently drop the privileges\n  dropPrivilegesPermanently();\n\n  \/\/ start features. now features are allowed to start threads, write files etc.\n  start();\n\n  \/\/ wait until we get signaled the shutdown request\n  wait();\n\n  \/\/ stop all features\n  stop();\n}\n\n\/\/ signal the server to shut down\nvoid ApplicationServer::beginShutdown() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::beginShutdown\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ fowards the begin shutdown signal to all features\n  for (auto it = _orderedFeatures.rbegin(); it != _orderedFeatures.rend();\n       ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->beginShutdown();\n    }\n  }\n\n  _stopping = true;\n  \/\/ TODO: use condition variable for signaling shutdown\n  \/\/ to run method\n}\n\nVPackBuilder ApplicationServer::options(\n    std::unordered_set const& excludes) const {\n  return _options->toVPack(false, excludes);\n}\n\n\/\/ fail and abort with the specified message\nvoid ApplicationServer::fail(std::string const& message) {\n  LOG(FATAL) << \"error. cannot proceed. reason: \" << message;\n  FATAL_ERROR_EXIT();\n}\n\n\/\/ walks over all features and runs a callback function for them\n\/\/ the order in which features are visited is unspecified\nvoid ApplicationServer::apply(std::function callback,\n                              bool enabledOnly) {\n  for (auto& it : _features) {\n    if (!enabledOnly || it.second->isEnabled()) {\n      callback(it.second);\n    }\n  }\n}\n\nvoid ApplicationServer::collectOptions() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::collectOptions\";\n\n  _options->addSection(\n      Section(\"\", \"Global configuration\", \"global options\", false, false));\n\n  _options->addHiddenOption(\"--dump-dependencies\", \"dump dependency graph\",\n                            new BooleanParameter(&_dumpDependencies, false));\n\n  apply([this](ApplicationFeature* feature) {\n    feature->collectOptions(_options);\n  }, true);\n}\n\nvoid ApplicationServer::parseOptions(int argc, char* argv[]) {\n  ArgumentParser parser(_options.get());\n\n  std::string helpSection = parser.helpSection(argc, argv);\n\n  if (!helpSection.empty()) {\n    \/\/ user asked for \"--help\"\n\n    \/\/ translate \"all\" to \"*\"\n    if (helpSection == \"all\") {\n      helpSection = \"*\";\n    }\n    _options->printHelp(helpSection);\n    exit(EXIT_SUCCESS);\n  }\n\n  if (!parser.parse(argc, argv)) {\n    \/\/ command-line option parsing failed. an error was already printed\n    \/\/ by now, so we can exit\n    exit(EXIT_FAILURE);\n  }\n\n  if (_dumpDependencies) {\n    std::cout << \"digraph dependencies\\n\"\n              << \"{\\n\"\n              << \"  overlap = false;\\n\";\n    for (auto feature : _features) {\n      for (auto before : feature.second->startsAfter()) {\n        std::cout << \"  \" << feature.first << \" -> \" << before << \";\\n\";\n      }\n    }\n    std::cout << \"}\\n\";\n    exit(EXIT_SUCCESS);\n  }\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->loadOptions(_options);\n    }\n  }\n}\n\nvoid ApplicationServer::validateOptions() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::validateOptions\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->validateOptions(_options);\n    }\n  }\n}\n\nvoid ApplicationServer::enableAutomaticFeatures() {\n  bool changed;\n  do {\n    changed = false;\n    for (auto& it : _features) {\n      auto other = it.second->enableWith();\n      if (other.empty()) {\n        continue;\n      }\n      if (!this->exists(other)) {\n        fail(\"feature '\" + it.second->name() +\n             \"' depends on unknown feature '\" + other + \"'\");\n      }\n      bool otherIsEnabled = this->feature(other)->isEnabled();\n      if (otherIsEnabled != it.second->isEnabled()) {\n        it.second->setEnabled(otherIsEnabled);\n        changed = true;\n      }\n    }\n  } while (changed);\n}\n\n\/\/ setup and validate all feature dependencies, determine feature order\nvoid ApplicationServer::setupDependencies(bool failOnMissing) {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"ApplicationServer::validateDependencies\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ first check if a feature references an unknown other feature\n  if (failOnMissing) {\n    apply([this](ApplicationFeature* feature) {\n      for (auto& other : feature->requires()) {\n        if (!this->exists(other)) {\n          fail(\"feature '\" + feature->name() +\n               \"' depends on unknown feature '\" + other + \"'\");\n        }\n        if (!this->feature(other)->isEnabled()) {\n          fail(\"enabled feature '\" + feature->name() +\n               \"' depends on other feature '\" + other + \"', which is disabled\");\n        }\n      }\n    }, true);\n  }\n\n  \/\/ first insert all features, even the inactive ones\n  std::vector features;\n  for (auto& it : _features) {\n    auto insertPosition = features.end();\n\n    if (!features.empty()) {\n      for (size_t i = features.size(); i > 0; --i) {\n        if (it.second->doesStartBefore(features[i - 1]->name())) {\n          insertPosition = features.begin() + (i - 1);\n        }\n      }\n    }\n    features.insert(insertPosition, it.second);\n  }\n\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ordered features:\";\n\n  for (auto feature : features) {\n    LOG_TOPIC(TRACE, Logger::STARTUP)\n        << \"  \" << feature->name()\n        << (feature->isEnabled() ? \"\" : \"(disabled)\");\n\n    auto startsAfter = feature->startsAfter();\n\n    if (!startsAfter.empty()) {\n      LOG_TOPIC(TRACE, Logger::STARTUP)\n          << \"    \" << StringUtils::join(feature->startsAfter(), \", \");\n    }\n  }\n\n  \/\/ remove all inactive features\n  for (auto it = features.begin(); it != features.end(); \/* no hoisting *\/) {\n    if ((*it)->isEnabled()) {\n      \/\/ keep feature\n      ++it;\n    } else {\n      \/\/ remove feature\n      it = features.erase(it);\n    }\n  }\n\n  _orderedFeatures = features;\n}\n\nvoid ApplicationServer::daemonize() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::daemonize\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      (*it)->daemonize();\n    }\n  }\n}\n\nvoid ApplicationServer::prepare() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::prepare\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  \/\/ we start with elevated privileges\n  bool privilegesElevated = true;\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    if ((*it)->isEnabled()) {\n      bool const requiresElevated = (*it)->requiresElevatedPrivileges();\n\n      if (requiresElevated != privilegesElevated) {\n        \/\/ must change privileges for the feature\n        if (requiresElevated) {\n          raisePrivilegesTemporarily();\n          privilegesElevated = true;\n        } else {\n          dropPrivilegesTemporarily();\n          privilegesElevated = false;\n        }\n      }\n\n      try {\n        (*it)->prepare();\n      } catch (...) {\n        \/\/ restore original privileges\n        if (!privilegesElevated) {\n          raisePrivilegesTemporarily();\n        }\n        throw;\n      }\n    }\n  }\n}\n\nvoid ApplicationServer::start() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::start\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.begin(); it != _orderedFeatures.end(); ++it) {\n    (*it)->start();\n  }\n}\n\nvoid ApplicationServer::stop() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::stop\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  for (auto it = _orderedFeatures.rbegin(); it != _orderedFeatures.rend();\n       ++it) {\n    (*it)->stop();\n  }\n}\n\nvoid ApplicationServer::wait() {\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"\";\n  LOG_TOPIC(TRACE, Logger::STARTUP) << \"ApplicationServer::wait\";\n  LOG_TOPIC(TRACE, Logger::STARTUP)\n      << \"------------------------------------------------\";\n\n  while (!_stopping) {\n    \/\/ TODO: use condition variable for waiting for shutdown\n    ::usleep(100000);\n  }\n}\n\n\/\/ temporarily raise privileges\nvoid ApplicationServer::raisePrivilegesTemporarily() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL, \"must not raise privileges after dropping them\");\n  }\n\n  \/\/ TODO\n}\n\n\/\/ temporarily drop privileges\nvoid ApplicationServer::dropPrivilegesTemporarily() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL,\n        \"must not try to drop privileges after dropping them\");\n  }\n\n  \/\/ TODO\n}\n\n\/\/ permanently dropped privileges\nvoid ApplicationServer::dropPrivilegesPermanently() {\n  if (_privilegesDropped) {\n    THROW_ARANGO_EXCEPTION_MESSAGE(\n        TRI_ERROR_INTERNAL,\n        \"must not try to drop privileges after dropping them\");\n  }\n  _privilegesDropped = true;\n\n  \/\/ TODO\n}\n<|endoftext|>"}
{"text":"#include \"stdafx.h\"\r\n#include \"Player.h\"\r\n#include \"Math.h\"\r\n#include \"PlayerManager.h\"\r\n\r\n\r\nPlayer::Player(void):mPosition(0,0),mPlayerState(PLAYER_STATE_IDLE)\r\n{\r\n}\r\n\r\nPlayer::Player(int id, ClientSession* client):mHP(100),mDamage(5),mPlayerState(PLAYER_STATE_IDLE),mMovedInfo(0),mAttackRange(12),mRadius(24)\r\n{\r\n\r\n\tmPlayerId = id;\r\n\tmClient = client;\r\n\r\n\twhile(1)\r\n\t{\r\n\t\tfloat x = rand() % (GGameMap->GetWidth() * 64);\r\n\t\tfloat y = rand() % (GGameMap->GetHeight() * 64);\r\n\t\tbool isOk = true;\r\n\t\tfor(float _x = x - mRadius; _x <= x + mRadius; _x += mRadius)\r\n\t\t{\r\n\t\t\tfor(float _y = y - mRadius; _y <= y + mRadius; _y += mRadius)\r\n\t\t\t{\r\n\t\t\t\tif(GGameMap->isValidTile(Point(x,y)) != true)\r\n\t\t\t\t{\r\n\t\t\t\t\tisOk = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(isOk == false)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tif(isOk == true)\r\n\t\t{\r\n\t\t\tmPosition = Point(x,y);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nPlayer::~Player(void)\r\n{\r\n}\r\n\r\nvoid Player::TransState(short state)\r\n{\r\n\tswitch (state)\r\n\t{\r\n\tcase PLAYER_STATE_IDLE:\r\n\t\t{\r\n\t\t\tmPlayerState = state;\r\n\r\n\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\tmClient->Broadcast(&outPacket);\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_WALK:\r\n\t\t{\r\n\t\t\tPoint willGoPosition = GetPosition();\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( -1.f, 0.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( +1.f, 0.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, -1.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, 1.f ) * mDTime * 100.f;\r\n\r\n\t\t\tif ( GGameMap->isValidTile(willGoPosition) == false )\r\n\t\t\t{\r\n\t\t\t\t\/\/ϱ walk ȯ .\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\t\t\t\tmMovedInfo = -1;\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_ATTACK:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_DIE:\r\n\t\t{\r\n\t\t\tmResponTime = 5.f;\r\n\t\t\tmPlayerState = state;\r\n\r\n\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_TYPESKILL:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\tcase PLAYER_STATE_USERSKILL:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\n\r\nvoid Player::Update( float dTime)\r\n{\r\n\tprintf(\"%f\\n\",dTime);\r\n\tmDTime = dTime;\r\n\tswitch (mPlayerState)\r\n\t{\r\n\tcase PLAYER_STATE_IDLE:\r\n\t\t{\r\n\t\t\tif( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.userActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_USERSKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.attackKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_ATTACK);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse if ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.upDirectKey == KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_WALK);\r\n\t\t\t}else if ( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_WALK:\r\n\t\t{\r\n\t\t\tif( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.userActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_USERSKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.attackKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_ATTACK);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\/\/Move myPlayer with Game Key States.\r\n\t\t\t\/\/Check Moving Input, and set Position to d\r\n\r\n\r\n\t\t\t\/\/ ٲ üũ\r\n\t\t\tint moveInfo = 0;\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED ) moveInfo |= 4;\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED ) moveInfo |= 2;\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED\t)\tmoveInfo |= 1;\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\tmoveInfo |= 8;\r\n\r\n\t\t\t\/\/  ϴ  map ̵  ̴?\r\n\t\t\tPoint willGoPosition = GetPosition();\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( -1.f, 0.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( +1.f, 0.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, -1.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, 1.f ) * (mRadius + dTime * 100.f);\r\n\t\t\t\r\n\t\t\t\/\/wasd    Ȯ\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.rightDirectKey == KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.upDirectKey == KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.downDirectKey == KEYSTATE_NOTPRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif ( GGameMap->isValidTile(willGoPosition) == false )\r\n\t\t\t{\r\n\t\t\t\t\/\/ϱ Idle· .\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\/\/׸   ʴ , Ʒ SetPosition ̵ϰ ͸  Ǹ Ŭ 忡  ó ...\r\n\t\t\tSetPosition(willGoPosition);\r\n\r\n\r\n\r\n\t\t\t\/\/ ٸ  ̵ߴ?\r\n\t\t\tif( mMovedInfo != -1 && moveInfo != mMovedInfo)\r\n\t\t\t{\r\n\t\t\t\t\/\/ٲ key .\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\r\n\t\t\tmMovedInfo = moveInfo;\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_ATTACK:\r\n\t\t{\r\n\t\t\tPoint AttackPoint = mPosition + Point(cos(mRotation) * mAttackRange,sin(mRotation) * mAttackRange);\r\n\t\t\tstd::map players = GPlayerManager->GetPlayers();\r\n\t\t\tfor( std::map::iterator it = players.begin(); it != players.end(); ++it ) \r\n\t\t\t{\r\n\t\t\t\tPlayer* enemy = it->second;\r\n\t\t\t\tif(enemy == this)continue;\r\n\r\n\t\t\t\tif( Point().GetDistance( enemy->GetPosition(), AttackPoint ) < mAttackRange )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ǰݵ\r\n\t\t\t\t\tenemy->Damaged(mHP);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tcase PLAYER_STATE_DIE:\r\n\t\t{\r\n\t\t\tmResponTime -= dTime;\r\n\t\t\tif(mResponTime < 0)\r\n\t\t\t{\r\n\t\t\t\t\/\/մϴ.\r\n\t\t\t\twhile(1)\r\n\t\t\t\t{\r\n\t\t\t\t\tfloat x = rand() % (GGameMap->GetWidth() * 64);\r\n\t\t\t\t\tfloat y = rand() % (GGameMap->GetHeight() * 64);\r\n\t\t\t\t\tif(GGameMap->isValidTile(Point(x,y)) == true)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmPosition = Point(x,y);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tSetHP(100);\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_TYPESKILL:\r\n\t\t{\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_USERSKILL:\r\n\t\t{\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\nvoid Player::Damaged(int damage)\r\n{\r\n\tif(mHP < damage)\r\n\t{\r\n\t\t\/\/׾\r\n\t\tTransState(PLAYER_STATE_DIE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tmHP-=damage;\r\n\t\t\/\/  󸶶 εij\r\n\t\tHPUpdateResult outPacket = HPUpdateResult();\r\n\t\toutPacket.mPlayerId = mPlayerId;\r\n\t\toutPacket.mHP = mHP;\r\n\t\tmClient->Broadcast(&outPacket);\r\n\t}\r\n\r\n}\r\nPlayerInfo Player::GetPlayerInfo()\r\n{\r\n\tPlayerInfo mPlayerInfo;\r\n\tmPlayerInfo.mGameKeyStates = mGameKeyStates;\r\n\tmPlayerInfo.mX = mPosition.x;\r\n\tmPlayerInfo.mY = mPosition.y;\r\n\tmPlayerInfo.mPlayerId = mPlayerId;\r\n\tmPlayerInfo.mAngle = mRotation;\r\n\tmPlayerInfo.mPlayerState = mPlayerState;\r\n\tmPlayerInfo.mHP = mHP;\r\n\treturn mPlayerInfo;\r\n}업데이트 로그 제거 #include \"stdafx.h\"\r\n#include \"Player.h\"\r\n#include \"Math.h\"\r\n#include \"PlayerManager.h\"\r\n\r\n\r\nPlayer::Player(void):mPosition(0,0),mPlayerState(PLAYER_STATE_IDLE)\r\n{\r\n}\r\n\r\nPlayer::Player(int id, ClientSession* client):mHP(100),mDamage(5),mPlayerState(PLAYER_STATE_IDLE),mMovedInfo(0),mAttackRange(12),mRadius(24)\r\n{\r\n\r\n\tmPlayerId = id;\r\n\tmClient = client;\r\n\r\n\twhile(1)\r\n\t{\r\n\t\tfloat x = rand() % (GGameMap->GetWidth() * 64);\r\n\t\tfloat y = rand() % (GGameMap->GetHeight() * 64);\r\n\t\tbool isOk = true;\r\n\t\tfor(float _x = x - mRadius; _x <= x + mRadius; _x += mRadius)\r\n\t\t{\r\n\t\t\tfor(float _y = y - mRadius; _y <= y + mRadius; _y += mRadius)\r\n\t\t\t{\r\n\t\t\t\tif(GGameMap->isValidTile(Point(x,y)) != true)\r\n\t\t\t\t{\r\n\t\t\t\t\tisOk = false;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(isOk == false)\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\tif(isOk == true)\r\n\t\t{\r\n\t\t\tmPosition = Point(x,y);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nPlayer::~Player(void)\r\n{\r\n}\r\n\r\nvoid Player::TransState(short state)\r\n{\r\n\tswitch (state)\r\n\t{\r\n\tcase PLAYER_STATE_IDLE:\r\n\t\t{\r\n\t\t\tmPlayerState = state;\r\n\r\n\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\tmClient->Broadcast(&outPacket);\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_WALK:\r\n\t\t{\r\n\t\t\tPoint willGoPosition = GetPosition();\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( -1.f, 0.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( +1.f, 0.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, -1.f ) * mDTime * 100.f;\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, 1.f ) * mDTime * 100.f;\r\n\r\n\t\t\tif ( GGameMap->isValidTile(willGoPosition) == false )\r\n\t\t\t{\r\n\t\t\t\t\/\/ϱ walk ȯ .\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\t\t\t\tmMovedInfo = -1;\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_ATTACK:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_DIE:\r\n\t\t{\r\n\t\t\tmResponTime = 5.f;\r\n\t\t\tmPlayerState = state;\r\n\r\n\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_TYPESKILL:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\tcase PLAYER_STATE_USERSKILL:\r\n\t\t{\r\n\t\t\tif(mPlayerState == PLAYER_STATE_IDLE ||\r\n\t\t\t\tmPlayerState == PLAYER_STATE_WALK)\r\n\t\t\t{\t\r\n\t\t\t\tmPlayerState = state;\r\n\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\n\r\nvoid Player::Update( float dTime)\r\n{\r\n\tmDTime = dTime;\r\n\tswitch (mPlayerState)\r\n\t{\r\n\tcase PLAYER_STATE_IDLE:\r\n\t\t{\r\n\t\t\tif( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.userActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_USERSKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.attackKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_ATTACK);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\telse if ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.upDirectKey == KEYSTATE_PRESSED \r\n\t\t\t\t|| mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_WALK);\r\n\t\t\t}else if ( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_WALK:\r\n\t\t{\r\n\t\t\tif( mGameKeyStates.typeActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_TYPESKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.userActiveSkillKey == KEYSTATE_PRESSED)\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_USERSKILL);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif( mGameKeyStates.attackKey == KEYSTATE_PRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_ATTACK);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\/\/Move myPlayer with Game Key States.\r\n\t\t\t\/\/Check Moving Input, and set Position to d\r\n\r\n\r\n\t\t\t\/\/ ٲ üũ\r\n\t\t\tint moveInfo = 0;\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED ) moveInfo |= 4;\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED ) moveInfo |= 2;\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED\t)\tmoveInfo |= 1;\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\tmoveInfo |= 8;\r\n\r\n\t\t\t\/\/  ϴ  map ̵  ̴?\r\n\t\t\tPoint willGoPosition = GetPosition();\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( -1.f, 0.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.rightDirectKey == KEYSTATE_PRESSED )willGoPosition = willGoPosition + Point( +1.f, 0.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.upDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, -1.f ) * (mRadius + dTime * 100.f);\r\n\t\t\tif ( mGameKeyStates.downDirectKey == KEYSTATE_PRESSED )\twillGoPosition = willGoPosition + Point( 0.f, 1.f ) * (mRadius + dTime * 100.f);\r\n\t\t\t\r\n\t\t\t\/\/wasd    Ȯ\r\n\t\t\tif ( mGameKeyStates.leftDirectKey ==  KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.rightDirectKey == KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.upDirectKey == KEYSTATE_NOTPRESSED \r\n\t\t\t\t&& mGameKeyStates.downDirectKey == KEYSTATE_NOTPRESSED )\r\n\t\t\t{\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif ( GGameMap->isValidTile(willGoPosition) == false )\r\n\t\t\t{\r\n\t\t\t\t\/\/ϱ Idle· .\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\/\/׸   ʴ , Ʒ SetPosition ̵ϰ ͸  Ǹ Ŭ 忡  ó ...\r\n\t\t\tSetPosition(willGoPosition);\r\n\r\n\r\n\r\n\t\t\t\/\/ ٸ  ̵ߴ?\r\n\t\t\tif( mMovedInfo != -1 && moveInfo != mMovedInfo)\r\n\t\t\t{\r\n\t\t\t\t\/\/ٲ key .\r\n\t\t\t\tGameKeyStatesUpdateResult outPacket = GameKeyStatesUpdateResult();\r\n\t\t\t\toutPacket.mMyPlayerInfo = this->GetPlayerInfo();\r\n\t\t\t\tmClient->Broadcast(&outPacket);\r\n\t\t\t}\r\n\r\n\t\t\tmMovedInfo = moveInfo;\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_ATTACK:\r\n\t\t{\r\n\t\t\tPoint AttackPoint = mPosition + Point(cos(mRotation) * mAttackRange,sin(mRotation) * mAttackRange);\r\n\t\t\tstd::map players = GPlayerManager->GetPlayers();\r\n\t\t\tfor( std::map::iterator it = players.begin(); it != players.end(); ++it ) \r\n\t\t\t{\r\n\t\t\t\tPlayer* enemy = it->second;\r\n\t\t\t\tif(enemy == this)continue;\r\n\r\n\t\t\t\tif( Point().GetDistance( enemy->GetPosition(), AttackPoint ) < mAttackRange )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ǰݵ\r\n\t\t\t\t\tenemy->Damaged(mHP);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tcase PLAYER_STATE_DIE:\r\n\t\t{\r\n\t\t\tmResponTime -= dTime;\r\n\t\t\tif(mResponTime < 0)\r\n\t\t\t{\r\n\t\t\t\t\/\/մϴ.\r\n\t\t\t\twhile(1)\r\n\t\t\t\t{\r\n\t\t\t\t\tfloat x = rand() % (GGameMap->GetWidth() * 64);\r\n\t\t\t\t\tfloat y = rand() % (GGameMap->GetHeight() * 64);\r\n\t\t\t\t\tif(GGameMap->isValidTile(Point(x,y)) == true)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmPosition = Point(x,y);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tSetHP(100);\r\n\t\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_TYPESKILL:\r\n\t\t{\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase PLAYER_STATE_USERSKILL:\r\n\t\t{\r\n\t\t\tTransState(PLAYER_STATE_IDLE);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\nvoid Player::Damaged(int damage)\r\n{\r\n\tif(mHP < damage)\r\n\t{\r\n\t\t\/\/׾\r\n\t\tTransState(PLAYER_STATE_DIE);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tmHP-=damage;\r\n\t\t\/\/  󸶶 εij\r\n\t\tHPUpdateResult outPacket = HPUpdateResult();\r\n\t\toutPacket.mPlayerId = mPlayerId;\r\n\t\toutPacket.mHP = mHP;\r\n\t\tmClient->Broadcast(&outPacket);\r\n\t}\r\n\r\n}\r\nPlayerInfo Player::GetPlayerInfo()\r\n{\r\n\tPlayerInfo mPlayerInfo;\r\n\tmPlayerInfo.mGameKeyStates = mGameKeyStates;\r\n\tmPlayerInfo.mX = mPosition.x;\r\n\tmPlayerInfo.mY = mPosition.y;\r\n\tmPlayerInfo.mPlayerId = mPlayerId;\r\n\tmPlayerInfo.mAngle = mRotation;\r\n\tmPlayerInfo.mPlayerState = mPlayerState;\r\n\tmPlayerInfo.mHP = mHP;\r\n\treturn mPlayerInfo;\r\n}<|endoftext|>"}
{"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\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\/\/ Interface header.\n#include \"genericsamplegenerator.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/rendering\/isamplerenderer.h\"\n#include \"renderer\/kernel\/rendering\/localaccumulationframebuffer.h\"\n#include \"renderer\/kernel\/rendering\/sample.h\"\n#include \"renderer\/kernel\/rendering\/samplegeneratorbase.h\"\n#include \"renderer\/kernel\/shading\/shadingresult.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/math\/population.h\"\n#include \"foundation\/math\/qmc.h\"\n#include \"foundation\/math\/rng.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\n\/\/ Forward declarations.\nnamespace foundation    { class LightingConditions; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n    class GenericSampleGenerator\n      : public SampleGeneratorBase\n    {\n      public:\n        GenericSampleGenerator(\n            const Frame&                    frame,\n            ISampleRendererFactory*         sample_renderer_factory,\n            const size_t                    generator_index,\n            const size_t                    generator_count)\n          : SampleGeneratorBase(generator_index, generator_count)\n          , m_frame(frame)\n          , m_frame_props(frame.image().properties())\n          , m_lighting_conditions(frame.get_lighting_conditions())\n          , m_sample_renderer(sample_renderer_factory->create())\n          , m_frame_width_next_pow2(next_power(static_cast(m_frame_props.m_canvas_width), 2.0))\n          , m_frame_height_next_pow3(next_power(static_cast(m_frame_props.m_canvas_height), 3.0))\n        {\n        }\n\n        virtual void release() override\n        {\n            delete this;\n        }\n\n        virtual void reset() override\n        {\n            SampleGeneratorBase::reset();\n            m_rng = MersenneTwister();\n        }\n\n        virtual StatisticsVector get_statistics() const override\n        {\n            Statistics stats;\n            stats.insert(\"max. samp. dim.\", m_total_sampling_dim);\n            stats.insert(\"max. samp. inst.\", m_total_sampling_inst);\n\n            StatisticsVector vec;\n            vec.insert(\"generic sample generator statistics\", stats);\n            vec.merge(m_sample_renderer->get_statistics());\n\n            return vec;\n        }\n\n      private:\n        const Frame&                        m_frame;\n        const CanvasProperties&             m_frame_props;\n        const LightingConditions&           m_lighting_conditions;\n        auto_release_ptr   m_sample_renderer;\n        MersenneTwister                     m_rng;\n\n        const double                        m_frame_width_next_pow2;\n        const double                        m_frame_height_next_pow3;\n\n        Population                  m_total_sampling_dim;\n        Population                  m_total_sampling_inst;\n\n        virtual size_t generate_samples(\n            const size_t                    sequence_index,\n            SampleVector&                   samples) override\n        {\n            \/\/ Compute the sample position in NDC.\n            const size_t Bases[2] = { 2, 3 };\n            const Vector2d s = halton_sequence(Bases, sequence_index);\n\n            \/\/ Compute the coordinates of the pixel in the larger frame.\n            const Vector2d t(s[0] * m_frame_width_next_pow2, s[1] * m_frame_height_next_pow3);\n            const size_t x = truncate(t[0]);\n            const size_t y = truncate(t[1]);\n\n            \/\/ Reject samples that fall outside the actual frame.\n            if (x >= m_frame_props.m_canvas_width || y >= m_frame_props.m_canvas_height)\n                return 0;\n\n            \/\/ Transform the sample position back to NDC. Full precision divisions are required\n            \/\/ to ensure that the sample position indeed lies in the [0,1)^2 interval.\n            const Vector2d sample_position(\n                t[0] \/ m_frame_props.m_canvas_width,\n                t[1] \/ m_frame_props.m_canvas_height);\n\n            \/\/ Create a sampling context. We start with an initial dimension of 2,\n            \/\/ corresponding to the Halton sequence used for the sample positions.\n            SamplingContext sampling_context(\n                m_rng,\n                2,                          \/\/ number of dimensions\n                sequence_index,             \/\/ number of samples\n                sequence_index);            \/\/ initial instance number\n\n            \/\/ Render the sample.\n            ShadingResult shading_result;\n            m_sample_renderer->render_sample(\n                sampling_context,\n                sample_position,\n                shading_result);\n\n            \/\/ Transform the sample to the linear RGB color space.\n            shading_result.transform_to_linear_rgb(m_lighting_conditions);\n\n            \/\/ Create a single sample.\n            Sample sample;\n            sample.m_position = sample_position;\n            sample.m_color[0] = shading_result.m_color[0];\n            sample.m_color[1] = shading_result.m_color[1];\n            sample.m_color[2] = shading_result.m_color[2];\n            sample.m_color[3] = shading_result.m_alpha[0];\n            samples.push_back(sample);\n\n            m_total_sampling_dim.insert(sampling_context.get_total_dimension());\n            m_total_sampling_inst.insert(sampling_context.get_total_instance());\n\n            return 1;\n        }\n    };\n}\n\n\n\/\/\n\/\/ GenericSampleGeneratorFactory class implementation.\n\/\/\n\nGenericSampleGeneratorFactory::GenericSampleGeneratorFactory(\n    const Frame&            frame,\n    ISampleRendererFactory* sample_renderer_factory)\n  : m_frame(frame)\n  , m_sample_renderer_factory(sample_renderer_factory)\n{\n}\n\nvoid GenericSampleGeneratorFactory::release()\n{\n    delete this;\n}\n\nISampleGenerator* GenericSampleGeneratorFactory::create(\n    const size_t            generator_index,\n    const size_t            generator_count)\n{\n    return\n        new GenericSampleGenerator(\n            m_frame,\n            m_sample_renderer_factory,\n            generator_index,\n            generator_count);\n}\n\nAccumulationFramebuffer* GenericSampleGeneratorFactory::create_accumulation_framebuffer(\n    const size_t            canvas_width,\n    const size_t            canvas_height)\n{\n    return\n        new LocalAccumulationFramebuffer(\n            canvas_width,\n            canvas_height);\n}\n\n}   \/\/ namespace renderer\nchanged some statistics to use 64-bit unsigned integers.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited\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\/\/ Interface header.\n#include \"genericsamplegenerator.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/rendering\/isamplerenderer.h\"\n#include \"renderer\/kernel\/rendering\/localaccumulationframebuffer.h\"\n#include \"renderer\/kernel\/rendering\/sample.h\"\n#include \"renderer\/kernel\/rendering\/samplegeneratorbase.h\"\n#include \"renderer\/kernel\/shading\/shadingresult.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/math\/population.h\"\n#include \"foundation\/math\/qmc.h\"\n#include \"foundation\/math\/rng.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\n\/\/ Forward declarations.\nnamespace foundation    { class LightingConditions; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n    class GenericSampleGenerator\n      : public SampleGeneratorBase\n    {\n      public:\n        GenericSampleGenerator(\n            const Frame&                    frame,\n            ISampleRendererFactory*         sample_renderer_factory,\n            const size_t                    generator_index,\n            const size_t                    generator_count)\n          : SampleGeneratorBase(generator_index, generator_count)\n          , m_frame(frame)\n          , m_frame_props(frame.image().properties())\n          , m_lighting_conditions(frame.get_lighting_conditions())\n          , m_sample_renderer(sample_renderer_factory->create())\n          , m_frame_width_next_pow2(next_power(static_cast(m_frame_props.m_canvas_width), 2.0))\n          , m_frame_height_next_pow3(next_power(static_cast(m_frame_props.m_canvas_height), 3.0))\n        {\n        }\n\n        virtual void release() override\n        {\n            delete this;\n        }\n\n        virtual void reset() override\n        {\n            SampleGeneratorBase::reset();\n            m_rng = MersenneTwister();\n        }\n\n        virtual StatisticsVector get_statistics() const override\n        {\n            Statistics stats;\n            stats.insert(\"max. samp. dim.\", m_total_sampling_dim);\n            stats.insert(\"max. samp. inst.\", m_total_sampling_inst);\n\n            StatisticsVector vec;\n            vec.insert(\"generic sample generator statistics\", stats);\n            vec.merge(m_sample_renderer->get_statistics());\n\n            return vec;\n        }\n\n      private:\n        const Frame&                        m_frame;\n        const CanvasProperties&             m_frame_props;\n        const LightingConditions&           m_lighting_conditions;\n        auto_release_ptr   m_sample_renderer;\n        MersenneTwister                     m_rng;\n\n        const double                        m_frame_width_next_pow2;\n        const double                        m_frame_height_next_pow3;\n\n        Population                  m_total_sampling_dim;\n        Population                  m_total_sampling_inst;\n\n        virtual size_t generate_samples(\n            const size_t                    sequence_index,\n            SampleVector&                   samples) override\n        {\n            \/\/ Compute the sample position in NDC.\n            const size_t Bases[2] = { 2, 3 };\n            const Vector2d s = halton_sequence(Bases, sequence_index);\n\n            \/\/ Compute the coordinates of the pixel in the larger frame.\n            const Vector2d t(s[0] * m_frame_width_next_pow2, s[1] * m_frame_height_next_pow3);\n            const size_t x = truncate(t[0]);\n            const size_t y = truncate(t[1]);\n\n            \/\/ Reject samples that fall outside the actual frame.\n            if (x >= m_frame_props.m_canvas_width || y >= m_frame_props.m_canvas_height)\n                return 0;\n\n            \/\/ Transform the sample position back to NDC. Full precision divisions are required\n            \/\/ to ensure that the sample position indeed lies in the [0,1)^2 interval.\n            const Vector2d sample_position(\n                t[0] \/ m_frame_props.m_canvas_width,\n                t[1] \/ m_frame_props.m_canvas_height);\n\n            \/\/ Create a sampling context. We start with an initial dimension of 2,\n            \/\/ corresponding to the Halton sequence used for the sample positions.\n            SamplingContext sampling_context(\n                m_rng,\n                2,                          \/\/ number of dimensions\n                sequence_index,             \/\/ number of samples\n                sequence_index);            \/\/ initial instance number\n\n            \/\/ Render the sample.\n            ShadingResult shading_result;\n            m_sample_renderer->render_sample(\n                sampling_context,\n                sample_position,\n                shading_result);\n\n            \/\/ Transform the sample to the linear RGB color space.\n            shading_result.transform_to_linear_rgb(m_lighting_conditions);\n\n            \/\/ Create a single sample.\n            Sample sample;\n            sample.m_position = sample_position;\n            sample.m_color[0] = shading_result.m_color[0];\n            sample.m_color[1] = shading_result.m_color[1];\n            sample.m_color[2] = shading_result.m_color[2];\n            sample.m_color[3] = shading_result.m_alpha[0];\n            samples.push_back(sample);\n\n            m_total_sampling_dim.insert(sampling_context.get_total_dimension());\n            m_total_sampling_inst.insert(sampling_context.get_total_instance());\n\n            return 1;\n        }\n    };\n}\n\n\n\/\/\n\/\/ GenericSampleGeneratorFactory class implementation.\n\/\/\n\nGenericSampleGeneratorFactory::GenericSampleGeneratorFactory(\n    const Frame&            frame,\n    ISampleRendererFactory* sample_renderer_factory)\n  : m_frame(frame)\n  , m_sample_renderer_factory(sample_renderer_factory)\n{\n}\n\nvoid GenericSampleGeneratorFactory::release()\n{\n    delete this;\n}\n\nISampleGenerator* GenericSampleGeneratorFactory::create(\n    const size_t            generator_index,\n    const size_t            generator_count)\n{\n    return\n        new GenericSampleGenerator(\n            m_frame,\n            m_sample_renderer_factory,\n            generator_index,\n            generator_count);\n}\n\nAccumulationFramebuffer* GenericSampleGeneratorFactory::create_accumulation_framebuffer(\n    const size_t            canvas_width,\n    const size_t            canvas_height)\n{\n    return\n        new LocalAccumulationFramebuffer(\n            canvas_width,\n            canvas_height);\n}\n\n}   \/\/ namespace renderer\n<|endoftext|>"}
{"text":"\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: DrawViewWrapper.hxx,v $\n *\n *  $Revision: 1.9 $\n *\n *  last change: $Author: rt $ $Date: 2007-07-25 08:39:24 $\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 _CHART2_DRAW_VIEW_WRAPPER_HXX\n#define _CHART2_DRAW_VIEW_WRAPPER_HXX\n\n#ifndef _E3D_VIEW3D_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include \n#endif\n\nclass SdrModel;\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.\nAnother task is to hide functionality we do not need, for example more than one page.\n*\/\n\nclass MarkHandleProvider\n{\npublic:\n    virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;\n    virtual bool getFrameDragSingles() =0;\n};\n\nclass DrawViewWrapper : public E3dView\n{\npublic:\n    DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut);\n    virtual ~DrawViewWrapper();\n\n    \/\/triggers the use of an updated first page\n    void    ReInit();\n\n    \/\/\/ tries to get an OutputDevice from the XParent of the model to use as reference device\n    void attachParentReferenceDevice(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel );\n\n    \/\/fill list of selection handles 'aHdl'\n    virtual void SetMarkHandles();\n\n    SdrPageView*    GetPageView() const;\n\n    SdrObject* getHitObject( const Point& rPnt ) const;\n    \/\/BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;\n    \/\/BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;\n    \/\/BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }\n\n    \/\/void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);\n    void MarkObject( SdrObject* pObj );\n\n    \/\/----------------------\n    \/\/pMarkHandleProvider can be NULL; ownership is not taken\n    void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );\n    void CompleteRedraw( OutputDevice* pOut, const Region& rReg, USHORT nPaintMode = 0,\n                         ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L );\n\n    SdrObject*   getSelectedObject() const;\n    SdrObject*   getTextEditObject() const;\n    SdrOutliner* getOutliner() const;\n\n    SfxItemSet   getPositionAndSizeItemSetFromMarkedObject() const;\n\n    SdrObject* getNamedSdrObject( const rtl::OUString& rName ) const;\n    bool IsObjectHit( SdrObject* pObj, const Point& rPnt ) const;\n\n    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n\n    static SdrObject* getSdrObject( const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::drawing::XShape >& xShape );\n\nprivate:\n    mutable MarkHandleProvider*     m_pMarkHandleProvider;\n\n    ::std::auto_ptr< SdrOutliner >  m_apOutliner;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n\nINTEGRATION: CWS chart15 (1.9.22); FILE MERGED 2007\/12\/05 12:21:19 bm 1.9.22.2: #i79965# scroll window back after text edit 2007\/11\/29 17:36:50 iha 1.9.22.1: #i82893#,#i75867# charts must be painted resolution dependent\/*************************************************************************\n *\n *  OpenOffice.org - a multi-platform office productivity suite\n *\n *  $RCSfile: DrawViewWrapper.hxx,v $\n *\n *  $Revision: 1.10 $\n *\n *  last change: $Author: ihi $ $Date: 2008-01-14 13:57:44 $\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 _CHART2_DRAW_VIEW_WRAPPER_HXX\n#define _CHART2_DRAW_VIEW_WRAPPER_HXX\n\n#ifndef _E3D_VIEW3D_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_\n#include \n#endif\n\nclass SdrModel;\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/** The DrawViewWrapper should help us to reduce effort if the underlying DrawingLayer changes.\nAnother task is to hide functionality we do not need, for example more than one page.\n*\/\n\nclass MarkHandleProvider\n{\npublic:\n    virtual bool getMarkHandles( SdrHdlList& rHdlList ) =0;\n    virtual bool getFrameDragSingles() =0;\n};\n\nclass DrawViewWrapper : public E3dView\n{\npublic:\n    DrawViewWrapper(SdrModel* pModel, OutputDevice* pOut, bool bPaintPageForEditMode);\n    virtual ~DrawViewWrapper();\n\n    \/\/triggers the use of an updated first page\n    void    ReInit();\n\n    \/\/\/ tries to get an OutputDevice from the XParent of the model to use as reference device\n    void attachParentReferenceDevice(\n        const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > & xChartModel );\n\n    \/\/fill list of selection handles 'aHdl'\n    virtual void SetMarkHandles();\n\n    SdrPageView*    GetPageView() const;\n\n    SdrObject* getHitObject( const Point& rPnt ) const;\n    \/\/BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions, SdrObject** ppRootObj, ULONG* pnMarkNum=NULL, USHORT* pnPassNum=NULL) const;\n    \/\/BOOL PickObj(const Point& rPnt, short nTol, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const;\n    \/\/BOOL PickObj(const Point& rPnt, SdrObject*& rpObj, SdrPageView*& rpPV, ULONG nOptions=0) const { return PickObj(rPnt,nHitTolLog,rpObj,rpPV,nOptions); }\n\n    \/\/void MarkObj(SdrObject* pObj, SdrPageView* pPV, BOOL bUnmark=FALSE, BOOL bImpNoSetMarkHdl=FALSE);\n    void MarkObject( SdrObject* pObj );\n\n    \/\/----------------------\n    \/\/pMarkHandleProvider can be NULL; ownership is not taken\n    void setMarkHandleProvider( MarkHandleProvider* pMarkHandleProvider );\n    void CompleteRedraw( OutputDevice* pOut, const Region& rReg, USHORT nPaintMode = 0,\n                         ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L );\n\n    SdrObject*   getSelectedObject() const;\n    SdrObject*   getTextEditObject() const;\n    SdrOutliner* getOutliner() const;\n\n    SfxItemSet   getPositionAndSizeItemSetFromMarkedObject() const;\n\n    SdrObject* getNamedSdrObject( const rtl::OUString& rName ) const;\n    bool IsObjectHit( SdrObject* pObj, const Point& rPnt ) const;\n\n    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n\n    static SdrObject* getSdrObject( const ::com::sun::star::uno::Reference<\n                    ::com::sun::star::drawing::XShape >& xShape );\n\nprivate:\n    mutable MarkHandleProvider*     m_pMarkHandleProvider;\n\n    ::std::auto_ptr< SdrOutliner >  m_apOutliner;\n\n    \/\/ #i79965# scroll back view when ending text edit\n    bool m_bRestoreMapMode;\n    MapMode m_aMapModeToRestore;\n};\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n\n<|endoftext|>"}
{"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"macros.hxx\"\n#include \"PropertyMapper.hxx\"\n#include \"CommonConverters.hxx\"\n\n#include \"AbstractShapeFactory.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"OpenglShapeFactory.hxx\"\n#include \"ShapeFactory.hxx\"\n\nusing namespace com::sun::star;\nusing ::com::sun::star::uno::Reference;\n\nnamespace chart {\n\nnamespace {\n\ntypedef opengl::OpenglShapeFactory* (*__getOpenglShapeFactory)(void);\n\nstatic void SAL_CALL thisModule() {}\n\nosl::Module* getOpenGLModule()\n{\n    static osl::Module aModule;\n    if (aModule.is())\n        \/\/ Already loaded.\n        return &aModule;\n\n    OUString aLibName(SVLIBRARY(\"chartopengl\"));\n    bool bLoaded = aModule.loadRelative(&thisModule, aLibName);\n    if (!bLoaded)\n        bLoaded = aModule.load(aLibName);\n\n    return bLoaded ? &aModule : NULL;\n}\n\n}\n\nAbstractShapeFactory* AbstractShapeFactory::getOrCreateShapeFactory(uno::Reference< lang::XMultiServiceFactory> xFactory)\n{\n    static AbstractShapeFactory* pShapeFactory = NULL;\n\n    if(pShapeFactory)\n        return pShapeFactory;\n\n    if(getenv(\"CHART_DUMMY_FACTORY\") && !Application::IsHeadlessModeEnabled())\n    {\n        osl::Module* pModule = getOpenGLModule();\n        if(pModule)\n        {\n            oslGenericFunction fn = pModule->getFunctionSymbol(\"getOpenglShapeFactory\");\n            if(fn)\n            {\n\n                pShapeFactory = reinterpret_cast<__getOpenglShapeFactory>(fn)();\n                pShapeFactory->setShapeFactory(xFactory);\n            }\n        }\n    }\n\n\n    if(!pShapeFactory)\n        pShapeFactory = new ShapeFactory(xFactory);\n\n    return pShapeFactory;\n}\n\nsal_Int32 AbstractShapeFactory::getSymbolCount()\n{\n    return Symbol_COUNT;\n}\n\nuno::Reference< drawing::XShapes > AbstractShapeFactory::getChartRootShape(\n    const uno::Reference< drawing::XDrawPage>& xDrawPage )\n{\n    uno::Reference< drawing::XShapes > xRet;\n    uno::Reference< drawing::XShapes > xShapes( xDrawPage, uno::UNO_QUERY );\n    if( xShapes.is() )\n    {\n        sal_Int32 nCount = xShapes->getCount();\n        uno::Reference< drawing::XShape > xShape;\n        for( sal_Int32 nN = nCount; nN--; )\n        {\n            if( xShapes->getByIndex( nN ) >>= xShape )\n            {\n                if( AbstractShapeFactory::getShapeName( xShape ).equals(\"com.sun.star.chart2.shapes\") )\n                {\n                    xRet = uno::Reference< drawing::XShapes >( xShape, uno::UNO_QUERY );\n                    break;\n                }\n            }\n        }\n    }\n    return xRet;\n}\n\nvoid AbstractShapeFactory::makeShapeInvisible( const uno::Reference< drawing::XShape >& xShape )\n{\n    uno::Reference< beans::XPropertySet > xShapeProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xShapeProp.is(), \"created shape offers no XPropertySet\");\n    if( xShapeProp.is())\n    {\n        try\n        {\n            xShapeProp->setPropertyValue( \"LineStyle\", uno::makeAny( drawing::LineStyle_NONE ));\n            xShapeProp->setPropertyValue( \"FillStyle\", uno::makeAny( drawing::FillStyle_NONE ));\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n}\n\n\/\/ set a name\/CID at a shape (is used for selection handling)\n\nvoid AbstractShapeFactory::setShapeName( const uno::Reference< drawing::XShape >& xShape\n                               , const OUString& rName )\n{\n    if(!xShape.is())\n        return;\n    uno::Reference< beans::XPropertySet > xProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xProp.is(), \"shape offers no XPropertySet\");\n    if( xProp.is())\n    {\n        try\n        {\n            xProp->setPropertyValue( UNO_NAME_MISC_OBJ_NAME\n                , uno::makeAny( rName ) );\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n}\n\nOUString AbstractShapeFactory::getShapeName( const uno::Reference< drawing::XShape >& xShape )\n{\n    OUString aRet;\n\n    uno::Reference< beans::XPropertySet > xProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xProp.is(), \"shape offers no XPropertySet\");\n    if( xProp.is())\n    {\n        try\n        {\n            xProp->getPropertyValue( UNO_NAME_MISC_OBJ_NAME ) >>= aRet;\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n\n    return aRet;\n}\n\nuno::Any AbstractShapeFactory::makeTransformation( const awt::Point& rScreenPosition2D, double fRotationAnglePi )\n{\n    ::basegfx::B2DHomMatrix aM;\n    \/\/As autogrow is active the rectangle is automatically expanded to that side\n    \/\/to which the text is not adjusted.\n    \/\/ aM.scale( 1, 1 ); Oops? A scale with this parameters is neutral, line commented out\n    aM.rotate( fRotationAnglePi );\n    aM.translate( rScreenPosition2D.X, rScreenPosition2D.Y );\n    uno::Any aATransformation = uno::makeAny( B2DHomMatrixToHomogenMatrix3(aM) );\n    return aATransformation;\n}\n\nOUString AbstractShapeFactory::getStackedString( const OUString& rString, bool bStacked )\n{\n    sal_Int32 nLen = rString.getLength();\n    if(!bStacked || !nLen)\n        return rString;\n\n    OUStringBuffer aStackStr;\n\n    \/\/add a newline after each letter\n    \/\/as we do not no letters here add a newline after each char\n    for( sal_Int32 nPosSrc=0; nPosSrc < nLen; nPosSrc++ )\n    {\n        if( nPosSrc )\n            aStackStr.append( '\\r' );\n        aStackStr.append(rString[nPosSrc]);\n    }\n    return aStackStr.makeStringAndClear();\n}\n\nbool AbstractShapeFactory::hasPolygonAnyLines( drawing::PolyPolygonShape3D& rPoly)\n{\n    \/\/ #i67757# check all contained polygons, if at least one polygon contains 2 or more points, return true\n    for( sal_Int32 nIdx = 0, nCount = rPoly.SequenceX.getLength(); nIdx < nCount; ++nIdx )\n        if( rPoly.SequenceX[ nIdx ].getLength() > 1 )\n            return true;\n    return false;\n}\n\nbool AbstractShapeFactory::isPolygonEmptyOrSinglePoint( drawing::PolyPolygonShape3D& rPoly)\n{\n    \/\/ true, if empty polypolygon or one polygon with one point\n    return (rPoly.SequenceX.getLength() == 0) ||\n        ((rPoly.SequenceX.getLength() == 1) && (rPoly.SequenceX[0].getLength() <= 1));\n}\n\nvoid AbstractShapeFactory::closePolygon( drawing::PolyPolygonShape3D& rPoly)\n{\n    OSL_ENSURE( rPoly.SequenceX.getLength() <= 1, \"AbstractShapeFactory::closePolygon - single polygon expected\" );\n    \/\/add a last point == first point\n    if(isPolygonEmptyOrSinglePoint(rPoly))\n        return;\n    drawing::Position3D aFirst(rPoly.SequenceX[0][0],rPoly.SequenceY[0][0],rPoly.SequenceZ[0][0]);\n    AddPointToPoly( rPoly, aFirst );\n}\n\nawt::Size AbstractShapeFactory::calculateNewSizeRespectingAspectRatio(\n         const awt::Size& rTargetSize\n         , const awt::Size& rSourceSizeWithCorrectAspectRatio )\n{\n    awt::Size aNewSize;\n\n    double fFactorWidth = double(rTargetSize.Width)\/double(rSourceSizeWithCorrectAspectRatio.Width);\n    double fFactorHeight = double(rTargetSize.Height)\/double(rSourceSizeWithCorrectAspectRatio.Height);\n    double fFactor = std::min(fFactorWidth,fFactorHeight);\n    aNewSize.Width=static_cast(fFactor*rSourceSizeWithCorrectAspectRatio.Width);\n    aNewSize.Height=static_cast(fFactor*rSourceSizeWithCorrectAspectRatio.Height);\n\n    return aNewSize;\n}\n\nawt::Point AbstractShapeFactory::calculateTopLeftPositionToCenterObject(\n           const awt::Point& rTargetAreaPosition\n         , const awt::Size& rTargetAreaSize\n         , const awt::Size& rObjectSize )\n{\n    awt::Point aNewPosition(rTargetAreaPosition);\n    aNewPosition.X += static_cast(double(rTargetAreaSize.Width-rObjectSize.Width)\/2.0);\n    aNewPosition.Y += static_cast(double(rTargetAreaSize.Height-rObjectSize.Height)\/2.0);\n    return aNewPosition;\n}\n\n::basegfx::B2IRectangle AbstractShapeFactory::getRectangleOfShape(\n        const uno::Reference< drawing::XShape >& xShape )\n{\n    ::basegfx::B2IRectangle aRet;\n\n    if( xShape.is() )\n    {\n        awt::Point aPos = xShape->getPosition();\n        awt::Size aSize = xShape->getSize();\n        aRet = BaseGFXHelper::makeRectangle(aPos,aSize);\n    }\n    return aRet;\n\n}\n\nawt::Size AbstractShapeFactory::getSizeAfterRotation(\n         const uno::Reference< drawing::XShape >& xShape, double fRotationAngleDegree )\n{\n    awt::Size aRet(0,0);\n    if(xShape.is())\n    {\n        const awt::Size aSize( xShape->getSize() );\n\n        if( ::rtl::math::approxEqual( fRotationAngleDegree, 0.0 ) )\n            aRet = aSize;\n        else\n        {\n            while(fRotationAngleDegree>=360.0)\n                fRotationAngleDegree-=360.0;\n            while(fRotationAngleDegree<0.0)\n                fRotationAngleDegree+=360.0;\n            if(fRotationAngleDegree>270.0)\n                fRotationAngleDegree=360.0-fRotationAngleDegree;\n            else if(fRotationAngleDegree>180.0)\n                fRotationAngleDegree=fRotationAngleDegree-180.0;\n            else if(fRotationAngleDegree>90.0)\n                fRotationAngleDegree=180.0-fRotationAngleDegree;\n\n            const double fAnglePi = fRotationAngleDegree*F_PI\/180.0;\n\n            aRet.Height = static_cast(\n                aSize.Width*rtl::math::sin( fAnglePi )\n                + aSize.Height*rtl::math::cos( fAnglePi ));\n            aRet.Width = static_cast(\n                aSize.Width*rtl::math::cos( fAnglePi )\n                + aSize.Height*rtl::math::sin( fAnglePi ));\n        }\n    }\n    return aRet;\n}\n\nvoid AbstractShapeFactory::removeSubShapes( const uno::Reference< drawing::XShapes >& xShapes )\n{\n    if( xShapes.is() )\n    {\n        sal_Int32 nSubCount = xShapes->getCount();\n        uno::Reference< drawing::XShape > xShape;\n        for( sal_Int32 nS = nSubCount; nS--; )\n        {\n            if( xShapes->getByIndex( nS ) >>= xShape )\n                xShapes->remove( xShape );\n        }\n    }\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nAdapt for the DISABLE_DYNLOADING case\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"macros.hxx\"\n#include \"PropertyMapper.hxx\"\n#include \"CommonConverters.hxx\"\n\n#include \"AbstractShapeFactory.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"OpenglShapeFactory.hxx\"\n#include \"ShapeFactory.hxx\"\n\nusing namespace com::sun::star;\nusing ::com::sun::star::uno::Reference;\n\nnamespace chart {\n\nnamespace {\n\ntypedef opengl::OpenglShapeFactory* (*__getOpenglShapeFactory)(void);\n\n#ifndef DISABLE_DYNLOADING\n\nstatic void SAL_CALL thisModule() {}\n\nosl::Module* getOpenGLModule()\n{\n    static osl::Module aModule;\n    if (aModule.is())\n        \/\/ Already loaded.\n        return &aModule;\n\n    OUString aLibName(SVLIBRARY(\"chartopengl\"));\n    bool bLoaded = aModule.loadRelative(&thisModule, aLibName);\n    if (!bLoaded)\n        bLoaded = aModule.load(aLibName);\n\n    return bLoaded ? &aModule : NULL;\n}\n\n#endif\n\n}\n\n#ifdef DISABLE_DYNLOADING\nextern \"C\" opengl::OpenglShapeFactory* getOpenglShapeFactory();\n#endif\n\nAbstractShapeFactory* AbstractShapeFactory::getOrCreateShapeFactory(uno::Reference< lang::XMultiServiceFactory> xFactory)\n{\n    static AbstractShapeFactory* pShapeFactory = NULL;\n\n    if(pShapeFactory)\n        return pShapeFactory;\n\n    if(getenv(\"CHART_DUMMY_FACTORY\") && !Application::IsHeadlessModeEnabled())\n    {\n#ifndef DISABLE_DYNLOADING\n        osl::Module* pModule = getOpenGLModule();\n        if(pModule)\n        {\n            oslGenericFunction fn = pModule->getFunctionSymbol(\"getOpenglShapeFactory\");\n            if(fn)\n            {\n\n                pShapeFactory = reinterpret_cast<__getOpenglShapeFactory>(fn)();\n                pShapeFactory->setShapeFactory(xFactory);\n            }\n        }\n#else\n        pShapeFactory = getOpenglShapeFactory();\n        pShapeFactory->setShapeFactory(xFactory);\n#endif\n    }\n\n\n    if(!pShapeFactory)\n        pShapeFactory = new ShapeFactory(xFactory);\n\n    return pShapeFactory;\n}\n\nsal_Int32 AbstractShapeFactory::getSymbolCount()\n{\n    return Symbol_COUNT;\n}\n\nuno::Reference< drawing::XShapes > AbstractShapeFactory::getChartRootShape(\n    const uno::Reference< drawing::XDrawPage>& xDrawPage )\n{\n    uno::Reference< drawing::XShapes > xRet;\n    uno::Reference< drawing::XShapes > xShapes( xDrawPage, uno::UNO_QUERY );\n    if( xShapes.is() )\n    {\n        sal_Int32 nCount = xShapes->getCount();\n        uno::Reference< drawing::XShape > xShape;\n        for( sal_Int32 nN = nCount; nN--; )\n        {\n            if( xShapes->getByIndex( nN ) >>= xShape )\n            {\n                if( AbstractShapeFactory::getShapeName( xShape ).equals(\"com.sun.star.chart2.shapes\") )\n                {\n                    xRet = uno::Reference< drawing::XShapes >( xShape, uno::UNO_QUERY );\n                    break;\n                }\n            }\n        }\n    }\n    return xRet;\n}\n\nvoid AbstractShapeFactory::makeShapeInvisible( const uno::Reference< drawing::XShape >& xShape )\n{\n    uno::Reference< beans::XPropertySet > xShapeProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xShapeProp.is(), \"created shape offers no XPropertySet\");\n    if( xShapeProp.is())\n    {\n        try\n        {\n            xShapeProp->setPropertyValue( \"LineStyle\", uno::makeAny( drawing::LineStyle_NONE ));\n            xShapeProp->setPropertyValue( \"FillStyle\", uno::makeAny( drawing::FillStyle_NONE ));\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n}\n\n\/\/ set a name\/CID at a shape (is used for selection handling)\n\nvoid AbstractShapeFactory::setShapeName( const uno::Reference< drawing::XShape >& xShape\n                               , const OUString& rName )\n{\n    if(!xShape.is())\n        return;\n    uno::Reference< beans::XPropertySet > xProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xProp.is(), \"shape offers no XPropertySet\");\n    if( xProp.is())\n    {\n        try\n        {\n            xProp->setPropertyValue( UNO_NAME_MISC_OBJ_NAME\n                , uno::makeAny( rName ) );\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n}\n\nOUString AbstractShapeFactory::getShapeName( const uno::Reference< drawing::XShape >& xShape )\n{\n    OUString aRet;\n\n    uno::Reference< beans::XPropertySet > xProp( xShape, uno::UNO_QUERY );\n    OSL_ENSURE(xProp.is(), \"shape offers no XPropertySet\");\n    if( xProp.is())\n    {\n        try\n        {\n            xProp->getPropertyValue( UNO_NAME_MISC_OBJ_NAME ) >>= aRet;\n        }\n        catch( const uno::Exception& e )\n        {\n            ASSERT_EXCEPTION( e );\n        }\n    }\n\n    return aRet;\n}\n\nuno::Any AbstractShapeFactory::makeTransformation( const awt::Point& rScreenPosition2D, double fRotationAnglePi )\n{\n    ::basegfx::B2DHomMatrix aM;\n    \/\/As autogrow is active the rectangle is automatically expanded to that side\n    \/\/to which the text is not adjusted.\n    \/\/ aM.scale( 1, 1 ); Oops? A scale with this parameters is neutral, line commented out\n    aM.rotate( fRotationAnglePi );\n    aM.translate( rScreenPosition2D.X, rScreenPosition2D.Y );\n    uno::Any aATransformation = uno::makeAny( B2DHomMatrixToHomogenMatrix3(aM) );\n    return aATransformation;\n}\n\nOUString AbstractShapeFactory::getStackedString( const OUString& rString, bool bStacked )\n{\n    sal_Int32 nLen = rString.getLength();\n    if(!bStacked || !nLen)\n        return rString;\n\n    OUStringBuffer aStackStr;\n\n    \/\/add a newline after each letter\n    \/\/as we do not no letters here add a newline after each char\n    for( sal_Int32 nPosSrc=0; nPosSrc < nLen; nPosSrc++ )\n    {\n        if( nPosSrc )\n            aStackStr.append( '\\r' );\n        aStackStr.append(rString[nPosSrc]);\n    }\n    return aStackStr.makeStringAndClear();\n}\n\nbool AbstractShapeFactory::hasPolygonAnyLines( drawing::PolyPolygonShape3D& rPoly)\n{\n    \/\/ #i67757# check all contained polygons, if at least one polygon contains 2 or more points, return true\n    for( sal_Int32 nIdx = 0, nCount = rPoly.SequenceX.getLength(); nIdx < nCount; ++nIdx )\n        if( rPoly.SequenceX[ nIdx ].getLength() > 1 )\n            return true;\n    return false;\n}\n\nbool AbstractShapeFactory::isPolygonEmptyOrSinglePoint( drawing::PolyPolygonShape3D& rPoly)\n{\n    \/\/ true, if empty polypolygon or one polygon with one point\n    return (rPoly.SequenceX.getLength() == 0) ||\n        ((rPoly.SequenceX.getLength() == 1) && (rPoly.SequenceX[0].getLength() <= 1));\n}\n\nvoid AbstractShapeFactory::closePolygon( drawing::PolyPolygonShape3D& rPoly)\n{\n    OSL_ENSURE( rPoly.SequenceX.getLength() <= 1, \"AbstractShapeFactory::closePolygon - single polygon expected\" );\n    \/\/add a last point == first point\n    if(isPolygonEmptyOrSinglePoint(rPoly))\n        return;\n    drawing::Position3D aFirst(rPoly.SequenceX[0][0],rPoly.SequenceY[0][0],rPoly.SequenceZ[0][0]);\n    AddPointToPoly( rPoly, aFirst );\n}\n\nawt::Size AbstractShapeFactory::calculateNewSizeRespectingAspectRatio(\n         const awt::Size& rTargetSize\n         , const awt::Size& rSourceSizeWithCorrectAspectRatio )\n{\n    awt::Size aNewSize;\n\n    double fFactorWidth = double(rTargetSize.Width)\/double(rSourceSizeWithCorrectAspectRatio.Width);\n    double fFactorHeight = double(rTargetSize.Height)\/double(rSourceSizeWithCorrectAspectRatio.Height);\n    double fFactor = std::min(fFactorWidth,fFactorHeight);\n    aNewSize.Width=static_cast(fFactor*rSourceSizeWithCorrectAspectRatio.Width);\n    aNewSize.Height=static_cast(fFactor*rSourceSizeWithCorrectAspectRatio.Height);\n\n    return aNewSize;\n}\n\nawt::Point AbstractShapeFactory::calculateTopLeftPositionToCenterObject(\n           const awt::Point& rTargetAreaPosition\n         , const awt::Size& rTargetAreaSize\n         , const awt::Size& rObjectSize )\n{\n    awt::Point aNewPosition(rTargetAreaPosition);\n    aNewPosition.X += static_cast(double(rTargetAreaSize.Width-rObjectSize.Width)\/2.0);\n    aNewPosition.Y += static_cast(double(rTargetAreaSize.Height-rObjectSize.Height)\/2.0);\n    return aNewPosition;\n}\n\n::basegfx::B2IRectangle AbstractShapeFactory::getRectangleOfShape(\n        const uno::Reference< drawing::XShape >& xShape )\n{\n    ::basegfx::B2IRectangle aRet;\n\n    if( xShape.is() )\n    {\n        awt::Point aPos = xShape->getPosition();\n        awt::Size aSize = xShape->getSize();\n        aRet = BaseGFXHelper::makeRectangle(aPos,aSize);\n    }\n    return aRet;\n\n}\n\nawt::Size AbstractShapeFactory::getSizeAfterRotation(\n         const uno::Reference< drawing::XShape >& xShape, double fRotationAngleDegree )\n{\n    awt::Size aRet(0,0);\n    if(xShape.is())\n    {\n        const awt::Size aSize( xShape->getSize() );\n\n        if( ::rtl::math::approxEqual( fRotationAngleDegree, 0.0 ) )\n            aRet = aSize;\n        else\n        {\n            while(fRotationAngleDegree>=360.0)\n                fRotationAngleDegree-=360.0;\n            while(fRotationAngleDegree<0.0)\n                fRotationAngleDegree+=360.0;\n            if(fRotationAngleDegree>270.0)\n                fRotationAngleDegree=360.0-fRotationAngleDegree;\n            else if(fRotationAngleDegree>180.0)\n                fRotationAngleDegree=fRotationAngleDegree-180.0;\n            else if(fRotationAngleDegree>90.0)\n                fRotationAngleDegree=180.0-fRotationAngleDegree;\n\n            const double fAnglePi = fRotationAngleDegree*F_PI\/180.0;\n\n            aRet.Height = static_cast(\n                aSize.Width*rtl::math::sin( fAnglePi )\n                + aSize.Height*rtl::math::cos( fAnglePi ));\n            aRet.Width = static_cast(\n                aSize.Width*rtl::math::cos( fAnglePi )\n                + aSize.Height*rtl::math::sin( fAnglePi ));\n        }\n    }\n    return aRet;\n}\n\nvoid AbstractShapeFactory::removeSubShapes( const uno::Reference< drawing::XShapes >& xShapes )\n{\n    if( xShapes.is() )\n    {\n        sal_Int32 nSubCount = xShapes->getCount();\n        uno::Reference< drawing::XShape > xShape;\n        for( sal_Int32 nS = nSubCount; nS--; )\n        {\n            if( xShapes->getByIndex( nS ) >>= xShape )\n                xShapes->remove( xShape );\n        }\n    }\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\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 \"app\/surface\/transport_dib.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/ref_counted_memory.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/render_messages_params.h\"\n#include \"chrome\/renderer\/render_widget_browsertest.h\"\n#include \"gfx\/codec\/jpeg_codec.h\"\n#include \"gfx\/size.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebSize.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebView.h\"\n\nconst int RenderWidgetTest::kNumBytesPerPixel = 4;\nconst int RenderWidgetTest::kLargeWidth = 1024;\nconst int RenderWidgetTest::kLargeHeight = 768;\nconst int RenderWidgetTest::kSmallWidth = 600;\nconst int RenderWidgetTest::kSmallHeight = 450;\nconst int RenderWidgetTest::kTextPositionX = 800;\nconst int RenderWidgetTest::kTextPositionY = 600;\nconst int RenderWidgetTest::kSequenceNum = 1;\nconst uint32 RenderWidgetTest::kRedARGB = 0xFFFF0000;\n\nRenderWidgetTest::RenderWidgetTest() {}\n\nvoid RenderWidgetTest::ResizeAndPaint(const gfx::Size& page_size,\n                                      const gfx::Size& desired_size,\n                                      SkBitmap* snapshot) {\n  ASSERT_TRUE(snapshot);\n  scoped_ptr pixels(\n      TransportDIB::Create(\n          page_size.width() * page_size.height() * kNumBytesPerPixel,\n          kSequenceNum));\n  view_->OnMsgPaintAtSize(pixels->handle(), kSequenceNum, page_size,\n                          desired_size);\n  ProcessPendingMessages();\n  const IPC::Message* msg = render_thread_.sink().GetUniqueMessageMatching(\n      ViewHostMsg_PaintAtSize_ACK::ID);\n  ASSERT_NE(static_cast(NULL), msg);\n  ViewHostMsg_PaintAtSize_ACK::Param params;\n  ViewHostMsg_PaintAtSize_ACK::Read(msg, ¶ms);\n  render_thread_.sink().ClearMessages();\n  EXPECT_EQ(kSequenceNum, params.a);\n  gfx::Size size = params.b;\n  EXPECT_EQ(desired_size, size);\n\n  SkBitmap tmp_bitmap;\n  tmp_bitmap.setConfig(SkBitmap::kARGB_8888_Config,\n                       size.width(), size.height());\n  tmp_bitmap.setPixels(pixels->memory());\n  \/\/ Copy the pixels from the TransportDIB object to the given snapshot.\n  ASSERT_TRUE(tmp_bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config));\n}\n\nvoid RenderWidgetTest::TestResizeAndPaint() {\n  \/\/ Hello World message is only visible if the view size is at least\n  \/\/ kTextPositionX x kTextPositionY\n  LoadHTML(StringPrintf(\n      \"
Hello World<\/div><\/body><\/html>\",\n kTextPositionY, kTextPositionX).c_str());\n WebKit::WebSize old_size = view_->webview()->size();\n\n SkBitmap bitmap;\n \/\/ If we re-size the view to something smaller than where the 'Hello World'\n \/\/ text is displayed we won't see any text in the snapshot. Hence,\n \/\/ the snapshot should not contain any red.\n gfx::Size size(kSmallWidth, kSmallHeight);\n ResizeAndPaint(size, size, &bitmap);\n \/\/ Make sure that the view has been re-sized to its old size.\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kSmallWidth, bitmap.width());\n EXPECT_EQ(kSmallHeight, bitmap.height());\n EXPECT_FALSE(ImageContainsColor(bitmap, kRedARGB));\n\n \/\/ Since we ask for the view to be re-sized to something larger than where the\n \/\/ 'Hello World' text is written the text should be visible in the snapshot.\n \/\/ Hence, the snapshot should contain some red.\n size.SetSize(kLargeWidth, kLargeHeight);\n ResizeAndPaint(size, size, &bitmap);\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kLargeWidth, bitmap.width());\n EXPECT_EQ(kLargeHeight, bitmap.height());\n EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB));\n\n \/\/ Even if the desired size is smaller than where the text is located we\n \/\/ should still see the 'Hello World' message since the view size is\n \/\/ still large enough.\n ResizeAndPaint(size, gfx::Size(kSmallWidth, kSmallHeight), &bitmap);\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kSmallWidth, bitmap.width());\n EXPECT_EQ(kSmallHeight, bitmap.height());\n EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB));\n}\n\nbool RenderWidgetTest::ImageContainsColor(const SkBitmap& bitmap,\n uint32 argb_color) {\n SkAutoLockPixels lock(bitmap);\n bool ready = bitmap.readyToDraw();\n EXPECT_TRUE(ready);\n if (!ready) {\n return false;\n }\n for (int x = 0; x < bitmap.width(); ++x) {\n for (int y = 0; y < bitmap.height(); ++y) {\n if (argb_color == *bitmap.getAddr32(x, y)) {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid RenderWidgetTest::OutputBitmapToFile(const SkBitmap& bitmap,\n const FilePath& file_path) {\n scoped_refptr bitmap_data = new RefCountedBytes();\n SkAutoLockPixels lock(bitmap);\n ASSERT_TRUE(gfx::JPEGCodec::Encode(\n reinterpret_cast(bitmap.getAddr32(0, 0)),\n gfx::JPEGCodec::FORMAT_BGRA,\n bitmap.width(),\n bitmap.height(),\n static_cast(bitmap.rowBytes()),\n 90 \/* quality *\/,\n &bitmap_data->data));\n ASSERT_LT(0, file_util::WriteFile(\n file_path,\n reinterpret_cast(bitmap_data->front()),\n bitmap_data->size()));\n}\n\nTEST_F(RenderWidgetTest, OnMsgPaintAtSize) {\n TestResizeAndPaint();\n}\nMark failing test OnMsgPaintAtSize failing TBR=noelutz BUG=none TEST=none Review URL: http:\/\/codereview.chromium.org\/3470011\/\/ 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 \"app\/surface\/transport_dib.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/ref_counted_memory.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/render_messages_params.h\"\n#include \"chrome\/renderer\/render_widget_browsertest.h\"\n#include \"gfx\/codec\/jpeg_codec.h\"\n#include \"gfx\/size.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebSize.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebView.h\"\n\nconst int RenderWidgetTest::kNumBytesPerPixel = 4;\nconst int RenderWidgetTest::kLargeWidth = 1024;\nconst int RenderWidgetTest::kLargeHeight = 768;\nconst int RenderWidgetTest::kSmallWidth = 600;\nconst int RenderWidgetTest::kSmallHeight = 450;\nconst int RenderWidgetTest::kTextPositionX = 800;\nconst int RenderWidgetTest::kTextPositionY = 600;\nconst int RenderWidgetTest::kSequenceNum = 1;\nconst uint32 RenderWidgetTest::kRedARGB = 0xFFFF0000;\n\nRenderWidgetTest::RenderWidgetTest() {}\n\nvoid RenderWidgetTest::ResizeAndPaint(const gfx::Size& page_size,\n const gfx::Size& desired_size,\n SkBitmap* snapshot) {\n ASSERT_TRUE(snapshot);\n scoped_ptr pixels(\n TransportDIB::Create(\n page_size.width() * page_size.height() * kNumBytesPerPixel,\n kSequenceNum));\n view_->OnMsgPaintAtSize(pixels->handle(), kSequenceNum, page_size,\n desired_size);\n ProcessPendingMessages();\n const IPC::Message* msg = render_thread_.sink().GetUniqueMessageMatching(\n ViewHostMsg_PaintAtSize_ACK::ID);\n ASSERT_NE(static_cast(NULL), msg);\n ViewHostMsg_PaintAtSize_ACK::Param params;\n ViewHostMsg_PaintAtSize_ACK::Read(msg, ¶ms);\n render_thread_.sink().ClearMessages();\n EXPECT_EQ(kSequenceNum, params.a);\n gfx::Size size = params.b;\n EXPECT_EQ(desired_size, size);\n\n SkBitmap tmp_bitmap;\n tmp_bitmap.setConfig(SkBitmap::kARGB_8888_Config,\n size.width(), size.height());\n tmp_bitmap.setPixels(pixels->memory());\n \/\/ Copy the pixels from the TransportDIB object to the given snapshot.\n ASSERT_TRUE(tmp_bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config));\n}\n\nvoid RenderWidgetTest::TestResizeAndPaint() {\n \/\/ Hello World message is only visible if the view size is at least\n \/\/ kTextPositionX x kTextPositionY\n LoadHTML(StringPrintf(\n \"
Hello World<\/div><\/body><\/html>\",\n kTextPositionY, kTextPositionX).c_str());\n WebKit::WebSize old_size = view_->webview()->size();\n\n SkBitmap bitmap;\n \/\/ If we re-size the view to something smaller than where the 'Hello World'\n \/\/ text is displayed we won't see any text in the snapshot. Hence,\n \/\/ the snapshot should not contain any red.\n gfx::Size size(kSmallWidth, kSmallHeight);\n ResizeAndPaint(size, size, &bitmap);\n \/\/ Make sure that the view has been re-sized to its old size.\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kSmallWidth, bitmap.width());\n EXPECT_EQ(kSmallHeight, bitmap.height());\n EXPECT_FALSE(ImageContainsColor(bitmap, kRedARGB));\n\n \/\/ Since we ask for the view to be re-sized to something larger than where the\n \/\/ 'Hello World' text is written the text should be visible in the snapshot.\n \/\/ Hence, the snapshot should contain some red.\n size.SetSize(kLargeWidth, kLargeHeight);\n ResizeAndPaint(size, size, &bitmap);\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kLargeWidth, bitmap.width());\n EXPECT_EQ(kLargeHeight, bitmap.height());\n EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB));\n\n \/\/ Even if the desired size is smaller than where the text is located we\n \/\/ should still see the 'Hello World' message since the view size is\n \/\/ still large enough.\n ResizeAndPaint(size, gfx::Size(kSmallWidth, kSmallHeight), &bitmap);\n EXPECT_EQ(old_size, view_->webview()->size());\n EXPECT_EQ(kSmallWidth, bitmap.width());\n EXPECT_EQ(kSmallHeight, bitmap.height());\n EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB));\n}\n\nbool RenderWidgetTest::ImageContainsColor(const SkBitmap& bitmap,\n uint32 argb_color) {\n SkAutoLockPixels lock(bitmap);\n bool ready = bitmap.readyToDraw();\n EXPECT_TRUE(ready);\n if (!ready) {\n return false;\n }\n for (int x = 0; x < bitmap.width(); ++x) {\n for (int y = 0; y < bitmap.height(); ++y) {\n if (argb_color == *bitmap.getAddr32(x, y)) {\n return true;\n }\n }\n }\n return false;\n}\n\nvoid RenderWidgetTest::OutputBitmapToFile(const SkBitmap& bitmap,\n const FilePath& file_path) {\n scoped_refptr bitmap_data = new RefCountedBytes();\n SkAutoLockPixels lock(bitmap);\n ASSERT_TRUE(gfx::JPEGCodec::Encode(\n reinterpret_cast(bitmap.getAddr32(0, 0)),\n gfx::JPEGCodec::FORMAT_BGRA,\n bitmap.width(),\n bitmap.height(),\n static_cast(bitmap.rowBytes()),\n 90 \/* quality *\/,\n &bitmap_data->data));\n ASSERT_LT(0, file_util::WriteFile(\n file_path,\n reinterpret_cast(bitmap_data->front()),\n bitmap_data->size()));\n}\n\nTEST_F(RenderWidgetTest, FAILS_OnMsgPaintAtSize) {\n TestResizeAndPaint();\n}\n<|endoftext|>"} {"text":"coverity#708124 Uninitialized scalar field<|endoftext|>"} {"text":"#include \"io_socket.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace cppio\n{\n\nUnixSocket::UnixSocket(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_UNIX, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n}\n\nUnixSocket::UnixSocket(int fd, const std::string& address)\n{\n\tm_socket = fd;\n\tm_address = address;\n}\n\nUnixSocket::~UnixSocket()\n{\n\tclose(m_socket);\n\tunlink(m_address.c_str());\n}\n\nvoid UnixSocket::connect()\n{\n\tsockaddr serverName;\n\tserverName.sa_family = AF_UNIX;\n\tstrncpy(serverName.sa_data, m_address.c_str(), sizeof(serverName.sa_data));\n\n\tint rc = ::connect(m_socket, &serverName, strlen(serverName.sa_data) + sizeof(serverName.sa_family));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to connect to socket: \" + std::to_string(rc) + \"\/\" + std::to_string(errno)));\n}\n\n\nssize_t UnixSocket::read(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::read(m_socket, buffer, buflen);\n\tif(rc < 0)\n\t{\n\t\tif((errno == ECONNRESET) || (errno == ENOTCONN))\n\t\t\tthrow ConnectionLost(\"\");\n\t\treturn 0;\n\t}\n\telse if(rc == 0)\n\t{\n\t\tif(errno != ETIMEDOUT)\n\t\t\tthrow ConnectionLost(\"\");\n\t}\n\treturn rc;\n}\n\nssize_t UnixSocket::write(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::write(m_socket, buffer, buflen);\n\treturn rc;\n}\n\nvoid UnixSocket::setOption(LineOption option, void* data)\n{\n\tswitch(option)\n\t{\n\t\tcase LineOption::ReceiveTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LineOption::SendTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow UnsupportedOption(\"\");\n\t}\n}\n\nUnixSocketAcceptor::UnixSocketAcceptor(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_UNIX, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n\n\tsockaddr serverName;\n\tserverName.sa_family = AF_UNIX;\n\tstrncpy(serverName.sa_data, m_address.c_str(), sizeof(serverName.sa_data));\n\n\tint rc = bind(m_socket, &serverName, strlen(serverName.sa_data) + sizeof(serverName.sa_family));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to bind socket: \" + std::to_string(rc)));\n\n\trc = listen(m_socket, 10);\n\tif(rc < 0)\n\t{\n\t\tclose(m_socket);\n\t\tunlink(m_address.c_str());\n\t\tthrow IoException(std::string(\"Unable to listen socket: \" + std::to_string(rc)));\n\t}\n}\n\nUnixSocketAcceptor::~UnixSocketAcceptor()\n{\n\tclose(m_socket);\n\tunlink(m_address.c_str());\n}\n\nstd::shared_ptr UnixSocketAcceptor::waitConnection(const std::chrono::milliseconds& timeout)\n{\n\tsockaddr addr;\n\tsocklen_t clen = sizeof(addr);\n\tint newsock = accept(m_socket, &addr, &clen);\n\tif(newsock > 0)\n\t{\n\t\treturn std::make_shared(newsock, \"\");\n\t}\n\treturn std::shared_ptr();\n}\n\nUnixSocketFactory::~UnixSocketFactory()\n{\n}\n\nbool UnixSocketFactory::supportsScheme(const std::string& scheme)\n{\n\treturn scheme == \"local\";\n}\n\nstd::shared_ptr UnixSocketFactory::createClient(const std::string& address)\n{\n\tauto socket = std::make_shared(address);\n\tif(socket)\n\t\tsocket->connect();\n\treturn socket;\n}\n\nstd::shared_ptr UnixSocketFactory::createServer(const std::string& address)\n{\n\treturn std::make_shared(address);\n}\n\n\/\/\/\/\/\/\/\n\nTcpSocket::TcpSocket(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_INET, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n}\n\nTcpSocket::TcpSocket(int fd, const std::string& address)\n{\n\tm_socket = fd;\n\tm_address = address;\n}\n\nTcpSocket::~TcpSocket()\n{\n\tclose(m_socket);\n}\n\nvoid TcpSocket::connect()\n{\n\tauto semicolon = m_address.find(':');\n\tauto host = m_address.substr(0, semicolon);\n\tauto port = atoi(m_address.substr(semicolon + 1).c_str());\n\tsockaddr_in addr;\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = inet_addr(host.c_str());\n\taddr.sin_port = htons(port);\n\t\n\tint rc = ::connect(m_socket, (sockaddr*)&addr, sizeof(addr));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to connect socket: \" + std::to_string(rc)));\n}\n\n\nssize_t TcpSocket::read(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::read(m_socket, buffer, buflen);\n\tif(rc < 0)\n\t{\n\t\tif((errno == ECONNRESET) || (errno == ENOTCONN))\n\t\t\tthrow ConnectionLost(\"\");\n\t\treturn 0;\n\t}\n\telse if(rc == 0)\n\t{\n\t\tif(errno != ETIMEDOUT)\n\t\t\tthrow ConnectionLost(\"\");\n\t}\n\treturn rc;\n}\n\nssize_t TcpSocket::write(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::write(m_socket, buffer, buflen);\n\treturn rc;\n}\n\nvoid TcpSocket::setOption(LineOption option, void* data)\n{\n\tswitch(option)\n\t{\n\t\tcase LineOption::ReceiveTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LineOption::SendTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow UnsupportedOption(\"\");\n\t}\n}\n\nTcpSocketAcceptor::TcpSocketAcceptor(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_INET, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n\n\tint enable = 1;\n\tif(setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0)\n\t\tthrow IoException(std::string(\"Unable to set socket option: \" + std::to_string(m_socket)));\n\n\n\tauto semicolon = m_address.find(':');\n\tauto host = m_address.substr(0, semicolon);\n\tauto port = atoi(m_address.substr(semicolon + 1).c_str());\n\tsockaddr_in serverName;\n\tmemset(&serverName, 0, sizeof(serverName));\n\tserverName.sin_family = AF_INET;\n\tif(host != \"*\")\n\t\tserverName.sin_addr.s_addr = inet_addr(host.c_str());\n\telse\n\t\tserverName.sin_addr.s_addr = INADDR_ANY;\n\tserverName.sin_port = htons(port);\n\n\tint rc = bind(m_socket, (sockaddr*)&serverName, sizeof(serverName));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to bind tcp socket: \" + std::to_string(rc)) + \"\/\" + std::to_string(errno));\n\n\trc = listen(m_socket, 10);\n\tif(rc < 0)\n\t{\n\t\tclose(m_socket);\n\t\tthrow IoException(std::string(\"Unable to listen socket: \" + std::to_string(rc)));\n\t}\n}\n\nTcpSocketAcceptor::~TcpSocketAcceptor()\n{\n\tclose(m_socket);\n}\n\nstd::shared_ptr TcpSocketAcceptor::waitConnection(const std::chrono::milliseconds& timeout)\n{\n\tsockaddr addr;\n\tsocklen_t clen = sizeof(addr);\n\tint newsock = accept(m_socket, &addr, &clen);\n\tif(newsock > 0)\n\t{\n\t\treturn std::make_shared(newsock, \"\");\n\t}\n\treturn std::shared_ptr();\n}\n\nTcpSocketFactory::~TcpSocketFactory()\n{\n}\n\nbool TcpSocketFactory::supportsScheme(const std::string& scheme)\n{\n\treturn scheme == \"tcp\";\n}\n\nstd::shared_ptr TcpSocketFactory::createClient(const std::string& address)\n{\n\tauto socket = std::make_shared(address);\n\tif(socket)\n\t\tsocket->connect();\n\treturn socket;\n}\n\nstd::shared_ptr TcpSocketFactory::createServer(const std::string& address)\n{\n\treturn std::make_shared(address);\n}\n\n}\n\nError message++#include \"io_socket.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace cppio\n{\n\nUnixSocket::UnixSocket(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_UNIX, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n}\n\nUnixSocket::UnixSocket(int fd, const std::string& address)\n{\n\tm_socket = fd;\n\tm_address = address;\n}\n\nUnixSocket::~UnixSocket()\n{\n\tclose(m_socket);\n\tunlink(m_address.c_str());\n}\n\nvoid UnixSocket::connect()\n{\n\tsockaddr serverName;\n\tserverName.sa_family = AF_UNIX;\n\tstrncpy(serverName.sa_data, m_address.c_str(), sizeof(serverName.sa_data));\n\n\tint rc = ::connect(m_socket, &serverName, strlen(serverName.sa_data) + sizeof(serverName.sa_family));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to connect to socket: \" + std::to_string(rc) + \"\/\" + std::to_string(errno)));\n}\n\n\nssize_t UnixSocket::read(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::read(m_socket, buffer, buflen);\n\tif(rc < 0)\n\t{\n\t\tif((errno == ECONNRESET) || (errno == ENOTCONN))\n\t\t\tthrow ConnectionLost(\"\");\n\t\treturn 0;\n\t}\n\telse if(rc == 0)\n\t{\n\t\tif(errno != ETIMEDOUT)\n\t\t\tthrow ConnectionLost(\"\");\n\t}\n\treturn rc;\n}\n\nssize_t UnixSocket::write(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::write(m_socket, buffer, buflen);\n\treturn rc;\n}\n\nvoid UnixSocket::setOption(LineOption option, void* data)\n{\n\tswitch(option)\n\t{\n\t\tcase LineOption::ReceiveTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LineOption::SendTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow UnsupportedOption(\"\");\n\t}\n}\n\nUnixSocketAcceptor::UnixSocketAcceptor(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_UNIX, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n\n\tsockaddr serverName;\n\tserverName.sa_family = AF_UNIX;\n\tstrncpy(serverName.sa_data, m_address.c_str(), sizeof(serverName.sa_data));\n\n\tint rc = bind(m_socket, &serverName, strlen(serverName.sa_data) + sizeof(serverName.sa_family));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to bind socket: \" + std::to_string(rc)));\n\n\trc = listen(m_socket, 10);\n\tif(rc < 0)\n\t{\n\t\tclose(m_socket);\n\t\tunlink(m_address.c_str());\n\t\tthrow IoException(std::string(\"Unable to listen socket: \" + std::to_string(rc)));\n\t}\n}\n\nUnixSocketAcceptor::~UnixSocketAcceptor()\n{\n\tclose(m_socket);\n\tunlink(m_address.c_str());\n}\n\nstd::shared_ptr UnixSocketAcceptor::waitConnection(const std::chrono::milliseconds& timeout)\n{\n\tsockaddr addr;\n\tsocklen_t clen = sizeof(addr);\n\tint newsock = accept(m_socket, &addr, &clen);\n\tif(newsock > 0)\n\t{\n\t\treturn std::make_shared(newsock, \"\");\n\t}\n\treturn std::shared_ptr();\n}\n\nUnixSocketFactory::~UnixSocketFactory()\n{\n}\n\nbool UnixSocketFactory::supportsScheme(const std::string& scheme)\n{\n\treturn scheme == \"local\";\n}\n\nstd::shared_ptr UnixSocketFactory::createClient(const std::string& address)\n{\n\tauto socket = std::make_shared(address);\n\tif(socket)\n\t\tsocket->connect();\n\treturn socket;\n}\n\nstd::shared_ptr UnixSocketFactory::createServer(const std::string& address)\n{\n\treturn std::make_shared(address);\n}\n\n\/\/\/\/\/\/\/\n\nTcpSocket::TcpSocket(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_INET, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n}\n\nTcpSocket::TcpSocket(int fd, const std::string& address)\n{\n\tm_socket = fd;\n\tm_address = address;\n}\n\nTcpSocket::~TcpSocket()\n{\n\tclose(m_socket);\n}\n\nvoid TcpSocket::connect()\n{\n\tauto semicolon = m_address.find(':');\n\tauto host = m_address.substr(0, semicolon);\n\tauto port = atoi(m_address.substr(semicolon + 1).c_str());\n\tsockaddr_in addr;\n\taddr.sin_family = AF_INET;\n\taddr.sin_addr.s_addr = inet_addr(host.c_str());\n\taddr.sin_port = htons(port);\n\t\n\tint rc = ::connect(m_socket, (sockaddr*)&addr, sizeof(addr));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to connect socket: \" + std::to_string(rc) + \"\/\" + std::to_string(errno)));\n}\n\n\nssize_t TcpSocket::read(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::read(m_socket, buffer, buflen);\n\tif(rc < 0)\n\t{\n\t\tif((errno == ECONNRESET) || (errno == ENOTCONN))\n\t\t\tthrow ConnectionLost(\"\");\n\t\treturn 0;\n\t}\n\telse if(rc == 0)\n\t{\n\t\tif(errno != ETIMEDOUT)\n\t\t\tthrow ConnectionLost(\"\");\n\t}\n\treturn rc;\n}\n\nssize_t TcpSocket::write(void* buffer, size_t buflen)\n{\n\tssize_t rc = ::write(m_socket, buffer, buflen);\n\treturn rc;\n}\n\nvoid TcpSocket::setOption(LineOption option, void* data)\n{\n\tswitch(option)\n\t{\n\t\tcase LineOption::ReceiveTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase LineOption::SendTimeout:\n\t\t\t{\n\t\t\t\tint msecs = *(int*)data;\n\t\t\t\tint secs = msecs \/ 1000;\n\t\t\t\tint restMsecs = msecs - secs * 1000;\n\t\t\t\tstruct timeval timeout;\n\t\t\t\ttimeout.tv_sec = secs;\n\t\t\t\ttimeout.tv_usec = restMsecs * 1000;\n\n\t\t\t\tsetsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout,\n\t\t\t\t\t\t\tsizeof(timeout));\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow UnsupportedOption(\"\");\n\t}\n}\n\nTcpSocketAcceptor::TcpSocketAcceptor(const std::string& address) : m_address(address)\n{\n\tm_socket = socket(AF_INET, SOCK_STREAM, 0);\n\tif(m_socket < 0)\n\t\tthrow IoException(std::string(\"Unable to create socket: \" + std::to_string(m_socket)));\n\n\tint enable = 1;\n\tif(setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0)\n\t\tthrow IoException(std::string(\"Unable to set socket option: \" + std::to_string(m_socket)));\n\n\n\tauto semicolon = m_address.find(':');\n\tauto host = m_address.substr(0, semicolon);\n\tauto port = atoi(m_address.substr(semicolon + 1).c_str());\n\tsockaddr_in serverName;\n\tmemset(&serverName, 0, sizeof(serverName));\n\tserverName.sin_family = AF_INET;\n\tif(host != \"*\")\n\t\tserverName.sin_addr.s_addr = inet_addr(host.c_str());\n\telse\n\t\tserverName.sin_addr.s_addr = INADDR_ANY;\n\tserverName.sin_port = htons(port);\n\n\tint rc = bind(m_socket, (sockaddr*)&serverName, sizeof(serverName));\n\tif(rc < 0)\n\t\tthrow IoException(std::string(\"Unable to bind tcp socket: \" + std::to_string(rc)) + \"\/\" + std::to_string(errno));\n\n\trc = listen(m_socket, 10);\n\tif(rc < 0)\n\t{\n\t\tclose(m_socket);\n\t\tthrow IoException(std::string(\"Unable to listen socket: \" + std::to_string(rc)));\n\t}\n}\n\nTcpSocketAcceptor::~TcpSocketAcceptor()\n{\n\tclose(m_socket);\n}\n\nstd::shared_ptr TcpSocketAcceptor::waitConnection(const std::chrono::milliseconds& timeout)\n{\n\tsockaddr addr;\n\tsocklen_t clen = sizeof(addr);\n\tint newsock = accept(m_socket, &addr, &clen);\n\tif(newsock > 0)\n\t{\n\t\treturn std::make_shared(newsock, \"\");\n\t}\n\treturn std::shared_ptr();\n}\n\nTcpSocketFactory::~TcpSocketFactory()\n{\n}\n\nbool TcpSocketFactory::supportsScheme(const std::string& scheme)\n{\n\treturn scheme == \"tcp\";\n}\n\nstd::shared_ptr TcpSocketFactory::createClient(const std::string& address)\n{\n\tauto socket = std::make_shared(address);\n\tif(socket)\n\t\tsocket->connect();\n\treturn socket;\n}\n\nstd::shared_ptr TcpSocketFactory::createServer(const std::string& address)\n{\n\treturn std::make_shared(address);\n}\n\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"coins.h\"\n#include \"random.h\"\n#include \"uint256.h\"\n#include \"test\/test_bitcoin.h\"\n\n#include \n#include \n\n#include \n\nnamespace\n{\nclass CCoinsViewTest : public CCoinsView\n{\n uint256 hashBestBlock_;\n std::map map_;\n\npublic:\n bool GetCoins(const uint256& txid, CCoins& coins) const\n {\n std::map::const_iterator it = map_.find(txid);\n if (it == map_.end()) {\n return false;\n }\n coins = it->second;\n if (coins.IsPruned() && insecure_rand() % 2 == 0) {\n \/\/ Randomly return false in case of an empty entry.\n return false;\n }\n return true;\n }\n\n bool HaveCoins(const uint256& txid) const\n {\n CCoins coins;\n return GetCoins(txid, coins);\n }\n\n uint256 GetBestBlock() const { return hashBestBlock_; }\n\n bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock)\n {\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {\n if (it->second.flags & CCoinsCacheEntry::DIRTY) {\n \/\/ Same optimization used in CCoinsViewDB is to only write dirty entries.\n map_[it->first] = it->second.coins;\n if (it->second.coins.IsPruned() && insecure_rand() % 3 == 0) {\n \/\/ Randomly delete empty entries on write.\n map_.erase(it->first);\n }\n }\n mapCoins.erase(it++);\n }\n if (!hashBlock.IsNull())\n hashBestBlock_ = hashBlock;\n return true;\n }\n\n bool GetStats(CCoinsStats& stats) const { return false; }\n};\n\nclass CCoinsViewCacheTest : public CCoinsViewCache\n{\npublic:\n CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {}\n\n void SelfTest() const\n {\n \/\/ Manually recompute the dynamic usage of the whole data, and compare it.\n size_t ret = memusage::DynamicUsage(cacheCoins);\n for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {\n ret += it->second.coins.DynamicMemoryUsage();\n }\n BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);\n }\n\n};\n\n}\n\nBOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)\n\nstatic const unsigned int NUM_SIMULATION_ITERATIONS = 40000;\n\n\/\/ This is a large randomized insert\/remove simulation test on a variable-size\n\/\/ stack of caches on top of CCoinsViewTest.\n\/\/\n\/\/ It will randomly create\/update\/delete CCoins entries to a tip of caches, with\n\/\/ txids picked from a limited list of random 256-bit hashes. Occasionally, a\n\/\/ new tip is added to the stack of caches, or the tip is flushed and removed.\n\/\/\n\/\/ During the process, booleans are kept to make sure that the randomized\n\/\/ operation hits all branches.\nBOOST_AUTO_TEST_CASE(coins_cache_simulation_test)\n{\n \/\/ Various coverage trackers.\n bool removed_all_caches = false;\n bool reached_4_caches = false;\n bool added_an_entry = false;\n bool removed_an_entry = false;\n bool updated_an_entry = false;\n bool found_an_entry = false;\n bool missed_an_entry = false;\n\n \/\/ A simple map to track what we expect the cache stack to represent.\n std::map result;\n\n \/\/ The cache stack.\n CCoinsViewTest base; \/\/ A CCoinsViewTest at the bottom.\n std::vector stack; \/\/ A stack of CCoinsViewCaches on top.\n stack.push_back(new CCoinsViewCacheTest(&base)); \/\/ Start with one cache.\n\n \/\/ Use a limited set of random transaction ids, so we do test overwriting entries.\n std::vector txids;\n txids.resize(NUM_SIMULATION_ITERATIONS \/ 8);\n for (unsigned int i = 0; i < txids.size(); i++) {\n txids[i] = GetRandHash();\n }\n\n for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {\n \/\/ Do a random modification.\n {\n uint256 txid = txids[insecure_rand() % txids.size()]; \/\/ txid we're going to modify in this iteration.\n CCoins& coins = result[txid];\n CCoinsModifier entry = stack.back()->ModifyCoins(txid);\n BOOST_CHECK(coins == *entry);\n if (insecure_rand() % 5 == 0 || coins.IsPruned()) {\n if (coins.IsPruned()) {\n added_an_entry = true;\n } else {\n updated_an_entry = true;\n }\n coins.nVersion = insecure_rand();\n coins.vout.resize(1);\n coins.vout[0].nValue = insecure_rand();\n *entry = coins;\n } else {\n coins.Clear();\n entry->Clear();\n removed_an_entry = true;\n }\n }\n\n \/\/ Once every 1000 iterations and at the end, verify the full cache.\n if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {\n for (std::map::iterator it = result.begin(); it != result.end(); it++) {\n const CCoins* coins = stack.back()->AccessCoins(it->first);\n if (coins) {\n BOOST_CHECK(*coins == it->second);\n found_an_entry = true;\n } else {\n BOOST_CHECK(it->second.IsPruned());\n missed_an_entry = true;\n }\n }\n BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {\n test->SelfTest();\n }\n }\n\n if (insecure_rand() % 100 == 0) {\n \/\/ Every 100 iterations, change the cache stack.\n if (stack.size() > 0 && insecure_rand() % 2 == 0) {\n stack.back()->Flush();\n delete stack.back();\n stack.pop_back();\n }\n if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {\n CCoinsView* tip = &base;\n if (stack.size() > 0) {\n tip = stack.back();\n } else {\n removed_all_caches = true;\n }\n stack.push_back(new CCoinsViewCacheTest(tip));\n if (stack.size() == 4) {\n reached_4_caches = true;\n }\n }\n }\n }\n\n \/\/ Clean up the stack.\n while (stack.size() > 0) {\n delete stack.back();\n stack.pop_back();\n }\n\n \/\/ Verify coverage.\n BOOST_CHECK(removed_all_caches);\n BOOST_CHECK(reached_4_caches);\n BOOST_CHECK(added_an_entry);\n BOOST_CHECK(removed_an_entry);\n BOOST_CHECK(updated_an_entry);\n BOOST_CHECK(found_an_entry);\n BOOST_CHECK(missed_an_entry);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nAdd unit test for UpdateCoins\/\/ Copyright (c) 2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"coins.h\"\n#include \"random.h\"\n#include \"uint256.h\"\n#include \"test\/test_bitcoin.h\"\n#include \"main.h\"\n#include \"consensus\/validation.h\"\n\n#include \n#include \n\n#include \n\nnamespace\n{\nclass CCoinsViewTest : public CCoinsView\n{\n uint256 hashBestBlock_;\n std::map map_;\n\npublic:\n bool GetCoins(const uint256& txid, CCoins& coins) const\n {\n std::map::const_iterator it = map_.find(txid);\n if (it == map_.end()) {\n return false;\n }\n coins = it->second;\n if (coins.IsPruned() && insecure_rand() % 2 == 0) {\n \/\/ Randomly return false in case of an empty entry.\n return false;\n }\n return true;\n }\n\n bool HaveCoins(const uint256& txid) const\n {\n CCoins coins;\n return GetCoins(txid, coins);\n }\n\n uint256 GetBestBlock() const { return hashBestBlock_; }\n\n bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock)\n {\n for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {\n if (it->second.flags & CCoinsCacheEntry::DIRTY) {\n \/\/ Same optimization used in CCoinsViewDB is to only write dirty entries.\n map_[it->first] = it->second.coins;\n if (it->second.coins.IsPruned() && insecure_rand() % 3 == 0) {\n \/\/ Randomly delete empty entries on write.\n map_.erase(it->first);\n }\n }\n mapCoins.erase(it++);\n }\n if (!hashBlock.IsNull())\n hashBestBlock_ = hashBlock;\n return true;\n }\n\n bool GetStats(CCoinsStats& stats) const { return false; }\n};\n\nclass CCoinsViewCacheTest : public CCoinsViewCache\n{\npublic:\n CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {}\n\n void SelfTest() const\n {\n \/\/ Manually recompute the dynamic usage of the whole data, and compare it.\n size_t ret = memusage::DynamicUsage(cacheCoins);\n for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {\n ret += it->second.coins.DynamicMemoryUsage();\n }\n BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);\n }\n\n};\n\n}\n\nBOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)\n\nstatic const unsigned int NUM_SIMULATION_ITERATIONS = 40000;\n\n\/\/ This is a large randomized insert\/remove simulation test on a variable-size\n\/\/ stack of caches on top of CCoinsViewTest.\n\/\/\n\/\/ It will randomly create\/update\/delete CCoins entries to a tip of caches, with\n\/\/ txids picked from a limited list of random 256-bit hashes. Occasionally, a\n\/\/ new tip is added to the stack of caches, or the tip is flushed and removed.\n\/\/\n\/\/ During the process, booleans are kept to make sure that the randomized\n\/\/ operation hits all branches.\nBOOST_AUTO_TEST_CASE(coins_cache_simulation_test)\n{\n \/\/ Various coverage trackers.\n bool removed_all_caches = false;\n bool reached_4_caches = false;\n bool added_an_entry = false;\n bool removed_an_entry = false;\n bool updated_an_entry = false;\n bool found_an_entry = false;\n bool missed_an_entry = false;\n\n \/\/ A simple map to track what we expect the cache stack to represent.\n std::map result;\n\n \/\/ The cache stack.\n CCoinsViewTest base; \/\/ A CCoinsViewTest at the bottom.\n std::vector stack; \/\/ A stack of CCoinsViewCaches on top.\n stack.push_back(new CCoinsViewCacheTest(&base)); \/\/ Start with one cache.\n\n \/\/ Use a limited set of random transaction ids, so we do test overwriting entries.\n std::vector txids;\n txids.resize(NUM_SIMULATION_ITERATIONS \/ 8);\n for (unsigned int i = 0; i < txids.size(); i++) {\n txids[i] = GetRandHash();\n }\n\n for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {\n \/\/ Do a random modification.\n {\n uint256 txid = txids[insecure_rand() % txids.size()]; \/\/ txid we're going to modify in this iteration.\n CCoins& coins = result[txid];\n CCoinsModifier entry = stack.back()->ModifyCoins(txid);\n BOOST_CHECK(coins == *entry);\n if (insecure_rand() % 5 == 0 || coins.IsPruned()) {\n if (coins.IsPruned()) {\n added_an_entry = true;\n } else {\n updated_an_entry = true;\n }\n coins.nVersion = insecure_rand();\n coins.vout.resize(1);\n coins.vout[0].nValue = insecure_rand();\n *entry = coins;\n } else {\n coins.Clear();\n entry->Clear();\n removed_an_entry = true;\n }\n }\n\n \/\/ Once every 1000 iterations and at the end, verify the full cache.\n if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {\n for (std::map::iterator it = result.begin(); it != result.end(); it++) {\n const CCoins* coins = stack.back()->AccessCoins(it->first);\n if (coins) {\n BOOST_CHECK(*coins == it->second);\n found_an_entry = true;\n } else {\n BOOST_CHECK(it->second.IsPruned());\n missed_an_entry = true;\n }\n }\n BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {\n test->SelfTest();\n }\n }\n\n if (insecure_rand() % 100 == 0) {\n \/\/ Every 100 iterations, change the cache stack.\n if (stack.size() > 0 && insecure_rand() % 2 == 0) {\n stack.back()->Flush();\n delete stack.back();\n stack.pop_back();\n }\n if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {\n CCoinsView* tip = &base;\n if (stack.size() > 0) {\n tip = stack.back();\n } else {\n removed_all_caches = true;\n }\n stack.push_back(new CCoinsViewCacheTest(tip));\n if (stack.size() == 4) {\n reached_4_caches = true;\n }\n }\n }\n }\n\n \/\/ Clean up the stack.\n while (stack.size() > 0) {\n delete stack.back();\n stack.pop_back();\n }\n\n \/\/ Verify coverage.\n BOOST_CHECK(removed_all_caches);\n BOOST_CHECK(reached_4_caches);\n BOOST_CHECK(added_an_entry);\n BOOST_CHECK(removed_an_entry);\n BOOST_CHECK(updated_an_entry);\n BOOST_CHECK(found_an_entry);\n BOOST_CHECK(missed_an_entry);\n}\n\n\/\/ This test is similar to the previous test\n\/\/ except the emphasis is on testing the functionality of UpdateCoins\n\/\/ random txs are created and UpdateCoins is used to update the cache stack\n\/\/ In particular it is tested that spending a duplicate coinbase tx\n\/\/ has the expected effect (the other duplicate is overwitten at all cache levels)\nBOOST_AUTO_TEST_CASE(updatecoins_simulation_test)\n{\n bool spent_a_duplicate_coinbase = false;\n \/\/ A simple map to track what we expect the cache stack to represent.\n std::map result;\n\n \/\/ The cache stack.\n CCoinsViewTest base; \/\/ A CCoinsViewTest at the bottom.\n std::vector stack; \/\/ A stack of CCoinsViewCaches on top.\n stack.push_back(new CCoinsViewCacheTest(&base)); \/\/ Start with one cache.\n\n \/\/ Track the txids we've used and whether they have been spent or not\n std::map coinbaseids;\n std::set alltxids;\n std::set duplicateids;\n\n for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {\n {\n CMutableTransaction tx;\n tx.vin.resize(1);\n tx.vout.resize(1);\n tx.vout[0].nValue = i; \/\/Keep txs unique unless intended to duplicate\n unsigned int height = insecure_rand();\n\n \/\/ 1\/10 times create a coinbase\n if (insecure_rand() % 10 == 0 || coinbaseids.size() < 10) {\n \/\/ 1\/100 times create a duplicate coinbase\n if (insecure_rand() % 10 == 0 && coinbaseids.size()) {\n std::map::iterator coinbaseIt = coinbaseids.lower_bound(GetRandHash());\n if (coinbaseIt == coinbaseids.end()) {\n coinbaseIt = coinbaseids.begin();\n }\n \/\/Use same random value to have same hash and be a true duplicate\n tx.vout[0].nValue = coinbaseIt->second;\n assert(tx.GetHash() == coinbaseIt->first);\n duplicateids.insert(coinbaseIt->first);\n }\n else {\n coinbaseids[tx.GetHash()] = tx.vout[0].nValue;\n }\n assert(CTransaction(tx).IsCoinBase());\n }\n \/\/ 9\/10 times create a regular tx\n else {\n uint256 prevouthash;\n \/\/ equally likely to spend coinbase or non coinbase\n std::set::iterator txIt = alltxids.lower_bound(GetRandHash());\n if (txIt == alltxids.end()) {\n txIt = alltxids.begin();\n }\n prevouthash = *txIt;\n\n \/\/ Construct the tx to spend the coins of prevouthash\n tx.vin[0].prevout.hash = prevouthash;\n tx.vin[0].prevout.n = 0;\n\n \/\/ Update the expected result of prevouthash to know these coins are spent\n CCoins& oldcoins = result[prevouthash];\n oldcoins.Clear();\n\n \/\/ It is of particular importance here that once we spend a coinbase tx hash\n \/\/ it is no longer available to be duplicated (or spent again)\n \/\/ BIP 34 in conjunction with enforcing BIP 30 (at least until BIP 34 was active)\n \/\/ results in the fact that no coinbases were duplicated after they were already spent\n alltxids.erase(prevouthash);\n coinbaseids.erase(prevouthash);\n\n \/\/ The test is designed to ensure spending a duplicate coinbase will work properly\n \/\/ if that ever happens and not resurrect the previously overwritten coinbase\n if (duplicateids.count(prevouthash))\n spent_a_duplicate_coinbase = true;\n\n assert(!CTransaction(tx).IsCoinBase());\n }\n \/\/ Track this tx to possibly spend later\n alltxids.insert(tx.GetHash());\n\n \/\/ Update the expected result to know about the new output coins\n CCoins &coins = result[tx.GetHash()];\n coins.FromTx(tx, height);\n\n CValidationState dummy;\n UpdateCoins(tx, dummy, *(stack.back()), height);\n }\n\n \/\/ Once every 1000 iterations and at the end, verify the full cache.\n if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {\n for (std::map::iterator it = result.begin(); it != result.end(); it++) {\n const CCoins* coins = stack.back()->AccessCoins(it->first);\n if (coins) {\n BOOST_CHECK(*coins == it->second);\n } else {\n BOOST_CHECK(it->second.IsPruned());\n }\n }\n }\n\n if (insecure_rand() % 100 == 0) {\n \/\/ Every 100 iterations, change the cache stack.\n if (stack.size() > 0 && insecure_rand() % 2 == 0) {\n stack.back()->Flush();\n delete stack.back();\n stack.pop_back();\n }\n if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {\n CCoinsView* tip = &base;\n if (stack.size() > 0) {\n tip = stack.back();\n }\n stack.push_back(new CCoinsViewCacheTest(tip));\n }\n }\n }\n\n \/\/ Clean up the stack.\n while (stack.size() > 0) {\n delete stack.back();\n stack.pop_back();\n }\n\n \/\/ Verify coverage.\n BOOST_CHECK(spent_a_duplicate_coinbase);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"am 51736de1: am 4c488cca: Merge \"[Asset Manager] Fix memory leakage bug\"<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev \n\/\/------------------------------------------------------------------------------\n\n#include \"ASTNodeEraser.h\"\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclVisitor.h\"\n#include \"clang\/AST\/DependentDiagnostic.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Sema\/Scope.h\"\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/\/\\brief The class does the actual work of removing a declaration and \n \/\/\/ resetting the internal structures of the compiler\n \/\/\/\n class DeclReverter : public DeclVisitor {\n private:\n Sema* m_Sema;\n\n public:\n DeclReverter(Sema* S): m_Sema(S) {}\n\n \/\/\/\\brief Function that contains common actions, done for every removal of\n \/\/\/ declaration.\n \/\/\/\n \/\/\/ For example: We must uncache the cached include, which brought that \n \/\/\/ declaration in the AST.\n \/\/\/\\param[in] D - A declaration.\n \/\/\/\n void PreVisitDecl(Decl* D);\n\n \/\/\/\\brief If it falls back in the base class just remove the declaration\n \/\/\/ only from the declaration context. \n \/\/\/ @param[in] D - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitDecl(Decl* D);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context.\n \/\/\/ @param[in] ND - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitNamedDecl(NamedDecl* ND);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context and it rebuilds the redeclaration chain.\n \/\/\/ @param[in] VD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitVarDecl(VarDecl* VD);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context and it rebuilds the redeclaration chain.\n \/\/\/ @param[in] FD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitFunctionDecl(FunctionDecl* FD);\n\n \/\/\/\\brief Removes the enumerator and its enumerator constants.\n \/\/\/ @param[in] ED - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitEnumDecl(EnumDecl* ED);\n\n\n \/\/\/\\brief Removes the namespace.\n \/\/\/ @param[in] NSD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitNamespaceDecl(NamespaceDecl* NSD);\n\n \/\/\/ @name Helpers\n \/\/\/ @{\n\n \/\/\/\\brief Checks whether the declaration was pushed onto the declaration\n \/\/\/ chains. Returns \n \/\/\/ @param[in] ND - The declaration that is being checked\n \/\/\/\n \/\/\/\\returns true if the ND was found in the lookup chain.\n \/\/\/\n bool isOnScopeChains(clang::NamedDecl* ND);\n\n \/\/\/\\brief Removes given declaration from the chain of redeclarations.\n \/\/\/ Rebuilds the chain and sets properly first and last redeclaration.\n \/\/\/ @param[in] R - The redeclarable, its chain to be rebuilt\n \/\/\/\n \/\/\/\\returns the most recent redeclaration in the new chain.\n \/\/\/\n template \n T* RemoveFromRedeclChain(clang::Redeclarable* R) {\n llvm::SmallVector PrevDecls;\n T* PrevDecl = 0;\n\n \/\/ [0]=>C [1]=>B [2]=>A ...\n while ((PrevDecl = R->getPreviousDecl())) {\n PrevDecls.push_back(PrevDecl);\n R = PrevDecl;\n }\n\n if (!PrevDecls.empty()) {\n \/\/ Put 0 in the end of the array so that the loop will reset the \n \/\/ pointer to latest redeclaration in the chain to itself.\n \/\/\n PrevDecls.push_back(0);\n\n \/\/ 0 <- A <- B <- C \n for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {\n PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);\n }\n }\n\n return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();\n }\n\n \/\/\/ @}\n };\n\n void DeclReverter::PreVisitDecl(Decl *D) {\n SourceLocation Loc = D->getLocStart();\n SourceManager& SM = m_Sema->getSourceManager();\n FileManager& FM = SM.getFileManager();\n const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));\n \/\/const FileEntry* NewEntry \n \/\/ = FM.getFile(OldEntry->getName(), \/*openFile*\/ true);\n \/\/std::string errStr = \"\";\n \/\/ SM.overrideFileContents(OldEntry, FM.getBufferForFile(NewEntry, &errStr));\n }\n\n \/\/ Gives us access to the protected members that we need.\n class DeclContextExt : public DeclContext {\n public:\n static bool removeIfLast(DeclContext* DC, Decl* D) {\n if (!D->getNextDeclInContext()) {\n \/\/ Either last (remove!), or invalid (nothing to remove)\n if (((DeclContextExt*)DC)->LastDecl == D) {\n \/\/ Valid. Thus remove.\n DC->removeDecl(D);\n return true;\n }\n } \n else {\n DC->removeDecl(D);\n return true;\n }\n\n return false;\n }\n };\n\n bool DeclReverter::VisitDecl(Decl* D) {\n assert(D && \"The Decl is null\"); \n PreVisitDecl(D);\n\n DeclContext* DC = D->getDeclContext();\n\n bool ExistsInDC = false;\n\n for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();\n E !=I; ++I) {\n if (*I == D) {\n ExistsInDC = true;\n break;\n }\n }\n\n bool Successful = DeclContextExt::removeIfLast(DC, D); \n\n \/\/ ExistsInDC && Successful \n \/\/ true false -> false \/\/ In the context but cannot delete\n \/\/ false false -> true \/\/ Not in the context cannot delete\n \/\/ true true -> true \/\/ In the context and can delete\n \/\/ false true -> assert \/\/ Not in the context but can delete ?\n assert(!(!ExistsInDC && Successful) && \"Not in the context but can delete?!\");\n if (ExistsInDC && !Successful)\n return false;\n else \/\/ in release we'd want the assert to fall into true\n return true;\n }\n\n bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {\n bool Successful = VisitDecl(ND);\n\n DeclContext* DC = ND->getDeclContext();\n \n \/\/ If the decl was removed make sure that we fix the lookup\n if (Successful) {\n Scope* S = m_Sema->getScopeForContext(DC);\n if (S)\n S->RemoveDecl(ND);\n \n if (isOnScopeChains(ND))\n m_Sema->IdResolver.RemoveDecl(ND);\n\n return true;\n }\n\n return false;\n }\n\n bool DeclReverter::VisitVarDecl(VarDecl* VD) {\n bool Successful = VisitNamedDecl(VD);\n\n DeclContext* DC = VD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false;\n StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n \n if (Pos->second.isNull())\n \/\/ We need to rewire the list of the redeclarations in order to exclude\n \/\/ the reverted one, because it gets found for example by \n \/\/ Sema::MergeVarDecl and ends up in the lookup\n \/\/\n if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {\n \n Pos->second.setOnlyValue(MostRecentVD);\n if (S)\n S->AddDecl(MostRecentVD);\n m_Sema->IdResolver.AddDecl(MostRecentVD);\n }\n\n return Successful;\n }\n\n bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {\n bool Successful = true;\n\n DeclContext* DC = FD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Template instantiation of templated function first creates a canonical\n \/\/ declaration and after the actual template specialization. For example:\n \/\/ template T TemplatedF(T t);\n \/\/ template<> int TemplatedF(int i) { return i + 1; } creates:\n \/\/ 1. Canonical decl: int TemplatedF(int i);\n \/\/ 2. int TemplatedF(int i){ return i + 1; }\n \/\/\n \/\/ The template specialization is attached to the list of specialization of\n \/\/ the templated function.\n \/\/ When TemplatedF is looked up it finds the templated function and the \n \/\/ lookup is extended by the templated function with its specializations.\n \/\/ In the end we don't need to remove the canonical decl because, it\n \/\/ doesn't end up in the lookup table.\n \/\/\n class FunctionTemplateDeclExt : public FunctionTemplateDecl {\n public:\n static llvm::FoldingSet& \n getSpecializationsExt(FunctionTemplateDecl* FTD) {\n assert(FTD && \"Cannot be null!\");\n return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();\n }\n };\n\n if (FD->isFunctionTemplateSpecialization()) {\n \/\/ 1. Remove the canonical decl.\n \/\/ TODO: Can the cannonical has another DeclContext and Scope, different\n \/\/ from the specialization's implementation?\n FunctionDecl* CanFD = FD->getCanonicalDecl();\n FunctionTemplateDecl* FTD \n = FD->getTemplateSpecializationInfo()->getTemplate();\n llvm::FoldingSet &FS \n = FunctionTemplateDeclExt::getSpecializationsExt(FTD);\n FS.RemoveNode(CanFD->getTemplateSpecializationInfo());\n }\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false; \n StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n\n if (Pos->second.getAsDecl()) {\n Successful = VisitNamedDecl(FD) && Successful;\n\n Pos = Map->find(FD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n\n if (Pos->second.isNull()) {\n \/\/ When we have template specialization we have to clean up\n if (FD->isFunctionTemplateSpecialization()) {\n while ((FD = FD->getPreviousDecl())) {\n Successful = VisitNamedDecl(FD) && Successful;\n }\n return true;\n }\n\n \/\/ We need to rewire the list of the redeclarations in order to exclude\n \/\/ the reverted one, because it gets found for example by \n \/\/ Sema::MergeVarDecl and ends up in the lookup\n \/\/\n if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {\n Pos->second.setOnlyValue(MostRecentFD);\n if (S)\n S->AddDecl(MostRecentFD);\n m_Sema->IdResolver.AddDecl(MostRecentFD);\n }\n }\n }\n else if (llvm::SmallVector* Decls \n = Pos->second.getAsVector()) {\n for(llvm::SmallVector::iterator I = Decls->begin();\n I != Decls->end(); ++I) {\n if ((*I) == FD) {\n if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {\n Successful = VisitNamedDecl(*I) && Successful;\n Decls->insert(I, MostRecentFD);\n }\n else\n Decls->erase(I);\n }\n }\n }\n\n return Successful;\n }\n\n bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {\n bool Successful = true;\n\n for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),\n E = ED->enumerator_end(); I != E; ++I) {\n assert((*I)->getDeclName() && \"EnumConstantDecl with no name?\");\n Successful = VisitNamedDecl(*I) && Successful;\n }\n\n Successful = VisitNamedDecl(ED) && Successful; \n\n return Successful;\n }\n\n bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {\n bool Successful = VisitNamedDecl(NSD);\n\n \/\/DeclContext* DC = NSD->getPrimaryContext();\n DeclContext* DC = NSD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false; \n StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n \n if (Pos->second.isNull())\n if (NSD != NSD->getOriginalNamespace()) {\n NamespaceDecl* NewNSD = NSD->getOriginalNamespace();\n Pos->second.setOnlyValue(NewNSD);\n if (S)\n S->AddDecl(NewNSD);\n m_Sema->IdResolver.AddDecl(NewNSD);\n }\n\n return Successful;\n }\n\n \/\/ See Sema::PushOnScopeChains\n bool DeclReverter::isOnScopeChains(NamedDecl* ND) {\n \n \/\/ Named decls without name shouldn't be in. Eg: struct {int a};\n if (!ND->getDeclName())\n return false;\n\n \/\/ Out-of-line definitions shouldn't be pushed into scope in C++.\n \/\/ Out-of-line variable and function definitions shouldn't even in C.\n if ((isa(ND) || isa(ND)) && ND->isOutOfLine() && \n !ND->getDeclContext()->getRedeclContext()->Equals(\n ND->getLexicalDeclContext()->getRedeclContext()))\n return false;\n\n \/\/ Template instantiations should also not be pushed into scope.\n if (isa(ND) &&\n cast(ND)->isFunctionTemplateSpecialization())\n return false;\n\n IdentifierResolver::iterator \n IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),\n IDRiEnd = m_Sema->IdResolver.end();\n \n for (; IDRi != IDRiEnd; ++IDRi) {\n if (ND == *IDRi) \n return true;\n }\n\n\n \/\/ Check if the declaration is template instantiation, which is not in\n \/\/ any DeclContext yet, because it came from \n \/\/ Sema::PerformPendingInstantiations\n \/\/ if (isa(D) && \n \/\/ cast(D)->getTemplateInstantiationPattern())\n \/\/ return false;ye\n\n\n return false;\n }\n\n ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {\n m_DeclReverter = new DeclReverter(S);\n }\n\n ASTNodeEraser::~ASTNodeEraser() {\n delete m_DeclReverter;\n m_DeclReverter = 0;\n }\n\n bool ASTNodeEraser::RevertDecl(Decl* D) {\n return m_DeclReverter->Visit(D);\n }\n\n} \/\/ end namespace cling\nComment out the method. It was checked in by accident and caused an warning.\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev \n\/\/------------------------------------------------------------------------------\n\n#include \"ASTNodeEraser.h\"\n\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/DeclVisitor.h\"\n#include \"clang\/AST\/DependentDiagnostic.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Sema\/Scope.h\"\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/\/\\brief The class does the actual work of removing a declaration and \n \/\/\/ resetting the internal structures of the compiler\n \/\/\/\n class DeclReverter : public DeclVisitor {\n private:\n Sema* m_Sema;\n\n public:\n DeclReverter(Sema* S): m_Sema(S) {}\n\n \/\/\/\\brief Function that contains common actions, done for every removal of\n \/\/\/ declaration.\n \/\/\/\n \/\/\/ For example: We must uncache the cached include, which brought that \n \/\/\/ declaration in the AST.\n \/\/\/\\param[in] D - A declaration.\n \/\/\/\n void PreVisitDecl(Decl* D);\n\n \/\/\/\\brief If it falls back in the base class just remove the declaration\n \/\/\/ only from the declaration context. \n \/\/\/ @param[in] D - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitDecl(Decl* D);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context.\n \/\/\/ @param[in] ND - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitNamedDecl(NamedDecl* ND);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context and it rebuilds the redeclaration chain.\n \/\/\/ @param[in] VD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitVarDecl(VarDecl* VD);\n\n \/\/\/\\brief Removes the declaration from the lookup chains and from the\n \/\/\/ declaration context and it rebuilds the redeclaration chain.\n \/\/\/ @param[in] FD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitFunctionDecl(FunctionDecl* FD);\n\n \/\/\/\\brief Removes the enumerator and its enumerator constants.\n \/\/\/ @param[in] ED - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitEnumDecl(EnumDecl* ED);\n\n\n \/\/\/\\brief Removes the namespace.\n \/\/\/ @param[in] NSD - The declaration to be removed.\n \/\/\/\n \/\/\/\\returns true on success.\n \/\/\/\n bool VisitNamespaceDecl(NamespaceDecl* NSD);\n\n \/\/\/ @name Helpers\n \/\/\/ @{\n\n \/\/\/\\brief Checks whether the declaration was pushed onto the declaration\n \/\/\/ chains. Returns \n \/\/\/ @param[in] ND - The declaration that is being checked\n \/\/\/\n \/\/\/\\returns true if the ND was found in the lookup chain.\n \/\/\/\n bool isOnScopeChains(clang::NamedDecl* ND);\n\n \/\/\/\\brief Removes given declaration from the chain of redeclarations.\n \/\/\/ Rebuilds the chain and sets properly first and last redeclaration.\n \/\/\/ @param[in] R - The redeclarable, its chain to be rebuilt\n \/\/\/\n \/\/\/\\returns the most recent redeclaration in the new chain.\n \/\/\/\n template \n T* RemoveFromRedeclChain(clang::Redeclarable* R) {\n llvm::SmallVector PrevDecls;\n T* PrevDecl = 0;\n\n \/\/ [0]=>C [1]=>B [2]=>A ...\n while ((PrevDecl = R->getPreviousDecl())) {\n PrevDecls.push_back(PrevDecl);\n R = PrevDecl;\n }\n\n if (!PrevDecls.empty()) {\n \/\/ Put 0 in the end of the array so that the loop will reset the \n \/\/ pointer to latest redeclaration in the chain to itself.\n \/\/\n PrevDecls.push_back(0);\n\n \/\/ 0 <- A <- B <- C \n for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {\n PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);\n }\n }\n\n return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();\n }\n\n \/\/\/ @}\n };\n\n void DeclReverter::PreVisitDecl(Decl *D) {\n \/\/SourceLocation Loc = D->getLocStart();\n \/\/SourceManager& SM = m_Sema->getSourceManager();\n \/\/FileManager& FM = SM.getFileManager();\n \/\/const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));\n \/\/const FileEntry* NewEntry \n \/\/ = FM.getFile(OldEntry->getName(), \/*openFile*\/ true);\n \/\/std::string errStr = \"\";\n \/\/ SM.overrideFileContents(OldEntry, FM.getBufferForFile(NewEntry, &errStr));\n }\n\n \/\/ Gives us access to the protected members that we need.\n class DeclContextExt : public DeclContext {\n public:\n static bool removeIfLast(DeclContext* DC, Decl* D) {\n if (!D->getNextDeclInContext()) {\n \/\/ Either last (remove!), or invalid (nothing to remove)\n if (((DeclContextExt*)DC)->LastDecl == D) {\n \/\/ Valid. Thus remove.\n DC->removeDecl(D);\n return true;\n }\n } \n else {\n DC->removeDecl(D);\n return true;\n }\n\n return false;\n }\n };\n\n bool DeclReverter::VisitDecl(Decl* D) {\n assert(D && \"The Decl is null\"); \n PreVisitDecl(D);\n\n DeclContext* DC = D->getDeclContext();\n\n bool ExistsInDC = false;\n\n for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();\n E !=I; ++I) {\n if (*I == D) {\n ExistsInDC = true;\n break;\n }\n }\n\n bool Successful = DeclContextExt::removeIfLast(DC, D); \n\n \/\/ ExistsInDC && Successful \n \/\/ true false -> false \/\/ In the context but cannot delete\n \/\/ false false -> true \/\/ Not in the context cannot delete\n \/\/ true true -> true \/\/ In the context and can delete\n \/\/ false true -> assert \/\/ Not in the context but can delete ?\n assert(!(!ExistsInDC && Successful) && \"Not in the context but can delete?!\");\n if (ExistsInDC && !Successful)\n return false;\n else \/\/ in release we'd want the assert to fall into true\n return true;\n }\n\n bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {\n bool Successful = VisitDecl(ND);\n\n DeclContext* DC = ND->getDeclContext();\n \n \/\/ If the decl was removed make sure that we fix the lookup\n if (Successful) {\n Scope* S = m_Sema->getScopeForContext(DC);\n if (S)\n S->RemoveDecl(ND);\n \n if (isOnScopeChains(ND))\n m_Sema->IdResolver.RemoveDecl(ND);\n\n return true;\n }\n\n return false;\n }\n\n bool DeclReverter::VisitVarDecl(VarDecl* VD) {\n bool Successful = VisitNamedDecl(VD);\n\n DeclContext* DC = VD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false;\n StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n \n if (Pos->second.isNull())\n \/\/ We need to rewire the list of the redeclarations in order to exclude\n \/\/ the reverted one, because it gets found for example by \n \/\/ Sema::MergeVarDecl and ends up in the lookup\n \/\/\n if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {\n \n Pos->second.setOnlyValue(MostRecentVD);\n if (S)\n S->AddDecl(MostRecentVD);\n m_Sema->IdResolver.AddDecl(MostRecentVD);\n }\n\n return Successful;\n }\n\n bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {\n bool Successful = true;\n\n DeclContext* DC = FD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Template instantiation of templated function first creates a canonical\n \/\/ declaration and after the actual template specialization. For example:\n \/\/ template T TemplatedF(T t);\n \/\/ template<> int TemplatedF(int i) { return i + 1; } creates:\n \/\/ 1. Canonical decl: int TemplatedF(int i);\n \/\/ 2. int TemplatedF(int i){ return i + 1; }\n \/\/\n \/\/ The template specialization is attached to the list of specialization of\n \/\/ the templated function.\n \/\/ When TemplatedF is looked up it finds the templated function and the \n \/\/ lookup is extended by the templated function with its specializations.\n \/\/ In the end we don't need to remove the canonical decl because, it\n \/\/ doesn't end up in the lookup table.\n \/\/\n class FunctionTemplateDeclExt : public FunctionTemplateDecl {\n public:\n static llvm::FoldingSet& \n getSpecializationsExt(FunctionTemplateDecl* FTD) {\n assert(FTD && \"Cannot be null!\");\n return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();\n }\n };\n\n if (FD->isFunctionTemplateSpecialization()) {\n \/\/ 1. Remove the canonical decl.\n \/\/ TODO: Can the cannonical has another DeclContext and Scope, different\n \/\/ from the specialization's implementation?\n FunctionDecl* CanFD = FD->getCanonicalDecl();\n FunctionTemplateDecl* FTD \n = FD->getTemplateSpecializationInfo()->getTemplate();\n llvm::FoldingSet &FS \n = FunctionTemplateDeclExt::getSpecializationsExt(FTD);\n FS.RemoveNode(CanFD->getTemplateSpecializationInfo());\n }\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false; \n StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n\n if (Pos->second.getAsDecl()) {\n Successful = VisitNamedDecl(FD) && Successful;\n\n Pos = Map->find(FD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n\n if (Pos->second.isNull()) {\n \/\/ When we have template specialization we have to clean up\n if (FD->isFunctionTemplateSpecialization()) {\n while ((FD = FD->getPreviousDecl())) {\n Successful = VisitNamedDecl(FD) && Successful;\n }\n return true;\n }\n\n \/\/ We need to rewire the list of the redeclarations in order to exclude\n \/\/ the reverted one, because it gets found for example by \n \/\/ Sema::MergeVarDecl and ends up in the lookup\n \/\/\n if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {\n Pos->second.setOnlyValue(MostRecentFD);\n if (S)\n S->AddDecl(MostRecentFD);\n m_Sema->IdResolver.AddDecl(MostRecentFD);\n }\n }\n }\n else if (llvm::SmallVector* Decls \n = Pos->second.getAsVector()) {\n for(llvm::SmallVector::iterator I = Decls->begin();\n I != Decls->end(); ++I) {\n if ((*I) == FD) {\n if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {\n Successful = VisitNamedDecl(*I) && Successful;\n Decls->insert(I, MostRecentFD);\n }\n else\n Decls->erase(I);\n }\n }\n }\n\n return Successful;\n }\n\n bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {\n bool Successful = true;\n\n for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),\n E = ED->enumerator_end(); I != E; ++I) {\n assert((*I)->getDeclName() && \"EnumConstantDecl with no name?\");\n Successful = VisitNamedDecl(*I) && Successful;\n }\n\n Successful = VisitNamedDecl(ED) && Successful; \n\n return Successful;\n }\n\n bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {\n bool Successful = VisitNamedDecl(NSD);\n\n \/\/DeclContext* DC = NSD->getPrimaryContext();\n DeclContext* DC = NSD->getDeclContext();\n Scope* S = m_Sema->getScopeForContext(DC);\n\n \/\/ Find other decls that the old one has replaced\n StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();\n if (!Map) \n return false; \n StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());\n assert(Pos != Map->end() && \"no lookup entry for decl\");\n \n if (Pos->second.isNull())\n if (NSD != NSD->getOriginalNamespace()) {\n NamespaceDecl* NewNSD = NSD->getOriginalNamespace();\n Pos->second.setOnlyValue(NewNSD);\n if (S)\n S->AddDecl(NewNSD);\n m_Sema->IdResolver.AddDecl(NewNSD);\n }\n\n return Successful;\n }\n\n \/\/ See Sema::PushOnScopeChains\n bool DeclReverter::isOnScopeChains(NamedDecl* ND) {\n \n \/\/ Named decls without name shouldn't be in. Eg: struct {int a};\n if (!ND->getDeclName())\n return false;\n\n \/\/ Out-of-line definitions shouldn't be pushed into scope in C++.\n \/\/ Out-of-line variable and function definitions shouldn't even in C.\n if ((isa(ND) || isa(ND)) && ND->isOutOfLine() && \n !ND->getDeclContext()->getRedeclContext()->Equals(\n ND->getLexicalDeclContext()->getRedeclContext()))\n return false;\n\n \/\/ Template instantiations should also not be pushed into scope.\n if (isa(ND) &&\n cast(ND)->isFunctionTemplateSpecialization())\n return false;\n\n IdentifierResolver::iterator \n IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),\n IDRiEnd = m_Sema->IdResolver.end();\n \n for (; IDRi != IDRiEnd; ++IDRi) {\n if (ND == *IDRi) \n return true;\n }\n\n\n \/\/ Check if the declaration is template instantiation, which is not in\n \/\/ any DeclContext yet, because it came from \n \/\/ Sema::PerformPendingInstantiations\n \/\/ if (isa(D) && \n \/\/ cast(D)->getTemplateInstantiationPattern())\n \/\/ return false;ye\n\n\n return false;\n }\n\n ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {\n m_DeclReverter = new DeclReverter(S);\n }\n\n ASTNodeEraser::~ASTNodeEraser() {\n delete m_DeclReverter;\n m_DeclReverter = 0;\n }\n\n bool ASTNodeEraser::RevertDecl(Decl* D) {\n return m_DeclReverter->Visit(D);\n }\n\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"\/\/ UDP sender node\n\/\/ Author: Max Schwarz \n\n#include \"udp_sender.h\"\n#include \"topic_sender.h\"\n#include \"udp_packet.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace nimbro_topic_transport\n{\n\nUDPSender::UDPSender()\n : m_msgID(0)\n{\n\tros::NodeHandle nh(\"~\");\n\n\tm_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif(m_fd < 0)\n\t{\n\t\tROS_FATAL(\"Could not create socket: %s\", strerror(errno));\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\n\tint on = 1;\n\tif(setsockopt(m_fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) != 0)\n\t{\n\t\tROS_FATAL(\"Could not enable SO_BROADCAST flag: %s\", strerror(errno));\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\t\n\tbool relay_mode;\n\tnh.param(\"relay_mode\", relay_mode, false);\n\n\tstd::string dest_host;\n\tnh.param(\"destination_addr\", dest_host, std::string(\"192.168.178.255\"));\n\n\tint dest_port;\n\tnh.param(\"destination_port\", dest_port, 5050);\n\n\tif(nh.hasParam(\"source_port\"))\n\t{\n\t\tint source_port;\n\t\tif(!nh.getParam(\"source_port\", source_port))\n\t\t{\n\t\t\tROS_FATAL(\"Invalid source_port\");\n\t\t\tthrow std::runtime_error(\"Invalid source port\");\n\t\t}\n\n\t\tsockaddr_in addr;\n\t\tmemset(&addr, 0, sizeof(addr));\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\t\taddr.sin_port = htons(source_port);\n\n\t\tif(bind(m_fd, (const sockaddr*)&addr, sizeof(addr)) != 0)\n\t\t{\n\t\t\tROS_FATAL(\"Could not bind to source port: %s\", strerror(errno));\n\t\t\tthrow std::runtime_error(strerror(errno));\n\t\t}\n\t}\n\n\tmemset(&m_addr, 0, sizeof(m_addr));\n\tm_addr.sin_addr.s_addr = inet_addr(dest_host.c_str());\n\tm_addr.sin_port = htons(dest_port);\n\tm_addr.sin_family = AF_INET;\n\n\n\tXmlRpc::XmlRpcValue list;\n\tnh.getParam(\"topics\", list);\n\n\tROS_ASSERT(list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor(int32_t i = 0; i < list.size(); ++i)\n\t{\n\t\tROS_ASSERT(list[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);\n\t\tROS_ASSERT(list[i].hasMember(\"name\"));\n\n\t\tint flags = 0;\n\t\tif(relay_mode)\n\t\t{\n\t\t\tflags |= UDP_FLAG_RELAY_MODE;\n\t\t}\n\t\t\n\t\tbool resend = false;\n\n\t\tdouble rate = 100.0;\n\t\tif(list[i].hasMember(\"rate\"))\n\t\t\trate = list[i][\"rate\"];\n\n\t\tif(list[i].hasMember(\"compress\") && ((bool)list[i][\"compress\"]))\n\t\t\tflags |= UDP_FLAG_COMPRESSED;\n\n\t\tif(list[i].hasMember(\"resend\") && ((bool)list[i][\"resend\"]))\n\t\t\tresend = true;\n\n\t\tm_senders.push_back(new TopicSender(this, &nh, list[i][\"name\"], rate, resend, flags));\n\t}\n\n\tnh.param(\"duplicate_first_packet\", m_duplicateFirstPacket, false);\n}\n\nUDPSender::~UDPSender()\n{\n\tfor(unsigned int i = 0; i < m_senders.size(); ++i)\n\t\tdelete m_senders[i];\n}\n\nuint16_t UDPSender::allocateMessageID()\n{\n\treturn m_msgID++;\n}\n\nbool UDPSender::send(void* data, uint32_t size)\n{\n\tros::Time now = ros::Time::now();\n\tros::Duration delta = now - m_lastTime;\n\n\tif(delta < ros::Duration(0.008))\n\t{\n\t\tm_sleepCounter++;\n\t\tdelta.sleep();\n\n\t\tif(m_sleepCounter > 125)\n\t\t{\n\t\t\tm_sleepCounter = 0;\n\t\t\tROS_ERROR(\"UDPSender: the 8ms rate limit is limiting communication. Please send fewer data or increase the limit!\");\n\t\t}\n\t}\n\telse\n\t\tm_sleepCounter = 0;\n\n\tif(sendto(m_fd, data, size, 0, (sockaddr*)&m_addr, sizeof(m_addr)) != size)\n\t{\n\t\tROS_ERROR(\"Could not send data of size %d: %s\", size, strerror(errno));\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nuint32_t UDPSender::getAllTopicsLastDataSize()\n{\n\tuint32_t size = 0;\n\t\n\tfor(uint32_t i = 0; i < m_senders.size(); ++i)\n\t{\n\t\tsize += m_senders[i]->getLastDataSize();\n\t}\n\t\n\treturn size;\n}\n\nvoid UDPSender::sendAllTopicsLastData()\n{\n\tfor(uint32_t i = 0; i < m_senders.size(); ++i)\n\t{\n\t\tm_senders[i]->sendLastData();\n\t}\n}\n\nvoid interrupt_handler(int s)\n{\n\texit(0);\n}\n\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"udp_sender\");\n\n\tros::NodeHandle nh(\"~\");\n\tbool relay_mode;\n\tnh.param(\"relay_mode\", relay_mode, false);\n\n\tsignal(SIGINT, &nimbro_topic_transport::interrupt_handler);\n\n\tnimbro_topic_transport::UDPSender sender;\n\tnimbro_topic_transport::BandwidthControl bwc(10, 100,\n\t\t&nimbro_topic_transport::UDPSender::getAllTopicsLastDataSize,\n\t\t&nimbro_topic_transport::UDPSender::sendAllTopicsLastData, &sender);\n\n\tif(relay_mode)\n\t{\n\t\twhile(1)\n\t\t{\n\t\t\tros::spinOnce();\n\t\t\tbwc.send();\n\t\t}\n\t}\n\telse\n\t{\n\t\tros::spin();\n\t}\n\n\treturn 0;\n}\nudp_sender: disable BWC for now, does strange things\/\/ UDP sender node\n\/\/ Author: Max Schwarz \n\n#include \"udp_sender.h\"\n#include \"topic_sender.h\"\n#include \"udp_packet.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace nimbro_topic_transport\n{\n\nUDPSender::UDPSender()\n : m_msgID(0)\n{\n\tros::NodeHandle nh(\"~\");\n\n\tm_fd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif(m_fd < 0)\n\t{\n\t\tROS_FATAL(\"Could not create socket: %s\", strerror(errno));\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\n\tint on = 1;\n\tif(setsockopt(m_fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) != 0)\n\t{\n\t\tROS_FATAL(\"Could not enable SO_BROADCAST flag: %s\", strerror(errno));\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\t\n\tbool relay_mode;\n\tnh.param(\"relay_mode\", relay_mode, false);\n\n\tstd::string dest_host;\n\tnh.param(\"destination_addr\", dest_host, std::string(\"192.168.178.255\"));\n\n\tint dest_port;\n\tnh.param(\"destination_port\", dest_port, 5050);\n\n\tif(nh.hasParam(\"source_port\"))\n\t{\n\t\tint source_port;\n\t\tif(!nh.getParam(\"source_port\", source_port))\n\t\t{\n\t\t\tROS_FATAL(\"Invalid source_port\");\n\t\t\tthrow std::runtime_error(\"Invalid source port\");\n\t\t}\n\n\t\tsockaddr_in addr;\n\t\tmemset(&addr, 0, sizeof(addr));\n\t\taddr.sin_family = AF_INET;\n\t\taddr.sin_addr.s_addr = INADDR_ANY;\n\t\taddr.sin_port = htons(source_port);\n\n\t\tif(bind(m_fd, (const sockaddr*)&addr, sizeof(addr)) != 0)\n\t\t{\n\t\t\tROS_FATAL(\"Could not bind to source port: %s\", strerror(errno));\n\t\t\tthrow std::runtime_error(strerror(errno));\n\t\t}\n\t}\n\n\tmemset(&m_addr, 0, sizeof(m_addr));\n\tm_addr.sin_addr.s_addr = inet_addr(dest_host.c_str());\n\tm_addr.sin_port = htons(dest_port);\n\tm_addr.sin_family = AF_INET;\n\n\n\tXmlRpc::XmlRpcValue list;\n\tnh.getParam(\"topics\", list);\n\n\tROS_ASSERT(list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor(int32_t i = 0; i < list.size(); ++i)\n\t{\n\t\tROS_ASSERT(list[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);\n\t\tROS_ASSERT(list[i].hasMember(\"name\"));\n\n\t\tint flags = 0;\n\t\tif(relay_mode)\n\t\t{\n\t\t\tflags |= UDP_FLAG_RELAY_MODE;\n\t\t}\n\t\t\n\t\tbool resend = false;\n\n\t\tdouble rate = 100.0;\n\t\tif(list[i].hasMember(\"rate\"))\n\t\t\trate = list[i][\"rate\"];\n\n\t\tif(list[i].hasMember(\"compress\") && ((bool)list[i][\"compress\"]))\n\t\t\tflags |= UDP_FLAG_COMPRESSED;\n\n\t\tif(list[i].hasMember(\"resend\") && ((bool)list[i][\"resend\"]))\n\t\t\tresend = true;\n\n\t\tm_senders.push_back(new TopicSender(this, &nh, list[i][\"name\"], rate, resend, flags));\n\t}\n\n\tnh.param(\"duplicate_first_packet\", m_duplicateFirstPacket, false);\n}\n\nUDPSender::~UDPSender()\n{\n\tfor(unsigned int i = 0; i < m_senders.size(); ++i)\n\t\tdelete m_senders[i];\n}\n\nuint16_t UDPSender::allocateMessageID()\n{\n\treturn m_msgID++;\n}\n\nbool UDPSender::send(void* data, uint32_t size)\n{\n\tros::Time now = ros::Time::now();\n\tros::Duration delta = now - m_lastTime;\n\n\tif(delta < ros::Duration(0.008))\n\t{\n\t\tm_sleepCounter++;\n\t\tdelta.sleep();\n\n\t\tif(m_sleepCounter > 125)\n\t\t{\n\t\t\tm_sleepCounter = 0;\n\t\t\tROS_ERROR(\"UDPSender: the 8ms rate limit is limiting communication. Please send fewer data or increase the limit!\");\n\t\t}\n\t}\n\telse\n\t\tm_sleepCounter = 0;\n\n\tif(sendto(m_fd, data, size, 0, (sockaddr*)&m_addr, sizeof(m_addr)) != size)\n\t{\n\t\tROS_ERROR(\"Could not send data of size %d: %s\", size, strerror(errno));\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nuint32_t UDPSender::getAllTopicsLastDataSize()\n{\n\tuint32_t size = 0;\n\t\n\tfor(uint32_t i = 0; i < m_senders.size(); ++i)\n\t{\n\t\tsize += m_senders[i]->getLastDataSize();\n\t}\n\t\n\treturn size;\n}\n\nvoid UDPSender::sendAllTopicsLastData()\n{\n\tfor(uint32_t i = 0; i < m_senders.size(); ++i)\n\t{\n\t\tm_senders[i]->sendLastData();\n\t}\n}\n\nvoid interrupt_handler(int s)\n{\n\texit(0);\n}\n\n}\n\nint main(int argc, char** argv)\n{\n\tros::init(argc, argv, \"udp_sender\");\n\n\tros::NodeHandle nh(\"~\");\n\tbool relay_mode;\n\tnh.param(\"relay_mode\", relay_mode, false);\n\n\tsignal(SIGINT, &nimbro_topic_transport::interrupt_handler);\n\n\tnimbro_topic_transport::UDPSender sender;\n\/\/ \tnimbro_topic_transport::BandwidthControl bwc(10, 100,\n\/\/ \t\t&nimbro_topic_transport::UDPSender::getAllTopicsLastDataSize,\n\/\/ \t\t&nimbro_topic_transport::UDPSender::sendAllTopicsLastData, &sender);\n\n\/\/ \tif(relay_mode)\n\/\/ \t{\n\/\/ \t\twhile(1)\n\/\/ \t\t{\n\/\/ \t\t\tros::spinOnce();\n\/\/ \t\t\tbwc.send();\n\/\/ \t\t}\n\/\/ \t}\n\/\/ \telse\n\t{\n\t\tros::spin();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TGLabel.cxx,v 1.18 2005\/05\/10 15:11:26 rdm Exp $\n\/\/ Author: Fons Rademakers 06\/01\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGLabel \/\/\n\/\/ \/\/\n\/\/ This class handles GUI labels. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGLabel.h\"\n#include \"TGWidget.h\"\n#include \"TGString.h\"\n#include \"TGResourcePool.h\"\n#include \"Riostream.h\"\n#include \"TColor.h\"\n\n\nconst TGFont *TGLabel::fgDefaultFont = 0;\nconst TGGC *TGLabel::fgDefaultGC = 0;\n\nClassImp(TGLabel)\n\n\/\/______________________________________________________________________________\nTGLabel::TGLabel(const TGWindow *p, TGString *text, GContext_t norm,\n FontStruct_t font, UInt_t options, ULong_t back) :\n TGFrame(p, 1, 1, options, back)\n{\n \/\/ Create a label GUI object. TGLabel will become the owner of the\n \/\/ text and will delete it in its dtor.\n\n fText = text;\n fTMode = kTextCenterX | kTextCenterY;\n fTextChanged = kTRUE;\n fFontStruct = font;\n fNormGC = norm;\n fHasOwnFont = kFALSE;\n fDisabled = kFALSE;\n\n int max_ascent, max_descent;\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n Resize(fTWidth, fTHeight + 1);\n SetWindowName();\n}\n\n\/\/______________________________________________________________________________\nTGLabel::TGLabel(const TGWindow *p, const char *text, GContext_t norm,\n FontStruct_t font, UInt_t options, ULong_t back) :\n TGFrame(p, 1, 1, options, back)\n{\n \/\/ Create a label GUI object.\n\n fText = new TGString(!text && !p ? GetName() : text);\n fTMode = kTextCenterX | kTextCenterY;\n fTextChanged = kTRUE;\n fFontStruct = font;\n fNormGC = norm;\n fHasOwnFont = kFALSE;\n fDisabled = kFALSE;\n\n int max_ascent, max_descent;\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n Resize(fTWidth, fTHeight + 1);\n SetWindowName();\n}\n\n\/\/______________________________________________________________________________\nTGLabel::~TGLabel()\n{\n \/\/ Delete label.\n\n if (fText) delete fText;\n if (fHasOwnFont) delete fClient->GetGCPool()->FindGC(fNormGC);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetText(TGString *new_text)\n{\n \/\/ Set new text in label. After calling this method one needs to call\n \/\/ the parents frame's Layout() method to force updating of the label size.\n \/\/ The new_text is adopted by the TGLabel and will be properly deleted.\n\n if (fText) delete fText;\n fText = new_text;\n fTextChanged = kTRUE;\n\n int max_ascent, max_descent;\n\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n\n \/\/ Resize is done when parent's is Layout() is called\n \/\/Resize(fTWidth, fTHeight + 1);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::DoRedraw()\n{\n \/\/ Redraw label widget.\n\n int x, y;\n\n TGFrame::DoRedraw();\n\n if (fTextChanged) {\n fTextChanged = kFALSE;\n }\n\n if (fTMode & kTextLeft)\n x = 0;\n else if (fTMode & kTextRight)\n x = fWidth - fTWidth;\n else\n x = (fWidth - fTWidth) >> 1;\n\n if (fTMode & kTextTop)\n y = 0;\n else if (fTMode & kTextBottom)\n y = fHeight - fTHeight;\n else\n y = (fHeight - fTHeight) >> 1;\n\n int max_ascent, max_descent;\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n if (!fDisabled) {\n fText->Draw(fId, GetBckgndGC()(), x +1, y +1 + max_ascent);\n fText->Draw(fId, fNormGC, x, y + max_ascent);\n } else {\n fText->Draw(fId, GetHilightGC()(), x + 1, y + 1 + max_ascent);\n fText->Draw(fId, GetShadowGC()(), x, y + max_ascent);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(FontStruct_t font, Bool_t global)\n{\n \/\/ Changes text font.\n \/\/ If global is true font is changed globally.\n\n FontH_t v = gVirtualX->GetFontHandle(font);\n if (!v) return;\n\n fTextChanged = kTRUE;\n\n fFontStruct = font;\n TGGC *gc = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n if (global) {\n gc = new TGGC(*gc); \/\/ copy\n fHasOwnFont = kTRUE;\n }\n gc->SetFont(v);\n fNormGC = gc->GetGC();\n\n int max_ascent, max_descent;\n\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n\n \/\/ Resize is done when parent's is Layout() is called\n \/\/Resize(fTWidth, fTHeight + 1);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(const char *fontName, Bool_t global)\n{\n \/\/ Changes text font specified by name.\n \/\/ If global is true font is changed globally.\n\n TGFont *font = fClient->GetFont(fontName);\n if (font) {\n SetTextFont(font->GetFontStruct(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(TGFont *font, Bool_t global)\n{\n \/\/ Changes text font specified by pointer to TGFont object.\n \/\/ If global is true font is changed globally.\n\n if (font) {\n SetTextFont(font->GetFontStruct(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextColor(Pixel_t color, Bool_t global)\n{\n \/\/ Changes text color.\n \/\/ If global is true color is changed globally\n\n TGGC *gc = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n\n if (!global) {\n gc = new TGGC(*gc); \/\/ copy\n fHasOwnFont = kTRUE;\n }\n\n gc->SetForeground(color);\n fNormGC = gc->GetGC();\n\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextColor(TColor *color, Bool_t global)\n{\n \/\/ Changes text color.\n \/\/ If global is true color is changed globally\n\n if (color) {\n SetTextColor(color->GetPixel(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextJustify(Int_t mode)\n{\n \/\/ Set text justification. Mode is an OR of the bits:\n \/\/ kTextTop, kTextLeft, kTextLeft, kTextRight, kTextCenterX and\n \/\/ kTextCenterY.\n\n fTextChanged = kTRUE;\n fTMode = mode;\n\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGLabel::HasOwnFont() const\n{\n \/\/ Returns kTRUE if text attributes are unique,\n \/\/ returns kFALSE if text attributes are shared (global).\n\n return fHasOwnFont;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a label widget as a C++ statement(s) on output stream out.\n\n char quote = '\"';\n\n \/\/ font + GC\n option = GetName()+5; \/\/ unique digit id of the name\n char parGC[50], parFont[50];\n sprintf(parFont,\"%s::GetDefaultFontStruct()\",IsA()->GetName());\n sprintf(parGC,\"%s::GetDefaultGC()()\",IsA()->GetName());\n if ((GetDefaultFontStruct() != fFontStruct) || (GetDefaultGC()() != fNormGC)) {\n TGFont *ufont = fClient->GetResourcePool()->GetFontPool()->FindFont(fFontStruct);\n if (ufont) {\n ufont->SavePrimitive(out, option);\n sprintf(parFont,\"ufont->GetFontStruct()\");\n }\n\n TGGC *userGC = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n if (userGC) {\n userGC->SavePrimitive(out, option);\n sprintf(parGC,\"uGC->GetGC()\");\n }\n }\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n TString label = GetText()->GetString();\n label.ReplaceAll(\"\\\"\",\"\\\\\\\"\");\n\n out << \" TGLabel *\";\n out << GetName() << \" = new TGLabel(\"<< fParent->GetName()\n << \",\" << quote << label << quote;\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n if (fFontStruct == GetDefaultFontStruct()) {\n if (fNormGC == GetDefaultGC()()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << parGC << \");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n if (fDisabled)\n out << \" \" << GetName() << \"->Disable();\" << endl;\n}\n\n\/\/______________________________________________________________________________\nFontStruct_t TGLabel::GetDefaultFontStruct()\n{\n \/\/ Static returning label default font struct.\n\n if (!fgDefaultFont)\n fgDefaultFont = gClient->GetResourcePool()->GetDefaultFont();\n return fgDefaultFont->GetFontStruct();\n}\n\n\/\/______________________________________________________________________________\nconst TGGC &TGLabel::GetDefaultGC()\n{\n \/\/ Static returning label default graphics context.\n\n if (!fgDefaultGC)\n fgDefaultGC = gClient->GetResourcePool()->GetFrameGC();\n return *fgDefaultGC;\n}\nFrom Ilka: Fix in TGLabel::DoRedraw() method - disabled labels were drawn with default font in spite of different font structure in use (set in the constructor or by the method TGLabel::SetTextFont). In addition, this patch fixes the reported case on Forum at: http:\/\/root.cern.ch\/phpBB2\/viewtopic.php?t=2742\/\/ @(#)root\/gui:$Name: $:$Id: TGLabel.cxx,v 1.19 2005\/09\/05 13:33:08 rdm Exp $\n\/\/ Author: Fons Rademakers 06\/01\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\/**************************************************************************\n\n This source is based on Xclass95, a Win95-looking GUI toolkit.\n Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.\n\n Xclass95 is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n**************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGLabel \/\/\n\/\/ \/\/\n\/\/ This class handles GUI labels. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGLabel.h\"\n#include \"TGWidget.h\"\n#include \"TGString.h\"\n#include \"TGResourcePool.h\"\n#include \"Riostream.h\"\n#include \"TColor.h\"\n\n\nconst TGFont *TGLabel::fgDefaultFont = 0;\nconst TGGC *TGLabel::fgDefaultGC = 0;\n\nClassImp(TGLabel)\n\n\/\/______________________________________________________________________________\nTGLabel::TGLabel(const TGWindow *p, TGString *text, GContext_t norm,\n FontStruct_t font, UInt_t options, ULong_t back) :\n TGFrame(p, 1, 1, options, back)\n{\n \/\/ Create a label GUI object. TGLabel will become the owner of the\n \/\/ text and will delete it in its dtor.\n\n fText = text;\n fTMode = kTextCenterX | kTextCenterY;\n fTextChanged = kTRUE;\n fFontStruct = font;\n fNormGC = norm;\n fHasOwnFont = kFALSE;\n fDisabled = kFALSE;\n\n int max_ascent, max_descent;\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n Resize(fTWidth, fTHeight + 1);\n SetWindowName();\n}\n\n\/\/______________________________________________________________________________\nTGLabel::TGLabel(const TGWindow *p, const char *text, GContext_t norm,\n FontStruct_t font, UInt_t options, ULong_t back) :\n TGFrame(p, 1, 1, options, back)\n{\n \/\/ Create a label GUI object.\n\n fText = new TGString(!text && !p ? GetName() : text);\n fTMode = kTextCenterX | kTextCenterY;\n fTextChanged = kTRUE;\n fFontStruct = font;\n fNormGC = norm;\n fHasOwnFont = kFALSE;\n fDisabled = kFALSE;\n\n int max_ascent, max_descent;\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n Resize(fTWidth, fTHeight + 1);\n SetWindowName();\n}\n\n\/\/______________________________________________________________________________\nTGLabel::~TGLabel()\n{\n \/\/ Delete label.\n\n if (fText) delete fText;\n if (fHasOwnFont) delete fClient->GetGCPool()->FindGC(fNormGC);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetText(TGString *new_text)\n{\n \/\/ Set new text in label. After calling this method one needs to call\n \/\/ the parents frame's Layout() method to force updating of the label size.\n \/\/ The new_text is adopted by the TGLabel and will be properly deleted.\n\n if (fText) delete fText;\n fText = new_text;\n fTextChanged = kTRUE;\n\n int max_ascent, max_descent;\n\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n\n \/\/ Resize is done when parent's is Layout() is called\n \/\/Resize(fTWidth, fTHeight + 1);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::DoRedraw()\n{\n \/\/ Redraw label widget.\n\n int x, y;\n\n TGFrame::DoRedraw();\n\n if (fTextChanged) {\n fTextChanged = kFALSE;\n }\n\n if (fTMode & kTextLeft)\n x = 0;\n else if (fTMode & kTextRight)\n x = fWidth - fTWidth;\n else\n x = (fWidth - fTWidth) >> 1;\n\n if (fTMode & kTextTop)\n y = 0;\n else if (fTMode & kTextBottom)\n y = fHeight - fTHeight;\n else\n y = (fHeight - fTHeight) >> 1;\n\n int max_ascent, max_descent;\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n if (!fDisabled) {\n fText->Draw(fId, fNormGC, x, y + max_ascent);\n } else {\n FontH_t fontH;\n if (GetDefaultFontStruct() != fFontStruct)\n fontH = gVirtualX->GetFontHandle(fFontStruct);\n else\n fontH = gVirtualX->GetFontHandle(GetDefaultFontStruct());\n TGGC *gc;\n gc = fClient->GetResourcePool()->GetGCPool()->FindGC(GetHilightGC()());\n gc->SetFont(fontH);\n fText->Draw(fId, gc->GetGC(), x + 1, y + 1 + max_ascent);\n gc = fClient->GetResourcePool()->GetGCPool()->FindGC(GetShadowGC()());\n gc->SetFont(fontH);\n fText->Draw(fId, gc->GetGC(), x, y + max_ascent);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(FontStruct_t font, Bool_t global)\n{\n \/\/ Changes text font.\n \/\/ If global is true font is changed globally.\n\n FontH_t v = gVirtualX->GetFontHandle(font);\n if (!v) return;\n\n fTextChanged = kTRUE;\n\n fFontStruct = font;\n TGGC *gc = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n if (global) {\n gc = new TGGC(*gc); \/\/ copy\n fHasOwnFont = kTRUE;\n }\n gc->SetFont(v);\n fNormGC = gc->GetGC();\n\n int max_ascent, max_descent;\n\n fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());\n gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);\n fTHeight = max_ascent + max_descent;\n\n \/\/ Resize is done when parent's is Layout() is called\n \/\/Resize(fTWidth, fTHeight + 1);\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(const char *fontName, Bool_t global)\n{\n \/\/ Changes text font specified by name.\n \/\/ If global is true font is changed globally.\n\n TGFont *font = fClient->GetFont(fontName);\n if (font) {\n SetTextFont(font->GetFontStruct(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextFont(TGFont *font, Bool_t global)\n{\n \/\/ Changes text font specified by pointer to TGFont object.\n \/\/ If global is true font is changed globally.\n\n if (font) {\n SetTextFont(font->GetFontStruct(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextColor(Pixel_t color, Bool_t global)\n{\n \/\/ Changes text color.\n \/\/ If global is true color is changed globally\n\n TGGC *gc = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n\n if (!global) {\n gc = new TGGC(*gc); \/\/ copy\n fHasOwnFont = kTRUE;\n }\n\n gc->SetForeground(color);\n fNormGC = gc->GetGC();\n\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextColor(TColor *color, Bool_t global)\n{\n \/\/ Changes text color.\n \/\/ If global is true color is changed globally\n\n if (color) {\n SetTextColor(color->GetPixel(), global);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SetTextJustify(Int_t mode)\n{\n \/\/ Set text justification. Mode is an OR of the bits:\n \/\/ kTextTop, kTextLeft, kTextLeft, kTextRight, kTextCenterX and\n \/\/ kTextCenterY.\n\n fTextChanged = kTRUE;\n fTMode = mode;\n\n fClient->NeedRedraw(this);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGLabel::HasOwnFont() const\n{\n \/\/ Returns kTRUE if text attributes are unique,\n \/\/ returns kFALSE if text attributes are shared (global).\n\n return fHasOwnFont;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLabel::SavePrimitive(ofstream &out, Option_t *option)\n{\n \/\/ Save a label widget as a C++ statement(s) on output stream out.\n\n char quote = '\"';\n\n \/\/ font + GC\n option = GetName()+5; \/\/ unique digit id of the name\n char parGC[50], parFont[50];\n sprintf(parFont,\"%s::GetDefaultFontStruct()\",IsA()->GetName());\n sprintf(parGC,\"%s::GetDefaultGC()()\",IsA()->GetName());\n if ((GetDefaultFontStruct() != fFontStruct) || (GetDefaultGC()() != fNormGC)) {\n TGFont *ufont = fClient->GetResourcePool()->GetFontPool()->FindFont(fFontStruct);\n if (ufont) {\n ufont->SavePrimitive(out, option);\n sprintf(parFont,\"ufont->GetFontStruct()\");\n }\n\n TGGC *userGC = fClient->GetResourcePool()->GetGCPool()->FindGC(fNormGC);\n if (userGC) {\n userGC->SavePrimitive(out, option);\n sprintf(parGC,\"uGC->GetGC()\");\n }\n }\n\n if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);\n\n TString label = GetText()->GetString();\n label.ReplaceAll(\"\\\"\",\"\\\\\\\"\");\n\n out << \" TGLabel *\";\n out << GetName() << \" = new TGLabel(\"<< fParent->GetName()\n << \",\" << quote << label << quote;\n if (fBackground == GetDefaultFrameBackground()) {\n if (!GetOptions()) {\n if (fFontStruct == GetDefaultFontStruct()) {\n if (fNormGC == GetDefaultGC()()) {\n out <<\");\" << endl;\n } else {\n out << \",\" << parGC << \");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \",\" << GetOptionString() <<\");\" << endl;\n }\n } else {\n out << \",\" << parGC << \",\" << parFont << \",\" << GetOptionString() << \",ucolor);\" << endl;\n }\n\n if (fDisabled)\n out << \" \" << GetName() << \"->Disable();\" << endl;\n}\n\n\/\/______________________________________________________________________________\nFontStruct_t TGLabel::GetDefaultFontStruct()\n{\n \/\/ Static returning label default font struct.\n\n if (!fgDefaultFont)\n fgDefaultFont = gClient->GetResourcePool()->GetDefaultFont();\n return fgDefaultFont->GetFontStruct();\n}\n\n\/\/______________________________________________________________________________\nconst TGGC &TGLabel::GetDefaultGC()\n{\n \/\/ Static returning label default graphics context.\n\n if (!fgDefaultGC)\n fgDefaultGC = gClient->GetResourcePool()->GetFrameGC();\n return *fgDefaultGC;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/cloud_policy_data_store.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_backend.pb.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_constants.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/system\/statistics_provider.h\"\n#endif\n\nnamespace {\n\n#if defined(OS_CHROMEOS)\n\/\/ MachineInfo key names.\nconst char kMachineInfoSystemHwqual[] = \"hardware_class\";\n\n\/\/ These are the machine serial number keys that we check in order until we\n\/\/ find a non-empty serial number. The VPD spec says the serial number should be\n\/\/ in the \"serial_number\" key for v2+ VPDs. However, we cannot check this first,\n\/\/ since we'd get the \"serial_number\" value from the SMBIOS (yes, there's a name\n\/\/ clash here!), which is different from the serial number we want and not\n\/\/ actually per-device. So, we check the the legacy keys first. If we find a\n\/\/ serial number for these, we use it, otherwise we must be on a newer device\n\/\/ that provides the correct data in \"serial_number\".\nconst char* kMachineInfoSerialNumberKeys[] = {\n \"sn\", \/\/ ZGB\n \"Product_S\/N\", \/\/ Alex\n \"serial_number\" \/\/ VPD v2+ devices\n};\n#endif\n\n} \/\/ namespace\n\nnamespace policy {\n\nCloudPolicyDataStore::~CloudPolicyDataStore() {}\n\n\/\/ static\nCloudPolicyDataStore* CloudPolicyDataStore::CreateForUserPolicies() {\n return new CloudPolicyDataStore(em::DeviceRegisterRequest::USER,\n kChromeUserPolicyType,\n \"\", \"\");\n}\n\n\/\/ static\nCloudPolicyDataStore* CloudPolicyDataStore::CreateForDevicePolicies() {\n std::string machine_model;\n std::string machine_id;\n\n#if defined(OS_CHROMEOS)\n chromeos::system::StatisticsProvider* provider =\n chromeos::system::StatisticsProvider::GetInstance();\n if (!provider->GetMachineStatistic(kMachineInfoSystemHwqual,\n &machine_model)) {\n LOG(ERROR) << \"Failed to get machine model.\";\n }\n for (unsigned int i = 0; i < arraysize(kMachineInfoSerialNumberKeys); i++) {\n if (provider->GetMachineStatistic(kMachineInfoSerialNumberKeys[i],\n &machine_id) &&\n !machine_id.empty()) {\n break;\n }\n }\n\n if (machine_id.empty())\n LOG(ERROR) << \"Failed to get machine serial number.\";\n#endif\n\n return new CloudPolicyDataStore(em::DeviceRegisterRequest::DEVICE,\n kChromeDevicePolicyType,\n machine_model,\n machine_id);\n}\n\nCloudPolicyDataStore::CloudPolicyDataStore(\n const em::DeviceRegisterRequest_Type policy_register_type,\n const std::string& policy_type,\n const std::string& machine_model,\n const std::string& machine_id)\n : policy_register_type_(policy_register_type),\n policy_type_(policy_type),\n machine_model_(machine_model),\n machine_id_(machine_id),\n token_cache_loaded_(false) {}\n\nvoid CloudPolicyDataStore::SetDeviceToken(const std::string& device_token,\n bool from_cache) {\n DCHECK(token_cache_loaded_ != from_cache);\n if (!token_cache_loaded_) {\n \/\/ The cache should be the first to set the token. (It may be \"\")\n DCHECK(from_cache);\n token_cache_loaded_ = true;\n } else {\n \/\/ The cache should never set the token later.\n DCHECK(!from_cache);\n }\n device_token_ = device_token;\n token_cache_loaded_ = true;\n NotifyDeviceTokenChanged();\n}\n\nvoid CloudPolicyDataStore::SetGaiaToken(const std::string& gaia_token) {\n DCHECK(!user_name_.empty());\n gaia_token_ = gaia_token;\n NotifyCredentialsChanged();\n}\n\nvoid CloudPolicyDataStore::SetOAuthToken(const std::string& oauth_token) {\n DCHECK(!user_name_.empty());\n oauth_token_ = oauth_token;\n NotifyCredentialsChanged();\n}\n\nvoid CloudPolicyDataStore::Reset() {\n user_name_ = \"\";\n gaia_token_ = \"\";\n device_id_ = \"\";\n device_token_ = \"\";\n}\n\nvoid CloudPolicyDataStore::SetupForTesting(const std::string& device_token,\n const std::string& device_id,\n const std::string& user_name,\n const std::string& gaia_token,\n bool token_cache_loaded) {\n device_id_ = device_id;\n user_name_ = user_name;\n gaia_token_ = gaia_token;\n device_token_ = device_token;\n token_cache_loaded_ = token_cache_loaded;\n}\n\nvoid CloudPolicyDataStore::set_device_id(const std::string& device_id) {\n device_id_ = device_id;\n}\n\nconst std::string& CloudPolicyDataStore::device_id() const {\n return device_id_;\n}\n\nvoid CloudPolicyDataStore::set_user_name(const std::string& user_name) {\n user_name_ = user_name;\n}\n\nconst std::string& CloudPolicyDataStore::device_token() const {\n return device_token_;\n}\n\nconst std::string& CloudPolicyDataStore::gaia_token() const {\n return gaia_token_;\n}\n\nconst std::string& CloudPolicyDataStore::oauth_token() const {\n return oauth_token_;\n}\n\nbool CloudPolicyDataStore::has_auth_token() const {\n return !oauth_token_.empty() || !gaia_token_.empty();\n}\n\nconst std::string& CloudPolicyDataStore::machine_id() const {\n return machine_id_;\n}\n\nconst std::string& CloudPolicyDataStore::machine_model() const {\n return machine_model_;\n}\n\nem::DeviceRegisterRequest_Type\nCloudPolicyDataStore::policy_register_type() const {\n return policy_register_type_;\n}\n\nconst std::string& CloudPolicyDataStore::policy_type() const {\n return policy_type_;\n}\n\nbool CloudPolicyDataStore::token_cache_loaded() const {\n return token_cache_loaded_;\n}\n\nconst std::string& CloudPolicyDataStore::user_name() const {\n return user_name_;\n}\n\nvoid CloudPolicyDataStore::AddObserver(\n CloudPolicyDataStore::Observer* observer) {\n observer_list_.AddObserver(observer);\n}\n\nvoid CloudPolicyDataStore::RemoveObserver(\n CloudPolicyDataStore::Observer* observer) {\n observer_list_.RemoveObserver(observer);\n}\n\nvoid CloudPolicyDataStore::NotifyCredentialsChanged() {\n FOR_EACH_OBSERVER(Observer, observer_list_, OnCredentialsChanged());\n}\n\nvoid CloudPolicyDataStore::NotifyDeviceTokenChanged() {\n FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenChanged());\n}\n\n} \/\/ namespace policy\nEnterprise Enrollment: Add legacy serial number key for Mario devices.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/policy\/cloud_policy_data_store.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/compiler_specific.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_backend.pb.h\"\n#include \"chrome\/browser\/policy\/proto\/device_management_constants.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/system\/statistics_provider.h\"\n#endif\n\nnamespace {\n\n#if defined(OS_CHROMEOS)\n\/\/ MachineInfo key names.\nconst char kMachineInfoSystemHwqual[] = \"hardware_class\";\n\n\/\/ These are the machine serial number keys that we check in order until we\n\/\/ find a non-empty serial number. The VPD spec says the serial number should be\n\/\/ in the \"serial_number\" key for v2+ VPDs. However, we cannot check this first,\n\/\/ since we'd get the \"serial_number\" value from the SMBIOS (yes, there's a name\n\/\/ clash here!), which is different from the serial number we want and not\n\/\/ actually per-device. So, we check the the legacy keys first. If we find a\n\/\/ serial number for these, we use it, otherwise we must be on a newer device\n\/\/ that provides the correct data in \"serial_number\".\nconst char* kMachineInfoSerialNumberKeys[] = {\n \"sn\", \/\/ ZGB\n \"Product_S\/N\", \/\/ Alex\n \"Product_SN\", \/\/ Mario\n \"serial_number\" \/\/ VPD v2+ devices\n};\n#endif\n\n} \/\/ namespace\n\nnamespace policy {\n\nCloudPolicyDataStore::~CloudPolicyDataStore() {}\n\n\/\/ static\nCloudPolicyDataStore* CloudPolicyDataStore::CreateForUserPolicies() {\n return new CloudPolicyDataStore(em::DeviceRegisterRequest::USER,\n kChromeUserPolicyType,\n \"\", \"\");\n}\n\n\/\/ static\nCloudPolicyDataStore* CloudPolicyDataStore::CreateForDevicePolicies() {\n std::string machine_model;\n std::string machine_id;\n\n#if defined(OS_CHROMEOS)\n chromeos::system::StatisticsProvider* provider =\n chromeos::system::StatisticsProvider::GetInstance();\n if (!provider->GetMachineStatistic(kMachineInfoSystemHwqual,\n &machine_model)) {\n LOG(ERROR) << \"Failed to get machine model.\";\n }\n for (unsigned int i = 0; i < arraysize(kMachineInfoSerialNumberKeys); i++) {\n if (provider->GetMachineStatistic(kMachineInfoSerialNumberKeys[i],\n &machine_id) &&\n !machine_id.empty()) {\n break;\n }\n }\n\n if (machine_id.empty())\n LOG(ERROR) << \"Failed to get machine serial number.\";\n#endif\n\n return new CloudPolicyDataStore(em::DeviceRegisterRequest::DEVICE,\n kChromeDevicePolicyType,\n machine_model,\n machine_id);\n}\n\nCloudPolicyDataStore::CloudPolicyDataStore(\n const em::DeviceRegisterRequest_Type policy_register_type,\n const std::string& policy_type,\n const std::string& machine_model,\n const std::string& machine_id)\n : policy_register_type_(policy_register_type),\n policy_type_(policy_type),\n machine_model_(machine_model),\n machine_id_(machine_id),\n token_cache_loaded_(false) {}\n\nvoid CloudPolicyDataStore::SetDeviceToken(const std::string& device_token,\n bool from_cache) {\n DCHECK(token_cache_loaded_ != from_cache);\n if (!token_cache_loaded_) {\n \/\/ The cache should be the first to set the token. (It may be \"\")\n DCHECK(from_cache);\n token_cache_loaded_ = true;\n } else {\n \/\/ The cache should never set the token later.\n DCHECK(!from_cache);\n }\n device_token_ = device_token;\n token_cache_loaded_ = true;\n NotifyDeviceTokenChanged();\n}\n\nvoid CloudPolicyDataStore::SetGaiaToken(const std::string& gaia_token) {\n DCHECK(!user_name_.empty());\n gaia_token_ = gaia_token;\n NotifyCredentialsChanged();\n}\n\nvoid CloudPolicyDataStore::SetOAuthToken(const std::string& oauth_token) {\n DCHECK(!user_name_.empty());\n oauth_token_ = oauth_token;\n NotifyCredentialsChanged();\n}\n\nvoid CloudPolicyDataStore::Reset() {\n user_name_ = \"\";\n gaia_token_ = \"\";\n device_id_ = \"\";\n device_token_ = \"\";\n}\n\nvoid CloudPolicyDataStore::SetupForTesting(const std::string& device_token,\n const std::string& device_id,\n const std::string& user_name,\n const std::string& gaia_token,\n bool token_cache_loaded) {\n device_id_ = device_id;\n user_name_ = user_name;\n gaia_token_ = gaia_token;\n device_token_ = device_token;\n token_cache_loaded_ = token_cache_loaded;\n}\n\nvoid CloudPolicyDataStore::set_device_id(const std::string& device_id) {\n device_id_ = device_id;\n}\n\nconst std::string& CloudPolicyDataStore::device_id() const {\n return device_id_;\n}\n\nvoid CloudPolicyDataStore::set_user_name(const std::string& user_name) {\n user_name_ = user_name;\n}\n\nconst std::string& CloudPolicyDataStore::device_token() const {\n return device_token_;\n}\n\nconst std::string& CloudPolicyDataStore::gaia_token() const {\n return gaia_token_;\n}\n\nconst std::string& CloudPolicyDataStore::oauth_token() const {\n return oauth_token_;\n}\n\nbool CloudPolicyDataStore::has_auth_token() const {\n return !oauth_token_.empty() || !gaia_token_.empty();\n}\n\nconst std::string& CloudPolicyDataStore::machine_id() const {\n return machine_id_;\n}\n\nconst std::string& CloudPolicyDataStore::machine_model() const {\n return machine_model_;\n}\n\nem::DeviceRegisterRequest_Type\nCloudPolicyDataStore::policy_register_type() const {\n return policy_register_type_;\n}\n\nconst std::string& CloudPolicyDataStore::policy_type() const {\n return policy_type_;\n}\n\nbool CloudPolicyDataStore::token_cache_loaded() const {\n return token_cache_loaded_;\n}\n\nconst std::string& CloudPolicyDataStore::user_name() const {\n return user_name_;\n}\n\nvoid CloudPolicyDataStore::AddObserver(\n CloudPolicyDataStore::Observer* observer) {\n observer_list_.AddObserver(observer);\n}\n\nvoid CloudPolicyDataStore::RemoveObserver(\n CloudPolicyDataStore::Observer* observer) {\n observer_list_.RemoveObserver(observer);\n}\n\nvoid CloudPolicyDataStore::NotifyCredentialsChanged() {\n FOR_EACH_OBSERVER(Observer, observer_list_, OnCredentialsChanged());\n}\n\nvoid CloudPolicyDataStore::NotifyDeviceTokenChanged() {\n FOR_EACH_OBSERVER(Observer, observer_list_, OnDeviceTokenChanged());\n}\n\n} \/\/ namespace policy\n<|endoftext|>"} {"text":"#include \"gui_main_window.h\"\n#include \"ui_gui_main_window.h\"\n#include \"parse_batch.h\"\n#include \"..\/decompose_imf_lib\/optimization_task.h\"\n#include \"..\/cpp_utils\/std_make_unique.h\"\n\n#include \n\nnamespace gui {\n\nstruct MainWindow::Impl\n{\n std::list optParams;\n Ui::MainWindow ui;\n dimf::OptimizationTask optTask;\n\n void updateState()\n {\n ui.runNextOptimizationPushButton->setEnabled( !optParams.empty() );\n\/* ui.statusBar->showMessage(\n QString(\"%1 optimization runs left.\")\n .arg(optParams.size()) );*\/\n }\n};\n\nMainWindow::MainWindow(QWidget *parent)\n : QMainWindow{parent}\n , m{ std::make_unique() }\n{\n m->ui.setupUi(this);\n m->updateState();\n}\n\nMainWindow::~MainWindow()\n{\n}\n\nvoid MainWindow::parse()\n{\n auto optParams = parseBatch(\n std::istringstream(\n m->ui.textEditor->toPlainText().toStdString()) );\n for ( auto & optParam : optParams )\n m->optParams.push_back( std::move(optParam) );\n m->updateState();\n}\n\nvoid MainWindow::runNextOptimization()\n{\n m->optTask.restart( m->optParams.front() );\n m->optParams.pop_front();\n m->updateState();\n}\n\n} \/\/ namespace gui\nThe statusbar now shows the number of remaining optimization tasks.#include \"gui_main_window.h\"\n#include \"ui_gui_main_window.h\"\n#include \"parse_batch.h\"\n#include \"..\/decompose_imf_lib\/optimization_task.h\"\n#include \"..\/cpp_utils\/std_make_unique.h\"\n\n#include \n\nnamespace gui {\n\nstruct MainWindow::Impl\n{\n std::list optParams;\n Ui::MainWindow ui;\n dimf::OptimizationTask optTask;\n\n void updateState()\n {\n ui.runNextOptimizationPushButton->setEnabled( !optParams.empty() );\n ui.statusbar->showMessage(\n QString(\"%1 optimization runs left.\")\n .arg(optParams.size()) );\n }\n};\n\nMainWindow::MainWindow(QWidget *parent)\n : QMainWindow{parent}\n , m{ std::make_unique() }\n{\n m->ui.setupUi(this);\n m->updateState();\n}\n\nMainWindow::~MainWindow()\n{\n}\n\nvoid MainWindow::parse()\n{\n auto optParams = parseBatch(\n std::istringstream(\n m->ui.textEditor->toPlainText().toStdString()) );\n for ( auto & optParam : optParams )\n m->optParams.push_back( std::move(optParam) );\n m->updateState();\n}\n\nvoid MainWindow::runNextOptimization()\n{\n m->optTask.restart( m->optParams.front() );\n m->optParams.pop_front();\n m->updateState();\n}\n\n} \/\/ namespace gui\n<|endoftext|>"} {"text":"#include \"AConfig.h\"\n#if(HAS_CAMERASERVO)\n\n\/\/ Includes\n#include \n#include \n#include \n\n#include \"CCameraServo.h\"\n#include \"CServo.h\"\n#include \"CPin.h\"\n#include \"NConfigManager.h\"\n#include \"NDataManager.h\"\n#include \"NModuleManager.h\"\n#include \"NCommManager.h\"\n#include \"CTimer.h\"\n\n#include \"CControllerBoard.h\"\n\n\/\/ Defines\n#ifndef F_CPU\n #define F_CPU 16000000UL\n#endif\n\n\/\/ File local variables and methods\nnamespace\n{\n \/\/ Helper functions specifically for the HITEC servo\n constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false )\n {\n return static_cast( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs );\n }\n\n constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false )\n {\n return ( isInverted ? -( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec )\n :( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) );\n }\n\n constexpr float kZeroPosMicrosecs = 1487.0f;\n constexpr float kMicrosecPerDegree = 9.523809f;\n constexpr float kDegPerMicrosec = ( 1 \/ kMicrosecPerDegree );\n\n constexpr float kNeutralPosition_deg = 0.0f;\n constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f );\n\n constexpr float kDefaultSpeed = 50.0f; \/\/ Degrees per sec\n\n \/\/ Attributes\n CTimer m_controlTimer;\n CTimer m_telemetryTimer;\n\n float m_targetPos_deg = kNeutralPosition_deg;\n float m_currentPos_deg = kNeutralPosition_deg;\n uint32_t m_targetPos_us = kNeutralPosition_us;\n uint32_t m_currentPos_us = kNeutralPosition_us;\n float m_fCurrentPos_us = kZeroPosMicrosecs;\n\n uint32_t m_tDelta = 0;\n uint32_t m_tLast = 0;\n\n \/\/ Settings\n float m_speed_deg_per_s = kDefaultSpeed;\n int m_isInverted = 0; \/\/ 0 - Not inverted, 1 - Inverted\n\n \/\/ Derived from settings\n float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree;\n\n \/\/ Float<->Int conversion helpers\n constexpr int32_t Encode( float valueIn )\n {\n return static_cast( valueIn * 1000.0f );\n }\n\n constexpr float Decode( int32_t valueIn )\n {\n return ( static_cast( valueIn ) * 0.001f );\n }\n\n void SetServoPosition( uint32_t microsecondsIn )\n {\n \/\/ Set to 90° --> pulsewdith = 1.5ms\n OCR1A = microsecondsIn * 2;\n }\n}\n\nvoid CCameraServo::Initialize()\n{\n \/\/ Set up the pin for the camera servo\n pinMode( CAMERAMOUNT_PIN, OUTPUT );\n\n \/\/ Set up the timers driving the PWM for the servo (AVR specific)\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 );\t\t\t\t\t\/\/ non-inverting mode for OC1A\n TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 );\t\/\/ Mode 14, Prescaler 8\n\n ICR1 = 40000; \/\/ 320000 \/ 8 = 40000\n\n \/\/ Set initial position\n SetServoPosition( kNeutralPosition_us );\n\n \/\/ Mark camera servo as enabled\n NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE );\n\n \/\/ Reset timers\n m_controlTimer.Reset();\n m_telemetryTimer.Reset();\n}\n\nvoid CCameraServo::Update( CCommand& command )\n{\n \/\/ Check for messages\n if( NCommManager::m_isCommandAvailable )\n {\n \/\/ Handle messages\n if( command.Equals( \"camServ_tpos\" ) )\n {\n \/\/ TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism\n \/\/ Acknowledge target position\n Serial.print( F( \"camServ_tpos:\" ) );\n Serial.print( command.m_arguments[1] );\n Serial.println( ';' );\n \n \/\/ Update the target position\n m_targetPos_deg = Decode( command.m_arguments[1] );\n\n \/\/ Update the target microseconds\n m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted );\n }\n else if( command.Equals( \"camServ_spd\" ) )\n {\n \/\/ Acknowledge receipt of command\n Serial.print( F( \"camServ_spd:\" ) );\n Serial.print( command.m_arguments[1] );\n Serial.println( ';' );\n\n \/\/ Decode the requested speed and update the setting\n m_speed_deg_per_s = Decode( command.m_arguments[1] );\n m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree;\n }\n else if( command.Equals( \"camServ_inv\" ) )\n {\n if( command.m_arguments[1] == 1 )\n {\n \/\/ Set inverted\n m_isInverted = 1;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:1;\" ) );\n }\n else if( command.m_arguments[1] == 0 )\n {\n \/\/ Set uninverted\n m_isInverted = 0;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:0;\" ) );\n }\n }\n }\n\n \/\/ Run servo adjustment at 200Hz\n if( m_controlTimer.HasElapsed( 5 ) )\n {\n \/\/ Get time elapsed since last position update\n m_tDelta = millis() - m_tLast;\n\n \/\/ Update position if not at desired location\n if( m_currentPos_us != m_targetPos_us )\n {\n float error = static_cast( m_targetPos_us ) - m_fCurrentPos_us;\n\n \/\/ Check to see if the error\/dT is smaller than the speed limit\n if( ( error \/ static_cast( m_tDelta ) ) < m_speed_us_per_ms )\n {\n \/\/ Move directly to the target\n \/\/ NOTE: Cannot use the cast method like below, since the floating point\n \/\/ representation of the target pos might be comparatively less than the integer value.\n \/\/ I.e. target = 32, static_cast( 32 ) -> 31.99999, static_cast( 31.99999 ) -> 31\n \/\/ This could lead to the current position never reaching the target\n m_currentPos_us = m_targetPos_us;\n\n \/\/ Update the floating point representation as well, for use in future target updates\n m_fCurrentPos_us = static_cast( m_targetPos_us );\n }\n else\n {\n \/\/ Move by the delta towards the target\n m_fCurrentPos_us += ( m_speed_us_per_ms * error );\n\n \/\/ Cast the floating point servo command to an integer\n m_currentPos_us = static_cast( m_fCurrentPos_us );\n }\n \n \/\/ Set the servo to this target\n SetServoPosition( m_currentPos_us );\n\n \/\/ Update the position value in degrees\n m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us );\n }\n\n m_tLast = millis();\n }\n\n \/\/ Emit position telemetry at 10Hz\n if( m_telemetryTimer.HasElapsed( 100 ) )\n {\n Serial.print( F( \"camServ_pos:\" ) );\n Serial.print( Encode( m_currentPos_deg ) );\n Serial.println( ';' );\n }\n}\n\n#endif\nFixed ordering of variables#include \"AConfig.h\"\n#if(HAS_CAMERASERVO)\n\n\/\/ Includes\n#include \n#include \n#include \n\n#include \"CCameraServo.h\"\n#include \"CServo.h\"\n#include \"CPin.h\"\n#include \"NConfigManager.h\"\n#include \"NDataManager.h\"\n#include \"NModuleManager.h\"\n#include \"NCommManager.h\"\n#include \"CTimer.h\"\n\n#include \"CControllerBoard.h\"\n\n\/\/ Defines\n#ifndef F_CPU\n #define F_CPU 16000000UL\n#endif\n\n\/\/ File local variables and methods\nnamespace\n{\n constexpr float kZeroPosMicrosecs = 1487.0f;\n constexpr float kMicrosecPerDegree = 9.523809f;\n constexpr float kDegPerMicrosec = ( 1 \/ kMicrosecPerDegree );\n\n \/\/ Helper functions specifically for the HITEC servo\n constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false )\n {\n return static_cast( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs );\n }\n\n constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false )\n {\n return ( isInverted ? -( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec )\n :( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) );\n }\n\n constexpr float kNeutralPosition_deg = 0.0f;\n constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f );\n\n constexpr float kDefaultSpeed = 50.0f; \/\/ Degrees per sec\n\n \/\/ Attributes\n CTimer m_controlTimer;\n CTimer m_telemetryTimer;\n\n float m_targetPos_deg = kNeutralPosition_deg;\n float m_currentPos_deg = kNeutralPosition_deg;\n uint32_t m_targetPos_us = kNeutralPosition_us;\n uint32_t m_currentPos_us = kNeutralPosition_us;\n float m_fCurrentPos_us = kZeroPosMicrosecs;\n\n uint32_t m_tDelta = 0;\n uint32_t m_tLast = 0;\n\n \/\/ Settings\n float m_speed_deg_per_s = kDefaultSpeed;\n int m_isInverted = 0; \/\/ 0 - Not inverted, 1 - Inverted\n\n \/\/ Derived from settings\n float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree;\n\n \/\/ Float<->Int conversion helpers\n constexpr int32_t Encode( float valueIn )\n {\n return static_cast( valueIn * 1000.0f );\n }\n\n constexpr float Decode( int32_t valueIn )\n {\n return ( static_cast( valueIn ) * 0.001f );\n }\n\n void SetServoPosition( uint32_t microsecondsIn )\n {\n \/\/ Set to 90° --> pulsewdith = 1.5ms\n OCR1A = microsecondsIn * 2;\n }\n}\n\nvoid CCameraServo::Initialize()\n{\n \/\/ Set up the pin for the camera servo\n pinMode( CAMERAMOUNT_PIN, OUTPUT );\n\n \/\/ Set up the timers driving the PWM for the servo (AVR specific)\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 );\t\t\t\t\t\/\/ non-inverting mode for OC1A\n TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 );\t\/\/ Mode 14, Prescaler 8\n\n ICR1 = 40000; \/\/ 320000 \/ 8 = 40000\n\n \/\/ Set initial position\n SetServoPosition( kNeutralPosition_us );\n\n \/\/ Mark camera servo as enabled\n NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE );\n\n \/\/ Reset timers\n m_controlTimer.Reset();\n m_telemetryTimer.Reset();\n}\n\nvoid CCameraServo::Update( CCommand& command )\n{\n \/\/ Check for messages\n if( NCommManager::m_isCommandAvailable )\n {\n \/\/ Handle messages\n if( command.Equals( \"camServ_tpos\" ) )\n {\n \/\/ TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism\n \/\/ Acknowledge target position\n Serial.print( F( \"camServ_tpos:\" ) );\n Serial.print( command.m_arguments[1] );\n Serial.println( ';' );\n \n \/\/ Update the target position\n m_targetPos_deg = Decode( command.m_arguments[1] );\n\n \/\/ Update the target microseconds\n m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted );\n }\n else if( command.Equals( \"camServ_spd\" ) )\n {\n \/\/ Acknowledge receipt of command\n Serial.print( F( \"camServ_spd:\" ) );\n Serial.print( command.m_arguments[1] );\n Serial.println( ';' );\n\n \/\/ Decode the requested speed and update the setting\n m_speed_deg_per_s = Decode( command.m_arguments[1] );\n m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree;\n }\n else if( command.Equals( \"camServ_inv\" ) )\n {\n if( command.m_arguments[1] == 1 )\n {\n \/\/ Set inverted\n m_isInverted = 1;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:1;\" ) );\n }\n else if( command.m_arguments[1] == 0 )\n {\n \/\/ Set uninverted\n m_isInverted = 0;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:0;\" ) );\n }\n }\n }\n\n \/\/ Run servo adjustment at 200Hz\n if( m_controlTimer.HasElapsed( 5 ) )\n {\n \/\/ Get time elapsed since last position update\n m_tDelta = millis() - m_tLast;\n\n \/\/ Update position if not at desired location\n if( m_currentPos_us != m_targetPos_us )\n {\n float error = static_cast( m_targetPos_us ) - m_fCurrentPos_us;\n\n \/\/ Check to see if the error\/dT is smaller than the speed limit\n if( ( error \/ static_cast( m_tDelta ) ) < m_speed_us_per_ms )\n {\n \/\/ Move directly to the target\n \/\/ NOTE: Cannot use the cast method like below, since the floating point\n \/\/ representation of the target pos might be comparatively less than the integer value.\n \/\/ I.e. target = 32, static_cast( 32 ) -> 31.99999, static_cast( 31.99999 ) -> 31\n \/\/ This could lead to the current position never reaching the target\n m_currentPos_us = m_targetPos_us;\n\n \/\/ Update the floating point representation as well, for use in future target updates\n m_fCurrentPos_us = static_cast( m_targetPos_us );\n }\n else\n {\n \/\/ Move by the delta towards the target\n m_fCurrentPos_us += ( m_speed_us_per_ms * error );\n\n \/\/ Cast the floating point servo command to an integer\n m_currentPos_us = static_cast( m_fCurrentPos_us );\n }\n \n \/\/ Set the servo to this target\n SetServoPosition( m_currentPos_us );\n\n \/\/ Update the position value in degrees\n m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us );\n }\n\n m_tLast = millis();\n }\n\n \/\/ Emit position telemetry at 10Hz\n if( m_telemetryTimer.HasElapsed( 100 ) )\n {\n Serial.print( F( \"camServ_pos:\" ) );\n Serial.print( Encode( m_currentPos_deg ) );\n Serial.println( ';' );\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/prefs\/pref_value_store.h\"\n#include \"chrome\/browser\/sync\/signin_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/ntp\/new_tab_ui.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/testing_pref_service.h\"\n\nclass NewTabUITest : public UITest {\n public:\n NewTabUITest() {\n dom_automation_enabled_ = true;\n \/\/ Set home page to the empty string so that we can set the home page using\n \/\/ preferences.\n set_homepage(\"\");\n\n \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n ProxyLauncher::DEFAULT_THEME));\n }\n};\n\nTEST_F(NewTabUITest, NTPHasThumbnails) {\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ TopSites should return at least 3 non-filler pages.\n \/\/ 8 - 3 = max 5 filler pages.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('filler').length <= 5)\",\n TestTimeouts::action_max_timeout_ms()));\n}\n\n\/\/ Sometimes hangs: http:\/\/crbug.com\/70157\nTEST_F(NewTabUITest, DISABLED_NTPHasLoginName) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername,\n \"user@gmail.com\"));\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n std::wstring displayed_username;\n \/\/ The login span should be eventually populated and have the\n \/\/ correct value.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementById('login-username').innerText.length > 0)\",\n TestTimeouts::action_max_timeout_ms()));\n\n ASSERT_TRUE(tab->ExecuteAndExtractString(\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementById('login-username').innerText)\",\n &displayed_username));\n\n EXPECT_EQ(L\"user@gmail.com\", displayed_username);\n}\n\n\/\/ Loads chrome:\/\/hang\/ into two NTP tabs, ensuring we don't crash.\n\/\/ See http:\/\/crbug.com\/59859.\nTEST_F(NewTabUITest, ChromeHangInNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ Navigate to chrome:\/\/hang\/ to stall the process.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n\n \/\/ Visit chrome:\/\/hang\/ again in another NTP. Don't bother waiting for the\n \/\/ NTP to load, because it's hung.\n ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB));\n scoped_refptr tab2 = window->GetActiveTab();\n ASSERT_TRUE(tab2.get());\n ASSERT_TRUE(tab2->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n}\n\n\/\/ Allows testing NTP in process-per-tab mode.\nclass NewTabUIProcessPerTabTest : public NewTabUITest {\n public:\n NewTabUIProcessPerTabTest() : NewTabUITest() {}\n\n protected:\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kProcessPerTab);\n UITest::SetUp();\n }\n};\n\n\/\/ Navigates away from NTP before it commits, in process-per-tab mode.\n\/\/ Ensures that we don't load the normal page in the NTP process (and thus\n\/\/ crash), as in http:\/\/crbug.com\/69224.\nTEST_F(NewTabUIProcessPerTabTest, NavBeforeNTPCommits) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ Navigate to chrome:\/\/hang\/ to stall the process.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n\n \/\/ Visit a normal URL in another NTP that hasn't committed.\n ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB));\n scoped_refptr tab2 = window->GetActiveTab();\n ASSERT_TRUE(tab2.get());\n ASSERT_TRUE(tab2->NavigateToURL(GURL(\"data:text\/html,hello world\")));\n}\n\n\/\/ Fails about ~5% of the time on all platforms. http:\/\/crbug.com\/45001\nTEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n scoped_refptr tab = window->GetTab(0);\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Ensure there are some thumbnails loaded in the page.\n int thumbnails_count = -1;\n ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('thumbnail-container').length)\",\n &thumbnails_count));\n EXPECT_GT(thumbnails_count, 0);\n}\n\nTEST_F(NewTabUITest, UpdateUserPrefsVersion) {\n \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n scoped_ptr prefs(new TestingPrefService);\n\n \/\/ Does the migration\n NewTabUI::RegisterUserPrefs(prefs.get());\n\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs->GetInteger(prefs::kNTPPrefVersion));\n\n \/\/ Reset the version\n prefs->ClearPref(prefs::kNTPPrefVersion);\n ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));\n\n bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n ASSERT_TRUE(migrated);\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs->GetInteger(prefs::kNTPPrefVersion));\n\n migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n ASSERT_FALSE(migrated);\n}\nMark NewTabUITest.NTPHasThumbnails as flaky on Linux.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/prefs\/pref_value_store.h\"\n#include \"chrome\/browser\/sync\/signin_manager.h\"\n#include \"chrome\/browser\/ui\/webui\/ntp\/new_tab_ui.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/testing_pref_service.h\"\n\nclass NewTabUITest : public UITest {\n public:\n NewTabUITest() {\n dom_automation_enabled_ = true;\n \/\/ Set home page to the empty string so that we can set the home page using\n \/\/ preferences.\n set_homepage(\"\");\n\n \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n ProxyLauncher::DEFAULT_THEME));\n }\n};\n\n#if defined(OS_LINUX)\n\/\/ This test is flaky on Linux and CrOS: http:\/\/crbug\/\n#define MAYBE_NTPHasThumbnails FLAKY_NTPHasThumbnails\n#else\n#define MAYBE_NTPHasThumbnails NTPHasThumbnails\n#endif\nTEST_F(NewTabUITest, MAYBE_NTPHasThumbnails) {\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ TopSites should return at least 3 non-filler pages.\n \/\/ 8 - 3 = max 5 filler pages.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('filler').length <= 5)\",\n TestTimeouts::action_max_timeout_ms()));\n}\n\n\/\/ Sometimes hangs: http:\/\/crbug.com\/70157\nTEST_F(NewTabUITest, DISABLED_NTPHasLoginName) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername,\n \"user@gmail.com\"));\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n std::wstring displayed_username;\n \/\/ The login span should be eventually populated and have the\n \/\/ correct value.\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementById('login-username').innerText.length > 0)\",\n TestTimeouts::action_max_timeout_ms()));\n\n ASSERT_TRUE(tab->ExecuteAndExtractString(\n L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementById('login-username').innerText)\",\n &displayed_username));\n\n EXPECT_EQ(L\"user@gmail.com\", displayed_username);\n}\n\n\/\/ Loads chrome:\/\/hang\/ into two NTP tabs, ensuring we don't crash.\n\/\/ See http:\/\/crbug.com\/59859.\nTEST_F(NewTabUITest, ChromeHangInNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ Navigate to chrome:\/\/hang\/ to stall the process.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n\n \/\/ Visit chrome:\/\/hang\/ again in another NTP. Don't bother waiting for the\n \/\/ NTP to load, because it's hung.\n ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB));\n scoped_refptr tab2 = window->GetActiveTab();\n ASSERT_TRUE(tab2.get());\n ASSERT_TRUE(tab2->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n}\n\n\/\/ Allows testing NTP in process-per-tab mode.\nclass NewTabUIProcessPerTabTest : public NewTabUITest {\n public:\n NewTabUIProcessPerTabTest() : NewTabUITest() {}\n\n protected:\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kProcessPerTab);\n UITest::SetUp();\n }\n};\n\n\/\/ Navigates away from NTP before it commits, in process-per-tab mode.\n\/\/ Ensures that we don't load the normal page in the NTP process (and thus\n\/\/ crash), as in http:\/\/crbug.com\/69224.\nTEST_F(NewTabUIProcessPerTabTest, NavBeforeNTPCommits) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ Navigate to chrome:\/\/hang\/ to stall the process.\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kChromeUIHangURL)));\n\n \/\/ Visit a normal URL in another NTP that hasn't committed.\n ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB));\n scoped_refptr tab2 = window->GetActiveTab();\n ASSERT_TRUE(tab2.get());\n ASSERT_TRUE(tab2->NavigateToURL(GURL(\"data:text\/html,hello world\")));\n}\n\n\/\/ Fails about ~5% of the time on all platforms. http:\/\/crbug.com\/45001\nTEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n scoped_refptr tab = window->GetTab(0);\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Ensure there are some thumbnails loaded in the page.\n int thumbnails_count = -1;\n ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('thumbnail-container').length)\",\n &thumbnails_count));\n EXPECT_GT(thumbnails_count, 0);\n}\n\nTEST_F(NewTabUITest, UpdateUserPrefsVersion) {\n \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n scoped_ptr prefs(new TestingPrefService);\n\n \/\/ Does the migration\n NewTabUI::RegisterUserPrefs(prefs.get());\n\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs->GetInteger(prefs::kNTPPrefVersion));\n\n \/\/ Reset the version\n prefs->ClearPref(prefs::kNTPPrefVersion);\n ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion));\n\n bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n ASSERT_TRUE(migrated);\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs->GetInteger(prefs::kNTPPrefVersion));\n\n migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get());\n ASSERT_FALSE(migrated);\n}\n<|endoftext|>"} {"text":"#include \"AConfig.h\"\n#if(HAS_CAMERASERVO)\n\n\/\/ Includes\n#include \n#include \n#include \n\n#include \"CCameraServo.h\"\n#include \"CServo.h\"\n#include \"CPin.h\"\n#include \"NConfigManager.h\"\n#include \"NDataManager.h\"\n#include \"NModuleManager.h\"\n#include \"NCommManager.h\"\n#include \"CTimer.h\"\n\n#include \"CControllerBoard.h\"\n\n\/\/ Defines\n#ifndef F_CPU\n #define F_CPU 16000000UL\n#endif\n\n\/\/ File local variables and methods\nnamespace\n{\n constexpr float kZeroPosMicrosecs = 1487.0f;\n constexpr float kMicrosecPerDegree = 9.523809f;\n constexpr float kDegPerMicrosec = ( 1 \/ kMicrosecPerDegree );\n\n \/\/ Helper functions specifically for the HITEC servo\n constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false )\n {\n return static_cast( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs );\n }\n\n constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false )\n {\n return ( isInverted ? -( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec )\n :( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) );\n }\n\n constexpr float kNeutralPosition_deg = 0.0f;\n constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f );\n\n constexpr float kDefaultSpeed = 50.0f; \/\/ Degrees per sec\n\n \/\/ Attributes\n CTimer m_controlTimer;\n CTimer m_telemetryTimer;\n\n float m_targetPos_deg = kNeutralPosition_deg;\n float m_currentPos_deg = kNeutralPosition_deg;\n uint32_t m_targetPos_us = kNeutralPosition_us;\n uint32_t m_currentPos_us = kNeutralPosition_us;\n float m_fCurrentPos_us = kZeroPosMicrosecs;\n\n uint32_t m_tDelta = 0;\n uint32_t m_tLast = 0;\n\n \/\/ Settings\n float m_speed_deg_per_s = kDefaultSpeed;\n int m_isInverted = 0; \/\/ 0 - Not inverted, 1 - Inverted\n\n \/\/ Derived from settings\n float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree;\n\n \/\/ Float<->Int conversion helpers\n constexpr int32_t Encode( float valueIn )\n {\n return static_cast( valueIn * 1000.0f );\n }\n\n constexpr float Decode( int32_t valueIn )\n {\n return ( static_cast( valueIn ) * 0.001f );\n }\n\n void SetServoPosition( uint32_t microsecondsIn )\n {\n \/\/ Set to 90° --> pulsewdith = 1.5ms\n OCR1A = microsecondsIn * 2;\n }\n}\n\nvoid CCameraServo::Initialize()\n{\n \/\/ Set up the pin for the camera servo\n pinMode( CAMERAMOUNT_PIN, OUTPUT );\n\n \/\/ Set up the timers driving the PWM for the servo (AVR specific)\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 );\t\t\t\t\t\/\/ non-inverting mode for OC1A\n TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 );\t\/\/ Mode 14, Prescaler 8\n\n ICR1 = 40000; \/\/ 320000 \/ 8 = 40000\n\n \/\/ Set initial position\n SetServoPosition( kNeutralPosition_us );\n\n \/\/ Mark camera servo as enabled\n NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE );\n\n \/\/ Reset timers\n m_controlTimer.Reset();\n m_telemetryTimer.Reset();\n}\n\nvoid CCameraServo::Update( CCommand& command )\n{\n \/\/ Check for messages\n if( NCommManager::m_isCommandAvailable )\n {\n \/\/ Handle messages\n if( command.Equals( \"camServ_tpos\" ) )\n {\n \/\/ TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism\n \/\/ Acknowledge target position\n Serial.print( F( \"camServ_tpos:\" ) );\n Serial.print( static_cast( command.m_arguments[1] ) );\n Serial.println( ';' );\n \n \/\/ Update the target position\n m_targetPos_deg = Decode( static_cast( command.m_arguments[1] ) );\n\n \/\/ Update the target microseconds\n m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted );\n }\n else if( command.Equals( \"camServ_spd\" ) )\n {\n \/\/ Acknowledge receipt of command\n Serial.print( F( \"camServ_spd:\" ) );\n Serial.print( static_cast( command.m_arguments[1] ) );\n Serial.println( ';' );\n\n \/\/ Decode the requested speed and update the setting\n m_speed_deg_per_s = Decode( static_cast( command.m_arguments[1] ) );\n m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree;\n }\n else if( command.Equals( \"camServ_inv\" ) )\n {\n if( command.m_arguments[1] == 1 )\n {\n \/\/ Set inverted\n m_isInverted = 1;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:1;\" ) );\n }\n else if( command.m_arguments[1] == 0 )\n {\n \/\/ Set uninverted\n m_isInverted = 0;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:0;\" ) );\n }\n }\n }\n\n \/\/ Run servo adjustment at 200Hz\n if( m_controlTimer.HasElapsed( 5 ) )\n {\n \/\/ Get time elapsed since last position update\n m_tDelta = millis() - m_tLast;\n\n \/\/ Update position if not at desired location\n if( m_currentPos_us != m_targetPos_us )\n {\n float error = static_cast( m_targetPos_us ) - m_fCurrentPos_us;\n\n \/\/ Check to see if the error\/dT is smaller than the speed limit\n if( ( error \/ static_cast( m_tDelta ) ) < m_speed_us_per_ms )\n {\n \/\/ Move directly to the target\n \/\/ NOTE: Cannot use the cast method like below, since the floating point\n \/\/ representation of the target pos might be comparatively less than the integer value.\n \/\/ I.e. target = 32, static_cast( 32 ) -> 31.99999, static_cast( 31.99999 ) -> 31\n \/\/ This could lead to the current position never reaching the target\n m_currentPos_us = m_targetPos_us;\n\n \/\/ Update the floating point representation as well, for use in future target updates\n m_fCurrentPos_us = static_cast( m_targetPos_us );\n }\n else\n {\n \/\/ Move by the delta towards the target\n m_fCurrentPos_us += ( m_speed_us_per_ms * static_cast( m_tDelta ) );\n\n \/\/ Cast the floating point servo command to an integer\n m_currentPos_us = static_cast( m_fCurrentPos_us );\n }\n \n \/\/ Set the servo to this target\n SetServoPosition( m_currentPos_us );\n\n \/\/ Update the position value in degrees\n m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us );\n }\n\n m_tLast = millis();\n }\n\n \/\/ Emit position telemetry at 10Hz\n if( m_telemetryTimer.HasElapsed( 100 ) )\n {\n Serial.print( F( \"camServ_pos:\" ) );\n Serial.print( Encode( m_currentPos_deg ) );\n Serial.println( ';' );\n }\n}\n\n#endif\nTook absolute of error which was causing immediate snaps on negative transitions#include \"AConfig.h\"\n#if(HAS_CAMERASERVO)\n\n\/\/ Includes\n#include \n#include \n#include \n\n#include \"CCameraServo.h\"\n#include \"CServo.h\"\n#include \"CPin.h\"\n#include \"NConfigManager.h\"\n#include \"NDataManager.h\"\n#include \"NModuleManager.h\"\n#include \"NCommManager.h\"\n#include \"CTimer.h\"\n\n#include \"CControllerBoard.h\"\n\n#include \n\n\/\/ Defines\n#ifndef F_CPU\n #define F_CPU 16000000UL\n#endif\n\n\/\/ File local variables and methods\nnamespace\n{\n constexpr float kZeroPosMicrosecs = 1487.0f;\n constexpr float kMicrosecPerDegree = 9.523809f;\n constexpr float kDegPerMicrosec = ( 1 \/ kMicrosecPerDegree );\n\n \/\/ Helper functions specifically for the HITEC servo\n constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false )\n {\n return static_cast( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs );\n }\n\n constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false )\n {\n return ( isInverted ? -( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec )\n :( ( static_cast( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) );\n }\n\n constexpr float kNeutralPosition_deg = 0.0f;\n constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f );\n\n constexpr float kDefaultSpeed = 50.0f; \/\/ Degrees per sec\n\n \/\/ Attributes\n CTimer m_controlTimer;\n CTimer m_telemetryTimer;\n\n float m_targetPos_deg = kNeutralPosition_deg;\n float m_currentPos_deg = kNeutralPosition_deg;\n uint32_t m_targetPos_us = kNeutralPosition_us;\n uint32_t m_currentPos_us = kNeutralPosition_us;\n float m_fCurrentPos_us = kZeroPosMicrosecs;\n\n uint32_t m_tDelta = 0;\n uint32_t m_tLast = 0;\n\n \/\/ Settings\n float m_speed_deg_per_s = kDefaultSpeed;\n int m_isInverted = 0; \/\/ 0 - Not inverted, 1 - Inverted\n\n \/\/ Derived from settings\n float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree;\n\n \/\/ Float<->Int conversion helpers\n constexpr int32_t Encode( float valueIn )\n {\n return static_cast( valueIn * 1000.0f );\n }\n\n constexpr float Decode( int32_t valueIn )\n {\n return ( static_cast( valueIn ) * 0.001f );\n }\n\n void SetServoPosition( uint32_t microsecondsIn )\n {\n \/\/ Set to 90° --> pulsewdith = 1.5ms\n OCR1A = microsecondsIn * 2;\n }\n}\n\nvoid CCameraServo::Initialize()\n{\n \/\/ Set up the pin for the camera servo\n pinMode( CAMERAMOUNT_PIN, OUTPUT );\n\n \/\/ Set up the timers driving the PWM for the servo (AVR specific)\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 );\t\t\t\t\t\/\/ non-inverting mode for OC1A\n TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 );\t\/\/ Mode 14, Prescaler 8\n\n ICR1 = 40000; \/\/ 320000 \/ 8 = 40000\n\n \/\/ Set initial position\n SetServoPosition( kNeutralPosition_us );\n\n \/\/ Mark camera servo as enabled\n NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE );\n\n \/\/ Reset timers\n m_controlTimer.Reset();\n m_telemetryTimer.Reset();\n}\n\nvoid CCameraServo::Update( CCommand& command )\n{\n \/\/ Check for messages\n if( NCommManager::m_isCommandAvailable )\n {\n \/\/ Handle messages\n if( command.Equals( \"camServ_tpos\" ) )\n {\n \/\/ TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism\n \/\/ Acknowledge target position\n Serial.print( F( \"camServ_tpos:\" ) );\n Serial.print( static_cast( command.m_arguments[1] ) );\n Serial.println( ';' );\n \n \/\/ Update the target position\n m_targetPos_deg = Decode( static_cast( command.m_arguments[1] ) );\n\n \/\/ Update the target microseconds\n m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted );\n }\n else if( command.Equals( \"camServ_spd\" ) )\n {\n \/\/ Acknowledge receipt of command\n Serial.print( F( \"camServ_spd:\" ) );\n Serial.print( static_cast( command.m_arguments[1] ) );\n Serial.println( ';' );\n\n \/\/ Decode the requested speed and update the setting\n m_speed_deg_per_s = Decode( static_cast( command.m_arguments[1] ) );\n m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree;\n }\n else if( command.Equals( \"camServ_inv\" ) )\n {\n if( command.m_arguments[1] == 1 )\n {\n \/\/ Set inverted\n m_isInverted = 1;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:1;\" ) );\n }\n else if( command.m_arguments[1] == 0 )\n {\n \/\/ Set uninverted\n m_isInverted = 0;\n\n \/\/ Report back\n Serial.print( F( \"camServ_inv:0;\" ) );\n }\n }\n }\n\n \/\/ Run servo adjustment at 200Hz\n if( m_controlTimer.HasElapsed( 5 ) )\n {\n \/\/ Get time elapsed since last position update\n m_tDelta = millis() - m_tLast;\n\n \/\/ Update position if not at desired location\n if( m_currentPos_us != m_targetPos_us )\n {\n float error = static_cast( m_targetPos_us ) - m_fCurrentPos_us;\n\n \/\/ Check to see if the error\/dT is smaller than the speed limit\n if( abs( error \/ static_cast( m_tDelta ) ) < m_speed_us_per_ms )\n {\n \/\/ Move directly to the target\n \/\/ NOTE: Cannot use the cast method like below, since the floating point\n \/\/ representation of the target pos might be comparatively less than the integer value.\n \/\/ I.e. target = 32, static_cast( 32 ) -> 31.99999, static_cast( 31.99999 ) -> 31\n \/\/ This could lead to the current position never reaching the target\n m_currentPos_us = m_targetPos_us;\n\n \/\/ Update the floating point representation as well, for use in future target updates\n m_fCurrentPos_us = static_cast( m_targetPos_us );\n }\n else\n {\n \/\/ Move by the delta towards the target\n m_fCurrentPos_us += ( m_speed_us_per_ms * static_cast( m_tDelta ) );\n\n \/\/ Cast the floating point servo command to an integer\n m_currentPos_us = static_cast( m_fCurrentPos_us );\n }\n \n \/\/ Set the servo to this target\n SetServoPosition( m_currentPos_us );\n\n \/\/ Update the position value in degrees\n m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us );\n }\n\n m_tLast = millis();\n }\n\n \/\/ Emit position telemetry at 10Hz\n if( m_telemetryTimer.HasElapsed( 100 ) )\n {\n Serial.print( F( \"camServ_pos:\" ) );\n Serial.print( Encode( m_currentPos_deg ) );\n Serial.println( ';' );\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/print_preview_handler.h\"\n\n#include \"base\/threading\/thread.h\"\n#include \"base\/values.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"printing\/backend\/print_backend.h\"\n\nclass EnumeratePrintersTaskProxy\n : public base::RefCountedThreadSafe {\n public:\n EnumeratePrintersTaskProxy(const base::WeakPtr& handler,\n printing::PrintBackend* print_backend)\n : handler_(handler),\n print_backend_(print_backend) {\n }\n\n void EnumeratePrinters() {\n ListValue* printers = new ListValue;\n\n printing::PrinterList printer_list;\n print_backend_->EnumeratePrinters(&printer_list);\n for (printing::PrinterList::iterator index = printer_list.begin();\n index != printer_list.end(); ++index) {\n printers->Append(new StringValue(index->printer_name));\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &EnumeratePrintersTaskProxy::SendPrinterList,\n printers));\n }\n\n void SendPrinterList(ListValue* printers) {\n if (handler_)\n handler_->SendPrinterList(*printers);\n delete printers;\n }\n\n private:\n base::WeakPtr handler_;\n\n scoped_refptr print_backend_;\n\n DISALLOW_COPY_AND_ASSIGN(EnumeratePrintersTaskProxy);\n};\n\nPrintPreviewHandler::PrintPreviewHandler()\n : print_backend_(printing::PrintBackend::CreateInstance(NULL)) {\n}\n\nPrintPreviewHandler::~PrintPreviewHandler() {\n}\n\nvoid PrintPreviewHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(\"getPrinters\",\n NewCallback(this, &PrintPreviewHandler::HandleGetPrinters));\n web_ui_->RegisterMessageCallback(\"print\",\n NewCallback(this, &PrintPreviewHandler::HandlePrint));\n}\n\nvoid PrintPreviewHandler::HandleGetPrinters(const ListValue*) {\n scoped_refptr task =\n new EnumeratePrintersTaskProxy(AsWeakPtr(), print_backend_.get());\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(task.get(),\n &EnumeratePrintersTaskProxy::EnumeratePrinters));\n}\n\nvoid PrintPreviewHandler::HandlePrint(const ListValue*) {\n web_ui_->GetRenderViewHost()->PrintForPrintPreview();\n}\n\nvoid PrintPreviewHandler::SendPrinterList(const ListValue& printers) {\n web_ui_->CallJavascriptFunction(L\"setPrinters\", printers);\n}\nPrint Preview: Make sure EnumeratePrintersTaskProxy gets deleted on the right thread.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/print_preview_handler.h\"\n\n#include \"base\/threading\/thread.h\"\n#include \"base\/values.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"printing\/backend\/print_backend.h\"\n\nclass EnumeratePrintersTaskProxy\n : public base::RefCountedThreadSafe {\n public:\n EnumeratePrintersTaskProxy(const base::WeakPtr& handler,\n printing::PrintBackend* print_backend)\n : handler_(handler),\n print_backend_(print_backend) {\n }\n\n void EnumeratePrinters() {\n ListValue* printers = new ListValue;\n\n printing::PrinterList printer_list;\n print_backend_->EnumeratePrinters(&printer_list);\n for (printing::PrinterList::iterator index = printer_list.begin();\n index != printer_list.end(); ++index) {\n printers->Append(new StringValue(index->printer_name));\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &EnumeratePrintersTaskProxy::SendPrinterList,\n printers));\n }\n\n void SendPrinterList(ListValue* printers) {\n if (handler_)\n handler_->SendPrinterList(*printers);\n delete printers;\n }\n\n private:\n friend struct BrowserThread::DeleteOnThread;\n friend class DeleteTask;\n\n ~EnumeratePrintersTaskProxy() {}\n\n base::WeakPtr handler_;\n\n scoped_refptr print_backend_;\n\n DISALLOW_COPY_AND_ASSIGN(EnumeratePrintersTaskProxy);\n};\n\nPrintPreviewHandler::PrintPreviewHandler()\n : print_backend_(printing::PrintBackend::CreateInstance(NULL)) {\n}\n\nPrintPreviewHandler::~PrintPreviewHandler() {\n}\n\nvoid PrintPreviewHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(\"getPrinters\",\n NewCallback(this, &PrintPreviewHandler::HandleGetPrinters));\n web_ui_->RegisterMessageCallback(\"print\",\n NewCallback(this, &PrintPreviewHandler::HandlePrint));\n}\n\nvoid PrintPreviewHandler::HandleGetPrinters(const ListValue*) {\n scoped_refptr task =\n new EnumeratePrintersTaskProxy(AsWeakPtr(), print_backend_.get());\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n NewRunnableMethod(task.get(),\n &EnumeratePrintersTaskProxy::EnumeratePrinters));\n}\n\nvoid PrintPreviewHandler::HandlePrint(const ListValue*) {\n web_ui_->GetRenderViewHost()->PrintForPrintPreview();\n}\n\nvoid PrintPreviewHandler::SendPrinterList(const ListValue& printers) {\n web_ui_->CallJavascriptFunction(L\"setPrinters\", printers);\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\/nacl\/nacl_main_platform_delegate.h\"\n\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"seccompsandbox\/sandbox.h\"\n\nNaClMainPlatformDelegate::NaClMainPlatformDelegate(\n const MainFunctionParams& parameters)\n : parameters_(parameters), sandbox_test_module_(NULL) {\n}\n\nNaClMainPlatformDelegate::~NaClMainPlatformDelegate() {\n}\n\nvoid NaClMainPlatformDelegate::PlatformInitialize() {\n}\n\nvoid NaClMainPlatformDelegate::PlatformUninitialize() {\n}\n\nvoid NaClMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {\n \/\/ The sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n return;\n}\n\nvoid NaClMainPlatformDelegate::EnableSandbox() {\n \/\/ The setuid sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n \/\/\n \/\/ The seccomp sandbox is started in the renderer.\n \/\/ http:\/\/code.google.com\/p\/seccompsandbox\/\n#if defined(ARCH_CPU_X86_FAMILY) && !defined(CHROMIUM_SELINUX) && \\\n !defined(__clang__)\n \/\/ N.b. SupportsSeccompSandbox() returns a cached result, as we already\n \/\/ called it earlier in the zygote. Thus, it is OK for us to not pass in\n \/\/ a file descriptor for \"\/proc\".\n if (switches::SeccompSandboxEnabled() && SupportsSeccompSandbox(-1))\n StartSeccompSandbox();\n#endif\n}\n\nbool NaClMainPlatformDelegate::RunSandboxTests() {\n \/\/ The sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n return true;\n}\nnacl: disable seccomp initialization in NaClMain()\/\/ 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\/nacl\/nacl_main_platform_delegate.h\"\n\n#include \"base\/command_line.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"seccompsandbox\/sandbox.h\"\n\nNaClMainPlatformDelegate::NaClMainPlatformDelegate(\n const MainFunctionParams& parameters)\n : parameters_(parameters), sandbox_test_module_(NULL) {\n}\n\nNaClMainPlatformDelegate::~NaClMainPlatformDelegate() {\n}\n\nvoid NaClMainPlatformDelegate::PlatformInitialize() {\n}\n\nvoid NaClMainPlatformDelegate::PlatformUninitialize() {\n}\n\nvoid NaClMainPlatformDelegate::InitSandboxTests(bool no_sandbox) {\n \/\/ The sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n return;\n}\n\nvoid NaClMainPlatformDelegate::EnableSandbox() {\n \/\/ The setuid sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n \/\/\n \/\/ The seccomp sandbox is started in the renderer.\n \/\/ http:\/\/code.google.com\/p\/seccompsandbox\/\n \/\/ seccomp is currently disabled for nacl.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=59423\n \/\/ See the code in chrome\/renderer\/renderer_main_platform_delegate_linux.cc\n \/\/ for how to turn seccomp on.\n \/\/\n \/\/ The seccomp sandbox should not be enabled for Native Client until\n \/\/ all of these issues are fixed:\n \/\/ http:\/\/code.google.com\/p\/nativeclient\/issues\/list?q=label:Seccomp\n \/\/ At best, NaCl will not work. At worst, enabling the seccomp sandbox\n \/\/ could create a hole in the NaCl sandbox.\n}\n\nbool NaClMainPlatformDelegate::RunSandboxTests() {\n \/\/ The sandbox is started in the zygote process: zygote_main_linux.cc\n \/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSUIDSandbox\n return true;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkStreamingImageIOBase.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/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 notices for more information.\n\n=========================================================================*\/\n#include \"itkStreamingImageIOBase.h\"\n\n\n#include \n\nnamespace itk\n{\n\nStreamingImageIOBase::StreamingImageIOBase()\n : ImageIOBase()\n{\n}\n\n\nvoid StreamingImageIOBase::PrintSelf(std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\n\nbool StreamingImageIOBase\n::StreamReadBufferAsBinary(std::istream& file, void *_buffer)\n{\n itkDebugMacro( << \"StreamingReadBufferAsBinary called\" );\n\n char *buffer = static_cast(_buffer);\n \/\/ Offset into file\n std::streampos dataPos = this->GetDataPosition();\n\n std::streamsize sizeOfRegion = static_cast( m_IORegion.GetNumberOfPixels() )\n *this->GetPixelSize();\n\n\n \/\/ compute the number of continuous bytes to be read\n std::streamsize sizeOfChunk = 1;\n unsigned int movingDirection = 0;\n do\n {\n sizeOfChunk *= m_IORegion.GetSize(movingDirection);\n ++movingDirection;\n }\n while ( movingDirection < m_IORegion.GetImageDimension() &&\n m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );\n sizeOfChunk *= this->GetPixelSize();\n\n ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();\n std::streamsize gcount = 0;\n while ( m_IORegion.IsInside(currentIndex) )\n {\n \/\/ calculate the position to seek to in the file\n std::streampos seekPos = 0;\n size_t subDimensionQuantity = 1;\n for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )\n {\n seekPos += subDimensionQuantity*this->GetPixelSize()*currentIndex[i];\n subDimensionQuantity *= this->GetDimensions(i);\n }\n\n\n itkDebugMacro(<< \"Reading \" << sizeOfChunk << \" of \" << sizeOfRegion << \" bytes for \" << m_FileName << \" at \" << dataPos+seekPos << \" position in file\");\n\n file.seekg( dataPos+seekPos, std::ios::beg );\n this->ReadBufferAsBinary( file, buffer, sizeOfChunk );\n\n \/\/ increment the buffer pointer\n buffer += sizeOfChunk;\n gcount += file.gcount();\n\n if ( file.fail() )\n {\n itkExceptionMacro(<<\"Fail reading\");\n }\n\n if (movingDirection == m_IORegion.GetImageDimension())\n break;\n\n \/\/ increment index to next chunk\n ++currentIndex[movingDirection];\n for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)\n {\n \/\/ when reaching the end of the moving index dimension carry to\n \/\/ higher dimensions\n if (static_cast(currentIndex[i] - m_IORegion.GetIndex(i)) >= m_IORegion.GetSize(i) )\n {\n currentIndex[i] = m_IORegion.GetIndex(i);\n ++currentIndex[i+1];\n }\n }\n }\n\n if ( gcount != sizeOfRegion )\n {\n itkExceptionMacro(\"Data not read completely. Expected = \" << sizeOfRegion << \", but only read \" << gcount << \" bytes.\");\n }\n\n return true;\n}\n\nbool StreamingImageIOBase::ReadBufferAsBinary( std::istream& is, void *buffer, StreamingImageIOBase::SizeType num )\n{\n\n \/\/ some systems have a limit of 2GB to be read at once\n const SizeType maxChunk = 1024*1024*1024;\n\n std::streamsize bytesRemaining = static_cast( num );\n\n while (bytesRemaining)\n {\n\n std::streamsize bytesToRead = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;\n\n itkDebugMacro(<< \"Reading \" << bytesToRead << \" of \" << bytesRemaining << \" bytes for \" << m_FileName);\n\n is.read( static_cast( buffer ) , bytesToRead );\n\n if ( (is.gcount() != bytesToRead) || is.fail() )\n {\n return false;\n }\n buffer = static_cast( buffer ) + bytesToRead;\n bytesRemaining -= bytesToRead;\n }\n\n return true;\n}\n\n\nbool StreamingImageIOBase::WriteBufferAsBinary( std::ostream& os, const void *buffer, StreamingImageIOBase::SizeType num )\n{\n \/\/ some systems have a limit of 2GB to be written at once\n const SizeType maxChunk = 1024*1024*1024;\n\n std::streamsize bytesRemaining = num;\n while (bytesRemaining)\n {\n\n SizeType bytesToWrite = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;\n\n itkDebugMacro(<< \"Writing \" << bytesToWrite << \" of \" << bytesRemaining << \" bytes for \" << m_FileName);\n\n os.write(static_cast(buffer) , bytesToWrite);\n if ( os.fail() )\n {\n return false;\n }\n\n buffer = static_cast( buffer ) + bytesToWrite;\n bytesRemaining -= bytesToWrite;\n }\n\n return true;\n}\n\n\nbool StreamingImageIOBase::StreamWriteBufferAsBinary(std::ostream& file, const void *_buffer)\n{\n itkDebugMacro( << \"StreamingWriteBufferAsBinary called\" );\n\n const char *buffer = static_cast< const char* >( _buffer );\n \/\/ Offset into file\n std::streampos dataPos = this->GetDataPosition();\n\n \/\/ compute the number of continuous bytes to be written\n std::streamsize sizeOfChunk = 1;\n unsigned int movingDirection = 0;\n do\n {\n sizeOfChunk *= m_IORegion.GetSize(movingDirection);\n ++movingDirection;\n }\n while ( movingDirection < m_IORegion.GetImageDimension() &&\n m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );\n sizeOfChunk *= this->GetPixelSize();\n\n\n ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();\n while ( m_IORegion.IsInside(currentIndex) )\n {\n \/\/ calculate the position to seek to in the file\n std::streampos seekPos = 0;\n size_t subDimensionQuantity = 1;\n for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )\n {\n seekPos += subDimensionQuantity*this->GetPixelSize()*currentIndex[i];\n subDimensionQuantity *= this->GetDimensions(i);\n }\n\n file.seekp( dataPos+seekPos, std::ios::beg );\n this->WriteBufferAsBinary( file, buffer, sizeOfChunk );\n\n \/\/ increment the buffer pointer\n buffer += sizeOfChunk;\n\n\n itkDebugMacro(<< \"Writing \" << sizeOfChunk << \" of \" << \" ?? bytes for \" << m_FileName << \" at \" << dataPos+seekPos << \" position in file\");\n\n\n if ( file.fail() )\n {\n itkExceptionMacro(<<\"Fail writing\");\n }\n\n if (movingDirection == m_IORegion.GetImageDimension())\n break;\n\n \/\/ increment index to next chunk\n ++currentIndex[movingDirection];\n for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)\n {\n \/\/ when reaching the end of the movingDirection dimension carry to\n \/\/ higher dimensions\n if ( static_cast(currentIndex[i] - m_IORegion.GetIndex(i))\n >= m_IORegion.GetSize(i) )\n {\n currentIndex[i] = m_IORegion.GetIndex(i);\n ++currentIndex[i+1];\n }\n }\n }\n\n\n return true;\n}\n\n\nvoid StreamingImageIOBase::OpenFileForReading(std::ifstream& os, const char* filename)\n{\n \/\/ Make sure that we have a file to\n if ( *filename == 0 )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n\n \/\/ Open the new file for reading\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n os.open(filename, std::ios::in | std::ios::binary );\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for reading: \" << filename);\n }\n\n}\n\nvoid StreamingImageIOBase::OpenFileForWriting(std::ofstream& os, const char* filename, bool truncate)\n{\n \/\/ Make sure that we have a file to\n if ( *filename == 0 )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n\n \/\/ Open the new file for writing\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n if (truncate)\n {\n \/\/ truncate\n os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::trunc );\n\n }\n else\n {\n os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::in );\n }\n\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for writing: \" << filename);\n }\n\n}\n\nbool StreamingImageIOBase::CanStreamRead( void )\n{\n return true;\n}\n\nbool StreamingImageIOBase::CanStreamWrite( void )\n{\n return true;\n}\n\n\nunsigned int\nStreamingImageIOBase::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits,\n const ImageIORegion &pasteRegion,\n const ImageIORegion &largestPossibleRegion)\n{\n if (!itksys::SystemTools::FileExists( m_FileName.c_str() ))\n {\n \/\/ file doesn't exits so we don't have potential problems\n }\n else if (pasteRegion != largestPossibleRegion)\n {\n \/\/ we are going to be pasting (may be streaming too)\n\n \/\/ need to check to see if the file is compatible\n std::string errorMessage;\n Pointer headerImageIOReader = dynamic_cast(this->CreateAnother().GetPointer());\n\n try\n {\n headerImageIOReader->SetFileName(m_FileName.c_str());\n headerImageIOReader->ReadImageInformation();\n }\n catch (...)\n {\n errorMessage = \"Unable to read information from file: \" + m_FileName;\n }\n\n \/\/ we now need to check that the following match:\n \/\/ 2)pixel type\n \/\/ 3)dimensions\n \/\/ 4)size\/origin\/spacing\n \/\/ 5)direction cosines\n \/\/\n \/\/ todo check for byte order\n\n if (errorMessage.size())\n {\n \/\/ 0) Can't read file\n }\n \/\/ 2)pixel type\n \/\/ this->GetPixelType() is not verified becasue the metaio file format\n \/\/ stores all multi-component types as arrays, so it does not\n \/\/ distinguish between pixel types. Also as long as the compoent\n \/\/ and number of compoents match we should be able to paste, that\n \/\/ is the numbers should be the same it is just the interpretation\n \/\/ that is not matching\n else if ( headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() ||\n headerImageIOReader->GetComponentType() != this->GetComponentType() )\n {\n errorMessage = \"Component type does not match in file: \" + m_FileName;\n }\n \/\/ 3)dimensions\/size\n else if (headerImageIOReader->GetNumberOfDimensions() != this->GetNumberOfDimensions())\n {\n errorMessage = \"Dimensions does not match in file: \" + m_FileName;\n }\n else\n {\n for (unsigned int i = 0; i < this->GetNumberOfDimensions(); ++i)\n {\n \/\/ 4)size\/origin\/spacing\n if (headerImageIOReader->GetDimensions(i) != this->GetDimensions(i) ||\n headerImageIOReader->GetSpacing(i) != this->GetSpacing(i) ||\n headerImageIOReader->GetOrigin(i) != this->GetOrigin(i))\n {\n errorMessage = \"Size, spacing or origin does not match in file: \" + m_FileName;\n break;\n }\n \/\/ 5)direction cosines\n if (headerImageIOReader->GetDirection(i) != this->GetDirection(i))\n {\n errorMessage = \"Direction cosines does not match in file: \" + m_FileName;\n break;\n }\n }\n }\n\n if (errorMessage.size())\n {\n itkExceptionMacro(\"Unable to paste because pasting file exists and is different. \" << errorMessage);\n }\n else if ( headerImageIOReader->GetPixelType() != this->GetPixelType() )\n {\n \/\/ since there is currently poor support for pixel types in\n \/\/ MetaIO we will just warn when it does not match\n itkWarningMacro(\"Pixel types does not match file, but component type and number of components do.\");\n }\n }\n else if (numberOfRequestedSplits != 1)\n {\n \/\/ we are going be streaming\n\n \/\/ need to remove the file incase the file doesn't match our\n \/\/ current header\/meta data information\n if (!itksys::SystemTools::RemoveFile(m_FileName.c_str()))\n itkExceptionMacro(\"Unable to remove file for streaming: \" << m_FileName);\n }\n\n return GetActualNumberOfSplitsForWritingCanStreamWrite(numberOfRequestedSplits, pasteRegion);\n\n}\n\n\nImageIORegion StreamingImageIOBase::GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requestedRegion ) const\n{\n \/\/ This implementation returns the requestedRegion if\n \/\/ \"UseStreamedReading\" is enabled\n\n ImageIORegion streamableRegion(this->m_NumberOfDimensions);\n if( !m_UseStreamedReading )\n {\n for( unsigned int i=0; i < this->m_NumberOfDimensions; i++ )\n {\n streamableRegion.SetSize( i, this->m_Dimensions[i] );\n streamableRegion.SetIndex( i, 0 );\n }\n }\n else\n {\n streamableRegion = requestedRegion;\n }\n\n return streamableRegion;\n}\n\n\nbool StreamingImageIOBase::RequestedToStream( void ) const\n{\n \/\/ we choose the max dimension and then pad the smaller with ones\n \/\/\n \/\/ This enables a 2D request from a 3D volume to get the first slice,\n \/\/ and a 4D with a 1-sized 4th dimension to equal the 3D volume\n \/\/ aswell.\n unsigned int maxNumberOfDimension = vnl_math_max( this->GetNumberOfDimensions(), this->GetIORegion().GetImageDimension() );\n\n ImageIORegion ioregion( maxNumberOfDimension );\n ImageIORegion largestRegion( maxNumberOfDimension );\n for(unsigned int i=0; iGetNumberOfDimensions() )\n {\n largestRegion.SetSize( i, this->GetDimensions(i) );\n }\n else\n {\n largestRegion.SetSize( i, 1 );\n }\n\n if ( i < this->GetIORegion().GetImageDimension() )\n {\n ioregion.SetIndex( i, this->GetIORegion().GetIndex(i) );\n ioregion.SetSize( i, this->GetIORegion().GetSize(i) );\n }\n else\n {\n ioregion.SetIndex( i, 0 );\n ioregion.SetSize( i, 1 );\n }\n\n }\n\n return (largestRegion != ioregion);\n}\n\n} \/\/ namespace itk\nCOMP: at least for Borland, must cast arg to std::fpos += operator to std::streamoff to avoid ambiguity.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkStreamingImageIOBase.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/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 notices for more information.\n\n=========================================================================*\/\n#include \"itkStreamingImageIOBase.h\"\n\n\n#include \n\nnamespace itk\n{\n\nStreamingImageIOBase::StreamingImageIOBase()\n : ImageIOBase()\n{\n}\n\n\nvoid StreamingImageIOBase::PrintSelf(std::ostream& os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n}\n\n\nbool StreamingImageIOBase\n::StreamReadBufferAsBinary(std::istream& file, void *_buffer)\n{\n itkDebugMacro( << \"StreamingReadBufferAsBinary called\" );\n\n char *buffer = static_cast(_buffer);\n \/\/ Offset into file\n std::streampos dataPos = this->GetDataPosition();\n\n std::streamsize sizeOfRegion = static_cast( m_IORegion.GetNumberOfPixels() )\n *this->GetPixelSize();\n\n\n \/\/ compute the number of continuous bytes to be read\n std::streamsize sizeOfChunk = 1;\n unsigned int movingDirection = 0;\n do\n {\n sizeOfChunk *= m_IORegion.GetSize(movingDirection);\n ++movingDirection;\n }\n while ( movingDirection < m_IORegion.GetImageDimension() &&\n m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );\n sizeOfChunk *= this->GetPixelSize();\n\n ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();\n std::streamsize gcount = 0;\n while ( m_IORegion.IsInside(currentIndex) )\n {\n \/\/ calculate the position to seek to in the file\n std::streampos seekPos = 0;\n size_t subDimensionQuantity = 1;\n for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )\n {\n seekPos += static_cast (subDimensionQuantity *\n this->GetPixelSize() *\n currentIndex[i]);\n subDimensionQuantity *= this->GetDimensions(i);\n }\n\n\n itkDebugMacro(<< \"Reading \" << sizeOfChunk << \" of \" << sizeOfRegion << \" bytes for \" << m_FileName << \" at \" << dataPos+seekPos << \" position in file\");\n\n file.seekg( dataPos+seekPos, std::ios::beg );\n this->ReadBufferAsBinary( file, buffer, sizeOfChunk );\n\n \/\/ increment the buffer pointer\n buffer += sizeOfChunk;\n gcount += file.gcount();\n\n if ( file.fail() )\n {\n itkExceptionMacro(<<\"Fail reading\");\n }\n\n if (movingDirection == m_IORegion.GetImageDimension())\n break;\n\n \/\/ increment index to next chunk\n ++currentIndex[movingDirection];\n for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)\n {\n \/\/ when reaching the end of the moving index dimension carry to\n \/\/ higher dimensions\n if (static_cast(currentIndex[i] - m_IORegion.GetIndex(i)) >= m_IORegion.GetSize(i) )\n {\n currentIndex[i] = m_IORegion.GetIndex(i);\n ++currentIndex[i+1];\n }\n }\n }\n\n if ( gcount != sizeOfRegion )\n {\n itkExceptionMacro(\"Data not read completely. Expected = \" << sizeOfRegion << \", but only read \" << gcount << \" bytes.\");\n }\n\n return true;\n}\n\nbool StreamingImageIOBase::ReadBufferAsBinary( std::istream& is, void *buffer, StreamingImageIOBase::SizeType num )\n{\n\n \/\/ some systems have a limit of 2GB to be read at once\n const SizeType maxChunk = 1024*1024*1024;\n\n std::streamsize bytesRemaining = static_cast( num );\n\n while (bytesRemaining)\n {\n\n std::streamsize bytesToRead = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;\n\n itkDebugMacro(<< \"Reading \" << bytesToRead << \" of \" << bytesRemaining << \" bytes for \" << m_FileName);\n\n is.read( static_cast( buffer ) , bytesToRead );\n\n if ( (is.gcount() != bytesToRead) || is.fail() )\n {\n return false;\n }\n buffer = static_cast( buffer ) + bytesToRead;\n bytesRemaining -= bytesToRead;\n }\n\n return true;\n}\n\n\nbool StreamingImageIOBase::WriteBufferAsBinary( std::ostream& os, const void *buffer, StreamingImageIOBase::SizeType num )\n{\n \/\/ some systems have a limit of 2GB to be written at once\n const SizeType maxChunk = 1024*1024*1024;\n\n std::streamsize bytesRemaining = num;\n while (bytesRemaining)\n {\n\n SizeType bytesToWrite = bytesRemaining > maxChunk ? maxChunk : bytesRemaining;\n\n itkDebugMacro(<< \"Writing \" << bytesToWrite << \" of \" << bytesRemaining << \" bytes for \" << m_FileName);\n\n os.write(static_cast(buffer) , bytesToWrite);\n if ( os.fail() )\n {\n return false;\n }\n\n buffer = static_cast( buffer ) + bytesToWrite;\n bytesRemaining -= bytesToWrite;\n }\n\n return true;\n}\n\n\nbool StreamingImageIOBase::StreamWriteBufferAsBinary(std::ostream& file, const void *_buffer)\n{\n itkDebugMacro( << \"StreamingWriteBufferAsBinary called\" );\n\n const char *buffer = static_cast< const char* >( _buffer );\n \/\/ Offset into file\n std::streampos dataPos = this->GetDataPosition();\n\n \/\/ compute the number of continuous bytes to be written\n std::streamsize sizeOfChunk = 1;\n unsigned int movingDirection = 0;\n do\n {\n sizeOfChunk *= m_IORegion.GetSize(movingDirection);\n ++movingDirection;\n }\n while ( movingDirection < m_IORegion.GetImageDimension() &&\n m_IORegion.GetSize(movingDirection-1) == this->GetDimensions(movingDirection-1) );\n sizeOfChunk *= this->GetPixelSize();\n\n\n ImageIORegion::IndexType currentIndex = m_IORegion.GetIndex();\n while ( m_IORegion.IsInside(currentIndex) )\n {\n \/\/ calculate the position to seek to in the file\n std::streampos seekPos = 0;\n size_t subDimensionQuantity = 1;\n for ( unsigned int i = 0; i < m_IORegion.GetImageDimension(); ++i )\n {\n seekPos += static_cast (subDimensionQuantity *\n this->GetPixelSize() *\n currentIndex[i]);\n subDimensionQuantity *= this->GetDimensions(i);\n }\n\n file.seekp( dataPos+seekPos, std::ios::beg );\n this->WriteBufferAsBinary( file, buffer, sizeOfChunk );\n\n \/\/ increment the buffer pointer\n buffer += sizeOfChunk;\n\n\n itkDebugMacro(<< \"Writing \" << sizeOfChunk << \" of \" << \" ?? bytes for \" << m_FileName << \" at \" << dataPos+seekPos << \" position in file\");\n\n\n if ( file.fail() )\n {\n itkExceptionMacro(<<\"Fail writing\");\n }\n\n if (movingDirection == m_IORegion.GetImageDimension())\n break;\n\n \/\/ increment index to next chunk\n ++currentIndex[movingDirection];\n for (unsigned int i = movingDirection; i < m_IORegion.GetImageDimension()-1; ++i)\n {\n \/\/ when reaching the end of the movingDirection dimension carry to\n \/\/ higher dimensions\n if ( static_cast(currentIndex[i] - m_IORegion.GetIndex(i))\n >= m_IORegion.GetSize(i) )\n {\n currentIndex[i] = m_IORegion.GetIndex(i);\n ++currentIndex[i+1];\n }\n }\n }\n\n\n return true;\n}\n\n\nvoid StreamingImageIOBase::OpenFileForReading(std::ifstream& os, const char* filename)\n{\n \/\/ Make sure that we have a file to\n if ( *filename == 0 )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n\n \/\/ Open the new file for reading\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n os.open(filename, std::ios::in | std::ios::binary );\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for reading: \" << filename);\n }\n\n}\n\nvoid StreamingImageIOBase::OpenFileForWriting(std::ofstream& os, const char* filename, bool truncate)\n{\n \/\/ Make sure that we have a file to\n if ( *filename == 0 )\n {\n itkExceptionMacro(<<\"A FileName must be specified.\");\n }\n\n \/\/ Close file from any previous image\n if ( os.is_open() )\n {\n os.close();\n }\n\n \/\/ Open the new file for writing\n itkDebugMacro(<< \"Initialize: opening file \" << filename);\n\n if (truncate)\n {\n \/\/ truncate\n os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::trunc );\n\n }\n else\n {\n os.open( m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::in );\n }\n\n if ( os.fail() )\n {\n itkExceptionMacro(<< \"Could not open file for writing: \" << filename);\n }\n\n}\n\nbool StreamingImageIOBase::CanStreamRead( void )\n{\n return true;\n}\n\nbool StreamingImageIOBase::CanStreamWrite( void )\n{\n return true;\n}\n\n\nunsigned int\nStreamingImageIOBase::GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits,\n const ImageIORegion &pasteRegion,\n const ImageIORegion &largestPossibleRegion)\n{\n if (!itksys::SystemTools::FileExists( m_FileName.c_str() ))\n {\n \/\/ file doesn't exits so we don't have potential problems\n }\n else if (pasteRegion != largestPossibleRegion)\n {\n \/\/ we are going to be pasting (may be streaming too)\n\n \/\/ need to check to see if the file is compatible\n std::string errorMessage;\n Pointer headerImageIOReader = dynamic_cast(this->CreateAnother().GetPointer());\n\n try\n {\n headerImageIOReader->SetFileName(m_FileName.c_str());\n headerImageIOReader->ReadImageInformation();\n }\n catch (...)\n {\n errorMessage = \"Unable to read information from file: \" + m_FileName;\n }\n\n \/\/ we now need to check that the following match:\n \/\/ 2)pixel type\n \/\/ 3)dimensions\n \/\/ 4)size\/origin\/spacing\n \/\/ 5)direction cosines\n \/\/\n \/\/ todo check for byte order\n\n if (errorMessage.size())\n {\n \/\/ 0) Can't read file\n }\n \/\/ 2)pixel type\n \/\/ this->GetPixelType() is not verified becasue the metaio file format\n \/\/ stores all multi-component types as arrays, so it does not\n \/\/ distinguish between pixel types. Also as long as the compoent\n \/\/ and number of compoents match we should be able to paste, that\n \/\/ is the numbers should be the same it is just the interpretation\n \/\/ that is not matching\n else if ( headerImageIOReader->GetNumberOfComponents() != this->GetNumberOfComponents() ||\n headerImageIOReader->GetComponentType() != this->GetComponentType() )\n {\n errorMessage = \"Component type does not match in file: \" + m_FileName;\n }\n \/\/ 3)dimensions\/size\n else if (headerImageIOReader->GetNumberOfDimensions() != this->GetNumberOfDimensions())\n {\n errorMessage = \"Dimensions does not match in file: \" + m_FileName;\n }\n else\n {\n for (unsigned int i = 0; i < this->GetNumberOfDimensions(); ++i)\n {\n \/\/ 4)size\/origin\/spacing\n if (headerImageIOReader->GetDimensions(i) != this->GetDimensions(i) ||\n headerImageIOReader->GetSpacing(i) != this->GetSpacing(i) ||\n headerImageIOReader->GetOrigin(i) != this->GetOrigin(i))\n {\n errorMessage = \"Size, spacing or origin does not match in file: \" + m_FileName;\n break;\n }\n \/\/ 5)direction cosines\n if (headerImageIOReader->GetDirection(i) != this->GetDirection(i))\n {\n errorMessage = \"Direction cosines does not match in file: \" + m_FileName;\n break;\n }\n }\n }\n\n if (errorMessage.size())\n {\n itkExceptionMacro(\"Unable to paste because pasting file exists and is different. \" << errorMessage);\n }\n else if ( headerImageIOReader->GetPixelType() != this->GetPixelType() )\n {\n \/\/ since there is currently poor support for pixel types in\n \/\/ MetaIO we will just warn when it does not match\n itkWarningMacro(\"Pixel types does not match file, but component type and number of components do.\");\n }\n }\n else if (numberOfRequestedSplits != 1)\n {\n \/\/ we are going be streaming\n\n \/\/ need to remove the file incase the file doesn't match our\n \/\/ current header\/meta data information\n if (!itksys::SystemTools::RemoveFile(m_FileName.c_str()))\n itkExceptionMacro(\"Unable to remove file for streaming: \" << m_FileName);\n }\n\n return GetActualNumberOfSplitsForWritingCanStreamWrite(numberOfRequestedSplits, pasteRegion);\n\n}\n\n\nImageIORegion StreamingImageIOBase::GenerateStreamableReadRegionFromRequestedRegion( const ImageIORegion & requestedRegion ) const\n{\n \/\/ This implementation returns the requestedRegion if\n \/\/ \"UseStreamedReading\" is enabled\n\n ImageIORegion streamableRegion(this->m_NumberOfDimensions);\n if( !m_UseStreamedReading )\n {\n for( unsigned int i=0; i < this->m_NumberOfDimensions; i++ )\n {\n streamableRegion.SetSize( i, this->m_Dimensions[i] );\n streamableRegion.SetIndex( i, 0 );\n }\n }\n else\n {\n streamableRegion = requestedRegion;\n }\n\n return streamableRegion;\n}\n\n\nbool StreamingImageIOBase::RequestedToStream( void ) const\n{\n \/\/ we choose the max dimension and then pad the smaller with ones\n \/\/\n \/\/ This enables a 2D request from a 3D volume to get the first slice,\n \/\/ and a 4D with a 1-sized 4th dimension to equal the 3D volume\n \/\/ aswell.\n unsigned int maxNumberOfDimension = vnl_math_max( this->GetNumberOfDimensions(), this->GetIORegion().GetImageDimension() );\n\n ImageIORegion ioregion( maxNumberOfDimension );\n ImageIORegion largestRegion( maxNumberOfDimension );\n for(unsigned int i=0; iGetNumberOfDimensions() )\n {\n largestRegion.SetSize( i, this->GetDimensions(i) );\n }\n else\n {\n largestRegion.SetSize( i, 1 );\n }\n\n if ( i < this->GetIORegion().GetImageDimension() )\n {\n ioregion.SetIndex( i, this->GetIORegion().GetIndex(i) );\n ioregion.SetSize( i, this->GetIORegion().GetSize(i) );\n }\n else\n {\n ioregion.SetIndex( i, 0 );\n ioregion.SetSize( i, 1 );\n }\n\n }\n\n return (largestRegion != ioregion);\n}\n\n} \/\/ namespace itk\n<|endoftext|>"} {"text":"\/**\n * @file\n * @brief Example of using new and delete operators\n * @date 12.07.12\n * @author Ilia Vaprol\n *\/\n\n#include \n\n#include \n\nEMBOX_TEST_SUITE(\"c++ memory test\");\n\n#if 0\nTEST_SETUP_SUITE(suite_setup);\n\nstatic int base_ctor;\nstatic int base_dtor;\n\nclass Base {\npublic:\n\tBase() { ++base_ctor; }\n\t~Base() { ++base_dtor; }\n};\n\nTEST_CASE(\"Class can allocated on stack\") {\n\t{\n\t\tBase base;\n\t\ttest_assert_equal(base_ctor, 1);\n\t\ttest_assert_equal(base_dtor, 0);\n\t}\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated one stack using placement new\") {\n\tchar storage[sizeof(Base)];\n\tBase *base_ptr = new(storage) Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tbase_ptr->~Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated on heap using nothrow new\") {\n\tBase *base_ptr = new(std::nothrow) Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tdelete base_ptr;\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated on heap using throwing new\") {\n\tBase *base_ptr = new Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tdelete base_ptr;\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nstatic int case_setup(void) {\n\tbase_ctor = base_dtor = 0;\n}\n#endif\ntests: c++: Fix memory test\/**\n * @file\n * @brief Example of using new and delete operators\n * @date 12.07.12\n * @author Ilia Vaprol\n *\/\n\n#include \n\n#include \n\nEMBOX_TEST_SUITE(\"c++ memory test\");\n\nTEST_SETUP(case_setup);\n\nstatic int base_ctor;\nstatic int base_dtor;\n\nclass Base {\npublic:\n\tBase() { ++base_ctor; }\n\t~Base() { ++base_dtor; }\n};\n\nTEST_CASE(\"Class can allocated on stack\") {\n\t{\n\t\tBase base;\n\t\ttest_assert_equal(base_ctor, 1);\n\t\ttest_assert_equal(base_dtor, 0);\n\t}\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated one stack using placement new\") {\n\tchar storage[sizeof(Base)];\n\tBase *base_ptr = new(storage) Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tbase_ptr->~Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated on heap using nothrow new\") {\n\tBase *base_ptr = new(std::nothrow) Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tdelete base_ptr;\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nTEST_CASE(\"Class can allocated on heap using throwing new\") {\n\tBase *base_ptr = new Base();\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 0);\n\tdelete base_ptr;\n\ttest_assert_equal(base_ctor, 1);\n\ttest_assert_equal(base_dtor, 1);\n}\n\nstatic int case_setup(void) {\n\tbase_ctor = base_dtor = 0;\n}\n<|endoftext|>"} {"text":"#include \"Transcriptome.h\"\n#include \"ReadAlign.h\"\n#include \"serviceFuns.cpp\"\n\n\nint alignToTranscript(Transcript &aG, uint trS1, uint8 trStr1, uint32 *exSE1, uint32 *exLenCum1, uint16 exN1, Transcript &aT) {\n\n \/\/find exon that overlaps beginning of the read\n uint32 g1=aG.exons[0][EX_G]-trS1;\/\/start of the transcript\n uint32 ex1=binarySearch1(g1, exSE1, 2*exN1);\n if (ex1>=2*exN1) return 0; \/\/align start is to the right of all exons\n\n if (ex1%2==1) {\/\/beginning of the read >=end of an exon\n if (exSE1[ex1]==g1) {\/\/first base of the read is exactly the last base of the exon\n --ex1;\n } else {\n return 0;\/\/beginning of the read is past the end of an exon, align does not belong to this transcript\n };\n };\n ex1=ex1\/2; \/\/this is the first exon of the alignment\n\n aT.nExons=0;\n aT.primaryFlag=false;\n\n aG.canonSJ[aG.nExons-1]=-999; \/\/marks the last exons\n for (uint32 iab=0; iabexSE1[2*ex1+1]+trS1+1) {\/\/block extends past exon end\n return 0;\n };\n\n if (iab==0 || aG.canonSJ[iab-1]<0) {\n aT.exons[aT.nExons][EX_R]=aG.exons[iab][EX_R];\n aT.exons[aT.nExons][EX_G]=aG.exons[iab][EX_G]-trS1-exSE1[2*ex1]+exLenCum1[ex1];\n aT.exons[aT.nExons][EX_L]=aG.exons[iab][EX_L];\n aT.exons[aT.nExons][EX_iFrag]=aG.exons[iab][EX_iFrag];\n if (aT.nExons>0) aT.canonSJ[aT.nExons-1]=aG.canonSJ[iab-1];\n ++aT.nExons;\n } else {\n aT.exons[aT.nExons-1][EX_L]+=aG.exons[iab][EX_L];\n };\n switch (aG.canonSJ[iab]) {\n case -999: \/\/last exon\n if (trStr1==2) {\/\/convert align coordinates if on the -strand\n uint32 trlength=exLenCum1[exN1-1]+exSE1[2*exN1-1]-exSE1[2*exN1-2]+1; \/\/transcript length\n for (uint32 iex=0; iex(aG.exons[iab+1][EX_G]-trS1, exSE1, 2*exN1);\n if (ex1%2==1) {\/\/beginning of the mext mate in the middle of the exon?\n return 0; \/\/align does not belong to this transcript\n } else {\n ex1=ex1\/2; \/\/this is the first exon of the second mate\n };\n break;\n case -2: \/\/insertion\n break;\n case -1: \/\/deletion\n break;\n default:\/\/junctions\n if ( aG.exons[iab][EX_G]+aG.exons[iab][EX_L]==exSE1[2*ex1+1]+trS1+1 && aG.exons[iab+1][EX_G]==exSE1[2*(ex1+1)]+trS1 ) {\n \/\/junction matches transcript junction\n ++ex1;\n } else {\n return 0;\n };\n };\n };\n return 0; \/\/this should not happen\n};\n\nuint32 Transcriptome::quantAlign (Transcript &aG, Transcript *aTall, vector> &readTranscripts, set &readGenes) {\n uint32 nAtr=0; \/\/number of alignments to the transcriptome\n\n \/\/binary search through transcript starts\n uint32 tr1=binarySearch1a(aG.exons[0][EX_G], trS, nTr);\n if (tr1==(uint32) -1) return 0; \/\/alignment outside of range of all transcripts\n\n uint aGend=aG.exons[aG.nExons-1][EX_G];\n\n ++tr1;\n do {\/\/cycle back through all the transcripts\n --tr1;\n if (aGend<=trE[tr1]) {\/\/this transcript contains the read\n int aStatus=alignToTranscript(aG, trS[tr1], trStr[tr1], exSE+2*trExI[tr1], exLenCum+trExI[tr1], trExN[tr1], aTall[nAtr]);\n if (aStatus==1) {\/\/align conforms with the transcript\n aTall[nAtr].Chr = tr1;\n aTall[nAtr].Str = trStr[tr1]==1 ? aG.Str : 1-aG.Str; \/\/TODO strandedness\n if (P.pSolo.strand==-1 || (int32) aTall[nAtr].Str == P.pSolo.strand) {\/\/correct strand\n uint32 distTTS=trLen[tr1]-(aTall[nAtr].exons[aTall[nAtr].nExons-1][EX_G] + aTall[nAtr].exons[aTall[nAtr].nExons-1][EX_L]);\n readTranscripts.push_back({tr1,distTTS});\n readGenes.insert(trGene[tr1]);\/\/genes for all alignments\n aG.alignGenes.insert(trGene[tr1]);\/\/genes for each alignmentset\n };\n ++nAtr;\n };\n };\n } while (trEmax[tr1]>=aGend && tr1>0);\n\n return nAtr;\n};\nFinished implementing CR3 CB\/UMI processing. Passed Lane 1 tests.#include \"Transcriptome.h\"\n#include \"ReadAlign.h\"\n#include \"serviceFuns.cpp\"\n\nint alignToTranscript(Transcript &aG, uint trS1, uint8 trStr1, uint32 *exSE1, uint32 *exLenCum1, uint16 exN1, Transcript &aT) {\n\n \/\/find exon that overlaps beginning of the read\n uint32 g1=aG.exons[0][EX_G]-trS1;\/\/start of the align\n uint32 ex1=binarySearch1(g1, exSE1, 2*exN1);\n \/\/this sholud not be possible - we check before we call this function\n if (ex1>=2*exN1) return 0; \/\/align start is to the right of all exons\n\n if (ex1%2==1) {\/\/beginning of the read >=end of an exon\n if (exSE1[ex1]==g1) {\/\/first base of the read is exactly the last base of the exon\n --ex1;\n } else {\n return 0;\/\/beginning of the read is past the end of an exon, align does not belong to this transcript\n };\n };\n ex1=ex1\/2; \/\/this is the first exon of the alignment\n\n aT.nExons=0;\n aT.primaryFlag=false;\n\n aG.canonSJ[aG.nExons-1]=-999; \/\/marks the last exons\n for (uint32 iab=0; iabexSE1[2*ex1+1]+trS1+1) {\/\/block extends past exon end\n return 0;\n };\n if (iab==0 || aG.canonSJ[iab-1]<0) {\n aT.exons[aT.nExons][EX_R]=aG.exons[iab][EX_R];\n aT.exons[aT.nExons][EX_G]=aG.exons[iab][EX_G]-trS1-exSE1[2*ex1]+exLenCum1[ex1];\n aT.exons[aT.nExons][EX_L]=aG.exons[iab][EX_L];\n aT.exons[aT.nExons][EX_iFrag]=aG.exons[iab][EX_iFrag];\n if (aT.nExons>0) aT.canonSJ[aT.nExons-1]=aG.canonSJ[iab-1];\n ++aT.nExons;\n } else {\n aT.exons[aT.nExons-1][EX_L]+=aG.exons[iab][EX_L];\n };\n switch (aG.canonSJ[iab]) {\n case -999: \/\/last exon\n if (trStr1==2) {\/\/convert align coordinates if on the -strand\n uint32 trlength=exLenCum1[exN1-1]+exSE1[2*exN1-1]-exSE1[2*exN1-2]+1; \/\/transcript length\n for (uint32 iex=0; iex(aG.exons[iab+1][EX_G]-trS1, exSE1, 2*exN1);\n if (ex1%2==1) {\/\/beginning of the mext mate in the middle of the exon?\n return 0; \/\/align does not belong to this transcript\n } else {\n ex1=ex1\/2; \/\/this is the first exon of the second mate\n };\n break;\n case -2: \/\/insertion\n break;\n case -1: \/\/deletion\n break;\n default:\/\/junctions\n if ( aG.exons[iab][EX_G]+aG.exons[iab][EX_L]==exSE1[2*ex1+1]+trS1+1 && aG.exons[iab+1][EX_G]==exSE1[2*(ex1+1)]+trS1 ) {\n \/\/junction matches transcript junction\n ++ex1;\n } else {\n return 0;\n };\n };\n };\n return 0; \/\/this should not happen\n};\n\nuint32 Transcriptome::quantAlign (Transcript &aG, Transcript *aTall, vector> &readTranscripts, set &readGenes) {\n uint32 nAtr=0; \/\/number of alignments to the transcriptome\n\n \/\/binary search through transcript starts\n uint32 tr1=binarySearch1a(aG.exons[0][EX_G], trS, nTr);\/\/tr1 has the maximum transcript start such that it is still <= align start\n if (tr1==(uint32) -1) return 0; \/\/alignment outside of range of all transcripts\n\n uint aGend=aG.exons[aG.nExons-1][EX_G];\n\n ++tr1;\n do {\/\/cycle back through all the transcripts\n --tr1;\n if (aGend<=trE[tr1]) {\/\/this transcript contains the read\n int aStatus=alignToTranscript(aG, trS[tr1], trStr[tr1], exSE+2*trExI[tr1], exLenCum+trExI[tr1], trExN[tr1], aTall[nAtr]);\n if (aStatus==1) {\/\/align conforms with the transcript\n aTall[nAtr].Chr = tr1;\n aTall[nAtr].Str = trStr[tr1]==1 ? aG.Str : 1-aG.Str; \/\/TODO strandedness\n if (P.pSolo.strand==-1 || (int32) aTall[nAtr].Str == P.pSolo.strand) {\/\/correct strand\n uint32 distTTS=trLen[tr1]-(aTall[nAtr].exons[aTall[nAtr].nExons-1][EX_G] + aTall[nAtr].exons[aTall[nAtr].nExons-1][EX_L]);\n readTranscripts.push_back({tr1,distTTS});\n readGenes.insert(trGene[tr1]);\/\/genes for all alignments\n aG.alignGenes.insert(trGene[tr1]);\/\/genes for each alignmentset\n };\n ++nAtr;\n };\n };\n } while (trEmax[tr1]>=aGend && tr1>0);\n\n return nAtr;\n};\n<|endoftext|>"} {"text":"\/*\n * Target.cc\n *\n * Author: William Ma \n *\n * Copyright (C) 2015 OpenCog Foundation\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 v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n\n#include \n#include \"Target.h\"\n#include \"BCLogger.h\"\n\nnamespace opencog {\n\nTarget::Target(const Handle& bd, const Handle& vd) : body(bd), vardecl(vd) {}\n\nstd::string\tTarget::to_string() const\n{\n\tstringstream ss;\n\tss << \"body:\" << std::endl << oc_to_string(body)\n\t << \"vardecl:\" << std::endl << oc_to_string(vardecl)\n\t << \"rules:\" << std::endl << oc_to_string(rules);\n\treturn ss.str();\n}\n\nstd::string oc_to_string(const Target& target)\n{\n\treturn target.to_string();\n}\n\n\/\/ #if 0\n\/\/ \/**\n\/\/ * Constructor of Target.\n\/\/ *\n\/\/ * Only the TargetSet class can create a Target object.\n\/\/ *\n\/\/ * @param as the AtomSpace in which to store temporary information\n\/\/ * @param h the original external Handle of the Target\n\/\/ *\/\n\/\/ Target::Target(AtomSpace& as, const Handle& h, const Handle& hvardecl) : _as(as)\n\/\/ {\n\/\/ \t_htarget = h;\n\/\/ \t_selection_count = 0;\n\n\/\/ \t_vardecl = hvardecl;\n\n\/\/ \tHandleSeq vars = VariableListCast(_vardecl)->get_variables().varseq;\n\n\/\/ \t\/\/ _varmap is a map that bases on the external space\n\/\/ \tfor (auto& hv : vars)\n\/\/ \t\t_varmap[hv] = UnorderedHandleSet();\n\/\/ }\n\n\/\/ \/**\n\/\/ * Store a specific inference step for the Target into the AtomSpace.\n\/\/ *\n\/\/ * @param r the rule applied\n\/\/ * @param premises the premises selected to be the rule's input\n\/\/ *\/\n\/\/ void Target::store_step(const Rule& r, const HandleSeq& premises)\n\/\/ {\n\/\/ \t\/\/ XXX TODO think of a good structure for storing the inference step\n\/\/ \t\/\/ XXX TODO if the rule was actually applied, store the change to the TV?\n\/\/ \t_as.add_link(SET_LINK,\n\/\/ \t _htarget,\n\/\/ \t _as.add_node(NODE, r.get_name()),\n\/\/ \t _as.add_link(LIST_LINK, premises));\n\/\/ }\n\n\/\/ \/**\n\/\/ * Store new variable mappings.\n\/\/ *\n\/\/ * @param vm a HandleMultimap object containing additional mappings\n\/\/ *\/\n\/\/ void Target::store_varmap(HandleMultimap& vm)\n\/\/ {\n\/\/ \tfor (auto& p : vm)\n\/\/ \t{\n\/\/ \t\tHandle hk = _as.add_atom(p.first);\n\n\/\/ \t\tif (_varmap.count(hk) == 1)\n\/\/ \t\t{\n\/\/ \t\t\tfor (auto& h : p.second)\n\/\/ \t\t\t\t_varmap[hk].insert(_as.add_atom(h));\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\n\/\/ \/**\n\/\/ * Store new variable mapping.\n\/\/ *\n\/\/ * @param vm a HandleMap object containing additional mapping\n\/\/ *\/\n\/\/ void Target::store_varmap(HandleMap& vm)\n\/\/ {\n\/\/ \tfor (auto& p : vm)\n\/\/ \t{\n\/\/ \t\tHandle hk = _as.add_atom(p.first);\n\n\/\/ \t\tif (_varmap.count(hk) == 1)\n\/\/ \t\t\t_varmap[hk].insert(_as.add_atom(p.second));\n\/\/ \t}\n\/\/ }\n\n\/\/ \/**\n\/\/ * Count how many times a Rule was selected for the Target.\n\/\/ *\n\/\/ * This method follow the inference tree atom structure to find all usage.\n\/\/ *\n\/\/ * @param r the Rule to search\n\/\/ * @return the number of times applied\n\/\/ *\/\n\/\/ unsigned int Target::rule_count(const Rule& r) const\n\/\/ {\n\/\/ \tHandle hname = _as.get_node(NODE, r.get_name());\n\n\/\/ \t\/\/ if this rule's name never appear in history, it wasn't used\n\/\/ \tif (hname == Handle::UNDEFINED)\n\/\/ \t\treturn 0;\n\n\/\/ \tHandle htarget = _as.get_atom(_htarget);\n\n\/\/ \tif (htarget == Handle::UNDEFINED)\n\/\/ \t\treturn 0;\n\n\/\/ \tHandleSeq q = get_target_neighbors(htarget, SET_LINK);\n\n\/\/ \treturn std::count(q.begin(), q.end(), hname);\n\/\/ }\n\n\/\/ std::string Target::to_string()\n\/\/ {\n\/\/ \tstringstream ss;\n\/\/ \tss << \"Target handle = \" << get_handle()->toShortString();\n\/\/ \tss << \"With var_decl = \" << get_vardecl()->toShortString();\n\/\/ \treturn ss.str();\n\/\/ }\n\n\/\/ \/\/==================================================================\n\n\n\/\/ \/**\n\/\/ * Constructor.\n\/\/ *\/\n\/\/ TargetSet::TargetSet() : _total_selection(0)\n\/\/ {\n\n\/\/ }\n\n\/\/ \/**\n\/\/ * Destructor.\n\/\/ *\/\n\/\/ TargetSet::~TargetSet()\n\/\/ {\n\n\/\/ }\n\n\/\/ \/**\n\/\/ * Clear the TargetSet.\n\/\/ *\/\n\/\/ void TargetSet::clear()\n\/\/ {\n\/\/ \t_history_space.clear();\n\/\/ \t_targets_map.clear();\n\/\/ }\n\n\/\/ \/**\n\/\/ * Add a new Target into the set.\n\/\/ *\n\/\/ * @param h the atom to which the Target will be created\n\/\/ *\/\n\/\/ void TargetSet::emplace(Handle h, Handle hvardecl)\n\/\/ {\n\/\/ \th = _history_space.add_atom(h);\n\n\/\/ \tif (_targets_map.count(h) == 1)\n\/\/ \t\treturn;\n\n\/\/ \thvardecl = _history_space.add_atom(hvardecl);\n\n\/\/ \tLAZY_BC_LOG_DEBUG << \"[Target] Adding:\" << std::endl\n\/\/ \t << h->toShortString() << \"to target set\";\n\n\/\/ \t_targets_map.insert(std::pair(h, Target(_history_space, h, hvardecl)));\n\/\/ }\n\n\/\/ \/**\n\/\/ * Get the size of the TargetSet.\n\/\/ *\/\n\/\/ unsigned int TargetSet::size()\n\/\/ {\n\/\/ \treturn _targets_map.size();\n\/\/ }\n\n\/\/ \/**\n\/\/ * Select a Target from the set using some fitness criteria.\n\/\/ *\n\/\/ * Currently uses the selection count to apply weighted random selection.\n\/\/ *\n\/\/ * XXX TODO use criteria such as\n\/\/ * - how many steps from the initial target\n\/\/ * - how much was gained on this target the last time it was chosen\n\/\/ * etc\n\/\/ *\n\/\/ * @return a reference to the selected Target\n\/\/ *\/\n\/\/ Target& TargetSet::select()\n\/\/ {\n\/\/ \tHandleSeq handles;\n\/\/ \tstd::vector weights;\n\/\/ \tfor (auto& p : _targets_map)\n\/\/ \t{\n\/\/ \t\thandles.push_back(p.first);\n\n\/\/ \t\t\/\/ XXX TODO add more criteria to the weight calculation\n\/\/ \t\tweights.push_back(_total_selection - p.second.get_selection_count() + 1);\n\/\/ \t}\n\n\/\/ \tTarget& t = _targets_map.at(handles[randGen().rand_discrete(weights)]);\n\/\/ \tt.increment_selection_count();\n\n\/\/ \t_total_selection++;\n\n\/\/ \treturn t;\n\/\/ }\n\n\/\/ \/**\n\/\/ * Get a specific Target.\n\/\/ *\n\/\/ * @param h the handle of the Target\n\/\/ * @return a reference to the Target\n\/\/ *\/\n\/\/ Target& TargetSet::get(Handle h)\n\/\/ {\n\/\/ \treturn _targets_map.at(_history_space.get_atom(h));\n\/\/ }\n\/\/ #endif\n\n} \/\/ ~namespace opencog\nClean Target.cc\/*\n * Target.cc\n *\n * Author: William Ma \n *\n * Copyright (C) 2015 OpenCog Foundation\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 v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n\n#include \n#include \"Target.h\"\n#include \"BCLogger.h\"\n\nnamespace opencog {\n\nTarget::Target(const Handle& bd, const Handle& vd) : body(bd), vardecl(vd) {}\n\nstd::string\tTarget::to_string() const\n{\n\tstringstream ss;\n\tss << \"body:\" << std::endl << oc_to_string(body)\n\t << \"vardecl:\" << std::endl << oc_to_string(vardecl)\n\t << \"rules:\" << std::endl << oc_to_string(rules);\n\treturn ss.str();\n}\n\nstd::string oc_to_string(const Target& target)\n{\n\treturn target.to_string();\n}\n\n} \/\/ ~namespace opencog\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing eastl::vector;\nusing eastl::array;\nusing namespace std::chrono;\nusing sg14::fixed_point;\n\n#include \"NativeBitmap.h\"\n#include \"Vec2i.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CItem.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n#include \"IFileLoaderDelegate.h\"\n#include \"CGame.h\"\n#include \"CPlainFileLoader.h\"\n#include \"Vec2i.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CItem.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n#include \"commands\/IGameCommand.h\"\n#include \"RasterizerCommon.h\"\n#include \"CRenderer.h\"\n#include \"CPackedFileReader.h\"\n#include \"LoadPNG.h\"\n\nstd::shared_ptr renderer;\n\nenum ESoundDriver : uint8_t { kNone, kPcSpeaker, kOpl2Lpt, kTandy, kCovox };\n\nESoundDriver soundDriver = kNone;\nint soundTiming = 0;\n\nvoid initOPL2(int instrument);\nvoid playTune(const std::string&);\nvoid setupOPL2(int instrument);\nvoid stopSounds();\nvoid soundTick();\nvoid playMusic(int instrument, const std::string &musicTrack);\n\nvoid initOPL2(int instrument) {\n setupOPL2(instrument);\n}\n\nstd::function< std::string(std::string)> kDosLongFileNameTransformer = [](const std::string& filename ) {\n char c = 219;\n c = 176;\n c = 177;\n c = 178;\n c = '.';\n std::cout << c;\n std::cout.flush();\n\n auto dotPosition = std::find( std::begin(filename), std::end( filename), '.');\n auto indexDot = std::distance( std::begin( filename ), dotPosition );\n auto extension = filename.substr( indexDot + 1, 3 );\n\n if ( indexDot > 8 ) {\n return filename.substr( 0, 6 ) + \"~1.\" + extension;\n }\n\n if ( filename.length() - indexDot > 4 ) {\n return filename.substr( 0, indexDot ) + \"~1.\" + extension;\n }\n\n return filename;\n};\n\nvoid* operator new[](size_t size, const char* pName, int flags, unsigned debugFlags,\n const char* file, int line) {\n return malloc( size );\n}\n\nvoid* operator new[](size_t size, size_t alignment, size_t alignmentOffset, const char* pName,\n int flags, unsigned debugFlags, const char* file, int line) {\n return malloc( size );\n}\n\nvoid renderTick() {\n renderer->render( 33 );\n renderer->handleSystemEvents();\n}\n\nstd::shared_ptr game;\n\nint getchWithSoundTicks() {\n\n if (soundDriver != kNone ) {\n while (!kbhit()) {\n usleep((75) * 1000);\n soundTick();\n }\n\n stopSounds();\n }\n\n return getch();\n}\n\n\nvoid showText(std::shared_ptr bg, const std::string& mainText, const std::string& bottom ) {\n renderer->drawBitmap(0, 0, bg );\n renderer->fill(0, 64, 320, 200 - 64, 0 );\n renderer->flip();\n gotoxy(1,9);\n puts(mainText.c_str());\n gotoxy(1,25);\n printf(bottom.c_str());\n}\n\nvoid playSoundForAction(Knights::CommandType command ) {\n if (command == Knights::kUseCurrentItemInInventoryCommand) {\n playTune(\"aca\");\n }\n\n if (command == Knights::kCycleLeftInventoryCommand) {\n playTune(\"ac\");\n }\n\n if (command == Knights::kCycleRightInventoryCommand) {\n playTune(\"ca\");\n }\n\n if (command == Knights::kPickItemCommand) {\n playTune(\"abc\");\n }\n\n if (command == Knights::kDropItemCommand) {\n playTune(\"cba\");\n }\n}\n\nvoid handleConsoleLines( Knights::CommandType command, int playerHealthDiff, int targetHealthDiff, std::shared_ptr renderer, std::shared_ptr actorAtTarget ) {\n if ( command != '.') {\n char buffer[81];\n snprintf(buffer, 80, \"%s\", game->getLastCommand().c_str());\n renderer->appendToLog( buffer );\n }\n\n if ( targetHealthDiff < 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player dealt %d of damage\", -targetHealthDiff );\n renderer->appendToLog( buffer );\n if (actorAtTarget == nullptr || !actorAtTarget->isAlive()) {\n renderer->addDeathAt(actorAtTarget->getPosition());\n } else {\n renderer->addSplatAt(actorAtTarget->getPosition());\n }\n }\n\n if ( playerHealthDiff < 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player took %d of damage\", -playerHealthDiff);\n renderer->appendToLog( buffer );\n renderer->startDamageHighlight();\n } else if ( playerHealthDiff > 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player gained %d of faith\", playerHealthDiff);\n renderer->appendToLog( buffer );\n renderer->startHealHighlight();\n }\n}\n\nint main(int argc, char **argv) {\n int instrument = -1;\n\n const auto LEVEL_LIMIT = 7;\n clock_t t0;\n clock_t t1;\n int healthAtTargetBefore = 0;\n int healthAtTargetAfter = 0;\n auto delegate = std::make_shared();\n auto fileLoader = std::make_shared(\"data.pfs\");\n auto bg = loadPNG( \"intro.png\", fileLoader );\n\n puts(\"Dungeons of Noudar 486 tech demo startup. Gonna load some stuff...\");\n\n if ( argc >= 2 ) {\n if ( !std::strcmp(argv[1], \"pcspeaker\")) {\n soundDriver = kPcSpeaker;\n soundTiming = 100;\n }\n\n if ( !std::strcmp(argv[1], \"opl2lpt\")) {\n instrument = 80;\n soundTiming = 75;\n soundDriver = kOpl2Lpt;\n\n if (argc >= 3 ) {\n instrument = atoi(argv[2]);\n }\n\n initOPL2(instrument);\n }\n }\n\n renderer = std::make_shared();\n\n auto titleText = fileLoader->loadFileFromPath(\"title.txt\");\n showText(bg, titleText, \"Press any key to continue\");\n getchWithSoundTicks();\n\n auto onLevelWillLoad = [&]() {\n showText(bg, \"\", \"Loading...\");\n };\n delegate->setOnLevelWillLoadCallback(onLevelWillLoad );\n\n game = std::make_shared( fileLoader, renderer, delegate );\n auto tileProperties = odb::loadTileProperties(game->getLevelNumber(), fileLoader);\n renderer->loadTextures( odb::loadTexturesForLevel(game->getLevelNumber(), fileLoader), tileProperties);\n\n char buffer[40];\n snprintf(buffer, 40, \"chapter%d.txt\", game->getLevelNumber() );\n auto introText = fileLoader->loadFileFromPath(buffer);\n\n playTune(\"e8e8f8g8g8f8e8d8c8c8d8e8e8d12d4e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4d8d8e8c8d8e12f12e8c8d8e12f12e8d8c8d8p8e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4\");\n showText(bg, introText, \"Press any key to start\" );\n getchWithSoundTicks();\n\n auto onLevelLoaded = [&]() {\n\n if (game != nullptr ) {\n if ( game->getLevelNumber() >= LEVEL_LIMIT ) {\n game->setIsPlaying( false );\n } else {\n auto tileProperties = odb::loadTileProperties(game->getLevelNumber(), fileLoader);\n renderer->loadTextures( odb::loadTexturesForLevel(game->getLevelNumber(), fileLoader), tileProperties);\n\n char buffer[40];\n snprintf(buffer, 40, \"chapter%d.txt\", game->getLevelNumber() );\n auto chapterText = fileLoader->loadFileFromPath(buffer);\n\n playTune(\"e8e8f8g8g8f8e8d8c8c8d8e8e8d12d4e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4d8d8e8c8d8e12f12e8c8d8e12f12e8d8c8d8p8e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4\");\n showText(bg, chapterText, \"Press any key to start\");\n getchWithSoundTicks();\n }\n }\n };\n delegate->setOnLevelLoadedCallback(onLevelLoaded );\n\n auto noteTime = soundTiming;\n\n while ( game->isPlaying() ) {\n\n if (soundDriver != kNone ) {\n t0 = uclock();\n }\n\n auto playerHealthBefore = game->getMap()->getAvatar()->getHP();\n auto cursorPosition = game->getMap()->getTargetProjection(game->getMap()->getAvatar());\n auto actorAtTarget = game->getMap()->getActorAt(cursorPosition);\n\n if ( actorAtTarget != nullptr ) {\n healthAtTargetBefore = actorAtTarget->getHP();\n } else {\n healthAtTargetBefore = 0;\n }\n\n game->tick();\n renderTick();\n Knights::CommandType command = renderer->peekInput();\n game->tick();\n\n if ( actorAtTarget != nullptr ) {\n healthAtTargetAfter = actorAtTarget->getHP();\n } else {\n healthAtTargetAfter = 0;\n }\n\n auto targetHealthDiff = healthAtTargetAfter - healthAtTargetBefore;\n auto playerHealthAfter = game->getMap()->getAvatar()->getHP();\n auto playerHealthDiff = playerHealthAfter - playerHealthBefore;\n\n handleConsoleLines( command, playerHealthDiff, targetHealthDiff, renderer, actorAtTarget );\n\n if (soundDriver != kNone ) {\n\n playSoundForAction(command);\n\n t1 = uclock();\n auto diff = (1000 * (t1 - t0)) \/ UCLOCKS_PER_SEC;\n if (diff == 0) {\n diff = 1;\n }\n noteTime -= diff;\n\n if (noteTime < 0) {\n noteTime = soundTiming;\n soundTick();\n }\n }\n\n }\n\n stopSounds();\n\n return 0;\n}\nMake action sounds longer\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing eastl::vector;\nusing eastl::array;\nusing namespace std::chrono;\nusing sg14::fixed_point;\n\n#include \"NativeBitmap.h\"\n#include \"Vec2i.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CItem.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n#include \"IFileLoaderDelegate.h\"\n#include \"CGame.h\"\n#include \"CPlainFileLoader.h\"\n#include \"Vec2i.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CItem.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n#include \"commands\/IGameCommand.h\"\n#include \"RasterizerCommon.h\"\n#include \"CRenderer.h\"\n#include \"CPackedFileReader.h\"\n#include \"LoadPNG.h\"\n\nstd::shared_ptr renderer;\n\nenum ESoundDriver : uint8_t { kNone, kPcSpeaker, kOpl2Lpt, kTandy, kCovox };\n\nESoundDriver soundDriver = kNone;\nint soundTiming = 0;\n\nvoid initOPL2(int instrument);\nvoid playTune(const std::string&);\nvoid setupOPL2(int instrument);\nvoid stopSounds();\nvoid soundTick();\nvoid playMusic(int instrument, const std::string &musicTrack);\n\nvoid initOPL2(int instrument) {\n setupOPL2(instrument);\n}\n\nstd::function< std::string(std::string)> kDosLongFileNameTransformer = [](const std::string& filename ) {\n char c = 219;\n c = 176;\n c = 177;\n c = 178;\n c = '.';\n std::cout << c;\n std::cout.flush();\n\n auto dotPosition = std::find( std::begin(filename), std::end( filename), '.');\n auto indexDot = std::distance( std::begin( filename ), dotPosition );\n auto extension = filename.substr( indexDot + 1, 3 );\n\n if ( indexDot > 8 ) {\n return filename.substr( 0, 6 ) + \"~1.\" + extension;\n }\n\n if ( filename.length() - indexDot > 4 ) {\n return filename.substr( 0, indexDot ) + \"~1.\" + extension;\n }\n\n return filename;\n};\n\nvoid* operator new[](size_t size, const char* pName, int flags, unsigned debugFlags,\n const char* file, int line) {\n return malloc( size );\n}\n\nvoid* operator new[](size_t size, size_t alignment, size_t alignmentOffset, const char* pName,\n int flags, unsigned debugFlags, const char* file, int line) {\n return malloc( size );\n}\n\nvoid renderTick() {\n renderer->render( 33 );\n renderer->handleSystemEvents();\n}\n\nstd::shared_ptr game;\n\nint getchWithSoundTicks() {\n\n if (soundDriver != kNone ) {\n while (!kbhit()) {\n usleep((75) * 1000);\n soundTick();\n }\n\n stopSounds();\n }\n\n return getch();\n}\n\n\nvoid showText(std::shared_ptr bg, const std::string& mainText, const std::string& bottom ) {\n renderer->drawBitmap(0, 0, bg );\n renderer->fill(0, 64, 320, 200 - 64, 0 );\n renderer->flip();\n gotoxy(1,9);\n puts(mainText.c_str());\n gotoxy(1,25);\n printf(bottom.c_str());\n}\n\nvoid playSoundForAction(Knights::CommandType command ) {\n if (command == Knights::kUseCurrentItemInInventoryCommand) {\n playTune(\"aca\");\n }\n\n if (command == Knights::kCycleLeftInventoryCommand) {\n playTune(\"abc\");\n }\n\n if (command == Knights::kCycleRightInventoryCommand) {\n playTune(\"cba\");\n }\n\n if (command == Knights::kPickItemCommand) {\n playTune(\"defg\");\n }\n\n if (command == Knights::kDropItemCommand) {\n playTune(\"gfed\");\n }\n}\n\nvoid handleConsoleLines( Knights::CommandType command, int playerHealthDiff, int targetHealthDiff, std::shared_ptr renderer, std::shared_ptr actorAtTarget ) {\n if ( command != '.') {\n char buffer[81];\n snprintf(buffer, 80, \"%s\", game->getLastCommand().c_str());\n renderer->appendToLog( buffer );\n }\n\n if ( targetHealthDiff < 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player dealt %d of damage\", -targetHealthDiff );\n renderer->appendToLog( buffer );\n if (actorAtTarget == nullptr || !actorAtTarget->isAlive()) {\n renderer->addDeathAt(actorAtTarget->getPosition());\n } else {\n renderer->addSplatAt(actorAtTarget->getPosition());\n }\n }\n\n if ( playerHealthDiff < 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player took %d of damage\", -playerHealthDiff);\n renderer->appendToLog( buffer );\n renderer->startDamageHighlight();\n } else if ( playerHealthDiff > 0 ) {\n char buffer[81];\n snprintf(buffer, 80, \"Player gained %d of faith\", playerHealthDiff);\n renderer->appendToLog( buffer );\n renderer->startHealHighlight();\n }\n}\n\nint main(int argc, char **argv) {\n int instrument = -1;\n\n const auto LEVEL_LIMIT = 7;\n clock_t t0;\n clock_t t1;\n int healthAtTargetBefore = 0;\n int healthAtTargetAfter = 0;\n auto delegate = std::make_shared();\n auto fileLoader = std::make_shared(\"data.pfs\");\n auto bg = loadPNG( \"intro.png\", fileLoader );\n\n puts(\"Dungeons of Noudar 486 tech demo startup. Gonna load some stuff...\");\n\n if ( argc >= 2 ) {\n if ( !std::strcmp(argv[1], \"pcspeaker\")) {\n soundDriver = kPcSpeaker;\n soundTiming = 100;\n }\n\n if ( !std::strcmp(argv[1], \"opl2lpt\")) {\n instrument = 80;\n soundTiming = 75;\n soundDriver = kOpl2Lpt;\n\n if (argc >= 3 ) {\n instrument = atoi(argv[2]);\n }\n\n initOPL2(instrument);\n }\n }\n\n renderer = std::make_shared();\n\n auto titleText = fileLoader->loadFileFromPath(\"title.txt\");\n showText(bg, titleText, \"Press any key to continue\");\n getchWithSoundTicks();\n\n auto onLevelWillLoad = [&]() {\n showText(bg, \"\", \"Loading...\");\n };\n delegate->setOnLevelWillLoadCallback(onLevelWillLoad );\n\n game = std::make_shared( fileLoader, renderer, delegate );\n auto tileProperties = odb::loadTileProperties(game->getLevelNumber(), fileLoader);\n renderer->loadTextures( odb::loadTexturesForLevel(game->getLevelNumber(), fileLoader), tileProperties);\n\n char buffer[40];\n snprintf(buffer, 40, \"chapter%d.txt\", game->getLevelNumber() );\n auto introText = fileLoader->loadFileFromPath(buffer);\n\n playTune(\"e8e8f8g8g8f8e8d8c8c8d8e8e8d12d4e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4d8d8e8c8d8e12f12e8c8d8e12f12e8d8c8d8p8e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4\");\n showText(bg, introText, \"Press any key to start\" );\n getchWithSoundTicks();\n\n auto onLevelLoaded = [&]() {\n\n if (game != nullptr ) {\n if ( game->getLevelNumber() >= LEVEL_LIMIT ) {\n game->setIsPlaying( false );\n } else {\n auto tileProperties = odb::loadTileProperties(game->getLevelNumber(), fileLoader);\n renderer->loadTextures( odb::loadTexturesForLevel(game->getLevelNumber(), fileLoader), tileProperties);\n\n char buffer[40];\n snprintf(buffer, 40, \"chapter%d.txt\", game->getLevelNumber() );\n auto chapterText = fileLoader->loadFileFromPath(buffer);\n\n playTune(\"e8e8f8g8g8f8e8d8c8c8d8e8e8d12d4e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4d8d8e8c8d8e12f12e8c8d8e12f12e8d8c8d8p8e8e8f8g8g8f8e8d8c8c8d8e8d8c12c4\");\n showText(bg, chapterText, \"Press any key to start\");\n getchWithSoundTicks();\n }\n }\n };\n delegate->setOnLevelLoadedCallback(onLevelLoaded );\n\n auto noteTime = soundTiming;\n\n while ( game->isPlaying() ) {\n\n if (soundDriver != kNone ) {\n t0 = uclock();\n }\n\n auto playerHealthBefore = game->getMap()->getAvatar()->getHP();\n auto cursorPosition = game->getMap()->getTargetProjection(game->getMap()->getAvatar());\n auto actorAtTarget = game->getMap()->getActorAt(cursorPosition);\n\n if ( actorAtTarget != nullptr ) {\n healthAtTargetBefore = actorAtTarget->getHP();\n } else {\n healthAtTargetBefore = 0;\n }\n\n game->tick();\n renderTick();\n Knights::CommandType command = renderer->peekInput();\n game->tick();\n\n if ( actorAtTarget != nullptr ) {\n healthAtTargetAfter = actorAtTarget->getHP();\n } else {\n healthAtTargetAfter = 0;\n }\n\n auto targetHealthDiff = healthAtTargetAfter - healthAtTargetBefore;\n auto playerHealthAfter = game->getMap()->getAvatar()->getHP();\n auto playerHealthDiff = playerHealthAfter - playerHealthBefore;\n\n handleConsoleLines( command, playerHealthDiff, targetHealthDiff, renderer, actorAtTarget );\n\n if (soundDriver != kNone ) {\n\n playSoundForAction(command);\n\n t1 = uclock();\n auto diff = (1000 * (t1 - t0)) \/ UCLOCKS_PER_SEC;\n if (diff == 0) {\n diff = 1;\n }\n noteTime -= diff;\n\n if (noteTime < 0) {\n noteTime = soundTiming;\n soundTick();\n }\n }\n\n }\n\n stopSounds();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\r\n\/\/ MeshFactoryTest.cc\r\n\/\/------------------------------------------------------------------------------\r\n#include \"Pre.h\"\r\n#include \"UnitTest++\/src\/UnitTest++.h\"\r\n#include \"Render\/Core\/stateWrapper.h\"\r\n#include \"Render\/Core\/meshFactory.h\"\r\n#include \"Render\/Setup\/RenderSetup.h\"\r\n#include \"Render\/Core\/displayMgr.h\"\r\n#include \"Render\/Util\/MeshBuilder.h\"\r\n#include \"Render\/Util\/RawMeshLoader.h\"\r\n\r\n#if ORYOL_OPENGL\r\n#include \"Render\/gl\/gl_impl.h\"\r\n#endif\r\n\r\nusing namespace Oryol;\r\nusing namespace Oryol::Core;\r\nusing namespace Oryol::IO;\r\nusing namespace Oryol::Render;\r\nusing namespace Oryol::Resource;\r\n\r\n\/\/ NOTE: this is should not be treated as sample code on how\r\n\/\/ to initialize a mesh!\r\nTEST(MeshFactoryTest) {\r\n \r\n \/\/ setup a GL context\r\n auto renderSetup = RenderSetup::Windowed(400, 300, \"Oryol Test\");\r\n displayMgr displayManager;\r\n displayManager.SetupDisplay(renderSetup);\r\n \r\n \/\/ setup a meshFactory object\r\n stateWrapper stWrapper;\r\n meshFactory factory;\r\n factory.Setup(&stWrapper);\r\n factory.AttachLoader(RawMeshLoader::Create());\r\n \r\n \/\/ setup a MeshBuilder and create mesh geometry\r\n MeshBuilder mb;\r\n mb.SetNumVertices(4);\r\n mb.SetNumIndices(6);\r\n mb.AddComponent(VertexAttr::Position, VertexFormat::Float3);\r\n mb.AddComponent(VertexAttr::TexCoord0, VertexFormat::Float2);\r\n mb.AddPrimitiveGroup(PrimitiveType::Triangles, 0, 6);\r\n mb.Begin();\r\n mb.Vertex(0, VertexAttr::Position, 0.0f, 0.0f, 0.0f); \/\/ top-left\r\n mb.Vertex(1, VertexAttr::Position, 1.0f, 0.0f, 0.0f); \/\/ top-right\r\n mb.Vertex(2, VertexAttr::Position, 1.0f, 1.0f, 0.0f); \/\/ bottom-right\r\n mb.Vertex(3, VertexAttr::Position, 0.0f, 1.0f, 0.0f); \/\/ bottom-left\r\n mb.Vertex(0, VertexAttr::TexCoord0, 0.0f, 0.0f);\r\n mb.Vertex(1, VertexAttr::TexCoord0, 1.0f, 0.0f);\r\n mb.Vertex(2, VertexAttr::TexCoord0, 1.0f, 1.0f);\r\n mb.Vertex(3, VertexAttr::TexCoord0, 0.0f, 1.0f);\r\n mb.Triangle(0, 0, 1, 2);\r\n mb.Triangle(1, 0, 2, 3);\r\n mb.End();\r\n \r\n \/\/ setup the mesh\r\n const Ptr& meshData = mb.GetStream();\r\n mesh mesh;\r\n mesh.setSetup(MeshSetup::FromData(Locator(\"myQuad\")));\r\n mesh.setState(Resource::State::Setup);\r\n \r\n factory.SetupResource(mesh, meshData);\r\n CHECK(mesh.GetState() == Resource::State::Valid);\r\n CHECK(!mesh.GetId().IsValid());\r\n CHECK(mesh.GetSetup().GetLocator().Location() == \"myQuad\");\r\n CHECK(mesh.GetVertexBufferAttrs().GetNumVertices() == 4);\r\n CHECK(mesh.GetVertexBufferAttrs().GetUsage() == Usage::Immutable);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetNumComponents() == 2);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetByteSize() == 20);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponentByteOffset(0) == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponentByteOffset(1) == 12);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetAttr() == VertexAttr::Position);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetFormat() == VertexFormat::Float3);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetByteSize() == 12);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetAttr() == VertexAttr::TexCoord0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetFormat() == VertexFormat::Float2);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetByteSize() == 8);\r\n CHECK(mesh.GetIndexBufferAttrs().GetNumIndices() == 6);\r\n CHECK(mesh.GetIndexBufferAttrs().GetIndexType() == IndexType::Index16);\r\n CHECK(mesh.GetIndexBufferAttrs().GetUsage() == Usage::Immutable);\r\n CHECK(mesh.GetIndexBufferAttrs().GetByteSize() == 12);\r\n CHECK(mesh.GetNumPrimitiveGroups() == 1);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetPrimitiveType() == PrimitiveType::Triangles);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetBaseElement() == 0);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetNumElements() == 6);\r\n #if ORYOL_OPENGL\r\n CHECK(mesh.glGetVertexBuffer() != 0);\r\n CHECK(mesh.glGetIndexBuffer() != 0);\r\n CHECK(mesh.glGetVertexArrayObject() != 0);\r\n for (uint32 i = 0; i < VertexAttr::NumVertexAttrs; i++) {\r\n const glVertexAttr& glAttr = mesh.glAttr(i);\r\n CHECK(glAttr.index == i);\r\n if (VertexAttr::Position == i) {\r\n CHECK(glAttr.enabled == GL_TRUE);\r\n CHECK(glAttr.size == 3);\r\n CHECK(glAttr.stride == 20);\r\n CHECK(glAttr.offset == 0);\r\n CHECK(glAttr.type == GL_FLOAT);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n else if (VertexAttr::TexCoord0 == i) {\r\n CHECK(glAttr.enabled == GL_TRUE);\r\n CHECK(glAttr.size == 2);\r\n CHECK(glAttr.stride == 20);\r\n CHECK(glAttr.offset == 12);\r\n CHECK(glAttr.type == GL_FLOAT);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n else {\r\n CHECK(glAttr.enabled == GL_FALSE);\r\n CHECK(glAttr.size == 0);\r\n CHECK(glAttr.stride == 0);\r\n CHECK(glAttr.offset == 0);\r\n CHECK(glAttr.type == 0);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n }\r\n #endif\r\n \r\n factory.DestroyResource(mesh);\r\n CHECK(mesh.GetState() == Resource::State::Setup);\r\n CHECK(!mesh.GetId().IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetNumVertices() == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetUsage() == Usage::InvalidUsage);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetNumComponents() == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetByteSize() == 0);\r\n CHECK(mesh.GetIndexBufferAttrs().GetNumIndices() == 0);\r\n CHECK(mesh.GetIndexBufferAttrs().GetIndexType() == IndexType::InvalidIndexType);\r\n CHECK(mesh.GetIndexBufferAttrs().GetUsage() == Usage::InvalidUsage);\r\n CHECK(mesh.GetNumPrimitiveGroups() == 0);\r\n factory.Discard();\r\n displayManager.DiscardDisplay();\r\n}Removed redundant code from MeshFactoryTest\/\/------------------------------------------------------------------------------\r\n\/\/ MeshFactoryTest.cc\r\n\/\/------------------------------------------------------------------------------\r\n#include \"Pre.h\"\r\n#include \"UnitTest++\/src\/UnitTest++.h\"\r\n#include \"Render\/Core\/stateWrapper.h\"\r\n#include \"Render\/Core\/meshFactory.h\"\r\n#include \"Render\/Setup\/RenderSetup.h\"\r\n#include \"Render\/Core\/displayMgr.h\"\r\n#include \"Render\/Util\/MeshBuilder.h\"\r\n#include \"Render\/Util\/RawMeshLoader.h\"\r\n\r\n#if ORYOL_OPENGL\r\n#include \"Render\/gl\/gl_impl.h\"\r\n#endif\r\n\r\nusing namespace Oryol;\r\nusing namespace Oryol::Core;\r\nusing namespace Oryol::IO;\r\nusing namespace Oryol::Render;\r\nusing namespace Oryol::Resource;\r\n\r\n\/\/ NOTE: this is should not be treated as sample code on how\r\n\/\/ to initialize a mesh!\r\nTEST(MeshFactoryTest) {\r\n \r\n \/\/ setup a GL context\r\n auto renderSetup = RenderSetup::Windowed(400, 300, \"Oryol Test\");\r\n displayMgr displayManager;\r\n displayManager.SetupDisplay(renderSetup);\r\n \r\n \/\/ setup a meshFactory object\r\n stateWrapper stWrapper;\r\n meshFactory factory;\r\n factory.Setup(&stWrapper);\r\n factory.AttachLoader(RawMeshLoader::Create());\r\n \r\n \/\/ setup a MeshBuilder and create mesh geometry\r\n MeshBuilder mb;\r\n mb.SetNumVertices(4);\r\n mb.SetNumIndices(6);\r\n mb.AddComponent(VertexAttr::Position, VertexFormat::Float3);\r\n mb.AddComponent(VertexAttr::TexCoord0, VertexFormat::Float2);\r\n mb.AddPrimitiveGroup(PrimitiveType::Triangles, 0, 6);\r\n mb.Begin();\r\n mb.Vertex(0, VertexAttr::Position, 0.0f, 0.0f, 0.0f); \/\/ top-left\r\n mb.Vertex(1, VertexAttr::Position, 1.0f, 0.0f, 0.0f); \/\/ top-right\r\n mb.Vertex(2, VertexAttr::Position, 1.0f, 1.0f, 0.0f); \/\/ bottom-right\r\n mb.Vertex(3, VertexAttr::Position, 0.0f, 1.0f, 0.0f); \/\/ bottom-left\r\n mb.Vertex(0, VertexAttr::TexCoord0, 0.0f, 0.0f);\r\n mb.Vertex(1, VertexAttr::TexCoord0, 1.0f, 0.0f);\r\n mb.Vertex(2, VertexAttr::TexCoord0, 1.0f, 1.0f);\r\n mb.Vertex(3, VertexAttr::TexCoord0, 0.0f, 1.0f);\r\n mb.Triangle(0, 0, 1, 2);\r\n mb.Triangle(1, 0, 2, 3);\r\n mb.End();\r\n \r\n \/\/ setup the mesh\r\n const Ptr& meshData = mb.GetStream();\r\n mesh mesh;\r\n mesh.setSetup(MeshSetup::FromData(Locator(\"myQuad\")));\r\n \r\n factory.SetupResource(mesh, meshData);\r\n CHECK(mesh.GetState() == Resource::State::Valid);\r\n CHECK(!mesh.GetId().IsValid());\r\n CHECK(mesh.GetSetup().GetLocator().Location() == \"myQuad\");\r\n CHECK(mesh.GetVertexBufferAttrs().GetNumVertices() == 4);\r\n CHECK(mesh.GetVertexBufferAttrs().GetUsage() == Usage::Immutable);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetNumComponents() == 2);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetByteSize() == 20);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponentByteOffset(0) == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponentByteOffset(1) == 12);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetAttr() == VertexAttr::Position);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetFormat() == VertexFormat::Float3);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(0).GetByteSize() == 12);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetAttr() == VertexAttr::TexCoord0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetFormat() == VertexFormat::Float2);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetComponent(1).GetByteSize() == 8);\r\n CHECK(mesh.GetIndexBufferAttrs().GetNumIndices() == 6);\r\n CHECK(mesh.GetIndexBufferAttrs().GetIndexType() == IndexType::Index16);\r\n CHECK(mesh.GetIndexBufferAttrs().GetUsage() == Usage::Immutable);\r\n CHECK(mesh.GetIndexBufferAttrs().GetByteSize() == 12);\r\n CHECK(mesh.GetNumPrimitiveGroups() == 1);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetPrimitiveType() == PrimitiveType::Triangles);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetBaseElement() == 0);\r\n CHECK(mesh.GetPrimitiveGroup(0).GetNumElements() == 6);\r\n #if ORYOL_OPENGL\r\n CHECK(mesh.glGetVertexBuffer() != 0);\r\n CHECK(mesh.glGetIndexBuffer() != 0);\r\n CHECK(mesh.glGetVertexArrayObject() != 0);\r\n for (uint32 i = 0; i < VertexAttr::NumVertexAttrs; i++) {\r\n const glVertexAttr& glAttr = mesh.glAttr(i);\r\n CHECK(glAttr.index == i);\r\n if (VertexAttr::Position == i) {\r\n CHECK(glAttr.enabled == GL_TRUE);\r\n CHECK(glAttr.size == 3);\r\n CHECK(glAttr.stride == 20);\r\n CHECK(glAttr.offset == 0);\r\n CHECK(glAttr.type == GL_FLOAT);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n else if (VertexAttr::TexCoord0 == i) {\r\n CHECK(glAttr.enabled == GL_TRUE);\r\n CHECK(glAttr.size == 2);\r\n CHECK(glAttr.stride == 20);\r\n CHECK(glAttr.offset == 12);\r\n CHECK(glAttr.type == GL_FLOAT);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n else {\r\n CHECK(glAttr.enabled == GL_FALSE);\r\n CHECK(glAttr.size == 0);\r\n CHECK(glAttr.stride == 0);\r\n CHECK(glAttr.offset == 0);\r\n CHECK(glAttr.type == 0);\r\n CHECK(glAttr.normalized == GL_FALSE);\r\n }\r\n }\r\n #endif\r\n \r\n factory.DestroyResource(mesh);\r\n CHECK(mesh.GetState() == Resource::State::Setup);\r\n CHECK(!mesh.GetId().IsValid());\r\n CHECK(mesh.GetVertexBufferAttrs().GetNumVertices() == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetUsage() == Usage::InvalidUsage);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetNumComponents() == 0);\r\n CHECK(mesh.GetVertexBufferAttrs().GetVertexLayout().GetByteSize() == 0);\r\n CHECK(mesh.GetIndexBufferAttrs().GetNumIndices() == 0);\r\n CHECK(mesh.GetIndexBufferAttrs().GetIndexType() == IndexType::InvalidIndexType);\r\n CHECK(mesh.GetIndexBufferAttrs().GetUsage() == Usage::InvalidUsage);\r\n CHECK(mesh.GetNumPrimitiveGroups() == 0);\r\n factory.Discard();\r\n displayManager.DiscardDisplay();\r\n}<|endoftext|>"} {"text":"\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Nathan, liujun@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not 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 disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ 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\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n#include \"test_precomp.hpp\"\n#include \n\nusing namespace cv;\nusing namespace cv::ocl;\nusing namespace testing;\nusing namespace std;\n\ntemplate \nstatic void blendLinearGold(const Mat &img1, const Mat &img2,\n const Mat &weights1, const Mat &weights2,\n Mat &result_gold)\n{\n CV_Assert(img1.size() == img2.size() && img1.type() == img2.type());\n CV_Assert(weights1.size() == weights2.size() && weights1.size() == img1.size() &&\n weights1.type() == CV_32FC1 && weights2.type() == CV_32FC1);\n\n result_gold.create(img1.size(), img1.type());\n\n int cn = img1.channels();\n int step1 = img1.cols * img1.channels();\n\n for (int y = 0; y < img1.rows; ++y)\n {\n const float * const weights1_row = weights1.ptr(y);\n const float * const weights2_row = weights2.ptr(y);\n const T * const img1_row = img1.ptr(y);\n const T * const img2_row = img2.ptr(y);\n T * const result_gold_row = result_gold.ptr(y);\n\n for (int x = 0; x < step1; ++x)\n {\n int x1 = x \/ cn;\n float w1 = weights1_row[x1], w2 = weights2_row[x1];\n result_gold_row[x] = saturate_cast(((float)img1_row[x] * w1\n + (float)img2_row[x] * w2) \/ (w1 + w2 + 1e-5f));\n }\n }\n}\n\nPARAM_TEST_CASE(Blend, MatDepth, int, bool)\n{\n int depth, channels;\n bool useRoi;\n\n Mat src1, src2, weights1, weights2, dst;\n Mat src1_roi, src2_roi, weights1_roi, weights2_roi, dst_roi;\n oclMat gsrc1, gsrc2, gweights1, gweights2, gdst, gst;\n oclMat gsrc1_roi, gsrc2_roi, gweights1_roi, gweights2_roi, gdst_roi;\n\n virtual void SetUp()\n {\n depth = GET_PARAM(0);\n channels = GET_PARAM(1);\n useRoi = GET_PARAM(2);\n }\n\n void random_roi()\n {\n const int type = CV_MAKE_TYPE(depth, channels);\n\n const double upValue = 1200;\n\n Size roiSize = randomSize(1, 20);\n Border src1Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(src1, src1_roi, roiSize, src1Border, type, -upValue, upValue);\n\n Border src2Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(src2, src2_roi, roiSize, src2Border, type, -upValue, upValue);\n\n Border weights1Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(weights1, weights1_roi, roiSize, weights1Border, CV_32FC1, -upValue, upValue);\n\n Border weights2Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(weights2, weights2_roi, roiSize, weights2Border, CV_32FC1, -upValue, upValue);\n\n Border dstBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(dst, dst_roi, roiSize, dstBorder, type, 5, 16);\n\n generateOclMat(gsrc1, gsrc1_roi, src1, roiSize, src1Border);\n generateOclMat(gsrc2, gsrc2_roi, src2, roiSize, src2Border);\n generateOclMat(gweights1, gweights1_roi, weights1, roiSize, weights1Border);\n generateOclMat(gweights2, gweights2_roi, weights2, roiSize, weights2Border);\n generateOclMat(gdst, gdst_roi, dst, roiSize, dstBorder);\n }\n\n void Near(double eps = 0.0)\n {\n Mat whole, roi;\n gdst.download(whole);\n gdst_roi.download(roi);\n\n EXPECT_MAT_NEAR(dst, whole, eps);\n EXPECT_MAT_NEAR(dst_roi, roi, eps);\n }\n};\n\ntypedef void (*blendLinearFunc)(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &weights1, const cv::Mat &weights2, cv::Mat &result_gold);\n\nOCL_TEST_P(Blend, Accuracy)\n{\n for (int i = 0; i < LOOP_TIMES; ++i)\n {\n random_roi();\n\n cv::ocl::blendLinear(gsrc1_roi, gsrc2_roi, gweights1_roi, gweights2_roi, gdst_roi);\n\n static blendLinearFunc funcs[] = {\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n };\n\n blendLinearFunc func = funcs[depth];\n func(src1_roi, src2_roi, weights1_roi, weights2_roi, dst_roi);\n\n Near(depth <= CV_32S ? 1.0 : 0.2);\n }\n}\n\nINSTANTIATE_TEST_CASE_P(OCL_ImgProc, Blend,\n Combine(testing::Values(CV_8U, CV_8S, CV_16U, CV_16S, CV_32S, CV_32F),\n testing::Range(1, 5), Bool()));\nocl: fix testdata for blendLinear\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.\n\/\/ Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ @Authors\n\/\/ Nathan, liujun@multicorewareinc.com\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not 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 disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ 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\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n#include \"test_precomp.hpp\"\n#include \n\nusing namespace cv;\nusing namespace cv::ocl;\nusing namespace testing;\nusing namespace std;\n\ntemplate \nstatic void blendLinearGold(const Mat &img1, const Mat &img2,\n const Mat &weights1, const Mat &weights2,\n Mat &result_gold)\n{\n CV_Assert(img1.size() == img2.size() && img1.type() == img2.type());\n CV_Assert(weights1.size() == weights2.size() && weights1.size() == img1.size() &&\n weights1.type() == CV_32FC1 && weights2.type() == CV_32FC1);\n\n result_gold.create(img1.size(), img1.type());\n\n int cn = img1.channels();\n int step1 = img1.cols * img1.channels();\n\n for (int y = 0; y < img1.rows; ++y)\n {\n const float * const weights1_row = weights1.ptr(y);\n const float * const weights2_row = weights2.ptr(y);\n const T * const img1_row = img1.ptr(y);\n const T * const img2_row = img2.ptr(y);\n T * const result_gold_row = result_gold.ptr(y);\n\n for (int x = 0; x < step1; ++x)\n {\n int x1 = x \/ cn;\n float w1 = weights1_row[x1], w2 = weights2_row[x1];\n result_gold_row[x] = saturate_cast(((float)img1_row[x] * w1\n + (float)img2_row[x] * w2) \/ (w1 + w2 + 1e-5f));\n }\n }\n}\n\nPARAM_TEST_CASE(Blend, MatDepth, int, bool)\n{\n int depth, channels;\n bool useRoi;\n\n Mat src1, src2, weights1, weights2, dst;\n Mat src1_roi, src2_roi, weights1_roi, weights2_roi, dst_roi;\n oclMat gsrc1, gsrc2, gweights1, gweights2, gdst, gst;\n oclMat gsrc1_roi, gsrc2_roi, gweights1_roi, gweights2_roi, gdst_roi;\n\n virtual void SetUp()\n {\n depth = GET_PARAM(0);\n channels = GET_PARAM(1);\n useRoi = GET_PARAM(2);\n }\n\n void random_roi()\n {\n const int type = CV_MAKE_TYPE(depth, channels);\n\n const double upValue = 256;\n const double sumMinValue = 0.01; \/\/ we don't want to divide by \"zero\"\n\n Size roiSize = randomSize(1, 20);\n Border src1Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(src1, src1_roi, roiSize, src1Border, type, -upValue, upValue);\n\n Border src2Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(src2, src2_roi, roiSize, src2Border, type, -upValue, upValue);\n\n Border weights1Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(weights1, weights1_roi, roiSize, weights1Border, CV_32FC1, -upValue, upValue);\n\n Border weights2Border = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(weights2, weights2_roi, roiSize, weights2Border, CV_32FC1, sumMinValue, upValue); \/\/ fill it as a (w1 + w12)\n\n weights2_roi = weights2_roi - weights1_roi;\n \/\/ check that weights2_roi is still a part of weights2 (not a new matrix)\n CV_Assert(checkNorm(weights2_roi,\n weights2(Rect(weights2Border.lef, weights2Border.top, roiSize.width, roiSize.height))) < 1e-6);\n\n Border dstBorder = randomBorder(0, useRoi ? MAX_VALUE : 0);\n randomSubMat(dst, dst_roi, roiSize, dstBorder, type, 5, 16);\n\n generateOclMat(gsrc1, gsrc1_roi, src1, roiSize, src1Border);\n generateOclMat(gsrc2, gsrc2_roi, src2, roiSize, src2Border);\n generateOclMat(gweights1, gweights1_roi, weights1, roiSize, weights1Border);\n generateOclMat(gweights2, gweights2_roi, weights2, roiSize, weights2Border);\n generateOclMat(gdst, gdst_roi, dst, roiSize, dstBorder);\n }\n\n void Near(double eps = 0.0)\n {\n Mat whole, roi;\n gdst.download(whole);\n gdst_roi.download(roi);\n\n EXPECT_MAT_NEAR(dst, whole, eps);\n EXPECT_MAT_NEAR(dst_roi, roi, eps);\n }\n};\n\ntypedef void (*blendLinearFunc)(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &weights1, const cv::Mat &weights2, cv::Mat &result_gold);\n\nOCL_TEST_P(Blend, Accuracy)\n{\n for (int i = 0; i < LOOP_TIMES; ++i)\n {\n random_roi();\n\n cv::ocl::blendLinear(gsrc1_roi, gsrc2_roi, gweights1_roi, gweights2_roi, gdst_roi);\n\n static blendLinearFunc funcs[] = {\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n blendLinearGold,\n };\n\n blendLinearFunc func = funcs[depth];\n func(src1_roi, src2_roi, weights1_roi, weights2_roi, dst_roi);\n\n Near(depth <= CV_32S ? 1.0 : 0.2);\n }\n}\n\nINSTANTIATE_TEST_CASE_P(OCL_ImgProc, Blend,\n Combine(testing::Values(CV_8U, CV_8S, CV_16U, CV_16S, CV_32S, CV_32F),\n testing::Range(1, 5), Bool()));\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace kdb;\nusing namespace kdb::tools;\nusing namespace kdb::tools::merging;\n\nImportCommand::ImportCommand()\n{}\n\nint ImportCommand::execute(Cmdline const& cl)\n{\n\tsize_t argc = cl.arguments.size();\n\tif (argc != 1 && argc != 2 && argc != 3)\n\t{\n\t\tthrow invalid_argument(\"need 1 to 3 arguments\");\n\t}\n\n\tKey root (cl.arguments[0], KEY_END);\n\tif (!root.isValid())\n\t{\n throw invalid_argument (\"root key \\\"\" + cl.arguments[0] + \"\\\" is not a valid key name\");\n\t}\n\n\tKeySet originalKeys;\n\tkdb.get (originalKeys, root);\n\tKeySet base = originalKeys.cut (root);\n\tprintWarnings (cerr, root);\n\n\tKeySet importedKeys;\n\n\tstring format = cl.format;\n\tif (argc > 1) format = cl.arguments[1];\n\n\tstring file = \"\/dev\/stdin\";\n\tif (argc > 2 && cl.arguments[2] != \"-\") file = cl.arguments[2];\n\n\tModules modules;\n\tPluginPtr plugin = modules.load (format);\n\n\tKey errorKey (root);\n\terrorKey.setString (file);\n\n\tplugin->get (importedKeys, errorKey);\n\n\tprintWarnings (cerr, errorKey);\n\tprintError (cerr, errorKey);\n\n\tThreeWayMerge merger;\n\tMergeHelper helper;\n\n\thelper.configureMerger (cl, merger);\n\tMergeResult result = merger.mergeKeySet (\n\t\t\tMergeTask (BaseMergeKeys (base, root), OurMergeKeys (base, root),\n\t\t\t\t\tTheirMergeKeys (importedKeys, root), root));\n\n\thelper.reportResult (cl, result, cout, cerr);\n\n\tif (!result.hasConflicts ())\n\t{\n if (cl.verbose)\n\t\t{\n\t\t\tcout << \"The merged keyset with strategy \" << cl.strategy << \" is:\" << endl;\n\t\t\tcout << result.getMergedKeys();\n\t\t}\n\n\t\tKeySet resultKeys = result.getMergedKeys();\n\t\toriginalKeys.append(resultKeys);\n\t\tkdb.set (originalKeys, root);\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\treturn -1;\n\t}\n}\n\nImportCommand::~ImportCommand()\n{}\ncut import keys#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace kdb;\nusing namespace kdb::tools;\nusing namespace kdb::tools::merging;\n\nImportCommand::ImportCommand()\n{}\n\nint ImportCommand::execute(Cmdline const& cl)\n{\n\tsize_t argc = cl.arguments.size();\n\tif (argc != 1 && argc != 2 && argc != 3)\n\t{\n\t\tthrow invalid_argument(\"need 1 to 3 arguments\");\n\t}\n\n\tKey root (cl.arguments[0], KEY_END);\n\tif (!root.isValid())\n\t{\n\t\tthrow invalid_argument (\"root key \\\"\" + cl.arguments[0] + \"\\\" is not a valid key name\");\n\t}\n\n\tKeySet originalKeys;\n\tkdb.get (originalKeys, root);\n\tKeySet base = originalKeys.cut (root);\n\tprintWarnings (cerr, root);\n\n\tKeySet importedKeys;\n\n\tstring format = cl.format;\n\tif (argc > 1) format = cl.arguments[1];\n\n\tstring file = \"\/dev\/stdin\";\n\tif (argc > 2 && cl.arguments[2] != \"-\") file = cl.arguments[2];\n\n\tModules modules;\n\tPluginPtr plugin = modules.load (format);\n\n\tKey errorKey (root);\n\terrorKey.setString (file);\n\n\tplugin->get(importedKeys, errorKey);\n\timportedKeys = importedKeys.cut(root);\n\n\tprintWarnings (cerr, errorKey);\n\tprintError (cerr, errorKey);\n\n\tThreeWayMerge merger;\n\tMergeHelper helper;\n\n\thelper.configureMerger (cl, merger);\n\tMergeResult result = merger.mergeKeySet (\n\t\t\tMergeTask (BaseMergeKeys (base, root), OurMergeKeys (base, root),\n\t\t\t\t\tTheirMergeKeys (importedKeys, root), root));\n\n\thelper.reportResult (cl, result, cout, cerr);\n\n\tif (!result.hasConflicts ())\n\t{\n if (cl.verbose)\n\t\t{\n\t\t\tcout << \"The merged keyset with strategy \" << cl.strategy << \" is:\" << endl;\n\t\t\tcout << result.getMergedKeys();\n\t\t}\n\n\t\tKeySet resultKeys = result.getMergedKeys();\n\t\toriginalKeys.append(resultKeys);\n\t\tkdb.set (originalKeys, root);\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\treturn -1;\n\t}\n}\n\nImportCommand::~ImportCommand()\n{}\n<|endoftext|>"} {"text":"\/*\n * strcheck.hpp\n * The class to check if strings are integer, decimal, or real number\n *\n * written by janus_wel\n * This source code is in public domain, and has NO WARRANTY.\n * *\/\n\n#ifndef STRCHECK_HPP\n#define STRCHECK_HPP\n\n#include \n#include \n#include \n\nnamespace util {\n namespace string {\n template struct numeric_traits;\n template<> struct numeric_traits {\n typedef char char_type;\n static const char_type positive = '+';\n static const char_type negative = '-';\n };\n template<> struct numeric_traits {\n typedef wchar_t char_type;\n static const char_type positive = L'+';\n static const char_type negative = L'-';\n };\n\n template< typename Char,\n typename CharTraits = std::char_traits,\n typename NumTraits = numeric_traits >\n class basic_check {\n public:\n typedef Char char_type;\n typedef std::basic_string string_type;\n typedef std::ctype ctype_type;\n typedef std::numpunct numpunct_type;\n\n private:\n std::locale loc;\n\n public:\n \/\/ constructor\n explicit basic_check(void) : loc(std::locale()) {}\n explicit basic_check(const std::locale& loc) : loc(loc) {}\n\n private:\n const ctype_type& ctype(void) const {\n static const ctype_type& ctype =\n std::use_facet(loc);\n return ctype;\n }\n\n char_type decimal_point(void) const {\n static const char_type decimal_point =\n std::use_facet(loc).decimal_point();\n return decimal_point;\n }\n\n public:\n bool is_integer(const char_type* const str) const {\n const char_type* const first =\n ( (str[0] == NumTraits::positive)\n | (str[0] == NumTraits::negative)) ? str + 1 : str;\n const char_type* const last =\n first + CharTraits::length(first);\n const char_type* const found =\n ctype().scan_not(ctype_type::digit, first, last);\n\n return found == last;\n }\n\n bool is_integer(const string_type& str) const {\n return is_integer(str.c_str());\n }\n\n bool is_decimal(const char_type* const str) const {\n const char_type* const first =\n ( (str[0] == NumTraits::positive)\n | (str[0] == NumTraits::negative)) ? str + 1 : str;\n\n const char_type* const point =\n CharTraits::find( first,\n CharTraits::length(first),\n decimal_point());\n\n if (point == 0 || point == first) return false;\n\n const char_type* integer =\n ctype().scan_not(ctype_type::digit, first, point);\n return ((integer == point) & is_integer(point + 1));\n }\n\n bool is_decimal(const string_type& str) const {\n return is_decimal(str.c_str());\n }\n\n bool is_real(const char_type* const str) const {\n return (is_integer(str) | is_decimal(str));\n }\n\n bool is_real(const string_type& str) const {\n return is_real(str.c_str());\n }\n };\n\n typedef basic_check check;\n typedef basic_check wcheck;\n }\n}\n\n#endif \/\/ STRCHECK_HPP\n\nAdd some member functions\/*\n * strcheck.hpp\n * The class to check if strings are integer, decimal, or real number\n *\n * written by janus_wel\n * This source code is in public domain, and has NO WARRANTY.\n * *\/\n\n#ifndef STRCHECK_HPP\n#define STRCHECK_HPP\n\n#include \n#include \n#include \n\nnamespace util {\n namespace string {\n template struct numeric_traits;\n template<> struct numeric_traits {\n typedef char char_type;\n static const char_type positive = '+';\n static const char_type negative = '-';\n };\n template<> struct numeric_traits {\n typedef wchar_t char_type;\n static const char_type positive = L'+';\n static const char_type negative = L'-';\n };\n\n template< typename Char,\n typename CharTraits = std::char_traits,\n typename NumTraits = numeric_traits >\n class basic_check {\n public:\n typedef Char char_type;\n typedef std::basic_string string_type;\n typedef std::ctype ctype_type;\n typedef std::numpunct numpunct_type;\n\n private:\n std::locale loc;\n\n public:\n \/\/ constructor\n explicit basic_check(void) : loc(std::locale()) {}\n explicit basic_check(const std::locale& loc) : loc(loc) {}\n\n private:\n const ctype_type& ctype(void) const {\n static const ctype_type& ctype =\n std::use_facet(loc);\n return ctype;\n }\n\n char_type decimal_point(void) const {\n static const char_type decimal_point =\n std::use_facet(loc).decimal_point();\n return decimal_point;\n }\n\n public:\n bool is_positive(const char_type* const str) const {\n return !is_negative(str);\n }\n\n bool is_positive(const string_type& str) const {\n return is_positive(str.c_str());\n }\n\n bool is_negative(const char_type* const str) const {\n return str[0] == NumTraits::negative;\n }\n\n bool is_negative(const string_type& str) const {\n return is_negative(str.c_str());\n }\n\n bool is_integer(const char_type* const str) const {\n const char_type* const first =\n ( (str[0] == NumTraits::positive)\n | (str[0] == NumTraits::negative)) ? str + 1 : str;\n const char_type* const last =\n first + CharTraits::length(first);\n const char_type* const found =\n ctype().scan_not(ctype_type::digit, first, last);\n\n return found == last;\n }\n\n bool is_integer(const string_type& str) const {\n return is_integer(str.c_str());\n }\n\n bool is_decimal(const char_type* const str) const {\n const char_type* const first =\n ( (str[0] == NumTraits::positive)\n | (str[0] == NumTraits::negative)) ? str + 1 : str;\n\n const char_type* const point =\n CharTraits::find( first,\n CharTraits::length(first),\n decimal_point());\n\n if (point == 0 || point == first) return false;\n\n const char_type* integer =\n ctype().scan_not(ctype_type::digit, first, point);\n return ((integer == point) & is_integer(point + 1));\n }\n\n bool is_decimal(const string_type& str) const {\n return is_decimal(str.c_str());\n }\n\n bool is_real(const char_type* const str) const {\n return (is_integer(str) | is_decimal(str));\n }\n\n bool is_real(const string_type& str) const {\n return is_real(str.c_str());\n }\n };\n\n typedef basic_check check;\n typedef basic_check wcheck;\n }\n}\n\n#endif \/\/ STRCHECK_HPP\n\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace aim {\n\n \/** Ordered hash map\n *\/\n template \n struct hash_map {\n using key_t = KeyT;\n using value_t = ValueT;\n using hash_fn = std::hash;\n using hash_t = decltype(hash_fn{}(std::declval()));\n using pair_t = std::tuple;\n\n using data_t = std::vector;\n using iterator = typename data_t::iterator;\n using const_iterator = typename data_t::const_iterator;\n\n hash_map()\n {}\n\n hash_map(std::initializer_list other)\n : data_(other)\n {}\n\n hash_map(const hash_map&) = default;\n hash_map(hash_map&&) = default;\n\n iterator begin() {\n return std::begin(data_);\n }\n\n const_iterator begin() const {\n return std::begin(data_);\n }\n\n iterator end() {\n return std::end(data_);\n }\n\n const_iterator end() const {\n return std::end(data_);\n }\n\n \/** \\brief Nonmutable iteration over map using function.\n * \\param func Function object takes type `pair_t` type as argument.\n *\/\n template \n void iter(Func&& func) const {\n for(auto&& node : data_)\n func(node);\n }\n\n \/** |brief Find existing element or return past-end element iterator.\n *\/\n iterator find(const key_t& key) {\n const auto hash_ = hash_fn{}(key);\n auto res_ = _find(hash_);\n return res_.found ? res_.itr : end();\n }\n\n \/** |brief Find existing element or return past-end element iterator.\n *\/\n const_iterator find(const key_t& key) const {\n return find(key);\n }\n\n \/** \\brief Inserts new element to map.\n * \\param key Key to access.\n * \\param value New value.\n * \\return New element was created or reassigned to existing key.\n *\/\n bool insert(const key_t& key, const value_t& value) {\n const auto hash_ = hash_fn{}(key);\n const auto& own = _find(hash_);\n if (own.found) {\n std::get<1>(*own.itr) = value;\n return false;\n }\n else {\n auto iter = own.itr;\n std::advance(iter, 1);\n data_.insert(iter, std::make_tuple(hash_, value));\n return true;\n }\n }\n\n \/** \\brief Removes element by its key.\n * \\param key\n * \\return True if element was removed and false otherwise.\n *\/\n bool remove(const key_t& key) {\n const auto hash_ = hash_fn{}(key);\n const auto& own = _find(hash_);\n if (own.found) {\n data_.erase(own.itr);\n return true;\n }\n else {\n return false;\n }\n }\n\n private:\n\n struct search_result {\n bool found; \/\/\/ Element was found\n iterator itr; \/\/\/ Iterator to previous element\n };\n\n \/** \\brief Searches element by its key's hash.\n * \\param hash_ Key's hash.\n *\/\n search_result _find(const hash_t hash_) {\n auto left = begin();\n auto right = end();\n bool searching = true;\n\n auto result = search_result{false, right};\n\n while (searching) {\n const std::size_t dist = std::distance(left, right) \/ 2;\n\n auto itr = left;\n\n if (dist == 0) {\n result.found = false;\n result.itr = itr;\n break;\n }\n\n std::advance(itr, dist);\n\n const auto itr_hash = std::get<0>(*itr);\n\n if (itr_hash < hash_) {\n left = itr;\n }\n else if (itr_hash > hash_) {\n right = itr;\n }\n else if (itr_hash == hash_) {\n result.found = true;\n result.itr = itr;\n searching = false;\n }\n else {\n result.found = false;\n result.itr = itr;\n searching = false;\n }\n }\n return result;\n }\n\n data_t data_;\n };\n}\nRemove unusable code#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace aim {\n\n \/** Ordered hash map\n *\/\n template \n struct hash_map {\n using key_t = KeyT;\n using value_t = ValueT;\n using hash_fn = std::hash;\n using hash_t = decltype(hash_fn{}(std::declval()));\n using pair_t = std::tuple;\n\n using data_t = std::vector;\n using iterator = typename data_t::iterator;\n using const_iterator = typename data_t::const_iterator;\n\n hash_map()\n {}\n\n hash_map(std::initializer_list other)\n : data_(other)\n {}\n\n hash_map(const hash_map&) = default;\n hash_map(hash_map&&) = default;\n\n iterator begin() {\n return std::begin(data_);\n }\n\n const_iterator begin() const {\n return std::begin(data_);\n }\n\n iterator end() {\n return std::end(data_);\n }\n\n const_iterator end() const {\n return std::end(data_);\n }\n\n \/** \\brief Nonmutable iteration over map using function.\n * \\param func Function object takes type `pair_t` type as argument.\n *\/\n template \n void iter(Func&& func) const {\n for(auto&& node : data_)\n func(node);\n }\n\n \/** |brief Find existing element or return past-end element iterator.\n *\/\n iterator find(const key_t& key) {\n const auto hash_ = hash_fn{}(key);\n auto res_ = _find(hash_);\n return res_.found ? res_.itr : end();\n }\n\n \/** |brief Find existing element or return past-end element iterator.\n *\/\n const_iterator find(const key_t& key) const {\n return find(key);\n }\n\n \/** \\brief Inserts new element to map.\n * \\param key Key to access.\n * \\param value New value.\n * \\return New element was created or reassigned to existing key.\n *\/\n bool insert(const key_t& key, const value_t& value) {\n const auto hash_ = hash_fn{}(key);\n const auto& own = _find(hash_);\n if (own.found) {\n std::get<1>(*own.itr) = value;\n return false;\n }\n else {\n auto iter = own.itr;\n std::advance(iter, 1);\n data_.insert(iter, std::make_tuple(hash_, value));\n return true;\n }\n }\n\n \/** \\brief Removes element by its key.\n * \\param key\n * \\return True if element was removed and false otherwise.\n *\/\n bool remove(const key_t& key) {\n const auto hash_ = hash_fn{}(key);\n const auto& own = _find(hash_);\n if (own.found) {\n data_.erase(own.itr);\n return true;\n }\n else {\n return false;\n }\n }\n\n private:\n\n struct search_result {\n bool found; \/\/\/ Element was found\n iterator itr; \/\/\/ Iterator to previous element\n };\n\n \/** \\brief Searches element by its key's hash.\n * \\param hash_ Key's hash.\n *\/\n search_result _find(const hash_t hash_) {\n auto left = begin();\n auto right = end();\n bool searching = true;\n\n auto result = search_result{false, right};\n\n while (searching) {\n const std::size_t dist = std::distance(left, right) \/ 2;\n\n auto itr = left;\n\n if (dist == 0) {\n result.found = false;\n result.itr = itr;\n break;\n }\n\n std::advance(itr, dist);\n\n const auto itr_hash = std::get<0>(*itr);\n\n if (itr_hash < hash_) {\n left = itr;\n }\n else if (itr_hash > hash_) {\n right = itr;\n }\n else {\n result.found = true;\n result.itr = itr;\n searching = false;\n }\n }\n return result;\n }\n\n data_t data_;\n };\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCellDataToPointData.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#include \"vtkCellDataToPointData.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCell.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkIdList.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkUnsignedIntArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n\n#include \n#include \n\nvtkStandardNewMacro(vtkCellDataToPointData);\n\n\/\/----------------------------------------------------------------------------\n\/\/ Instantiate object so that cell data is not passed to output.\nvtkCellDataToPointData::vtkCellDataToPointData()\n{\n this->PassCellData = 0;\n}\n\n#define VTK_MAX_CELLS_PER_POINT 4096\n\n\/\/----------------------------------------------------------------------------\nint vtkCellDataToPointData::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* info = outputVector->GetInformationObject(0);\n vtkDataSet *output = vtkDataSet::SafeDownCast(\n info->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);\n vtkDataSet *input = vtkDataSet::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkDebugMacro(<<\"Mapping cell data to point data\");\n\n \/\/ Special traversal algorithm for unstructured grid\n if (input->IsA(\"vtkUnstructuredGrid\"))\n {\n return this->RequestDataForUnstructuredGrid(0, inputVector, outputVector);\n }\n\n vtkIdType cellId, ptId;\n vtkIdType numCells, numPts;\n vtkCellData *inPD=input->GetCellData();\n vtkPointData *outPD=output->GetPointData();\n vtkIdList *cellIds;\n double weight;\n double *weights;\n\n vtkDebugMacro(<<\"Mapping cell data to point data\");\n\n \/\/ First, copy the input to the output as a starting point\n output->CopyStructure( input );\n\n cellIds = vtkIdList::New();\n cellIds->Allocate(VTK_MAX_CELLS_PER_POINT);\n\n if ( (numPts=input->GetNumberOfPoints()) < 1 )\n {\n vtkDebugMacro(<<\"No input point data!\");\n cellIds->Delete();\n return 1;\n }\n weights = new double[VTK_MAX_CELLS_PER_POINT];\n\n \/\/ Pass the point data first. The fields and attributes\n \/\/ which also exist in the cell data of the input will\n \/\/ be over-written during CopyAllocate\n output->GetPointData()->CopyGlobalIdsOff();\n output->GetPointData()->PassData(input->GetPointData());\n output->GetPointData()->CopyFieldOff(\"vtkGhostLevels\");\n\n \/\/ notice that inPD and outPD are vtkCellData and vtkPointData; respectively.\n \/\/ It's weird, but it works.\n outPD->InterpolateAllocate(inPD,numPts);\n\n int abort=0;\n vtkIdType progressInterval=numPts\/20 + 1;\n for (ptId=0; ptId < numPts && !abort; ptId++)\n {\n if ( !(ptId % progressInterval) )\n {\n this->UpdateProgress(static_cast(ptId)\/numPts);\n abort = GetAbortExecute();\n }\n\n input->GetPointCells(ptId, cellIds);\n numCells = cellIds->GetNumberOfIds();\n if ( numCells > 0 && numCells < VTK_MAX_CELLS_PER_POINT )\n {\n weight = 1.0 \/ numCells;\n for (cellId=0; cellId < numCells; cellId++)\n {\n weights[cellId] = weight;\n }\n outPD->InterpolatePoint(inPD, ptId, cellIds, weights);\n }\n else\n {\n outPD->NullPoint(ptId);\n }\n }\n\n if ( !this->PassCellData )\n {\n output->GetCellData()->CopyAllOff();\n output->GetCellData()->CopyFieldOn(\"vtkGhostLevels\");\n }\n output->GetCellData()->PassData(input->GetCellData());\n\n cellIds->Delete();\n delete [] weights;\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkCellDataToPointData::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Pass Cell Data: \" << (this->PassCellData ? \"On\\n\" : \"Off\\n\");\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Helper template function that implement the major part of the algorighm\n\/\/ which will be expanded by the vtkTemplateMacro. The template function is\n\/\/ provided so that coverage test can cover this function.\nnamespace\n{\n template \n void __spread (vtkUnstructuredGrid* const src, vtkUnsignedIntArray* const num,\n vtkDataArray* const srcarray, vtkDataArray* const dstarray,\n vtkIdType ncells, vtkIdType npoints, vtkIdType ncomps)\n {\n T const* const srcptr = static_cast(srcarray->GetVoidPointer(0));\n T * const dstptr = static_cast(dstarray->GetVoidPointer(0));\n\n \/\/ zero initialization\n std::fill_n(dstptr, npoints*ncomps, T(0));\n\n \/\/ accumulate\n T const* srcbeg = srcptr;\n for (vtkIdType cid = 0; cid < ncells; ++cid, srcbeg += ncomps)\n {\n vtkIdList* const pids = src->GetCell(cid)->GetPointIds();\n for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)\n {\n T* const dstbeg = dstptr + pids->GetId(i)*ncomps;\n \/\/ accumulate cell data to point data <==> point_data += cell_data\n std::transform(srcbeg,srcbeg+ncomps,dstbeg,dstbeg,std::plus());\n }\n }\n\n \/\/ average\n T* dstbeg = dstptr;\n for (vtkIdType pid = 0; pid < npoints; ++pid, dstbeg += ncomps)\n {\n \/\/ guard against divide by zero\n if (unsigned int const denum = num->GetValue(pid))\n {\n \/\/ divide point data by the number of cells using it <==>\n \/\/ point_data \/= denum\n std::transform(dstbeg, dstbeg+ncomps, dstbeg,\n std::bind2nd(std::divides(), denum));\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkCellDataToPointData::RequestDataForUnstructuredGrid\n (vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkUnstructuredGrid* const src = vtkUnstructuredGrid::SafeDownCast(\n inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));\n vtkUnstructuredGrid* const dst = vtkUnstructuredGrid::SafeDownCast(\n outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkIdType const ncells = src->GetNumberOfCells ();\n vtkIdType const npoints = src->GetNumberOfPoints();\n if (ncells < 1 || npoints < 1)\n {\n vtkDebugMacro(<<\"No input data!\");\n return 1;\n }\n\n \/\/ count the number of cells associated with each point\n vtkSmartPointer num\n = vtkSmartPointer::New();\n num->SetNumberOfComponents(1);\n num->SetNumberOfTuples(npoints);\n std::fill_n(num->GetPointer(0), npoints, 0u);\n for (vtkIdType cid = 0; cid < ncells; ++cid)\n {\n vtkIdList* const pids = src->GetCell(cid)->GetPointIds();\n for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)\n {\n vtkIdType const pid = pids->GetId(i);\n num->SetValue(pid, num->GetValue(pid)+1);\n }\n }\n\n \/\/ First, copy the input to the output as a starting point\n dst->CopyStructure(src);\n vtkPointData* const opd = dst->GetPointData();\n\n \/\/ Pass the point data first. The fields and attributes\n \/\/ which also exist in the cell data of the input will\n \/\/ be over-written during CopyAllocate\n opd->CopyGlobalIdsOff();\n opd->PassData(src->GetPointData());\n opd->CopyFieldOff(\"vtkGhostLevels\");\n\n \/\/ Copy all existing cell fields into a temporary cell data array\n vtkSmartPointer clean = vtkSmartPointer::New();\n clean->PassData(src->GetCellData());\n\n \/\/ Remove all fields that are not a data array.\n for (vtkIdType fid = clean->GetNumberOfArrays(); fid--;)\n {\n if (!clean->GetAbstractArray(fid)->IsA(\"vtkDataArray\"))\n {\n clean->RemoveArray(fid);\n }\n }\n\n \/\/ Cell field list constructed from the filtered cell data array\n vtkDataSetAttributes::FieldList cfl(1);\n cfl.InitializeFieldList(clean);\n opd->InterpolateAllocate(cfl, npoints, npoints);\n\n for (int fid = 0, nfields = cfl.GetNumberOfFields(); fid < nfields; ++fid)\n {\n \/\/ update progress and check for an abort request.\n this->UpdateProgress((fid+1.)\/nfields);\n if (this->GetAbortExecute())\n {\n break;\n }\n\n \/\/ indices into the field arrays associated with the cell and the point\n \/\/ respectively\n int const dstid = cfl.GetFieldIndex(fid);\n int const srcid = cfl.GetDSAIndex(0,fid);\n if (srcid < 0 || dstid < 0)\n {\n continue;\n }\n\n vtkCellData * const srccelldata = clean;\n vtkPointData* const dstpointdata = dst->GetPointData();\n\n if (!srccelldata || !dstpointdata)\n {\n continue;\n }\n\n vtkDataArray* const srcarray = srccelldata ->GetArray(srcid);\n vtkDataArray* const dstarray = dstpointdata->GetArray(dstid);\n dstarray->SetNumberOfTuples(npoints);\n\n vtkIdType const ncomps = srcarray->GetNumberOfComponents();\n switch (srcarray->GetDataType())\n {\n vtkTemplateMacro\n (__spread(src,num,srcarray,dstarray,ncells,npoints,ncomps));\n }\n }\n\n if (!this->PassCellData)\n {\n dst->GetCellData()->CopyAllOff();\n dst->GetCellData()->CopyFieldOn(\"vtkGhostLevels\");\n }\n dst->GetCellData()->PassData(src->GetCellData());\n\n return 1;\n}\n\nPerformance improvement to CellToPoint.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkCellDataToPointData.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#include \"vtkCellDataToPointData.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCell.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkIdList.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkUnsignedIntArray.h\"\n#include \"vtkUnstructuredGrid.h\"\n\n#include \n#include \n\nvtkStandardNewMacro(vtkCellDataToPointData);\n\n\/\/----------------------------------------------------------------------------\n\/\/ Instantiate object so that cell data is not passed to output.\nvtkCellDataToPointData::vtkCellDataToPointData()\n{\n this->PassCellData = 0;\n}\n\n#define VTK_MAX_CELLS_PER_POINT 4096\n\n\/\/----------------------------------------------------------------------------\nint vtkCellDataToPointData::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* info = outputVector->GetInformationObject(0);\n vtkDataSet *output = vtkDataSet::SafeDownCast(\n info->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);\n vtkDataSet *input = vtkDataSet::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkDebugMacro(<<\"Mapping cell data to point data\");\n\n \/\/ Special traversal algorithm for unstructured grid\n if (input->IsA(\"vtkUnstructuredGrid\"))\n {\n return this->RequestDataForUnstructuredGrid(0, inputVector, outputVector);\n }\n\n vtkIdType cellId, ptId;\n vtkIdType numCells, numPts;\n vtkCellData *inPD=input->GetCellData();\n vtkPointData *outPD=output->GetPointData();\n vtkIdList *cellIds;\n double weight;\n double *weights;\n\n vtkDebugMacro(<<\"Mapping cell data to point data\");\n\n \/\/ First, copy the input to the output as a starting point\n output->CopyStructure( input );\n\n cellIds = vtkIdList::New();\n cellIds->Allocate(VTK_MAX_CELLS_PER_POINT);\n\n if ( (numPts=input->GetNumberOfPoints()) < 1 )\n {\n vtkDebugMacro(<<\"No input point data!\");\n cellIds->Delete();\n return 1;\n }\n weights = new double[VTK_MAX_CELLS_PER_POINT];\n\n \/\/ Pass the point data first. The fields and attributes\n \/\/ which also exist in the cell data of the input will\n \/\/ be over-written during CopyAllocate\n output->GetPointData()->CopyGlobalIdsOff();\n output->GetPointData()->PassData(input->GetPointData());\n output->GetPointData()->CopyFieldOff(\"vtkGhostLevels\");\n\n \/\/ notice that inPD and outPD are vtkCellData and vtkPointData; respectively.\n \/\/ It's weird, but it works.\n outPD->InterpolateAllocate(inPD,numPts);\n\n int abort=0;\n vtkIdType progressInterval=numPts\/20 + 1;\n for (ptId=0; ptId < numPts && !abort; ptId++)\n {\n if ( !(ptId % progressInterval) )\n {\n this->UpdateProgress(static_cast(ptId)\/numPts);\n abort = GetAbortExecute();\n }\n\n input->GetPointCells(ptId, cellIds);\n numCells = cellIds->GetNumberOfIds();\n if ( numCells > 0 && numCells < VTK_MAX_CELLS_PER_POINT )\n {\n weight = 1.0 \/ numCells;\n for (cellId=0; cellId < numCells; cellId++)\n {\n weights[cellId] = weight;\n }\n outPD->InterpolatePoint(inPD, ptId, cellIds, weights);\n }\n else\n {\n outPD->NullPoint(ptId);\n }\n }\n\n if ( !this->PassCellData )\n {\n output->GetCellData()->CopyAllOff();\n output->GetCellData()->CopyFieldOn(\"vtkGhostLevels\");\n }\n output->GetCellData()->PassData(input->GetCellData());\n\n cellIds->Delete();\n delete [] weights;\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkCellDataToPointData::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"Pass Cell Data: \" << (this->PassCellData ? \"On\\n\" : \"Off\\n\");\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Helper template function that implement the major part of the algorighm\n\/\/ which will be expanded by the vtkTemplateMacro. The template function is\n\/\/ provided so that coverage test can cover this function.\nnamespace\n{\n template \n void __spread (vtkUnstructuredGrid* const src, vtkUnsignedIntArray* const num,\n vtkDataArray* const srcarray, vtkDataArray* const dstarray,\n vtkIdType ncells, vtkIdType npoints, vtkIdType ncomps)\n {\n T const* const srcptr = static_cast(srcarray->GetVoidPointer(0));\n T * const dstptr = static_cast(dstarray->GetVoidPointer(0));\n\n \/\/ zero initialization\n std::fill_n(dstptr, npoints*ncomps, T(0));\n\n \/\/ accumulate\n T const* srcbeg = srcptr;\n vtkNew pids;\n for (vtkIdType cid = 0; cid < ncells; ++cid, srcbeg += ncomps)\n {\n src->GetCellPoints(cid, pids.GetPointer());\n for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)\n {\n T* const dstbeg = dstptr + pids->GetId(i)*ncomps;\n \/\/ accumulate cell data to point data <==> point_data += cell_data\n std::transform(srcbeg,srcbeg+ncomps,dstbeg,dstbeg,std::plus());\n }\n }\n\n \/\/ average\n T* dstbeg = dstptr;\n for (vtkIdType pid = 0; pid < npoints; ++pid, dstbeg += ncomps)\n {\n \/\/ guard against divide by zero\n if (unsigned int const denum = num->GetValue(pid))\n {\n \/\/ divide point data by the number of cells using it <==>\n \/\/ point_data \/= denum\n std::transform(dstbeg, dstbeg+ncomps, dstbeg,\n std::bind2nd(std::divides(), denum));\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkCellDataToPointData::RequestDataForUnstructuredGrid\n (vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkUnstructuredGrid* const src = vtkUnstructuredGrid::SafeDownCast(\n inputVector[0]->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));\n vtkUnstructuredGrid* const dst = vtkUnstructuredGrid::SafeDownCast(\n outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT()));\n\n vtkIdType const ncells = src->GetNumberOfCells ();\n vtkIdType const npoints = src->GetNumberOfPoints();\n if (ncells < 1 || npoints < 1)\n {\n vtkDebugMacro(<<\"No input data!\");\n return 1;\n }\n\n \/\/ count the number of cells associated with each point\n vtkSmartPointer num\n = vtkSmartPointer::New();\n num->SetNumberOfComponents(1);\n num->SetNumberOfTuples(npoints);\n std::fill_n(num->GetPointer(0), npoints, 0u);\n vtkNew pids;\n for (vtkIdType cid = 0; cid < ncells; ++cid)\n {\n src->GetCellPoints(cid, pids.GetPointer());\n for (vtkIdType i = 0, I = pids->GetNumberOfIds(); i < I; ++i)\n {\n vtkIdType const pid = pids->GetId(i);\n num->SetValue(pid, num->GetValue(pid)+1);\n }\n }\n\n \/\/ First, copy the input to the output as a starting point\n dst->CopyStructure(src);\n vtkPointData* const opd = dst->GetPointData();\n\n \/\/ Pass the point data first. The fields and attributes\n \/\/ which also exist in the cell data of the input will\n \/\/ be over-written during CopyAllocate\n opd->CopyGlobalIdsOff();\n opd->PassData(src->GetPointData());\n opd->CopyFieldOff(\"vtkGhostLevels\");\n\n \/\/ Copy all existing cell fields into a temporary cell data array\n vtkSmartPointer clean = vtkSmartPointer::New();\n clean->PassData(src->GetCellData());\n\n \/\/ Remove all fields that are not a data array.\n for (vtkIdType fid = clean->GetNumberOfArrays(); fid--;)\n {\n if (!clean->GetAbstractArray(fid)->IsA(\"vtkDataArray\"))\n {\n clean->RemoveArray(fid);\n }\n }\n\n \/\/ Cell field list constructed from the filtered cell data array\n vtkDataSetAttributes::FieldList cfl(1);\n cfl.InitializeFieldList(clean);\n opd->InterpolateAllocate(cfl, npoints, npoints);\n\n for (int fid = 0, nfields = cfl.GetNumberOfFields(); fid < nfields; ++fid)\n {\n \/\/ update progress and check for an abort request.\n this->UpdateProgress((fid+1.)\/nfields);\n if (this->GetAbortExecute())\n {\n break;\n }\n\n \/\/ indices into the field arrays associated with the cell and the point\n \/\/ respectively\n int const dstid = cfl.GetFieldIndex(fid);\n int const srcid = cfl.GetDSAIndex(0,fid);\n if (srcid < 0 || dstid < 0)\n {\n continue;\n }\n\n vtkCellData * const srccelldata = clean;\n vtkPointData* const dstpointdata = dst->GetPointData();\n\n if (!srccelldata || !dstpointdata)\n {\n continue;\n }\n\n vtkDataArray* const srcarray = srccelldata ->GetArray(srcid);\n vtkDataArray* const dstarray = dstpointdata->GetArray(dstid);\n dstarray->SetNumberOfTuples(npoints);\n\n vtkIdType const ncomps = srcarray->GetNumberOfComponents();\n switch (srcarray->GetDataType())\n {\n vtkTemplateMacro\n (__spread(src,num,srcarray,dstarray,ncells,npoints,ncomps));\n }\n }\n\n if (!this->PassCellData)\n {\n dst->GetCellData()->CopyAllOff();\n dst->GetCellData()->CopyFieldOn(\"vtkGhostLevels\");\n }\n dst->GetCellData()->PassData(src->GetCellData());\n\n return 1;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \"InteractiveInterpreter.h\"\n#include \"InterpretedDefinition.h\"\n#include \"Util.h\"\n#include \"Globals.h\"\n\nInteractiveInterpreter::InteractiveInterpreter(Emmental& interpreter)\n\t: Interpreter(interpreter)\n{\n\tGenerateCommands();\n}\n\nint InteractiveInterpreter::RunLoop()\n{\n\tInterpreter.OutputStream << \"Entering Interactive Mode\" << std::endl;\n\tInterpreter.OutputStream << \"Inputs not starting with '__' will be interpreted by Emmental.\" << std::endl;\n\tInterpreter.OutputStream << \"Type __help for a list of commands, or __exit to exit.\" << std::endl;\n\n\n\twhile (true)\n\t{\n\t\tInterpreter.OutputStream << std::endl;\n\t\tInterpreter.OutputStream << \"> \";\n\t\tstd::string input;\n\t\tstd::getline(Interpreter.InputStream, input);\n\t\tInterpreter.OutputStream << std::endl;\n\n\t\tif (EnableCommands)\n\t\t{\n\t\t\t\/\/ Special command to exit the loop\n\t\t\tif (input.find(\"__exit\") == 0)\n\t\t\t\treturn EXIT_SUCCESS;\n\n\t\t\tif (ParseCommand(input))\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tfor (auto&& x : input)\n\t\t{\n\t\t\tSymbolT symbol = (SymbolT)x;\n\t\t\tInterpreter.Interpret(symbol);\n\t\t}\n\n\t\tif (Globals::DebugMode)\n\t\t{\n\t\t\tUtil::DescribeMemory(Interpreter, Interpreter.OutputStream);\n\t\t}\n\t}\n}\n\nvoid InteractiveInterpreter::AddCommand(const InteractiveCommand& command) { Commands.push_back(command); }\n\nvoid InteractiveInterpreter::GenerateCommands()\n{\n\t\/\/ These commands are handled as special cases, they'll never be called normally.\n\tAddCommand(InteractiveCommand(\"exit\", \"Exits this program.\", nullptr));\n\tAddCommand(InteractiveCommand(\"help\", \"Shows this list.\", nullptr));\n\n\t\/\/ Normal commands here\n\tAddCommand(InteractiveCommand(\"disablecommands\", \"Disables all commands, interpreting all input as Emmental code.\", [&](Emmental& interpreter, std::string)\n\t{\n\t\tUtil::Colorize(Util::ConsoleColor::BrightYellow, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"WARNING! \";\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"All commands will be disabled, including __exit. Do you want to continue? (Y\/N)\";\n\n\t\tstd::string answer;\n\t\tstd::getline(Interpreter.InputStream, answer);\n\t\tif (answer == \"y\" || answer == \"Y\")\n\t\t{\n\t\t\tEnableCommands = false;\n\t\t\tinterpreter.OutputStream << \"All commands disabled.\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Operation cancelled. \" << std::endl;\n\t\t}\n\t}));\n\tAddCommand(InteractiveCommand(\"reset\", \"Resets the interpreter back to its original state.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.Reset();\n\t\tinterpreter.OutputStream << \"Interpreter reset.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"clearstack\", \"Clears the stack.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ClearStack();\n\t\tinterpreter.OutputStream << \"Stack cleared.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"clearqueue\", \"Clears the queue.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ClearQueue();\n\t\tinterpreter.OutputStream << \"Queue cleared.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"resetdefs\", \"Resets all symbol definitions back to their original native definitions.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ResetDefinitions();\n\t\tinterpreter.OutputStream << \"Symbol definitions reset to original native definitions.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"undef\", \"Undefines a symbol. Pass the symbol number as an argument.\", [](Emmental& interpreter, std::string arg)\n\t{\n\t\tSymbolT symbol;\n\n\t\ttry\n\t\t{\n\t\t\tsymbol = std::stoi(arg);\n\t\t}\n\t\tcatch (std::invalid_argument)\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Invalid symbol number.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tcatch (std::out_of_range)\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Symbol value out of range.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tinterpreter.Undefine(symbol);\n\t\tinterpreter.OutputStream << \"Undefined symbol \";\n\t\tUtil::DescribeSymbol(symbol, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \".\" << std::endl;\n\n\t}));\n\n\tAddCommand(InteractiveCommand(\"debug\", \"Toggles debug mode on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::DebugMode = !Globals::DebugMode;\n\t\tinterpreter.OutputStream << \"Debug mode is now \" << (Globals::DebugMode ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"color\", \"Toggles Virtual Console coloring on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::UseVirtualConsole = !Globals::UseVirtualConsole;\n\t\tinterpreter.OutputStream << \"Virtual Console coloring is now \" << (Globals::UseVirtualConsole ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"optimize\", \"Toggles program optimization on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::OptimizeProgram = !Globals::OptimizeProgram;\n\t\tinterpreter.OutputStream << \"Optimization is now \" << (Globals::OptimizeProgram ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"memory\", \"Shows the current stack and queue\", [](Emmental& interpreter, std::string)\n\t{\n\t\tUtil::DescribeMemory(interpreter, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"pushraw\",\n\t\t\"Pushes its argument into the stack (interpreted as raw ASCII bytes).\",\n\t\t[](Emmental& interpreter, std::string args)\n\t{\n\t\tfor (auto& symbol : args)\n\t\t{\n\t\t\tinterpreter.Push(symbol);\n\t\t\tUtil::DescribeSymbol(symbol, interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << \", \";\n\t\t}\n\n\t\tinterpreter.OutputStream << std::endl;\n\t\tinterpreter.OutputStream << \"Pushed \" << args.length() << \" bytes into the stack.\" << std::endl;\n\t\tinterpreter.OutputStream << std::endl;\n\n\t\tUtil::DescribeMemory(interpreter, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << std::endl;\n\n\t}));\n\n\tAddCommand(InteractiveCommand(\"defs\", \n\t\t\"Without argument: Displays all current symbol definitions. With symbol number as argument: Displays all captured definitions for the symbol.\",\n\t\t[](Emmental& interpreter, std::string arg)\n\t{\n\t\tif (arg.empty())\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Current interpreter definitions: \" << std::endl;\n\t\t\tUtil::DescribeDefinitions(interpreter.CopyDefinitions(), interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSymbolT symbol;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tsymbol = std::stoi(arg);\n\t\t\t}\n\t\t\tcatch (std::invalid_argument)\n\t\t\t{\n\t\t\t\tinterpreter.OutputStream << \"Invalid symbol number.\" << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcatch (std::out_of_range)\n\t\t\t{\n\t\t\t\tinterpreter.OutputStream << \"Symbol value out of range.\" << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tUtil::DescribeDefinition(symbol, interpreter.CopyDefinitions(), true, interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << std::endl;\n\t\t}\n\t}));\n\n\tAddCommand(InteractiveCommand(\"info\", \"Display interpreter information.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.OutputStream << \"Gory Emmental Interpreter 1.0.0 by Davipb\" << std::endl;\n\n\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"== Compile-Time Settings ==\" << std::endl;\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"Symbol Type: \" << typeid(SymbolT).name() << std::endl;\n\t\tinterpreter.OutputStream << \"Symbol Size: \" << sizeof(SymbolT) << \" byte(s)\" << std::endl;\n\t\tinterpreter.OutputStream << \"Max Stack Size: \" << EMMENTAL_MAX_STACK_SIZE << std::endl;\n\t\tinterpreter.OutputStream << \"Max Queue Size: \" << EMMENTAL_MAX_QUEUE_SIZE << std::endl;\n\t\tinterpreter.OutputStream << \"Max Recursion Level: \" << EMMENTAL_MAX_RECURSION_LEVEL << std::endl;\n\n\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"== Runtime Settings ==\" << std::endl;\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"Debug Mode: \" << (Globals::DebugMode ? \"On\" : \"Off\") << std::endl;\n\t\tinterpreter.OutputStream << \"Colors: \" << (Globals::UseVirtualConsole ? \"On\" : \"Off\") << std::endl;\n\t\tinterpreter.OutputStream << \"Optimization: \" << (Globals::OptimizeProgram ? \"On\" : \"Off\") << std::endl;\n\n\t}));\n}\n\nbool InteractiveInterpreter::ParseCommand(std::string input)\n{\n\tif (input.find(\"__\") != 0)\n\t\treturn false;\n\n\tstd::string command = input.substr(2, input.size() - 2);\n\n\tif (command.find(\"help\") == 0)\n\t{\n\t\tInterpreter.OutputStream << \"Commands are case-sensitive. Arguments come right after a command.\" << std::endl;\n\t\tInterpreter.OutputStream << std::endl;\n\n\t\tfor (auto& x : Commands)\n\t\t{\n\t\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, Interpreter.OutputStream);\n\t\t\tInterpreter.OutputStream << \"__\" << x.GetName() << \": \";\n\t\t\tUtil::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);\n\t\t\tInterpreter.OutputStream << x.GetDescription() << std::endl;\n\t\t}\n\t\treturn true;\n\t}\n\n\tfor (auto& x : Commands)\n\t{\n\t\tif (command.find(x.GetName()) == 0)\n\t\t{\n\t\t\tstd::string argument = command.substr(x.GetName().size(), command.size() - x.GetName().size());\n\t\t\t\/\/ Trim initial space from argument to allow \"__command arg\" instead of just \"__commandarg\"\n\t\t\tif (argument.length() > 0 && argument[0] == ' ')\n\t\t\t\targument = argument.substr(1, argument.length() - 1);\n\n\t\t\tx.Execute(Interpreter, argument);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\t\n\tUtil::Colorize(Util::ConsoleColor::Red, Interpreter.OutputStream);\n\tInterpreter.OutputStream << \"Unknown command. Use __help for a list of commands.\" << std::endl;\n\tUtil::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);\n\n\treturn true;\n}Improve Interactivity command parsing#include \n#include \"InteractiveInterpreter.h\"\n#include \"InterpretedDefinition.h\"\n#include \"Util.h\"\n#include \"Globals.h\"\n\nInteractiveInterpreter::InteractiveInterpreter(Emmental& interpreter)\n\t: Interpreter(interpreter)\n{\n\tGenerateCommands();\n}\n\nint InteractiveInterpreter::RunLoop()\n{\n\tInterpreter.OutputStream << \"Entering Interactive Mode\" << std::endl;\n\tInterpreter.OutputStream << \"Inputs not starting with '__' will be interpreted by Emmental.\" << std::endl;\n\tInterpreter.OutputStream << \"Type __help for a list of commands, or __exit to exit.\" << std::endl;\n\n\n\twhile (true)\n\t{\n\t\tInterpreter.OutputStream << std::endl;\n\t\tInterpreter.OutputStream << \"> \";\n\t\tstd::string input;\n\t\tstd::getline(Interpreter.InputStream, input);\n\t\tInterpreter.OutputStream << std::endl;\n\n\t\tif (EnableCommands)\n\t\t{\n\t\t\t\/\/ Special command to exit the loop\n\t\t\tif (input.find(\"__exit\") == 0)\n\t\t\t\treturn EXIT_SUCCESS;\n\n\t\t\tif (ParseCommand(input))\n\t\t\t\tcontinue;\n\t\t}\n\n\t\tfor (auto&& x : input)\n\t\t{\n\t\t\tSymbolT symbol = (SymbolT)x;\n\t\t\tInterpreter.Interpret(symbol);\n\t\t}\n\n\t\tif (Globals::DebugMode)\n\t\t{\n\t\t\tUtil::DescribeMemory(Interpreter, Interpreter.OutputStream);\n\t\t}\n\t}\n}\n\nvoid InteractiveInterpreter::AddCommand(const InteractiveCommand& command) { Commands.push_back(command); }\n\nvoid InteractiveInterpreter::GenerateCommands()\n{\n\t\/\/ These commands are handled as special cases, they'll never be called normally.\n\tAddCommand(InteractiveCommand(\"exit\", \"Exits this program.\", nullptr));\n\tAddCommand(InteractiveCommand(\"help\", \"Shows this list.\", nullptr));\n\n\t\/\/ Normal commands here\n\tAddCommand(InteractiveCommand(\"disablecommands\", \"Disables all commands, interpreting all input as Emmental code.\", [&](Emmental& interpreter, std::string)\n\t{\n\t\tUtil::Colorize(Util::ConsoleColor::BrightYellow, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"WARNING! \";\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"All commands will be disabled, including __exit. Do you want to continue? (Y\/N)\";\n\n\t\tstd::string answer;\n\t\tstd::getline(Interpreter.InputStream, answer);\n\t\tif (answer == \"y\" || answer == \"Y\")\n\t\t{\n\t\t\tEnableCommands = false;\n\t\t\tinterpreter.OutputStream << \"All commands disabled.\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Operation cancelled. \" << std::endl;\n\t\t}\n\t}));\n\tAddCommand(InteractiveCommand(\"reset\", \"Resets the interpreter back to its original state.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.Reset();\n\t\tinterpreter.OutputStream << \"Interpreter reset.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"clearstack\", \"Clears the stack.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ClearStack();\n\t\tinterpreter.OutputStream << \"Stack cleared.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"clearqueue\", \"Clears the queue.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ClearQueue();\n\t\tinterpreter.OutputStream << \"Queue cleared.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"resetdefs\", \"Resets all symbol definitions back to their original native definitions.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.ResetDefinitions();\n\t\tinterpreter.OutputStream << \"Symbol definitions reset to original native definitions.\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"undef\", \"Undefines a symbol. Pass the symbol number as an argument.\", [](Emmental& interpreter, std::string arg)\n\t{\n\t\tSymbolT symbol;\n\n\t\ttry\n\t\t{\n\t\t\tsymbol = std::stoi(arg);\n\t\t}\n\t\tcatch (std::invalid_argument)\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Invalid symbol number.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tcatch (std::out_of_range)\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Symbol value out of range.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tinterpreter.Undefine(symbol);\n\t\tinterpreter.OutputStream << \"Undefined symbol \";\n\t\tUtil::DescribeSymbol(symbol, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \".\" << std::endl;\n\n\t}));\n\n\tAddCommand(InteractiveCommand(\"debug\", \"Toggles debug mode on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::DebugMode = !Globals::DebugMode;\n\t\tinterpreter.OutputStream << \"Debug mode is now \" << (Globals::DebugMode ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"color\", \"Toggles Virtual Console coloring on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::UseVirtualConsole = !Globals::UseVirtualConsole;\n\t\tinterpreter.OutputStream << \"Virtual Console coloring is now \" << (Globals::UseVirtualConsole ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"optimize\", \"Toggles program optimization on\/off\", [](Emmental& interpreter, std::string)\n\t{\n\t\tGlobals::OptimizeProgram = !Globals::OptimizeProgram;\n\t\tinterpreter.OutputStream << \"Optimization is now \" << (Globals::OptimizeProgram ? \"on\" : \"off\") << \".\" << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"memory\", \"Shows the current stack and queue\", [](Emmental& interpreter, std::string)\n\t{\n\t\tUtil::DescribeMemory(interpreter, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << std::endl;\n\t}));\n\n\tAddCommand(InteractiveCommand(\"pushraw\",\n\t\t\"Pushes its argument into the stack (interpreted as raw ASCII bytes).\",\n\t\t[](Emmental& interpreter, std::string args)\n\t{\n\t\tfor (auto& symbol : args)\n\t\t{\n\t\t\tinterpreter.Push(symbol);\n\t\t\tUtil::DescribeSymbol(symbol, interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << \", \";\n\t\t}\n\n\t\tinterpreter.OutputStream << std::endl;\n\t\tinterpreter.OutputStream << \"Pushed \" << args.length() << \" bytes into the stack.\" << std::endl;\n\t\tinterpreter.OutputStream << std::endl;\n\n\t\tUtil::DescribeMemory(interpreter, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << std::endl;\n\n\t}));\n\n\tAddCommand(InteractiveCommand(\"defs\", \n\t\t\"Without argument: Displays all current symbol definitions. With symbol number as argument: Displays all captured definitions for the symbol.\",\n\t\t[](Emmental& interpreter, std::string arg)\n\t{\n\t\tif (arg.empty())\n\t\t{\n\t\t\tinterpreter.OutputStream << \"Current interpreter definitions: \" << std::endl;\n\t\t\tUtil::DescribeDefinitions(interpreter.CopyDefinitions(), interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSymbolT symbol;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tsymbol = std::stoi(arg);\n\t\t\t}\n\t\t\tcatch (std::invalid_argument)\n\t\t\t{\n\t\t\t\tinterpreter.OutputStream << \"Invalid symbol number.\" << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcatch (std::out_of_range)\n\t\t\t{\n\t\t\t\tinterpreter.OutputStream << \"Symbol value out of range.\" << std::endl;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tUtil::DescribeDefinition(symbol, interpreter.CopyDefinitions(), true, interpreter.OutputStream);\n\t\t\tinterpreter.OutputStream << std::endl;\n\t\t}\n\t}));\n\n\tAddCommand(InteractiveCommand(\"info\", \"Display interpreter information.\", [](Emmental& interpreter, std::string)\n\t{\n\t\tinterpreter.OutputStream << \"Gory Emmental Interpreter 1.0.0 by Davipb\" << std::endl;\n\n\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"== Compile-Time Settings ==\" << std::endl;\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"Symbol Type: \" << typeid(SymbolT).name() << std::endl;\n\t\tinterpreter.OutputStream << \"Symbol Size: \" << sizeof(SymbolT) << \" byte(s)\" << std::endl;\n\t\tinterpreter.OutputStream << \"Max Stack Size: \" << EMMENTAL_MAX_STACK_SIZE << std::endl;\n\t\tinterpreter.OutputStream << \"Max Queue Size: \" << EMMENTAL_MAX_QUEUE_SIZE << std::endl;\n\t\tinterpreter.OutputStream << \"Max Recursion Level: \" << EMMENTAL_MAX_RECURSION_LEVEL << std::endl;\n\n\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"== Runtime Settings ==\" << std::endl;\n\t\tUtil::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);\n\t\tinterpreter.OutputStream << \"Debug Mode: \" << (Globals::DebugMode ? \"On\" : \"Off\") << std::endl;\n\t\tinterpreter.OutputStream << \"Colors: \" << (Globals::UseVirtualConsole ? \"On\" : \"Off\") << std::endl;\n\t\tinterpreter.OutputStream << \"Optimization: \" << (Globals::OptimizeProgram ? \"On\" : \"Off\") << std::endl;\n\n\t}));\n}\n\nbool InteractiveInterpreter::ParseCommand(std::string input)\n{\n\tif (input.find(\"__\") != 0)\n\t\treturn false;\n\n\tstd::string command = input.substr(2, input.size() - 2);\n\n\tif (command.find(\"help\") == 0)\n\t{\n\t\tInterpreter.OutputStream << \"Commands are case-sensitive. Arguments come right after a command.\" << std::endl;\n\t\tInterpreter.OutputStream << std::endl;\n\n\t\tfor (auto& x : Commands)\n\t\t{\n\t\t\tUtil::Colorize(Util::ConsoleColor::BrightGreen, Interpreter.OutputStream);\n\t\t\tInterpreter.OutputStream << \"__\" << x.GetName() << \": \";\n\t\t\tUtil::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);\n\t\t\tInterpreter.OutputStream << x.GetDescription() << std::endl;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstd::string commandName = command;\n\tstd::string argument;\n\tauto spaceLocation = commandName.find(' ');\n\tif (spaceLocation != commandName.length())\n\t{\n\t\tcommandName = command.substr(0, spaceLocation);\n\t\targument = command.substr(spaceLocation + 1, command.length() - spaceLocation - 1);\n\t}\n\n\tfor (auto& x : Commands)\n\t{\n\t\tif (x.GetName() == commandName)\n\t\t{\n\t\t\tx.Execute(Interpreter, argument);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\t\n\tUtil::Colorize(Util::ConsoleColor::Red, Interpreter.OutputStream);\n\tInterpreter.OutputStream << \"Unknown command '\" << commandName << \"'. Use __help for a list of commands.\" << std::endl;\n\tUtil::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);\n\n\treturn true;\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"buyiopdialog.h\"\n\n#include \"addressbookpage.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nBuyIoPDialog::BuyIoPDialog(const PlatformStyle* _platformStyle, QWidget* parent) : QDialog(parent), platformStyle(_platformStyle), model(0)\n{\n slotblock = false;\n\n QVBoxLayout* layout = new QVBoxLayout(this);\n\n \/\/ ADRESS SELECTION\n adressLineEdit = new QLineEdit(this);\n adressLineEdit->setPlaceholderText(tr(\"choose adress or paste your own\"));\n selectAdress = new QPushButton(tr(\"choose\"));\n\n mailEdit = new QLineEdit(this);\n mailEdit->setPlaceholderText(tr(\"your email adress\"));\n\n QLabel* adressInfoLabel = new QLabel(tr(\"exchange service provided by indacoin.com\"));\n adressInfoLabel->setObjectName(\"buy_adressInfo\");\n\n QWidget* addressWidget = new QWidget(this);\n QVBoxLayout* topLayout = new QVBoxLayout(addressWidget);\n QHBoxLayout* adressLayout = new QHBoxLayout();\n QHBoxLayout* mailLayout = new QHBoxLayout();\n\n adressLayout->setContentsMargins(3, 0, 3, 0);\n adressLayout->setSpacing(3);\n adressLayout->addWidget(adressLineEdit);\n adressLayout->addWidget(selectAdress);\n mailLayout->addWidget(mailEdit);\n\n topLayout->addLayout(adressLayout);\n topLayout->addSpacing(20);\n topLayout->addLayout(mailLayout);\n topLayout->addSpacing(5);\n topLayout->addWidget(adressInfoLabel);\n\n layout->addWidget(addressWidget);\n\n layout->addSpacing(30);\n\n \/\/ AMOUNT SELECTION\n amountInfoLabel = new QLabel();\n QLabel* amountVaryInfoLabel = new QLabel(tr(\"the amount may vary\"));\n amountInfoLabel->setObjectName(\"buy_amountInfo\");\n amountVaryInfoLabel->setObjectName(\"buy_amountVaryInfo\");\n\n\n amountIOP = new QLabel();\n amountIOP->setMaximumWidth(350);\n amountIOP->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n amountIOP->setObjectName(\"buy_amountIOP\");\n\n IOPLabel = new QLabel(\"IOP\");\n IOPLabel->setObjectName(\"buy_IOPLabel\");\n \/\/IOPLabel->setMaximumWidth(500);\n\n currency = new QComboBox(this);\n currency->addItem(\"USD\");\n currency->addItem(\"EUR\");\n currency->addItem(\"RUB\");\n currency->setObjectName(\"buy_currency\");\n \/\/currency->setMaximumWidth(500);\n\n paySpinBox = new QDoubleSpinBox();\n paySpinBox->setObjectName(\"pay_spinbox\");\n paySpinBox->setRange(50, 50000);\n paySpinBox->setDecimals(2);\n paySpinBox->setSingleStep(1);\n paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);\n \/\/paySpinBox->setMaximumWidth(350);\n paySpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n\n buyButton = new QPushButton(tr(\"buy\"));\n buyButton->setObjectName(\"buyButton\");\n buyButton->setEnabled(false);\n\n QWidget* bottomWidget = new QWidget(this);\n QGridLayout* bottomLayout = new QGridLayout(bottomWidget);\n\n QWidget* buttonWidget = new QWidget(bottomWidget);\n QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);\n\n buttonLayout->addWidget(buyButton);\n\n QWidget* payAmount = new QWidget(bottomWidget);\n QGridLayout* payLayout = new QGridLayout(payAmount);\n payLayout->setHorizontalSpacing(10);\n payLayout->setVerticalSpacing(5);\n payLayout->setRowMinimumHeight(2,10);\n payLayout->setColumnMinimumWidth(0,100);\n\n payLayout->addWidget(paySpinBox,0,0);\n payLayout->addWidget(currency,0,1);\n payLayout->addWidget(amountInfoLabel,1,0,1,2);\n\n payLayout->addWidget(amountIOP,3,0);\n payLayout->addWidget(IOPLabel,3,1);\n payLayout->addWidget(amountVaryInfoLabel,4,0,2,1);\n\n bottomLayout->addWidget(payAmount, 0, 0, Qt::AlignLeft);\n bottomLayout->addWidget(buttonWidget, 0, 1, Qt::AlignBottom | Qt::AlignRight);\n\n layout->addWidget(bottomWidget);\n \n amountInfoLabel->setText(tr(\"minimum exchange value: \").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(\" \").append(CURRENCY[currency->currentIndex()]));\n\n \n QFrame* lineb1 = new QFrame(this);\n lineb1->setObjectName(QStringLiteral(\"lineb1\"));\n lineb1->setFrameShape(QFrame::HLine);\n lineb1->setFrameShadow(QFrame::Sunken);\n layout->addWidget(lineb1);\n\n layout->addSpacing(20);\n\n\n \n \/\/network management\n iopPriceNAM = new QNetworkAccessManager();\n\n \/\/SLOTS\n connect(currency, SIGNAL(currentIndexChanged(int)), this, SLOT(physicalUpdated(int)));\n connect(adressLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(adressChanged(const QString&)));\n connect(selectAdress, SIGNAL(clicked()), this, SLOT(chooseAdress()));\n connect(paySpinBox, SIGNAL(valueChanged(double)), this, SLOT(physicalUpdated(double)));\n connect(iopPriceNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotIoPPrice(QNetworkReply*)));\n connect(buyButton, SIGNAL(clicked()), this, SLOT(sendBuyRequest()));\n\n\n updateIoPPrice(paySpinBox->value());\n}\n\n\nvoid BuyIoPDialog::setModel(WalletModel* _model)\n{\n this->model = _model;\n}\n\nvoid BuyIoPDialog::adressChanged(const QString& txt)\n{\n if (adressLineEdit->text().isEmpty() || model->validateAddress(adressLineEdit->text())) {\n buyButton->setEnabled(true);\n adressLineEdit->setStyleSheet(\"\");\n \/\/std::cout << \"buybutton enabled\" << std::endl;\n } else {\n buyButton->setEnabled(false);\n \/\/adressLineEdit->setValid(false);\n adressLineEdit->setStyleSheet(\"background: rgb(155,0,0);\");\n\n \/\/std::cout << \"buybutton enabled\" << std::endl;\n }\n}\n\nvoid BuyIoPDialog::chooseAdress()\n{\n if (model) {\n AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);\n dlg.setModel(model->getAddressTableModel());\n if (dlg.exec()) {\n adressLineEdit->setText(dlg.getReturnValue());\n }\n }\n}\n\nvoid BuyIoPDialog::physicalUpdated(int i)\n{\n BuyIoPDialog::physicalUpdated(paySpinBox->value());\n}\n\nvoid BuyIoPDialog::physicalUpdated(double i)\n{\n\n amountInfoLabel->setText(tr(\"minimum exchange value: \").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(\" \").append(CURRENCY[currency->currentIndex()]));\n \n if (i > MIN_PRICE[currency->currentIndex()] && i < MAX_PRICE[currency->currentIndex()])\n updateIoPPrice(i);\n else {\n paySpinBox->setRange(MIN_PRICE[currency->currentIndex()], MAX_PRICE[currency->currentIndex()]);\n \/* if (i <= MIN_PRICE[currency->currentIndex()])\n paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);\n if (i >= MAX_PRICE[currency->currentIndex()])\n paySpinBox->setValue(MAX_PRICE[currency->currentIndex()]); *\/\n }\n}\n\nvoid BuyIoPDialog::updateIoPPrice(double amount)\n{\n responsed = false;\n QNetworkRequest request(QUrl(QString(GET_PRICE).append(CURRENCY[currency->currentIndex()]).append(SEPERATOR).append(IOP_CURRENCY).append(SEPERATOR).append(QString::number(amount).append(SEPERATOR))));\n \/\/std::cout << \"iop price: \" << request.url().toString().toStdString() << std::endl;\n iopPriceNAM->get(request);\n}\n\nvoid BuyIoPDialog::sendBuyRequest()\n{\n QString adress = QString(BUY_URL).append(PARTNER_NAME).append(CUR_FROM).append(CURRENCY[currency->currentIndex()]).append(CUR_TO).append(IOP_CURRENCY).append(AMOUNT).append(QString::number(paySpinBox->value()).append(ADDRESS).append(adressLineEdit->text()).append(USER_ID).append(mailEdit->text().replace('@',\"%40\",Qt::CaseInsensitive)));\n \/\/std::cout << \"buy url: \" << adress.toStdString() << std::endl;\n\n QDesktopServices::openUrl(QUrl(adress, QUrl::TolerantMode));\n}\n\nvoid BuyIoPDialog::gotIoPPrice(QNetworkReply* reply)\n{\n if (reply->error()) {\n std::cout << \"ERROR! \" << reply->errorString().toStdString() << std::endl; \/\/Error handling\n responsed = true;\n return;\n }\n QString answer = reply->readAll();\n bool successfullParsed;\n iopPrice = answer.toDouble(&successfullParsed);\n \/\/std::cout << \"GOT PRICE: \" << answer.toStdString() << std::endl;\n amountIOP->setText(QString::number(iopPrice));\n responsed = true;\n return;\n}\n\nBuyIoPDialog::~BuyIoPDialog()\n{\n}\nmatching number seperators\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"buyiopdialog.h\"\n\n#include \"addressbookpage.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nBuyIoPDialog::BuyIoPDialog(const PlatformStyle* _platformStyle, QWidget* parent) : QDialog(parent), platformStyle(_platformStyle), model(0)\n{\n slotblock = false;\n\n QVBoxLayout* layout = new QVBoxLayout(this);\n\n \/\/ ADRESS SELECTION\n adressLineEdit = new QLineEdit(this);\n adressLineEdit->setPlaceholderText(tr(\"choose adress or paste your own\"));\n selectAdress = new QPushButton(tr(\"choose\"));\n\n mailEdit = new QLineEdit(this);\n mailEdit->setPlaceholderText(tr(\"your email adress\"));\n\n QLabel* adressInfoLabel = new QLabel(tr(\"exchange service provided by indacoin.com\"));\n adressInfoLabel->setObjectName(\"buy_adressInfo\");\n\n QWidget* addressWidget = new QWidget(this);\n QVBoxLayout* topLayout = new QVBoxLayout(addressWidget);\n QHBoxLayout* adressLayout = new QHBoxLayout();\n QHBoxLayout* mailLayout = new QHBoxLayout();\n\n adressLayout->setContentsMargins(3, 0, 3, 0);\n adressLayout->setSpacing(3);\n adressLayout->addWidget(adressLineEdit);\n adressLayout->addWidget(selectAdress);\n mailLayout->addWidget(mailEdit);\n\n topLayout->addLayout(adressLayout);\n topLayout->addSpacing(20);\n topLayout->addLayout(mailLayout);\n topLayout->addSpacing(5);\n topLayout->addWidget(adressInfoLabel);\n\n layout->addWidget(addressWidget);\n\n layout->addSpacing(30);\n\n \/\/ AMOUNT SELECTION\n amountInfoLabel = new QLabel();\n QLabel* amountVaryInfoLabel = new QLabel(tr(\"the amount may vary\"));\n amountInfoLabel->setObjectName(\"buy_amountInfo\");\n amountVaryInfoLabel->setObjectName(\"buy_amountVaryInfo\");\n\n\n amountIOP = new QLabel();\n amountIOP->setMaximumWidth(350);\n amountIOP->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n amountIOP->setObjectName(\"buy_amountIOP\");\n\n IOPLabel = new QLabel(\"IOP\");\n IOPLabel->setObjectName(\"buy_IOPLabel\");\n \/\/IOPLabel->setMaximumWidth(500);\n\n currency = new QComboBox(this);\n currency->addItem(\"USD\");\n currency->addItem(\"EUR\");\n currency->addItem(\"RUB\");\n currency->setObjectName(\"buy_currency\");\n \/\/currency->setMaximumWidth(500);\n\n paySpinBox = new QDoubleSpinBox();\n paySpinBox->setObjectName(\"pay_spinbox\");\n paySpinBox->setRange(50, 50000);\n paySpinBox->setDecimals(2);\n paySpinBox->setSingleStep(1);\n paySpinBox->setLocale(QLocale::Language::English);\n paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);\n \/\/paySpinBox->setMaximumWidth(350);\n paySpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);\n\n buyButton = new QPushButton(tr(\"buy\"));\n buyButton->setObjectName(\"buyButton\");\n buyButton->setEnabled(false);\n\n QWidget* bottomWidget = new QWidget(this);\n QGridLayout* bottomLayout = new QGridLayout(bottomWidget);\n\n QWidget* buttonWidget = new QWidget(bottomWidget);\n QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);\n\n buttonLayout->addWidget(buyButton);\n\n QWidget* payAmount = new QWidget(bottomWidget);\n QGridLayout* payLayout = new QGridLayout(payAmount);\n payLayout->setHorizontalSpacing(10);\n payLayout->setVerticalSpacing(5);\n payLayout->setRowMinimumHeight(2,10);\n payLayout->setColumnMinimumWidth(0,100);\n\n payLayout->addWidget(paySpinBox,0,0);\n payLayout->addWidget(currency,0,1);\n payLayout->addWidget(amountInfoLabel,1,0,1,2);\n\n payLayout->addWidget(amountIOP,3,0);\n payLayout->addWidget(IOPLabel,3,1);\n payLayout->addWidget(amountVaryInfoLabel,4,0,2,1);\n\n bottomLayout->addWidget(payAmount, 0, 0, Qt::AlignLeft);\n bottomLayout->addWidget(buttonWidget, 0, 1, Qt::AlignBottom | Qt::AlignRight);\n\n layout->addWidget(bottomWidget);\n \n amountInfoLabel->setText(tr(\"minimum exchange value: \").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(\" \").append(CURRENCY[currency->currentIndex()]));\n\n \n QFrame* lineb1 = new QFrame(this);\n lineb1->setObjectName(QStringLiteral(\"lineb1\"));\n lineb1->setFrameShape(QFrame::HLine);\n lineb1->setFrameShadow(QFrame::Sunken);\n layout->addWidget(lineb1);\n\n layout->addSpacing(20);\n\n\n \n \/\/network management\n iopPriceNAM = new QNetworkAccessManager();\n\n \/\/SLOTS\n connect(currency, SIGNAL(currentIndexChanged(int)), this, SLOT(physicalUpdated(int)));\n connect(adressLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(adressChanged(const QString&)));\n connect(selectAdress, SIGNAL(clicked()), this, SLOT(chooseAdress()));\n connect(paySpinBox, SIGNAL(valueChanged(double)), this, SLOT(physicalUpdated(double)));\n connect(iopPriceNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotIoPPrice(QNetworkReply*)));\n connect(buyButton, SIGNAL(clicked()), this, SLOT(sendBuyRequest()));\n\n\n updateIoPPrice(paySpinBox->value());\n}\n\n\nvoid BuyIoPDialog::setModel(WalletModel* _model)\n{\n this->model = _model;\n}\n\nvoid BuyIoPDialog::adressChanged(const QString& txt)\n{\n if (adressLineEdit->text().isEmpty() || model->validateAddress(adressLineEdit->text())) {\n buyButton->setEnabled(true);\n adressLineEdit->setStyleSheet(\"\");\n \/\/std::cout << \"buybutton enabled\" << std::endl;\n } else {\n buyButton->setEnabled(false);\n \/\/adressLineEdit->setValid(false);\n adressLineEdit->setStyleSheet(\"background: rgb(155,0,0);\");\n\n \/\/std::cout << \"buybutton enabled\" << std::endl;\n }\n}\n\nvoid BuyIoPDialog::chooseAdress()\n{\n if (model) {\n AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);\n dlg.setModel(model->getAddressTableModel());\n if (dlg.exec()) {\n adressLineEdit->setText(dlg.getReturnValue());\n }\n }\n}\n\nvoid BuyIoPDialog::physicalUpdated(int i)\n{\n BuyIoPDialog::physicalUpdated(paySpinBox->value());\n}\n\nvoid BuyIoPDialog::physicalUpdated(double i)\n{\n\n amountInfoLabel->setText(tr(\"minimum exchange value: \").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(\" \").append(CURRENCY[currency->currentIndex()]));\n \n if (i > MIN_PRICE[currency->currentIndex()] && i < MAX_PRICE[currency->currentIndex()])\n updateIoPPrice(i);\n else {\n paySpinBox->setRange(MIN_PRICE[currency->currentIndex()], MAX_PRICE[currency->currentIndex()]);\n \/* if (i <= MIN_PRICE[currency->currentIndex()])\n paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);\n if (i >= MAX_PRICE[currency->currentIndex()])\n paySpinBox->setValue(MAX_PRICE[currency->currentIndex()]); *\/\n }\n}\n\nvoid BuyIoPDialog::updateIoPPrice(double amount)\n{\n responsed = false;\n QNetworkRequest request(QUrl(QString(GET_PRICE).append(CURRENCY[currency->currentIndex()]).append(SEPERATOR).append(IOP_CURRENCY).append(SEPERATOR).append(QString::number(amount).append(SEPERATOR))));\n \/\/std::cout << \"iop price: \" << request.url().toString().toStdString() << std::endl;\n iopPriceNAM->get(request);\n}\n\nvoid BuyIoPDialog::sendBuyRequest()\n{\n QString adress = QString(BUY_URL).append(PARTNER_NAME).append(CUR_FROM).append(CURRENCY[currency->currentIndex()]).append(CUR_TO).append(IOP_CURRENCY).append(AMOUNT).append(QString::number(paySpinBox->value()).append(ADDRESS).append(adressLineEdit->text()).append(USER_ID).append(mailEdit->text().replace('@',\"%40\",Qt::CaseInsensitive)));\n \/\/std::cout << \"buy url: \" << adress.toStdString() << std::endl;\n\n QDesktopServices::openUrl(QUrl(adress, QUrl::TolerantMode));\n}\n\nvoid BuyIoPDialog::gotIoPPrice(QNetworkReply* reply)\n{\n if (reply->error()) {\n std::cout << \"ERROR! \" << reply->errorString().toStdString() << std::endl; \/\/Error handling\n responsed = true;\n return;\n }\n QString answer = reply->readAll();\n bool successfullParsed;\n iopPrice = answer.toDouble(&successfullParsed);\n \/\/std::cout << \"GOT PRICE: \" << answer.toStdString() << std::endl;\n amountIOP->setText(QString::number(iopPrice));\n responsed = true;\n return;\n}\n\nBuyIoPDialog::~BuyIoPDialog()\n{\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights\n\/\/ reserved. Use of this source code is governed by a BSD-style license that\n\/\/ can be found in the LICENSE file.\n\/\/\n\/\/ ---------------------------------------------------------------------------\n\/\/\n\/\/ A portion of this file was generated by the CEF translator tool. When\n\/\/ making changes by hand only do so within the body of existing function\n\/\/ implementations. See the translator.README.txt file in the tools directory\n\/\/ for more information.\n\/\/\n\n#include \"libcef_dll\/cpptoc\/client_cpptoc.h\"\n#include \"libcef_dll\/cpptoc\/life_span_handler_cpptoc.h\"\n#include \"libcef_dll\/ctocpp\/browser_ctocpp.h\"\n\n\n\/\/ MEMBER FUNCTIONS - Body may be edited by hand.\n\nint CEF_CALLBACK life_span_handler_on_before_popup(\n struct _cef_life_span_handler_t* self, cef_browser_t* parentBrowser,\n const struct _cef_popup_features_t* popupFeatures,\n cef_window_info_t* windowInfo, const cef_string_t* url,\n struct _cef_client_t** client, struct _cef_browser_settings_t* settings)\n{\n DCHECK(self);\n DCHECK(parentBrowser);\n DCHECK(popupFeatures);\n DCHECK(windowInfo);\n DCHECK(url);\n DCHECK(client);\n DCHECK(settings);\n if (!self || !parentBrowser || !popupFeatures || !windowInfo || !url ||\n !client || !settings)\n return 0;\n\n CefWindowInfo wndInfo;\n CefBrowserSettings browserSettings;\n CefPopupFeatures features;\n \n \/\/ Take ownership of the values.\n wndInfo.AttachTo(*windowInfo);\n browserSettings.AttachTo(*settings);\n \n \/\/ Reference the existing values instead of copying.\n features.Set(*popupFeatures, false);\n \n \/\/ |newHandler| will start off pointing to the current handler.\n CefRefPtr clientPtr;\n if (*client)\n clientPtr = CefClientCppToC::Unwrap(*client);\n CefClient* origClient = clientPtr.get();\n \n \/\/ |parentBrowser| will be NULL if this is a top-level browser window.\n CefRefPtr browserPtr(CefBrowserCToCpp::Wrap(parentBrowser));\n \n bool rv = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup(\n browserPtr, features, wndInfo, CefString(url), clientPtr,\n browserSettings);\n\n if (clientPtr.get()) {\n if (clientPtr.get() != origClient) {\n \/\/ The handler has been changed.\n *client = CefClientCppToC::Wrap(clientPtr);\n }\n } else {\n *client = NULL;\n }\n\n \/\/ Return the values to the structures.\n wndInfo.DetachTo(*windowInfo);\n browserSettings.DetachTo(*settings);\n\n return rv;\n}\n\nvoid CEF_CALLBACK life_span_handler_on_after_created(\n struct _cef_life_span_handler_t* self, cef_browser_t* browser)\n{\n DCHECK(self);\n DCHECK(browser);\n if (!self || !browser)\n return;\n\n CefLifeSpanHandlerCppToC::Get(self)->OnAfterCreated(\n CefBrowserCToCpp::Wrap(browser));\n}\n\nvoid CEF_CALLBACK life_span_handler_on_before_close(\n struct _cef_life_span_handler_t* self, cef_browser_t* browser)\n{\n DCHECK(self);\n DCHECK(browser);\n if (!self || !browser)\n return;\n\n CefLifeSpanHandlerCppToC::Get(self)->OnBeforeClose(\n CefBrowserCToCpp::Wrap(browser));\n}\n\n\n\/\/ CONSTRUCTOR - Do not edit by hand.\n\nCefLifeSpanHandlerCppToC::CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls)\n : CefCppToC(cls)\n{\n struct_.struct_.on_before_popup = life_span_handler_on_before_popup;\n struct_.struct_.on_after_created = life_span_handler_on_after_created;\n struct_.struct_.on_before_close = life_span_handler_on_before_close;\n}\n\n#ifndef NDEBUG\ntemplate<> long CefCppToC::DebugObjCt = 0;\n#endif\n\nRemove the url check from life_span_handler_on_before_popup because the URL will be NULL when clicking a link with target=\"_blank\" (issue #247).\/\/ Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights\n\/\/ reserved. Use of this source code is governed by a BSD-style license that\n\/\/ can be found in the LICENSE file.\n\/\/\n\/\/ ---------------------------------------------------------------------------\n\/\/\n\/\/ A portion of this file was generated by the CEF translator tool. When\n\/\/ making changes by hand only do so within the body of existing function\n\/\/ implementations. See the translator.README.txt file in the tools directory\n\/\/ for more information.\n\/\/\n\n#include \"libcef_dll\/cpptoc\/client_cpptoc.h\"\n#include \"libcef_dll\/cpptoc\/life_span_handler_cpptoc.h\"\n#include \"libcef_dll\/ctocpp\/browser_ctocpp.h\"\n\n\n\/\/ MEMBER FUNCTIONS - Body may be edited by hand.\n\nint CEF_CALLBACK life_span_handler_on_before_popup(\n struct _cef_life_span_handler_t* self, cef_browser_t* parentBrowser,\n const struct _cef_popup_features_t* popupFeatures,\n cef_window_info_t* windowInfo, const cef_string_t* url,\n struct _cef_client_t** client, struct _cef_browser_settings_t* settings)\n{\n DCHECK(self);\n DCHECK(parentBrowser);\n DCHECK(popupFeatures);\n DCHECK(windowInfo);\n DCHECK(client);\n DCHECK(settings);\n if (!self || !parentBrowser || !popupFeatures || !windowInfo || !client ||\n !settings)\n return 0;\n\n CefWindowInfo wndInfo;\n CefBrowserSettings browserSettings;\n CefPopupFeatures features;\n\n \/\/ Take ownership of the values.\n wndInfo.AttachTo(*windowInfo);\n browserSettings.AttachTo(*settings);\n\n \/\/ Reference the existing values instead of copying.\n features.Set(*popupFeatures, false);\n\n \/\/ |newHandler| will start off pointing to the current handler.\n CefRefPtr clientPtr;\n if (*client)\n clientPtr = CefClientCppToC::Unwrap(*client);\n CefClient* origClient = clientPtr.get();\n\n \/\/ |parentBrowser| will be NULL if this is a top-level browser window.\n CefRefPtr browserPtr(CefBrowserCToCpp::Wrap(parentBrowser));\n\n bool rv = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup(\n browserPtr, features, wndInfo, CefString(url), clientPtr,\n browserSettings);\n\n if (clientPtr.get()) {\n if (clientPtr.get() != origClient) {\n \/\/ The handler has been changed.\n *client = CefClientCppToC::Wrap(clientPtr);\n }\n } else {\n *client = NULL;\n }\n\n \/\/ Return the values to the structures.\n wndInfo.DetachTo(*windowInfo);\n browserSettings.DetachTo(*settings);\n\n return rv;\n}\n\nvoid CEF_CALLBACK life_span_handler_on_after_created(\n struct _cef_life_span_handler_t* self, cef_browser_t* browser)\n{\n DCHECK(self);\n DCHECK(browser);\n if (!self || !browser)\n return;\n\n CefLifeSpanHandlerCppToC::Get(self)->OnAfterCreated(\n CefBrowserCToCpp::Wrap(browser));\n}\n\nvoid CEF_CALLBACK life_span_handler_on_before_close(\n struct _cef_life_span_handler_t* self, cef_browser_t* browser)\n{\n DCHECK(self);\n DCHECK(browser);\n if (!self || !browser)\n return;\n\n CefLifeSpanHandlerCppToC::Get(self)->OnBeforeClose(\n CefBrowserCToCpp::Wrap(browser));\n}\n\n\n\/\/ CONSTRUCTOR - Do not edit by hand.\n\nCefLifeSpanHandlerCppToC::CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls)\n : CefCppToC(cls)\n{\n struct_.struct_.on_before_popup = life_span_handler_on_before_popup;\n struct_.struct_.on_after_created = life_span_handler_on_after_created;\n struct_.struct_.on_before_close = life_span_handler_on_before_close;\n}\n\n#ifndef NDEBUG\ntemplate<> long CefCppToC::DebugObjCt = 0;\n#endif\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestMultiBlock.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\/\/ This example demonstrates how hierarchical box (uniform rectilinear)\n\/\/ AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class. \n\/\/ \n\/\/ The command line arguments are:\n\/\/ -I => run in interactive mode; unless this is used, the program will\n\/\/ not allow interaction and exit\n\/\/ -D => path to the data; the data should be in \/Data\/\n\n#include \"vtkCellDataToPointData.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkDebugLeaks.h\"\n#include \"vtkHierarchicalDataExtractDataSets.h\"\n#include \"vtkHierarchicalDataSetGeometryFilter.h\"\n#include \"vtkMultiBlockPLOT3DReader.h\"\n#include \"vtkOutlineCornerFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkShrinkPolyData.h\"\n#include \"vtkTestUtilities.h\"\n\nint TestMultiBlock(int argc, char* argv[])\n{\n \/\/ Disable for testing\n vtkDebugLeaks::PromptUserOff();\n\n \/\/ Standard rendering classes\n vtkRenderer *ren = vtkRenderer::New();\n vtkRenderWindow *renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren);\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n char* xyzname = \n vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/mbwavelet_ascii.xyz\");\n char* qname = \n vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/mbwavelet_ascii.q\");\n\n vtkMultiBlockPLOT3DReader* reader = vtkMultiBlockPLOT3DReader::New();\n reader->SetXYZFileName(xyzname);\n reader->SetQFileName(qname);\n reader->SetMultiGrid(1);\n reader->SetBinaryFile(0);\n delete[] xyzname;\n delete[] qname;\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom->SetInputConnection(0, reader->GetOutputPort(0));\n\n vtkShrinkPolyData* shrink = vtkShrinkPolyData::New();\n shrink->SetShrinkFactor(0.2);\n shrink->SetInputConnection(0, geom->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* shMapper = vtkPolyDataMapper::New();\n shMapper->SetInputConnection(0, shrink->GetOutputPort(0));\n vtkActor* shActor = vtkActor::New();\n shActor->SetMapper(shMapper);\n shActor->GetProperty()->SetColor(0, 0, 1);\n ren->AddActor(shActor);\n\n \/\/ corner outline\n vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New();\n ocf->SetInputConnection(0, reader->GetOutputPort(0));\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom2 = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom2->SetInputConnection(0, ocf->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* ocMapper = vtkPolyDataMapper::New();\n ocMapper->SetInputConnection(0, geom2->GetOutputPort(0));\n vtkActor* ocActor = vtkActor::New();\n ocActor->SetMapper(ocMapper);\n ocActor->GetProperty()->SetColor(1, 0, 0);\n ren->AddActor(ocActor);\n\n \/\/ extract a block\n vtkHierarchicalDataExtractDataSets* eds = \n vtkHierarchicalDataExtractDataSets::New();\n eds->SetInputConnection(0, reader->GetOutputPort(0));\n eds->AddDataSet(0, 1);\n\n \/\/ contour\n vtkContourFilter* contour = vtkContourFilter::New();\n contour->SetInputConnection(0, eds->GetOutputPort(0));\n contour->SetValue(0, 149);\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom3 = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom3->SetInputConnection(0, contour->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* contMapper = vtkPolyDataMapper::New();\n contMapper->SetInputConnection(0, geom3->GetOutputPort(0));\n vtkActor* contActor = vtkActor::New();\n contActor->SetMapper(contMapper);\n contActor->GetProperty()->SetColor(1, 0, 0);\n ren->AddActor(contActor);\n \n \/\/ Standard testing code.\n eds->Delete();\n ocf->Delete();\n geom2->Delete();\n ocMapper->Delete();\n ocActor->Delete();\n contour->Delete();\n geom3->Delete();\n contMapper->Delete();\n contActor->Delete();\n ren->SetBackground(1,1,1);\n renWin->SetSize(300,300);\n renWin->Render();\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n \n \/\/ Cleanup\n geom->Delete();\n shMapper->Delete();\n shActor->Delete();\n ren->Delete();\n renWin->Delete();\n iren->Delete();\n reader->Delete();\n shrink->Delete();\n \n return !retVal;\n}\nENH: Changed camera position to avoid small polygones (failure on some opengl drivers)\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestMultiBlock.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\/\/ This example demonstrates how hierarchical box (uniform rectilinear)\n\/\/ AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class. \n\/\/ \n\/\/ The command line arguments are:\n\/\/ -I => run in interactive mode; unless this is used, the program will\n\/\/ not allow interaction and exit\n\/\/ -D => path to the data; the data should be in \/Data\/\n\n#include \"vtkCamera.h\"\n#include \"vtkCellDataToPointData.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkDebugLeaks.h\"\n#include \"vtkHierarchicalDataExtractDataSets.h\"\n#include \"vtkHierarchicalDataSetGeometryFilter.h\"\n#include \"vtkMultiBlockPLOT3DReader.h\"\n#include \"vtkOutlineCornerFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkShrinkPolyData.h\"\n#include \"vtkTestUtilities.h\"\n\nint TestMultiBlock(int argc, char* argv[])\n{\n \/\/ Disable for testing\n vtkDebugLeaks::PromptUserOff();\n\n \/\/ Standard rendering classes\n vtkRenderer *ren = vtkRenderer::New();\n vtkCamera* cam = ren->GetActiveCamera();\n cam->SetPosition(-5.1828, 5.89733, 8.97969);\n cam->SetFocalPoint(14.6491, -2.08677, -8.92362);\n cam->SetViewUp(0.210794, 0.95813, -0.193784);\n\n vtkRenderWindow *renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren);\n vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n\n char* xyzname = \n vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/mbwavelet_ascii.xyz\");\n char* qname = \n vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/mbwavelet_ascii.q\");\n\n vtkMultiBlockPLOT3DReader* reader = vtkMultiBlockPLOT3DReader::New();\n reader->SetXYZFileName(xyzname);\n reader->SetQFileName(qname);\n reader->SetMultiGrid(1);\n reader->SetBinaryFile(0);\n delete[] xyzname;\n delete[] qname;\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom->SetInputConnection(0, reader->GetOutputPort(0));\n\n vtkShrinkPolyData* shrink = vtkShrinkPolyData::New();\n shrink->SetShrinkFactor(0.2);\n shrink->SetInputConnection(0, geom->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* shMapper = vtkPolyDataMapper::New();\n shMapper->SetInputConnection(0, shrink->GetOutputPort(0));\n vtkActor* shActor = vtkActor::New();\n shActor->SetMapper(shMapper);\n shActor->GetProperty()->SetColor(0, 0, 1);\n ren->AddActor(shActor);\n\n \/\/ corner outline\n vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New();\n ocf->SetInputConnection(0, reader->GetOutputPort(0));\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom2 = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom2->SetInputConnection(0, ocf->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* ocMapper = vtkPolyDataMapper::New();\n ocMapper->SetInputConnection(0, geom2->GetOutputPort(0));\n vtkActor* ocActor = vtkActor::New();\n ocActor->SetMapper(ocMapper);\n ocActor->GetProperty()->SetColor(1, 0, 0);\n ren->AddActor(ocActor);\n\n \/\/ extract a block\n vtkHierarchicalDataExtractDataSets* eds = \n vtkHierarchicalDataExtractDataSets::New();\n eds->SetInputConnection(0, reader->GetOutputPort(0));\n eds->AddDataSet(0, 1);\n\n \/\/ contour\n vtkContourFilter* contour = vtkContourFilter::New();\n contour->SetInputConnection(0, eds->GetOutputPort(0));\n contour->SetValue(0, 149);\n\n \/\/ geometry filter\n vtkHierarchicalDataSetGeometryFilter* geom3 = \n vtkHierarchicalDataSetGeometryFilter::New();\n geom3->SetInputConnection(0, contour->GetOutputPort(0));\n\n \/\/ Rendering objects\n vtkPolyDataMapper* contMapper = vtkPolyDataMapper::New();\n contMapper->SetInputConnection(0, geom3->GetOutputPort(0));\n vtkActor* contActor = vtkActor::New();\n contActor->SetMapper(contMapper);\n contActor->GetProperty()->SetColor(1, 0, 0);\n ren->AddActor(contActor);\n \n \/\/ Standard testing code.\n eds->Delete();\n ocf->Delete();\n geom2->Delete();\n ocMapper->Delete();\n ocActor->Delete();\n contour->Delete();\n geom3->Delete();\n contMapper->Delete();\n contActor->Delete();\n ren->SetBackground(1,1,1);\n renWin->SetSize(300,300);\n renWin->Render();\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n \n \/\/ Cleanup\n geom->Delete();\n shMapper->Delete();\n shActor->Delete();\n ren->Delete();\n renWin->Delete();\n iren->Delete();\n reader->Delete();\n shrink->Delete();\n \n return !retVal;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2018 Istio Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/envoy\/http\/authn\/http_filter.h\"\n#include \"authentication\/v1alpha1\/policy.pb.h\"\n#include \"common\/http\/utility.h\"\n#include \"envoy\/config\/filter\/http\/authn\/v2alpha1\/config.pb.h\"\n#include \"src\/envoy\/http\/authn\/origin_authenticator.h\"\n#include \"src\/envoy\/http\/authn\/peer_authenticator.h\"\n#include \"src\/envoy\/utils\/authn.h\"\n#include \"src\/envoy\/utils\/utils.h\"\n\nusing istio::authn::Payload;\nusing istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig;\n\nnamespace iaapi = istio::authentication::v1alpha1;\n\nnamespace Envoy {\nnamespace Http {\nnamespace Istio {\nnamespace AuthN {\n\nAuthenticationFilter::AuthenticationFilter(const FilterConfig& filter_config)\n : filter_config_(filter_config) {}\n\nAuthenticationFilter::~AuthenticationFilter() {}\n\nvoid AuthenticationFilter::onDestroy() {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n}\n\nFilterHeadersStatus AuthenticationFilter::decodeHeaders(HeaderMap& headers,\n bool) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n state_ = State::PROCESSING;\n\n filter_context_.reset(new Istio::AuthN::FilterContext(\n &headers, decoder_callbacks_->connection(), filter_config_));\n\n Payload payload;\n\n if (!createPeerAuthenticator(filter_context_.get())->run(&payload)) {\n rejectRequest(\"Peer authentication failed.\");\n return FilterHeadersStatus::StopIteration;\n }\n\n bool success =\n createOriginAuthenticator(filter_context_.get())->run(&payload);\n\n \/\/ After Istio authn, the JWT headers consumed by Istio authn should be\n \/\/ removed.\n \/\/ TODO: remove internal headers used to pass data between filters\n \/\/ https:\/\/github.com\/istio\/istio\/issues\/4689\n for (auto const iter : filter_config_.jwt_output_payload_locations()) {\n filter_context_->headers()->remove(LowerCaseString(iter.second));\n }\n\n if (!success) {\n rejectRequest(\"Origin authentication failed.\");\n return FilterHeadersStatus::StopIteration;\n }\n\n \/\/ Put authentication result to headers.\n if (filter_context_ != nullptr) {\n Utils::Authentication::SaveResultToHeader(\n filter_context_->authenticationResult(), filter_context_->headers());\n }\n\n return FilterHeadersStatus::Continue;\n}\n\nFilterDataStatus AuthenticationFilter::decodeData(Buffer::Instance&, bool) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n ENVOY_LOG(debug,\n \"Called AuthenticationFilter : {} FilterDataStatus::Continue;\",\n __FUNCTION__);\n if (state_ == State::PROCESSING) {\n return FilterDataStatus::StopIterationAndWatermark;\n }\n return FilterDataStatus::Continue;\n}\n\nFilterTrailersStatus AuthenticationFilter::decodeTrailers(HeaderMap&) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n if (state_ == State::PROCESSING) {\n return FilterTrailersStatus::StopIteration;\n }\n return FilterTrailersStatus::Continue;\n}\n\nvoid AuthenticationFilter::setDecoderFilterCallbacks(\n StreamDecoderFilterCallbacks& callbacks) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n decoder_callbacks_ = &callbacks;\n}\n\nvoid AuthenticationFilter::rejectRequest(const std::string& message) {\n if (state_ != State::PROCESSING) {\n ENVOY_LOG(error, \"State {} is not PROCESSING.\", state_);\n return;\n }\n state_ = State::REJECTED;\n Utility::sendLocalReply(*decoder_callbacks_, false, Http::Code::Unauthorized,\n message);\n}\n\nstd::unique_ptr\nAuthenticationFilter::createPeerAuthenticator(\n Istio::AuthN::FilterContext* filter_context) {\n return std::make_unique(\n filter_context, filter_config_.policy());\n}\n\nstd::unique_ptr\nAuthenticationFilter::createOriginAuthenticator(\n Istio::AuthN::FilterContext* filter_context) {\n return std::make_unique(\n filter_context, filter_config_.policy());\n}\n\n} \/\/ namespace AuthN\n} \/\/ namespace Istio\n} \/\/ namespace Http\n} \/\/ namespace Envoy\nFix a bug that Istio authn filter blocks downstream filters (#1465)\/* Copyright 2018 Istio Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/envoy\/http\/authn\/http_filter.h\"\n#include \"authentication\/v1alpha1\/policy.pb.h\"\n#include \"common\/http\/utility.h\"\n#include \"envoy\/config\/filter\/http\/authn\/v2alpha1\/config.pb.h\"\n#include \"src\/envoy\/http\/authn\/origin_authenticator.h\"\n#include \"src\/envoy\/http\/authn\/peer_authenticator.h\"\n#include \"src\/envoy\/utils\/authn.h\"\n#include \"src\/envoy\/utils\/utils.h\"\n\nusing istio::authn::Payload;\nusing istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig;\n\nnamespace iaapi = istio::authentication::v1alpha1;\n\nnamespace Envoy {\nnamespace Http {\nnamespace Istio {\nnamespace AuthN {\n\nAuthenticationFilter::AuthenticationFilter(const FilterConfig& filter_config)\n : filter_config_(filter_config) {}\n\nAuthenticationFilter::~AuthenticationFilter() {}\n\nvoid AuthenticationFilter::onDestroy() {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n}\n\nFilterHeadersStatus AuthenticationFilter::decodeHeaders(HeaderMap& headers,\n bool) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n state_ = State::PROCESSING;\n\n filter_context_.reset(new Istio::AuthN::FilterContext(\n &headers, decoder_callbacks_->connection(), filter_config_));\n\n Payload payload;\n\n if (!createPeerAuthenticator(filter_context_.get())->run(&payload)) {\n rejectRequest(\"Peer authentication failed.\");\n return FilterHeadersStatus::StopIteration;\n }\n\n bool success =\n createOriginAuthenticator(filter_context_.get())->run(&payload);\n\n \/\/ After Istio authn, the JWT headers consumed by Istio authn should be\n \/\/ removed.\n \/\/ TODO: remove internal headers used to pass data between filters\n \/\/ https:\/\/github.com\/istio\/istio\/issues\/4689\n for (auto const iter : filter_config_.jwt_output_payload_locations()) {\n filter_context_->headers()->remove(LowerCaseString(iter.second));\n }\n\n if (!success) {\n rejectRequest(\"Origin authentication failed.\");\n return FilterHeadersStatus::StopIteration;\n }\n\n \/\/ Put authentication result to headers.\n if (filter_context_ != nullptr) {\n Utils::Authentication::SaveResultToHeader(\n filter_context_->authenticationResult(), filter_context_->headers());\n }\n state_ = State::COMPLETE;\n return FilterHeadersStatus::Continue;\n}\n\nFilterDataStatus AuthenticationFilter::decodeData(Buffer::Instance&, bool) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n ENVOY_LOG(debug,\n \"Called AuthenticationFilter : {} FilterDataStatus::Continue;\",\n __FUNCTION__);\n if (state_ == State::PROCESSING) {\n return FilterDataStatus::StopIterationAndWatermark;\n }\n return FilterDataStatus::Continue;\n}\n\nFilterTrailersStatus AuthenticationFilter::decodeTrailers(HeaderMap&) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n if (state_ == State::PROCESSING) {\n return FilterTrailersStatus::StopIteration;\n }\n return FilterTrailersStatus::Continue;\n}\n\nvoid AuthenticationFilter::setDecoderFilterCallbacks(\n StreamDecoderFilterCallbacks& callbacks) {\n ENVOY_LOG(debug, \"Called AuthenticationFilter : {}\", __func__);\n decoder_callbacks_ = &callbacks;\n}\n\nvoid AuthenticationFilter::rejectRequest(const std::string& message) {\n if (state_ != State::PROCESSING) {\n ENVOY_LOG(error, \"State {} is not PROCESSING.\", state_);\n return;\n }\n state_ = State::REJECTED;\n Utility::sendLocalReply(*decoder_callbacks_, false, Http::Code::Unauthorized,\n message);\n}\n\nstd::unique_ptr\nAuthenticationFilter::createPeerAuthenticator(\n Istio::AuthN::FilterContext* filter_context) {\n return std::make_unique(\n filter_context, filter_config_.policy());\n}\n\nstd::unique_ptr\nAuthenticationFilter::createOriginAuthenticator(\n Istio::AuthN::FilterContext* filter_context) {\n return std::make_unique(\n filter_context, filter_config_.policy());\n}\n\n} \/\/ namespace AuthN\n} \/\/ namespace Istio\n} \/\/ namespace Http\n} \/\/ namespace Envoy\n<|endoftext|>"} {"text":"\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#pragma once\n#include \n#include \n#include \n\nnamespace eosio { namespace chain {\n\n\/**\n\nasset includes amount and currency symbol\n\nasset::from_string takes a string of the form \"10.0000 CUR\" and constructs an asset \nwith amount = 10 and symbol(4,\"CUR\")\n\n*\/\n\nstruct asset\n{\n static constexpr int64_t max_amount = (1LL << 62) - 1;\n\n explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {\n EOS_ASSERT( is_amount_within_range(), asset_type_exception, \"magnitude of asset amount must be less than 2^62\" );\n EOS_ASSERT( sym.valid(), asset_type_exception, \"invalid symbol\" );\n }\n\n bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }\n bool is_valid()const { return is_amount_within_range() && sym.valid(); }\n\n double to_real()const { return static_cast(amount) \/ precision(); }\n\n uint8_t decimals()const;\n string symbol_name()const;\n int64_t precision()const;\n const symbol& get_symbol() const { return sym; }\n\n static asset from_string(const string& from);\n string to_string()const;\n\n asset& operator += (const asset& o)\n {\n FC_ASSERT(get_symbol() == o.get_symbol());\n amount += o.amount;\n return *this;\n }\n\n asset& operator -= (const asset& o)\n {\n FC_ASSERT(get_symbol() == o.get_symbol());\n amount -= o.amount;\n return *this;\n }\n asset operator -()const { return asset(-amount, get_symbol()); }\n\n friend bool operator == (const asset& a, const asset& b)\n {\n return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);\n }\n friend bool operator < (const asset& a, const asset& b)\n {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());\n }\n friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }\n friend bool operator != (const asset& a, const asset& b) { return !(a == b); }\n friend bool operator > (const asset& a, const asset& b) { return !(a <= b); }\n friend bool operator >= (const asset& a, const asset& b) { return !(a < b); }\n\n friend asset operator - (const asset& a, const asset& b) {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return asset(a.amount - b.amount, a.get_symbol());\n }\n\n friend asset operator + (const asset& a, const asset& b) {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return asset(a.amount + b.amount, a.get_symbol());\n }\n\n friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }\n\n friend struct fc::reflector;\n\n void reflector_verify()const {\n EOS_ASSERT( is_amount_within_range(), asset_type_exception, \"magnitude of asset amount must be less than 2^62\" );\n EOS_ASSERT( sym.valid(), asset_type_exception, \"invalid symbol\" );\n }\n\nprivate:\n share_type amount;\n symbol sym;\n\n};\n\nstruct extended_asset {\n extended_asset(){}\n extended_asset( asset a, name n ):quantity(a),contract(n){}\n asset quantity;\n name contract;\n};\n\nbool operator < (const asset& a, const asset& b);\nbool operator <= (const asset& a, const asset& b);\n\n}} \/\/ namespace eosio::chain\n\nnamespace fc {\ninline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }\ninline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {\n vo = eosio::chain::asset::from_string(var.get_string());\n}\n}\n\nFC_REFLECT(eosio::chain::asset, (amount)(sym))\nFC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )\nAdd get_amount()\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#pragma once\n#include \n#include \n#include \n\nnamespace eosio { namespace chain {\n\n\/**\n\nasset includes amount and currency symbol\n\nasset::from_string takes a string of the form \"10.0000 CUR\" and constructs an asset \nwith amount = 10 and symbol(4,\"CUR\")\n\n*\/\n\nstruct asset\n{\n static constexpr int64_t max_amount = (1LL << 62) - 1;\n\n explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {\n EOS_ASSERT( is_amount_within_range(), asset_type_exception, \"magnitude of asset amount must be less than 2^62\" );\n EOS_ASSERT( sym.valid(), asset_type_exception, \"invalid symbol\" );\n }\n\n bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }\n bool is_valid()const { return is_amount_within_range() && sym.valid(); }\n\n double to_real()const { return static_cast(amount) \/ precision(); }\n\n uint8_t decimals()const;\n string symbol_name()const;\n int64_t precision()const;\n const symbol& get_symbol() const { return sym; }\n share_type get_amount()const { return amount; }\n\n static asset from_string(const string& from);\n string to_string()const;\n\n asset& operator += (const asset& o)\n {\n FC_ASSERT(get_symbol() == o.get_symbol());\n amount += o.amount;\n return *this;\n }\n\n asset& operator -= (const asset& o)\n {\n FC_ASSERT(get_symbol() == o.get_symbol());\n amount -= o.amount;\n return *this;\n }\n asset operator -()const { return asset(-amount, get_symbol()); }\n\n friend bool operator == (const asset& a, const asset& b)\n {\n return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);\n }\n friend bool operator < (const asset& a, const asset& b)\n {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());\n }\n friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }\n friend bool operator != (const asset& a, const asset& b) { return !(a == b); }\n friend bool operator > (const asset& a, const asset& b) { return !(a <= b); }\n friend bool operator >= (const asset& a, const asset& b) { return !(a < b); }\n\n friend asset operator - (const asset& a, const asset& b) {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return asset(a.amount - b.amount, a.get_symbol());\n }\n\n friend asset operator + (const asset& a, const asset& b) {\n FC_ASSERT(a.get_symbol() == b.get_symbol());\n return asset(a.amount + b.amount, a.get_symbol());\n }\n\n friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }\n\n friend struct fc::reflector;\n\n void reflector_verify()const {\n EOS_ASSERT( is_amount_within_range(), asset_type_exception, \"magnitude of asset amount must be less than 2^62\" );\n EOS_ASSERT( sym.valid(), asset_type_exception, \"invalid symbol\" );\n }\n\nprivate:\n share_type amount;\n symbol sym;\n\n};\n\nstruct extended_asset {\n extended_asset(){}\n extended_asset( asset a, name n ):quantity(a),contract(n){}\n asset quantity;\n name contract;\n};\n\nbool operator < (const asset& a, const asset& b);\nbool operator <= (const asset& a, const asset& b);\n\n}} \/\/ namespace eosio::chain\n\nnamespace fc {\ninline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }\ninline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {\n vo = eosio::chain::asset::from_string(var.get_string());\n}\n}\n\nFC_REFLECT(eosio::chain::asset, (amount)(sym))\nFC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"navcoinunits.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"util.h\"\n\n#include \n\n#include \n#include \n\nNavCoinUnits::NavCoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList NavCoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(NAV);\n\/\/ unitlist.append(mNAV);\n\/\/ unitlist.append(uNAV);\n unitlist.append(BTC);\n unitlist.append(EUR);\n unitlist.append(USD);\n return unitlist;\n}\n\nbool NavCoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case NAV:\n\/\/ case mNAV:\n\/\/ case uNAV:\n case BTC:\n case EUR:\n case USD:\n return true;\n default:\n return false;\n }\n}\n\nQString NavCoinUnits::name(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NAV\");\n\/\/ case mNAV: return QString(\"mNAV\");\n\/\/ case uNAV: return QString::fromUtf8(\"μNAV\");\n case BTC: return QString::fromUtf8(\"BTC\");\n case EUR: return QString::fromUtf8(\"EUR\");\n case USD: return QString::fromUtf8(\"USD\");\n default: return QString(\"???\");\n }\n}\n\nQString NavCoinUnits::description(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NavCoins\");\n\/\/ case mNAV: return QString(\"Milli-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000)\");\n\/\/ case uNAV: return QString(\"Micro-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000\" THIN_SP_UTF8 \"000)\");\n case BTC: return QString(\"BTC\");\n case EUR: return QString(\"Euro\");\n case USD: return QString(\"US Dolar\");\n default: return QString(\"???\");\n }\n}\n\nqint64 NavCoinUnits::factor(int unit)\n{\n\n QSettings settings;\n\n switch(unit)\n {\n case NAV: return 100000000;\n\/\/ case mNAV: return 100000;\n\/\/ case uNAV: return 100;\n case BTC: return settings.value(\"btcFactor\", 0).toFloat();\n case EUR: return settings.value(\"eurFactor\", 0).toFloat();\n case USD: return settings.value(\"usdFactor\", 0).toFloat();\n default: return 100000000;\n }\n}\n\nint NavCoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case NAV: return 8;\n\/\/ case mNAV: return 5;\n\/\/ case uNAV: return 2;\n case BTC: return 8;\n case EUR: return 6;\n case USD: return 6;\n default: return 0;\n }\n}\n\nQString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 n = (qint64)nIn;\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n double quotient;\n qint64 remainder;\n\n double q;\n double r = modf((double)n_abs \/ (double)coin, &q);\n quotient = q;\n remainder = r * (double)pow(10,num_decimals);\n\n QString quotient_str = QString::number((qint64)quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Use SI-style thin space separators as these are locale independent and can't be\n \/\/ confused with the decimal marker.\n QChar thin_sp(THIN_SP_CP);\n int q_size = quotient_str.size();\n if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))\n for (int i = 3; i < q_size; i += 3)\n quotient_str.insert(q_size - i, thin_sp);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n\n return quotient_str + QString(\".\") + remainder_str;\n}\n\n\n\/\/ NOTE: Using formatWithUnit in an HTML context risks wrapping\n\/\/ quantities at the thousands separator. More subtly, it also results\n\/\/ in a standard space rather than a thin space, due to a bug in Qt's\n\/\/ XML whitespace canonicalisation\n\/\/\n\/\/ Please take care to use formatHtmlWithUnit instead, when\n\/\/ appropriate.\n\nQString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n return format(unit, amount, plussign, separators) + QString(\" \") + name(unit);\n}\n\nQString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n QString str(formatWithUnit(unit, amount, plussign, separators));\n str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));\n return QString(\"%1<\/span>\").arg(str);\n}\n\n\nbool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n\n \/\/ Ignore spaces and thin spaces when parsing\n QStringList parts = removeSpaces(value).split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n CAmount retvalue(str.toLongLong(&ok));\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nQString NavCoinUnits::getAmountColumnTitle(int unit)\n{\n QString amountTitle = QObject::tr(\"Amount\");\n if (NavCoinUnits::valid(unit))\n {\n amountTitle += \" (\"+NavCoinUnits::name(unit) + \")\";\n }\n return amountTitle;\n}\n\nint NavCoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant NavCoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n\nCAmount NavCoinUnits::maxMoney()\n{\n return MAX_MONEY;\n}\ngui: fixes amount precision\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"navcoinunits.h\"\n\n#include \"primitives\/transaction.h\"\n#include \"util.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nNavCoinUnits::NavCoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList NavCoinUnits::availableUnits()\n{\n QList unitlist;\n unitlist.append(NAV);\n\/\/ unitlist.append(mNAV);\n\/\/ unitlist.append(uNAV);\n unitlist.append(BTC);\n unitlist.append(EUR);\n unitlist.append(USD);\n return unitlist;\n}\n\nbool NavCoinUnits::valid(int unit)\n{\n switch(unit)\n {\n case NAV:\n\/\/ case mNAV:\n\/\/ case uNAV:\n case BTC:\n case EUR:\n case USD:\n return true;\n default:\n return false;\n }\n}\n\nQString NavCoinUnits::name(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NAV\");\n\/\/ case mNAV: return QString(\"mNAV\");\n\/\/ case uNAV: return QString::fromUtf8(\"μNAV\");\n case BTC: return QString::fromUtf8(\"BTC\");\n case EUR: return QString::fromUtf8(\"EUR\");\n case USD: return QString::fromUtf8(\"USD\");\n default: return QString(\"???\");\n }\n}\n\nQString NavCoinUnits::description(int unit)\n{\n switch(unit)\n {\n case NAV: return QString(\"NavCoins\");\n\/\/ case mNAV: return QString(\"Milli-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000)\");\n\/\/ case uNAV: return QString(\"Micro-NavCoins (1 \/ 1\" THIN_SP_UTF8 \"000\" THIN_SP_UTF8 \"000)\");\n case BTC: return QString(\"BTC\");\n case EUR: return QString(\"Euro\");\n case USD: return QString(\"US Dolar\");\n default: return QString(\"???\");\n }\n}\n\nqint64 NavCoinUnits::factor(int unit)\n{\n\n QSettings settings;\n\n switch(unit)\n {\n case NAV: return 100000000;\n\/\/ case mNAV: return 100000;\n\/\/ case uNAV: return 100;\n case BTC: return settings.value(\"btcFactor\", 0).toFloat();\n case EUR: return settings.value(\"eurFactor\", 0).toFloat();\n case USD: return settings.value(\"usdFactor\", 0).toFloat();\n default: return 100000000;\n }\n}\n\nint NavCoinUnits::decimals(int unit)\n{\n switch(unit)\n {\n case NAV: return 8;\n\/\/ case mNAV: return 5;\n\/\/ case uNAV: return 2;\n case BTC: return 8;\n case EUR: return 6;\n case USD: return 6;\n default: return 0;\n }\n}\n\nQString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)\n{\n \/\/ Note: not using straight sprintf here because we do NOT want\n \/\/ localized number formatting.\n if(!valid(unit))\n return QString(); \/\/ Refuse to format invalid unit\n qint64 n = (qint64)nIn;\n qint64 coin = factor(unit);\n int num_decimals = decimals(unit);\n qint64 n_abs = (n > 0 ? n : -n);\n double quotient;\n qint64 remainder;\n\n quotient = n_abs \/ coin;\n\n std::ostringstream out;\n out << std::setprecision(num_decimals) << std::fixed\n << std::showpoint << (double)n_abs \/ (double)coin;\n std::istringstream in(out.str());\n std::string wholePart;\n std::getline(in, wholePart, '.');\n in >> remainder;\n\n QString quotient_str = QString::number((qint64)quotient);\n QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');\n\n \/\/ Use SI-style thin space separators as these are locale independent and can't be\n \/\/ confused with the decimal marker.\n QChar thin_sp(THIN_SP_CP);\n int q_size = quotient_str.size();\n if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))\n for (int i = 3; i < q_size; i += 3)\n quotient_str.insert(q_size - i, thin_sp);\n\n if (n < 0)\n quotient_str.insert(0, '-');\n else if (fPlus && n > 0)\n quotient_str.insert(0, '+');\n\n return quotient_str + QString(\".\") + remainder_str;\n}\n\n\n\/\/ NOTE: Using formatWithUnit in an HTML context risks wrapping\n\/\/ quantities at the thousands separator. More subtly, it also results\n\/\/ in a standard space rather than a thin space, due to a bug in Qt's\n\/\/ XML whitespace canonicalisation\n\/\/\n\/\/ Please take care to use formatHtmlWithUnit instead, when\n\/\/ appropriate.\n\nQString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n return format(unit, amount, plussign, separators) + QString(\" \") + name(unit);\n}\n\nQString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)\n{\n QString str(formatWithUnit(unit, amount, plussign, separators));\n str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));\n return QString(\"%1<\/span>\").arg(str);\n}\n\n\nbool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)\n{\n if(!valid(unit) || value.isEmpty())\n return false; \/\/ Refuse to parse invalid unit or empty string\n int num_decimals = decimals(unit);\n\n \/\/ Ignore spaces and thin spaces when parsing\n QStringList parts = removeSpaces(value).split(\".\");\n\n if(parts.size() > 2)\n {\n return false; \/\/ More than one dot\n }\n QString whole = parts[0];\n QString decimals;\n\n if(parts.size() > 1)\n {\n decimals = parts[1];\n }\n if(decimals.size() > num_decimals)\n {\n return false; \/\/ Exceeds max precision\n }\n bool ok = false;\n QString str = whole + decimals.leftJustified(num_decimals, '0');\n\n if(str.size() > 18)\n {\n return false; \/\/ Longer numbers will exceed 63 bits\n }\n CAmount retvalue(str.toLongLong(&ok));\n if(val_out)\n {\n *val_out = retvalue;\n }\n return ok;\n}\n\nQString NavCoinUnits::getAmountColumnTitle(int unit)\n{\n QString amountTitle = QObject::tr(\"Amount\");\n if (NavCoinUnits::valid(unit))\n {\n amountTitle += \" (\"+NavCoinUnits::name(unit) + \")\";\n }\n return amountTitle;\n}\n\nint NavCoinUnits::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return unitlist.size();\n}\n\nQVariant NavCoinUnits::data(const QModelIndex &index, int role) const\n{\n int row = index.row();\n if(row >= 0 && row < unitlist.size())\n {\n Unit unit = unitlist.at(row);\n switch(role)\n {\n case Qt::EditRole:\n case Qt::DisplayRole:\n return QVariant(name(unit));\n case Qt::ToolTipRole:\n return QVariant(description(unit));\n case UnitRole:\n return QVariant(static_cast(unit));\n }\n }\n return QVariant();\n}\n\nCAmount NavCoinUnits::maxMoney()\n{\n return MAX_MONEY;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: layerdefaultremover.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ssmith $ $Date: 2002-11-11 13:18: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 EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_XML_LAYERDECORATOR_HXX\n#define CONFIGMGR_XML_LAYERDECORATOR_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif \/\/ _CPPUHELPER_IMPLBASE1_HXX_\n\n#ifndef INCLUDED_VECTOR\n#include \n#define INCLUDED_VECTOR\n#endif\n\n#include \n\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n \/\/ -----------------------------------------------------------------------------\n using rtl::OUString;\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace beans = ::com::sun::star::beans;\n namespace container = ::com::sun::star::container;\n namespace backenduno = ::drafts::com::sun::star::configuration::backend;\n\n \/\/ -----------------------------------------------------------------------------\n\n class LayerDefaultRemover : public cppu::WeakImplHelper1\n {\n public:\n typedef uno::Reference< backenduno::XLayerHandler > ResultHandler;\n explicit\n LayerDefaultRemover(ResultHandler const & _xResultHandler);\n virtual ~LayerDefaultRemover();\n\n \/\/ XLayerHandler\n public:\n virtual void SAL_CALL\n startLayer( )\n throw (backenduno::MalformedDataException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endLayer( )\n throw (backenduno::MalformedDataException, lang::IllegalAccessException, uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideNode( const OUString& aName, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, container::NoSuchElementException, beans::IllegalTypeException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endNode( )\n throw (backenduno::MalformedDataException, uno::RuntimeException);\n\n virtual void SAL_CALL\n dropNode( const OUString& aName )\n throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (backenduno::MalformedDataException, beans::UnknownPropertyException, beans::IllegalTypeException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (backenduno::MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (backenduno::MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endProperty( )\n throw (backenduno::MalformedDataException, uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValue( const uno::Any& aValue )\n throw (backenduno::MalformedDataException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (backenduno::MalformedDataException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);\n\n private:\n void playBackNodeStack( bool bPlayProperty=false);\n void raiseMalformedDataException(sal_Char const * pMsg);\n inline bool hasPendingProperty();\n inline void clearPendingProperty();\n private:\n ResultHandler m_xResultHandler;\n typedef std::vector NodeStack;\n NodeStack m_aNodeStack;\n struct PropertyStruct\n {\n OUString Name;\n uno::Type Type;\n }m_aPropName;\n };\n \/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n \/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n#endif INTEGRATION: CWS configapi01 (1.2.26); FILE MERGED 2003\/04\/15 10:25:28 jb 1.2.26.2: #i11893# backend\\updatedata.cxx 2003\/04\/10 15:47:06 jb 1.2.26.1: #1077715# Move configuration backend API out of drafts; adjust to API changes\/*************************************************************************\n *\n * $RCSfile: layerdefaultremover.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2003-04-17 13:15:56 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_XML_LAYERDECORATOR_HXX\n#define CONFIGMGR_XML_LAYERDECORATOR_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif \/\/ _CPPUHELPER_IMPLBASE1_HXX_\n\n#ifndef INCLUDED_VECTOR\n#include \n#define INCLUDED_VECTOR\n#endif\n\n#include \n\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n \/\/ -----------------------------------------------------------------------------\n using rtl::OUString;\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace backenduno = ::com::sun::star::configuration::backend;\n\n using backenduno::MalformedDataException;\n \/\/ -----------------------------------------------------------------------------\n\n class LayerDefaultRemover : public cppu::WeakImplHelper1\n {\n public:\n typedef uno::Reference< backenduno::XLayerHandler > ResultHandler;\n explicit\n LayerDefaultRemover(ResultHandler const & _xResultHandler);\n virtual ~LayerDefaultRemover();\n\n \/\/ XLayerHandler\n public:\n virtual void SAL_CALL\n startLayer( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endLayer( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endNode( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n dropNode( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n endProperty( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValue( const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);\n\n private:\n void playBackNodeStack( bool bPlayProperty=false);\n void raiseMalformedDataException(sal_Char const * pMsg);\n inline bool hasPendingProperty();\n inline void clearPendingProperty();\n private:\n ResultHandler m_xResultHandler;\n typedef std::vector NodeStack;\n NodeStack m_aNodeStack;\n struct PropertyStruct\n {\n OUString Name;\n uno::Type Type;\n }m_aPropName;\n };\n \/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n \/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n#endif <|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"optionsmodel.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"txdb.h\" \/\/ for -dbcache defaults\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#endif\n\n#include \n#include \n#include \n\nOptionsModel::OptionsModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n Init();\n}\n\nvoid OptionsModel::addOverriddenOption(const std::string &option)\n{\n strOverriddenByCommandLine += QString::fromStdString(option) + \"=\" + QString::fromStdString(mapArgs[option]) + \" \";\n}\n\n\/\/ Writes all missing QSettings with their default values\nvoid OptionsModel::Init()\n{\n QSettings settings;\n\n \/\/ Ensure restart flag is unset on client startup\n setRestartRequired(false);\n\n \/\/ These are Qt-only settings:\n\n \/\/ Window\n if (!settings.contains(\"fMinimizeToTray\"))\n settings.setValue(\"fMinimizeToTray\", false);\n fMinimizeToTray = settings.value(\"fMinimizeToTray\").toBool();\n\n if (!settings.contains(\"fMinimizeOnClose\"))\n settings.setValue(\"fMinimizeOnClose\", false);\n fMinimizeOnClose = settings.value(\"fMinimizeOnClose\").toBool();\n\n \/\/ Display\n if (!settings.contains(\"nDisplayUnit\"))\n settings.setValue(\"nDisplayUnit\", BitcoinUnits::BTC);\n nDisplayUnit = settings.value(\"nDisplayUnit\").toInt();\n\n if (!settings.contains(\"bDisplayAddresses\"))\n settings.setValue(\"bDisplayAddresses\", false);\n bDisplayAddresses = settings.value(\"bDisplayAddresses\", false).toBool();\n\n if (!settings.contains(\"strThirdPartyTxUrls\"))\n settings.setValue(\"strThirdPartyTxUrls\", \"\");\n strThirdPartyTxUrls = settings.value(\"strThirdPartyTxUrls\", \"\").toString();\n\n if (!settings.contains(\"fCoinControlFeatures\"))\n settings.setValue(\"fCoinControlFeatures\", false);\n fCoinControlFeatures = settings.value(\"fCoinControlFeatures\", false).toBool();\n\n \/\/ These are shared with the core or have a command-line parameter\n \/\/ and we want command-line parameters to overwrite the GUI settings.\n \/\/\n \/\/ If setting doesn't exist create it with defaults.\n \/\/\n \/\/ If SoftSetArg() or SoftSetBoolArg() return false we were overridden\n \/\/ by command-line and show this in the UI.\n\n \/\/ Main\n if (!settings.contains(\"nDatabaseCache\"))\n settings.setValue(\"nDatabaseCache\", (qint64)nDefaultDbCache);\n if (!SoftSetArg(\"-dbcache\", settings.value(\"nDatabaseCache\").toString().toStdString()))\n addOverriddenOption(\"-dbcache\");\n\n if (!settings.contains(\"nThreadsScriptVerif\"))\n settings.setValue(\"nThreadsScriptVerif\", DEFAULT_SCRIPTCHECK_THREADS);\n if (!SoftSetArg(\"-par\", settings.value(\"nThreadsScriptVerif\").toString().toStdString()))\n addOverriddenOption(\"-par\");\n\n \/\/ Wallet\n#ifdef ENABLE_WALLET\n if (!settings.contains(\"nTransactionFee\"))\n settings.setValue(\"nTransactionFee\", DEFAULT_TRANSACTION_FEE);\n nTransactionFee = settings.value(\"nTransactionFee\").toLongLong(); \/\/ if -paytxfee is set, this will be overridden later in init.cpp\n if (mapArgs.count(\"-paytxfee\"))\n addOverriddenOption(\"-paytxfee\");\n\n if (!settings.contains(\"bSpendZeroConfChange\"))\n settings.setValue(\"bSpendZeroConfChange\", true);\n if (!SoftSetBoolArg(\"-spendzeroconfchange\", settings.value(\"bSpendZeroConfChange\").toBool()))\n addOverriddenOption(\"-spendzeroconfchange\");\n#endif\n\n \/\/ Network\n if (!settings.contains(\"fUseUPnP\"))\n#ifdef USE_UPNP\n settings.setValue(\"fUseUPnP\", true);\n#else\n settings.setValue(\"fUseUPnP\", false);\n#endif\n if (!SoftSetBoolArg(\"-upnp\", settings.value(\"fUseUPnP\").toBool()))\n addOverriddenOption(\"-upnp\");\n\n if (!settings.contains(\"fUseProxy\"))\n settings.setValue(\"fUseProxy\", false);\n if (!settings.contains(\"addrProxy\"))\n settings.setValue(\"addrProxy\", \"127.0.0.1:9050\");\n \/\/ Only try to set -proxy, if user has enabled fUseProxy\n if (settings.value(\"fUseProxy\").toBool() && !SoftSetArg(\"-proxy\", settings.value(\"addrProxy\").toString().toStdString()))\n addOverriddenOption(\"-proxy\");\n if (!settings.contains(\"nSocksVersion\"))\n settings.setValue(\"nSocksVersion\", 5);\n \/\/ Only try to set -socks, if user has enabled fUseProxy\n if (settings.value(\"fUseProxy\").toBool() && !SoftSetArg(\"-socks\", settings.value(\"nSocksVersion\").toString().toStdString()))\n addOverriddenOption(\"-socks\");\n\n \/\/ Display\n if (!settings.contains(\"language\"))\n settings.setValue(\"language\", \"\");\n if (!SoftSetArg(\"-lang\", settings.value(\"language\").toString().toStdString()))\n addOverriddenOption(\"-lang\");\n\n language = settings.value(\"language\").toString();\n}\n\nvoid OptionsModel::Reset()\n{\n QSettings settings;\n\n \/\/ Remove all entries from our QSettings object\n settings.clear();\n\n \/\/ default setting for OptionsModel::StartAtStartup - disabled\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(false);\n}\n\nint OptionsModel::rowCount(const QModelIndex & parent) const\n{\n return OptionIDRowCount;\n}\n\n\/\/ read QSettings values and return them\nQVariant OptionsModel::data(const QModelIndex & index, int role) const\n{\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n return GUIUtil::GetStartOnSystemStartup();\n case MinimizeToTray:\n return fMinimizeToTray;\n case MapPortUPnP:\n#ifdef USE_UPNP\n return settings.value(\"fUseUPnP\");\n#else\n return false;\n#endif\n case MinimizeOnClose:\n return fMinimizeOnClose;\n\n \/\/ default proxy\n case ProxyUse:\n return settings.value(\"fUseProxy\", false);\n case ProxyIP: {\n \/\/ contains IP at index 0 and port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n return strlIpPort.at(0);\n }\n case ProxyPort: {\n \/\/ contains IP at index 0 and port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n return strlIpPort.at(1);\n }\n case ProxySocksVersion:\n return settings.value(\"nSocksVersion\", 5);\n\n#ifdef ENABLE_WALLET\n case Fee:\n \/\/ Attention: Init() is called before nTransactionFee is set in AppInit2()!\n \/\/ To ensure we can change the fee on-the-fly update our QSetting when\n \/\/ opening OptionsDialog, which queries Fee via the mapper.\n if (nTransactionFee != settings.value(\"nTransactionFee\").toLongLong())\n settings.setValue(\"nTransactionFee\", (qint64)nTransactionFee);\n \/\/ Todo: Consider to revert back to use just nTransactionFee here, if we don't want\n \/\/ -paytxfee to update our QSettings!\n return settings.value(\"nTransactionFee\");\n case SpendZeroConfChange:\n return settings.value(\"bSpendZeroConfChange\");\n#endif\n case DisplayUnit:\n return nDisplayUnit;\n case DisplayAddresses:\n return bDisplayAddresses;\n case ThirdPartyTxUrls:\n return strThirdPartyTxUrls;\n case Language:\n return settings.value(\"language\");\n case CoinControlFeatures:\n return fCoinControlFeatures;\n case DatabaseCache:\n return settings.value(\"nDatabaseCache\");\n case ThreadsScriptVerif:\n return settings.value(\"nThreadsScriptVerif\");\n default:\n return QVariant();\n }\n }\n return QVariant();\n}\n\n\/\/ write QSettings values\nbool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)\n{\n bool successful = true; \/* set to false on parse error *\/\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n successful = GUIUtil::SetStartOnSystemStartup(value.toBool());\n break;\n case MinimizeToTray:\n fMinimizeToTray = value.toBool();\n settings.setValue(\"fMinimizeToTray\", fMinimizeToTray);\n break;\n case MapPortUPnP: \/\/ core option - can be changed on-the-fly\n settings.setValue(\"fUseUPnP\", value.toBool());\n MapPort(value.toBool());\n break;\n case MinimizeOnClose:\n fMinimizeOnClose = value.toBool();\n settings.setValue(\"fMinimizeOnClose\", fMinimizeOnClose);\n break;\n\n \/\/ default proxy\n case ProxyUse:\n if (settings.value(\"fUseProxy\") != value) {\n settings.setValue(\"fUseProxy\", value.toBool());\n setRestartRequired(true);\n }\n break;\n case ProxyIP: {\n \/\/ contains current IP at index 0 and current port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n \/\/ if that key doesn't exist or has a changed IP\n if (!settings.contains(\"addrProxy\") || strlIpPort.at(0) != value.toString()) {\n \/\/ construct new value from new IP and current port\n QString strNewValue = value.toString() + \":\" + strlIpPort.at(1);\n settings.setValue(\"addrProxy\", strNewValue);\n setRestartRequired(true);\n }\n }\n break;\n case ProxyPort: {\n \/\/ contains current IP at index 0 and current port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n \/\/ if that key doesn't exist or has a changed port\n if (!settings.contains(\"addrProxy\") || strlIpPort.at(1) != value.toString()) {\n \/\/ construct new value from current IP and new port\n QString strNewValue = strlIpPort.at(0) + \":\" + value.toString();\n settings.setValue(\"addrProxy\", strNewValue);\n setRestartRequired(true);\n }\n }\n break;\n case ProxySocksVersion: {\n if (settings.value(\"nSocksVersion\") != value) {\n settings.setValue(\"nSocksVersion\", value.toInt());\n setRestartRequired(true);\n }\n }\n break;\n#ifdef ENABLE_WALLET\n case Fee: \/\/ core option - can be changed on-the-fly\n \/\/ Todo: Add is valid check and warn via message, if not\n nTransactionFee = value.toLongLong();\n settings.setValue(\"nTransactionFee\", (qint64)nTransactionFee);\n emit transactionFeeChanged(nTransactionFee);\n break;\n case SpendZeroConfChange:\n if (settings.value(\"bSpendZeroConfChange\") != value) {\n settings.setValue(\"bSpendZeroConfChange\", value);\n setRestartRequired(true);\n }\n break;\n#endif\n case DisplayUnit:\n nDisplayUnit = value.toInt();\n settings.setValue(\"nDisplayUnit\", nDisplayUnit);\n emit displayUnitChanged(nDisplayUnit);\n break;\n case DisplayAddresses:\n bDisplayAddresses = value.toBool();\n settings.setValue(\"bDisplayAddresses\", bDisplayAddresses);\n break;\n case ThirdPartyTxUrls:\n if (strThirdPartyTxUrls != value.toString()) {\n strThirdPartyTxUrls = value.toString();\n settings.setValue(\"strThirdPartyTxUrls\", strThirdPartyTxUrls);\n setRestartRequired(true);\n }\n break;\n case Language:\n if (settings.value(\"language\") != value) {\n settings.setValue(\"language\", value);\n setRestartRequired(true);\n }\n break;\n case CoinControlFeatures:\n fCoinControlFeatures = value.toBool();\n settings.setValue(\"fCoinControlFeatures\", fCoinControlFeatures);\n emit coinControlFeaturesChanged(fCoinControlFeatures);\n break;\n case DatabaseCache:\n if (settings.value(\"nDatabaseCache\") != value) {\n settings.setValue(\"nDatabaseCache\", value);\n setRestartRequired(true);\n }\n break;\n case ThreadsScriptVerif:\n if (settings.value(\"nThreadsScriptVerif\") != value) {\n settings.setValue(\"nThreadsScriptVerif\", value);\n setRestartRequired(true);\n }\n break;\n default:\n break;\n }\n }\n emit dataChanged(index, index);\n\n return successful;\n}\n\nbool OptionsModel::getProxySettings(QNetworkProxy& proxy) const\n{\n \/\/ Directly query current base proxy, because\n \/\/ GUI settings can be overridden with -proxy.\n proxyType curProxy;\n if (GetProxy(NET_IPV4, curProxy)) {\n if (curProxy.second == 5) {\n proxy.setType(QNetworkProxy::Socks5Proxy);\n proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));\n proxy.setPort(curProxy.first.GetPort());\n\n return true;\n }\n else\n return false;\n }\n else\n proxy.setType(QNetworkProxy::NoProxy);\n\n return true;\n}\n\nvoid OptionsModel::setRestartRequired(bool fRequired)\n{\n QSettings settings;\n return settings.setValue(\"fRestartRequired\", fRequired);\n}\n\nbool OptionsModel::isRestartRequired()\n{\n QSettings settings;\n return settings.value(\"fRestartRequired\", false).toBool();\n}\nqt: fix compile issue in Qt GUI\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"bitcoin-config.h\"\n#endif\n\n#include \"optionsmodel.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiutil.h\"\n\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"txdb.h\" \/\/ for -dbcache defaults\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#endif\n\n#include \n#include \n#include \n\nOptionsModel::OptionsModel(QObject *parent) :\n QAbstractListModel(parent)\n{\n Init();\n}\n\nvoid OptionsModel::addOverriddenOption(const std::string &option)\n{\n strOverriddenByCommandLine += QString::fromStdString(option) + \"=\" + QString::fromStdString(mapArgs[option]) + \" \";\n}\n\n\/\/ Writes all missing QSettings with their default values\nvoid OptionsModel::Init()\n{\n QSettings settings;\n\n \/\/ Ensure restart flag is unset on client startup\n setRestartRequired(false);\n\n \/\/ These are Qt-only settings:\n\n \/\/ Window\n if (!settings.contains(\"fMinimizeToTray\"))\n settings.setValue(\"fMinimizeToTray\", false);\n fMinimizeToTray = settings.value(\"fMinimizeToTray\").toBool();\n\n if (!settings.contains(\"fMinimizeOnClose\"))\n settings.setValue(\"fMinimizeOnClose\", false);\n fMinimizeOnClose = settings.value(\"fMinimizeOnClose\").toBool();\n\n \/\/ Display\n if (!settings.contains(\"nDisplayUnit\"))\n settings.setValue(\"nDisplayUnit\", BitcoinUnits::BTC);\n nDisplayUnit = settings.value(\"nDisplayUnit\").toInt();\n\n if (!settings.contains(\"bDisplayAddresses\"))\n settings.setValue(\"bDisplayAddresses\", false);\n bDisplayAddresses = settings.value(\"bDisplayAddresses\", false).toBool();\n\n if (!settings.contains(\"strThirdPartyTxUrls\"))\n settings.setValue(\"strThirdPartyTxUrls\", \"\");\n strThirdPartyTxUrls = settings.value(\"strThirdPartyTxUrls\", \"\").toString();\n\n if (!settings.contains(\"fCoinControlFeatures\"))\n settings.setValue(\"fCoinControlFeatures\", false);\n fCoinControlFeatures = settings.value(\"fCoinControlFeatures\", false).toBool();\n\n \/\/ These are shared with the core or have a command-line parameter\n \/\/ and we want command-line parameters to overwrite the GUI settings.\n \/\/\n \/\/ If setting doesn't exist create it with defaults.\n \/\/\n \/\/ If SoftSetArg() or SoftSetBoolArg() return false we were overridden\n \/\/ by command-line and show this in the UI.\n\n \/\/ Main\n if (!settings.contains(\"nDatabaseCache\"))\n settings.setValue(\"nDatabaseCache\", (qint64)nDefaultDbCache);\n if (!SoftSetArg(\"-dbcache\", settings.value(\"nDatabaseCache\").toString().toStdString()))\n addOverriddenOption(\"-dbcache\");\n\n if (!settings.contains(\"nThreadsScriptVerif\"))\n settings.setValue(\"nThreadsScriptVerif\", DEFAULT_SCRIPTCHECK_THREADS);\n if (!SoftSetArg(\"-par\", settings.value(\"nThreadsScriptVerif\").toString().toStdString()))\n addOverriddenOption(\"-par\");\n\n \/\/ Wallet\n#ifdef ENABLE_WALLET\n if (!settings.contains(\"nTransactionFee\"))\n settings.setValue(\"nTransactionFee\", (qint64)DEFAULT_TRANSACTION_FEE);\n nTransactionFee = settings.value(\"nTransactionFee\").toLongLong(); \/\/ if -paytxfee is set, this will be overridden later in init.cpp\n if (mapArgs.count(\"-paytxfee\"))\n addOverriddenOption(\"-paytxfee\");\n\n if (!settings.contains(\"bSpendZeroConfChange\"))\n settings.setValue(\"bSpendZeroConfChange\", true);\n if (!SoftSetBoolArg(\"-spendzeroconfchange\", settings.value(\"bSpendZeroConfChange\").toBool()))\n addOverriddenOption(\"-spendzeroconfchange\");\n#endif\n\n \/\/ Network\n if (!settings.contains(\"fUseUPnP\"))\n#ifdef USE_UPNP\n settings.setValue(\"fUseUPnP\", true);\n#else\n settings.setValue(\"fUseUPnP\", false);\n#endif\n if (!SoftSetBoolArg(\"-upnp\", settings.value(\"fUseUPnP\").toBool()))\n addOverriddenOption(\"-upnp\");\n\n if (!settings.contains(\"fUseProxy\"))\n settings.setValue(\"fUseProxy\", false);\n if (!settings.contains(\"addrProxy\"))\n settings.setValue(\"addrProxy\", \"127.0.0.1:9050\");\n \/\/ Only try to set -proxy, if user has enabled fUseProxy\n if (settings.value(\"fUseProxy\").toBool() && !SoftSetArg(\"-proxy\", settings.value(\"addrProxy\").toString().toStdString()))\n addOverriddenOption(\"-proxy\");\n if (!settings.contains(\"nSocksVersion\"))\n settings.setValue(\"nSocksVersion\", 5);\n \/\/ Only try to set -socks, if user has enabled fUseProxy\n if (settings.value(\"fUseProxy\").toBool() && !SoftSetArg(\"-socks\", settings.value(\"nSocksVersion\").toString().toStdString()))\n addOverriddenOption(\"-socks\");\n\n \/\/ Display\n if (!settings.contains(\"language\"))\n settings.setValue(\"language\", \"\");\n if (!SoftSetArg(\"-lang\", settings.value(\"language\").toString().toStdString()))\n addOverriddenOption(\"-lang\");\n\n language = settings.value(\"language\").toString();\n}\n\nvoid OptionsModel::Reset()\n{\n QSettings settings;\n\n \/\/ Remove all entries from our QSettings object\n settings.clear();\n\n \/\/ default setting for OptionsModel::StartAtStartup - disabled\n if (GUIUtil::GetStartOnSystemStartup())\n GUIUtil::SetStartOnSystemStartup(false);\n}\n\nint OptionsModel::rowCount(const QModelIndex & parent) const\n{\n return OptionIDRowCount;\n}\n\n\/\/ read QSettings values and return them\nQVariant OptionsModel::data(const QModelIndex & index, int role) const\n{\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n return GUIUtil::GetStartOnSystemStartup();\n case MinimizeToTray:\n return fMinimizeToTray;\n case MapPortUPnP:\n#ifdef USE_UPNP\n return settings.value(\"fUseUPnP\");\n#else\n return false;\n#endif\n case MinimizeOnClose:\n return fMinimizeOnClose;\n\n \/\/ default proxy\n case ProxyUse:\n return settings.value(\"fUseProxy\", false);\n case ProxyIP: {\n \/\/ contains IP at index 0 and port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n return strlIpPort.at(0);\n }\n case ProxyPort: {\n \/\/ contains IP at index 0 and port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n return strlIpPort.at(1);\n }\n case ProxySocksVersion:\n return settings.value(\"nSocksVersion\", 5);\n\n#ifdef ENABLE_WALLET\n case Fee:\n \/\/ Attention: Init() is called before nTransactionFee is set in AppInit2()!\n \/\/ To ensure we can change the fee on-the-fly update our QSetting when\n \/\/ opening OptionsDialog, which queries Fee via the mapper.\n if (nTransactionFee != settings.value(\"nTransactionFee\").toLongLong())\n settings.setValue(\"nTransactionFee\", (qint64)nTransactionFee);\n \/\/ Todo: Consider to revert back to use just nTransactionFee here, if we don't want\n \/\/ -paytxfee to update our QSettings!\n return settings.value(\"nTransactionFee\");\n case SpendZeroConfChange:\n return settings.value(\"bSpendZeroConfChange\");\n#endif\n case DisplayUnit:\n return nDisplayUnit;\n case DisplayAddresses:\n return bDisplayAddresses;\n case ThirdPartyTxUrls:\n return strThirdPartyTxUrls;\n case Language:\n return settings.value(\"language\");\n case CoinControlFeatures:\n return fCoinControlFeatures;\n case DatabaseCache:\n return settings.value(\"nDatabaseCache\");\n case ThreadsScriptVerif:\n return settings.value(\"nThreadsScriptVerif\");\n default:\n return QVariant();\n }\n }\n return QVariant();\n}\n\n\/\/ write QSettings values\nbool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)\n{\n bool successful = true; \/* set to false on parse error *\/\n if(role == Qt::EditRole)\n {\n QSettings settings;\n switch(index.row())\n {\n case StartAtStartup:\n successful = GUIUtil::SetStartOnSystemStartup(value.toBool());\n break;\n case MinimizeToTray:\n fMinimizeToTray = value.toBool();\n settings.setValue(\"fMinimizeToTray\", fMinimizeToTray);\n break;\n case MapPortUPnP: \/\/ core option - can be changed on-the-fly\n settings.setValue(\"fUseUPnP\", value.toBool());\n MapPort(value.toBool());\n break;\n case MinimizeOnClose:\n fMinimizeOnClose = value.toBool();\n settings.setValue(\"fMinimizeOnClose\", fMinimizeOnClose);\n break;\n\n \/\/ default proxy\n case ProxyUse:\n if (settings.value(\"fUseProxy\") != value) {\n settings.setValue(\"fUseProxy\", value.toBool());\n setRestartRequired(true);\n }\n break;\n case ProxyIP: {\n \/\/ contains current IP at index 0 and current port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n \/\/ if that key doesn't exist or has a changed IP\n if (!settings.contains(\"addrProxy\") || strlIpPort.at(0) != value.toString()) {\n \/\/ construct new value from new IP and current port\n QString strNewValue = value.toString() + \":\" + strlIpPort.at(1);\n settings.setValue(\"addrProxy\", strNewValue);\n setRestartRequired(true);\n }\n }\n break;\n case ProxyPort: {\n \/\/ contains current IP at index 0 and current port at index 1\n QStringList strlIpPort = settings.value(\"addrProxy\").toString().split(\":\", QString::SkipEmptyParts);\n \/\/ if that key doesn't exist or has a changed port\n if (!settings.contains(\"addrProxy\") || strlIpPort.at(1) != value.toString()) {\n \/\/ construct new value from current IP and new port\n QString strNewValue = strlIpPort.at(0) + \":\" + value.toString();\n settings.setValue(\"addrProxy\", strNewValue);\n setRestartRequired(true);\n }\n }\n break;\n case ProxySocksVersion: {\n if (settings.value(\"nSocksVersion\") != value) {\n settings.setValue(\"nSocksVersion\", value.toInt());\n setRestartRequired(true);\n }\n }\n break;\n#ifdef ENABLE_WALLET\n case Fee: \/\/ core option - can be changed on-the-fly\n \/\/ Todo: Add is valid check and warn via message, if not\n nTransactionFee = value.toLongLong();\n settings.setValue(\"nTransactionFee\", (qint64)nTransactionFee);\n emit transactionFeeChanged(nTransactionFee);\n break;\n case SpendZeroConfChange:\n if (settings.value(\"bSpendZeroConfChange\") != value) {\n settings.setValue(\"bSpendZeroConfChange\", value);\n setRestartRequired(true);\n }\n break;\n#endif\n case DisplayUnit:\n nDisplayUnit = value.toInt();\n settings.setValue(\"nDisplayUnit\", nDisplayUnit);\n emit displayUnitChanged(nDisplayUnit);\n break;\n case DisplayAddresses:\n bDisplayAddresses = value.toBool();\n settings.setValue(\"bDisplayAddresses\", bDisplayAddresses);\n break;\n case ThirdPartyTxUrls:\n if (strThirdPartyTxUrls != value.toString()) {\n strThirdPartyTxUrls = value.toString();\n settings.setValue(\"strThirdPartyTxUrls\", strThirdPartyTxUrls);\n setRestartRequired(true);\n }\n break;\n case Language:\n if (settings.value(\"language\") != value) {\n settings.setValue(\"language\", value);\n setRestartRequired(true);\n }\n break;\n case CoinControlFeatures:\n fCoinControlFeatures = value.toBool();\n settings.setValue(\"fCoinControlFeatures\", fCoinControlFeatures);\n emit coinControlFeaturesChanged(fCoinControlFeatures);\n break;\n case DatabaseCache:\n if (settings.value(\"nDatabaseCache\") != value) {\n settings.setValue(\"nDatabaseCache\", value);\n setRestartRequired(true);\n }\n break;\n case ThreadsScriptVerif:\n if (settings.value(\"nThreadsScriptVerif\") != value) {\n settings.setValue(\"nThreadsScriptVerif\", value);\n setRestartRequired(true);\n }\n break;\n default:\n break;\n }\n }\n emit dataChanged(index, index);\n\n return successful;\n}\n\nbool OptionsModel::getProxySettings(QNetworkProxy& proxy) const\n{\n \/\/ Directly query current base proxy, because\n \/\/ GUI settings can be overridden with -proxy.\n proxyType curProxy;\n if (GetProxy(NET_IPV4, curProxy)) {\n if (curProxy.second == 5) {\n proxy.setType(QNetworkProxy::Socks5Proxy);\n proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));\n proxy.setPort(curProxy.first.GetPort());\n\n return true;\n }\n else\n return false;\n }\n else\n proxy.setType(QNetworkProxy::NoProxy);\n\n return true;\n}\n\nvoid OptionsModel::setRestartRequired(bool fRequired)\n{\n QSettings settings;\n return settings.setValue(\"fRestartRequired\", fRequired);\n}\n\nbool OptionsModel::isRestartRequired()\n{\n QSettings settings;\n return settings.value(\"fRestartRequired\", false).toBool();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \"LibUtilities\/Foundations\/Foundations.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Nektar;\nusing namespace Nektar::LibUtilities;\n\n\n\/\/ Quintic polynomial\nlong double polyFunc(long double x) {\n return (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0;\n}\n\n\/\/ Derivative of the Quintic polynomial\nlong double derivativePolyFunc(long double x) {\n return ((15.0*x*x - 15.0)*x + 2.0)*x - 2.0;\n}\n\n\/\/ A Fourier function that integrates to 0 with the Trapezoidal rule\nlong double fourierFunc(long double x, int N) {\n long double z = M_PI*(x + 1.0);\n return (cos(N\/2.0*z) + sin((N\/2.0 - 2.0)*z))\/M_PI;\n}\n\n\/\/ Derivative of the Fourier function above\nlong double derivativeFourierFunc(long double x, int N) {\n long double z = M_PI*(x + 1.0);\n long double a = (N-4.0)\/2.0;\n long double b = N\/2.0;\n return M_PI*M_PI*(a*cos(a*z) - b*sin(b*z));\n}\n\nlong double function(long double x, int N, PointsType type) {\n long double y = 0;\n if( type == eFourierEvenlySpaced) {\n y = fourierFunc(x,N);\n } else {\n y = polyFunc(x);\n }\n return y;\n}\n\nlong double derivativeFunction(long double x, int N, PointsType type){\n long double yDerivative = 0;\n if(type == eFourierEvenlySpaced){\n yDerivative = derivativeFourierFunc(x, N);\n } else {\n yDerivative = derivativePolyFunc(x);\n }\n return yDerivative;\n}\n\nlong double integrationFunction(int nPts, PointsType type){\n long double integral = 0;\n switch(type){\n case eFourierEvenlySpaced:\n integral = 0;\n break;\n default:\n integral = (long double)20.0\/3.0; \n }\n return integral;\n}\n\nlong double integrandWeightFunction(long double x, PointsType type){\n long double weight = 1;\n\n switch(type) {\n case eGaussGaussChebyshev:\n case eGaussRadauMChebyshev:\n case eGaussRadauPChebyshev:\n case eGaussLobattoChebyshev: \n weight = 1.0 \/ sqrt(1.0 - x*x);\n break;\n\n case eGaussRadauMAlpha0Beta1:\n \/\/ weight = 1.0 + x; \/\/ ?\n break;\n\n case eGaussRadauMAlpha0Beta2: \n \/\/ weight = (1.0 + x)*(1.0 + x); \/\/ ?\n break;\n \n\n default:\n weight = 1.0;\n }\n return weight;\n}\n\/\/ This routine projects a polynomial or trigonmetric functions which\n\/\/ has energy in all modes of the expansions and report an error.\n\nint main(int argc, char *argv[]) {\n\n \/\/ Argument check: Display a help message if the count is wrong\n if(argc != 3) {\n cerr << \"Usage: FoundationDemo Points1D-Type nPts\" << endl;\n\n cerr << \"Where type is an integer value which dictates the basis as:\\n\";\n for(int i=0; i > points = PointsManager()[key];\n\n \/\/ Get the abscissas and their matching quadrature weights\n SharedArray z, w;\n points->GetZW(z,w);\n\n \/\/ Evaluate the example function at the z[i] points in the interval [-1,1].\n \/\/ This generates the data samples, which we store in the y vector and use later\n \/\/ during interpolation\/integration\/differentiation\n SharedArray y(nPts);\n for(int i = 0; i < nPts; ++i) {\n y[i] = function( z[i], nPts, pointsType );\n }\n \n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Interpolation \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Generate a list of interpolating nodes\n int nNodes = 2*nPts; \/\/ Number of interpolating nodes\n const ptr > nodes = PointsManager()[PointsKey(nNodes, pointsType)];\n SharedArray zNode = nodes->GetZ();\n \n \/\/ Get the interpolation matrix I\n \/\/ Note that I is 2N rows by N columns\n const Points::MatrixSharedPtrType Iptr = points->GetI(nNodes, zNode);\n const NekMatrix & I = *Iptr;\n \n \n \n \/\/ Interpolate the data values in the y vector using the interpolation matrix I\n SharedArray u(I.GetRows());\n for(int i = 0; i < I.GetRows(); ++i) {\n u[i] = 0;\n for(int j = 0; j < I.GetColumns(); ++j) {\n u[i] += I(i,j) * y[j];\n }\n }\n\n \/\/ Display the original samples\n cout << setprecision(3);\n cout << \"\\nOriginal data: \\nx = \";\n for(int i = 0; i < nPts; ++i) {\n cout << setw(6) << z[i] << \" \";\n }\n cout << \"\\ny = \";\n for(int i = 0; i < nPts; ++i) {\n cout << setw(6) << y[i] << \" \";\n }\n\n \/\/ Display the interpolated data\n cout << \"\\n\\n\\n **** Interpolation ****\";\n cout << \"\\n\\nResults of interpolation with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\ninterp = \";\n for(int i = 0; i < nNodes; ++i) {\n cout << setw(6) << u[i] << \" \";\n }\n \n \/\/ Determine the exact solutions\n cout << \"\\nexact = \";\n for(int i = 0; i < nNodes; ++i) {\n cout << setw(6) << function(zNode[i], nPts, pointsType) << \" \";\n }\n\n \/\/ Display the pointwise error\n cout << setprecision(1);\n cout << \"\\nerror = \";\n long double Linf = 0, RMS = 0;\n for(int i = 0; i < I.GetRows(); ++i) {\n \/\/long double exact = function(zNode[i], nNodes, pointsType);\n long double exact = function(zNode[i], nPts, pointsType);\n long double error = exact - u[i];\n Linf = fmax(Linf, fabs(error));\n RMS += error*error;\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon ) {\n error \/= exact;\n }\n cout << setw(6) << error << \" \";\n }\n RMS = sqrt(RMS) \/ I.GetRows();\n cout << setprecision(6);\n cout << \"\\nLinf = \" << setw(6) << Linf;\n cout << \"\\nRMS = \" << setw(6) << RMS << endl;\n \n \/\/ Show the interpolation matrix\n cout << \"\\nI = \\n\";\n for(int i = 0; i < I.GetRows(); ++i) {\n cout << \" \";\n for(int j = 0; j < I.GetColumns(); ++j) {\n printf(\"% 5.3f \", I(i,j));\n }\n cout << \"\\n\";\n }\n\n\n\n \n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Derivation \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n \/\/ Get the derivation matrix D\n \/\/ Note that, unlike I, D is N rows by N columns\n const Points::MatrixSharedPtrType Dptr = points->GetD();\n const NekMatrix & D = *Dptr;\n \n \n \/\/ Differentiate the data values in the y vector using the derivative matrix D\n SharedArray v(nPts);\n for(int i = 0; i < D.GetRows(); ++i) {\n v[i] = 0;\n for(int j = 0; j < D.GetColumns(); ++j) {\n v[i] += D(i,j) * y[j];\n }\n }\n\n \n \/\/ Display the derivative approximations\n cout << \"\\n\\n\\n **** Differentiation ****\" << setprecision(3);\n cout << \"\\n\\nResults of differentiation with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\nderived = \";\n for(int i = 0; i < nPts; ++i) {\n cout << setw(6) << v[i] << \" \";\n }\n \n \/\/ Determine the exact solutions\n cout << \"\\nexact = \";\n for(int i = 0; i < nPts; ++i) {\n cout << setw(6) << derivativeFunction(z[i], nPts, pointsType) << \" \";\n }\n\n \/\/ Display the pointwise error\n cout << setprecision(1);\n cout << \"\\nerror = \";\n Linf = 0, RMS = 0;\n for(int i = 0; i < nPts; ++i) {\n long double exact = derivativeFunction(z[i], nPts, pointsType);\n long double error = exact - v[i];\n Linf = fmax(Linf, fabs(error));\n RMS += error*error;\n\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon ) {\n error \/= exact;\n }\n cout << setw(6) << error << \" \";\n }\n\n \/\/ Display the global error\n RMS = sqrt(RMS) \/ I.GetRows();\n cout << setprecision(6);\n cout << \"\\nLinf = \" << setw(6) << Linf;\n cout << \"\\nRMS = \" << setw(6) << RMS << endl;\n \n\n \/\/ Show the derivation matrix\n cout << \"\\nD = \\n\";\n for(int i = 0; i < D.GetRows(); ++i) {\n cout << \" \";\n for(int j = 0; j < D.GetColumns(); ++j) {\n printf(\"% 5.3f \", D(i,j));\n }\n cout << \"\\n\";\n }\n\n\n \n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Integration \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \/\/ Integrate the function by approximating the integral as a weighted\n \/\/ linear combination of function evaluations at the z[i] points: y[i] = f(z[i])\n long double numericalIntegration = 0.0;\n for(int i = 0; i < nPts; ++i) {\n numericalIntegration += w[i] * y[i] \/ integrandWeightFunction(z[i], pointsType);\n }\n\n \n \/\/ Display the integral approximation\n cout << \"\\n\\n\\n **** Integration ****\" << setprecision(6);\n cout << \"\\n\\nResults of integration with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\nnumerical integral = \" << setw(12) << numericalIntegration;\n\n \/\/ Determine the exact solutions\n cout << \"\\nexact = \" << setw(12) << integrationFunction(nPts, pointsType);\n\n \/\/ Display the error\n cout << \"\\nerror = \";\n {\n long double exact = integrationFunction(nPts, pointsType);\n long double error = exact - numericalIntegration;\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon ) {\n error \/= exact;\n }\n cout << setw(12) << error;\n }\n\n\n \/\/ Show the weights\n cout << \"\\nquatdrature weights = \" << setprecision(3);\n for(int i = 0; i < nPts; ++i) {\n cout << setw(7) << w[i] << \" \";\n }\n cout << endl;\n\n}\n\nFixed new changes of SharedArray stuff#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#include \"LibUtilities\/Foundations\/Foundations.hpp\"\n#include \n#include \n\nusing namespace Nektar;\nusing namespace Nektar::LibUtilities;\n\n\n\/\/ Quintic polynomial\nlong double polyFunc(long double x)\n{\n return (((3.0*x*x - 5.0)*x + 1.0)*x - 2.0)*x + 3.0;\n}\n\n\/\/ Derivative of the Quintic polynomial\nlong double derivativePolyFunc(long double x)\n{\n return ((15.0*x*x - 15.0)*x + 2.0)*x - 2.0;\n}\n\n\/\/ A Fourier function that integrates to 0 with the Trapezoidal rule\nlong double fourierFunc(long double x, int N)\n{\n long double z = M_PI*(x + 1.0);\n return (cos(N\/2.0*z) + sin((N\/2.0 - 2.0)*z))\/M_PI;\n}\n\n\/\/ Derivative of the Fourier function above\nlong double derivativeFourierFunc(long double x, int N)\n{\n long double z = M_PI*(x + 1.0);\n long double a = (N-4.0)\/2.0;\n long double b = N\/2.0;\n return M_PI*M_PI*(a*cos(a*z) - b*sin(b*z));\n}\n\nlong double function(long double x, int N, PointsType type)\n{\n long double y = 0;\n if( type == eFourierEvenlySpaced)\n {\n y = fourierFunc(x,N);\n } else\n {\n y = polyFunc(x);\n }\n return y;\n}\n\nlong double derivativeFunction(long double x, int N, PointsType type)\n{\n long double yDerivative = 0;\n if(type == eFourierEvenlySpaced)\n {\n yDerivative = derivativeFourierFunc(x, N);\n }\n else\n {\n yDerivative = derivativePolyFunc(x);\n }\n return yDerivative;\n}\n\nlong double integrationFunction(int nPts, PointsType type)\n{\n long double integral = 0;\n switch(type)\n {\n case eFourierEvenlySpaced:\n integral = 0;\n break;\n default:\n integral = (long double)20.0\/3.0; \n }\n return integral;\n}\n\nlong double integrandWeightFunction(long double x, PointsType type)\n{\n long double weight = 1;\n\n switch(type)\n {\n case eGaussGaussChebyshev:\n case eGaussRadauMChebyshev:\n case eGaussRadauPChebyshev:\n case eGaussLobattoChebyshev: \n weight = 1.0 \/ sqrt(1.0 - x*x);\n break;\n\n case eGaussRadauMAlpha0Beta1:\n \/\/ weight = 1.0 + x; \/\/ ?\n break;\n\n case eGaussRadauMAlpha0Beta2: \n \/\/ weight = (1.0 + x)*(1.0 + x); \/\/ ?\n break;\n \n\n default:\n weight = 1.0;\n }\n return weight;\n}\n\/\/ This routine projects a polynomial or trigonmetric functions which\n\/\/ has energy in all modes of the expansions and report an error.\n\nint main(int argc, char *argv[])\n{\n\n \/\/ Argument check: Display a help message if the count is wrong\n if(argc != 3)\n {\n cerr << \"Usage: FoundationDemo Points1D-Type nPts\" << endl;\n\n cerr << \"Where type is an integer value which dictates the basis as:\\n\";\n for(int i=0; i > points = PointsManager()[key];\n \/\/const ptr > points = PointsManager()[key];\n\n \/\/ Get the abscissas and their matching quadrature weights\n \/\/ SharedArray z, w;\n ConstArray z, w;\n points->GetZW(z,w);\n\n \/\/ Evaluate the example function at the z[i] points in the interval [-1,1].\n \/\/ This generates the data samples, which we store in the y vector and use later\n \/\/ during interpolation\/integration\/differentiation\n \/\/ SharedArray y(nPts);\n Array y(nPts);\n for(int i = 0; i < nPts; ++i)\n {\n y[i] = function( z[i], nPts, pointsType );\n }\n \n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Interpolation \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Generate a list of interpolating nodes\n int nNodes = 2*nPts; \/\/ Number of interpolating nodes\n boost::shared_ptr > nodes = PointsManager()[PointsKey(nNodes, pointsType)];\n \/\/ const ptr > nodes = PointsManager()[PointsKey(nNodes, pointsType)];\n \/\/SharedArray zNode = nodes->GetZ();\n ConstArray zNode = nodes->GetZ();\n \n \/\/ Get the interpolation matrix I\n \/\/ Note that I is 2N rows by N columns\n const Points::MatrixSharedPtrType Iptr = points->GetI(nNodes,zNode);\n\/\/ const Points::MatrixSharedPtrType Iptr = points->GetI(nNodes, zNode);\n const NekMatrix & I = *Iptr;\n \n \n \n \/\/ Interpolate the data values in the y vector using the interpolation matrix I\n\/\/ SharedArray u(I.GetRows());\n Array u(I.GetRows());\n for(int i = 0; i < int(I.GetRows()); ++i)\n {\n u[i] = 0;\n for(int j = 0; j < int(I.GetColumns()); ++j)\n {\n u[i] += I(i,j) * y[j];\n }\n }\n\n \/\/ Display the original samples\n cout << setprecision(3);\n cout << \"\\nOriginal data: \\nx = \";\n for(int i = 0; i < nPts; ++i)\n {\n cout << setw(6) << z[i] << \" \";\n }\n cout << \"\\ny = \";\n for(int i = 0; i < nPts; ++i)\n {\n cout << setw(6) << y[i] << \" \";\n }\n\n \/\/ Display the interpolated data\n cout << \"\\n\\n\\n **** Interpolation ****\";\n cout << \"\\n\\nResults of interpolation with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\ninterp = \";\n for(int i = 0; i < nNodes; ++i)\n {\n cout << setw(6) << u[i] << \" \";\n }\n \n \/\/ Determine the exact solutions\n cout << \"\\nexact = \";\n for(int i = 0; i < nNodes; ++i)\n {\n cout << setw(6) << function(zNode[i], nPts, pointsType) << \" \";\n }\n\n \/\/ Display the pointwise error\n cout << setprecision(1);\n cout << \"\\nerror = \";\n long double Linf = 0, RMS = 0;\n for(int i = 0; i < int(I.GetRows()); ++i)\n {\n \/\/long double exact = function(zNode[i], nNodes, pointsType);\n long double exact = function(zNode[i], nPts, pointsType);\n long double error = exact - u[i];\n Linf = max(Linf, fabs(error));\n RMS += error*error;\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon )\n {\n error \/= exact;\n }\n cout << setw(6) << error << \" \";\n }\n RMS = sqrt(RMS) \/ int(I.GetRows());\n cout << setprecision(6);\n cout << \"\\nLinf = \" << setw(6) << Linf;\n cout << \"\\nRMS = \" << setw(6) << RMS << endl;\n \n \/\/ Show the interpolation matrix\n cout << \"\\nI = \\n\";\n for(int i = 0; i < int(I.GetRows()); ++i)\n {\n cout << \" \";\n for(int j = 0; j < int(I.GetColumns()); ++j)\n {\n printf(\"% 5.3f \", I(i,j));\n }\n cout << \"\\n\";\n }\n\n\n\n \n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Derivation \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n \/\/ Get the derivation matrix D\n \/\/ Note that, unlike I, D is N rows by N columns\n const Points::MatrixSharedPtrType Dptr = points->GetD();\n const NekMatrix & D = *Dptr;\n \n \n \/\/ Differentiate the data values in the y vector using the derivative matrix D\n Array v(nPts);\n for(int i = 0; i < int(D.GetRows()); ++i)\n {\n v[i] = 0;\n for(int j = 0; j < int(D.GetColumns()); ++j)\n {\n v[i] += D(i,j) * y[j];\n }\n }\n\n \n \/\/ Display the derivative approximations\n cout << \"\\n\\n\\n **** Differentiation ****\" << setprecision(3);\n cout << \"\\n\\nResults of differentiation with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\nderived = \";\n for(int i = 0; i < nPts; ++i)\n {\n cout << setw(6) << v[i] << \" \";\n }\n \n \/\/ Determine the exact solutions\n cout << \"\\nexact = \";\n for(int i = 0; i < nPts; ++i)\n {\n cout << setw(6) << derivativeFunction(z[i], nPts, pointsType) << \" \";\n }\n\n \/\/ Display the pointwise error\n cout << setprecision(1);\n cout << \"\\nerror = \";\n Linf = 0, RMS = 0;\n for(int i = 0; i < nPts; ++i)\n {\n long double exact = derivativeFunction(z[i], nPts, pointsType);\n long double error = exact - v[i];\n Linf = max(Linf, fabs(error));\n RMS += error*error;\n\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon )\n {\n error \/= exact;\n }\n cout << setw(6) << error << \" \";\n }\n\n \/\/ Display the global error\n RMS = sqrt(RMS) \/ I.GetRows();\n cout << setprecision(6);\n cout << \"\\nLinf = \" << setw(6) << Linf;\n cout << \"\\nRMS = \" << setw(6) << RMS << endl;\n \n\n \/\/ Show the derivation matrix\n cout << \"\\nD = \\n\";\n for(int i = 0; i < int(D.GetRows()); ++i)\n {\n cout << \" \";\n for(int j = 0; j < int(D.GetColumns()); ++j)\n {\n printf(\"% 5.3f \", D(i,j));\n }\n cout << \"\\n\";\n }\n\n\n \n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Integration \/\/\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \/\/ Integrate the function by approximating the integral as a weighted\n \/\/ linear combination of function evaluations at the z[i] points: y[i] = f(z[i])\n long double numericalIntegration = 0.0;\n for(int i = 0; i < nPts; ++i)\n {\n numericalIntegration += w[i] * y[i] \/ integrandWeightFunction(z[i], pointsType);\n }\n\n \n \/\/ Display the integral approximation\n cout << \"\\n\\n\\n **** Integration ****\" << setprecision(6);\n cout << \"\\n\\nResults of integration with \" << PointsTypeMap[pointsType] << \":\";\n cout << \"\\nnumerical integral = \" << setw(12) << numericalIntegration;\n\n \/\/ Determine the exact solutions\n cout << \"\\nexact = \" << setw(12) << integrationFunction(nPts, pointsType);\n\n \/\/ Display the error\n cout << \"\\nerror = \";\n {\n long double exact = integrationFunction(nPts, pointsType);\n long double error = exact - numericalIntegration;\n long double epsilon = 1e-2;\n if( fabs(exact) > epsilon )\n {\n error \/= exact;\n }\n cout << setw(12) << error;\n }\n\n\n \/\/ Show the weights\n cout << \"\\nquatdrature weights = \" << setprecision(3);\n for(int i = 0; i < nPts; ++i)\n {\n cout << setw(7) << w[i] << \" \";\n }\n cout << endl;\n\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"bitcoinunits.h\"\n#include \"clientmodel.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"init.h\"\n#include \"obfuscation.h\"\n#include \"obfuscationconfig.h\"\n#include \"optionsmodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"transactiontablemodel.h\"\n#include \"walletmodel.h\"\n\n#include \n#include \n#include \n#include \n\n#define DECORATION_SIZE 48\n#define ICON_OFFSET 16\n#define NUM_ITEMS 5\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate() : QAbstractItemDelegate(), unit(BitcoinUnits::PIV)\n {\n }\n\n inline void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n mainRect.moveLeft(ICON_OFFSET);\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2 * ypad) \/ 2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top() + ypad + halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n QVariant value = index.data(Qt::ForegroundRole);\n QColor foreground = COLOR_BLACK;\n if (value.canConvert()) {\n QBrush brush = qvariant_cast(value);\n foreground = brush.color();\n }\n\n painter->setPen(foreground);\n QRect boundingRect;\n painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);\n\n if (index.data(TransactionTableModel::WatchonlyRole).toBool()) {\n QIcon iconWatchonly = qvariant_cast(index.data(TransactionTableModel::WatchonlyDecorationRole));\n QRect watchonlyRect(boundingRect.right() + 5, mainRect.top() + ypad + halfheight, 16, halfheight);\n iconWatchonly.paint(painter, watchonlyRect);\n }\n\n if (amount < 0) {\n foreground = COLOR_NEGATIVE;\n } else if (!confirmed) {\n foreground = COLOR_UNCONFIRMED;\n } else {\n foreground = COLOR_BLACK;\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);\n if (!confirmed) {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText);\n\n painter->setPen(COLOR_BLACK);\n painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget* parent) : QWidget(parent),\n ui(new Ui::OverviewPage),\n clientModel(0),\n walletModel(0),\n currentBalance(-1),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n currentZerocoinBalance(-1),\n currentWatchOnlyBalance(-1),\n currentWatchUnconfBalance(-1),\n currentWatchImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n nDisplayUnit = 0; \/\/ just make sure it's not unitialized\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex& index)\n{\n if (filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nOverviewPage::~OverviewPage()\n{\n if (!fLiteMode && !fMasterNode) disconnect(timer, SIGNAL(timeout()), this, SLOT(obfuScationStatus()));\n delete ui;\n}\n\nvoid OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)\n{\n currentBalance = balance;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n currentZerocoinBalance = zerocoinBalance;\n currentWatchOnlyBalance = watchOnlyBalance;\n currentWatchUnconfBalance = watchUnconfBalance;\n currentWatchImmatureBalance = watchImmatureBalance;\n\n ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelzBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, zerocoinBalance, false, BitcoinUnits::separatorAlways));\n ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n\n ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n bool showWatchOnlyImmature = watchImmatureBalance != 0;\n\n \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n ui->labelWatchImmature->setVisible(showWatchOnlyImmature); \/\/ show watch-only immature balance\n\n static int cachedTxLocks = 0;\n\n if (cachedTxLocks != nCompleteTXLocks) {\n cachedTxLocks = nCompleteTXLocks;\n ui->listTransactions->update();\n }\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n ui->labelSpendable->setVisible(showWatchOnly); \/\/ show spendable label (only when watch-only is active)\n ui->labelWatchonly->setVisible(showWatchOnly); \/\/ show watch-only label\n ui->lineWatchBalance->setVisible(showWatchOnly); \/\/ show watch-only balance separator line\n ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n ui->labelWatchPending->setVisible(showWatchOnly); \/\/ show watch-only pending balance\n ui->labelWatchTotal->setVisible(showWatchOnly); \/\/ show watch-only total balance\n\n if (!showWatchOnly) {\n ui->labelWatchImmature->hide();\n } else {\n ui->labelBalance->setIndent(20);\n ui->labelUnconfirmed->setIndent(20);\n ui->labelImmature->setIndent(20);\n ui->labelTotal->setIndent(20);\n }\n}\n\nvoid OverviewPage::setClientModel(ClientModel* model)\n{\n this->clientModel = model;\n if (model) {\n \/\/ Show warning if this is a prerelease version\n connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n updateAlerts(model->getStatusBarWarnings());\n }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel* model)\n{\n this->walletModel = model;\n if (model && model->getOptionsModel()) {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setLimit(NUM_ITEMS);\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->setShowInactive(false);\n filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance(),\n model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());\n connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n updateWatchOnlyLabels(model->haveWatchOnly());\n connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));\n }\n\n \/\/ update the display unit, to not use the default (\"PIV\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if (walletModel && walletModel->getOptionsModel()) {\n nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();\n if (currentBalance != -1)\n setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance,\n currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = nDisplayUnit;\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::updateAlerts(const QString& warnings)\n{\n this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n}\nFix segfault on exit\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Copyright (c) 2014-2015 The Dash developers\n\/\/ Copyright (c) 2015-2017 The PIVX developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#include \"bitcoinunits.h\"\n#include \"clientmodel.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"init.h\"\n#include \"obfuscation.h\"\n#include \"obfuscationconfig.h\"\n#include \"optionsmodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"transactiontablemodel.h\"\n#include \"walletmodel.h\"\n\n#include \n#include \n#include \n#include \n\n#define DECORATION_SIZE 48\n#define ICON_OFFSET 16\n#define NUM_ITEMS 5\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate() : QAbstractItemDelegate(), unit(BitcoinUnits::PIV)\n {\n }\n\n inline void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n mainRect.moveLeft(ICON_OFFSET);\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2 * ypad) \/ 2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top() + ypad, mainRect.width() - xspace - ICON_OFFSET, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top() + ypad + halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n QVariant value = index.data(Qt::ForegroundRole);\n QColor foreground = COLOR_BLACK;\n if (value.canConvert()) {\n QBrush brush = qvariant_cast(value);\n foreground = brush.color();\n }\n\n painter->setPen(foreground);\n QRect boundingRect;\n painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignVCenter, address, &boundingRect);\n\n if (index.data(TransactionTableModel::WatchonlyRole).toBool()) {\n QIcon iconWatchonly = qvariant_cast(index.data(TransactionTableModel::WatchonlyDecorationRole));\n QRect watchonlyRect(boundingRect.right() + 5, mainRect.top() + ypad + halfheight, 16, halfheight);\n iconWatchonly.paint(painter, watchonlyRect);\n }\n\n if (amount < 0) {\n foreground = COLOR_NEGATIVE;\n } else if (!confirmed) {\n foreground = COLOR_UNCONFIRMED;\n } else {\n foreground = COLOR_BLACK;\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true, BitcoinUnits::separatorAlways);\n if (!confirmed) {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight | Qt::AlignVCenter, amountText);\n\n painter->setPen(COLOR_BLACK);\n painter->drawText(amountRect, Qt::AlignLeft | Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget* parent) : QWidget(parent),\n ui(new Ui::OverviewPage),\n clientModel(0),\n walletModel(0),\n currentBalance(-1),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n currentZerocoinBalance(-1),\n currentWatchOnlyBalance(-1),\n currentWatchUnconfBalance(-1),\n currentWatchImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n nDisplayUnit = 0; \/\/ just make sure it's not unitialized\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex& index)\n{\n if (filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nOverviewPage::~OverviewPage()\n{\n delete ui;\n}\n\nvoid OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)\n{\n currentBalance = balance;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n currentZerocoinBalance = zerocoinBalance;\n currentWatchOnlyBalance = watchOnlyBalance;\n currentWatchUnconfBalance = watchUnconfBalance;\n currentWatchImmatureBalance = watchImmatureBalance;\n\n ui->labelBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelzBalance->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, zerocoinBalance, false, BitcoinUnits::separatorAlways));\n ui->labelUnconfirmed->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n ui->labelImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, immatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance + unconfirmedBalance, false, BitcoinUnits::separatorAlways));\n\n ui->labelWatchAvailable->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchPending->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchUnconfBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchImmature->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n ui->labelWatchTotal->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, BitcoinUnits::separatorAlways));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n bool showWatchOnlyImmature = watchImmatureBalance != 0;\n\n \/\/ for symmetry reasons also show immature label when the watch-only one is shown\n ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);\n ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);\n ui->labelWatchImmature->setVisible(showWatchOnlyImmature); \/\/ show watch-only immature balance\n\n static int cachedTxLocks = 0;\n\n if (cachedTxLocks != nCompleteTXLocks) {\n cachedTxLocks = nCompleteTXLocks;\n ui->listTransactions->update();\n }\n}\n\n\/\/ show\/hide watch-only labels\nvoid OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)\n{\n ui->labelSpendable->setVisible(showWatchOnly); \/\/ show spendable label (only when watch-only is active)\n ui->labelWatchonly->setVisible(showWatchOnly); \/\/ show watch-only label\n ui->lineWatchBalance->setVisible(showWatchOnly); \/\/ show watch-only balance separator line\n ui->labelWatchAvailable->setVisible(showWatchOnly); \/\/ show watch-only available balance\n ui->labelWatchPending->setVisible(showWatchOnly); \/\/ show watch-only pending balance\n ui->labelWatchTotal->setVisible(showWatchOnly); \/\/ show watch-only total balance\n\n if (!showWatchOnly) {\n ui->labelWatchImmature->hide();\n } else {\n ui->labelBalance->setIndent(20);\n ui->labelUnconfirmed->setIndent(20);\n ui->labelImmature->setIndent(20);\n ui->labelTotal->setIndent(20);\n }\n}\n\nvoid OverviewPage::setClientModel(ClientModel* model)\n{\n this->clientModel = model;\n if (model) {\n \/\/ Show warning if this is a prerelease version\n connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));\n updateAlerts(model->getStatusBarWarnings());\n }\n}\n\nvoid OverviewPage::setWalletModel(WalletModel* model)\n{\n this->walletModel = model;\n if (model && model->getOptionsModel()) {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setLimit(NUM_ITEMS);\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->setShowInactive(false);\n filter->sort(TransactionTableModel::Date, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n\n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getZerocoinBalance(),\n model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());\n connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n updateWatchOnlyLabels(model->haveWatchOnly());\n connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));\n }\n\n \/\/ update the display unit, to not use the default (\"PIV\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if (walletModel && walletModel->getOptionsModel()) {\n nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();\n if (currentBalance != -1)\n setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance,\n currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = nDisplayUnit;\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::updateAlerts(const QString& warnings)\n{\n this->ui->labelAlerts->setVisible(!warnings.isEmpty());\n this->ui->labelAlerts->setText(warnings);\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n}\n<|endoftext|>"} {"text":"\n\n#include \n#include \n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#ifndef Q_MOC_RUN\n#include \"main.h\"\n#endif\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \n#include \n\n#ifdef WIN32\n#include \n#include \"..\/global_objects.hpp\"\n#include \"..\/global_objects_noui.hpp\"\n#endif\n\n#define DECORATION_SIZE 64\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)\n {\n\n }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2*ypad)\/2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n\n\n\t\t\/\/QColor foreground = option.palette.color(QPalette::Text);\n\t\t\/\/R Halford: 11-28-2013: \n\t\tQColor foreground = QColor(200, 0, 0);\n\t\t\n QVariant value = index.data(Qt::ForegroundRole);\n \/\/QColor foreground = option.palette.color(QPalette::Text);\n if(value.canConvert(QMetaType::QColor))\n {\n foreground = qvariant_cast(value);\n }\n\n painter->setPen(foreground);\n painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);\n\n if(amount < 0)\n {\n foreground = COLOR_NEGATIVE;\n }\n else if(!confirmed)\n {\n foreground = COLOR_UNCONFIRMED;\n }\n else\n {\n foreground = option.palette.color(QPalette::Text);\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);\n if(!confirmed)\n {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n painter->setPen(option.palette.color(QPalette::Text));\n painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::OverviewPage),\n currentBalance(-1),\n currentStake(0),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n updateTransactions();\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n\tOverviewPage::UpdateBoincUtilization();\n\n if(filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n updateTransactions();\n}\n\nvoid OverviewPage::showEvent(QShowEvent *event)\n{\n QWidget::showEvent(event);\n updateTransactions();\n}\n\nvoid OverviewPage::updateTransactions()\n{ \n if(filter)\n {\n \/\/ Show the maximum number of transactions the transaction list widget\n \/\/ can hold without overflowing.\n const size_t itemHeight = DECORATION_SIZE + ui->listTransactions->spacing();\n const size_t contentsHeight = ui->listTransactions->height();\n const size_t numItems = contentsHeight \/ itemHeight;\n filter->setLimit(numItems);\n ui->listTransactions->update();\n }\n}\n\nOverviewPage::~OverviewPage()\n{\n delete ui;\n}\n\nvoid OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)\n{\n int unit = model->getOptionsModel()->getDisplayUnit();\n currentBalance = balance;\n currentStake = stake;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));\n ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));\n ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));\n ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n ui->labelImmature->setVisible(showImmature);\n ui->labelImmatureText->setVisible(showImmature);\n\tOverviewPage::UpdateBoincUtilization();\n\n}\n\nvoid OverviewPage::UpdateBoincUtilization()\n{\n LOCK(GlobalStatusStruct.lock);\n ui->labelBlocks->setText(QString::fromUtf8(GlobalStatusStruct.blocks.c_str()));\n ui->labelDifficulty->setText(QString::fromUtf8(GlobalStatusStruct.difficulty.c_str()));\n ui->labelNetWeight->setText(QString::fromUtf8(GlobalStatusStruct.netWeight.c_str()));\n ui->labelCoinWeight->setText(QString::fromUtf8(GlobalStatusStruct.coinWeight.c_str()));\n ui->labelMagnitude->setText(QString::fromUtf8(GlobalStatusStruct.magnitude.c_str()));\n ui->labelProject->setText(QString::fromUtf8(GlobalStatusStruct.project.c_str()));\n ui->labelCpid->setText(QString::fromUtf8(GlobalStatusStruct.cpid.c_str()));\n ui->labelStatus->setText(QString::fromUtf8(GlobalStatusStruct.status.c_str()));\n ui->labelPoll->setText(QString::fromUtf8(GlobalStatusStruct.poll.c_str()).replace(QChar('_'),QChar(' '), Qt::CaseSensitive));\n ui->labelErrors->setText(QString::fromUtf8(GlobalStatusStruct.errors.c_str()));\n}\n\nvoid OverviewPage::setModel(WalletModel *model)\n{\n this->model = model;\n if(model && model->getOptionsModel())\n {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->setShowInactive(false);\n filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n \n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n UpdateBoincUtilization();\n }\n\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n if(currentBalance != -1)\n setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = model->getOptionsModel()->getDisplayUnit();\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n\tOverviewPage::UpdateBoincUtilization();\n}\n\nvoid OverviewPage::updateglobalstatus()\n{\n\n\tOverviewPage::UpdateBoincUtilization();\n}\n\nChange QVariant cast check.\n\n#include \n#include \n\n#include \"overviewpage.h\"\n#include \"ui_overviewpage.h\"\n\n#ifndef Q_MOC_RUN\n#include \"main.h\"\n#endif\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"optionsmodel.h\"\n#include \"transactiontablemodel.h\"\n#include \"transactionfilterproxy.h\"\n#include \"guiutil.h\"\n#include \"guiconstants.h\"\n\n#include \n#include \n\n#ifdef WIN32\n#include \n#include \"..\/global_objects.hpp\"\n#include \"..\/global_objects_noui.hpp\"\n#endif\n\n#define DECORATION_SIZE 64\n\nclass TxViewDelegate : public QAbstractItemDelegate\n{\n Q_OBJECT\npublic:\n TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)\n {\n\n }\n\n inline void paint(QPainter *painter, const QStyleOptionViewItem &option,\n const QModelIndex &index ) const\n {\n painter->save();\n\n QIcon icon = qvariant_cast(index.data(Qt::DecorationRole));\n QRect mainRect = option.rect;\n QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));\n int xspace = DECORATION_SIZE + 8;\n int ypad = 6;\n int halfheight = (mainRect.height() - 2*ypad)\/2;\n QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);\n QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);\n icon.paint(painter, decorationRect);\n\n QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();\n QString address = index.data(Qt::DisplayRole).toString();\n qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();\n bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();\n\n\t\tQColor foreground = QColor(200, 0, 0);\n QVariant value = index.data(Qt::ForegroundRole);\n if(value.canConvert())\n {\n foreground = qvariant_cast(value);\n }\n\n painter->setPen(foreground);\n painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);\n\n if(amount < 0)\n {\n foreground = COLOR_NEGATIVE;\n }\n else if(!confirmed)\n {\n foreground = COLOR_UNCONFIRMED;\n }\n else\n {\n foreground = option.palette.color(QPalette::Text);\n }\n painter->setPen(foreground);\n QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);\n if(!confirmed)\n {\n amountText = QString(\"[\") + amountText + QString(\"]\");\n }\n painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);\n\n painter->setPen(option.palette.color(QPalette::Text));\n painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));\n\n painter->restore();\n }\n\n inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n return QSize(DECORATION_SIZE, DECORATION_SIZE);\n }\n\n int unit;\n\n};\n#include \"overviewpage.moc\"\n\nOverviewPage::OverviewPage(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::OverviewPage),\n currentBalance(-1),\n currentStake(0),\n currentUnconfirmedBalance(-1),\n currentImmatureBalance(-1),\n txdelegate(new TxViewDelegate()),\n filter(0)\n{\n ui->setupUi(this);\n\n \/\/ Recent transactions\n ui->listTransactions->setItemDelegate(txdelegate);\n ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));\n ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);\n updateTransactions();\n\n connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));\n\n \/\/ init \"out of sync\" warning labels\n ui->labelWalletStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n ui->labelTransactionsStatus->setText(\"(\" + tr(\"out of sync\") + \")\");\n\n \/\/ start with displaying the \"out of sync\" warnings\n showOutOfSyncWarning(true);\n}\n\nvoid OverviewPage::handleTransactionClicked(const QModelIndex &index)\n{\n\tOverviewPage::UpdateBoincUtilization();\n\n if(filter)\n emit transactionClicked(filter->mapToSource(index));\n}\n\nvoid OverviewPage::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n updateTransactions();\n}\n\nvoid OverviewPage::showEvent(QShowEvent *event)\n{\n QWidget::showEvent(event);\n updateTransactions();\n}\n\nvoid OverviewPage::updateTransactions()\n{ \n if(filter)\n {\n \/\/ Show the maximum number of transactions the transaction list widget\n \/\/ can hold without overflowing.\n const size_t itemHeight = DECORATION_SIZE + ui->listTransactions->spacing();\n const size_t contentsHeight = ui->listTransactions->height();\n const size_t numItems = contentsHeight \/ itemHeight;\n filter->setLimit(numItems);\n ui->listTransactions->update();\n }\n}\n\nOverviewPage::~OverviewPage()\n{\n delete ui;\n}\n\nvoid OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)\n{\n int unit = model->getOptionsModel()->getDisplayUnit();\n currentBalance = balance;\n currentStake = stake;\n currentUnconfirmedBalance = unconfirmedBalance;\n currentImmatureBalance = immatureBalance;\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));\n ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));\n ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));\n ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));\n\n \/\/ only show immature (newly mined) balance if it's non-zero, so as not to complicate things\n \/\/ for the non-mining users\n bool showImmature = immatureBalance != 0;\n ui->labelImmature->setVisible(showImmature);\n ui->labelImmatureText->setVisible(showImmature);\n\tOverviewPage::UpdateBoincUtilization();\n\n}\n\nvoid OverviewPage::UpdateBoincUtilization()\n{\n LOCK(GlobalStatusStruct.lock);\n ui->labelBlocks->setText(QString::fromUtf8(GlobalStatusStruct.blocks.c_str()));\n ui->labelDifficulty->setText(QString::fromUtf8(GlobalStatusStruct.difficulty.c_str()));\n ui->labelNetWeight->setText(QString::fromUtf8(GlobalStatusStruct.netWeight.c_str()));\n ui->labelCoinWeight->setText(QString::fromUtf8(GlobalStatusStruct.coinWeight.c_str()));\n ui->labelMagnitude->setText(QString::fromUtf8(GlobalStatusStruct.magnitude.c_str()));\n ui->labelProject->setText(QString::fromUtf8(GlobalStatusStruct.project.c_str()));\n ui->labelCpid->setText(QString::fromUtf8(GlobalStatusStruct.cpid.c_str()));\n ui->labelStatus->setText(QString::fromUtf8(GlobalStatusStruct.status.c_str()));\n ui->labelPoll->setText(QString::fromUtf8(GlobalStatusStruct.poll.c_str()).replace(QChar('_'),QChar(' '), Qt::CaseSensitive));\n ui->labelErrors->setText(QString::fromUtf8(GlobalStatusStruct.errors.c_str()));\n}\n\nvoid OverviewPage::setModel(WalletModel *model)\n{\n this->model = model;\n if(model && model->getOptionsModel())\n {\n \/\/ Set up transaction list\n filter = new TransactionFilterProxy();\n filter->setSourceModel(model->getTransactionTableModel());\n filter->setDynamicSortFilter(true);\n filter->setSortRole(Qt::EditRole);\n filter->setShowInactive(false);\n filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);\n\n ui->listTransactions->setModel(filter);\n ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);\n \n \/\/ Keep up to date with wallet\n setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n UpdateBoincUtilization();\n }\n\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid OverviewPage::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n if(currentBalance != -1)\n setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);\n\n \/\/ Update txdelegate->unit with the current unit\n txdelegate->unit = model->getOptionsModel()->getDisplayUnit();\n\n ui->listTransactions->update();\n }\n}\n\nvoid OverviewPage::showOutOfSyncWarning(bool fShow)\n{\n ui->labelWalletStatus->setVisible(fShow);\n ui->labelTransactionsStatus->setVisible(fShow);\n\tOverviewPage::UpdateBoincUtilization();\n}\n\nvoid OverviewPage::updateglobalstatus()\n{\n\n\tOverviewPage::UpdateBoincUtilization();\n}\n\n<|endoftext|>"} {"text":"#include \"qrcodedialog.h\"\n#include \"ui_qrcodedialog.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n\n#include \n#include \n\n#include \n\nQRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::QRCodeDialog),\n model(0),\n address(addr)\n{\n ui->setupUi(this);\n\n setWindowTitle(QString(\"%1\").arg(address));\n\n ui->chkReqPayment->setVisible(enableReq);\n ui->lblAmount->setVisible(enableReq);\n ui->lnReqAmount->setVisible(enableReq);\n\n ui->lnLabel->setText(label);\n\n ui->btnSaveAs->setEnabled(false);\n\n genCode();\n}\n\nQRCodeDialog::~QRCodeDialog()\n{\n delete ui;\n}\n\nvoid QRCodeDialog::setModel(OptionsModel *model)\n{\n this->model = model;\n\n if (model)\n connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n \/\/ update the display unit, to not use the default (\"QRK\")\n updateDisplayUnit();\n}\n\nvoid QRCodeDialog::genCode()\n{\n QString uri = getURI();\n\n if (uri != \"\")\n {\n ui->lblQRCode->setText(\"\");\n\n QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);\n if (!code)\n {\n ui->lblQRCode->setText(tr(\"Error encoding URI into QR Code.\"));\n return;\n }\n myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);\n myImage.fill(0xffffff);\n unsigned char *p = code->data;\n for (int y = 0; y < code->width; y++)\n {\n for (int x = 0; x < code->width; x++)\n {\n myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));\n p++;\n }\n }\n QRcode_free(code);\n\n ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));\n\n ui->outUri->setPlainText(uri);\n }\n}\n\nQString QRCodeDialog::getURI()\n{\n QString ret = QString(\"bitcoin:%1\").arg(address);\n int paramCount = 0;\n\n ui->outUri->clear();\n\n if (ui->chkReqPayment->isChecked())\n {\n if (ui->lnReqAmount->validate())\n {\n \/\/ even if we allow a non QRK unit input in lnReqAmount, we generate the URI with QRK as unit (as defined in BIP21)\n ret += QString(\"?amount=%1\").arg(BitcoinUnits::format(BitcoinUnits::QRK, ui->lnReqAmount->value()));\n paramCount++;\n }\n else\n {\n ui->btnSaveAs->setEnabled(false);\n ui->lblQRCode->setText(tr(\"The entered amount is invalid, please check.\"));\n return QString(\"\");\n }\n }\n\n if (!ui->lnLabel->text().isEmpty())\n {\n QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));\n ret += QString(\"%1label=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(lbl);\n paramCount++;\n }\n\n if (!ui->lnMessage->text().isEmpty())\n {\n QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));\n ret += QString(\"%1message=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(msg);\n paramCount++;\n }\n\n \/\/ limit URI length to prevent a DoS against the QR-Code dialog\n if (ret.length() > MAX_URI_LENGTH)\n {\n ui->btnSaveAs->setEnabled(false);\n ui->lblQRCode->setText(tr(\"Resulting URI too long, try to reduce the text for label \/ message.\"));\n return QString(\"\");\n }\n\n ui->btnSaveAs->setEnabled(true);\n return ret;\n}\n\nvoid QRCodeDialog::on_lnReqAmount_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_lnLabel_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_lnMessage_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_btnSaveAs_clicked()\n{\n QString fn = GUIUtil::getSaveFileName(this, tr(\"Save QR Code\"), QString(), tr(\"PNG Images (*.png)\"));\n if (!fn.isEmpty())\n myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);\n}\n\nvoid QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)\n{\n if (!fChecked)\n \/\/ if chkReqPayment is not active, don't display lnReqAmount as invalid\n ui->lnReqAmount->setValid(true);\n\n genCode();\n}\n\nvoid QRCodeDialog::updateDisplayUnit()\n{\n if (model)\n {\n \/\/ Update lnReqAmount with the current unit\n ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());\n }\n}\nUpdate QR prefix to quark#include \"qrcodedialog.h\"\n#include \"ui_qrcodedialog.h\"\n\n#include \"bitcoinunits.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n#include \"optionsmodel.h\"\n\n#include \n#include \n\n#include \n\nQRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::QRCodeDialog),\n model(0),\n address(addr)\n{\n ui->setupUi(this);\n\n setWindowTitle(QString(\"%1\").arg(address));\n\n ui->chkReqPayment->setVisible(enableReq);\n ui->lblAmount->setVisible(enableReq);\n ui->lnReqAmount->setVisible(enableReq);\n\n ui->lnLabel->setText(label);\n\n ui->btnSaveAs->setEnabled(false);\n\n genCode();\n}\n\nQRCodeDialog::~QRCodeDialog()\n{\n delete ui;\n}\n\nvoid QRCodeDialog::setModel(OptionsModel *model)\n{\n this->model = model;\n\n if (model)\n connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n \/\/ update the display unit, to not use the default (\"QRK\")\n updateDisplayUnit();\n}\n\nvoid QRCodeDialog::genCode()\n{\n QString uri = getURI();\n\n if (uri != \"\")\n {\n ui->lblQRCode->setText(\"\");\n\n QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);\n if (!code)\n {\n ui->lblQRCode->setText(tr(\"Error encoding URI into QR Code.\"));\n return;\n }\n myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);\n myImage.fill(0xffffff);\n unsigned char *p = code->data;\n for (int y = 0; y < code->width; y++)\n {\n for (int x = 0; x < code->width; x++)\n {\n myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));\n p++;\n }\n }\n QRcode_free(code);\n\n ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));\n\n ui->outUri->setPlainText(uri);\n }\n}\n\nQString QRCodeDialog::getURI()\n{\n QString ret = QString(\"quark:%1\").arg(address);\n int paramCount = 0;\n\n ui->outUri->clear();\n\n if (ui->chkReqPayment->isChecked())\n {\n if (ui->lnReqAmount->validate())\n {\n \/\/ even if we allow a non QRK unit input in lnReqAmount, we generate the URI with QRK as unit (as defined in BIP21)\n ret += QString(\"?amount=%1\").arg(BitcoinUnits::format(BitcoinUnits::QRK, ui->lnReqAmount->value()));\n paramCount++;\n }\n else\n {\n ui->btnSaveAs->setEnabled(false);\n ui->lblQRCode->setText(tr(\"The entered amount is invalid, please check.\"));\n return QString(\"\");\n }\n }\n\n if (!ui->lnLabel->text().isEmpty())\n {\n QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));\n ret += QString(\"%1label=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(lbl);\n paramCount++;\n }\n\n if (!ui->lnMessage->text().isEmpty())\n {\n QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));\n ret += QString(\"%1message=%2\").arg(paramCount == 0 ? \"?\" : \"&\").arg(msg);\n paramCount++;\n }\n\n \/\/ limit URI length to prevent a DoS against the QR-Code dialog\n if (ret.length() > MAX_URI_LENGTH)\n {\n ui->btnSaveAs->setEnabled(false);\n ui->lblQRCode->setText(tr(\"Resulting URI too long, try to reduce the text for label \/ message.\"));\n return QString(\"\");\n }\n\n ui->btnSaveAs->setEnabled(true);\n return ret;\n}\n\nvoid QRCodeDialog::on_lnReqAmount_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_lnLabel_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_lnMessage_textChanged()\n{\n genCode();\n}\n\nvoid QRCodeDialog::on_btnSaveAs_clicked()\n{\n QString fn = GUIUtil::getSaveFileName(this, tr(\"Save QR Code\"), QString(), tr(\"PNG Images (*.png)\"));\n if (!fn.isEmpty())\n myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);\n}\n\nvoid QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)\n{\n if (!fChecked)\n \/\/ if chkReqPayment is not active, don't display lnReqAmount as invalid\n ui->lnReqAmount->setValid(true);\n\n genCode();\n}\n\nvoid QRCodeDialog::updateDisplayUnit()\n{\n if (model)\n {\n \/\/ Update lnReqAmount with the current unit\n ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace QtumLedger_NS {\n\/\/ Read json document\nUniValue json_read_doc(const std::string& jsondata)\n{\n UniValue v;\n v.read(jsondata);\n return v;\n}\n\n\/\/ Read json object\nUniValue json_get_object(const UniValue& jsondata)\n{\n UniValue v(UniValue::VOBJ);\n if(jsondata.isObject())\n v = jsondata.get_obj();\n return v;\n}\n\n\/\/ Read json array\nUniValue json_get_array(const UniValue& jsondata)\n{\n UniValue v(UniValue::VARR);\n if(jsondata.isArray())\n v = jsondata.get_array();\n return v;\n}\n\n\/\/ Get json string for key\nstd::string json_get_key_string(const UniValue& jsondata, std::string key)\n{\n UniValue v(UniValue::VSTR);\n if(jsondata.exists(key))\n {\n UniValue data = jsondata[key];\n if(data.isStr())\n v = data;\n }\n\n return v.get_str();\n}\n\n\/\/ Append data to vector\nstd::vector& operator<<(std::vector& os, const std::string& dt)\n{\n os.push_back(dt);\n return os;\n}\n\n\/\/ Start process from qtumd\nclass CProcess\n{\npublic:\n ~CProcess()\n {\n clean();\n }\n\n \/\/ Set process params\n void start(const std::string& prog, const std::vector &arg)\n {\n clean();\n m_program = prog;\n m_arguments = arg;\n }\n\n \/\/ Start and wait for it to finish\n void waitForFinished()\n {\n boost::asio::io_service svc;\n boost::asio::streambuf out, err;\n boost::process::child child(m_program, boost::process::args(m_arguments),\n boost::process::std_out > out, boost::process::std_err > err, svc);\n\n svc.run();\n child.wait();\n m_std_out = toString(&out);\n m_std_err = toString(&err);\n }\n\n \/\/ Read all standard output\n std::string readAllStandardOutput()\n {\n return m_std_out;\n }\n\n \/\/ Read all standard error\n std::string readAllStandardError()\n {\n return m_std_err;\n }\n\n \/\/ Clean process\n void clean()\n {\n m_program = \"\";\n m_std_out = \"\";\n m_std_err = \"\";\n }\n\n\nprivate:\n std::string toString(boost::asio::streambuf* stream)\n {\n std::istream is(stream);\n std::ostringstream os;\n is >> os.rdbuf();\n return os.str();\n }\n\nprivate:\n std::string m_program;\n std::vector m_arguments;\n std::string m_std_out;\n std::string m_std_err;\n};\n}\nusing namespace QtumLedger_NS;\n\nclass QtumLedgerPriv\n{\npublic:\n QtumLedgerPriv()\n {\n toolPath = gArgs.GetArg(\"-hwitoolpath\", \"\");\n toolExists = boost::filesystem::exists(toolPath);\n if(gArgs.GetChainName() != CBaseChainParams::MAIN)\n {\n arguments << \"--testnet\";\n }\n }\n\n std::atomic fStarted{false};\n CProcess process;\n std::string strStdout;\n std::string strError;\n std::string toolPath;\n std::vector arguments;\n bool toolExists = false;\n};\n\nQtumLedger::QtumLedger():\n d(0)\n{\n d = new QtumLedgerPriv();\n}\n\nQtumLedger::~QtumLedger()\n{\n if(d)\n delete d;\n d = 0;\n}\n\nbool QtumLedger::signCoinStake(const std::string &fingerprint, std::string &psbt)\n{\n \/\/ Check if tool exists\n if(!toolExists())\n return false;\n\n \/\/ Sign PSBT transaction\n if(isStarted())\n return false;\n\n if(!beginSignTx(fingerprint, psbt))\n return false;\n\n wait();\n\n return endSignTx(fingerprint, psbt);\n}\n\nbool QtumLedger::signBlockHeader(const std::string &fingerprint, const std::string &header, const std::string &path, std::vector &vchSig)\n{\n \/\/ Check if tool exists\n if(!toolExists())\n return false;\n\n \/\/ Sign block header\n if(isStarted())\n return false;\n\n if(!beginSignBlockHeader(fingerprint, header, path, vchSig))\n return false;\n\n wait();\n\n return endSignBlockHeader(fingerprint, header, path, vchSig);\n}\n\nbool QtumLedger::toolExists()\n{\n return d->toolExists;\n}\n\nbool QtumLedger::isStarted()\n{\n return d->fStarted;\n}\n\nvoid QtumLedger::wait()\n{\n if(d->fStarted)\n {\n d->process.waitForFinished();\n d->strStdout = d->process.readAllStandardOutput();\n d->strError = d->process.readAllStandardError();\n d->fStarted = false;\n }\n}\n\nbool QtumLedger::beginSignTx(const std::string &fingerprint, std::string &psbt)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"-f\" << fingerprint << \"signtx\" << psbt;\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endSignTx(const std::string &, std::string &psbt)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue data = json_get_object(jsonDocument);\n std::string psbtSigned = json_get_key_string(data, \"psbt\");\n if(!psbtSigned.empty())\n {\n psbt = psbtSigned;\n return true;\n }\n\n return false;\n}\n\nbool QtumLedger::beginSignBlockHeader(const std::string &fingerprint, const std::string &header, const std::string &path, std::vector &)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"-f\" << fingerprint << \"signheader\" << header << path;\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endSignBlockHeader(const std::string &, const std::string &, const std::string &, std::vector &vchSig)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue data = json_get_object(jsonDocument);\n std::string headerSigned = json_get_key_string(data, \"signature\");\n if(!headerSigned.empty())\n {\n vchSig = DecodeBase64(headerSigned.c_str());\n return vchSig.size() == CPubKey::COMPACT_SIGNATURE_SIZE;\n }\n\n return false;\n}\n\nbool QtumLedger::isConnected(const std::string &fingerprint)\n{\n \/\/ Check if a device is connected\n try\n {\n std::vector devices;\n if(enumerate(devices))\n {\n for(LedgerDevice device: devices)\n {\n if(device.fingerprint == fingerprint)\n return true;\n }\n }\n }\n catch(...)\n {}\n\n return false;\n}\n\nbool QtumLedger::enumerate(std::vector &devices)\n{\n \/\/ Enumerate hardware wallet devices\n if(isStarted())\n return false;\n\n if(!beginEnumerate(devices))\n return false;\n\n wait();\n\n return endEnumerate(devices);\n}\n\nbool QtumLedger::beginEnumerate(std::vector &)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"enumerate\";\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endEnumerate(std::vector &devices)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue jsonDevices = json_get_array(jsonDocument);\n for(size_t i = 0; i < jsonDevices.size(); i++)\n {\n const UniValue& jsonDevice = jsonDevices[i];\n if(!jsonDevice.isObject())\n return false;\n\n \/\/ Get device info\n UniValue data = json_get_object(jsonDevice);\n LedgerDevice device;\n device.fingerprint = json_get_key_string(data, \"fingerprint\");\n device.serial_number = json_get_key_string(data, \"serial_number\");\n device.type = json_get_key_string(data, \"type\");\n device.path = json_get_key_string(data, \"path\");\n device.error = json_get_key_string(data, \"error\");\n device.model = json_get_key_string(data, \"model\");\n device.code = json_get_key_string(data, \"code\");\n devices.push_back(device);\n }\n\n return devices.size() > 0;\n}\n\nQtumLedger &QtumLedger::instance()\n{\n static QtumLedger device;\n return device;\n}\nHide console for child process in Windows#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef WIN32\n#include \n#endif\n\nnamespace QtumLedger_NS {\n\/\/ Read json document\nUniValue json_read_doc(const std::string& jsondata)\n{\n UniValue v;\n v.read(jsondata);\n return v;\n}\n\n\/\/ Read json object\nUniValue json_get_object(const UniValue& jsondata)\n{\n UniValue v(UniValue::VOBJ);\n if(jsondata.isObject())\n v = jsondata.get_obj();\n return v;\n}\n\n\/\/ Read json array\nUniValue json_get_array(const UniValue& jsondata)\n{\n UniValue v(UniValue::VARR);\n if(jsondata.isArray())\n v = jsondata.get_array();\n return v;\n}\n\n\/\/ Get json string for key\nstd::string json_get_key_string(const UniValue& jsondata, std::string key)\n{\n UniValue v(UniValue::VSTR);\n if(jsondata.exists(key))\n {\n UniValue data = jsondata[key];\n if(data.isStr())\n v = data;\n }\n\n return v.get_str();\n}\n\n\/\/ Append data to vector\nstd::vector& operator<<(std::vector& os, const std::string& dt)\n{\n os.push_back(dt);\n return os;\n}\n\n\/\/ Start process from qtumd\nclass CProcess\n{\npublic:\n ~CProcess()\n {\n clean();\n }\n\n \/\/ Set process params\n void start(const std::string& prog, const std::vector &arg)\n {\n clean();\n m_program = prog;\n m_arguments = arg;\n }\n\n \/\/ Start and wait for it to finish\n void waitForFinished()\n {\n boost::asio::io_service svc;\n boost::asio::streambuf out, err;\n#ifdef WIN32\n boost::process::child child(m_program, ::boost::process::windows::create_no_window, boost::process::args(m_arguments),\n boost::process::std_out > out, boost::process::std_err > err, svc);\n#else\n boost::process::child child(m_program, boost::process::args(m_arguments),\n boost::process::std_out > out, boost::process::std_err > err, svc);\n#endif\n\n svc.run();\n child.wait();\n m_std_out = toString(&out);\n m_std_err = toString(&err);\n }\n\n \/\/ Read all standard output\n std::string readAllStandardOutput()\n {\n return m_std_out;\n }\n\n \/\/ Read all standard error\n std::string readAllStandardError()\n {\n return m_std_err;\n }\n\n \/\/ Clean process\n void clean()\n {\n m_program = \"\";\n m_std_out = \"\";\n m_std_err = \"\";\n }\n\n\nprivate:\n std::string toString(boost::asio::streambuf* stream)\n {\n std::istream is(stream);\n std::ostringstream os;\n is >> os.rdbuf();\n return os.str();\n }\n\nprivate:\n std::string m_program;\n std::vector m_arguments;\n std::string m_std_out;\n std::string m_std_err;\n};\n}\nusing namespace QtumLedger_NS;\n\nclass QtumLedgerPriv\n{\npublic:\n QtumLedgerPriv()\n {\n toolPath = gArgs.GetArg(\"-hwitoolpath\", \"\");\n toolExists = boost::filesystem::exists(toolPath);\n if(gArgs.GetChainName() != CBaseChainParams::MAIN)\n {\n arguments << \"--testnet\";\n }\n }\n\n std::atomic fStarted{false};\n CProcess process;\n std::string strStdout;\n std::string strError;\n std::string toolPath;\n std::vector arguments;\n bool toolExists = false;\n};\n\nQtumLedger::QtumLedger():\n d(0)\n{\n d = new QtumLedgerPriv();\n}\n\nQtumLedger::~QtumLedger()\n{\n if(d)\n delete d;\n d = 0;\n}\n\nbool QtumLedger::signCoinStake(const std::string &fingerprint, std::string &psbt)\n{\n \/\/ Check if tool exists\n if(!toolExists())\n return false;\n\n \/\/ Sign PSBT transaction\n if(isStarted())\n return false;\n\n if(!beginSignTx(fingerprint, psbt))\n return false;\n\n wait();\n\n return endSignTx(fingerprint, psbt);\n}\n\nbool QtumLedger::signBlockHeader(const std::string &fingerprint, const std::string &header, const std::string &path, std::vector &vchSig)\n{\n \/\/ Check if tool exists\n if(!toolExists())\n return false;\n\n \/\/ Sign block header\n if(isStarted())\n return false;\n\n if(!beginSignBlockHeader(fingerprint, header, path, vchSig))\n return false;\n\n wait();\n\n return endSignBlockHeader(fingerprint, header, path, vchSig);\n}\n\nbool QtumLedger::toolExists()\n{\n return d->toolExists;\n}\n\nbool QtumLedger::isStarted()\n{\n return d->fStarted;\n}\n\nvoid QtumLedger::wait()\n{\n if(d->fStarted)\n {\n d->process.waitForFinished();\n d->strStdout = d->process.readAllStandardOutput();\n d->strError = d->process.readAllStandardError();\n d->fStarted = false;\n }\n}\n\nbool QtumLedger::beginSignTx(const std::string &fingerprint, std::string &psbt)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"-f\" << fingerprint << \"signtx\" << psbt;\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endSignTx(const std::string &, std::string &psbt)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue data = json_get_object(jsonDocument);\n std::string psbtSigned = json_get_key_string(data, \"psbt\");\n if(!psbtSigned.empty())\n {\n psbt = psbtSigned;\n return true;\n }\n\n return false;\n}\n\nbool QtumLedger::beginSignBlockHeader(const std::string &fingerprint, const std::string &header, const std::string &path, std::vector &)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"-f\" << fingerprint << \"signheader\" << header << path;\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endSignBlockHeader(const std::string &, const std::string &, const std::string &, std::vector &vchSig)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue data = json_get_object(jsonDocument);\n std::string headerSigned = json_get_key_string(data, \"signature\");\n if(!headerSigned.empty())\n {\n vchSig = DecodeBase64(headerSigned.c_str());\n return vchSig.size() == CPubKey::COMPACT_SIGNATURE_SIZE;\n }\n\n return false;\n}\n\nbool QtumLedger::isConnected(const std::string &fingerprint)\n{\n \/\/ Check if a device is connected\n try\n {\n std::vector devices;\n if(enumerate(devices))\n {\n for(LedgerDevice device: devices)\n {\n if(device.fingerprint == fingerprint)\n return true;\n }\n }\n }\n catch(...)\n {}\n\n return false;\n}\n\nbool QtumLedger::enumerate(std::vector &devices)\n{\n \/\/ Enumerate hardware wallet devices\n if(isStarted())\n return false;\n\n if(!beginEnumerate(devices))\n return false;\n\n wait();\n\n return endEnumerate(devices);\n}\n\nbool QtumLedger::beginEnumerate(std::vector &)\n{\n \/\/ Execute command line\n std::vector arguments = d->arguments;\n arguments << \"enumerate\";\n d->process.start(d->toolPath, arguments);\n d->fStarted = true;\n\n return d->fStarted;\n}\n\nbool QtumLedger::endEnumerate(std::vector &devices)\n{\n \/\/ Decode command line results\n UniValue jsonDocument = json_read_doc(d->strStdout);\n UniValue jsonDevices = json_get_array(jsonDocument);\n for(size_t i = 0; i < jsonDevices.size(); i++)\n {\n const UniValue& jsonDevice = jsonDevices[i];\n if(!jsonDevice.isObject())\n return false;\n\n \/\/ Get device info\n UniValue data = json_get_object(jsonDevice);\n LedgerDevice device;\n device.fingerprint = json_get_key_string(data, \"fingerprint\");\n device.serial_number = json_get_key_string(data, \"serial_number\");\n device.type = json_get_key_string(data, \"type\");\n device.path = json_get_key_string(data, \"path\");\n device.error = json_get_key_string(data, \"error\");\n device.model = json_get_key_string(data, \"model\");\n device.code = json_get_key_string(data, \"code\");\n devices.push_back(device);\n }\n\n return devices.size() > 0;\n}\n\nQtumLedger &QtumLedger::instance()\n{\n static QtumLedger device;\n return device;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \"qsparql_tracker_direct_sync_result_p.h\"\n#include \"qsparql_tracker_direct.h\"\n#include \"qsparql_tracker_direct_driver_p.h\"\n#include \"qsparql_tracker_direct_result_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#define XSD_INTEGER\n#include \"..\/..\/kernel\/qsparqlxsd_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nstruct QTrackerDirectSyncResultPrivate\n{\n QTrackerDirectSyncResultPrivate(QTrackerDirectDriverPrivate *dpp, const QSparqlQueryOptions& options);\n ~QTrackerDirectSyncResultPrivate();\n TrackerSparqlCursor* cursor;\n int n_columns;\n QTrackerDirectDriverPrivate *driverPrivate;\n QSparqlQueryOptions options;\n};\n\nQTrackerDirectSyncResultPrivate::QTrackerDirectSyncResultPrivate(QTrackerDirectDriverPrivate *dpp,\n const QSparqlQueryOptions& options)\n : cursor(0), n_columns(-1), driverPrivate(dpp), options(options)\n{\n}\n\nQTrackerDirectSyncResultPrivate::~QTrackerDirectSyncResultPrivate()\n{\n if (cursor)\n g_object_unref(cursor);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQTrackerDirectSyncResult::QTrackerDirectSyncResult(QTrackerDirectDriverPrivate* p,\n const QString& query,\n QSparqlQuery::StatementType type,\n const QSparqlQueryOptions& options)\n{\n setQuery(query);\n setStatementType(type);\n d = new QTrackerDirectSyncResultPrivate(p, options);\n connect(p->driver, SIGNAL(closing()), this, SLOT(driverClosing()));\n}\n\nQTrackerDirectSyncResult::~QTrackerDirectSyncResult()\n{\n delete d;\n}\n\nvoid QTrackerDirectSyncResult::exec()\n{\n if (!d->driverPrivate->driver->isOpen()) {\n setLastError(QSparqlError(d->driverPrivate->error,\n QSparqlError::ConnectionError));\n return;\n }\n\n GError * error = 0;\n d->cursor = tracker_sparql_connection_query(d->driverPrivate->connection, query().toUtf8().constData(), 0, &error);\n if (error || !d->cursor) {\n setLastError(QSparqlError(QString::fromUtf8(error ? error->message : \"unknown error\"),\n error ? errorCodeToType(error->code) : QSparqlError::StatementError,\n error ? error->code : -1));\n if (error)\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n }\n}\n\nvoid QTrackerDirectSyncResult::update()\n{\n if (!d->driverPrivate->driver->isOpen()) {\n setLastError(QSparqlError(d->driverPrivate->error,\n QSparqlError::ConnectionError));\n return;\n }\n\n GError * error = 0;\n tracker_sparql_connection_update(d->driverPrivate->connection,\n query().toUtf8().constData(),\n qSparqlPriorityToGlib(d->options.priority()),\n 0,\n &error);\n if (error) {\n setLastError(QSparqlError(QString::fromUtf8(error->message),\n errorCodeToType(error->code),\n error->code));\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n }\n}\n\nvoid QTrackerDirectSyncResult::driverClosing()\n{\n if (!isFinished()) {\n \/\/ If connection is closed before all results have been accessed set the result to be in error\n setLastError(QSparqlError(\n QString::fromUtf8(\"QSparqlConnection closed before QSparqlResult\"),\n QSparqlError::ConnectionError));\n }\n if (d->cursor) {\n g_object_unref(d->cursor);\n d->cursor = 0;\n }\n qWarning() << \"QTrackerDirectSyncResult: QSparqlConnection closed before QSparqlResult with query:\" << query();\n}\n\nbool QTrackerDirectSyncResult::next()\n{\n if (!d->cursor)\n return false;\n\n GError * error = 0;\n const gboolean active = tracker_sparql_cursor_next(d->cursor, 0, &error);\n\n \/\/ if this is an ask query, get the result\n if (isBool() && active && tracker_sparql_cursor_get_value_type(d->cursor, 0) == TRACKER_SPARQL_VALUE_TYPE_BOOLEAN) {\n const gboolean value = tracker_sparql_cursor_get_boolean(d->cursor, 0);\n setBoolValue(value != FALSE);\n }\n\n if (error) {\n setLastError(QSparqlError(QString::fromUtf8(error->message),\n errorCodeToType(error->code),\n error->code));\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n g_object_unref(d->cursor);\n d->cursor = 0;\n return false;\n }\n\n if (!active) {\n g_object_unref(d->cursor);\n d->cursor = 0;\n updatePos(QSparql::AfterLastRow);\n return false;\n }\n const int oldPos = pos();\n if (oldPos == QSparql::BeforeFirstRow)\n updatePos(0);\n else\n updatePos(oldPos + 1);\n return true;\n}\n\nQSparqlResultRow QTrackerDirectSyncResult::current() const\n{\n \/\/ Note: this function reads and constructs the data again every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QSparqlResultRow();\n\n QSparqlResultRow resultRow;\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n for (int i = 0; i < d->n_columns; i++) {\n resultRow.append(binding(i));\n }\n return resultRow;\n}\n\nQSparqlBinding QTrackerDirectSyncResult::binding(int i) const\n{\n \/\/ Note: this function reads and constructs the data again every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QSparqlBinding();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QSparqlBinding();\n\n const gchar* name = tracker_sparql_cursor_get_variable_name(d->cursor, i);\n const QVariant& value = readVariant(d->cursor, i);\n\n \/\/ A special case: we store TRACKER_SPARQL_VALUE_TYPE_INTEGER as longlong,\n \/\/ but its data type uri should be xsd:integer. Set it manually here.\n QSparqlBinding b;\n b.setName(QString::fromUtf8(name));\n if (value.type() == QVariant::LongLong) {\n b.setValue(value.toString(), *XSD::Integer());\n }\n else {\n b.setValue(value);\n }\n return b;\n}\n\nQVariant QTrackerDirectSyncResult::value(int i) const\n{\n \/\/ Note: this function re-constructs the data every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QVariant();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QVariant();\n\n return readVariant(d->cursor, i);\n}\n\nQString QTrackerDirectSyncResult::stringValue(int i) const\n{\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QString();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QString();\n\n return QString::fromUtf8(tracker_sparql_cursor_get_string(d->cursor, i, 0));\n}\n\nbool QTrackerDirectSyncResult::isFinished() const\n{\n return !d->cursor;\n}\n\nbool QTrackerDirectSyncResult::hasFeature(QSparqlResult::Feature feature) const\n{\n switch (feature) {\n case QSparqlResult::Sync:\n case QSparqlResult::ForwardOnly:\n return true;\n case QSparqlResult::QuerySize:\n return false;\n default:\n return false;\n }\n}\n\nQT_END_NAMESPACE\nMake tracker direct sync result update the result position in next() also when the connection has been destroyed\/****************************************************************************\n**\n** Copyright (C) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \"qsparql_tracker_direct_sync_result_p.h\"\n#include \"qsparql_tracker_direct.h\"\n#include \"qsparql_tracker_direct_driver_p.h\"\n#include \"qsparql_tracker_direct_result_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#define XSD_INTEGER\n#include \"..\/..\/kernel\/qsparqlxsd_p.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nstruct QTrackerDirectSyncResultPrivate\n{\n QTrackerDirectSyncResultPrivate(QTrackerDirectDriverPrivate *dpp, const QSparqlQueryOptions& options);\n ~QTrackerDirectSyncResultPrivate();\n TrackerSparqlCursor* cursor;\n int n_columns;\n QTrackerDirectDriverPrivate *driverPrivate;\n QSparqlQueryOptions options;\n};\n\nQTrackerDirectSyncResultPrivate::QTrackerDirectSyncResultPrivate(QTrackerDirectDriverPrivate *dpp,\n const QSparqlQueryOptions& options)\n : cursor(0), n_columns(-1), driverPrivate(dpp), options(options)\n{\n}\n\nQTrackerDirectSyncResultPrivate::~QTrackerDirectSyncResultPrivate()\n{\n if (cursor)\n g_object_unref(cursor);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nQTrackerDirectSyncResult::QTrackerDirectSyncResult(QTrackerDirectDriverPrivate* p,\n const QString& query,\n QSparqlQuery::StatementType type,\n const QSparqlQueryOptions& options)\n{\n setQuery(query);\n setStatementType(type);\n d = new QTrackerDirectSyncResultPrivate(p, options);\n connect(p->driver, SIGNAL(closing()), this, SLOT(driverClosing()));\n}\n\nQTrackerDirectSyncResult::~QTrackerDirectSyncResult()\n{\n delete d;\n}\n\nvoid QTrackerDirectSyncResult::exec()\n{\n if (!d->driverPrivate->driver->isOpen()) {\n setLastError(QSparqlError(d->driverPrivate->error,\n QSparqlError::ConnectionError));\n return;\n }\n\n GError * error = 0;\n d->cursor = tracker_sparql_connection_query(d->driverPrivate->connection, query().toUtf8().constData(), 0, &error);\n if (error || !d->cursor) {\n setLastError(QSparqlError(QString::fromUtf8(error ? error->message : \"unknown error\"),\n error ? errorCodeToType(error->code) : QSparqlError::StatementError,\n error ? error->code : -1));\n if (error)\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n }\n}\n\nvoid QTrackerDirectSyncResult::update()\n{\n if (!d->driverPrivate->driver->isOpen()) {\n setLastError(QSparqlError(d->driverPrivate->error,\n QSparqlError::ConnectionError));\n return;\n }\n\n GError * error = 0;\n tracker_sparql_connection_update(d->driverPrivate->connection,\n query().toUtf8().constData(),\n qSparqlPriorityToGlib(d->options.priority()),\n 0,\n &error);\n if (error) {\n setLastError(QSparqlError(QString::fromUtf8(error->message),\n errorCodeToType(error->code),\n error->code));\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n }\n}\n\nvoid QTrackerDirectSyncResult::driverClosing()\n{\n if (!isFinished()) {\n \/\/ If connection is closed before all results have been accessed set the result to be in error\n setLastError(QSparqlError(\n QString::fromUtf8(\"QSparqlConnection closed before QSparqlResult\"),\n QSparqlError::ConnectionError));\n }\n if (d->cursor) {\n g_object_unref(d->cursor);\n d->cursor = 0;\n }\n qWarning() << \"QTrackerDirectSyncResult: QSparqlConnection closed before QSparqlResult with query:\" << query();\n}\n\nbool QTrackerDirectSyncResult::next()\n{\n if (!d->cursor) {\n \/\/ The cursor may have been unreferenced because the connection was deleted\n \/\/ and now the user is calling next(), so set the row here\n updatePos(QSparql::AfterLastRow);\n return false;\n }\n\n GError * error = 0;\n const gboolean active = tracker_sparql_cursor_next(d->cursor, 0, &error);\n\n \/\/ if this is an ask query, get the result\n if (isBool() && active && tracker_sparql_cursor_get_value_type(d->cursor, 0) == TRACKER_SPARQL_VALUE_TYPE_BOOLEAN) {\n const gboolean value = tracker_sparql_cursor_get_boolean(d->cursor, 0);\n setBoolValue(value != FALSE);\n }\n\n if (error) {\n setLastError(QSparqlError(QString::fromUtf8(error->message),\n errorCodeToType(error->code),\n error->code));\n g_error_free(error);\n qWarning() << \"QTrackerDirectSyncResult:\" << lastError() << query();\n g_object_unref(d->cursor);\n d->cursor = 0;\n return false;\n }\n\n if (!active) {\n g_object_unref(d->cursor);\n d->cursor = 0;\n updatePos(QSparql::AfterLastRow);\n return false;\n }\n const int oldPos = pos();\n if (oldPos == QSparql::BeforeFirstRow)\n updatePos(0);\n else\n updatePos(oldPos + 1);\n return true;\n}\n\nQSparqlResultRow QTrackerDirectSyncResult::current() const\n{\n \/\/ Note: this function reads and constructs the data again every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QSparqlResultRow();\n\n QSparqlResultRow resultRow;\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n for (int i = 0; i < d->n_columns; i++) {\n resultRow.append(binding(i));\n }\n return resultRow;\n}\n\nQSparqlBinding QTrackerDirectSyncResult::binding(int i) const\n{\n \/\/ Note: this function reads and constructs the data again every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QSparqlBinding();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QSparqlBinding();\n\n const gchar* name = tracker_sparql_cursor_get_variable_name(d->cursor, i);\n const QVariant& value = readVariant(d->cursor, i);\n\n \/\/ A special case: we store TRACKER_SPARQL_VALUE_TYPE_INTEGER as longlong,\n \/\/ but its data type uri should be xsd:integer. Set it manually here.\n QSparqlBinding b;\n b.setName(QString::fromUtf8(name));\n if (value.type() == QVariant::LongLong) {\n b.setValue(value.toString(), *XSD::Integer());\n }\n else {\n b.setValue(value);\n }\n return b;\n}\n\nQVariant QTrackerDirectSyncResult::value(int i) const\n{\n \/\/ Note: this function re-constructs the data every time it's called.\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QVariant();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QVariant();\n\n return readVariant(d->cursor, i);\n}\n\nQString QTrackerDirectSyncResult::stringValue(int i) const\n{\n if (!d->cursor || pos() == QSparql::BeforeFirstRow || pos() == QSparql::AfterLastRow)\n return QString();\n\n \/\/ get the no. of columns only once; it won't change between rows\n if (d->n_columns < 0)\n d->n_columns = tracker_sparql_cursor_get_n_columns(d->cursor);\n\n if (i < 0 || i >= d->n_columns)\n return QString();\n\n return QString::fromUtf8(tracker_sparql_cursor_get_string(d->cursor, i, 0));\n}\n\nbool QTrackerDirectSyncResult::isFinished() const\n{\n return !d->cursor;\n}\n\nbool QTrackerDirectSyncResult::hasFeature(QSparqlResult::Feature feature) const\n{\n switch (feature) {\n case QSparqlResult::Sync:\n case QSparqlResult::ForwardOnly:\n return true;\n case QSparqlResult::QuerySize:\n return false;\n default:\n return false;\n }\n}\n\nQT_END_NAMESPACE\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 \"content\/renderer\/renderer_webstoragearea_impl.h\"\n\n#include \"content\/common\/dom_storage_messages.h\"\n#include \"content\/renderer\/render_thread.h\"\n#include \"content\/renderer\/render_view.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebURL.h\"\n\nusing WebKit::WebString;\nusing WebKit::WebURL;\n\nRendererWebStorageAreaImpl::RendererWebStorageAreaImpl(\n int64 namespace_id, const WebString& origin) {\n RenderThread::current()->Send(\n new DOMStorageHostMsg_StorageAreaId(namespace_id, origin,\n &storage_area_id_));\n}\n\nRendererWebStorageAreaImpl::~RendererWebStorageAreaImpl() {\n}\n\nunsigned RendererWebStorageAreaImpl::length() {\n unsigned length;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Length(storage_area_id_, &length));\n return length;\n}\n\nWebString RendererWebStorageAreaImpl::key(unsigned index) {\n NullableString16 key;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Key(storage_area_id_, index, &key));\n return key;\n}\n\nWebString RendererWebStorageAreaImpl::getItem(const WebString& key) {\n NullableString16 value;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_GetItem(storage_area_id_, key, &value));\n return value;\n}\n\nvoid RendererWebStorageAreaImpl::setItem(\n const WebString& key, const WebString& value, const WebURL& url,\n WebStorageArea::Result& result, WebString& old_value_webkit) {\n NullableString16 old_value;\n RenderThread::current()->Send(new DOMStorageHostMsg_SetItem(\n storage_area_id_, key, value, url, &result, &old_value));\n old_value_webkit = old_value;\n}\n\nvoid RendererWebStorageAreaImpl::removeItem(\n const WebString& key, const WebURL& url, WebString& old_value_webkit) {\n NullableString16 old_value;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_RemoveItem(storage_area_id_, key, url, &old_value));\n old_value_webkit = old_value;\n}\n\nvoid RendererWebStorageAreaImpl::clear(\n const WebURL& url, bool& cleared_something) {\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Clear(storage_area_id_, url, &cleared_something));\n}\nDefend against very large localstorage key names and values.\/\/ 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 \"content\/renderer\/renderer_webstoragearea_impl.h\"\n\n#include \"content\/common\/dom_storage_messages.h\"\n#include \"content\/renderer\/render_thread.h\"\n#include \"content\/renderer\/render_view.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebStorageNamespace.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebURL.h\"\n\nusing WebKit::WebStorageNamespace;\nusing WebKit::WebString;\nusing WebKit::WebURL;\n\nRendererWebStorageAreaImpl::RendererWebStorageAreaImpl(\n int64 namespace_id, const WebString& origin) {\n RenderThread::current()->Send(\n new DOMStorageHostMsg_StorageAreaId(namespace_id, origin,\n &storage_area_id_));\n}\n\nRendererWebStorageAreaImpl::~RendererWebStorageAreaImpl() {\n}\n\nunsigned RendererWebStorageAreaImpl::length() {\n unsigned length;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Length(storage_area_id_, &length));\n return length;\n}\n\nWebString RendererWebStorageAreaImpl::key(unsigned index) {\n NullableString16 key;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Key(storage_area_id_, index, &key));\n return key;\n}\n\nWebString RendererWebStorageAreaImpl::getItem(const WebString& key) {\n NullableString16 value;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_GetItem(storage_area_id_, key, &value));\n return value;\n}\n\nvoid RendererWebStorageAreaImpl::setItem(\n const WebString& key, const WebString& value, const WebURL& url,\n WebStorageArea::Result& result, WebString& old_value_webkit) {\n const size_t kMaxKeyValueLength = WebStorageNamespace::m_localStorageQuota;\n if (key.length() + value.length() > kMaxKeyValueLength) {\n result = ResultBlockedByQuota;\n return;\n }\n NullableString16 old_value;\n RenderThread::current()->Send(new DOMStorageHostMsg_SetItem(\n storage_area_id_, key, value, url, &result, &old_value));\n old_value_webkit = old_value;\n}\n\nvoid RendererWebStorageAreaImpl::removeItem(\n const WebString& key, const WebURL& url, WebString& old_value_webkit) {\n NullableString16 old_value;\n RenderThread::current()->Send(\n new DOMStorageHostMsg_RemoveItem(storage_area_id_, key, url, &old_value));\n old_value_webkit = old_value;\n}\n\nvoid RendererWebStorageAreaImpl::clear(\n const WebURL& url, bool& cleared_something) {\n RenderThread::current()->Send(\n new DOMStorageHostMsg_Clear(storage_area_id_, url, &cleared_something));\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\nnamespace Renderer {\n\tHgMath::mat4f ProjectionMatrix;\n\tHgMath::mat4f ViewMatrix;\n\n\tvoid Init() {\n\t\tRENDERER()->Init();\n\t}\n}\n\nRenderBackend* RENDERER() {\n\t\/\/replace with some kind of configure based factory thing\n\tstatic RenderBackend* api = OGLBackend::Create();\n\treturn api;\n}\n\nvoid RenderBackend::setup_viewports(uint16_t width, uint16_t height) {\n\tuint8_t i = 0;\n\n\tview_port[i].x = view_port[i].y = 0;\n\tview_port[i].width = width;\n\tview_port[i].height = height;\n\t++i;\n\n\tview_port[i].x = view_port[i].y = 0;\n\tview_port[i].width = width \/ 2;\n\tview_port[i].height = height;\n\t++i;\n\n\tview_port[i].x = width \/ 2;\n\tview_port[i].y = 0;\n\tview_port[i].width = width \/ 2;\n\tview_port[i].height = height;\n}\n\nstatic void submit_for_render_serial(uint8_t viewport_idx, HgCamera* camera, RenderData* renderData, const float* worldSpaceMatrix) {\n\tRENDERER()->Viewport(viewport_idx);\n\n\t\/\/load texture data to GPU here. Can this be made to be done right after loading the image data, regardless of thread?\n\tif (renderData->updateTextures()) {\n\t\trenderData->updateGpuTextures();\n\t\trenderData->updateTextures(false);\n\t}\n\n\tHgShader* shader = renderData->shader;\n\tif (shader) {\n\t\tshader->enable();\n\t\t\/\/perspective and camera probably need to be rebound here as well. (if the shader program changed. uniforms are local to shader programs).\n\t\t\/\/we could give each shader program a \"needsGlobalUniforms\" flag that is reset every frame, to check if uniforms need to be updated\n\t\t\/\/shader->setGlobalUniforms(*camera);\n\t\t\/\/const auto spacial = e->getSpacialData();\n\t\tshader->uploadMatrices(worldSpaceMatrix, Renderer::ProjectionMatrix, Renderer::ViewMatrix);\n\t\tshader->setLocalUniforms(*renderData);\n\t}\n\n\trenderData->render();\n}\n\nvoid Renderer::Render(uint8_t viewportIdx, HgCamera* camera, const HgMath::mat4f& projection, RenderQueue* queue) {\n\tProjectionMatrix = projection;\n\tViewMatrix = camera->toViewMatrix();\n\n\tfor (auto& renderInstance : queue->getOpaqueQueue()) {\n\t\tsubmit_for_render_serial(viewportIdx, camera, renderInstance.renderData.get(), renderInstance.worldSpaceMatrix);\n\t}\n\n\tfor (auto& renderInstance : queue->getTransparentQueue()) {\n\t\tsubmit_for_render_serial(viewportIdx, camera, renderInstance.renderData.get(), renderInstance.worldSpaceMatrix);\n\t}\n}\n\nvoid RenderQueue::Enqueue(const HgEntity* e)\n{\n\tconst auto worldSpaceMatrix = e->computeWorldSpaceMatrix();\n\tauto renderData = e->getRenderDataPtr();\n\n\tif (renderData->renderFlags.transparent) {\n\t\t\/\/order by distance back to front?\n\t\tm_transparentEntities.emplace_back(worldSpaceMatrix, renderData, e->getDrawOrder());\n\t}\n\telse {\n\t\t\/\/order by distance front to back?\n\t\tm_opaqueEntities.emplace_back(worldSpaceMatrix, renderData);\n\t}\n}\n\nvoid RenderQueue::Finalize()\n{\n\tsort(m_opaqueEntities);\n\tsort(m_transparentEntities);\n}\n\nvoid RenderQueue::sort(std::vector& v)\n{\n\tstd::sort(v.begin(), v.end(),\n\t\t[](RenderInstance& a, RenderInstance& b)\n\t{\n\t\treturn a.drawOrder > b.drawOrder;\n\t});\n}\ndraw order for opaque things too#include \n#include \n\n#include \n#include \n\nnamespace Renderer {\n\tHgMath::mat4f ProjectionMatrix;\n\tHgMath::mat4f ViewMatrix;\n\n\tvoid Init() {\n\t\tRENDERER()->Init();\n\t}\n}\n\nRenderBackend* RENDERER() {\n\t\/\/replace with some kind of configure based factory thing\n\tstatic RenderBackend* api = OGLBackend::Create();\n\treturn api;\n}\n\nvoid RenderBackend::setup_viewports(uint16_t width, uint16_t height) {\n\tuint8_t i = 0;\n\n\tview_port[i].x = view_port[i].y = 0;\n\tview_port[i].width = width;\n\tview_port[i].height = height;\n\t++i;\n\n\tview_port[i].x = view_port[i].y = 0;\n\tview_port[i].width = width \/ 2;\n\tview_port[i].height = height;\n\t++i;\n\n\tview_port[i].x = width \/ 2;\n\tview_port[i].y = 0;\n\tview_port[i].width = width \/ 2;\n\tview_port[i].height = height;\n}\n\nstatic void submit_for_render_serial(uint8_t viewport_idx, HgCamera* camera, RenderData* renderData, const float* worldSpaceMatrix) {\n\tRENDERER()->Viewport(viewport_idx);\n\n\t\/\/load texture data to GPU here. Can this be made to be done right after loading the image data, regardless of thread?\n\tif (renderData->updateTextures()) {\n\t\trenderData->updateGpuTextures();\n\t\trenderData->updateTextures(false);\n\t}\n\n\tHgShader* shader = renderData->shader;\n\tif (shader) {\n\t\tshader->enable();\n\t\t\/\/perspective and camera probably need to be rebound here as well. (if the shader program changed. uniforms are local to shader programs).\n\t\t\/\/we could give each shader program a \"needsGlobalUniforms\" flag that is reset every frame, to check if uniforms need to be updated\n\t\t\/\/shader->setGlobalUniforms(*camera);\n\t\t\/\/const auto spacial = e->getSpacialData();\n\t\tshader->uploadMatrices(worldSpaceMatrix, Renderer::ProjectionMatrix, Renderer::ViewMatrix);\n\t\tshader->setLocalUniforms(*renderData);\n\t}\n\n\trenderData->render();\n}\n\nvoid Renderer::Render(uint8_t viewportIdx, HgCamera* camera, const HgMath::mat4f& projection, RenderQueue* queue) {\n\tProjectionMatrix = projection;\n\tViewMatrix = camera->toViewMatrix();\n\n\tfor (auto& renderInstance : queue->getOpaqueQueue()) {\n\t\tsubmit_for_render_serial(viewportIdx, camera, renderInstance.renderData.get(), renderInstance.worldSpaceMatrix);\n\t}\n\n\tfor (auto& renderInstance : queue->getTransparentQueue()) {\n\t\tsubmit_for_render_serial(viewportIdx, camera, renderInstance.renderData.get(), renderInstance.worldSpaceMatrix);\n\t}\n}\n\nvoid RenderQueue::Enqueue(const HgEntity* e)\n{\n\tconst auto worldSpaceMatrix = e->computeWorldSpaceMatrix();\n\tauto renderData = e->getRenderDataPtr();\n\n\tif (renderData->renderFlags.transparent) {\n\t\t\/\/order by distance back to front?\n\t\tm_transparentEntities.emplace_back(worldSpaceMatrix, renderData, e->getDrawOrder());\n\t}\n\telse {\n\t\t\/\/order by distance front to back?\n\t\tm_opaqueEntities.emplace_back(worldSpaceMatrix, renderData, e->getDrawOrder());\n\t}\n}\n\nvoid RenderQueue::Finalize()\n{\n\tsort(m_opaqueEntities);\n\tsort(m_transparentEntities);\n}\n\nvoid RenderQueue::sort(std::vector& v)\n{\n\tstd::sort(v.begin(), v.end(),\n\t\t[](RenderInstance& a, RenderInstance& b)\n\t{\n\t\treturn a.drawOrder > b.drawOrder;\n\t});\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/extensions\/api\/file_system\/file_system_api.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n\nusing extensions::FileSystemChooseEntryFunction;\n\nclass FileSystemApiTest : public extensions::PlatformAppBrowserTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);\n test_root_folder_ = test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"file_system\");\n }\n\n virtual void TearDown() OVERRIDE {\n FileSystemChooseEntryFunction::StopSkippingPickerForTest();\n extensions::PlatformAppBrowserTest::TearDown();\n };\n\n protected:\n base::FilePath TempFilePath(const std::string& destination_name,\n bool copy_gold) {\n if (!temp_dir_.CreateUniqueTempDir()) {\n ADD_FAILURE() << \"CreateUniqueTempDir failed\";\n return base::FilePath();\n }\n base::FilePath destination = temp_dir_.path().AppendASCII(destination_name);\n if (copy_gold) {\n base::FilePath source = test_root_folder_.AppendASCII(\"gold.txt\");\n EXPECT_TRUE(file_util::CopyFile(source, destination));\n }\n return destination;\n }\n\n base::FilePath test_root_folder_;\n base::ScopedTempDir temp_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPath) {\n base::FilePath test_file = test_root_folder_.AppendASCII(\"gold.txt\");\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/get_display_path\"))\n << message_;\n}\n\n#if defined(OS_WIN) || defined(OS_POSIX)\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettify) {\n#if defined(OS_WIN)\n int override = base::DIR_PROFILE;\n#elif defined(OS_POSIX)\n int override = base::DIR_HOME;\n#endif\n ASSERT_TRUE(PathService::OverrideAndCreateIfNeeded(override,\n test_root_folder_, false));\n\n base::FilePath test_file = test_root_folder_.AppendASCII(\"gold.txt\");\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_display_path_prettify\")) << message_;\n}\n#endif\n\n#if defined(OS_MACOSX)\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiGetDisplayPathPrettifyMac) {\n \/\/ On Mac, \"test.localized\" will be localized into just \"test\".\n base::FilePath test_path = TempFilePath(\"test.localized\", false);\n ASSERT_TRUE(file_util::CreateDirectory(test_path));\n\n base::FilePath test_file = test_path.AppendASCII(\"gold.txt\");\n base::FilePath source = test_root_folder_.AppendASCII(\"gold.txt\");\n EXPECT_TRUE(file_util::CopyFile(source, test_file));\n\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_display_path_prettify_mac\")) << message_;\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_existing\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiInvalidChooseEntryTypeTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/invalid_choose_file_type\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenWritableExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_writable_existing\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenWritableExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_writable_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenCancelTest) {\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_cancel\"))\n << message_;\n}\n\n#if defined(OS_LINUX)\n\/\/ Disabled on linux due to crbug.com\/178679.\n#define MAYBE_FileSystemApiSaveBackgroundTest \\\n DISABLED_FileSystemApiOpenBackgroundTest\n#else\n#define MAYBE_FileSystemApiOpenBackgroundTest FileSystemApiOpenBackgroundTest\n#endif\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n MAYBE_FileSystemApiOpenBackgroundTest) {\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_background\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileTest) {\n base::FilePath test_file = TempFilePath(\"save_new.txt\", false);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_new\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"save_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_existing\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiSaveNewFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"save_new.txt\", false);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_new_with_write\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiSaveExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"save_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/save_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveCancelTest) {\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_cancel\"))\n << message_;\n}\n\n#if defined(OS_LINUX)\n\/\/ Disabled on linux due to crbug.com\/178679.\n#define MAYBE_FileSystemApiSaveBackgroundTest \\\n DISABLED_FileSystemApiSaveBackgroundTest\n#else\n#define MAYBE_FileSystemApiSaveBackgroundTest FileSystemApiSaveBackgroundTest\n#endif\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n MAYBE_FileSystemApiSaveBackgroundTest) {\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_background\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_writable_file_entry\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiGetWritableWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_writable_file_entry_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/is_writable_file_entry\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetEntryId) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_entry_id\")) << message_;\n}\nFix #define copy paste error... (sigh).. Originally introduced here: https:\/\/src.chromium.org\/viewvc\/chrome?view=rev&revision=185259\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/extensions\/api\/file_system\/file_system_api.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n\nusing extensions::FileSystemChooseEntryFunction;\n\nclass FileSystemApiTest : public extensions::PlatformAppBrowserTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);\n test_root_folder_ = test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"file_system\");\n }\n\n virtual void TearDown() OVERRIDE {\n FileSystemChooseEntryFunction::StopSkippingPickerForTest();\n extensions::PlatformAppBrowserTest::TearDown();\n };\n\n protected:\n base::FilePath TempFilePath(const std::string& destination_name,\n bool copy_gold) {\n if (!temp_dir_.CreateUniqueTempDir()) {\n ADD_FAILURE() << \"CreateUniqueTempDir failed\";\n return base::FilePath();\n }\n base::FilePath destination = temp_dir_.path().AppendASCII(destination_name);\n if (copy_gold) {\n base::FilePath source = test_root_folder_.AppendASCII(\"gold.txt\");\n EXPECT_TRUE(file_util::CopyFile(source, destination));\n }\n return destination;\n }\n\n base::FilePath test_root_folder_;\n base::ScopedTempDir temp_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPath) {\n base::FilePath test_file = test_root_folder_.AppendASCII(\"gold.txt\");\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/get_display_path\"))\n << message_;\n}\n\n#if defined(OS_WIN) || defined(OS_POSIX)\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetDisplayPathPrettify) {\n#if defined(OS_WIN)\n int override = base::DIR_PROFILE;\n#elif defined(OS_POSIX)\n int override = base::DIR_HOME;\n#endif\n ASSERT_TRUE(PathService::OverrideAndCreateIfNeeded(override,\n test_root_folder_, false));\n\n base::FilePath test_file = test_root_folder_.AppendASCII(\"gold.txt\");\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_display_path_prettify\")) << message_;\n}\n#endif\n\n#if defined(OS_MACOSX)\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiGetDisplayPathPrettifyMac) {\n \/\/ On Mac, \"test.localized\" will be localized into just \"test\".\n base::FilePath test_path = TempFilePath(\"test.localized\", false);\n ASSERT_TRUE(file_util::CreateDirectory(test_path));\n\n base::FilePath test_file = test_path.AppendASCII(\"gold.txt\");\n base::FilePath source = test_root_folder_.AppendASCII(\"gold.txt\");\n EXPECT_TRUE(file_util::CopyFile(source, test_file));\n\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_display_path_prettify_mac\")) << message_;\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_existing\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiInvalidChooseEntryTypeTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/invalid_choose_file_type\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenWritableExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_writable_existing\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiOpenWritableExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"open_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/open_writable_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiOpenCancelTest) {\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_cancel\"))\n << message_;\n}\n\n#if defined(OS_LINUX)\n\/\/ Disabled on linux due to crbug.com\/178679.\n#define MAYBE_FileSystemApiOpenBackgroundTest \\\n DISABLED_FileSystemApiOpenBackgroundTest\n#else\n#define MAYBE_FileSystemApiOpenBackgroundTest FileSystemApiOpenBackgroundTest\n#endif\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n MAYBE_FileSystemApiOpenBackgroundTest) {\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/open_background\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveNewFileTest) {\n base::FilePath test_file = TempFilePath(\"save_new.txt\", false);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_new\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveExistingFileTest) {\n base::FilePath test_file = TempFilePath(\"save_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_existing\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiSaveNewFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"save_new.txt\", false);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_new_with_write\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiSaveExistingFileWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"save_existing.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/save_existing_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiSaveCancelTest) {\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysCancelForTest();\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_cancel\"))\n << message_;\n}\n\n#if defined(OS_LINUX)\n\/\/ Disabled on linux due to crbug.com\/178679.\n#define MAYBE_FileSystemApiSaveBackgroundTest \\\n DISABLED_FileSystemApiSaveBackgroundTest\n#else\n#define MAYBE_FileSystemApiSaveBackgroundTest FileSystemApiSaveBackgroundTest\n#endif\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n MAYBE_FileSystemApiSaveBackgroundTest) {\n ASSERT_TRUE(RunPlatformAppTest(\"api_test\/file_system\/save_background\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetWritableTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_writable_file_entry\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest,\n FileSystemApiGetWritableWithWriteTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_writable_file_entry_with_write\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiIsWritableTest) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/is_writable_file_entry\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(FileSystemApiTest, FileSystemApiGetEntryId) {\n base::FilePath test_file = TempFilePath(\"writable.txt\", true);\n ASSERT_FALSE(test_file.empty());\n FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(\n &test_file);\n ASSERT_TRUE(RunPlatformAppTest(\n \"api_test\/file_system\/get_entry_id\")) << message_;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"SDL.h\"\n\n#include \"Debug.h\"\n#include \"Platform.h\"\n#include \"String.h\"\n\n#if defined(_WINDOWS)\n#include \n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n#include \n#include \n#include \n#include \n#endif\n\nconst std::string Platform::XDGDataHome = \"XDG_DATA_HOME\";\nconst std::string Platform::XDGConfigHome = \"XDG_CONFIG_HOME\";\n\nstd::string Platform::getHomeEnv()\n{\n\tconst char *homeEnvPtr = SDL_getenv(\"HOME\");\n\treturn (homeEnvPtr != nullptr) ? std::string(homeEnvPtr) : std::string();\n}\n\nstd::string Platform::getXDGDataHomeEnv()\n{\n\tconst char *xdgEnv = SDL_getenv(Platform::XDGDataHome.c_str());\n\treturn (xdgEnv != nullptr) ? std::string(xdgEnv) :\n\t\t(Platform::getHomeEnv() + \"\/.local\/share\");\n}\n\nstd::string Platform::getXDGConfigHomeEnv()\n{\n\tconst char *xdgEnv = SDL_getenv(Platform::XDGConfigHome.c_str());\n\treturn (xdgEnv != nullptr) ? std::string(xdgEnv) :\n\t\t(Platform::getHomeEnv() + \"\/.config\");\n}\n\nstd::string Platform::getPlatform()\n{\n\treturn std::string(SDL_GetPlatform());\n}\n\nstd::string Platform::getBasePath()\n{\n\t\/\/ Allocate the base path from SDL.\n\tchar *basePathPtr = SDL_GetBasePath();\n\n\tif (basePathPtr == nullptr)\n\t{\n\t\tDebugWarning(\"SDL_GetBasePath() not available on this platform.\");\n\t\tbasePathPtr = SDL_strdup(\".\/\");\n\t}\n\n\tconst std::string basePathString(basePathPtr);\n\tSDL_free(basePathPtr);\n\n\t\/\/ Convert Windows backslashes to forward slashes.\n\treturn String::replace(basePathString, '\\\\', '\/');\n}\n\nstd::string Platform::getOptionsPath()\n{\n\tconst std::string platform = Platform::getPlatform();\n\n\tif (platform == \"Windows\")\n\t{\n\t\t\/\/ SDL_GetPrefPath() creates the desired folder if it doesn't exist.\n\t\tchar *optionsPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"options\");\n\n\t\tif (optionsPathPtr == nullptr)\n\t\t{\n\t\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\t\toptionsPathPtr = SDL_strdup(\"options\/\");\n\t\t}\n\n\t\tconst std::string optionsPathString(optionsPathPtr);\n\t\tSDL_free(optionsPathPtr);\n\n\t\t\/\/ Convert Windows backslashes to forward slashes.\n\t\treturn String::replace(optionsPathString, '\\\\', '\/');\n\t}\n\telse if (platform == \"Linux\")\n\t{\n\t\treturn Platform::getXDGConfigHomeEnv() + \"\/OpenTESArena\/options\/\";\n\t}\n\telse if (platform == \"Mac OS X\")\n\t{\n\t\treturn Platform::getHomeEnv() + \"\/Library\/Preferences\/OpenTESArena\/options\/\";\n\t}\n\telse\n\t{\n\t\tDebugWarning(\"No default options path on this platform.\");\n\t\treturn \"OpenTESArena\/options\/\";\n\t}\n}\n\nstd::string Platform::getScreenshotPath()\n{\n\t\/\/ SDL_GetPrefPath() creates the desired folder if it doesn't exist.\n\tchar *screenshotPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"screenshots\");\n\n\tif (screenshotPathPtr == nullptr)\n\t{\n\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\tscreenshotPathPtr = SDL_strdup(\"screenshots\/\");\n\t}\n\n\tconst std::string screenshotPathString(screenshotPathPtr);\n\tSDL_free(screenshotPathPtr);\n\n\t\/\/ Convert Windows backslashes to forward slashes.\n\treturn String::replace(screenshotPathString, '\\\\', '\/');\n}\n\nstd::string Platform::getLogPath()\n{\n\t\/\/ Unfortunately there's no SDL_GetLogPath(), so we need to make our own.\n\tconst std::string platform = Platform::getPlatform();\n\n\tif (platform == \"Windows\")\n\t{\n\t\tchar *logPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"log\");\n\n\t\tif (logPathPtr == nullptr)\n\t\t{\n\t\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\t\tlogPathPtr = SDL_strdup(\"log\/\");\n\t\t}\n\n\t\tconst std::string logPathString(logPathPtr);\n\t\tSDL_free(logPathPtr);\n\n\t\t\/\/ Convert Windows backslashes to forward slashes.\n\t\treturn String::replace(logPathString, '\\\\', '\/');\n\t}\n\telse if (platform == \"Linux\")\n\t{\n\t\treturn Platform::getXDGConfigHomeEnv() + \"\/OpenTESArena\/log\/\";\n\t}\n\telse if (platform == \"Mac OS X\")\n\t{\n\t\treturn Platform::getHomeEnv() + \"\/Library\/Logs\/OpenTESArena\/log\/\";\n\t}\n\telse\n\t{\n\t\tDebugWarning(\"No default log path on this platform.\");\n\t\treturn \"OpenTESArena\/log\/\";\n\t}\n}\n\nint Platform::getThreadCount()\n{\n\tconst int threadCount = static_cast(std::thread::hardware_concurrency());\n\n\t\/\/ hardware_concurrency() might return 0, so it needs to be clamped positive.\n\tif (threadCount == 0)\n\t{\n\t\tDebugWarning(\"hardware_concurrency() returned 0.\");\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\treturn threadCount;\n\t}\n}\n\nbool Platform::directoryExists(const std::string &path)\n{\n#if defined(_WINDOWS)\n\tconst DWORD attrs = GetFileAttributes(path.c_str());\n\treturn (attrs != INVALID_FILE_ATTRIBUTES) &&\n\t\t((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0);\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\tstruct stat st;\n\tstd::memset(&st, 0, sizeof(st));\n\tif (stat(path.c_str(), &st) == 0)\n\t{\n\t\t\/\/ Returns true if the entry is a directory.\n\t\treturn (st.st_mode & S_IFDIR) != 0;\n\t}\n\telse\n\t{\n\t\tif (errno != ENOENT)\n\t\t{\n\t\t\tthrow DebugException(\"stat(): \" + std::string(strerror(errno)) + \".\");\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n#else\n\t\/\/ Unknown platform.\n\tDebugNotImplemented();\n\treturn false;\n#endif\n}\n\nnamespace\n{\n#if defined(_WINDOWS)\n\tvoid createWindowsDirectory(const std::string &path)\n\t{\n\t\tCreateDirectoryA(path.c_str(), nullptr);\n\t}\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\tvoid createUnixDirectory(const std::string &path, mode_t permissions)\n\t{\n\t\tif (mkdir(path.c_str(), permissions) == -1)\n\t\t{\n\t\t\tDebugWarning(\"mkdir(): \" + std::string(strerror(errno)) + \".\");\n\t\t}\n\t}\n#endif\n}\n\nvoid Platform::createDirectoryRecursively(std::string path)\n{\n\tconst bool pathIsEmpty = path.size() == 0;\n\tconst bool hasTrailingSlash = !pathIsEmpty &&\n\t\t((path.back() == '\/') || (path.back() == '\\\\'));\n\n\tif (!hasTrailingSlash)\n\t{\n\t\tpath.push_back('\/');\n\t}\n\n\tsize_t index = 0;\n\tdo\n\t{\n\t\tindex = path.find_first_of(\"\\\\\/\", index + 1);\n\t\tconst std::string subStr = path.substr(0, index);\n\n\t\tif (!Platform::directoryExists(subStr))\n\t\t{\n#if defined(_WINDOWS)\n\t\t\tcreateWindowsDirectory(subStr);\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\t\t\tcreateUnixDirectory(subStr, 0700);\n#else\n\t\t\t\/\/ Unknown platform.\n\t\t\tDebugNotImplemented();\n#endif\n\t\t}\n\t} while (index != std::string::npos);\n}\nImproved Platform error reporting.#include \n\n#include \"SDL.h\"\n\n#include \"Debug.h\"\n#include \"Platform.h\"\n#include \"String.h\"\n\n#if defined(_WINDOWS)\n#include \n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n#include \n#include \n#include \n#include \n#endif\n\nconst std::string Platform::XDGDataHome = \"XDG_DATA_HOME\";\nconst std::string Platform::XDGConfigHome = \"XDG_CONFIG_HOME\";\n\nstd::string Platform::getHomeEnv()\n{\n\tconst char *homeEnvPtr = SDL_getenv(\"HOME\");\n\treturn (homeEnvPtr != nullptr) ? std::string(homeEnvPtr) : std::string();\n}\n\nstd::string Platform::getXDGDataHomeEnv()\n{\n\tconst char *xdgEnv = SDL_getenv(Platform::XDGDataHome.c_str());\n\treturn (xdgEnv != nullptr) ? std::string(xdgEnv) :\n\t\t(Platform::getHomeEnv() + \"\/.local\/share\");\n}\n\nstd::string Platform::getXDGConfigHomeEnv()\n{\n\tconst char *xdgEnv = SDL_getenv(Platform::XDGConfigHome.c_str());\n\treturn (xdgEnv != nullptr) ? std::string(xdgEnv) :\n\t\t(Platform::getHomeEnv() + \"\/.config\");\n}\n\nstd::string Platform::getPlatform()\n{\n\treturn std::string(SDL_GetPlatform());\n}\n\nstd::string Platform::getBasePath()\n{\n\t\/\/ Allocate the base path from SDL.\n\tchar *basePathPtr = SDL_GetBasePath();\n\n\tif (basePathPtr == nullptr)\n\t{\n\t\tDebugWarning(\"SDL_GetBasePath() not available on this platform.\");\n\t\tbasePathPtr = SDL_strdup(\".\/\");\n\t}\n\n\tconst std::string basePathString(basePathPtr);\n\tSDL_free(basePathPtr);\n\n\t\/\/ Convert Windows backslashes to forward slashes.\n\treturn String::replace(basePathString, '\\\\', '\/');\n}\n\nstd::string Platform::getOptionsPath()\n{\n\tconst std::string platform = Platform::getPlatform();\n\n\tif (platform == \"Windows\")\n\t{\n\t\t\/\/ SDL_GetPrefPath() creates the desired folder if it doesn't exist.\n\t\tchar *optionsPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"options\");\n\n\t\tif (optionsPathPtr == nullptr)\n\t\t{\n\t\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\t\toptionsPathPtr = SDL_strdup(\"options\/\");\n\t\t}\n\n\t\tconst std::string optionsPathString(optionsPathPtr);\n\t\tSDL_free(optionsPathPtr);\n\n\t\t\/\/ Convert Windows backslashes to forward slashes.\n\t\treturn String::replace(optionsPathString, '\\\\', '\/');\n\t}\n\telse if (platform == \"Linux\")\n\t{\n\t\treturn Platform::getXDGConfigHomeEnv() + \"\/OpenTESArena\/options\/\";\n\t}\n\telse if (platform == \"Mac OS X\")\n\t{\n\t\treturn Platform::getHomeEnv() + \"\/Library\/Preferences\/OpenTESArena\/options\/\";\n\t}\n\telse\n\t{\n\t\tDebugWarning(\"No default options path on this platform.\");\n\t\treturn \"OpenTESArena\/options\/\";\n\t}\n}\n\nstd::string Platform::getScreenshotPath()\n{\n\t\/\/ SDL_GetPrefPath() creates the desired folder if it doesn't exist.\n\tchar *screenshotPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"screenshots\");\n\n\tif (screenshotPathPtr == nullptr)\n\t{\n\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\tscreenshotPathPtr = SDL_strdup(\"screenshots\/\");\n\t}\n\n\tconst std::string screenshotPathString(screenshotPathPtr);\n\tSDL_free(screenshotPathPtr);\n\n\t\/\/ Convert Windows backslashes to forward slashes.\n\treturn String::replace(screenshotPathString, '\\\\', '\/');\n}\n\nstd::string Platform::getLogPath()\n{\n\t\/\/ Unfortunately there's no SDL_GetLogPath(), so we need to make our own.\n\tconst std::string platform = Platform::getPlatform();\n\n\tif (platform == \"Windows\")\n\t{\n\t\tchar *logPathPtr = SDL_GetPrefPath(\"OpenTESArena\", \"log\");\n\n\t\tif (logPathPtr == nullptr)\n\t\t{\n\t\t\tDebugWarning(\"SDL_GetPrefPath() not available on this platform.\");\n\t\t\tlogPathPtr = SDL_strdup(\"log\/\");\n\t\t}\n\n\t\tconst std::string logPathString(logPathPtr);\n\t\tSDL_free(logPathPtr);\n\n\t\t\/\/ Convert Windows backslashes to forward slashes.\n\t\treturn String::replace(logPathString, '\\\\', '\/');\n\t}\n\telse if (platform == \"Linux\")\n\t{\n\t\treturn Platform::getXDGConfigHomeEnv() + \"\/OpenTESArena\/log\/\";\n\t}\n\telse if (platform == \"Mac OS X\")\n\t{\n\t\treturn Platform::getHomeEnv() + \"\/Library\/Logs\/OpenTESArena\/log\/\";\n\t}\n\telse\n\t{\n\t\tDebugWarning(\"No default log path on this platform.\");\n\t\treturn \"OpenTESArena\/log\/\";\n\t}\n}\n\nint Platform::getThreadCount()\n{\n\tconst int threadCount = static_cast(std::thread::hardware_concurrency());\n\n\t\/\/ hardware_concurrency() might return 0, so it needs to be clamped positive.\n\tif (threadCount == 0)\n\t{\n\t\tDebugWarning(\"hardware_concurrency() returned 0.\");\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\treturn threadCount;\n\t}\n}\n\nbool Platform::directoryExists(const std::string &path)\n{\n#if defined(_WINDOWS)\n\tconst DWORD attrs = GetFileAttributes(path.c_str());\n\treturn (attrs != INVALID_FILE_ATTRIBUTES) &&\n\t\t((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0);\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\tstruct stat st;\n\tstd::memset(&st, 0, sizeof(st));\n\tif (stat(path.c_str(), &st) == 0)\n\t{\n\t\t\/\/ Returns true if the entry is a directory.\n\t\treturn (st.st_mode & S_IFDIR) != 0;\n\t}\n\telse\n\t{\n\t\tif (errno != ENOENT)\n\t\t{\n\t\t\tthrow DebugException(\"stat(): \" + std::string(strerror(errno)) + \".\");\n\t\t}\n\n\t\treturn false;\n\t}\n#else\n#error Unknown platform.\n#endif\n}\n\nnamespace\n{\n#if defined(_WINDOWS)\n\tvoid createWindowsDirectory(const std::string &path)\n\t{\n\t\tconst BOOL success = CreateDirectoryA(path.c_str(), nullptr);\n\t\tif (success == 0)\n\t\t{\n\t\t\tconst std::string message = [&path]() -> std::string\n\t\t\t{\n\t\t\t\tconst DWORD lastError = GetLastError();\n\t\t\t\tif (lastError == ERROR_ALREADY_EXISTS)\n\t\t\t\t{\n\t\t\t\t\treturn \"\\\"\" + path + \"\\\" already exists.\";\n\t\t\t\t}\n\t\t\t\telse if (lastError == ERROR_PATH_NOT_FOUND)\n\t\t\t\t{\n\t\t\t\t\treturn \"\\\"\" + path + \"\\\" not found.\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\treturn \"Unknown error.\";\n\t\t\t\t}\n\t\t\t}();\n\n\t\t\tDebugWarning(\"CreateDirectoryA(): \" + message);\n\t\t}\n\t}\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\tvoid createUnixDirectory(const std::string &path, mode_t permissions)\n\t{\n\t\tif (mkdir(path.c_str(), permissions) == -1)\n\t\t{\n\t\t\tDebugWarning(\"mkdir(): \" + std::string(strerror(errno)) + \".\");\n\t\t}\n\t}\n#endif\n}\n\nvoid Platform::createDirectoryRecursively(std::string path)\n{\n\tconst bool pathIsEmpty = path.size() == 0;\n\tconst bool hasTrailingSlash = !pathIsEmpty &&\n\t\t((path.back() == '\/') || (path.back() == '\\\\'));\n\n\tif (!hasTrailingSlash)\n\t{\n\t\tpath.push_back('\/');\n\t}\n\n\tsize_t index = 0;\n\tdo\n\t{\n\t\tindex = path.find_first_of(\"\\\\\/\", index + 1);\n\t\tconst std::string subStr = path.substr(0, index);\n\n\t\tif (!Platform::directoryExists(subStr))\n\t\t{\n#if defined(_WINDOWS)\n\t\t\tcreateWindowsDirectory(subStr);\n#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\t\t\tcreateUnixDirectory(subStr, 0700);\n#else\n#error Unknown platform.\n#endif\n\t\t}\n\t} while (index != std::string::npos);\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of TelepathyQt4Logger\n *\n * Copyright (C) 2011 Collabora Ltd. \n *\n * This library is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 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 Lesser General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"tpl-tool.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nTplToolApplication::TplToolApplication(int &argc, char **argv)\n : QCoreApplication(argc, argv)\n{\n debugfn();\n\n mAccountManager = Tp::AccountManager::create();\n connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onAccountManagerReady(Tp::PendingOperation*)));\n}\n\nTp::AccountPtr TplToolApplication::accountPtr(const QString &id)\n{\n debugfn();\n\n mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii());\n if (!mAccountPtr->isValid()) {\n return mAccountPtr;\n }\n\n connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onAccountReady(Tp::PendingOperation*)));\n\n return mAccountPtr;\n}\n\nTpl::EntityPtr TplToolApplication::entityPtr(const QString &id)\n{\n debugfn();\n\n return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL);\n}\n\nbool TplToolApplication::parseArgs1()\n{\n debugfn();\n\n QStringList args = arguments();\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n return false;\n }\n\n if (args.size() == 2 && args.at(1) == \"accounts\") {\n Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts();\n QList accounts = accountSet->accounts();\n Tp::AccountPtr account;\n int i = 0;\n Q_FOREACH(account, accounts) {\n qDebug() << \"account \" << i++ << account->objectPath();\n }\n this->exit();\n return true;\n } else if ((args.size() == 3 && args.at(1) == \"contacts\") ||\n (args.size() == 4 && args.at(1) == \"exists\") ||\n (args.size() == 3 && args.at(1) == \"entities\") ||\n (args.size() == 4 && args.at(1) == \"dates\") ||\n (args.size() == 4 && args.at(1) == \"events\") ||\n (args.size() == 5 && args.at(1) == \"filteredEvents\")) {\n Tp::AccountPtr account = accountPtr(args.at(2).toAscii());\n if (account.isNull()) {\n qWarning() << \"Account not found \" << args.at(2);\n }\n return true;\n } else if (args.size() == 3 && args.at(1) == \"search\") {\n Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny);\n debugfn() << \"PendingSearch=\" << ps;\n if (!ps) {\n qWarning() << \"Error in search\";\n this->exit(-1);\n return false;\n }\n\n connect(ps,\n SIGNAL(finished(Tpl::PendingOperation*)),\n this,\n SLOT(onPendingSearch(Tpl::PendingOperation*)));\n\n ps->start();\n\n return true;\n }\n\n qDebug() << \"Telepathy logger command line tool (qt4)\";\n qDebug() << \"\";\n qDebug() << \"General usage: tpl-tool \";\n qDebug() << \"\";\n qDebug() << \"tpl-tool accounts\";\n qDebug() << \"tpl-tool contacts \";\n qDebug() << \"tpl-tool exists \";\n qDebug() << \"tpl-tool entities \";\n qDebug() << \"tpl-tool dates \";\n qDebug() << \"tpl-tool events \";\n qDebug() << \"tpl-tool filteredEvents \";\n qDebug() << \"tpl-tool search \";\n this->exit(-1);\n\n return false;\n}\n\nbool TplToolApplication::parseArgs2()\n{\n debugfn();\n\n QStringList args = arguments();\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n return false;\n }\n\n if (args.size() == 3 && args.at(1) == \"contacts\") {\n Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts();\n debugfn() << \"number of contacts = \" << contacts.size();\n\n Tp::ContactPtr contact;\n int i = 0;\n Q_FOREACH(contact, contacts) {\n qDebug() << \"contact \" << i++ << contact->id();\n }\n this->exit();\n return true;\n } else if (args.size() == 4 && args.at(1) == \"exists\") {\n Tpl::EntityPtr entity = entityPtr(args.at(3));\n if (entity.isNull()) {\n qWarning() << \"Entity not found \" << args.at(3);\n }\n\n bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny);\n qDebug() << \"tpl-tool exists \" << args.at(2) << args.at(3) << \" -> \" << ret;\n this->exit();\n return true;\n } else if (args.at(0) == \"entities\") {\n } else if (args.at(0) == \"dates\") {\n } else if (args.at(0) == \"events\") {\n } else if (args.at(0) == \"filteredEvents\") {\n }\n\n return false;\n}\n\nvoid TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n return;\n }\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n return;\n }\n\n logManager->setAccountManagerPtr(mAccountManager);\n\n parseArgs1();\n}\n\nvoid TplToolApplication::onAccountReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n return;\n }\n\n Tp::ConnectionPtr connection = mAccountPtr->connection();\n if (connection.isNull()) {\n return;\n }\n\n connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onConnectionReady(Tp::PendingOperation*)));\n}\n\nvoid TplToolApplication::onConnectionReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n return;\n }\n\n parseArgs2();\n}\n\nvoid TplToolApplication::onPendingSearch(Tpl::PendingOperation *po)\n{\n Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po;\n\n debugfn() << \" search hits \" << ps->hits().size();\n\n Tpl::SearchHit hit;\n Q_FOREACH(hit, ps->hits()) {\n \/\/debugfn() << \"account=\" << hit.account << \"date=\" << hit.date << \"target=\" << hit.target ? hit.target->identifier() : \"null\";\n debugfn() << \"account=\" << hit.account;\n debugfn() << \"date=\" << hit.date;\n debugfn() << \"entity=\" << (hit.target.isNull() ? \"null\" : hit.target->identifier());\n }\n\n this->exit();\n}\n\nint main(int argc, char **argv)\n{\n g_type_init();\n Tp::registerTypes();\n\n TplToolApplication app(argc, argv);\n Tpl::init();\n\n return app.exec();\n}\nAdapting search to last changes Added some debug output to tpl-tool\/*\n * This file is part of TelepathyQt4Logger\n *\n * Copyright (C) 2011 Collabora Ltd. \n *\n * This library is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 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 Lesser General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"tpl-tool.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nTplToolApplication::TplToolApplication(int &argc, char **argv)\n : QCoreApplication(argc, argv)\n{\n debugfn();\n\n mAccountManager = Tp::AccountManager::create();\n connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onAccountManagerReady(Tp::PendingOperation*)));\n}\n\nTp::AccountPtr TplToolApplication::accountPtr(const QString &id)\n{\n debugfn();\n\n mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii());\n if (!mAccountPtr->isValid()) {\n return mAccountPtr;\n }\n\n connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onAccountReady(Tp::PendingOperation*)));\n\n return mAccountPtr;\n}\n\nTpl::EntityPtr TplToolApplication::entityPtr(const QString &id)\n{\n debugfn();\n\n return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL);\n}\n\nbool TplToolApplication::parseArgs1()\n{\n debugfn();\n\n QStringList args = arguments();\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n return false;\n }\n\n if (args.size() == 2 && args.at(1) == \"accounts\") {\n Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts();\n QList accounts = accountSet->accounts();\n Tp::AccountPtr account;\n int i = 0;\n Q_FOREACH(account, accounts) {\n qDebug() << \"account \" << i++ << account->objectPath();\n }\n this->exit();\n return true;\n } else if ((args.size() == 3 && args.at(1) == \"contacts\") ||\n (args.size() == 4 && args.at(1) == \"exists\") ||\n (args.size() == 3 && args.at(1) == \"entities\") ||\n (args.size() == 4 && args.at(1) == \"dates\") ||\n (args.size() == 4 && args.at(1) == \"events\") ||\n (args.size() == 5 && args.at(1) == \"filteredEvents\")) {\n Tp::AccountPtr account = accountPtr(args.at(2).toAscii());\n if (account.isNull()) {\n qWarning() << \"Account not found \" << args.at(2);\n }\n return true;\n } else if (args.size() == 3 && args.at(1) == \"search\") {\n Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny);\n debugfn() << \"PendingSearch=\" << ps;\n if (!ps) {\n qWarning() << \"Error in search\";\n this->exit(-1);\n return false;\n }\n\n connect(ps,\n SIGNAL(finished(Tpl::PendingOperation*)),\n this,\n SLOT(onPendingSearch(Tpl::PendingOperation*)));\n\n ps->start();\n\n return true;\n }\n\n qDebug() << \"Telepathy logger command line tool (qt4)\";\n qDebug() << \"\";\n qDebug() << \"General usage: tpl-tool \";\n qDebug() << \"\";\n qDebug() << \"tpl-tool accounts\";\n qDebug() << \"tpl-tool contacts \";\n qDebug() << \"tpl-tool exists \";\n qDebug() << \"tpl-tool entities \";\n qDebug() << \"tpl-tool dates \";\n qDebug() << \"tpl-tool events \";\n qDebug() << \"tpl-tool filteredEvents \";\n qDebug() << \"tpl-tool search \";\n this->exit(-1);\n\n return false;\n}\n\nbool TplToolApplication::parseArgs2()\n{\n debugfn();\n\n QStringList args = arguments();\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n return false;\n }\n\n if (args.size() == 3 && args.at(1) == \"contacts\") {\n Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts();\n debugfn() << \"number of contacts = \" << contacts.size();\n\n Tp::ContactPtr contact;\n int i = 0;\n Q_FOREACH(contact, contacts) {\n qDebug() << \"contact \" << i++ << contact->id();\n }\n this->exit();\n return true;\n } else if (args.size() == 4 && args.at(1) == \"exists\") {\n Tpl::EntityPtr entity = entityPtr(args.at(3));\n if (entity.isNull()) {\n qWarning() << \"Entity not found \" << args.at(3);\n }\n\n bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny);\n qDebug() << \"tpl-tool exists \" << args.at(2) << args.at(3) << \" -> \" << ret;\n this->exit();\n return true;\n } else if (args.at(0) == \"entities\") {\n } else if (args.at(0) == \"dates\") {\n } else if (args.at(0) == \"events\") {\n } else if (args.at(0) == \"filteredEvents\") {\n }\n\n return false;\n}\n\nvoid TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n qWarning() << \"error getting account mananger ready\";\n exit(-1);\n return;\n }\n\n Tpl::LogManagerPtr logManager = Tpl::LogManager::instance();\n if (logManager.isNull()) {\n qWarning() << \"LogManager not found\";\n exit(-1);\n return;\n }\n\n logManager->setAccountManagerPtr(mAccountManager);\n\n parseArgs1();\n}\n\nvoid TplToolApplication::onAccountReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n qWarning() << \"error getting account ready\";\n exit(-1);\n return;\n }\n\n Tp::ConnectionPtr connection = mAccountPtr->connection();\n if (connection.isNull()) {\n qWarning() << \"error null connection\";\n exit(-1);\n return;\n }\n\n connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster),\n SIGNAL(finished(Tp::PendingOperation*)),\n this,\n SLOT(onConnectionReady(Tp::PendingOperation*)));\n}\n\nvoid TplToolApplication::onConnectionReady(Tp::PendingOperation *po)\n{\n debugfn() << \"po=\" << po << \"isError=\" << po->isError();\n\n if (po->isError()) {\n qWarning() << \"error getting connection ready\";\n exit(-1);\n return;\n }\n\n parseArgs2();\n}\n\nvoid TplToolApplication::onPendingSearch(Tpl::PendingOperation *po)\n{\n Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po;\n\n if (ps->isError()) {\n qWarning() << \"error in search\";\n exit(-1);\n return;\n }\n\n Tpl::SearchHitList *hits = ps->hits();\n debugfn() << \" search hits \" << hits->size();\n\n Tpl::SearchHit *hit;\n Q_FOREACH(hit, *hits) {\n \/\/debugfn() << \"account=\" << hit->account << \"date=\" << hit->date << \"target=\" << hit->target ? hit->target->identifier() : \"null\";\n debugfn() << \"account=\" << hit->account;\n debugfn() << \"date=\" << hit->date;\n debugfn() << \"entity=\" << (hit->target.isNull() ? \"null\" : hit->target->identifier());\n }\n\n this->exit();\n}\n\nint main(int argc, char **argv)\n{\n g_type_init();\n Tp::registerTypes();\n\n TplToolApplication app(argc, argv);\n Tpl::init();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"ros_igtl_bridge.h\"\n#include \"ShowPolyData.h\"\n\n#include \"rib_converter_point.h\"\n#include \"rib_converter_pointcloud.h\"\n#include \"rib_converter_transform.h\"\n#include \"rib_converter_polydata.h\"\n#include \"rib_converter_string.h\"\n#include \"rib_converter_image.h\"\n\n\n\/\/----------------------------------------------------------------------\nROS_IGTL_Bridge::ROS_IGTL_Bridge(int argc, char *argv[], const char* node_name)\n{\n ros::init(argc, argv, node_name);\n nh = new ros::NodeHandle;\t\n \n \/\/ run bridge as client or server\n std::string type;\n ROS_INFO(\"[ROS-IGTL-Bridge] a\");\n if(nh->getParam(\"\/RIB_type\",type))\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] b \");\n if(type == \"client\")\n ConnectToIGTLServer();\t\t\n else if(type == \"server\")\n CreateIGTLServer();\n else\n ROS_ERROR(\"[ROS-IGTL-Bridge] Unknown Value for Parameter 'RIB_type'\");\t\n }\n else\n {\n short srvcl = 0;\n while(1)\n {\n std::cout<<\"[ROS-IGTL-Bridge] Please type <1> or <2> to run node as OpenIGTLink client or server\"<>srvcl;\n \n if (srvcl==1)\n {\n CreateIGTLServer();\n break;\n }\n else if (srvcl==2)\n {\n ConnectToIGTLServer();\n break;\n }\n }\n }\n \n ROS_INFO(\"[ROS-IGTL-Bridge] ROS-IGTL-Bridge up and Running.\");\n \n \/\/this->ribcpoint = new RIBConverterPoint;\n \/\/ribcpoint->setup(nh, socket, 10);\n \/\/ribcpoint->publish(\"IGTL_POINT_IN\");\n \/\/ribcpoint->subscribe(\"IGTL_POINT_OUT\");\n \/\/\n \/\/this->ribctransform = new RIBConverterTransform;\n \/\/ribctransform->setup(nh, socket, 10);\n \/\/ribctransform->publish(\"IGTL_TRANSFORM_IN\");\n \/\/ribctransform->subscribe(\"IGTL_TRANSFORM_OUT\");\n \/\/\n \/\/this->ribcpolydata = new RIBConverterPolyData;\n \/\/ribcpolydata->setup(nh, socket, 10);\n \/\/ribcpolydata->publish(\"IGTL_POLYDATA_IN\");\n \/\/ribcpolydata->subscribe(\"IGTL_POLYDATA_OUT\");\n \/\/\n \/\/this->ribcstring = new RIBConverterString;\n \/\/ribcstring->setup(nh, socket, 10);\n \/\/ribcstring->publish(\"IGTL_STRING_IN\");\n \/\/ribcstring->subscribe(\"IGTL_STRING_OUT\");\n \/\/\n \/\/this->ribcimage = new RIBConverterImage;\n \/\/ribcimage->setup(nh, socket, 5);\n \/\/ribcimage->publish(\"IGTL_IMAGE_IN\");\n \/\/ribcimage->subscribe(\"IGTL_IMAGE_OUT\");\n \/\/\n \/\/this->ribcpointcloud = new RIBConverterPointCloud;\n \/\/ribcpointcloud->setup(nh, socket, 5);\n \/\/ribcpointcloud->publish(\"IGTL_POINTCLOUD_IN\");\n \/\/ribcpointcloud->subscribe(\"IGTL_POINTCLOUD_OUT\");\n\n\n RIBConverterPoint * point = new RIBConverterPoint;\n this->AddConverter(point, 10, \"IGTL_POINT_IN\", \"IGTL_POINT_OUT\");\n \n RIBConverterTransform* transform = new RIBConverterTransform;\n this->AddConverter(transform, 10, \"IGTL_TRANSFORM_IN\", \"IGTL_TRANSFORM_OUT\");\n \n RIBConverterPolyData* polydata = new RIBConverterPolyData;\n this->AddConverter(polydata, 10, \"IGTL_POLYDATA_IN\", \"IGTL_POLYDATA_OUT\");\n\n RIBConverterString* string = new RIBConverterString;\n this->AddConverter(string, 10, \"IGTL_STRING_IN\", \"IGTL_STRING_OUT\");\n\n RIBConverterImage* image = new RIBConverterImage;\n this->AddConverter(image, 10, \"IGTL_IMAGE_IN\", \"IGTL_IMAGE_OUT\");\n\n RIBConverterPointCloud* pointcloud = new RIBConverterPointCloud;\n this->AddConverter(pointcloud, 10, \"IGTL_POINTCLOUD_IN\", \"IGTL_POINTCLOUD_OUT\");\n\n \/\/ start receiver thread\n boost::thread* receiver_thread = new boost::thread(boost::bind(&ROS_IGTL_Bridge::IGTLReceiverThread, this)); \n}\n\n\/\/----------------------------------------------------------------------\nROS_IGTL_Bridge::~ROS_IGTL_Bridge()\n{\n socket->CloseSocket();\n}\n\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::Run()\n{\n ros::spin();\n}\n\n\/\/----------------------------------------------------------------------\nigtl::Socket::Pointer ROS_IGTL_Bridge::GetSocketPointer()\n{\n igtl::Socket::Pointer socket_ptr = static_cast(socket);\n return socket_ptr;\n}\n\n\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::CreateIGTLServer()\n{\n int port = 18944; \/\/ std port\n if(nh->getParam(\"\/RIB_port\",port))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Input socket port: \");\n std::cin >> port;\n }\n igtl::ServerSocket::Pointer serverSocket;\n serverSocket = igtl::ServerSocket::New();\n int c = serverSocket->CreateServer(port);\n \n if (c < 0)\n {\n ROS_ERROR(\"[ROS-IGTL-Bridge] Cannot create a server socket.\");\n }\n ROS_INFO(\"[ROS-IGTL-Bridge] Server socket created. Please connect to port: %d\",port);\n \n \/\/ wait for connection\n while (1)\n {\n socket = serverSocket->WaitForConnection(1000);\n if (ROS_IGTL_Bridge::socket.IsNotNull()) \n { \n break;\n }\n }\n}\n\n\/\/----------------------------------\nvoid ROS_IGTL_Bridge::ConnectToIGTLServer()\n{\n igtl::ClientSocket::Pointer clientsocket;\n clientsocket = igtl::ClientSocket::New();\n \n int port = 18944; \/\/ std port\n std::string ip;\n \/\/ get ip\n if(nh->getParam(\"\/RIB_server_ip\",ip))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Please enter ServerIP: \");\n std::cin >> ip;\n }\n \/\/ get port\n if(nh->getParam(\"\/RIB_port\",port))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Please enter ServerPort: \");\n std::cin >> port;\n }\n \/\/ connect to server\n int r = clientsocket->ConnectToServer(ip.c_str(), port);\n \n if (r != 0)\n {\n ROS_ERROR(\"[ROS-IGTL-Bridge] Cannot connect to server.\");\n exit(0);\n }\n socket = (igtl::Socket *)(clientsocket);\n}\n\n\/\/ ----- receiving from slicer -----------------------------------------\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::IGTLReceiverThread()\n{\n igtl::MessageHeader::Pointer headerMsg;\n headerMsg = igtl::MessageHeader::New();\n int rs = 0;\n while(1)\n {\n headerMsg->InitPack();\n \/\/ receive packet\n rs = socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());\n \n if (rs == 0)\n socket->CloseSocket();\n if (rs != headerMsg->GetPackSize())\n continue;\n \n headerMsg->Unpack();\n \n std::vector< RIBConverterBase* >::iterator iter;\n for (iter = this->converters.begin(); iter != this->converters.end(); iter ++)\n {\n if (strcmp(headerMsg->GetDeviceType(), (*iter)->messageTypeString()) == 0)\n {\n (*iter)->onIGTLMessage(headerMsg);\n break;\n }\n }\n if (iter == this->converters.end())\n {\n socket->Skip(headerMsg->GetBodySizeToRead(),0);\n }\n }\n \n \/\/\/\/ DATATYPE POINT ----------------------------------------------\n \/\/if (strcmp(headerMsg->GetDeviceType(), \"POINT\") == 0)\n \/\/ {\n \/\/ this->ribcpoint->onIGTLMessage(headerMsg);\n \/\/ }\n \/\/\/\/ DATATYPE STRING ---------------------------------------------\n \/\/else if (strcmp(headerMsg->GetDeviceType(), \"STRING\") == 0)\n \/\/ {\n \/\/ this->ribcstring->onIGTLMessage(headerMsg);\n \/\/ }\n \/\/\/\/ DATATYPE TRANSFORM ------------------------------------------\n \/\/else if (strcmp(headerMsg->GetDeviceType(), \"TRANSFORM\") == 0)\n \/\/ { \n \/\/ this->ribctransform->onIGTLMessage(headerMsg);\n \/\/ }\n \/\/\/\/ DATATYPE POLYDATA -------------------------------------------\n \/\/else if (strcmp(headerMsg->GetDeviceType(), \"POLYDATA\") == 0)\n \/\/ {\n \/\/ this->ribcpolydata->onIGTLMessage(headerMsg);\n \/\/ }\n \/\/\/\/ DATATYPE IMAGE -------------------------------------------\n \/\/else if (strcmp(headerMsg->GetDeviceType(), \"IMAGE\") == 0)\n \/\/ {\n \/\/ this->ribcimage->onIGTLMessage(headerMsg);\n \/\/ }\n \/\/\/\/ SKIP DATA \n \/\/else\n \/\/ {\n \/\/ socket->Skip(headerMsg->GetBodySizeToRead(),0);\n \/\/ }\n \/\/}\n}\n\n\nvoid ROS_IGTL_Bridge::AddConverter(RIBConverterBase* converter, uint32_t size, const char* topicPublish, const char* topicSubscribe)\n{\n converter->setup(this->nh, this->socket, size);\n converter->publish(topicPublish);\n converter->subscribe(topicSubscribe);\n this->converters.push_back(converter);\n}\n\n\nRemove comments.#include \n\n#include \"ros_igtl_bridge.h\"\n#include \"ShowPolyData.h\"\n\n#include \"rib_converter_point.h\"\n#include \"rib_converter_pointcloud.h\"\n#include \"rib_converter_transform.h\"\n#include \"rib_converter_polydata.h\"\n#include \"rib_converter_string.h\"\n#include \"rib_converter_image.h\"\n\n\n\/\/----------------------------------------------------------------------\nROS_IGTL_Bridge::ROS_IGTL_Bridge(int argc, char *argv[], const char* node_name)\n{\n ros::init(argc, argv, node_name);\n nh = new ros::NodeHandle;\t\n \n \/\/ run bridge as client or server\n std::string type;\n ROS_INFO(\"[ROS-IGTL-Bridge] a\");\n if(nh->getParam(\"\/RIB_type\",type))\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] b \");\n if(type == \"client\")\n ConnectToIGTLServer();\t\t\n else if(type == \"server\")\n CreateIGTLServer();\n else\n ROS_ERROR(\"[ROS-IGTL-Bridge] Unknown Value for Parameter 'RIB_type'\");\t\n }\n else\n {\n short srvcl = 0;\n while(1)\n {\n std::cout<<\"[ROS-IGTL-Bridge] Please type <1> or <2> to run node as OpenIGTLink client or server\"<>srvcl;\n \n if (srvcl==1)\n {\n CreateIGTLServer();\n break;\n }\n else if (srvcl==2)\n {\n ConnectToIGTLServer();\n break;\n }\n }\n }\n \n ROS_INFO(\"[ROS-IGTL-Bridge] ROS-IGTL-Bridge up and Running.\");\n \n RIBConverterPoint * point = new RIBConverterPoint;\n this->AddConverter(point, 10, \"IGTL_POINT_IN\", \"IGTL_POINT_OUT\");\n \n RIBConverterTransform* transform = new RIBConverterTransform;\n this->AddConverter(transform, 10, \"IGTL_TRANSFORM_IN\", \"IGTL_TRANSFORM_OUT\");\n \n RIBConverterPolyData* polydata = new RIBConverterPolyData;\n this->AddConverter(polydata, 10, \"IGTL_POLYDATA_IN\", \"IGTL_POLYDATA_OUT\");\n\n RIBConverterString* string = new RIBConverterString;\n this->AddConverter(string, 10, \"IGTL_STRING_IN\", \"IGTL_STRING_OUT\");\n\n RIBConverterImage* image = new RIBConverterImage;\n this->AddConverter(image, 10, \"IGTL_IMAGE_IN\", \"IGTL_IMAGE_OUT\");\n\n RIBConverterPointCloud* pointcloud = new RIBConverterPointCloud;\n this->AddConverter(pointcloud, 10, \"IGTL_POINTCLOUD_IN\", \"IGTL_POINTCLOUD_OUT\");\n\n \/\/ start receiver thread\n boost::thread* receiver_thread = new boost::thread(boost::bind(&ROS_IGTL_Bridge::IGTLReceiverThread, this)); \n}\n\n\/\/----------------------------------------------------------------------\nROS_IGTL_Bridge::~ROS_IGTL_Bridge()\n{\n socket->CloseSocket();\n}\n\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::Run()\n{\n ros::spin();\n}\n\n\/\/----------------------------------------------------------------------\nigtl::Socket::Pointer ROS_IGTL_Bridge::GetSocketPointer()\n{\n igtl::Socket::Pointer socket_ptr = static_cast(socket);\n return socket_ptr;\n}\n\n\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::CreateIGTLServer()\n{\n int port = 18944; \/\/ std port\n if(nh->getParam(\"\/RIB_port\",port))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Input socket port: \");\n std::cin >> port;\n }\n igtl::ServerSocket::Pointer serverSocket;\n serverSocket = igtl::ServerSocket::New();\n int c = serverSocket->CreateServer(port);\n \n if (c < 0)\n {\n ROS_ERROR(\"[ROS-IGTL-Bridge] Cannot create a server socket.\");\n }\n ROS_INFO(\"[ROS-IGTL-Bridge] Server socket created. Please connect to port: %d\",port);\n \n \/\/ wait for connection\n while (1)\n {\n socket = serverSocket->WaitForConnection(1000);\n if (ROS_IGTL_Bridge::socket.IsNotNull()) \n { \n break;\n }\n }\n}\n\n\/\/----------------------------------\nvoid ROS_IGTL_Bridge::ConnectToIGTLServer()\n{\n igtl::ClientSocket::Pointer clientsocket;\n clientsocket = igtl::ClientSocket::New();\n \n int port = 18944; \/\/ std port\n std::string ip;\n \/\/ get ip\n if(nh->getParam(\"\/RIB_server_ip\",ip))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Please enter ServerIP: \");\n std::cin >> ip;\n }\n \/\/ get port\n if(nh->getParam(\"\/RIB_port\",port))\n {}\n else\n {\n ROS_INFO(\"[ROS-IGTL-Bridge] Please enter ServerPort: \");\n std::cin >> port;\n }\n \/\/ connect to server\n int r = clientsocket->ConnectToServer(ip.c_str(), port);\n \n if (r != 0)\n {\n ROS_ERROR(\"[ROS-IGTL-Bridge] Cannot connect to server.\");\n exit(0);\n }\n socket = (igtl::Socket *)(clientsocket);\n}\n\n\/\/ ----- receiving from slicer -----------------------------------------\n\/\/----------------------------------------------------------------------\nvoid ROS_IGTL_Bridge::IGTLReceiverThread()\n{\n igtl::MessageHeader::Pointer headerMsg;\n headerMsg = igtl::MessageHeader::New();\n int rs = 0;\n while(1)\n {\n headerMsg->InitPack();\n \/\/ receive packet\n rs = socket->Receive(headerMsg->GetPackPointer(), headerMsg->GetPackSize());\n \n if (rs == 0)\n socket->CloseSocket();\n if (rs != headerMsg->GetPackSize())\n continue;\n \n headerMsg->Unpack();\n \n std::vector< RIBConverterBase* >::iterator iter;\n for (iter = this->converters.begin(); iter != this->converters.end(); iter ++)\n {\n if (strcmp(headerMsg->GetDeviceType(), (*iter)->messageTypeString()) == 0)\n {\n (*iter)->onIGTLMessage(headerMsg);\n break;\n }\n }\n if (iter == this->converters.end())\n {\n socket->Skip(headerMsg->GetBodySizeToRead(),0);\n }\n }\n}\n\n\nvoid ROS_IGTL_Bridge::AddConverter(RIBConverterBase* converter, uint32_t size, const char* topicPublish, const char* topicSubscribe)\n{\n converter->setup(this->nh, this->socket, size);\n converter->publish(topicPublish);\n converter->subscribe(topicSubscribe);\n this->converters.push_back(converter);\n}\n\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Jolla Ltd.\n** Contact: Vesa-Matti Hartikainen \n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \"qdeclarativemozview.h\"\n#include \"quickmozview.h\"\n#include \"qmozcontext.h\"\n\n#include \"declarativebookmarkmodel.h\"\n#include \"declarativewebutils.h\"\n#include \"browserservice.h\"\n#include \"downloadmanager.h\"\n#include \"settingmanager.h\"\n#include \"closeeventfilter.h\"\n#include \"declarativetab.h\"\n#include \"declarativetabmodel.h\"\n#include \"declarativehistorymodel.h\"\n\n#include \n\n#ifdef HAS_BOOSTER\n#include \n#endif\n\nQ_DECL_EXPORT int main(int argc, char *argv[])\n{\n \/\/ EGL FPS are lower with threaded render loop\n \/\/ that's why this workaround.\n \/\/ See JB#7358\n setenv(\"QML_BAD_GUI_RENDER_LOOP\", \"1\", 1);\n setenv(\"USE_ASYNC\", \"1\", 1);\n#ifdef HAS_BOOSTER\n QScopedPointer app(MDeclarativeCache::qApplication(argc, argv));\n QScopedPointer view(MDeclarativeCache::qQuickView());\n#else\n QScopedPointer app(new QGuiApplication(argc, argv));\n QScopedPointer view(new QQuickView);\n#endif\n app->setQuitOnLastWindowClosed(false);\n\n \/\/ TODO : Remove this and set custom user agent always\n \/\/ Don't set custom user agent string when arguments contains -developerMode, give url as last argument\n if (!app->arguments().contains(\"-developerMode\")) {\n setenv(\"CUSTOM_UA\", \"Mozilla\/5.0 (Linux; U; Jolla; Sailfish; Mobile; rv:20.0) Gecko\/20.0 Firefox\/20.0 Sailfish Browser\/1.0 Mobile\", 1);\n }\n\n BrowserService *service = new BrowserService(app.data());\n \/\/ Handle command line launch\n if (!service->registered()) {\n QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), \"\/\",\n service->serviceName(), \"openUrl\");\n QStringList args;\n \/\/ Pass url argument if given\n if (app->arguments().count() > 1) {\n args << app->arguments().at(1);\n }\n message.setArguments(QVariantList() << args);\n\n QDBusConnection::sessionBus().asyncCall(message);\n if (QCoreApplication::hasPendingEvents()) {\n QCoreApplication::processEvents();\n }\n\n return 0;\n }\n\n \/\/% \"Browser\"\n QT_TRID_NOOP(\"sailfish-browser-ap-name\");\n\n QString translationPath(\"\/usr\/share\/translations\/\");\n QTranslator engineeringEnglish;\n engineeringEnglish.load(\"sailfish-browser_eng_en\", translationPath);\n qApp->installTranslator(&engineeringEnglish);\n\n QTranslator translator;\n translator.load(QLocale(), \"sailfish-browser\", \"-\", translationPath);\n qApp->installTranslator(&translator);\n\n \/\/ We want to have SignonUI in process, if user wants to create account from Browser\n SignonUiService ssoui(0, true); \/\/ in process\n ssoui.setInProcessServiceName(QLatin1String(\"org.sailfishos.browser\"));\n ssoui.setInProcessObjectPath(QLatin1String(\"\/JollaBrowserSignonUi\"));\n\n QDBusConnection sessionBus = QDBusConnection::sessionBus();\n bool registeredService = sessionBus.registerService(QLatin1String(\"org.sailfishos.browser\"));\n bool registeredObject = sessionBus.registerObject(QLatin1String(\"\/JollaBrowserSignonUi\"), &ssoui,\n QDBusConnection::ExportAllContents);\n\n if (!registeredService || !registeredObject) {\n qWarning() << Q_FUNC_INFO << \"CRITICAL: unable to register signon ui service:\"\n << QLatin1String(\"org.sailfishos.browser\") << \"at object path:\"\n << QLatin1String(\"\/JollaBrowserSignonUi\");\n }\n\n view->rootContext()->setContextProperty(\"jolla_signon_ui_service\", &ssoui);\n\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"BookmarkModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"TabModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"HistoryModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"Tab\");\n\n QString componentPath(DEFAULT_COMPONENTS_PATH);\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/components\/EmbedLiteBinComponents.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/components\/EmbedLiteJSComponents.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/chrome\/EmbedLiteJSScripts.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/chrome\/EmbedLiteOverrides.manifest\"));\n\n app->setApplicationName(QString(\"sailfish-browser\"));\n app->setOrganizationName(QString(\"org.sailfishos\"));\n\n DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());\n view->rootContext()->setContextProperty(\"WebUtils\", utils);\n view->rootContext()->setContextProperty(\"MozContext\", QMozContext::GetInstance());\n\n DownloadManager * dlMgr = new DownloadManager(service, app.data());\n CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());\n view->installEventFilter(clsEventFilter);\n QObject::connect(service, SIGNAL(openUrlRequested(QString)),\n clsEventFilter, SLOT(cancelStopApplication()));\n\n SettingManager * settingMgr = new SettingManager(app.data());\n QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),\n settingMgr, SLOT(initialize()));\n\n QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),\n utils, SLOT(openUrl(QString)));\n\n bool isDesktop = qApp->arguments().contains(\"-desktop\");\n\n QString path;\n if (isDesktop) {\n path = qApp->applicationDirPath() + QDir::separator();\n } else {\n path = QString(DEPLOYMENT_PATH);\n }\n view->setSource(QUrl::fromLocalFile(path+\"browser.qml\"));\n view->showFullScreen();\n\n \/\/ Setup embedding\n QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));\n\n return app->exec();\n}\n[sailfish-browser] Update for custom user agent. Contributes to JB#8552\/****************************************************************************\n**\n** Copyright (C) 2013 Jolla Ltd.\n** Contact: Vesa-Matti Hartikainen \n**\n****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/#include \"qdeclarativemozview.h\"\n#include \"quickmozview.h\"\n#include \"qmozcontext.h\"\n\n#include \"declarativebookmarkmodel.h\"\n#include \"declarativewebutils.h\"\n#include \"browserservice.h\"\n#include \"downloadmanager.h\"\n#include \"settingmanager.h\"\n#include \"closeeventfilter.h\"\n#include \"declarativetab.h\"\n#include \"declarativetabmodel.h\"\n#include \"declarativehistorymodel.h\"\n\n#include \n\n#ifdef HAS_BOOSTER\n#include \n#endif\n\nQ_DECL_EXPORT int main(int argc, char *argv[])\n{\n \/\/ EGL FPS are lower with threaded render loop\n \/\/ that's why this workaround.\n \/\/ See JB#7358\n setenv(\"QML_BAD_GUI_RENDER_LOOP\", \"1\", 1);\n setenv(\"USE_ASYNC\", \"1\", 1);\n#ifdef HAS_BOOSTER\n QScopedPointer app(MDeclarativeCache::qApplication(argc, argv));\n QScopedPointer view(MDeclarativeCache::qQuickView());\n#else\n QScopedPointer app(new QGuiApplication(argc, argv));\n QScopedPointer view(new QQuickView);\n#endif\n app->setQuitOnLastWindowClosed(false);\n\n \/\/ TODO : Remove this and set custom user agent always\n \/\/ Don't set custom user agent string when arguments contains -developerMode, give url as last argument\n if (!app->arguments().contains(\"-developerMode\")) {\n setenv(\"CUSTOM_UA\", \"Mozilla\/5.0 (Linux; U; Jolla; Sailfish; Mobile; rv:20.0) Gecko\/20.0 Firefox\/20.0 Sailfish Browser\/1.0 like Safari\/535.19\", 1);\n }\n\n BrowserService *service = new BrowserService(app.data());\n \/\/ Handle command line launch\n if (!service->registered()) {\n QDBusMessage message = QDBusMessage::createMethodCall(service->serviceName(), \"\/\",\n service->serviceName(), \"openUrl\");\n QStringList args;\n \/\/ Pass url argument if given\n if (app->arguments().count() > 1) {\n args << app->arguments().at(1);\n }\n message.setArguments(QVariantList() << args);\n\n QDBusConnection::sessionBus().asyncCall(message);\n if (QCoreApplication::hasPendingEvents()) {\n QCoreApplication::processEvents();\n }\n\n return 0;\n }\n\n \/\/% \"Browser\"\n QT_TRID_NOOP(\"sailfish-browser-ap-name\");\n\n QString translationPath(\"\/usr\/share\/translations\/\");\n QTranslator engineeringEnglish;\n engineeringEnglish.load(\"sailfish-browser_eng_en\", translationPath);\n qApp->installTranslator(&engineeringEnglish);\n\n QTranslator translator;\n translator.load(QLocale(), \"sailfish-browser\", \"-\", translationPath);\n qApp->installTranslator(&translator);\n\n \/\/ We want to have SignonUI in process, if user wants to create account from Browser\n SignonUiService ssoui(0, true); \/\/ in process\n ssoui.setInProcessServiceName(QLatin1String(\"org.sailfishos.browser\"));\n ssoui.setInProcessObjectPath(QLatin1String(\"\/JollaBrowserSignonUi\"));\n\n QDBusConnection sessionBus = QDBusConnection::sessionBus();\n bool registeredService = sessionBus.registerService(QLatin1String(\"org.sailfishos.browser\"));\n bool registeredObject = sessionBus.registerObject(QLatin1String(\"\/JollaBrowserSignonUi\"), &ssoui,\n QDBusConnection::ExportAllContents);\n\n if (!registeredService || !registeredObject) {\n qWarning() << Q_FUNC_INFO << \"CRITICAL: unable to register signon ui service:\"\n << QLatin1String(\"org.sailfishos.browser\") << \"at object path:\"\n << QLatin1String(\"\/JollaBrowserSignonUi\");\n }\n\n view->rootContext()->setContextProperty(\"jolla_signon_ui_service\", &ssoui);\n\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"BookmarkModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"TabModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"HistoryModel\");\n qmlRegisterType(\"Sailfish.Browser\", 1, 0, \"Tab\");\n\n QString componentPath(DEFAULT_COMPONENTS_PATH);\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/components\/EmbedLiteBinComponents.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/components\/EmbedLiteJSComponents.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/chrome\/EmbedLiteJSScripts.manifest\"));\n QMozContext::GetInstance()->addComponentManifest(componentPath + QString(\"\/chrome\/EmbedLiteOverrides.manifest\"));\n\n app->setApplicationName(QString(\"sailfish-browser\"));\n app->setOrganizationName(QString(\"org.sailfishos\"));\n\n DeclarativeWebUtils * utils = new DeclarativeWebUtils(app->arguments(), service, app.data());\n view->rootContext()->setContextProperty(\"WebUtils\", utils);\n view->rootContext()->setContextProperty(\"MozContext\", QMozContext::GetInstance());\n\n DownloadManager * dlMgr = new DownloadManager(service, app.data());\n CloseEventFilter * clsEventFilter = new CloseEventFilter(dlMgr, app.data());\n view->installEventFilter(clsEventFilter);\n QObject::connect(service, SIGNAL(openUrlRequested(QString)),\n clsEventFilter, SLOT(cancelStopApplication()));\n\n SettingManager * settingMgr = new SettingManager(app.data());\n QObject::connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),\n settingMgr, SLOT(initialize()));\n\n QObject::connect(QMozContext::GetInstance(), SIGNAL(newWindowRequested(QString,uint,QNewWindowResponse*)),\n utils, SLOT(openUrl(QString)));\n\n bool isDesktop = qApp->arguments().contains(\"-desktop\");\n\n QString path;\n if (isDesktop) {\n path = qApp->applicationDirPath() + QDir::separator();\n } else {\n path = QString(DEPLOYMENT_PATH);\n }\n view->setSource(QUrl::fromLocalFile(path+\"browser.qml\"));\n view->showFullScreen();\n\n \/\/ Setup embedding\n QTimer::singleShot(0, QMozContext::GetInstance(), SLOT(runEmbedding()));\n\n return app->exec();\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id: AliAODPWG4ParticleCorrelation.h $ *\/\n\n\/\/-------------------------------------------------------------------------\n\/\/ AOD class for photon and other particles storage and \n\/\/ correlation studies\n\/\/ Author: Yves Schutz, CERN, Gustavo Conesa, INFN\n\/\/-------------------------------------------------------------------------\n\n\/\/-- ROOT system --\n\n\/\/-- Analysis system\n#include \"AliAODPWG4ParticleCorrelation.h\"\n\nClassImp(AliAODPWG4ParticleCorrelation)\n\n\n\/\/______________________________________________________________________________\n AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation() :\n AliAODPWG4Particle(), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0),\n fListOfObjArrays(new TList)\n{\n \/\/ constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(Double_t px, Double_t py, Double_t pz, Double_t e):\n AliAODPWG4Particle(), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(),\n fCorrBkg(), fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n SetMomentum(new TLorentzVector(px, py, pz, e));\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(TLorentzVector & p):\n AliAODPWG4Particle(p), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(AliAODPWG4Particle & p):\n AliAODPWG4Particle(p), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(),fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n \n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::~AliAODPWG4ParticleCorrelation() \n{\n \/\/ destructor\n if(fListOfObjArrays){\n fListOfObjArrays->Clear();\n delete fListOfObjArrays ;\n }\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(const AliAODPWG4ParticleCorrelation& part) :\n AliAODPWG4Particle(part), fIsolated(part.fIsolated),\n fLeadingDetector(part.fLeadingDetector), fLeading(part.fLeading), \n fCorrJet(part.fCorrJet), fCorrBkg(part.fCorrBkg), fRefJet(part.fRefJet), \n fListOfObjArrays()\n{\n \/\/ Copy constructor\n\n}\n\n\/\/______________________________________________________________________________\n\/\/AliAODPWG4ParticleCorrelation& AliAODPWG4ParticleCorrelation::operator=(const AliAODPWG4ParticleCorrelation& part)\n\/\/{\n\/\/ \/\/ Assignment operator\n\/\/ if(this!=&part) {\n\/\/ \n\/\/ fIsolated = part.fIsolated;\n\/\/ fRefJet = part.fRefJet ;\n\/\/ fLeadingDetector =part.fLeadingDetector;\n\/\/ fLeading = part.fLeading;\n\/\/ fCorrJet = part.fCorrJet ;\n\/\/ fCorrBkg = part.fCorrBkg; \n\/\/ fListOfObjArrays = fListOfObjArrays;\n\/\/\n\/\/ }\n\/\/ \n\/\/ return *this;\n\/\/}\n\n\/\/______________________________________________________________________________\nvoid AliAODPWG4ParticleCorrelation::Print(Option_t* \/*option*\/) const \n{\n \/\/ Print information of all data members\n AliAODPWG4Particle::Print(\"\");\n\n if(fIsolated) printf(\"Isolated! \\n\");\n\n if(GetJet()) GetJet()->Print(\"\");\n\n printf(\"Leading Detector : %s\\n\",fLeadingDetector.Data());\n printf(\"Leading Particle 4-vector:\\n\");\n printf(\" E = %13.3f\", fLeading.E() );\n printf(\" Px = %13.3f\", fLeading.Px());\n printf(\" Py = %13.3f\", fLeading.Py());\n printf(\" Pz = %13.3f\\n\", fLeading.Pz());\n\n if( fListOfObjArrays) fListOfObjArrays->Print(\"\");\n}\n Set Ownership to avoid mem leaking\/**************************************************************************\n * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id: AliAODPWG4ParticleCorrelation.h $ *\/\n\n\/\/-------------------------------------------------------------------------\n\/\/ AOD class for photon and other particles storage and \n\/\/ correlation studies\n\/\/ Author: Yves Schutz, CERN, Gustavo Conesa, INFN\n\/\/-------------------------------------------------------------------------\n\n\/\/-- ROOT system --\n\n\/\/-- Analysis system\n#include \"AliAODPWG4ParticleCorrelation.h\"\n\nClassImp(AliAODPWG4ParticleCorrelation)\n\n\n\/\/______________________________________________________________________________\n AliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation() :\n AliAODPWG4Particle(), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0),\n fListOfObjArrays(new TList)\n{\n \/\/ constructor\n fListOfObjArrays->SetOwner(kTRUE);\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(Double_t px, Double_t py, Double_t pz, Double_t e):\n AliAODPWG4Particle(), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(),\n fCorrBkg(), fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n SetMomentum(new TLorentzVector(px, py, pz, e));\n fListOfObjArrays->SetOwner(kTRUE);\n\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(TLorentzVector & p):\n AliAODPWG4Particle(p), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(), fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n fListOfObjArrays->SetOwner(kTRUE);\n\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(AliAODPWG4Particle & p):\n AliAODPWG4Particle(p), fIsolated(kFALSE),\n fLeadingDetector(\"\"), fLeading(), fCorrJet(), fCorrBkg(),fRefJet(0), fListOfObjArrays(new TList)\n{\n \/\/ constructor\n fListOfObjArrays->SetOwner(kTRUE);\n\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::~AliAODPWG4ParticleCorrelation() \n{\n \/\/ destructor\n if(fListOfObjArrays){\n fListOfObjArrays->Clear();\n delete fListOfObjArrays ;\n }\n}\n\n\/\/______________________________________________________________________________\nAliAODPWG4ParticleCorrelation::AliAODPWG4ParticleCorrelation(const AliAODPWG4ParticleCorrelation& part) :\n AliAODPWG4Particle(part), fIsolated(part.fIsolated),\n fLeadingDetector(part.fLeadingDetector), fLeading(part.fLeading), \n fCorrJet(part.fCorrJet), fCorrBkg(part.fCorrBkg), fRefJet(part.fRefJet), \n fListOfObjArrays()\n{\n \/\/ Copy constructor\n\n}\n\n\/\/______________________________________________________________________________\n\/\/AliAODPWG4ParticleCorrelation& AliAODPWG4ParticleCorrelation::operator=(const AliAODPWG4ParticleCorrelation& part)\n\/\/{\n\/\/ \/\/ Assignment operator\n\/\/ if(this!=&part) {\n\/\/ \n\/\/ fIsolated = part.fIsolated;\n\/\/ fRefJet = part.fRefJet ;\n\/\/ fLeadingDetector =part.fLeadingDetector;\n\/\/ fLeading = part.fLeading;\n\/\/ fCorrJet = part.fCorrJet ;\n\/\/ fCorrBkg = part.fCorrBkg; \n\/\/ fListOfObjArrays = fListOfObjArrays;\n\/\/\n\/\/ }\n\/\/ \n\/\/ return *this;\n\/\/}\n\n\/\/______________________________________________________________________________\nvoid AliAODPWG4ParticleCorrelation::Print(Option_t* \/*option*\/) const \n{\n \/\/ Print information of all data members\n AliAODPWG4Particle::Print(\"\");\n\n if(fIsolated) printf(\"Isolated! \\n\");\n\n if(GetJet()) GetJet()->Print(\"\");\n\n printf(\"Leading Detector : %s\\n\",fLeadingDetector.Data());\n printf(\"Leading Particle 4-vector:\\n\");\n printf(\" E = %13.3f\", fLeading.E() );\n printf(\" Px = %13.3f\", fLeading.Px());\n printf(\" Py = %13.3f\", fLeading.Py());\n printf(\" Pz = %13.3f\\n\", fLeading.Pz());\n\n if( fListOfObjArrays) fListOfObjArrays->Print(\"\");\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n\n#include \"dukdemo\/scripting\/util.h\"\n#include \"dukdemo\/scripting\/World.h\"\n#include \"dukdemo\/scripting\/loaders.h\"\n\n\nnamespace dukdemo {\nnamespace scripting {\nnamespace world {\n\n\nvoid\ninit(duk_context* pContext)\n{\n\tduk_push_c_function(pContext, constructor, 1); \/\/ [ctor].\n\n\t\/\/ Initialise prototype.\n\tauto const prototypeIdx = duk_push_object(pContext); \/\/ [ctor, proto].\n#define PUSH_METHOD(method, nargs) \\\n\tduk_push_c_function(pContext, methods::method, nargs); \\\n\tduk_put_prop_string(pContext, prototypeIdx, #method)\n\n\tPUSH_METHOD(setGravity, 2);\n\tPUSH_METHOD(getGravity, 1);\n#undef PUSH_METHOD\n\n\tduk_dup(pContext, prototypeIdx); \/\/ [ctor, proto, proto].\n\n\t\/\/ Store the prototype globally under a hidden symbol.\n\tduk_put_global_string(pContext, g_worldProtoSym); \/\/ [ctor, proto].\n\n\t\/\/ Store the prototype on the constructor.\n\tduk_put_prop_string(pContext, -2, \"prototype\"); \/\/ [ctor].\n\n\t\/\/ Put the constructor on the global object.\n\tduk_put_global_string(pContext, g_worldCtorSym); \/\/ [].\n}\n\n\nb2World*\ngetOwnWorldPtr(duk_context* pContext)\n{\n\treturn static_cast(\n\t\tgetPointerFromThis(pContext, g_ownWorldPtrSym));\n}\n\n\nvoid\ninitialiseWorldObject(duk_context* pContext, duk_idx_t objIdx, b2World* pWorld)\n{\n\tassert(objIdx >= 0 && \"Index must be non-negative\");\n\tduk_get_global_string(pContext, g_worldProtoSym);\n\tduk_set_prototype(pContext, objIdx);\n\tduk_push_pointer(pContext, pWorld);\n\tduk_put_prop_string(pContext, objIdx, g_ownWorldPtrSym);\n}\n\n\nduk_idx_t\npushWorldWithoutFinalizer(duk_context* pContext, b2World* pWorld)\n{\n\tauto const worldIdx = duk_push_object(pContext);\n\tinitialiseWorldObject(pContext, worldIdx, pWorld);\n\treturn worldIdx;\n}\n\n\nduk_idx_t\npushWorldWithFinalizer(duk_context* pContext, std::unique_ptr pWorld)\n{\n\tauto const objIdx = pushWorldWithoutFinalizer(pContext, pWorld.get());\n\tduk_push_c_function(pContext, finalizer, 1);\n\tduk_set_finalizer(pContext, -2);\n\tpWorld.release();\n\treturn objIdx;\n}\n\n\nduk_ret_t\nconstructor(duk_context* pContext)\n{\n\tif (!duk_is_constructor_call(pContext))\n\t{\n\t\treturn DUK_RET_TYPE_ERROR;\n\t}\n\n\tb2Vec2 gravity{0.0f, 0.0f};\n\tif (!loadVec2(pContext, 0, &gravity))\n\t{\n\t\treturn DUK_RET_TYPE_ERROR;\n\t}\n\n\tauto pWorld = std::make_unique(gravity);\n\tduk_push_this(pContext);\n\tinitialiseWorldObject(pContext, 1, pWorld.get());\n\tduk_push_c_function(pContext, finalizer, 1);\n\tduk_set_finalizer(pContext, -2);\n\tpWorld.release();\n\treturn 0;\n}\n\n\nduk_ret_t\nfinalizer(duk_context* pContext)\n{\n\tduk_get_prop_string(pContext, 0, g_ownWorldPtrSym);\n\tauto* const pWorld = static_cast(duk_get_pointer(pContext, 1));\n\tduk_pop(pContext);\n\n\t\/\/ If the world pointer is null, we're finalising something which has\n\t\/\/ already been destroyed, or the prototype itself, so can bail out.\n\tif (pWorld == nullptr)\n\t{\n\t\treturn 0;\n\t}\n\n\t\/\/ Replace the world's internal pointer with a nullptr.\n\tduk_push_pointer(pContext, nullptr);\n\tduk_put_prop_string(pContext, 0, g_ownWorldPtrSym);\n\tpWorld->~b2World();\n\treturn 0;\n}\n\n\nduk_ret_t\nmethods::setGravity(duk_context* pContext)\n{\n\tassert(duk_is_number(pContext, 0) && duk_is_number(pContext, 1) &&\n\t\t\"setGravity requires two arguments\");\n\tb2Vec2 vec{\n\t\tfloat(duk_get_number(pContext, 0)),\n\t\tfloat(duk_get_number(pContext, 1))\n\t};\n\tduk_pop_2(pContext);\n\n\tauto* const pWorld = getOwnWorldPtr(pContext);\n\tpWorld->SetGravity(vec);\n\treturn 0;\n}\n\n\nduk_ret_t\nmethods::getGravity(duk_context* pContext)\n{\n\tassert(duk_is_array(pContext, 0) && \"getGravity requires array argument\");\n\tauto const* const pWorld = getOwnWorldPtr(pContext);\n\twriteVec2ToArray(pContext, 0, pWorld->GetGravity());\n\treturn 1;\n}\n\n\n} \/\/ namespace world\n} \/\/ namespace scripting\n} \/\/ namespace dukdemo\nAdd World#createBody#include \n\n#include \n#include \n\n#include \n\n#include \"dukdemo\/scripting\/util.h\"\n#include \"dukdemo\/scripting\/Body.h\"\n#include \"dukdemo\/scripting\/World.h\"\n#include \"dukdemo\/scripting\/loaders.h\"\n\n\nnamespace dukdemo {\nnamespace scripting {\nnamespace world {\n\n\nvoid\ninit(duk_context* pContext)\n{\n\tduk_push_c_function(pContext, constructor, 1); \/\/ [ctor].\n\n\t\/\/ Initialise prototype.\n\tauto const prototypeIdx = duk_push_object(pContext); \/\/ [ctor, proto].\n#define PUSH_METHOD(method, nargs) \\\n\tduk_push_c_function(pContext, methods::method, nargs); \\\n\tduk_put_prop_string(pContext, prototypeIdx, #method)\n\n\tPUSH_METHOD(setGravity, 2);\n\tPUSH_METHOD(getGravity, 1);\n#undef PUSH_METHOD\n\n\tduk_dup(pContext, prototypeIdx); \/\/ [ctor, proto, proto].\n\n\t\/\/ Store the prototype globally under a hidden symbol.\n\tduk_put_global_string(pContext, g_worldProtoSym); \/\/ [ctor, proto].\n\n\t\/\/ Store the prototype on the constructor.\n\tduk_put_prop_string(pContext, -2, \"prototype\"); \/\/ [ctor].\n\n\t\/\/ Put the constructor on the global object.\n\tduk_put_global_string(pContext, g_worldCtorSym); \/\/ [].\n}\n\n\nb2World*\ngetOwnWorldPtr(duk_context* pContext)\n{\n\treturn static_cast(\n\t\tgetPointerFromThis(pContext, g_ownWorldPtrSym));\n}\n\n\nvoid\ninitialiseWorldObject(duk_context* pContext, duk_idx_t objIdx, b2World* pWorld)\n{\n\tassert(objIdx >= 0 && \"Index must be non-negative\");\n\tduk_get_global_string(pContext, g_worldProtoSym);\n\tduk_set_prototype(pContext, objIdx);\n\tduk_push_pointer(pContext, pWorld);\n\tduk_put_prop_string(pContext, objIdx, g_ownWorldPtrSym);\n}\n\n\nduk_idx_t\npushWorldWithoutFinalizer(duk_context* pContext, b2World* pWorld)\n{\n\tauto const worldIdx = duk_push_object(pContext);\n\tinitialiseWorldObject(pContext, worldIdx, pWorld);\n\treturn worldIdx;\n}\n\n\nduk_idx_t\npushWorldWithFinalizer(duk_context* pContext, std::unique_ptr pWorld)\n{\n\tauto const objIdx = pushWorldWithoutFinalizer(pContext, pWorld.get());\n\tduk_push_c_function(pContext, finalizer, 1);\n\tduk_set_finalizer(pContext, -2);\n\tpWorld.release();\n\treturn objIdx;\n}\n\n\nduk_ret_t\nconstructor(duk_context* pContext)\n{\n\tif (!duk_is_constructor_call(pContext))\n\t{\n\t\treturn DUK_RET_TYPE_ERROR;\n\t}\n\n\tb2Vec2 gravity{0.0f, 0.0f};\n\tif (!loadVec2(pContext, 0, &gravity))\n\t{\n\t\treturn DUK_RET_TYPE_ERROR;\n\t}\n\n\tauto pWorld = std::make_unique(gravity);\n\tduk_push_this(pContext);\n\tinitialiseWorldObject(pContext, 1, pWorld.get());\n\tduk_push_c_function(pContext, finalizer, 1);\n\tduk_set_finalizer(pContext, -2);\n\tpWorld.release();\n\treturn 0;\n}\n\n\nduk_ret_t\nfinalizer(duk_context* pContext)\n{\n\tduk_get_prop_string(pContext, 0, g_ownWorldPtrSym);\n\tauto* const pWorld = static_cast(duk_get_pointer(pContext, 1));\n\tduk_pop(pContext);\n\n\t\/\/ If the world pointer is null, we're finalising something which has\n\t\/\/ already been destroyed, or the prototype itself, so can bail out.\n\tif (pWorld == nullptr)\n\t{\n\t\treturn 0;\n\t}\n\n\t\/\/ Replace the world's internal pointer with a nullptr.\n\tduk_push_pointer(pContext, nullptr);\n\tduk_put_prop_string(pContext, 0, g_ownWorldPtrSym);\n\tpWorld->~b2World();\n\treturn 0;\n}\n\n\nduk_ret_t\nmethods::setGravity(duk_context* pContext)\n{\n\tassert(duk_is_number(pContext, 0) && duk_is_number(pContext, 1) &&\n\t\t\"setGravity requires two arguments\");\n\tb2Vec2 vec{\n\t\tfloat(duk_get_number(pContext, 0)),\n\t\tfloat(duk_get_number(pContext, 1))\n\t};\n\tduk_pop_2(pContext);\n\n\tauto* const pWorld = getOwnWorldPtr(pContext);\n\tpWorld->SetGravity(vec);\n\treturn 0;\n}\n\n\nduk_ret_t\nmethods::getGravity(duk_context* pContext)\n{\n\tassert(duk_is_array(pContext, 0) && \"getGravity requires array argument\");\n\tauto const* const pWorld = getOwnWorldPtr(pContext);\n\twriteVec2ToArray(pContext, 0, pWorld->GetGravity());\n\treturn 1;\n}\n\n\nduk_ret_t\nmethods::createBody(duk_context* pContext)\n{\n\t\/\/ Stack: [bodyDef].\n\tb2BodyDef bodyDef;\n\tif (!loadBodyDef(pContext, 0, &bodyDef))\n\t{\n\t\treturn DUK_RET_TYPE_ERROR;\n\t}\n\tduk_pop(pContext);\n\n\t\/\/ Create object.\n\tauto const bodyIdx = duk_push_object(pContext);\n\t\/\/ Stack: [body].\n\n\t\/\/ Set internal prototype to Body.prototype.\n\tduk_get_global_string(pContext, g_bodyProtoSym);\n\tduk_set_prototype(pContext, bodyIdx);\n\t\/\/ Stack: [body].\n\n\t\/\/ Get the world pointer.\n\tduk_push_this(pContext);\n\tduk_get_prop_string(pContext, -1, g_ownWorldPtrSym);\n\t\/\/ Stack: [body, world, pWorld].\n\n\tauto* const pWorld = static_cast(duk_get_pointer(pContext, -1));\n\tduk_pop(pContext);\n\t\/\/ Stack: [body, world].\n\n\tduk_put_prop_string(pContext, bodyIdx, g_ownWorldPropSym);\n\t\/\/ Stack: [body].\n\n\t\/\/ Create the b2Body and add to the JS object.\n\tauto* const pBody = pWorld->CreateBody(&bodyDef);\n\tduk_push_pointer(pContext, pBody);\n\tduk_put_prop_string(pContext, bodyIdx, g_ownWorldPtrSym);\n\t\/\/ Stack: [body].\n\treturn 1;\n}\n\n\nduk_ret_t\nmethods::destroyBody(duk_context* pContext)\n{\n\tbody::destroyBodyAt(pContext, 0);\n\treturn 0;\n}\n\n\nduk_ret_t\nmethods::toString(duk_context* pContext)\n{\n\tduk_push_string(pContext, \"[World]\");\n\treturn 1;\n}\n\n\n} \/\/ namespace world\n} \/\/ namespace scripting\n} \/\/ namespace dukdemo\n<|endoftext|>"} {"text":"\/\/\/ HEADER\n#include \"assign_feature_classifications.h\"\n\n\/\/\/ PROJECT\n#include \n#include \n#include \n#include \n#include \n#include \n\nCSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node)\n\nusing namespace csapex;\nusing namespace connection_types;\n\nAssignFeatureClassifications::AssignFeatureClassifications()\n{\n\n}\n\nvoid AssignFeatureClassifications::setup(NodeModifier &node_modifier)\n{\n in_features_ = node_modifier.addInput(\"Features\");\n in_labels_ = node_modifier.addOptionalInput(\"Classifications\");\n out_ = node_modifier.addOutput(\"Labelled features\");\n}\n\nvoid AssignFeatureClassifications::setupParameters(Parameterizable ¶meters)\n{\n parameters.addParameter(param::ParameterFactory::declareRange(\"label\", 0, 255, 0, 1),\n label_);\n}\n\nvoid AssignFeatureClassifications::process()\n{\n std::shared_ptr const> in_features =\n msg::getMessage(in_features_);\n std::shared_ptr> out_features;\n\n if(msg::hasMessage(in_labels_)) {\n std::shared_ptr const> in_labels = msg::getMessage(in_labels_);\n\n if(in_features->size() != in_labels->size())\n throw std::runtime_error(\"Label count != FeatureMsg count!\");\n\n for(std::size_t i = 0 ; i < in_features->size() ; ++i) {\n FeaturesMessage feature = in_features->at(i);\n int label = (int) in_labels->at(i);\n feature.classification = label;\n out_features->emplace_back(feature);\n }\n } else {\n for(FeaturesMessage feature : *in_features) {\n feature.classification = label_;\n out_features->emplace_back(feature);\n }\n }\n msg::publish(out_, out_features);\n}\nsegfault fixed\/\/\/ HEADER\n#include \"assign_feature_classifications.h\"\n\n\/\/\/ PROJECT\n#include \n#include \n#include \n#include \n#include \n#include \n\nCSAPEX_REGISTER_CLASS(csapex::AssignFeatureClassifications, csapex::Node)\n\nusing namespace csapex;\nusing namespace connection_types;\n\nAssignFeatureClassifications::AssignFeatureClassifications()\n{\n\n}\n\nvoid AssignFeatureClassifications::setup(NodeModifier &node_modifier)\n{\n in_features_ = node_modifier.addInput(\"Features\");\n in_labels_ = node_modifier.addOptionalInput(\"Classifications\");\n out_ = node_modifier.addOutput(\"Labelled features\");\n}\n\nvoid AssignFeatureClassifications::setupParameters(Parameterizable ¶meters)\n{\n parameters.addParameter(param::ParameterFactory::declareRange(\"label\", 0, 255, 0, 1),\n label_);\n}\n\nvoid AssignFeatureClassifications::process()\n{\n std::shared_ptr const> in_features =\n msg::getMessage(in_features_);\n std::shared_ptr> out_features = std::make_shared>();\n\n if(msg::hasMessage(in_labels_)) {\n std::shared_ptr const> in_labels = msg::getMessage(in_labels_);\n\n if(in_features->size() != in_labels->size())\n throw std::runtime_error(\"Label count != FeatureMsg count!\");\n\n for(std::size_t i = 0 ; i < in_features->size() ; ++i) {\n FeaturesMessage feature = in_features->at(i);\n int label = (int) in_labels->at(i);\n feature.classification = label;\n out_features->emplace_back(feature);\n }\n } else {\n for(FeaturesMessage feature : *in_features) {\n feature.classification = label_;\n out_features->emplace_back(feature);\n }\n }\n msg::publish(out_, out_features);\n}\n<|endoftext|>"} {"text":"#include \"dsa_common.h\"\n\n#include \"session.h\"\n\n#include \"client.h\"\n#include \"server.h\"\n\n#include \"stream\/ack_stream.h\"\n\nnamespace dsa {\n\nSession::Session(LinkStrandRef strand, const std::string &session_id)\n : _strand(std::move(strand)),\n _session_id(session_id),\n requester(*this),\n responder(*this),\n _ack_stream(new AckStream(get_ref())) {}\n\nSession::~Session() = default;\n\nvoid Session::connected(shared_ptr_ connection) {\n if (_connection != nullptr) {\n _connection->close();\n }\n _connection = std::move(connection);\n}\n\nvoid Session::close_impl() {\n requester.close_impl();\n responder.close_impl();\n if (_connection != nullptr) {\n _connection->close();\n }\n _ack_stream.reset();\n}\n\nvoid Session::disconnected(const shared_ptr_ &connection) {\n if (_connection.get() == connection.get()) {\n _connection.reset();\n }\n}\n\nvoid Session::check_pending_acks(int32_t ack) {\n while (!_pending_acks.empty()) {\n AckHolder &first = _pending_acks.front();\n uint32_t d = static_cast(ack - first.ack);\n if (d < 0x10000000) {\n first.callback(true);\n _pending_acks.pop_front();\n } else {\n return;\n }\n }\n}\n\nvoid Session::receive_message(MessageRef &&message) {\n LOG_TRACE(_strand->logger(), LOG << \"receive message: \" << message->type());\n\n if (message->need_ack()) {\n _ack_stream->add_ack(message->get_ack_id());\n }\n if (message->type() == MessageType::ACK) {\n check_pending_acks(DOWN_CAST(message.get())->get_ack_id());\n return;\n }\n if (message->is_request()) {\n \/\/ responder receive request and send response\n responder.receive_message(std::move(message));\n } else {\n \/\/ requester sent request and receive response\n requester.receive_message(std::move(message));\n }\n}\n\nref_ Session::get_next_ready_stream() {\n while (!_write_streams.empty()) {\n ref_ stream = std::move(_write_streams.front());\n _write_streams.pop_front();\n if (stream->peek_next_message_size(0) > 0) {\n return std::move(stream);\n }\n }\n return nullptr;\n}\n\nsize_t Session::peek_next_message(size_t availible) {\n while (!_write_streams.empty()) {\n ref_ &stream = _write_streams.front();\n size_t size = stream->peek_next_message_size(availible);\n if (size > 0) {\n return size;\n }\n _write_streams.pop_front();\n }\n return 0;\n}\n\nvoid Session::write_loop(ref_ sthis) {\n Connection *connection = sthis->_connection.get();\n if (connection == nullptr) {\n sthis->_is_writing = false;\n return;\n }\n\n size_t next_message_size =\n sthis->peek_next_message(connection->max_buffer_size());\n if (next_message_size == 0) {\n sthis->_is_writing = false;\n return;\n }\n\n sthis->_is_writing = true;\n std::vector &buf = connection->_write_buffer;\n\n size_t total_size = 0;\n while (next_message_size > 0 &&\n total_size < connection->preferred_buffer_size() &&\n total_size + next_message_size < connection->max_buffer_size()) {\n auto stream = sthis->get_next_ready_stream();\n AckCallback ack_callback;\n MessageCRef message = stream->get_next_message(ack_callback);\n\n if (buf.size() < connection->max_buffer_size() &&\n total_size + message->size() > buf.size()) {\n buf.resize(buf.size() * 4);\n }\n\n ++sthis->_waiting_ack;\n if (ack_callback != nullptr) {\n sthis->_pending_acks.push_back(\n AckHolder(sthis->_waiting_ack, std::move(ack_callback)));\n }\n\n LOG_TRACE(sthis->_strand->logger(),\n LOG << \"send message: \" << message->type());\n\n message->write(&buf[total_size], stream->rid, sthis->_waiting_ack);\n total_size += message->size();\n\n next_message_size =\n sthis->peek_next_message(connection->max_buffer_size() - total_size);\n }\n\n connection->write(\n buf.data(),\n total_size, [sthis = std::move(sthis)](\n const boost::system::error_code &error) mutable {\n LinkStrandRef strand = sthis->_strand;\n (*strand)()->dispatch([sthis = std::move(sthis)]() mutable {\n Session::write_loop(std::move(sthis));\n });\n });\n}\n\nvoid Session::write_stream(ref_ &&stream) {\n _write_streams.push_back(std::move(stream));\n if (!_is_writing) {\n write_loop(get_ref());\n }\n}\n\n} \/\/ namespace dsaremove preferred packet size optimization#include \"dsa_common.h\"\n\n#include \"session.h\"\n\n#include \"client.h\"\n#include \"server.h\"\n\n#include \"stream\/ack_stream.h\"\n\nnamespace dsa {\n\nSession::Session(LinkStrandRef strand, const std::string &session_id)\n : _strand(std::move(strand)),\n _session_id(session_id),\n requester(*this),\n responder(*this),\n _ack_stream(new AckStream(get_ref())) {}\n\nSession::~Session() = default;\n\nvoid Session::connected(shared_ptr_ connection) {\n if (_connection != nullptr) {\n _connection->close();\n }\n _connection = std::move(connection);\n}\n\nvoid Session::close_impl() {\n requester.close_impl();\n responder.close_impl();\n if (_connection != nullptr) {\n _connection->close();\n }\n _ack_stream.reset();\n}\n\nvoid Session::disconnected(const shared_ptr_ &connection) {\n if (_connection.get() == connection.get()) {\n _connection.reset();\n }\n}\n\nvoid Session::check_pending_acks(int32_t ack) {\n while (!_pending_acks.empty()) {\n AckHolder &first = _pending_acks.front();\n uint32_t d = static_cast(ack - first.ack);\n if (d < 0x10000000) {\n first.callback(true);\n _pending_acks.pop_front();\n } else {\n return;\n }\n }\n}\n\nvoid Session::receive_message(MessageRef &&message) {\n LOG_TRACE(_strand->logger(), LOG << \"receive message: \" << message->type());\n\n if (message->need_ack()) {\n _ack_stream->add_ack(message->get_ack_id());\n }\n if (message->type() == MessageType::ACK) {\n check_pending_acks(DOWN_CAST(message.get())->get_ack_id());\n return;\n }\n if (message->is_request()) {\n \/\/ responder receive request and send response\n responder.receive_message(std::move(message));\n } else {\n \/\/ requester sent request and receive response\n requester.receive_message(std::move(message));\n }\n}\n\nref_ Session::get_next_ready_stream() {\n while (!_write_streams.empty()) {\n ref_ stream = std::move(_write_streams.front());\n _write_streams.pop_front();\n if (stream->peek_next_message_size(0) > 0) {\n return std::move(stream);\n }\n }\n return nullptr;\n}\n\nsize_t Session::peek_next_message(size_t availible) {\n while (!_write_streams.empty()) {\n ref_ &stream = _write_streams.front();\n size_t size = stream->peek_next_message_size(availible);\n if (size > 0) {\n return size;\n }\n _write_streams.pop_front();\n }\n return 0;\n}\n\nvoid Session::write_loop(ref_ sthis) {\n Connection *connection = sthis->_connection.get();\n if (connection == nullptr) {\n sthis->_is_writing = false;\n return;\n }\n\n size_t next_message_size =\n sthis->peek_next_message(connection->max_buffer_size());\n if (next_message_size == 0) {\n sthis->_is_writing = false;\n return;\n }\n\n sthis->_is_writing = true;\n std::vector &buf = connection->_write_buffer;\n\n size_t total_size = 0;\n while (next_message_size > 0 &&\n total_size + next_message_size < connection->max_buffer_size()) {\n auto stream = sthis->get_next_ready_stream();\n AckCallback ack_callback;\n MessageCRef message = stream->get_next_message(ack_callback);\n\n if (buf.size() < connection->max_buffer_size() &&\n total_size + message->size() > buf.size()) {\n buf.resize(buf.size() * 4);\n }\n\n ++sthis->_waiting_ack;\n if (ack_callback != nullptr) {\n sthis->_pending_acks.push_back(\n AckHolder(sthis->_waiting_ack, std::move(ack_callback)));\n }\n\n LOG_TRACE(sthis->_strand->logger(),\n LOG << \"send message: \" << message->type());\n\n message->write(&buf[total_size], stream->rid, sthis->_waiting_ack);\n total_size += message->size();\n\n next_message_size =\n sthis->peek_next_message(connection->max_buffer_size() - total_size);\n }\n\n connection->write(\n buf.data(),\n total_size, [sthis = std::move(sthis)](\n const boost::system::error_code &error) mutable {\n LinkStrandRef strand = sthis->_strand;\n (*strand)()->dispatch([sthis = std::move(sthis)]() mutable {\n Session::write_loop(std::move(sthis));\n });\n });\n}\n\nvoid Session::write_stream(ref_ &&stream) {\n _write_streams.push_back(std::move(stream));\n if (!_is_writing) {\n write_loop(get_ref());\n }\n}\n\n} \/\/ namespace dsa<|endoftext|>"} {"text":"\/*\n * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa\n * .wWV!!!T |Wm; dQ[ $WF _mWT!\"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW\n * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ\n * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk

ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<. a J@\\\n * this list of conditions and the j(]1u\n\nnamespace gcn\n{\n\n void SDLGraphics::setTarget(SDL_Surface* target)\n {\n mTarget = target;\n Rectangle area;\n area.x = 0;\n area.y = 0;\n area.width = target->w;\n area.height = target->h;\n pushClipArea(area);\n\n } \/\/ end setTarget\n\n bool SDLGraphics::pushClipArea(Rectangle area)\n {\n SDL_Rect rect;\n bool result = Graphics::pushClipArea(area);\n\n ClipRectangle carea = mClipStack.top();\n rect.x = carea.x;\n rect.y = carea.y;\n rect.w = carea.width;\n rect.h = carea.height;\n \n SDL_SetClipRect(mTarget, &rect);\n\n return result;\n \n } \/\/ end pushClipArea\n\n void SDLGraphics::popClipArea()\n {\n SDL_Rect rect;\n Graphics::popClipArea();\n\n ClipRectangle carea = mClipStack.top();\n rect.x = carea.x;\n rect.y = carea.y;\n rect.w = carea.width;\n rect.h = carea.height;\n \n SDL_SetClipRect(mTarget, &rect); \n\n } \/\/ end popClipArea\n \n SDL_Surface* SDLGraphics::getTarget() const\n {\n return mTarget;\n\n } \/\/ end getTarget \n \n void SDLGraphics::drawImage(const Image* image, int srcX,\n int srcY, int dstX, int dstY,\n int width, int height)\n {\n ClipRectangle top = mClipStack.top();\n SDL_Rect src;\n SDL_Rect dst;\n src.x = srcX;\n src.y = srcY;\n src.w = width;\n src.h = height;\n dst.x = dstX + top.xOffset;\n dst.y = dstY + top.yOffset;\n\n SDL_Surface* srcImage = (SDL_Surface*)image->_getData();\n \n SDL_BlitSurface(srcImage, &src, mTarget, &dst);\n \n } \/\/ end drawImage\n\n void SDLGraphics::fillRectangle(const Rectangle& rectangle)\n {\n \n Rectangle area = rectangle;\n ClipRectangle top = mClipStack.top(); \n area.x += top.xOffset;\n area.y += top.yOffset;\n\n if(!area.intersect(top))\n {\n return;\n }\n \n SDL_Rect rect;\n rect.x = area.x;\n rect.y = area.y;\n rect.w = area.width;\n rect.h = area.height;\n \n Uint32 color = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n SDL_FillRect(mTarget, &rect, color);\n\n } \/\/ end fillRectangle\n\n void SDLGraphics::drawPoint(int x, int y)\n {\n ClipRectangle top = mClipStack.top();\n x += top.xOffset;\n y += top.yOffset;\n\n if(!top.isPointInRect(x,y))\n return;\n\n SDLputPixel(mTarget, x, y, mColor);\n \n } \/\/ end drawPoint\n\n void SDLGraphics::drawHLine(int x1, int y, int x2)\n {\n ClipRectangle top = mClipStack.top();\n x1 += top.xOffset;\n y += top.yOffset;\n x2 += top.xOffset;\n\n if (y < top.y || y >= top.y + top.height)\n return;\n \n if (x1 > x2)\n {\n x1 ^= x2;\n x2 ^= x1;\n x1 ^= x2;\n }\n\n if (top.x > x1)\n {\n if (top.x > x2)\n {\n return;\n }\n x1 = top.x;\n }\n\n if (top.x + top.width <= x2)\n {\n if (top.x + top.width <= x1)\n {\n return;\n } \n x2 = top.x + top.width -1;\n }\n \n int bpp = mTarget->format->BytesPerPixel;\n \n SDL_LockSurface(mTarget);\n \n Uint8 *p = (Uint8 *)mTarget->pixels + y * mTarget->pitch + x1 * bpp;\n \n Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n \n switch(bpp) {\n case 1:\n {\n for (;x1 <= x2; ++x1)\n { \n *(p++) = pixel;\n }\n } break;\n \n case 2:\n {\n Uint16* q = (Uint16*)p;\n for (;x1 <= x2; ++x1)\n {\n *(q++) = pixel;\n }\n } break;\n \n case 3: \n {\n if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {\n for (;x1 <= x2; ++x1)\n {\n p[0] = (pixel >> 16) & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = pixel & 0xff;\n p += 3;\n }\n }\n else\n {\n for (;x1 <= x2; ++x1)\n {\n p[0] = pixel & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = (pixel >> 16) & 0xff;\n p += 3;\n }\n } \n } break;\n \n case 4:\n {\n Uint32* q = (Uint32*)p;\n for (;x1 <= x2; ++x1)\n {\n *(q++) = pixel;\n }\n } break;\n } \/\/ end switch\n \n SDL_UnlockSurface(mTarget);\n \n } \/\/ end drawHLine\n\n void SDLGraphics::drawVLine(int x, int y1, int y2)\n {\n ClipRectangle top = mClipStack.top();\n x += top.xOffset;\n y1 += top.yOffset;\n y2 += top.yOffset;\n\n if (x < top.x || x >= top.x + top.width)\n return;\n \n if (y1 > y2)\n {\n y1 ^= y2;\n y2 ^= y1;\n y1 ^= y2;\n }\n\n if (top.y > y1)\n {\n if (top.y > y2)\n {\n return;\n }\n y1 = top.y;\n }\n\n if (top.y + top.height <= y2)\n {\n if (top.y + top.height <= y1)\n {\n return;\n } \n y2 = top.y + top.height - 1;\n }\n \n int bpp = mTarget->format->BytesPerPixel;\n \n SDL_LockSurface(mTarget);\n \n Uint8 *p = (Uint8 *)mTarget->pixels + y1 * mTarget->pitch + x * bpp;\n \n Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n \n switch(bpp) {\n case 1:\n {\n for (;y1 <= y2; ++y1)\n { \n *p = pixel;\n p += mTarget->pitch;\n }\n } break;\n \n case 2:\n {\n for (;y1 <= y2; ++y1)\n {\n *(Uint16*)p = pixel;\n p += mTarget->pitch;\n }\n } break;\n \n case 3: \n {\n if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {\n for (;y1 <= y2; ++y1)\n {\n p[0] = (pixel >> 16) & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = pixel & 0xff;\n p += mTarget->pitch;\n }\n }\n else\n {\n for (;y1 <= y2; ++y1)\n {\n p[0] = pixel & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = (pixel >> 16) & 0xff;\n p += mTarget->pitch;\n }\n } \n } break;\n \n case 4:\n {\n for (;y1 <= y2; ++y1)\n {\n *(Uint32*)p = pixel;\n p += mTarget->pitch;\n }\n } break;\n } \/\/ end switch\n \n SDL_UnlockSurface(mTarget);\n\n } \/\/ end drawVLine\n\n void SDLGraphics::drawRectangle(const Rectangle& rectangle)\n {\n int x1 = rectangle.x;\n int x2 = rectangle.x + rectangle.width - 1;\n int y1 = rectangle.y;\n int y2 = rectangle.y + rectangle.height - 1;\n\n drawHLine(x1, y1, x2);\n drawHLine(x1, y2, x2);\n\n drawVLine(x1, y1, y2);\n drawVLine(x2, y1, y2);\n \n } \/\/ end drawRectangle\n\n void SDLGraphics::drawLine(int x1, int y1, int x2, int y2)\n {\n\n if (x1 == x2)\n {\n drawVLine(x1, y1, y2);\n return;\n }\n if (y1 == y2)\n {\n drawHLine(x1, y1, x2);\n return;\n }\n \n bool yLonger = false;\n int incrementVal;\n int endVal;\n \n int shortLen = y2 - y1;\n int longLen = x2 - x1;\n\n if (std::abs(shortLen) > std::abs(longLen))\n {\n int swap = shortLen;\n shortLen = longLen;\n longLen = swap;\n yLonger = true;\n }\n\t\n endVal = longLen;\n\n if (longLen< 0)\n {\n incrementVal = -1;\n longLen = - longLen;\n }\n else\n {\n incrementVal = 1;\n }\n \n double decInc;\n\n if (longLen == 0)\n {\n decInc = (double)shortLen;\n }\n else\n {\n decInc = (double)shortLen \/ (double)longLen;\n }\n \n double j = 0.0;\n\n if (yLonger)\n {\n for (int i = 0; i != endVal; i += incrementVal)\n {\n drawPoint(x1 + (int)j, y1 + i);\n j += decInc;\n }\n }\n else\n {\n for (int i = 0; i != endVal; i += incrementVal)\n {\n drawPoint(x1 + i, y1 + (int)j);\n j += decInc;\n }\n } \n } \/\/ end drawLine\n \n} \/\/ end gcn\nFixed drawLine to draw the last pixel.\/*\n * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa\n * .wWV!!!T |Wm; dQ[ $WF _mWT!\"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW\n * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ\n * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk

ws?a-?' ._\/L #'\n * binary forms, with or without )4d[#7r, . ' )d`)[\n * modification, are permitted provided _Q-5'5W..j\/?' -?!\\)cam'\n * that the following conditions are met: j<. a J@\\\n * this list of conditions and the j(]1u\n\nnamespace gcn\n{\n\n void SDLGraphics::setTarget(SDL_Surface* target)\n {\n mTarget = target;\n Rectangle area;\n area.x = 0;\n area.y = 0;\n area.width = target->w;\n area.height = target->h;\n pushClipArea(area);\n\n } \/\/ end setTarget\n\n bool SDLGraphics::pushClipArea(Rectangle area)\n {\n SDL_Rect rect;\n bool result = Graphics::pushClipArea(area);\n\n ClipRectangle carea = mClipStack.top();\n rect.x = carea.x;\n rect.y = carea.y;\n rect.w = carea.width;\n rect.h = carea.height;\n \n SDL_SetClipRect(mTarget, &rect);\n\n return result;\n \n } \/\/ end pushClipArea\n\n void SDLGraphics::popClipArea()\n {\n SDL_Rect rect;\n Graphics::popClipArea();\n\n ClipRectangle carea = mClipStack.top();\n rect.x = carea.x;\n rect.y = carea.y;\n rect.w = carea.width;\n rect.h = carea.height;\n \n SDL_SetClipRect(mTarget, &rect); \n\n } \/\/ end popClipArea\n \n SDL_Surface* SDLGraphics::getTarget() const\n {\n return mTarget;\n\n } \/\/ end getTarget \n \n void SDLGraphics::drawImage(const Image* image, int srcX,\n int srcY, int dstX, int dstY,\n int width, int height)\n {\n ClipRectangle top = mClipStack.top();\n SDL_Rect src;\n SDL_Rect dst;\n src.x = srcX;\n src.y = srcY;\n src.w = width;\n src.h = height;\n dst.x = dstX + top.xOffset;\n dst.y = dstY + top.yOffset;\n\n SDL_Surface* srcImage = (SDL_Surface*)image->_getData();\n \n SDL_BlitSurface(srcImage, &src, mTarget, &dst);\n \n } \/\/ end drawImage\n\n void SDLGraphics::fillRectangle(const Rectangle& rectangle)\n {\n \n Rectangle area = rectangle;\n ClipRectangle top = mClipStack.top(); \n area.x += top.xOffset;\n area.y += top.yOffset;\n\n if(!area.intersect(top))\n {\n return;\n }\n \n SDL_Rect rect;\n rect.x = area.x;\n rect.y = area.y;\n rect.w = area.width;\n rect.h = area.height;\n \n Uint32 color = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n SDL_FillRect(mTarget, &rect, color);\n\n } \/\/ end fillRectangle\n\n void SDLGraphics::drawPoint(int x, int y)\n {\n ClipRectangle top = mClipStack.top();\n x += top.xOffset;\n y += top.yOffset;\n\n if(!top.isPointInRect(x,y))\n return;\n\n SDLputPixel(mTarget, x, y, mColor);\n \n } \/\/ end drawPoint\n\n void SDLGraphics::drawHLine(int x1, int y, int x2)\n {\n ClipRectangle top = mClipStack.top();\n x1 += top.xOffset;\n y += top.yOffset;\n x2 += top.xOffset;\n\n if (y < top.y || y >= top.y + top.height)\n return;\n \n if (x1 > x2)\n {\n x1 ^= x2;\n x2 ^= x1;\n x1 ^= x2;\n }\n\n if (top.x > x1)\n {\n if (top.x > x2)\n {\n return;\n }\n x1 = top.x;\n }\n\n if (top.x + top.width <= x2)\n {\n if (top.x + top.width <= x1)\n {\n return;\n } \n x2 = top.x + top.width -1;\n }\n \n int bpp = mTarget->format->BytesPerPixel;\n \n SDL_LockSurface(mTarget);\n \n Uint8 *p = (Uint8 *)mTarget->pixels + y * mTarget->pitch + x1 * bpp;\n \n Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n \n switch(bpp) {\n case 1:\n {\n for (;x1 <= x2; ++x1)\n { \n *(p++) = pixel;\n }\n } break;\n \n case 2:\n {\n Uint16* q = (Uint16*)p;\n for (;x1 <= x2; ++x1)\n {\n *(q++) = pixel;\n }\n } break;\n \n case 3: \n {\n if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {\n for (;x1 <= x2; ++x1)\n {\n p[0] = (pixel >> 16) & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = pixel & 0xff;\n p += 3;\n }\n }\n else\n {\n for (;x1 <= x2; ++x1)\n {\n p[0] = pixel & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = (pixel >> 16) & 0xff;\n p += 3;\n }\n } \n } break;\n \n case 4:\n {\n Uint32* q = (Uint32*)p;\n for (;x1 <= x2; ++x1)\n {\n *(q++) = pixel;\n }\n } break;\n } \/\/ end switch\n \n SDL_UnlockSurface(mTarget);\n \n } \/\/ end drawHLine\n\n void SDLGraphics::drawVLine(int x, int y1, int y2)\n {\n ClipRectangle top = mClipStack.top();\n x += top.xOffset;\n y1 += top.yOffset;\n y2 += top.yOffset;\n\n if (x < top.x || x >= top.x + top.width)\n return;\n \n if (y1 > y2)\n {\n y1 ^= y2;\n y2 ^= y1;\n y1 ^= y2;\n }\n\n if (top.y > y1)\n {\n if (top.y > y2)\n {\n return;\n }\n y1 = top.y;\n }\n\n if (top.y + top.height <= y2)\n {\n if (top.y + top.height <= y1)\n {\n return;\n } \n y2 = top.y + top.height - 1;\n }\n \n int bpp = mTarget->format->BytesPerPixel;\n \n SDL_LockSurface(mTarget);\n \n Uint8 *p = (Uint8 *)mTarget->pixels + y1 * mTarget->pitch + x * bpp;\n \n Uint32 pixel = SDL_MapRGB(mTarget->format, mColor.r, mColor.g, mColor.b);\n \n switch(bpp) {\n case 1:\n {\n for (;y1 <= y2; ++y1)\n { \n *p = pixel;\n p += mTarget->pitch;\n }\n } break;\n \n case 2:\n {\n for (;y1 <= y2; ++y1)\n {\n *(Uint16*)p = pixel;\n p += mTarget->pitch;\n }\n } break;\n \n case 3: \n {\n if(SDL_BYTEORDER == SDL_BIG_ENDIAN) {\n for (;y1 <= y2; ++y1)\n {\n p[0] = (pixel >> 16) & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = pixel & 0xff;\n p += mTarget->pitch;\n }\n }\n else\n {\n for (;y1 <= y2; ++y1)\n {\n p[0] = pixel & 0xff;\n p[1] = (pixel >> 8) & 0xff;\n p[2] = (pixel >> 16) & 0xff;\n p += mTarget->pitch;\n }\n } \n } break;\n \n case 4:\n {\n for (;y1 <= y2; ++y1)\n {\n *(Uint32*)p = pixel;\n p += mTarget->pitch;\n }\n } break;\n } \/\/ end switch\n \n SDL_UnlockSurface(mTarget);\n\n } \/\/ end drawVLine\n\n void SDLGraphics::drawRectangle(const Rectangle& rectangle)\n {\n int x1 = rectangle.x;\n int x2 = rectangle.x + rectangle.width - 1;\n int y1 = rectangle.y;\n int y2 = rectangle.y + rectangle.height - 1;\n\n drawHLine(x1, y1, x2);\n drawHLine(x1, y2, x2);\n\n drawVLine(x1, y1, y2);\n drawVLine(x2, y1, y2);\n \n } \/\/ end drawRectangle\n\n void SDLGraphics::drawLine(int x1, int y1, int x2, int y2)\n {\n int i;\n \n if (x1 == x2)\n {\n drawVLine(x1, y1, y2);\n return;\n }\n if (y1 == y2)\n {\n drawHLine(x1, y1, x2);\n return;\n }\n \n bool yLonger = false;\n int incrementVal;\n int endVal;\n \n int shortLen = y2 - y1;\n int longLen = x2 - x1;\n\n if (std::abs(shortLen) > std::abs(longLen))\n {\n int swap = shortLen;\n shortLen = longLen;\n longLen = swap;\n yLonger = true;\n }\n\t\n endVal = longLen;\n\n if (longLen< 0)\n {\n incrementVal = -1;\n longLen = - longLen;\n }\n else\n {\n incrementVal = 1;\n }\n \n double decInc;\n\n if (longLen == 0)\n {\n decInc = (double)shortLen;\n }\n else\n {\n decInc = (double)shortLen \/ (double)longLen;\n }\n \n double j = 0.0;\n\n if (yLonger)\n {\n for (i = 0; i != endVal; i += incrementVal)\n {\n drawPoint(x1 + (int)j, y1 + i);\n j += decInc;\n }\n drawPoint(x1 + (int)j, y1 + i);\n }\n else\n {\n for (i = 0; i != endVal; i += incrementVal)\n {\n drawPoint(x1 + i, y1 + (int)j);\n j += decInc;\n }\n drawPoint(x1 + i, y1 + (int)j);\n } \n } \/\/ end drawLine\n \n} \/\/ end gcn\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/autofill\/content\/browser\/wallet\/wallet_service_url.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"components\/autofill\/core\/common\/autofill_switches.h\"\n#include \"google_apis\/gaia\/gaia_urls.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/url_util.h\"\n\nnamespace autofill {\nnamespace {\n\nconst char kProdWalletServiceUrl[] = \"https:\/\/wallet.google.com\/\";\n\n\/\/ TODO(ahutter): Remove this once production is ready.\nconst char kSandboxWalletServiceUrl[] =\n \"https:\/\/payments-form-dogfood.sandbox.google.com\/\";\n\n\/\/ TODO(ahutter): Remove this once production is ready.\nconst char kSandboxWalletSecureServiceUrl[] =\n \"https:\/\/wallet-web.sandbox.google.com\/\";\n\nbool IsWalletProductionEnabled() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n return command_line.HasSwitch(switches::kWalletServiceUseProd) ||\n base::FieldTrialList::FindFullName(\"WalletProductionService\") == \"Yes\";\n}\n\nGURL GetWalletHostUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string wallet_service_hostname =\n command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);\n if (!wallet_service_hostname.empty())\n return GURL(wallet_service_hostname);\n if (IsWalletProductionEnabled())\n return GURL(kProdWalletServiceUrl);\n return GURL(kSandboxWalletServiceUrl);\n}\n\nGURL GetBaseWalletUrl() {\n return GetWalletHostUrl().Resolve(\"online\/v2\/\");\n}\n\nGURL GetBaseAutocheckoutUrl() {\n return GetBaseWalletUrl().Resolve(\"wallet\/autocheckout\/v1\/\");\n}\n\nGURL GetBaseSecureUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string wallet_secure_url =\n command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);\n if (!wallet_secure_url.empty())\n return GURL(wallet_secure_url);\n if (IsWalletProductionEnabled())\n return GURL(kProdWalletServiceUrl);\n return GURL(kSandboxWalletSecureServiceUrl);\n}\n\n} \/\/ namespace\n\nnamespace wallet {\n\nGURL GetGetWalletItemsUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"getWalletItemsJwtless\");\n}\n\nGURL GetGetFullWalletUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"getFullWalletJwtless\");\n}\n\nGURL GetManageInstrumentsUrl() {\n return GetBaseSecureUrl().Resolve(\"manage\/w\/0\/#paymentMethods:\");\n}\n\nGURL GetManageAddressesUrl() {\n return GetBaseSecureUrl().Resolve(\"manage\/w\/0\/#settings:addresses\");\n}\n\nGURL GetAcceptLegalDocumentsUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"acceptLegalDocument\");\n}\n\nGURL GetAuthenticateInstrumentUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"authenticateInstrument\");\n}\n\nGURL GetSendStatusUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"reportStatus\");\n}\n\nGURL GetSaveToWalletUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"saveToWallet\");\n}\n\nGURL GetPassiveAuthUrl() {\n return GetBaseWalletUrl().Resolve(\"passiveauth?isChromePayments=true\");\n}\n\nGURL GetEncryptionUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n \/\/ TODO(ahutter): Stop checking these switches once we switch over to prod.\n if (IsWalletProductionEnabled() ||\n command_line.HasSwitch(switches::kWalletServiceUrl)) {\n return GetWalletHostUrl().Resolve(\n \"online-secure\/temporarydata\/cvv?s7e=cvv\");\n } else {\n return GetBaseSecureUrl().Resolve(\n \"online-secure\/temporarydata\/cvv?s7e=cvv\");\n }\n}\n\nGURL GetEscrowUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n \/\/ TODO(ahutter): Stop checking these switches once we switch over to prod.\n if (IsWalletProductionEnabled() ||\n command_line.HasSwitch(switches::kWalletServiceUrl)) {\n return GetBaseSecureUrl().Resolve(\"dehEfe?s7e=cardNumber%3Bcvv\");\n } else {\n return GetBaseSecureUrl().Resolve(\"checkout\/dehEfe?s7e=cardNumber%3Bcvv\");\n }\n}\n\nGURL GetSignInUrl() {\n GURL url(GaiaUrls::GetInstance()->service_login_url());\n url = net::AppendQueryParameter(url, \"service\", \"toolbar\");\n url = net::AppendQueryParameter(url, \"nui\", \"1\");\n url = net::AppendQueryParameter(url,\n \"continue\",\n GetSignInContinueUrl().spec());\n return url;\n}\n\n\/\/ The continue url portion of the sign-in URL.\nGURL GetSignInContinueUrl() {\n return GetPassiveAuthUrl();\n}\n\nbool IsSignInContinueUrl(const GURL& url) {\n GURL final_url = wallet::GetSignInContinueUrl();\n return url.SchemeIsSecure() &&\n url.host() == final_url.host() &&\n url.path() == final_url.path();\n}\n\nbool IsUsingProd() {\n return GetWalletHostUrl() == GURL(kProdWalletServiceUrl);\n}\n\n} \/\/ namespace wallet\n} \/\/ namespace autofill\nTalk to production wallet server when Autocheckout experiment is enabled\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/autofill\/content\/browser\/wallet\/wallet_service_url.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"components\/autofill\/core\/common\/autofill_switches.h\"\n#include \"google_apis\/gaia\/gaia_urls.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/url_util.h\"\n\nnamespace autofill {\nnamespace {\n\nconst char kProdWalletServiceUrl[] = \"https:\/\/wallet.google.com\/\";\n\n\/\/ TODO(ahutter): Remove this once production is ready.\nconst char kSandboxWalletServiceUrl[] =\n \"https:\/\/payments-form-dogfood.sandbox.google.com\/\";\n\n\/\/ TODO(ahutter): Remove this once production is ready.\nconst char kSandboxWalletSecureServiceUrl[] =\n \"https:\/\/wallet-web.sandbox.google.com\/\";\n\nbool IsWalletProductionEnabled() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n return command_line.HasSwitch(switches::kWalletServiceUseProd) ||\n base::FieldTrialList::FindFullName(\"WalletProductionService\") == \"Yes\" ||\n base::FieldTrialList::FindFullName(\"Autocheckout\") == \"Yes\";\n}\n\nGURL GetWalletHostUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string wallet_service_hostname =\n command_line.GetSwitchValueASCII(switches::kWalletServiceUrl);\n if (!wallet_service_hostname.empty())\n return GURL(wallet_service_hostname);\n if (IsWalletProductionEnabled())\n return GURL(kProdWalletServiceUrl);\n return GURL(kSandboxWalletServiceUrl);\n}\n\nGURL GetBaseWalletUrl() {\n return GetWalletHostUrl().Resolve(\"online\/v2\/\");\n}\n\nGURL GetBaseAutocheckoutUrl() {\n return GetBaseWalletUrl().Resolve(\"wallet\/autocheckout\/v1\/\");\n}\n\nGURL GetBaseSecureUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n std::string wallet_secure_url =\n command_line.GetSwitchValueASCII(switches::kWalletSecureServiceUrl);\n if (!wallet_secure_url.empty())\n return GURL(wallet_secure_url);\n if (IsWalletProductionEnabled())\n return GURL(kProdWalletServiceUrl);\n return GURL(kSandboxWalletSecureServiceUrl);\n}\n\n} \/\/ namespace\n\nnamespace wallet {\n\nGURL GetGetWalletItemsUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"getWalletItemsJwtless\");\n}\n\nGURL GetGetFullWalletUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"getFullWalletJwtless\");\n}\n\nGURL GetManageInstrumentsUrl() {\n return GetBaseSecureUrl().Resolve(\"manage\/w\/0\/#paymentMethods:\");\n}\n\nGURL GetManageAddressesUrl() {\n return GetBaseSecureUrl().Resolve(\"manage\/w\/0\/#settings:addresses\");\n}\n\nGURL GetAcceptLegalDocumentsUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"acceptLegalDocument\");\n}\n\nGURL GetAuthenticateInstrumentUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"authenticateInstrument\");\n}\n\nGURL GetSendStatusUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"reportStatus\");\n}\n\nGURL GetSaveToWalletUrl() {\n return GetBaseAutocheckoutUrl().Resolve(\"saveToWallet\");\n}\n\nGURL GetPassiveAuthUrl() {\n return GetBaseWalletUrl().Resolve(\"passiveauth?isChromePayments=true\");\n}\n\nGURL GetEncryptionUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n \/\/ TODO(ahutter): Stop checking these switches once we switch over to prod.\n if (IsWalletProductionEnabled() ||\n command_line.HasSwitch(switches::kWalletServiceUrl)) {\n return GetWalletHostUrl().Resolve(\n \"online-secure\/temporarydata\/cvv?s7e=cvv\");\n } else {\n return GetBaseSecureUrl().Resolve(\n \"online-secure\/temporarydata\/cvv?s7e=cvv\");\n }\n}\n\nGURL GetEscrowUrl() {\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n \/\/ TODO(ahutter): Stop checking these switches once we switch over to prod.\n if (IsWalletProductionEnabled() ||\n command_line.HasSwitch(switches::kWalletServiceUrl)) {\n return GetBaseSecureUrl().Resolve(\"dehEfe?s7e=cardNumber%3Bcvv\");\n } else {\n return GetBaseSecureUrl().Resolve(\"checkout\/dehEfe?s7e=cardNumber%3Bcvv\");\n }\n}\n\nGURL GetSignInUrl() {\n GURL url(GaiaUrls::GetInstance()->service_login_url());\n url = net::AppendQueryParameter(url, \"service\", \"toolbar\");\n url = net::AppendQueryParameter(url, \"nui\", \"1\");\n url = net::AppendQueryParameter(url,\n \"continue\",\n GetSignInContinueUrl().spec());\n return url;\n}\n\n\/\/ The continue url portion of the sign-in URL.\nGURL GetSignInContinueUrl() {\n return GetPassiveAuthUrl();\n}\n\nbool IsSignInContinueUrl(const GURL& url) {\n GURL final_url = wallet::GetSignInContinueUrl();\n return url.SchemeIsSecure() &&\n url.host() == final_url.host() &&\n url.path() == final_url.path();\n}\n\nbool IsUsingProd() {\n return GetWalletHostUrl() == GURL(kProdWalletServiceUrl);\n}\n\n} \/\/ namespace wallet\n} \/\/ namespace autofill\n<|endoftext|>"} {"text":"#include \"nova_renderer\/window.hpp\"\n\n#include \n#if NOVA_WINDOWS\n#define GLFW_EXPOSE_NATIVE_WIN32\n#elif NOVA_LINUX\ntypedef int Bool; \/\/ Because X11 is stupid\n#define GLFW_EXPOSE_NATIVE_X11\n#endif\n\/\/ We have to include this here so it exists before we #undef Bool, but ReSharper doesn't know the horrors of X11\n\/\/ ReSharper disable once CppUnusedIncludeDirective\n#include \n\n#include \"nova_renderer\/nova_renderer.hpp\"\n#include \"nova_renderer\/util\/platform.hpp\"\n\n#include \"..\/util\/logger.hpp\"\n\nvoid glfw_error_callback(const int error, const char* desc) { NOVA_LOG(ERROR) << \"GLFW error(\" << error << \") \" << desc; }\n\nvoid glfw_key_callback(GLFWwindow* window, const int key, int \/* scancode *\/, const int action, int \/* mods *\/) {\n if(action == GLFW_PRESS) {\n void* user_data = glfwGetWindowUserPointer(window);\n auto* my_window = static_cast(user_data);\n my_window->process_key(key);\n }\n}\n\nnamespace nova::renderer {\n NovaWindow::NovaWindow(const NovaSettings& options) {\n if(!glfwInit()) {\n NOVA_LOG(FATAL) << \"Failed to init GLFW\";\n return;\n }\n\n glfwSetErrorCallback(glfw_error_callback);\n\n if(options.api == GraphicsApi::NvGl4) {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n if(options.debug.enabled) {\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);\n }\n }\n\n window = glfwCreateWindow(static_cast(options.window.width),\n static_cast(options.window.height),\n options.window.title,\n nullptr,\n nullptr);\n if(!window) {\n NOVA_LOG(FATAL) << \"Failed to create window\";\n return;\n }\n\n if(options.api == GraphicsApi::NvGl4) {\n glfwMakeContextCurrent(window);\n }\n\n glfwSetWindowUserPointer(window, this);\n glfwSetKeyCallback(window, glfw_key_callback);\n }\n\n NovaWindow::~NovaWindow() {\n glfwDestroyWindow(window);\n glfwTerminate();\n }\n\n void NovaWindow::register_key_callback(std::function&& key_callback) { key_callbacks.push_back(key_callback); }\n\n void NovaWindow::process_key(const int key) {\n for(const auto& callback : key_callbacks) {\n callback(key);\n }\n }\n\n \/\/ This _can_ be static, but I don't want it to be\n \/\/ ReSharper disable once CppMemberFunctionMayBeStatic\n void NovaWindow::poll_input() const { glfwPollEvents(); }\n\n bool NovaWindow::should_close() const { return glfwWindowShouldClose(window); }\n\n glm::uvec2 NovaWindow::get_window_size() const {\n int width;\n int height;\n glfwGetFramebufferSize(window, &width, &height);\n\n return {width, height};\n }\n\n#if NOVA_WINDOWS\n HWND NovaWindow::get_window_handle() const { return glfwGetWin32Window(window); }\n\n#elif NOVA_LINUX\n Window NovaWindow::get_window_handle() const { return glfwGetX11Window(window); };\n\n Display* NovaWindow::get_display() const { return glfwGetX11Display(window); };\n#endif\n\n#if NOVA_OPENGL_RHI\n void NovaWindow::swap_backbuffer() const { glfwSwapBuffers(window); }\n\n void* NovaWindow::get_gl_proc_address(const char* proc_name) { return reinterpret_cast(glfwGetProcAddress(proc_name)); }\n#endif\n} \/\/ namespace nova::renderer\n[window] Whoops to omany bindings#include \"nova_renderer\/window.hpp\"\n\n#include \n#if NOVA_WINDOWS\n#define GLFW_EXPOSE_NATIVE_WIN32\n#elif NOVA_LINUX\ntypedef int Bool; \/\/ Because X11 is stupid\n#define GLFW_EXPOSE_NATIVE_X11\n#endif\n\/\/ We have to include this here so it exists before we #undef Bool, but ReSharper doesn't know the horrors of X11\n\/\/ ReSharper disable once CppUnusedIncludeDirective\n#include \n\n#include \"nova_renderer\/nova_renderer.hpp\"\n#include \"nova_renderer\/util\/platform.hpp\"\n\n#include \"..\/util\/logger.hpp\"\n\nvoid glfw_error_callback(const int error, const char* desc) { NOVA_LOG(ERROR) << \"GLFW error(\" << error << \") \" << desc; }\n\nvoid glfw_key_callback(GLFWwindow* window, const int key, int \/* scancode *\/, const int action, int \/* mods *\/) {\n if(action == GLFW_PRESS) {\n void* user_data = glfwGetWindowUserPointer(window);\n auto* my_window = static_cast(user_data);\n my_window->process_key(key);\n }\n}\n\nnamespace nova::renderer {\n NovaWindow::NovaWindow(const NovaSettings& options) {\n if(!glfwInit()) {\n NOVA_LOG(FATAL) << \"Failed to init GLFW\";\n return;\n }\n\n glfwSetErrorCallback(glfw_error_callback);\n\n if(options.api == GraphicsApi::NvGl4) {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n if(options.debug.enabled) {\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);\n }\n }\n\n window = glfwCreateWindow(static_cast(options.window.width),\n static_cast(options.window.height),\n options.window.title,\n nullptr,\n nullptr);\n if(!window) {\n NOVA_LOG(FATAL) << \"Failed to create window\";\n return;\n }\n\n if(options.api == GraphicsApi::NvGl4) {\n glfwMakeContextCurrent(window);\n }\n\n glfwSetWindowUserPointer(window, this);\n glfwSetKeyCallback(window, glfw_key_callback);\n }\n\n NovaWindow::~NovaWindow() {\n glfwDestroyWindow(window);\n glfwTerminate();\n }\n\n void NovaWindow::register_key_callback(std::function&& key_callback) { key_callbacks.push_back(key_callback); }\n\n void NovaWindow::process_key(const int key) {\n for(const auto& callback : key_callbacks) {\n callback(key);\n }\n }\n\n \/\/ This _can_ be static, but I don't want it to be\n \/\/ ReSharper disable once CppMemberFunctionMayBeStatic\n void NovaWindow::poll_input() const { glfwPollEvents(); }\n\n bool NovaWindow::should_close() const { return glfwWindowShouldClose(window); }\n\n glm::uvec2 NovaWindow::get_window_size() const {\n int width;\n int height;\n glfwGetFramebufferSize(window, &width, &height);\n\n return {width, height};\n }\n\n#if NOVA_WINDOWS\n HWND NovaWindow::get_window_handle() const { return glfwGetWin32Window(window); }\n\n#elif NOVA_LINUX\n Window NovaWindow::get_window_handle() const { return glfwGetX11Window(window); };\n\n Display* NovaWindow::get_display() const { return glfwGetX11Display(); };\n#endif\n\n#if NOVA_OPENGL_RHI\n void NovaWindow::swap_backbuffer() const { glfwSwapBuffers(window); }\n\n void* NovaWindow::get_gl_proc_address(const char* proc_name) { return reinterpret_cast(glfwGetProcAddress(proc_name)); }\n#endif\n} \/\/ namespace nova::renderer\n<|endoftext|>"} {"text":"\/\/ License: MIT\n\n#include \"Unit.h\"\n#include \"Players\/Player.h\"\n\nvoid Unit::setCombatFlag(bool enabled)\n{\n if (enabled)\n {\n SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);\n }\n else\n {\n RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);\n }\n}\n\nbool Unit::isInCombat() const\n{\n return m_combatStatus.isInCombat();\n}\n\nbool Unit::isAttacking(Unit* target) const\n{\n ASSERT(target);\n\n return m_combatStatus.isAttacking(target);\n}\n\nvoid Unit::enterCombat()\n{\n setCombatFlag(true);\n\n if (!hasStateFlag(UF_ATTACKING))\n {\n addStateFlag(UF_ATTACKING);\n }\n}\n\nvoid Unit::leaveCombat()\n{\n setCombatFlag(false);\n\n if (hasStateFlag(UF_ATTACKING))\n {\n clearStateFlag(UF_ATTACKING);\n }\n\n if (IsPlayer())\n {\n static_cast(this)->UpdatePotionCooldown();\n }\n}\n\nvoid Unit::onDamageDealt(Unit* target)\n{\n ASSERT(target);\n\n m_combatStatus.onDamageDealt(target);\n}\n\nvoid Unit::addHealTarget(Unit* target)\n{\n ASSERT(target != nullptr);\n\n if (target->IsPlayer())\n {\n m_combatStatus.addHealTarget(reinterpret_cast(target));\n }\n}\n\nvoid Unit::removeHealTarget(Unit* target)\n{\n ASSERT(target != nullptr);\n\n if (target->IsPlayer())\n {\n m_combatStatus.removeHealTarget(reinterpret_cast(target));\n }\n}\n\nvoid Unit::addHealer(Unit* healer)\n{\n ASSERT(healer != nullptr);\n\n if (healer->IsPlayer())\n {\n m_combatStatus.addHealer(reinterpret_cast(healer));\n }\n}\n\nvoid Unit::removeHealer(Unit* healer)\n{\n ASSERT(healer != nullptr);\n\n if (healer->IsPlayer())\n {\n m_combatStatus.removeHealer(reinterpret_cast(healer));\n }\n}\n\nvoid Unit::addAttacker(Unit* attacker)\n{\n ASSERT(attacker);\n\n m_combatStatus.addAttacker(attacker);\n}\n\nbool Unit::hasAttacker(uint64_t guid) const\n{\n return m_combatStatus.hasAttacker(guid);\n}\n\nvoid Unit::removeAttacker(Unit* attacker)\n{\n ASSERT(attacker != nullptr);\n \/\/ASSERT(IsInWorld()); \/\/Zyres: unit is not in world. remove attack target only for units in world\n if (this->IsInWorld())\n {\n m_combatStatus.removeAttacker(attacker);\n }\n}\n\nvoid Unit::removeAttacker(uint64_t guid)\n{\n m_combatStatus.removeAttacker(guid);\n}\n\nvoid Unit::removeAttackTarget(Unit* attackTarget)\n{\n ASSERT(attackTarget != nullptr);\n \/\/ASSERT(IsInWorld()); \/\/Zyres: unit is not in world. remove attack target only for units in world\n if (this->IsInWorld())\n {\n m_combatStatus.removeAttackTarget(attackTarget);\n }\n}\n\nvoid Unit::updateCombatStatus()\n{\n m_combatStatus.update();\n}\n\nvoid Unit::clearAllCombatTargets()\n{\n m_combatStatus.clearAllCombatTargets();\n}\n\nuint64_t Unit::getPrimaryAttackTarget() const\n{\n return m_combatStatus.getPrimaryAttackTarget();\n}\n\nvoid Unit::PlaySpellVisual(uint64_t guid, uint32_t spell_id)\n{\n WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);\n data << uint64_t(guid);\n data << uint32_t(spell_id);\n\n if (IsPlayer())\n static_cast(this)->SendMessageToSet(&data, true);\n else\n SendMessageToSet(&data, false);\n}\nInclude headerfile Unit.cpp\/\/ License: MIT\n\n#include \"Unit.h\"\n#include \"Server\/Packets\/Opcodes.h\"\n#include \"Players\/Player.h\"\n\nvoid Unit::setCombatFlag(bool enabled)\n{\n if (enabled)\n {\n SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);\n }\n else\n {\n RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_COMBAT);\n }\n}\n\nbool Unit::isInCombat() const\n{\n return m_combatStatus.isInCombat();\n}\n\nbool Unit::isAttacking(Unit* target) const\n{\n ASSERT(target);\n\n return m_combatStatus.isAttacking(target);\n}\n\nvoid Unit::enterCombat()\n{\n setCombatFlag(true);\n\n if (!hasStateFlag(UF_ATTACKING))\n {\n addStateFlag(UF_ATTACKING);\n }\n}\n\nvoid Unit::leaveCombat()\n{\n setCombatFlag(false);\n\n if (hasStateFlag(UF_ATTACKING))\n {\n clearStateFlag(UF_ATTACKING);\n }\n\n if (IsPlayer())\n {\n static_cast(this)->UpdatePotionCooldown();\n }\n}\n\nvoid Unit::onDamageDealt(Unit* target)\n{\n ASSERT(target);\n\n m_combatStatus.onDamageDealt(target);\n}\n\nvoid Unit::addHealTarget(Unit* target)\n{\n ASSERT(target != nullptr);\n\n if (target->IsPlayer())\n {\n m_combatStatus.addHealTarget(reinterpret_cast(target));\n }\n}\n\nvoid Unit::removeHealTarget(Unit* target)\n{\n ASSERT(target != nullptr);\n\n if (target->IsPlayer())\n {\n m_combatStatus.removeHealTarget(reinterpret_cast(target));\n }\n}\n\nvoid Unit::addHealer(Unit* healer)\n{\n ASSERT(healer != nullptr);\n\n if (healer->IsPlayer())\n {\n m_combatStatus.addHealer(reinterpret_cast(healer));\n }\n}\n\nvoid Unit::removeHealer(Unit* healer)\n{\n ASSERT(healer != nullptr);\n\n if (healer->IsPlayer())\n {\n m_combatStatus.removeHealer(reinterpret_cast(healer));\n }\n}\n\nvoid Unit::addAttacker(Unit* attacker)\n{\n ASSERT(attacker);\n\n m_combatStatus.addAttacker(attacker);\n}\n\nbool Unit::hasAttacker(uint64_t guid) const\n{\n return m_combatStatus.hasAttacker(guid);\n}\n\nvoid Unit::removeAttacker(Unit* attacker)\n{\n ASSERT(attacker != nullptr);\n \/\/ASSERT(IsInWorld()); \/\/Zyres: unit is not in world. remove attack target only for units in world\n if (this->IsInWorld())\n {\n m_combatStatus.removeAttacker(attacker);\n }\n}\n\nvoid Unit::removeAttacker(uint64_t guid)\n{\n m_combatStatus.removeAttacker(guid);\n}\n\nvoid Unit::removeAttackTarget(Unit* attackTarget)\n{\n ASSERT(attackTarget != nullptr);\n \/\/ASSERT(IsInWorld()); \/\/Zyres: unit is not in world. remove attack target only for units in world\n if (this->IsInWorld())\n {\n m_combatStatus.removeAttackTarget(attackTarget);\n }\n}\n\nvoid Unit::updateCombatStatus()\n{\n m_combatStatus.update();\n}\n\nvoid Unit::clearAllCombatTargets()\n{\n m_combatStatus.clearAllCombatTargets();\n}\n\nuint64_t Unit::getPrimaryAttackTarget() const\n{\n return m_combatStatus.getPrimaryAttackTarget();\n}\n\nvoid Unit::PlaySpellVisual(uint64_t guid, uint32_t spell_id)\n{\n WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 12);\n data << uint64_t(guid);\n data << uint32_t(spell_id);\n\n if (IsPlayer())\n static_cast(this)->SendMessageToSet(&data, true);\n else\n SendMessageToSet(&data, false);\n}\n<|endoftext|>"} {"text":"\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file KitwareConverter.cpp\r\n \\author Jens Krueger\r\n SCI Institute\r\n University of Utah\r\n \\date December 2008\r\n*\/\r\n\r\n#include \r\n#include \"KitwareConverter.h\"\r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\n\r\n\r\nKitwareConverter::KitwareConverter()\r\n{\r\n m_vConverterDesc = \"Kitware MHD Data\";\r\n m_vSupportedExt.push_back(\"MHD\");\r\n}\r\n\r\nbool KitwareConverter::ConvertToRAW(const std::string& strSourceFilename,\r\n const std::string&, bool,\r\n UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,\r\n bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,\r\n FLOATVECTOR3& vVolumeAspect, std::string& strTitle,\r\n UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,\r\n bool& bDeleteIntermediateFile) {\r\n\r\n MESSAGE(\"Attempting to convert Kitware MHD dataset %s\", strSourceFilename.c_str());\r\n\r\n eType = UVFTables::ES_UNDEFINED;\r\n strTitle = \"Kitware MHD data\";\r\n\r\n KeyValueFileParser parser(strSourceFilename,false,\"=\");\r\n\r\n if (parser.FileReadable()) {\r\n KeyValPair* dims = parser.GetData(\"NDIMS\");\r\n KeyValPair* dimsize = parser.GetData(\"DIMSIZE\");\r\n KeyValPair* ElementSpacing = parser.GetData(\"ELEMENTSPACING\");\r\n KeyValPair* BigEndianFlag = parser.GetData(\"ELEMENTBYTEORDERMSB\");\r\n if (BigEndianFlag == NULL) BigEndianFlag = parser.GetData(\"BINARYDATABYTEORDERMSB\"); \r\n KeyValPair* ElementType = parser.GetData(\"ELEMENTTYPE\");\r\n KeyValPair* CompressedData = parser.GetData(\"COMPRESSEDDATA\");\r\n KeyValPair* BinaryData = parser.GetData(\"BINARYDATA\"); \r\n KeyValPair* Position = parser.GetData(\"POSITION\");\r\n KeyValPair* ElementNumberOfChannels = parser.GetData(\"ELEMENTNUMBEROFCHANNELS\");\r\n KeyValPair* ElementDataFile = parser.GetData(\"ELEMENTDATAFILE\");\r\n KeyValPair* HeaderSize = parser.GetData(\"HEADERSIZE\");\r\n KeyValPair* ObjectType = parser.GetData(\"OBJECTTYPE\");\r\n\r\n if (ObjectType && ObjectType->strValueUpper != \"IMAGE\") {\r\n T_ERROR(\"Only image type MHD file are currently supported.\");\r\n return false;\r\n } \r\n\r\n if (ElementDataFile == NULL) {\r\n T_ERROR(\"Unable to find 'ElementDataFile' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n } \r\n \r\n if (dimsize == NULL) {\r\n T_ERROR(\"Unable to find 'DimSize' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n } \r\n \r\n if (ElementType == NULL) {\r\n T_ERROR(\"Unable to find 'ElementType' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n }\r\n\r\n if (BigEndianFlag == NULL) {\r\n MESSAGE(\"Unable to find 'ElementByteOrderMSB' or 'BinaryDataByteOrderMSB' tags in file %s assuming little endian data.\", strSourceFilename.c_str());\r\n bConvertEndianess = EndianConvert::IsBigEndian();\r\n } else {\r\n if(BigEndianFlag->strValueUpper == \"FALSE\") {\r\n bConvertEndianess = EndianConvert::IsBigEndian();\r\n } else {\r\n bConvertEndianess = EndianConvert::IsLittleEndian();\r\n }\r\n }\r\n\r\n if(ElementType->strValueUpper == \"MET_CHAR\") {\r\n bSigned = true;\r\n iComponentSize = 8;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_UCHAR\") {\r\n bSigned = false;\r\n iComponentSize = 8;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_SHORT\") {\r\n bSigned = true;\r\n iComponentSize = 16;\r\n bIsFloat = false;\r\n }else if (ElementType->strValueUpper == \"MET_USHORT\") {\r\n bSigned = false;\r\n iComponentSize = 16;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_INT\") {\r\n bSigned = true;\r\n iComponentSize = 32;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_UINT\") {\r\n bSigned = false;\r\n iComponentSize = 32;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_FLOAT\") {\r\n bSigned = true;\r\n iComponentSize = 32;\r\n bIsFloat = true;\r\n }\r\n\r\n if (ElementNumberOfChannels == NULL) {\r\n MESSAGE(\"Unable to find 'ElementNumberOfChannels ' tag in file %s assuming scalar data.\", strSourceFilename.c_str());\r\n iComponentCount = EndianConvert::IsBigEndian();\r\n } else {\r\n iComponentCount = ElementNumberOfChannels->iValue;\r\n }\r\n\r\n strIntermediateFile = ElementDataFile->strValue;\r\n\r\n if (strIntermediateFile == \"LIST\") {\r\n T_ERROR(\"LISTS are currently not supported in MHD files.\");\r\n return false;\r\n }\r\n\r\n UINT32 iDims = static_cast(dimsize->vuiValue.size());\r\n\r\n if (dims == NULL) {\r\n WARNING(\"Unable to find 'NDims' tag in file %s relying on 'DimSize' tag.\", strSourceFilename.c_str());\r\n } else {\r\n if (iDims != dims->uiValue) {\r\n T_ERROR(\"Tags 'NDims' and 'DimSize' are incosistent in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n }\r\n }\r\n\r\n if (iDims > 3) {\r\n T_ERROR(\"Currently only up to 3D data supported.\");\r\n return false;\r\n }\r\n\r\n vVolumeSize = UINT64VECTOR3(dimsize->vuiValue, 1);\r\n vVolumeAspect = FLOATVECTOR3(ElementSpacing->vfValue,1.0f);\r\n\r\n if (Position != NULL) {\r\n for (size_t i = 0;ivfValue.size();i++) {\r\n if (ElementSpacing->vfValue[i] != 0.0f) {\r\n WARNING(\"Ignoring non zero position.\");\r\n break;\r\n }\r\n }\r\n }\r\n\r\n \r\n \/\/ TODO: find a non binary MHD payload file and figure out its format\r\n if (BinaryData != NULL) {\r\n if(BinaryData->strValueUpper == \"FALSE\") {\r\n T_ERROR(\"Currently only binary MHD data supported.\");\r\n return false;\r\n }\r\n }\r\n\r\n \/\/ TODO: find a compressed MHD payload file and figure out its format\r\n if (CompressedData != NULL) {\r\n if(CompressedData->strValueUpper == \"TRUE\") {\r\n T_ERROR(\"Currently only uncompressed MHD data supported.\");\r\n return false;\r\n }\r\n }\r\n bDeleteIntermediateFile = false;\r\n \r\n strIntermediateFile = SysTools::GetPath(strSourceFilename) + strIntermediateFile;\r\n\r\n if (HeaderSize != NULL) {\r\n if (dimsize->iValue != -1 ) { \/\/ size -1 means compute header size automatically\r\n iHeaderSkip = dimsize->uiValue;\r\n } else {\r\n LargeRAWFile f(strIntermediateFile);\r\n if (f.Open(false)) {\r\n UINT64 iFileSize = f.GetCurrentSize();\r\n f.Close();\r\n iHeaderSkip = iFileSize - (iComponentSize\/8)*vVolumeSize.volume()*iComponentCount;\r\n } else {\r\n T_ERROR(\"Unable to open paload file %s.\", strIntermediateFile.c_str());\r\n return false;\r\n }\r\n }\r\n } else {\r\n iHeaderSkip = 0;\r\n }\r\n\r\n } else return false;\r\n\r\n return true;\r\n}\r\n\r\nbool KitwareConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,\r\n UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,\r\n UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool bNoUserInteraction,\r\n const bool bQuantizeTo8Bit) {\r\n\r\n \/\/ compute fromat string\r\n string strFormat;\r\n if (!bQuantizeTo8Bit) {\r\n if (bFloatingPoint && bSigned && iComponentSize == 32)\r\n strFormat = \"MET_FLOAT\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 32)\r\n strFormat = \"MET_INT\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 32)\r\n strFormat = \"MET_UINT\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 8)\r\n strFormat = \"MET_CHAR\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 8)\r\n strFormat = \"MET_UCHAR\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 16)\r\n strFormat = \"MET_SHORT\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 16)\r\n strFormat = \"MET_USHORT\";\r\n else {\r\n T_ERROR(\"This data type is not supported by the MHD writer.\");\r\n return false;\r\n }\r\n } else {\r\n if (bSigned)\r\n strFormat = \"MET_CHAR\";\r\n else\r\n strFormat = \"MET_UCHAR\";\r\n }\r\n\r\n\r\n \/\/ create textfile from metadata\r\n string strTargetRAWFilename = strTargetFilename+\".raw\";\r\n\r\n ofstream fTarget(strTargetFilename.c_str());\r\n if (!fTarget.is_open()) {\r\n T_ERROR(\"Unable to open target file %s.\", strTargetFilename.c_str());\r\n return false;\r\n }\r\n\r\n MESSAGE(\"Writing MHD File\");\r\n\r\n fTarget << \"ObjectType = Image\" << endl;\r\n fTarget << \"BinaryData = True\" << endl;\r\n if (EndianConvert::IsBigEndian())\r\n fTarget << \"BinaryDataByteOrderMSB = true\" << endl;\r\n else\r\n fTarget << \"BinaryDataByteOrderMSB = false\" << endl;\r\n fTarget << \"HeaderSize = 0\" << endl;\r\n\r\n fTarget << \"NDims = 3\" << endl;\r\n fTarget << \"DimSize = \" << vVolumeSize.x << \" \" << vVolumeSize.y << \" \"<< vVolumeSize.z << endl;\r\n fTarget << \"ElementSpacing = \" << vVolumeAspect.x << \" \" << vVolumeAspect.y << \" \"<< vVolumeAspect.z << endl;\r\n\r\n fTarget << \"ElementNumberOfChannels = \" << iComponentCount << endl;\r\n fTarget << \"ElementType = \" << strFormat << endl;\r\n fTarget << \"ElementDataFile = \" << SysTools::GetFilename(strTargetRAWFilename) << endl;\r\n fTarget.close();\r\n\r\n MESSAGE(\"Writing RAW File\");\r\n\r\n \/\/ copy RAW file using the parent's call\r\n bool bRAWSuccess = RAWConverter::ConvertToNative(strRawFilename, strTargetRAWFilename, iHeaderSkip,\r\n iComponentSize, iComponentCount, bSigned, bFloatingPoint,\r\n vVolumeSize, vVolumeAspect, bNoUserInteraction,bQuantizeTo8Bit);\r\n\r\n if (bRAWSuccess) {\r\n return true;\r\n } else {\r\n T_ERROR(\"Error creating raw target file %s.\", strTargetRAWFilename.c_str());\r\n remove(strTargetFilename.c_str());\r\n return false;\r\n }\r\n}\r\nadded DOUBLE to Kitware converter\/*\r\n For more information, please see: http:\/\/software.sci.utah.edu\r\n\r\n The MIT License\r\n\r\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\r\n University of Utah.\r\n\r\n\r\n Permission is hereby granted, free of charge, to any person obtaining a\r\n copy of this software and associated documentation files (the \"Software\"),\r\n to deal in the Software without restriction, including without limitation\r\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n and\/or sell copies of the Software, and to permit persons to whom the\r\n Software is furnished to do so, subject to the following conditions:\r\n\r\n The above copyright notice and this permission notice shall be included\r\n in all copies or substantial portions of the Software.\r\n\r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/**\r\n \\file KitwareConverter.cpp\r\n \\author Jens Krueger\r\n SCI Institute\r\n University of Utah\r\n \\date December 2008\r\n*\/\r\n\r\n#include \r\n#include \"KitwareConverter.h\"\r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\n\r\n\r\nKitwareConverter::KitwareConverter()\r\n{\r\n m_vConverterDesc = \"Kitware MHD Data\";\r\n m_vSupportedExt.push_back(\"MHD\");\r\n}\r\n\r\nbool KitwareConverter::ConvertToRAW(const std::string& strSourceFilename,\r\n const std::string&, bool,\r\n UINT64& iHeaderSkip, UINT64& iComponentSize, UINT64& iComponentCount,\r\n bool& bConvertEndianess, bool& bSigned, bool& bIsFloat, UINT64VECTOR3& vVolumeSize,\r\n FLOATVECTOR3& vVolumeAspect, std::string& strTitle,\r\n UVFTables::ElementSemanticTable& eType, std::string& strIntermediateFile,\r\n bool& bDeleteIntermediateFile) {\r\n\r\n MESSAGE(\"Attempting to convert Kitware MHD dataset %s\", strSourceFilename.c_str());\r\n\r\n eType = UVFTables::ES_UNDEFINED;\r\n strTitle = \"Kitware MHD data\";\r\n\r\n KeyValueFileParser parser(strSourceFilename,false,\"=\");\r\n\r\n if (parser.FileReadable()) {\r\n KeyValPair* dims = parser.GetData(\"NDIMS\");\r\n KeyValPair* dimsize = parser.GetData(\"DIMSIZE\");\r\n KeyValPair* ElementSpacing = parser.GetData(\"ELEMENTSPACING\");\r\n KeyValPair* BigEndianFlag = parser.GetData(\"ELEMENTBYTEORDERMSB\");\r\n if (BigEndianFlag == NULL) BigEndianFlag = parser.GetData(\"BINARYDATABYTEORDERMSB\"); \r\n KeyValPair* ElementType = parser.GetData(\"ELEMENTTYPE\");\r\n KeyValPair* CompressedData = parser.GetData(\"COMPRESSEDDATA\");\r\n KeyValPair* BinaryData = parser.GetData(\"BINARYDATA\"); \r\n KeyValPair* Position = parser.GetData(\"POSITION\");\r\n KeyValPair* ElementNumberOfChannels = parser.GetData(\"ELEMENTNUMBEROFCHANNELS\");\r\n KeyValPair* ElementDataFile = parser.GetData(\"ELEMENTDATAFILE\");\r\n KeyValPair* HeaderSize = parser.GetData(\"HEADERSIZE\");\r\n KeyValPair* ObjectType = parser.GetData(\"OBJECTTYPE\");\r\n\r\n if (ObjectType && ObjectType->strValueUpper != \"IMAGE\") {\r\n T_ERROR(\"Only image type MHD file are currently supported.\");\r\n return false;\r\n } \r\n\r\n if (ElementDataFile == NULL) {\r\n T_ERROR(\"Unable to find 'ElementDataFile' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n } \r\n \r\n if (dimsize == NULL) {\r\n T_ERROR(\"Unable to find 'DimSize' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n } \r\n \r\n if (ElementType == NULL) {\r\n T_ERROR(\"Unable to find 'ElementType' tag in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n }\r\n\r\n if (BigEndianFlag == NULL) {\r\n MESSAGE(\"Unable to find 'ElementByteOrderMSB' or 'BinaryDataByteOrderMSB' tags in file %s assuming little endian data.\", strSourceFilename.c_str());\r\n bConvertEndianess = EndianConvert::IsBigEndian();\r\n } else {\r\n if(BigEndianFlag->strValueUpper == \"FALSE\") {\r\n bConvertEndianess = EndianConvert::IsBigEndian();\r\n } else {\r\n bConvertEndianess = EndianConvert::IsLittleEndian();\r\n }\r\n }\r\n\r\n if(ElementType->strValueUpper == \"MET_CHAR\") {\r\n bSigned = true;\r\n iComponentSize = 8;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_UCHAR\") {\r\n bSigned = false;\r\n iComponentSize = 8;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_SHORT\") {\r\n bSigned = true;\r\n iComponentSize = 16;\r\n bIsFloat = false;\r\n }else if (ElementType->strValueUpper == \"MET_USHORT\") {\r\n bSigned = false;\r\n iComponentSize = 16;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_INT\") {\r\n bSigned = true;\r\n iComponentSize = 32;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_UINT\") {\r\n bSigned = false;\r\n iComponentSize = 32;\r\n bIsFloat = false;\r\n } else if (ElementType->strValueUpper == \"MET_FLOAT\") {\r\n bSigned = true;\r\n iComponentSize = 32;\r\n bIsFloat = true;\r\n } else if (ElementType->strValueUpper == \"MET_DOUBLE\") {\r\n bSigned = true;\r\n iComponentSize = 64;\r\n bIsFloat = true;\r\n }\r\n\r\n\r\n if (ElementNumberOfChannels == NULL) {\r\n MESSAGE(\"Unable to find 'ElementNumberOfChannels ' tag in file %s assuming scalar data.\", strSourceFilename.c_str());\r\n iComponentCount = EndianConvert::IsBigEndian();\r\n } else {\r\n iComponentCount = ElementNumberOfChannels->iValue;\r\n }\r\n\r\n strIntermediateFile = ElementDataFile->strValue;\r\n\r\n if (strIntermediateFile == \"LIST\") {\r\n T_ERROR(\"LISTS are currently not supported in MHD files.\");\r\n return false;\r\n }\r\n\r\n UINT32 iDims = static_cast(dimsize->vuiValue.size());\r\n\r\n if (dims == NULL) {\r\n WARNING(\"Unable to find 'NDims' tag in file %s relying on 'DimSize' tag.\", strSourceFilename.c_str());\r\n } else {\r\n if (iDims != dims->uiValue) {\r\n T_ERROR(\"Tags 'NDims' and 'DimSize' are incosistent in file %s.\", strSourceFilename.c_str());\r\n return false;\r\n }\r\n }\r\n\r\n if (iDims > 3) {\r\n T_ERROR(\"Currently only up to 3D data supported.\");\r\n return false;\r\n }\r\n\r\n vVolumeSize = UINT64VECTOR3(dimsize->vuiValue, 1);\r\n vVolumeAspect = FLOATVECTOR3(ElementSpacing->vfValue,1.0f);\r\n\r\n if (Position != NULL) {\r\n for (size_t i = 0;ivfValue.size();i++) {\r\n if (ElementSpacing->vfValue[i] != 0.0f) {\r\n WARNING(\"Ignoring non zero position.\");\r\n break;\r\n }\r\n }\r\n }\r\n\r\n \r\n \/\/ TODO: find a non binary MHD payload file and figure out its format\r\n if (BinaryData != NULL) {\r\n if(BinaryData->strValueUpper == \"FALSE\") {\r\n T_ERROR(\"Currently only binary MHD data supported.\");\r\n return false;\r\n }\r\n }\r\n\r\n \/\/ TODO: find a compressed MHD payload file and figure out its format\r\n if (CompressedData != NULL) {\r\n if(CompressedData->strValueUpper == \"TRUE\") {\r\n T_ERROR(\"Currently only uncompressed MHD data supported.\");\r\n return false;\r\n }\r\n }\r\n bDeleteIntermediateFile = false;\r\n \r\n strIntermediateFile = SysTools::GetPath(strSourceFilename) + strIntermediateFile;\r\n\r\n if (HeaderSize != NULL) {\r\n if (dimsize->iValue != -1 ) { \/\/ size -1 means compute header size automatically\r\n iHeaderSkip = dimsize->uiValue;\r\n } else {\r\n LargeRAWFile f(strIntermediateFile);\r\n if (f.Open(false)) {\r\n UINT64 iFileSize = f.GetCurrentSize();\r\n f.Close();\r\n iHeaderSkip = iFileSize - (iComponentSize\/8)*vVolumeSize.volume()*iComponentCount;\r\n } else {\r\n T_ERROR(\"Unable to open paload file %s.\", strIntermediateFile.c_str());\r\n return false;\r\n }\r\n }\r\n } else {\r\n iHeaderSkip = 0;\r\n }\r\n\r\n } else return false;\r\n\r\n return true;\r\n}\r\n\r\nbool KitwareConverter::ConvertToNative(const std::string& strRawFilename, const std::string& strTargetFilename, UINT64 iHeaderSkip,\r\n UINT64 iComponentSize, UINT64 iComponentCount, bool bSigned, bool bFloatingPoint,\r\n UINT64VECTOR3 vVolumeSize,FLOATVECTOR3 vVolumeAspect, bool bNoUserInteraction,\r\n const bool bQuantizeTo8Bit) {\r\n\r\n \/\/ compute fromat string\r\n string strFormat;\r\n if (!bQuantizeTo8Bit) {\r\n if (bFloatingPoint && bSigned && iComponentSize == 64)\r\n strFormat = \"MET_DOUBLE\";\r\n else\r\n if (bFloatingPoint && bSigned && iComponentSize == 32)\r\n strFormat = \"MET_FLOAT\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 32)\r\n strFormat = \"MET_INT\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 32)\r\n strFormat = \"MET_UINT\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 8)\r\n strFormat = \"MET_CHAR\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 8)\r\n strFormat = \"MET_UCHAR\";\r\n else\r\n if (!bFloatingPoint && bSigned && iComponentSize == 16)\r\n strFormat = \"MET_SHORT\";\r\n else\r\n if (!bFloatingPoint && !bSigned && iComponentSize == 16)\r\n strFormat = \"MET_USHORT\";\r\n else {\r\n T_ERROR(\"This data type is not supported by the MHD writer.\");\r\n return false;\r\n }\r\n } else {\r\n if (bSigned)\r\n strFormat = \"MET_CHAR\";\r\n else\r\n strFormat = \"MET_UCHAR\";\r\n }\r\n\r\n\r\n \/\/ create textfile from metadata\r\n string strTargetRAWFilename = strTargetFilename+\".raw\";\r\n\r\n ofstream fTarget(strTargetFilename.c_str());\r\n if (!fTarget.is_open()) {\r\n T_ERROR(\"Unable to open target file %s.\", strTargetFilename.c_str());\r\n return false;\r\n }\r\n\r\n MESSAGE(\"Writing MHD File\");\r\n\r\n fTarget << \"ObjectType = Image\" << endl;\r\n fTarget << \"BinaryData = True\" << endl;\r\n if (EndianConvert::IsBigEndian())\r\n fTarget << \"BinaryDataByteOrderMSB = true\" << endl;\r\n else\r\n fTarget << \"BinaryDataByteOrderMSB = false\" << endl;\r\n fTarget << \"HeaderSize = 0\" << endl;\r\n\r\n fTarget << \"NDims = 3\" << endl;\r\n fTarget << \"DimSize = \" << vVolumeSize.x << \" \" << vVolumeSize.y << \" \"<< vVolumeSize.z << endl;\r\n fTarget << \"ElementSpacing = \" << vVolumeAspect.x << \" \" << vVolumeAspect.y << \" \"<< vVolumeAspect.z << endl;\r\n\r\n fTarget << \"ElementNumberOfChannels = \" << iComponentCount << endl;\r\n fTarget << \"ElementType = \" << strFormat << endl;\r\n fTarget << \"ElementDataFile = \" << SysTools::GetFilename(strTargetRAWFilename) << endl;\r\n fTarget.close();\r\n\r\n MESSAGE(\"Writing RAW File\");\r\n\r\n \/\/ copy RAW file using the parent's call\r\n bool bRAWSuccess = RAWConverter::ConvertToNative(strRawFilename, strTargetRAWFilename, iHeaderSkip,\r\n iComponentSize, iComponentCount, bSigned, bFloatingPoint,\r\n vVolumeSize, vVolumeAspect, bNoUserInteraction,bQuantizeTo8Bit);\r\n\r\n if (bRAWSuccess) {\r\n return true;\r\n } else {\r\n T_ERROR(\"Error creating raw target file %s.\", strTargetRAWFilename.c_str());\r\n remove(strTargetFilename.c_str());\r\n return false;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \"CDAP.pb.h\"\n\nusing namespace std;\n\n\nint main()\n{\n return 0;\n}\ncdap: added internal CDAPMessage struct#include \n#include \n\n#include \"rinalite\/rinalite-common.h\"\n#include \"CDAP.pb.h\"\n\nusing namespace std;\n\n\n\/* Internal representation of a CDAP message. *\/\nstruct CDAPMessage {\n int abs_syntax;\n gpb::authTypes_t auth_mech;\n struct {\n string auth_name;\n string auth_password;\n string auth_other;\n } auth_value;\n struct rina_name local_appl;\n struct rina_name remote_appl;\n string filter;\n gpb::flagValues_t flags;\n int invoke_id;\n string obj_class;\n long obj_inst;\n string obj_name;\n gpb::opCode_t op_code;\n int result;\n string result_reason;\n int scope;\n long version;\n\n enum obj_value_t {\n NONE,\n I32,\n I64,\n BYTES,\n FLOAT,\n DOUBLE,\n BOOL,\n STRING,\n };\n\n bool is(obj_value_t tt) const { return obj_value.ty == tt; }\n\nprivate:\n \/* Representation of the object value. *\/\n struct {\n obj_value_t ty;\n union {\n int32_t i32; \/* intval and sintval *\/\n int64_t i64; \/* int64val and sint64val *\/\n void *bytes;\n float fp_single;\n double fp_double;\n bool boolean;\n } u;\n string str; \/* strval *\/\n } obj_value;\n};\n\nint main()\n{\n gpb::CDAPMessage gm;\n CDAPMessage m;\n\n (void)gm;\n (void)m;\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"AliVertex.h\"\n \nClassImp(AliVertex) \/\/ Class implementation to enable ROOT I\/O\n \nAliVertex::AliVertex()\n{\n\/\/ Default constructor\n\/\/ All variables initialised to 0\n\/\/ Initial maximum number of tracks is set to the default value\n\/\/ Initial maximum number of sec. vertices is set to the default value\n fNvmax=0;\n fVertices=0;\n Reset();\n SetNtinit();\n SetNvmax();\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex::AliVertex(Int_t n)\n{\n\/\/ Create a vertex to hold initially a maximum of n tracks\n\/\/ All variables initialised to 0\n fNvmax=0;\n fVertices=0;\n Reset();\n if (n > 0)\n {\n SetNtinit(n);\n }\n else\n {\n cout << endl;\n cout << \" *AliVertex* Initial max. number of tracks entered : \" << n << endl;\n cout << \" This is invalid. Default initial maximum will be used.\" << endl;\n cout << endl;\n SetNtinit();\n }\n SetNvmax();\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex::~AliVertex()\n{\n\/\/ Default destructor\n if (fVertices) delete fVertices;\n fVertices=0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::SetNvmax(Int_t n)\n{\n\/\/ Set the initial maximum number of (secondary) vertices\n if (n > 0)\n {\n fNvmax=n;\n }\n else\n {\n fNvmax=1;\n }\n if (fVertices) delete fVertices;\n fVertices=new TObjArray(fNvmax);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Reset()\n{\n\/\/ Reset all variables to 0\n\/\/ The max. number of tracks is set to the initial value again\n\/\/ The max. number of vertices is set to the default value again\n\n AliJet::Reset();\n\n fNvtx=0;\n if (fNvmax>0) SetNvmax(fNvmax);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Add(AliJet& j)\n{\n\/\/ Add the tracks of a jet to the vertex\n AliTrack* tj;\n for (Int_t i=1; i<=j.GetNtracks(); i++)\n {\n tj=j.GetTrack(i);\n AliJet::Add(tj);\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Add(AliVertex& v)\n{\n\/\/ Add a (secondary) vertex to the current vertex.\n\/\/ In case the maximum number of (secondary) vertices has been reached,\n\/\/ the array space will be extended automatically\n\/\/\n\/\/ Note : The 4-momentum of the current (primary) vertex\n\/\/ is updated automatically, but the track connecting\n\/\/ both vertices has to be entered separately by the user.\n\/\/\n if (fNvtx == fNvmax) \/\/ Check if maximum vertex number is reached\n {\n fNvmax++;\n fVertices->Expand(fNvmax);\n }\n \n \/\/ Update 4-momentum for current vertex\n fNvtx++;\n fVertices->Add(&v);\n (Ali4Vector)(*this)+=v;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Info(TString f)\n{\n\/\/ Provide vertex information within the coordinate frame f\n cout << \" *AliVertex::Info* Invmass : \" << GetInvmass()\n << \" Charge : \" << GetCharge() << \" Momentum : \" << GetMomentum()\n << \" Ntracks : \" << GetNtracks() << \" Nvertices : \" << fNvtx << endl;\n cout << \" \";\n Ali4Vector::Info(f);\n cout << \" Position\";\n AliPosition::Info(f); \n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::List(TString f)\n{\n\/\/ Provide primary track and sec. vertex information within the coordinate frame f\n\n Info(f); \/\/ Information of the current vertex\n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=GetNtracks(); it++)\n {\n t=GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->Info(f); \n }\n else\n {\n cout << \" *AliVertex::List* Error : No track present.\" << endl; \n }\n }\n\n \/\/ The secondary vertices of this vertex\n AliVertex* v; \n for (Int_t iv=1; iv<=GetNvertices(); iv++)\n {\n v=GetVertex(iv);\n if (v)\n {\n cout << \" ---Level 1 sec. vertex no. \" << iv << endl;\n cout << \" \";\n v->Info(f); \n }\n else\n {\n cout << \" *AliVertex::List* Error : No sec. vertex present.\" << endl; \n }\n }\n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::ListAll(TString f)\n{\n\/\/ Provide complete (sec) vertex and (decay) track info within the coordinate frame f\n\n Info(f); \/\/ Information of the current vertex\n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=GetNtracks(); it++)\n {\n t=GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->ListAll(f); \n }\n else\n {\n cout << \" *AliVertex::ListAll* Error : No track present.\" << endl; \n }\n }\n\n AliVertex* v=this;\n Dump(v,1,f); \/\/ Information of all sec. vertices\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Dump(AliVertex* v,Int_t n,TString f)\n{\n\/\/ Recursively provide the info of all secondary vertices of this vertex\n AliVertex* vs; \n for (Int_t iv=1; iv<=v->GetNvertices(); iv++)\n {\n vs=v->GetVertex(iv);\n if (vs)\n {\n cout << \" ---Level \" << n << \" sec. vertex no. \" << iv << endl;\n cout << \" \";\n vs->Info(f); \n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=vs->GetNtracks(); it++)\n {\n t=vs->GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->ListAll(f); \n }\n else\n {\n cout << \" *AliVertex::Dump* Error : No track present.\" << endl; \n }\n }\n\n \/\/ Go for next sec. vertex level of this sec. vertex recursively\n Dump(vs,n+1,f);\n }\n else\n {\n cout << \" *AliVertex::Dump* Error : No sec. vertex present.\" << endl; \n }\n }\n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nInt_t AliVertex::GetNvertices()\n{\n\/\/ Return the current number of (secondary) vertices\n return fNvtx;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex* AliVertex::GetVertex(Int_t i)\n{\n\/\/ Return the i-th (secondary) vertex of the current vertex\n return (AliVertex*)fVertices->At(i-1);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSmall syntax correction for SunOS#include \"AliVertex.h\"\n \nClassImp(AliVertex) \/\/ Class implementation to enable ROOT I\/O\n \nAliVertex::AliVertex()\n{\n\/\/ Default constructor\n\/\/ All variables initialised to 0\n\/\/ Initial maximum number of tracks is set to the default value\n\/\/ Initial maximum number of sec. vertices is set to the default value\n fNvmax=0;\n fVertices=0;\n Reset();\n SetNtinit();\n SetNvmax();\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex::AliVertex(Int_t n)\n{\n\/\/ Create a vertex to hold initially a maximum of n tracks\n\/\/ All variables initialised to 0\n fNvmax=0;\n fVertices=0;\n Reset();\n if (n > 0)\n {\n SetNtinit(n);\n }\n else\n {\n cout << endl;\n cout << \" *AliVertex* Initial max. number of tracks entered : \" << n << endl;\n cout << \" This is invalid. Default initial maximum will be used.\" << endl;\n cout << endl;\n SetNtinit();\n }\n SetNvmax();\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex::~AliVertex()\n{\n\/\/ Default destructor\n if (fVertices) delete fVertices;\n fVertices=0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::SetNvmax(Int_t n)\n{\n\/\/ Set the initial maximum number of (secondary) vertices\n if (n > 0)\n {\n fNvmax=n;\n }\n else\n {\n fNvmax=1;\n }\n if (fVertices) delete fVertices;\n fVertices=new TObjArray(fNvmax);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Reset()\n{\n\/\/ Reset all variables to 0\n\/\/ The max. number of tracks is set to the initial value again\n\/\/ The max. number of vertices is set to the default value again\n\n AliJet::Reset();\n\n fNvtx=0;\n if (fNvmax>0) SetNvmax(fNvmax);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Add(AliJet& j)\n{\n\/\/ Add the tracks of a jet to the vertex\n AliTrack* tj;\n for (Int_t i=1; i<=j.GetNtracks(); i++)\n {\n tj=j.GetTrack(i);\n AliJet::Add(tj);\n }\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Add(AliVertex& v)\n{\n\/\/ Add a (secondary) vertex to the current vertex.\n\/\/ In case the maximum number of (secondary) vertices has been reached,\n\/\/ the array space will be extended automatically\n\/\/\n\/\/ Note : The 4-momentum of the current (primary) vertex\n\/\/ is updated automatically, but the track connecting\n\/\/ both vertices has to be entered separately by the user.\n\/\/\n if (fNvtx == fNvmax) \/\/ Check if maximum vertex number is reached\n {\n fNvmax++;\n fVertices->Expand(fNvmax);\n }\n \n \/\/ Update 4-momentum for current vertex\n fNvtx++;\n fVertices->Add(&v);\n (*(Ali4Vector*)this)+=v;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Info(TString f)\n{\n\/\/ Provide vertex information within the coordinate frame f\n cout << \" *AliVertex::Info* Invmass : \" << GetInvmass()\n << \" Charge : \" << GetCharge() << \" Momentum : \" << GetMomentum()\n << \" Ntracks : \" << GetNtracks() << \" Nvertices : \" << fNvtx << endl;\n cout << \" \";\n Ali4Vector::Info(f);\n cout << \" Position\";\n AliPosition::Info(f); \n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::List(TString f)\n{\n\/\/ Provide primary track and sec. vertex information within the coordinate frame f\n\n Info(f); \/\/ Information of the current vertex\n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=GetNtracks(); it++)\n {\n t=GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->Info(f); \n }\n else\n {\n cout << \" *AliVertex::List* Error : No track present.\" << endl; \n }\n }\n\n \/\/ The secondary vertices of this vertex\n AliVertex* v; \n for (Int_t iv=1; iv<=GetNvertices(); iv++)\n {\n v=GetVertex(iv);\n if (v)\n {\n cout << \" ---Level 1 sec. vertex no. \" << iv << endl;\n cout << \" \";\n v->Info(f); \n }\n else\n {\n cout << \" *AliVertex::List* Error : No sec. vertex present.\" << endl; \n }\n }\n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::ListAll(TString f)\n{\n\/\/ Provide complete (sec) vertex and (decay) track info within the coordinate frame f\n\n Info(f); \/\/ Information of the current vertex\n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=GetNtracks(); it++)\n {\n t=GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->ListAll(f); \n }\n else\n {\n cout << \" *AliVertex::ListAll* Error : No track present.\" << endl; \n }\n }\n\n AliVertex* v=this;\n Dump(v,1,f); \/\/ Information of all sec. vertices\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid AliVertex::Dump(AliVertex* v,Int_t n,TString f)\n{\n\/\/ Recursively provide the info of all secondary vertices of this vertex\n AliVertex* vs; \n for (Int_t iv=1; iv<=v->GetNvertices(); iv++)\n {\n vs=v->GetVertex(iv);\n if (vs)\n {\n cout << \" ---Level \" << n << \" sec. vertex no. \" << iv << endl;\n cout << \" \";\n vs->Info(f); \n\n \/\/ The tracks of this vertex\n AliTrack* t; \n for (Int_t it=1; it<=vs->GetNtracks(); it++)\n {\n t=vs->GetTrack(it);\n if (t)\n {\n cout << \" ---Track no. \" << it << endl;\n cout << \" \";\n t->ListAll(f); \n }\n else\n {\n cout << \" *AliVertex::Dump* Error : No track present.\" << endl; \n }\n }\n\n \/\/ Go for next sec. vertex level of this sec. vertex recursively\n Dump(vs,n+1,f);\n }\n else\n {\n cout << \" *AliVertex::Dump* Error : No sec. vertex present.\" << endl; \n }\n }\n} \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nInt_t AliVertex::GetNvertices()\n{\n\/\/ Return the current number of (secondary) vertices\n return fNvtx;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nAliVertex* AliVertex::GetVertex(Int_t i)\n{\n\/\/ Return the i-th (secondary) vertex of the current vertex\n return (AliVertex*)fVertices->At(i-1);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"#include \"Modeler3D.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \"GUI\/AllWidgets.h\"\n#include \"GUI\/IAction.h\"\n#include \"Math\/VectorMath.h\"\n\n#include \"FileIO.h\"\n#include \"GuiRenderer.h\"\n\nusing namespace std;\nusing namespace Core;\nusing namespace Core::Math;\nusing namespace Video;\n\nstd::string VertSource = \"\"\n \"#version 120 \\n\"\n \"\"\n \"attribute vec3 aPosition; \\n\"\n \"attribute vec3 aNormal; \\n\"\n \"\"\n \"varying vec3 vViewPosition; \\n\"\n \"varying vec3 vNormal; \\n\"\n \"\"\n \"uniform mat4 Projection; \\n\"\n \"uniform mat4 View; \\n\"\n \"uniform mat4 Model; \\n\"\n \"uniform mat3 NormalMat; \\n\"\n \"\"\n \"void main() \\n\"\n \"{ \\n\"\n \" vNormal = normalize(NormalMat * aNormal); \\n\"\n \" gl_Position = View * Model * vec4(aPosition, 1.0); \\n\"\n \" vViewPosition = gl_Position.xyz \/ gl_Position.w; \\n \"\n \" gl_Position = Projection * gl_Position; \\n\"\n \"} \\n\";\n\nstd::string FragSource = \"\"\n \"#version 120 \\n\"\n \"\"\n \"varying vec3 vViewPosition; \\n\"\n \"varying vec3 vNormal; \\n\"\n \"\"\n \"uniform vec3 LightDirection = vec3(-1, -0.5, -1); \\n\"\n \"\"\n \"float Diffuse(vec3 normal, vec3 lightDir) \\n\"\n \"{ \\n\"\n \" return clamp(dot(normal, -lightDir), 0.0, 1.0); \\n\"\n \"} \\n\"\n \"\"\n \"float Specular(vec3 normal, vec3 lightDir, vec3 cameraDir, float power) \\n\"\n \"{ \\n\"\n \" vec3 halfVec = normalize(lightDir + cameraDir); \\n\"\n \" return pow(clamp(abs(dot(normal, -halfVec)), 0.0, 1.0), power); \"\n \"} \\n\"\n \"\"\n \"void main() \\n\"\n \"{ \\n\"\n \" vec3 normal = normalize(vNormal); \\n\"\n \" vec3 lightDir = normalize(LightDirection); \\n\"\n \" vec3 cameraDir = normalize(vViewPosition); \\n\"\n \"\"\n \" vec3 color = vec3(1.0); \\n\"\n \" float diffuse = Diffuse(normal, lightDir); \\n\"\n \" float specular = Specular(normal, lightDir, cameraDir, 100); \\n\"\n \"\"\n \" gl_FragColor = vec4(color * (diffuse * 0.4 + 0.4 + specular * 0.4), 1.0); \\n\"\n \"} \\n\";\n\nclass LoadAction : public Gui::IAction\n{\npublic:\n LoadAction(Modeler3D* modeler, std::string file) : mModeler(modeler), mFile(file) {}\n ~LoadAction() {}\n\n void OnActionPerformed(Gui::Widget* widget)\n {\n cout << \"Loading file: \" << mFile << endl;\n mModeler->LoadObj(mFile);\n }\nprivate:\n Modeler3D* mModeler;\n std::string mFile;\n};\n\nclass ZoomAction : public Gui::IAction\n{\npublic:\n\tZoomAction(Modeler3D* modeler, int32 zoom) : mModeler(modeler), mZoom(zoom) {}\n ~ZoomAction() {}\n\n void OnActionPerformed(Gui::Widget* widget)\n {\n cout << \"Zoom set to: \" << mZoom << endl;\n mModeler->SetZoom(mZoom);\n }\nprivate:\n Modeler3D* mModeler;\n int32 mZoom;\n};\n\nnamespace Core\n{\n\nVideo::VertexFormat vboFormat = Video::VertexFormat()\n .AddElement(Video::Attribute::Position, 3)\n .AddElement(Video::Attribute::Normal, 3);\n\nstruct VertexPosition3Normal3\n{\n Vector3f Position;\n Vector3f Normal;\n};\n\nModeler3D::Modeler3D(IBackend* backend)\n : Application(backend),\n mEnv(nullptr),\n mGuiRenderer(nullptr),\n mShader(nullptr),\n mGeometry(nullptr),\n mVbo(nullptr),\n mAngle(0),\n\t mMouse(backend->GetWindow()->GetMouse()),\n\t mZoom(2)\n{\n}\n\nModeler3D::~Modeler3D()\n{\n}\n\nvoid Modeler3D::LoadObj(const string& file)\n{\n if (mVbo)\n {\n mGeometry->SetVertexBuffer(nullptr);\n mVbo->Release();\n delete mVbo;\n }\n\n boost::filesystem::path obj(file);\n FileIO objFile;\n objFile.LoadObj(obj);\n\n\/\/ boost::filesystem::path obj(file);\n\/\/ FileIO objFile;\n\/\/ vector> positionss;\n\/\/ vector> textureVertices;\n\/\/ vector> normalVertices;\n\/\/ vector>> faces;\n\/\/ objFile.LoadObj2(obj, positionss, textureVertices, normalVertices, faces);\n\n vector vertices;\n vector> positions = objFile.GetGeometricVertices();\n vector>> faces = objFile.GetFaceElements();\n\n for (uint i = 0; i < faces.size(); i++)\n {\n VertexPosition3Normal3 verts[3];\n for (uint j = 0; j < 3; j++)\n {\n vector pos = positions[faces[i][0][j] - 1];\n for (uint k = 0; k < 3; k++)\n {\n verts[j].Position[k] = pos[k] * 10;\n }\n }\n Vector3f normal = Cross(Normalize( verts[1].Position - verts[0].Position), Normalize( verts[2].Position - verts[0].Position));\n verts[0].Normal = normal;\n verts[1].Normal = normal;\n verts[2].Normal = normal;\n\n vertices.push_back(verts[0]);\n vertices.push_back(verts[1]);\n vertices.push_back(verts[2]);\n }\n\n mVbo = Graphics->CreateVertexBuffer(vboFormat, vertices.size(), Video::BufferHint::Static);\n mVbo->SetData((float32*)(&vertices[0]), 0, vertices.size());\n mGeometry->SetVertexBuffer(mVbo);\n}\n\nvoid Modeler3D::OnInit()\n{\n cout << \"Initializing Modeler3D\" << endl;\n\n mGeometry = Graphics->CreateGeometry();\n\n mEnv = Backend->GetWindow()->GetEnvironment();\n mGuiRenderer = new GuiRenderer(Graphics);\n mShader = Graphics->CreateShader(VertSource, FragSource);\n\n Gui::Button* elem1 = new Gui::Button(10, 10 + 50 * 0, 80, 40, new LoadAction(this, \"Assets\/bunny.obj\"));\n Gui::Button* elem2 = new Gui::Button(10, 10 + 50 * 1, 80, 40, new LoadAction(this, \"Assets\/cube.obj\"));\n Gui::Button* elem3 = new Gui::Button(10, 10 + 50 * 2, 80, 40, new LoadAction(this, \"Assets\/dragon.obj\"));\n Gui::Button* elem4 = new Gui::Button(10, 10 + 50 * 3, 80, 40, new LoadAction(this, \"Assets\/pencil.obj\"));\n\n Gui::Widget* elem5 = new Gui::Button(10, 10 + 50 * 0,80,40, new ZoomAction(this, 1));\n Gui::Widget* elem6 = new Gui::Button(10, 10 + 50 * 1,80,40, new ZoomAction(this, 100));\n Gui::Widget* elem7 = new Gui::Button(10, 10 + 50 * 2,80,40, new ZoomAction(this, 1000));\n Gui::Widget* elem8 = new Gui::Button(10, 10 + 50 * 3,80,40, new ZoomAction(this, 2500));\n\n elem1->SetAlignment(0, 1);\n elem2->SetAlignment(0, 1);\n elem3->SetAlignment(0, 1);\n elem4->SetAlignment(0, 1);\n\n elem5->SetAlignment(1, 1);\n elem6->SetAlignment(1, 1);\n elem7->SetAlignment(1, 1);\n elem8->SetAlignment(1, 1);\n\n mEnv->AddWidget(elem1);\n mEnv->AddWidget(elem2);\n mEnv->AddWidget(elem3);\n mEnv->AddWidget(elem4);\n\n mEnv->AddWidget(elem5);\n mEnv->AddWidget(elem6);\n mEnv->AddWidget(elem7);\n mEnv->AddWidget(elem8);\n}\n\nvoid Modeler3D::OnUpdate(float64 dt)\n{\n mAngle += 1.0 * dt;\n\n mEnv->SetSize(Window->GetWidth(), Window->GetHeight());\n mEnv->Update(dt);\n}\n\nvoid Modeler3D::OnRender()\n{\n Graphics->SetClearColor(0.3, 0.3, 0.3);\n Graphics->Clear();\n\n if (mVbo)\n {\n \tint32 amt = mMouse->GetWheelScroll();\n \tint32 factor = (mZoom <= 50 ? 2 : (mZoom <= 200 ? 3 : (mZoom <= 1000 ? 4 : 5)));\n \tif(amt != 0)\n \t{\n \t\tif(amt > 0)\n \t\t{\n \t\t\tmZoom -= pow(factor,amt);\n \t\t}\n \t\telse\n \t\t{\n \t\t\tmZoom += pow(factor,abs(amt));\n \t\t}\n\n \t\tif(mZoom < 1) mZoom = 1;\n\n \t\tstd::cout << mZoom << std::endl;\n \t}\n\n Matrix4f projection = Matrix4f::ToPerspective(Math::ToRadians(70.0f), Graphics->GetAspectRatio(), 0.1f, 3000.0f);\n Matrix4f view = Matrix4f::ToLookAt(Vector3f(0, 1, mZoom), Vector3f::Zero, Vector3f::Up);\n Matrix4f model = Matrix4f::ToYaw(mAngle) * Matrix4f::ToPitch(mAngle * 1.3) * Matrix4f::ToRoll(mAngle * 1.7) * Matrix4f::ToTranslation(Vector3f(0.2, -0.8, 0));\n Matrix3f normalMat(Inverse(Transpose(model)));\n\n mShader->SetMatrix4f(\"Projection\", projection);\n mShader->SetMatrix4f(\"View\", view);\n mShader->SetMatrix4f(\"Model\", model);\n mShader->SetMatrix3f(\"NormalMat\", normalMat);\n\n Graphics->SetShader(mShader);\n Graphics->SetGeometry(mGeometry);\n Graphics->Draw(Video::Primitive::TriangleList, 0, mVbo->GetLength() \/ 3);\n }\n\n mGuiRenderer->Reset();\n mEnv->Draw(mGuiRenderer);\n}\n\nvoid Modeler3D::SetZoom(int32 zoom) { mZoom = zoom; }\n\nvoid Modeler3D::OnDestroy()\n{\n cout << \"Destroying Modeler3D\" << endl;\n mGuiRenderer->Release();\n mShader->Release();\n mGeometry->SetVertexBuffer(nullptr);\n mGeometry->Release();\n mVbo->Release();\n}\n\n}\nslowed down scrolling for close view#include \"Modeler3D.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \"GUI\/AllWidgets.h\"\n#include \"GUI\/IAction.h\"\n#include \"Math\/VectorMath.h\"\n\n#include \"FileIO.h\"\n#include \"GuiRenderer.h\"\n\nusing namespace std;\nusing namespace Core;\nusing namespace Core::Math;\nusing namespace Video;\n\nstd::string VertSource = \"\"\n \"#version 120 \\n\"\n \"\"\n \"attribute vec3 aPosition; \\n\"\n \"attribute vec3 aNormal; \\n\"\n \"\"\n \"varying vec3 vViewPosition; \\n\"\n \"varying vec3 vNormal; \\n\"\n \"\"\n \"uniform mat4 Projection; \\n\"\n \"uniform mat4 View; \\n\"\n \"uniform mat4 Model; \\n\"\n \"uniform mat3 NormalMat; \\n\"\n \"\"\n \"void main() \\n\"\n \"{ \\n\"\n \" vNormal = normalize(NormalMat * aNormal); \\n\"\n \" gl_Position = View * Model * vec4(aPosition, 1.0); \\n\"\n \" vViewPosition = gl_Position.xyz \/ gl_Position.w; \\n \"\n \" gl_Position = Projection * gl_Position; \\n\"\n \"} \\n\";\n\nstd::string FragSource = \"\"\n \"#version 120 \\n\"\n \"\"\n \"varying vec3 vViewPosition; \\n\"\n \"varying vec3 vNormal; \\n\"\n \"\"\n \"uniform vec3 LightDirection = vec3(-1, -0.5, -1); \\n\"\n \"\"\n \"float Diffuse(vec3 normal, vec3 lightDir) \\n\"\n \"{ \\n\"\n \" return clamp(dot(normal, -lightDir), 0.0, 1.0); \\n\"\n \"} \\n\"\n \"\"\n \"float Specular(vec3 normal, vec3 lightDir, vec3 cameraDir, float power) \\n\"\n \"{ \\n\"\n \" vec3 halfVec = normalize(lightDir + cameraDir); \\n\"\n \" return pow(clamp(abs(dot(normal, -halfVec)), 0.0, 1.0), power); \"\n \"} \\n\"\n \"\"\n \"void main() \\n\"\n \"{ \\n\"\n \" vec3 normal = normalize(vNormal); \\n\"\n \" vec3 lightDir = normalize(LightDirection); \\n\"\n \" vec3 cameraDir = normalize(vViewPosition); \\n\"\n \"\"\n \" vec3 color = vec3(1.0); \\n\"\n \" float diffuse = Diffuse(normal, lightDir); \\n\"\n \" float specular = Specular(normal, lightDir, cameraDir, 100); \\n\"\n \"\"\n \" gl_FragColor = vec4(color * (diffuse * 0.4 + 0.4 + specular * 0.4), 1.0); \\n\"\n \"} \\n\";\n\nclass LoadAction : public Gui::IAction\n{\npublic:\n LoadAction(Modeler3D* modeler, std::string file) : mModeler(modeler), mFile(file) {}\n ~LoadAction() {}\n\n void OnActionPerformed(Gui::Widget* widget)\n {\n cout << \"Loading file: \" << mFile << endl;\n mModeler->LoadObj(mFile);\n }\nprivate:\n Modeler3D* mModeler;\n std::string mFile;\n};\n\nclass ZoomAction : public Gui::IAction\n{\npublic:\n\tZoomAction(Modeler3D* modeler, int32 zoom) : mModeler(modeler), mZoom(zoom) {}\n ~ZoomAction() {}\n\n void OnActionPerformed(Gui::Widget* widget)\n {\n cout << \"Zoom set to: \" << mZoom << endl;\n mModeler->SetZoom(mZoom);\n }\nprivate:\n Modeler3D* mModeler;\n int32 mZoom;\n};\n\nnamespace Core\n{\n\nVideo::VertexFormat vboFormat = Video::VertexFormat()\n .AddElement(Video::Attribute::Position, 3)\n .AddElement(Video::Attribute::Normal, 3);\n\nstruct VertexPosition3Normal3\n{\n Vector3f Position;\n Vector3f Normal;\n};\n\nModeler3D::Modeler3D(IBackend* backend)\n : Application(backend),\n mEnv(nullptr),\n mGuiRenderer(nullptr),\n mShader(nullptr),\n mGeometry(nullptr),\n mVbo(nullptr),\n mAngle(0),\n\t mMouse(backend->GetWindow()->GetMouse()),\n\t mZoom(2)\n{\n}\n\nModeler3D::~Modeler3D()\n{\n}\n\nvoid Modeler3D::LoadObj(const string& file)\n{\n if (mVbo)\n {\n mGeometry->SetVertexBuffer(nullptr);\n mVbo->Release();\n delete mVbo;\n }\n\n boost::filesystem::path obj(file);\n FileIO objFile;\n objFile.LoadObj(obj);\n\n\/\/ boost::filesystem::path obj(file);\n\/\/ FileIO objFile;\n\/\/ vector> positionss;\n\/\/ vector> textureVertices;\n\/\/ vector> normalVertices;\n\/\/ vector>> faces;\n\/\/ objFile.LoadObj2(obj, positionss, textureVertices, normalVertices, faces);\n\n vector vertices;\n vector> positions = objFile.GetGeometricVertices();\n vector>> faces = objFile.GetFaceElements();\n\n for (uint i = 0; i < faces.size(); i++)\n {\n VertexPosition3Normal3 verts[3];\n for (uint j = 0; j < 3; j++)\n {\n vector pos = positions[faces[i][0][j] - 1];\n for (uint k = 0; k < 3; k++)\n {\n verts[j].Position[k] = pos[k] * 10;\n }\n }\n Vector3f normal = Cross(Normalize( verts[1].Position - verts[0].Position), Normalize( verts[2].Position - verts[0].Position));\n verts[0].Normal = normal;\n verts[1].Normal = normal;\n verts[2].Normal = normal;\n\n vertices.push_back(verts[0]);\n vertices.push_back(verts[1]);\n vertices.push_back(verts[2]);\n }\n\n mVbo = Graphics->CreateVertexBuffer(vboFormat, vertices.size(), Video::BufferHint::Static);\n mVbo->SetData((float32*)(&vertices[0]), 0, vertices.size());\n mGeometry->SetVertexBuffer(mVbo);\n}\n\nvoid Modeler3D::OnInit()\n{\n cout << \"Initializing Modeler3D\" << endl;\n\n mGeometry = Graphics->CreateGeometry();\n\n mEnv = Backend->GetWindow()->GetEnvironment();\n mGuiRenderer = new GuiRenderer(Graphics);\n mShader = Graphics->CreateShader(VertSource, FragSource);\n\n Gui::Button* elem1 = new Gui::Button(10, 10 + 50 * 0, 80, 40, new LoadAction(this, \"Assets\/bunny.obj\"));\n Gui::Button* elem2 = new Gui::Button(10, 10 + 50 * 1, 80, 40, new LoadAction(this, \"Assets\/cube.obj\"));\n Gui::Button* elem3 = new Gui::Button(10, 10 + 50 * 2, 80, 40, new LoadAction(this, \"Assets\/dragon.obj\"));\n Gui::Button* elem4 = new Gui::Button(10, 10 + 50 * 3, 80, 40, new LoadAction(this, \"Assets\/pencil.obj\"));\n\n Gui::Widget* elem5 = new Gui::Button(10, 10 + 50 * 0,80,40, new ZoomAction(this, 1));\n Gui::Widget* elem6 = new Gui::Button(10, 10 + 50 * 1,80,40, new ZoomAction(this, 100));\n Gui::Widget* elem7 = new Gui::Button(10, 10 + 50 * 2,80,40, new ZoomAction(this, 1000));\n Gui::Widget* elem8 = new Gui::Button(10, 10 + 50 * 3,80,40, new ZoomAction(this, 2500));\n\n elem1->SetAlignment(0, 1);\n elem2->SetAlignment(0, 1);\n elem3->SetAlignment(0, 1);\n elem4->SetAlignment(0, 1);\n\n elem5->SetAlignment(1, 1);\n elem6->SetAlignment(1, 1);\n elem7->SetAlignment(1, 1);\n elem8->SetAlignment(1, 1);\n\n mEnv->AddWidget(elem1);\n mEnv->AddWidget(elem2);\n mEnv->AddWidget(elem3);\n mEnv->AddWidget(elem4);\n\n mEnv->AddWidget(elem5);\n mEnv->AddWidget(elem6);\n mEnv->AddWidget(elem7);\n mEnv->AddWidget(elem8);\n}\n\nvoid Modeler3D::OnUpdate(float64 dt)\n{\n mAngle += 1.0 * dt;\n\n mEnv->SetSize(Window->GetWidth(), Window->GetHeight());\n mEnv->Update(dt);\n}\n\nvoid Modeler3D::OnRender()\n{\n Graphics->SetClearColor(0.3, 0.3, 0.3);\n Graphics->Clear();\n\n if (mVbo)\n {\n \tint32 amt = mMouse->GetWheelScroll();\n \tif(amt != 0)\n \t{\n \tamt = (amt > 4 ? 4 : amt);\n \tamt = (amt < -4 ? -4 : amt);\n \tint32 factor = (mZoom <= 50 ? 1 : (mZoom <= 200 ? 2 : (mZoom <= 1000 ? 3 : 4)));\n \t\tif(amt > 0)\n \t\t{\n \t\t\tmZoom -= pow(factor,amt);\n \t\t}\n \t\telse\n \t\t{\n \t\t\tmZoom += pow(factor,abs(amt));\n \t\t}\n\n \t\tif(mZoom < 1) mZoom = 1;\n \t}\n\n Matrix4f projection = Matrix4f::ToPerspective(Math::ToRadians(70.0f), Graphics->GetAspectRatio(), 0.1f, 3000.0f);\n Matrix4f view = Matrix4f::ToLookAt(Vector3f(0, 1, mZoom), Vector3f::Zero, Vector3f::Up);\n Matrix4f model = Matrix4f::ToYaw(mAngle) * Matrix4f::ToPitch(mAngle * 1.3) * Matrix4f::ToRoll(mAngle * 1.7) * Matrix4f::ToTranslation(Vector3f(0.2, -0.8, 0));\n Matrix3f normalMat(Inverse(Transpose(model)));\n\n mShader->SetMatrix4f(\"Projection\", projection);\n mShader->SetMatrix4f(\"View\", view);\n mShader->SetMatrix4f(\"Model\", model);\n mShader->SetMatrix3f(\"NormalMat\", normalMat);\n\n Graphics->SetShader(mShader);\n Graphics->SetGeometry(mGeometry);\n Graphics->Draw(Video::Primitive::TriangleList, 0, mVbo->GetLength() \/ 3);\n }\n\n mGuiRenderer->Reset();\n mEnv->Draw(mGuiRenderer);\n}\n\nvoid Modeler3D::SetZoom(int32 zoom) { mZoom = zoom; }\n\nvoid Modeler3D::OnDestroy()\n{\n cout << \"Destroying Modeler3D\" << endl;\n mGuiRenderer->Release();\n mShader->Release();\n mGeometry->SetVertexBuffer(nullptr);\n mGeometry->Release();\n mVbo->Release();\n}\n\n}\n<|endoftext|>"} {"text":"#include \"SF2Reader.h\"\n#include \"SF2Sound.h\"\n#include \"SFZSample.h\"\n#include \"RIFF.h\"\n#include \"SF2.h\"\n#include \"SF2Generator.h\"\n#include \"SFZDebug.h\"\n\n\nSF2Reader::SF2Reader(SF2Sound* soundIn, const File& fileIn)\n\t: sound(soundIn)\n{\n\tfile = fileIn.createInputStream();\n}\n\n\nSF2Reader::~SF2Reader()\n{\n\tdelete file;\n}\n\n\nvoid SF2Reader::read()\n{\n\tif (file == NULL) {\n\t\tsound->addError(\"Couldn't open file.\");\n\t\treturn;\n\t\t}\n\n\t\/\/ Read the hydra.\n\tSF2::Hydra hydra;\n\tfile->setPosition(0);\n\tRIFFChunk riffChunk;\n\triffChunk.ReadFrom(file);\n\twhile (file->getPosition() < riffChunk.End()) {\n\t\tRIFFChunk chunk;\n\t\tchunk.ReadFrom(file);\n\t\tif (FourCCEquals(chunk.id, \"pdta\")) {\n\t\t\thydra.ReadFrom(file, chunk.End());\n\t\t\tbreak;\n\t\t\t}\n\t\tchunk.SeekAfter(file);\n\t\t}\n\tif (!hydra.IsComplete()) {\n\t\tsound->addError(\"Invalid SF2 file (missing or incomplete hydra).\");\n\t\treturn;\n\t\t}\n\n\t\/\/ Read each preset.\n\tfor (int whichPreset = 0; whichPreset < hydra.phdrNumItems - 1; ++whichPreset) {\n\t\tSF2::phdr* phdr = &hydra.phdrItems[whichPreset];\n\t\tSF2Sound::Preset* preset = new SF2Sound::Preset(phdr->presetName, phdr->preset);\n\t\tsound->addPreset(preset);\n\n\t\t\/\/ Zones.\n\t\t\/\/*** TODO: Handle global zone.\n\t\tint zoneEnd = phdr[1].presetBagNdx;\n\t\tfor (int whichZone = phdr->presetBagNdx; whichZone < zoneEnd; ++whichZone) {\n\t\t\tSF2::pbag* pbag = &hydra.pbagItems[whichZone];\n\t\t\tSFZRegion presetRegion;\n\t\t\tpresetRegion.clearForSF2();\n\n\t\t\t\/\/ Generators.\n\t\t\tint genEnd = pbag[1].genNdx;\n\t\t\tfor (int whichGen = pbag->genNdx; whichGen < genEnd; ++whichGen) {\n\t\t\t\tSF2::pgen* pgen = &hydra.pgenItems[whichGen];\n\n\t\t\t\t\/\/ Instrument.\n\t\t\t\tif (pgen->genOper == SF2Generator::instrument) {\n\t\t\t\t\tword whichInst = pgen->genAmount.wordAmount;\n\t\t\t\t\tif (whichInst < hydra.instNumItems) {\n\t\t\t\t\t\tSFZRegion instRegion = presetRegion;\n\t\t\t\t\t\tSF2::inst* inst = &hydra.instItems[whichInst];\n\t\t\t\t\t\tint zoneEnd = inst[1].instBagNdx;\n\t\t\t\t\t\tfor (int whichZone = inst->instBagNdx; whichZone < zoneEnd; ++whichZone) {\n\t\t\t\t\t\t\tSF2::ibag* ibag = &hydra.ibagItems[whichZone];\n\n\t\t\t\t\t\t\t\/\/ Generators.\n\t\t\t\t\t\t\tSFZRegion zoneRegion = instRegion;\n\t\t\t\t\t\t\tint genEnd = ibag[1].instGenNdx;\n\t\t\t\t\t\t\tfor (int whichGen = ibag->instGenNdx; whichGen < genEnd; ++whichGen) {\n\t\t\t\t\t\t\t\tSF2::igen* igen = &hydra.igenItems[whichGen];\n\t\t\t\t\t\t\t\tif (igen->genOper == SF2Generator::sampleID) {\n\t\t\t\t\t\t\t\t\tint whichSample = igen->genAmount.wordAmount;\n\t\t\t\t\t\t\t\t\tSF2::shdr* shdr = &hydra.shdrItems[whichSample];\n\t\t\t\t\t\t\t\t\tzoneRegion.offset += shdr->start;\n\t\t\t\t\t\t\t\t\tzoneRegion.end += shdr->end;\n\t\t\t\t\t\t\t\t\tzoneRegion.loop_start += shdr->startLoop;\n\t\t\t\t\t\t\t\t\tzoneRegion.loop_end += shdr->endLoop;\n\t\t\t\t\t\t\t\t\tif (shdr->endLoop > 0)\n\t\t\t\t\t\t\t\t\t\tzoneRegion.loop_end -= 1;\n\t\t\t\t\t\t\t\t\tif (zoneRegion.pitch_keycenter == -1)\n\t\t\t\t\t\t\t\t\t\tzoneRegion.pitch_keycenter = shdr->originalPitch;\n\t\t\t\t\t\t\t\t\tzoneRegion.tune += shdr->pitchCorrection;\n\n\t\t\t\t\t\t\t\t\tSFZRegion* newRegion = new SFZRegion();\n\t\t\t\t\t\t\t\t\t*newRegion = zoneRegion;\n\t\t\t\t\t\t\t\t\tpreset->addRegion(newRegion);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\taddGeneratorToRegion(igen->genOper, &igen->genAmount, &zoneRegion);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ Modulators.\n\t\t\t\t\t\t\tint modEnd = ibag[1].instModNdx;\n\t\t\t\t\t\t\tint whichMod = ibag->instModNdx;\n\t\t\t\t\t\t\tif (whichMod < modEnd)\n\t\t\t\t\t\t\t\tsound->addUnsupportedOpcode(\"any modulator\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsound->addError(\"Instrument out of range.\");\n\t\t\t\t\t}\n\n\t\t\t\t\/\/ Other generators.\n\t\t\t\telse\n\t\t\t\t\taddGeneratorToRegion(pgen->genOper, &pgen->genAmount, &presetRegion);\n\t\t\t\t}\n\n\t\t\t\/\/ Modulators.\n\t\t\tint modEnd = pbag[1].modNdx;\n\t\t\tint whichMod = pbag->modNdx;\n\t\t\tif (whichMod < modEnd)\n\t\t\t\tsound->addUnsupportedOpcode(\"any modulator\");\n\t\t\t}\n\t\t}\n\n\t\/\/ Check the samples for the sample rate.\n\tdword sampleRate = 0;\n\tfor (int whichSample = 0; whichSample < hydra.shdrNumItems - 1; ++whichSample) {\n\t\tSF2::shdr* shdr = &hydra.shdrItems[whichSample];\n\t\tif (whichSample == 0)\n\t\t\tsampleRate = shdr->sampleRate;\n\t\telse if (shdr->sampleRate != sampleRate)\n\t\t\tsound->addError(\"SFZero doesn't support SF2's that use multiple sample rates.\");\n\t\t}\n\tthis->sampleRate = sampleRate;\n}\n\n\nSFZSample* SF2Reader::readSamples(double sampleRate, double* progressVar, Thread* thread)\n{\n\tstatic const unsigned long bufferSize = 32768;\n\n\tif (file == NULL) {\n\t\tsound->addError(\"Couldn't open file.\");\n\t\treturn NULL;\n\t\t}\n\n\t\/\/ Find the \"sdta\" chunk.\n\tfile->setPosition(0);\n\tRIFFChunk riffChunk;\n\triffChunk.ReadFrom(file);\n\tbool found = false;\n\tRIFFChunk chunk;\n\twhile (file->getPosition() < riffChunk.End()) {\n\t\tchunk.ReadFrom(file);\n\t\tif (FourCCEquals(chunk.id, \"sdta\")) {\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t\t}\n\t\tchunk.SeekAfter(file);\n\t\t}\n\tif (!found) {\n\t\tsound->addError(\"SF2 is missing its \\\"smpl\\\" chunk.\");\n\t\treturn NULL;\n\t\t}\n\n\t\/\/ Allocate the AudioSampleBuffer.\n\tunsigned long numSamples = chunk.size \/ sizeof(short);\n\tAudioSampleBuffer* sampleBuffer = new AudioSampleBuffer(1, numSamples);\n\n\t\/\/ Read and convert.\n\tshort* buffer = new short[bufferSize];\n\tunsigned long samplesLeft = numSamples;\n\tfloat* out = sampleBuffer->getSampleData(0);\n\twhile (samplesLeft > 0) {\n\t\t\/\/ Read the buffer.\n\t\tunsigned long samplesToRead = bufferSize;\n\t\tif (samplesToRead > samplesLeft)\n\t\t\tsamplesToRead = samplesLeft;\n\t\tfile->read(buffer, samplesToRead * sizeof(short));\n\n\t\t\/\/ Convert from signed 16-bit to float.\n\t\tunsigned long samplesToConvert = samplesToRead;\n\t\tshort* in = buffer;\n\t\tfor (; samplesToConvert > 0; --samplesToConvert) {\n\t\t\t\/\/ If we ever need to compile for big-endian platforms, we'll need to\n\t\t\t\/\/ byte-swap here.\n\t\t\t*out++ = *in++ \/ 32767.0;\n\t\t\t}\n\n\t\tsamplesLeft -= samplesToRead;\n\n\t\tif (progressVar)\n\t\t\t*progressVar = (float) (numSamples - samplesLeft) \/ numSamples;\n\t\tif (thread && thread->threadShouldExit()) {\n\t\t\tdelete buffer;\n\t\t\tdelete sampleBuffer;\n\t\t\treturn NULL;\n\t\t\t}\n\t\t}\n\tdelete buffer;\n\n\tif (progressVar)\n\t\t*progressVar = 1.0;\n\n\treturn new SFZSample(sampleBuffer, sampleRate);\n}\n\n\nvoid SF2Reader::addGeneratorToRegion(\n\tword genOper, SF2::genAmountType* amount, SFZRegion* region)\n{\n\tswitch (genOper) {\n\t\tcase SF2Generator::startAddrsOffset:\n\t\t\tregion->offset += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endAddrsOffset:\n\t\t\tregion->end += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::startloopAddrsOffset:\n\t\t\tregion->loop_start += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endloopAddrsOffset:\n\t\t\tregion->loop_end += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::startAddrsCoarseOffset:\n\t\t\tregion->offset += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::endAddrsCoarseOffset:\n\t\t\tregion->end += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::pan:\n\t\t\tregion->pan = amount->shortAmount * (2.0 \/ 10.0);\n\t\t\tbreak;\n\t\tcase SF2Generator::delayVolEnv:\n\t\t\tregion->ampeg.delay = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::attackVolEnv:\n\t\t\tregion->ampeg.attack = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::holdVolEnv:\n\t\t\tregion->ampeg.hold = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::decayVolEnv:\n\t\t\tregion->ampeg.decay = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::sustainVolEnv:\n\t\t\tregion->ampeg.sustain = 100.0 - amount->shortAmount \/ 10.0;\n\t\t\tbreak;\n\t\tcase SF2Generator::releaseVolEnv:\n\t\t\tregion->ampeg.release = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::keyRange:\n\t\t\tregion->lokey = amount->range.lo;\n\t\t\tregion->hikey = amount->range.hi;\n\t\t\tbreak;\n\t\tcase SF2Generator::velRange:\n\t\t\tregion->lovel = amount->range.lo;\n\t\t\tregion->hivel = amount->range.hi;\n\t\t\tbreak;\n\t\tcase SF2Generator::startloopAddrsCoarseOffset:\n\t\t\tregion->loop_start += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::initialAttenuation:\n\t\t\tregion->volume = -amount->shortAmount \/ 10.0;\n\t\t\tbreak;\n\t\tcase SF2Generator::endloopAddrsCoarseOffset:\n\t\t\tregion->loop_end += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::coarseTune:\n\t\t\tregion->transpose = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::fineTune:\n\t\t\tregion->tune = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::sampleModes:\n\t\t\t{\n\t\t\t\tSFZRegion::LoopMode loopModes[] = {\n\t\t\t\t\tSFZRegion::no_loop, SFZRegion::loop_continuous,\n\t\t\t\t\tSFZRegion::no_loop, SFZRegion::loop_sustain };\n\t\t\t\tregion->loop_mode = loopModes[amount->wordAmount & 0x03];\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SF2Generator::scaleTuning:\n\t\t\tregion->pitch_keytrack = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::exclusiveClass:\n\t\t\tregion->group = region->off_by = amount->wordAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::overridingRootKey:\n\t\t\tregion->pitch_keycenter = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endOper:\n\t\t\t\/\/ Ignore.\n\t\t\tbreak;\n\n\t\tcase SF2Generator::modLfoToPitch:\n\t\tcase SF2Generator::vibLfoToPitch:\n\t\tcase SF2Generator::modEnvToPitch:\n\t\tcase SF2Generator::initialFilterFc:\n\t\tcase SF2Generator::initialFilterQ:\n\t\tcase SF2Generator::modLfoToFilterFc:\n\t\tcase SF2Generator::modEnvToFilterFc:\n\t\tcase SF2Generator::modLfoToVolume:\n\t\tcase SF2Generator::unused1:\n\t\tcase SF2Generator::chorusEffectsSend:\n\t\tcase SF2Generator::reverbEffectsSend:\n\t\tcase SF2Generator::unused2:\n\t\tcase SF2Generator::unused3:\n\t\tcase SF2Generator::unused4:\n\t\tcase SF2Generator::delayModLFO:\n\t\tcase SF2Generator::freqModLFO:\n\t\tcase SF2Generator::delayVibLFO:\n\t\tcase SF2Generator::freqVibLFO:\n\t\tcase SF2Generator::delayModEnv:\n\t\tcase SF2Generator::attackModEnv:\n\t\tcase SF2Generator::holdModEnv:\n\t\tcase SF2Generator::decayModEnv:\n\t\tcase SF2Generator::sustainModEnv:\n\t\tcase SF2Generator::releaseModEnv:\n\t\tcase SF2Generator::keynumToModEnvHold:\n\t\tcase SF2Generator::keynumToModEnvDecay:\n\t\tcase SF2Generator::keynumToVolEnvHold:\n\t\tcase SF2Generator::keynumToVolEnvDecay:\n\t\tcase SF2Generator::instrument:\n\t\t\t\/\/ Only allowed in certain places, where we already special-case it.\n\t\tcase SF2Generator::reserved1:\n\t\tcase SF2Generator::keynum:\n\t\tcase SF2Generator::velocity:\n\t\tcase SF2Generator::reserved2:\n\t\tcase SF2Generator::sampleID:\n\t\t\t\/\/ Only allowed in certain places, where we already special-case it.\n\t\tcase SF2Generator::reserved3:\n\t\tcase SF2Generator::unused5:\n\t\t\t{\n\t\t\t\tconst SF2Generator* generator = GeneratorFor(genOper);\n\t\t\t\tsound->addUnsupportedOpcode(generator->name);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n}\n\n\nfloat SF2Reader::timecents2Secs(short timecents)\n{\n\treturn pow(2.0, timecents \/ 1200.0);\n}\n\n\n\nSF2: Only one message for multiple sample rates.#include \"SF2Reader.h\"\n#include \"SF2Sound.h\"\n#include \"SFZSample.h\"\n#include \"RIFF.h\"\n#include \"SF2.h\"\n#include \"SF2Generator.h\"\n#include \"SFZDebug.h\"\n\n\nSF2Reader::SF2Reader(SF2Sound* soundIn, const File& fileIn)\n\t: sound(soundIn)\n{\n\tfile = fileIn.createInputStream();\n}\n\n\nSF2Reader::~SF2Reader()\n{\n\tdelete file;\n}\n\n\nvoid SF2Reader::read()\n{\n\tif (file == NULL) {\n\t\tsound->addError(\"Couldn't open file.\");\n\t\treturn;\n\t\t}\n\n\t\/\/ Read the hydra.\n\tSF2::Hydra hydra;\n\tfile->setPosition(0);\n\tRIFFChunk riffChunk;\n\triffChunk.ReadFrom(file);\n\twhile (file->getPosition() < riffChunk.End()) {\n\t\tRIFFChunk chunk;\n\t\tchunk.ReadFrom(file);\n\t\tif (FourCCEquals(chunk.id, \"pdta\")) {\n\t\t\thydra.ReadFrom(file, chunk.End());\n\t\t\tbreak;\n\t\t\t}\n\t\tchunk.SeekAfter(file);\n\t\t}\n\tif (!hydra.IsComplete()) {\n\t\tsound->addError(\"Invalid SF2 file (missing or incomplete hydra).\");\n\t\treturn;\n\t\t}\n\n\t\/\/ Read each preset.\n\tfor (int whichPreset = 0; whichPreset < hydra.phdrNumItems - 1; ++whichPreset) {\n\t\tSF2::phdr* phdr = &hydra.phdrItems[whichPreset];\n\t\tSF2Sound::Preset* preset = new SF2Sound::Preset(phdr->presetName, phdr->preset);\n\t\tsound->addPreset(preset);\n\n\t\t\/\/ Zones.\n\t\t\/\/*** TODO: Handle global zone.\n\t\tint zoneEnd = phdr[1].presetBagNdx;\n\t\tfor (int whichZone = phdr->presetBagNdx; whichZone < zoneEnd; ++whichZone) {\n\t\t\tSF2::pbag* pbag = &hydra.pbagItems[whichZone];\n\t\t\tSFZRegion presetRegion;\n\t\t\tpresetRegion.clearForSF2();\n\n\t\t\t\/\/ Generators.\n\t\t\tint genEnd = pbag[1].genNdx;\n\t\t\tfor (int whichGen = pbag->genNdx; whichGen < genEnd; ++whichGen) {\n\t\t\t\tSF2::pgen* pgen = &hydra.pgenItems[whichGen];\n\n\t\t\t\t\/\/ Instrument.\n\t\t\t\tif (pgen->genOper == SF2Generator::instrument) {\n\t\t\t\t\tword whichInst = pgen->genAmount.wordAmount;\n\t\t\t\t\tif (whichInst < hydra.instNumItems) {\n\t\t\t\t\t\tSFZRegion instRegion = presetRegion;\n\t\t\t\t\t\tSF2::inst* inst = &hydra.instItems[whichInst];\n\t\t\t\t\t\tint zoneEnd = inst[1].instBagNdx;\n\t\t\t\t\t\tfor (int whichZone = inst->instBagNdx; whichZone < zoneEnd; ++whichZone) {\n\t\t\t\t\t\t\tSF2::ibag* ibag = &hydra.ibagItems[whichZone];\n\n\t\t\t\t\t\t\t\/\/ Generators.\n\t\t\t\t\t\t\tSFZRegion zoneRegion = instRegion;\n\t\t\t\t\t\t\tint genEnd = ibag[1].instGenNdx;\n\t\t\t\t\t\t\tfor (int whichGen = ibag->instGenNdx; whichGen < genEnd; ++whichGen) {\n\t\t\t\t\t\t\t\tSF2::igen* igen = &hydra.igenItems[whichGen];\n\t\t\t\t\t\t\t\tif (igen->genOper == SF2Generator::sampleID) {\n\t\t\t\t\t\t\t\t\tint whichSample = igen->genAmount.wordAmount;\n\t\t\t\t\t\t\t\t\tSF2::shdr* shdr = &hydra.shdrItems[whichSample];\n\t\t\t\t\t\t\t\t\tzoneRegion.offset += shdr->start;\n\t\t\t\t\t\t\t\t\tzoneRegion.end += shdr->end;\n\t\t\t\t\t\t\t\t\tzoneRegion.loop_start += shdr->startLoop;\n\t\t\t\t\t\t\t\t\tzoneRegion.loop_end += shdr->endLoop;\n\t\t\t\t\t\t\t\t\tif (shdr->endLoop > 0)\n\t\t\t\t\t\t\t\t\t\tzoneRegion.loop_end -= 1;\n\t\t\t\t\t\t\t\t\tif (zoneRegion.pitch_keycenter == -1)\n\t\t\t\t\t\t\t\t\t\tzoneRegion.pitch_keycenter = shdr->originalPitch;\n\t\t\t\t\t\t\t\t\tzoneRegion.tune += shdr->pitchCorrection;\n\n\t\t\t\t\t\t\t\t\tSFZRegion* newRegion = new SFZRegion();\n\t\t\t\t\t\t\t\t\t*newRegion = zoneRegion;\n\t\t\t\t\t\t\t\t\tpreset->addRegion(newRegion);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\taddGeneratorToRegion(igen->genOper, &igen->genAmount, &zoneRegion);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ Modulators.\n\t\t\t\t\t\t\tint modEnd = ibag[1].instModNdx;\n\t\t\t\t\t\t\tint whichMod = ibag->instModNdx;\n\t\t\t\t\t\t\tif (whichMod < modEnd)\n\t\t\t\t\t\t\t\tsound->addUnsupportedOpcode(\"any modulator\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tsound->addError(\"Instrument out of range.\");\n\t\t\t\t\t}\n\n\t\t\t\t\/\/ Other generators.\n\t\t\t\telse\n\t\t\t\t\taddGeneratorToRegion(pgen->genOper, &pgen->genAmount, &presetRegion);\n\t\t\t\t}\n\n\t\t\t\/\/ Modulators.\n\t\t\tint modEnd = pbag[1].modNdx;\n\t\t\tint whichMod = pbag->modNdx;\n\t\t\tif (whichMod < modEnd)\n\t\t\t\tsound->addUnsupportedOpcode(\"any modulator\");\n\t\t\t}\n\t\t}\n\n\t\/\/ Check the samples for the sample rate.\n\tdword sampleRate = 0;\n\tbool multipleSampleRates = false;\n\tfor (int whichSample = 0; whichSample < hydra.shdrNumItems - 1; ++whichSample) {\n\t\tSF2::shdr* shdr = &hydra.shdrItems[whichSample];\n\t\tif (whichSample == 0)\n\t\t\tsampleRate = shdr->sampleRate;\n\t\telse if (shdr->sampleRate != sampleRate)\n\t\t\tmultipleSampleRates = true;\n\t\t}\n\tthis->sampleRate = sampleRate;\n\tif (multipleSampleRates)\n\t\tsound->addError(\"SFZero doesn't support SF2's that use multiple sample rates.\");\n}\n\n\nSFZSample* SF2Reader::readSamples(double sampleRate, double* progressVar, Thread* thread)\n{\n\tstatic const unsigned long bufferSize = 32768;\n\n\tif (file == NULL) {\n\t\tsound->addError(\"Couldn't open file.\");\n\t\treturn NULL;\n\t\t}\n\n\t\/\/ Find the \"sdta\" chunk.\n\tfile->setPosition(0);\n\tRIFFChunk riffChunk;\n\triffChunk.ReadFrom(file);\n\tbool found = false;\n\tRIFFChunk chunk;\n\twhile (file->getPosition() < riffChunk.End()) {\n\t\tchunk.ReadFrom(file);\n\t\tif (FourCCEquals(chunk.id, \"sdta\")) {\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t\t}\n\t\tchunk.SeekAfter(file);\n\t\t}\n\tif (!found) {\n\t\tsound->addError(\"SF2 is missing its \\\"smpl\\\" chunk.\");\n\t\treturn NULL;\n\t\t}\n\n\t\/\/ Allocate the AudioSampleBuffer.\n\tunsigned long numSamples = chunk.size \/ sizeof(short);\n\tAudioSampleBuffer* sampleBuffer = new AudioSampleBuffer(1, numSamples);\n\n\t\/\/ Read and convert.\n\tshort* buffer = new short[bufferSize];\n\tunsigned long samplesLeft = numSamples;\n\tfloat* out = sampleBuffer->getSampleData(0);\n\twhile (samplesLeft > 0) {\n\t\t\/\/ Read the buffer.\n\t\tunsigned long samplesToRead = bufferSize;\n\t\tif (samplesToRead > samplesLeft)\n\t\t\tsamplesToRead = samplesLeft;\n\t\tfile->read(buffer, samplesToRead * sizeof(short));\n\n\t\t\/\/ Convert from signed 16-bit to float.\n\t\tunsigned long samplesToConvert = samplesToRead;\n\t\tshort* in = buffer;\n\t\tfor (; samplesToConvert > 0; --samplesToConvert) {\n\t\t\t\/\/ If we ever need to compile for big-endian platforms, we'll need to\n\t\t\t\/\/ byte-swap here.\n\t\t\t*out++ = *in++ \/ 32767.0;\n\t\t\t}\n\n\t\tsamplesLeft -= samplesToRead;\n\n\t\tif (progressVar)\n\t\t\t*progressVar = (float) (numSamples - samplesLeft) \/ numSamples;\n\t\tif (thread && thread->threadShouldExit()) {\n\t\t\tdelete buffer;\n\t\t\tdelete sampleBuffer;\n\t\t\treturn NULL;\n\t\t\t}\n\t\t}\n\tdelete buffer;\n\n\tif (progressVar)\n\t\t*progressVar = 1.0;\n\n\treturn new SFZSample(sampleBuffer, sampleRate);\n}\n\n\nvoid SF2Reader::addGeneratorToRegion(\n\tword genOper, SF2::genAmountType* amount, SFZRegion* region)\n{\n\tswitch (genOper) {\n\t\tcase SF2Generator::startAddrsOffset:\n\t\t\tregion->offset += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endAddrsOffset:\n\t\t\tregion->end += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::startloopAddrsOffset:\n\t\t\tregion->loop_start += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endloopAddrsOffset:\n\t\t\tregion->loop_end += amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::startAddrsCoarseOffset:\n\t\t\tregion->offset += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::endAddrsCoarseOffset:\n\t\t\tregion->end += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::pan:\n\t\t\tregion->pan = amount->shortAmount * (2.0 \/ 10.0);\n\t\t\tbreak;\n\t\tcase SF2Generator::delayVolEnv:\n\t\t\tregion->ampeg.delay = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::attackVolEnv:\n\t\t\tregion->ampeg.attack = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::holdVolEnv:\n\t\t\tregion->ampeg.hold = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::decayVolEnv:\n\t\t\tregion->ampeg.decay = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::sustainVolEnv:\n\t\t\tregion->ampeg.sustain = 100.0 - amount->shortAmount \/ 10.0;\n\t\t\tbreak;\n\t\tcase SF2Generator::releaseVolEnv:\n\t\t\tregion->ampeg.release = timecents2Secs(amount->shortAmount);\n\t\t\tbreak;\n\t\tcase SF2Generator::keyRange:\n\t\t\tregion->lokey = amount->range.lo;\n\t\t\tregion->hikey = amount->range.hi;\n\t\t\tbreak;\n\t\tcase SF2Generator::velRange:\n\t\t\tregion->lovel = amount->range.lo;\n\t\t\tregion->hivel = amount->range.hi;\n\t\t\tbreak;\n\t\tcase SF2Generator::startloopAddrsCoarseOffset:\n\t\t\tregion->loop_start += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::initialAttenuation:\n\t\t\tregion->volume = -amount->shortAmount \/ 10.0;\n\t\t\tbreak;\n\t\tcase SF2Generator::endloopAddrsCoarseOffset:\n\t\t\tregion->loop_end += amount->shortAmount * 32768;\n\t\t\tbreak;\n\t\tcase SF2Generator::coarseTune:\n\t\t\tregion->transpose = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::fineTune:\n\t\t\tregion->tune = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::sampleModes:\n\t\t\t{\n\t\t\t\tSFZRegion::LoopMode loopModes[] = {\n\t\t\t\t\tSFZRegion::no_loop, SFZRegion::loop_continuous,\n\t\t\t\t\tSFZRegion::no_loop, SFZRegion::loop_sustain };\n\t\t\t\tregion->loop_mode = loopModes[amount->wordAmount & 0x03];\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SF2Generator::scaleTuning:\n\t\t\tregion->pitch_keytrack = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::exclusiveClass:\n\t\t\tregion->group = region->off_by = amount->wordAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::overridingRootKey:\n\t\t\tregion->pitch_keycenter = amount->shortAmount;\n\t\t\tbreak;\n\t\tcase SF2Generator::endOper:\n\t\t\t\/\/ Ignore.\n\t\t\tbreak;\n\n\t\tcase SF2Generator::modLfoToPitch:\n\t\tcase SF2Generator::vibLfoToPitch:\n\t\tcase SF2Generator::modEnvToPitch:\n\t\tcase SF2Generator::initialFilterFc:\n\t\tcase SF2Generator::initialFilterQ:\n\t\tcase SF2Generator::modLfoToFilterFc:\n\t\tcase SF2Generator::modEnvToFilterFc:\n\t\tcase SF2Generator::modLfoToVolume:\n\t\tcase SF2Generator::unused1:\n\t\tcase SF2Generator::chorusEffectsSend:\n\t\tcase SF2Generator::reverbEffectsSend:\n\t\tcase SF2Generator::unused2:\n\t\tcase SF2Generator::unused3:\n\t\tcase SF2Generator::unused4:\n\t\tcase SF2Generator::delayModLFO:\n\t\tcase SF2Generator::freqModLFO:\n\t\tcase SF2Generator::delayVibLFO:\n\t\tcase SF2Generator::freqVibLFO:\n\t\tcase SF2Generator::delayModEnv:\n\t\tcase SF2Generator::attackModEnv:\n\t\tcase SF2Generator::holdModEnv:\n\t\tcase SF2Generator::decayModEnv:\n\t\tcase SF2Generator::sustainModEnv:\n\t\tcase SF2Generator::releaseModEnv:\n\t\tcase SF2Generator::keynumToModEnvHold:\n\t\tcase SF2Generator::keynumToModEnvDecay:\n\t\tcase SF2Generator::keynumToVolEnvHold:\n\t\tcase SF2Generator::keynumToVolEnvDecay:\n\t\tcase SF2Generator::instrument:\n\t\t\t\/\/ Only allowed in certain places, where we already special-case it.\n\t\tcase SF2Generator::reserved1:\n\t\tcase SF2Generator::keynum:\n\t\tcase SF2Generator::velocity:\n\t\tcase SF2Generator::reserved2:\n\t\tcase SF2Generator::sampleID:\n\t\t\t\/\/ Only allowed in certain places, where we already special-case it.\n\t\tcase SF2Generator::reserved3:\n\t\tcase SF2Generator::unused5:\n\t\t\t{\n\t\t\t\tconst SF2Generator* generator = GeneratorFor(genOper);\n\t\t\t\tsound->addUnsupportedOpcode(generator->name);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n}\n\n\nfloat SF2Reader::timecents2Secs(short timecents)\n{\n\treturn pow(2.0, timecents \/ 1200.0);\n}\n\n\n\n<|endoftext|>"} {"text":"#include \"Fraction.h\"\n#include \n#include \n\nlong long Fraction::gcd(long long numerator, long long denominator) { \/\/ method of successive division\n\tlong long temp;\n\tif (numerator < denominator) {\n\t\ttemp = denominator;\n\t\tdenominator = numerator;\n\t\tnumerator = temp;\n\t}\n\twhile (denominator != 0) {\n\t\ttemp = numerator % denominator;\n\t\tnumerator = denominator;\n\t\tdenominator = temp;\n\t}\n\treturn numerator;\n}\n\nvoid Fraction::rof() {\n\tif (numerator) {\n\t\tlong long g = gcd(abs(numerator), denominator); \/\/ The g is greatest common divisor of two numbers.\n\t\tnumerator \/= g;\n\t\tdenominator \/= g;\n\t}\n\telse {\n\t\tdenominator = 1;\n\t}\n}\n\n\/\/ Operator overloading.\nFraction operator + (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator += (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator - (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator -= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator * (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator *= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator \/ (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);\n}\n\nFraction operator \/= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);\n\treturn frac1;\n}\n\nstd::ostream& operator<< (std::ostream &os, const Fraction &frac) {\n\tFraction frac_temp(frac.numerator, frac.denominator);\n\tos << frac_temp.numerator;\t\t\t\t\t\t\/\/ When denominator is 1, do not output it.\n\tif (frac_temp.denominator != 1)\n\t\tos << \"\/\" << frac_temp.denominator;\n\treturn os;\n}\n\nstd::istream& operator>> (std::istream &is, Fraction &frac) {\n\tis >> frac.numerator;\n\tif (is.get() != '\/') {\t\t\t\t\t\t\t\/\/ read denominator if and only if next char is '\/'\n\t\treturn is;\n\t}\n\telse {\n\t\tis >> frac.denominator;\n\t}\n\tis.get();\t\t\t\t\t\t\t\t\/\/ use get() to clear the break\n\treturn is;\n}\n\nbool operator == (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);\n}\n\nbool operator != (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 == frac2);\n}\n\nbool operator < (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);\n}\n\nbool operator <= (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1 < frac2) || (frac1 == frac2);\n}\n\nbool operator > (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 <= frac2);\n}\n\nbool operator >= (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 < frac2);\n}\n\nFraction Fraction::Frac_abs(Fraction &temp_frac) { \/\/ Absolute value of a fraction.\n\treturn (temp_frac >= 0) ? temp_frac : (0 - temp_frac);\n}\n\nvoid Fraction::cin_num(long long temp_a) {\n\tthis->numerator = temp_a;\n}\n\nvoid Fraction::cin_den(long long temp_a) {\n\tthis->denominator = temp_a;\n}\nUpdate Fraction.cpp#include \"Fraction.h\"\n#include \n#include \n#include \n\nlong long Fraction::gcd(long long numerator, long long denominator) { \/\/ Greatest common factor\n\tlong long temp;\n\tif (numerator < denominator) {\n\t\ttemp = denominator;\n\t\tdenominator = numerator;\n\t\tnumerator = temp;\n\t}\n\twhile (denominator != 0) {\n\t\ttemp = numerator % denominator;\n\t\tnumerator = denominator;\n\t\tdenominator = temp;\n\t}\n\treturn numerator;\n}\n\nvoid Fraction::rof() {\n\tif (numerator) {\n\t\tlong long g = gcd(abs(numerator), denominator); \/\/ The g is greatest common divisor of two numbers.\n\t\tnumerator \/= g;\n\t\tdenominator \/= g;\n\t}\n\telse {\n\t\tdenominator = 1;\n\t}\n}\n\n\/\/ Operator overloading.\nFraction operator + (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator += (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator - (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator -= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator * (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);\n}\n\nFraction operator *= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);\n\treturn frac1;\n}\n\nFraction operator \/ (const Fraction &frac1, const Fraction &frac2) {\n\treturn Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);\n}\n\nFraction operator \/= (Fraction &frac1, const Fraction &frac2) {\n\tfrac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);\n\treturn frac1;\n}\n\nstd::ostream& operator<< (std::ostream &os, const Fraction &frac) {\n\tFraction frac_temp(frac.numerator, frac.denominator);\n\tos << frac_temp.numerator;\t\t\t\t\t\t\/\/ When denominator is 1, do not output it.\n\tif (frac_temp.denominator != 1)\n\t\tos << \"\/\" << frac_temp.denominator;\n\treturn os;\n}\n\nstd::istream& operator >> (std::istream &is, Fraction &frac) {\n\tis >> frac.numerator;\n\tif (is.get() != '\/') {\t\t\t\t\t\t\t\/\/ read denominator if and only if next char is '\/'\n\t\treturn is;\n\t}\n\telse {\n\t\tis >> frac.denominator;\n\t}\n\tis.get();\t\t\t\t\t\t\t\t \/\/ use get() to clear the break\n\treturn is;\n}\n\nbool operator == (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);\n}\n\nbool operator != (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 == frac2);\n}\n\nbool operator < (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);\n}\n\nbool operator <= (const Fraction &frac1, const Fraction &frac2) {\n\treturn (frac1 < frac2) || (frac1 == frac2);\n}\n\nbool operator > (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 <= frac2);\n}\n\nbool operator >= (const Fraction &frac1, const Fraction &frac2) {\n\treturn !(frac1 < frac2);\n}\n\nFraction Fraction::Frac_abs(Fraction &temp_frac) { \/\/ Absolute value of a fraction.\n\treturn (temp_frac >= 0) ? temp_frac : (0 - temp_frac);\n}\n\nvoid Fraction::cin_num(long long temp_a) { \/\/ Input a Fraction's numerator.\n\tthis->numerator = temp_a;\n}\n\nvoid Fraction::cin_den(long long temp_a) { \/\/ Input a Fraction's denminator.\n\tthis->denominator = temp_a;\n}\n\nstring Fraction::cout_temp_addition_for_transmission() const { \/\/ Temporary output.\n\tstd::ostringstream out;\n\tout << *this;\n\n\treturn out.str();\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/-----------------------------------------------------------------\n\/\/ Implementation of the TPC PID class\n\/\/ Very naive one... Should be made better by the detector experts...\n\/\/ Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch\n\/\/-----------------------------------------------------------------\n\n#include \"AliTPCpidESD.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDtrack.h\"\n\nClassImp(AliTPCpidESD)\n\n\/\/_________________________________________________________________________\n AliTPCpidESD::AliTPCpidESD(Double_t *param):\n fMIP(0.),\n fRes(0.),\n fRange(0.)\n{\n \/\/\n \/\/ The main constructor\n \/\/\n fMIP=param[0];\n fRes=param[1];\n fRange=param[2];\n}\n\nDouble_t AliTPCpidESD::Bethe(Double_t bg) {\n \/\/\n \/\/ This is the Bethe-Bloch function normalised to 1 at the minimum\n \/\/\n Double_t bg2=bg*bg;\n Double_t bethe;\n if (bg<3.5e1) \n bethe=(1.+ bg2)\/bg2*(log(5940*bg2) - bg2\/(1.+ bg2));\n else \/\/ Density effect ( approximately :) \n bethe=1.15*(1.+ bg2)\/bg2*(log(3.5*5940*bg) - bg2\/(1.+ bg2));\n return bethe\/11.091;\n}\n\n\/\/_________________________________________________________________________\nInt_t AliTPCpidESD::MakePID(AliESDEvent *event)\n{\n \/\/\n \/\/ This function calculates the \"detector response\" PID probabilities \n \/\/\n Int_t ntrk=event->GetNumberOfTracks();\n for (Int_t i=0; iGetTrack(i);\n if ((t->GetStatus()&AliESDtrack::kTPCin )==0)\n if ((t->GetStatus()&AliESDtrack::kTPCout)==0) continue;\n Double_t p[10];\n Double_t mom=t->GetP();\n const AliExternalTrackParam *in=t->GetInnerParam();\n if (in) mom=in->GetP();\n Double_t dedx=t->GetTPCsignal()\/fMIP;\n Bool_t mismatch=kTRUE, heavy=kTRUE;\n for (Int_t j=0; j fRange*sigma) {\n\tp[j]=TMath::Exp(-0.5*fRange*fRange)\/sigma;\n } else {\n p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)\/(sigma*sigma))\/sigma;\n mismatch=kFALSE;\n }\n\n \/\/ Check for particles heavier than (AliPID::kSPECIES - 1)\n if (dedx < (bethe + fRange*sigma)) heavy=kFALSE;\n\n }\n\n if (mismatch)\n for (Int_t j=0; jSetTPCpid(p);\n\n if (heavy) t->ResetStatus(AliESDtrack::kTPCpid);\n\n }\n return 0;\n}\nImproved Bethe-Bloch formula (Yuri)\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/-----------------------------------------------------------------\n\/\/ Implementation of the TPC PID class\n\/\/ Very naive one... Should be made better by the detector experts...\n\/\/ Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch\n\/\/-----------------------------------------------------------------\n\n#include \"AliTPCpidESD.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDtrack.h\"\n\nClassImp(AliTPCpidESD)\n\n\/\/_________________________________________________________________________\n AliTPCpidESD::AliTPCpidESD(Double_t *param):\n fMIP(0.),\n fRes(0.),\n fRange(0.)\n{\n \/\/\n \/\/ The main constructor\n \/\/\n fMIP=param[0];\n fRes=param[1];\n fRange=param[2];\n}\n\nDouble_t AliTPCpidESD::Bethe(Double_t bg) {\n \/\/\n \/\/ This is the Bethe-Bloch function normalised to 1 at the minimum\n \/\/\n Double_t bg2=bg*bg;\n Double_t beta2 = bg2\/(1.+ bg2);\n\n return 8.62702e-2*(9.14550 - beta2 - TMath::Log(3.51000e-5 + 1.\/bg2))\/beta2;\n}\n\n\/\/_________________________________________________________________________\nInt_t AliTPCpidESD::MakePID(AliESDEvent *event)\n{\n \/\/\n \/\/ This function calculates the \"detector response\" PID probabilities \n \/\/\n Int_t ntrk=event->GetNumberOfTracks();\n for (Int_t i=0; iGetTrack(i);\n if ((t->GetStatus()&AliESDtrack::kTPCin )==0)\n if ((t->GetStatus()&AliESDtrack::kTPCout)==0) continue;\n Double_t p[10];\n Double_t mom=t->GetP();\n const AliExternalTrackParam *in=t->GetInnerParam();\n if (in) mom=in->GetP();\n Double_t dedx=t->GetTPCsignal()\/fMIP;\n Bool_t mismatch=kTRUE, heavy=kTRUE;\n for (Int_t j=0; j fRange*sigma) {\n\tp[j]=TMath::Exp(-0.5*fRange*fRange)\/sigma;\n } else {\n p[j]=TMath::Exp(-0.5*(dedx-bethe)*(dedx-bethe)\/(sigma*sigma))\/sigma;\n mismatch=kFALSE;\n }\n\n \/\/ Check for particles heavier than (AliPID::kSPECIES - 1)\n if (dedx < (bethe + fRange*sigma)) heavy=kFALSE;\n\n }\n\n if (mismatch)\n for (Int_t j=0; jSetTPCpid(p);\n\n if (heavy) t->ResetStatus(AliESDtrack::kTPCpid);\n\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/extensions\/file_manager\/url_util.h\"\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"net\/base\/escape.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace file_manager {\nnamespace util {\nnamespace {\n\n\/\/ Pretty print the JSON escaped in the query string.\nstd::string PrettyPrintEscapedJson(const std::string& query) {\n const std::string json = net::UnescapeURLComponent(\n query, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);\n const base::Value* value = base::JSONReader::Read(json);\n std::string pretty_json;\n base::JSONWriter::WriteWithOptions(value,\n base::JSONWriter::OPTIONS_PRETTY_PRINT,\n &pretty_json);\n return pretty_json;\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerBaseUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\",\n GetFileManagerBaseUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/main.html\",\n GetFileManagerMainPageUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrlWithParams_NoFileTypes) {\n const GURL url = GetFileManagerMainPageUrlWithParams(\n ui::SelectFileDialog::SELECT_OPEN_FILE,\n base::UTF8ToUTF16(\"some title\"),\n base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n NULL, \/\/ No file types\n 0, \/\/ Hence no file type index.\n FILE_PATH_LITERAL(\"txt\"));\n EXPECT_EQ(\"chrome-extension\", url.scheme());\n EXPECT_EQ(\"hhaomjibdihmijegdhdafkllkbggdgoj\", url.host());\n EXPECT_EQ(\"\/main.html\", url.path());\n \/\/ Confirm that \"%20\" is used instead of \"+\" in the query.\n EXPECT_TRUE(url.query().find(\"+\") == std::string::npos);\n EXPECT_TRUE(url.query().find(\"%20\") != std::string::npos);\n \/\/ The escaped query is hard to read. Pretty print the escaped JSON.\n EXPECT_EQ(\"{\\n\"\n \" \\\"defaultExtension\\\": \\\"txt\\\",\\n\"\n \" \\\"defaultPath\\\": \\\"foo.txt\\\",\\n\"\n \" \\\"shouldReturnLocalPath\\\": true,\\n\"\n \" \\\"title\\\": \\\"some title\\\",\\n\"\n \" \\\"type\\\": \\\"open-file\\\"\\n\"\n \"}\\n\",\n PrettyPrintEscapedJson(url.query()));\n}\n\nTEST(FileManagerUrlUtilTest,\n GetFileManagerMainPageUrlWithParams_WithFileTypes) {\n \/\/ Create a FileTypeInfo which looks like:\n \/\/ extensions: [[\"htm\", \"html\"], [\"txt\"]]\n \/\/ descriptions: [\"HTML\", \"TEXT\"]\n ui::SelectFileDialog::FileTypeInfo file_types;\n file_types.extensions.push_back(std::vector());\n file_types.extensions[0].push_back(FILE_PATH_LITERAL(\"htm\"));\n file_types.extensions[0].push_back(FILE_PATH_LITERAL(\"html\"));\n file_types.extensions.push_back(std::vector());\n file_types.extensions[1].push_back(FILE_PATH_LITERAL(\"txt\"));\n file_types.extension_description_overrides.push_back(\n base::UTF8ToUTF16(\"HTML\"));\n file_types.extension_description_overrides.push_back(\n base::UTF8ToUTF16(\"TEXT\"));\n \/\/ \"shouldReturnLocalPath\" will be false if drive is supported.\n file_types.support_drive = true;\n\n const GURL url = GetFileManagerMainPageUrlWithParams(\n ui::SelectFileDialog::SELECT_OPEN_FILE,\n base::UTF8ToUTF16(\"some title\"),\n base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n &file_types,\n 1, \/\/ The file type index is 1-based.\n FILE_PATH_LITERAL(\"txt\"));\n EXPECT_EQ(\"chrome-extension\", url.scheme());\n EXPECT_EQ(\"hhaomjibdihmijegdhdafkllkbggdgoj\", url.host());\n EXPECT_EQ(\"\/main.html\", url.path());\n \/\/ Confirm that \"%20\" is used instead of \"+\" in the query.\n EXPECT_TRUE(url.query().find(\"+\") == std::string::npos);\n EXPECT_TRUE(url.query().find(\"%20\") != std::string::npos);\n \/\/ The escaped query is hard to read. Pretty print the escaped JSON.\n EXPECT_EQ(\"{\\n\"\n \" \\\"defaultExtension\\\": \\\"txt\\\",\\n\"\n \" \\\"defaultPath\\\": \\\"foo.txt\\\",\\n\"\n \" \\\"includeAllFiles\\\": false,\\n\"\n \" \\\"shouldReturnLocalPath\\\": false,\\n\"\n \" \\\"title\\\": \\\"some title\\\",\\n\"\n \" \\\"type\\\": \\\"open-file\\\",\\n\"\n \" \\\"typeList\\\": [ {\\n\"\n \" \\\"description\\\": \\\"HTML\\\",\\n\"\n \" \\\"extensions\\\": [ \\\"htm\\\", \\\"html\\\" ],\\n\"\n \" \\\"selected\\\": true\\n\"\n \" }, {\\n\"\n \" \\\"description\\\": \\\"TEXT\\\",\\n\"\n \" \\\"extensions\\\": [ \\\"txt\\\" ],\\n\"\n \" \\\"selected\\\": false\\n\"\n \" } ]\\n\"\n \"}\\n\",\n PrettyPrintEscapedJson(url.query()));\n}\n\nTEST(FileManagerUrlUtilTest, GetMediaPlayerUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"mediaplayer.html\",\n GetMediaPlayerUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetActionChoiceUrl_RegularMode) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"action_choice.html#\/foo.txt\",\n GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n false).spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetActionChoiceUrl_AdvancedMode) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"action_choice.html?advanced-mode#\/foo.txt\",\n GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n true).spec());\n}\n\n} \/\/ namespace\n} \/\/ namespace util\n} \/\/ namespace file_manager\nfile_manager: Fix memory leak in FileManagerUrlUtilTest\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/extensions\/file_manager\/url_util.h\"\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/json\/json_writer.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"net\/base\/escape.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace file_manager {\nnamespace util {\nnamespace {\n\n\/\/ Pretty print the JSON escaped in the query string.\nstd::string PrettyPrintEscapedJson(const std::string& query) {\n const std::string json = net::UnescapeURLComponent(\n query, net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);\n scoped_ptr value(base::JSONReader::Read(json));\n std::string pretty_json;\n base::JSONWriter::WriteWithOptions(value.get(),\n base::JSONWriter::OPTIONS_PRETTY_PRINT,\n &pretty_json);\n return pretty_json;\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerBaseUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\",\n GetFileManagerBaseUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/main.html\",\n GetFileManagerMainPageUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetFileManagerMainPageUrlWithParams_NoFileTypes) {\n const GURL url = GetFileManagerMainPageUrlWithParams(\n ui::SelectFileDialog::SELECT_OPEN_FILE,\n base::UTF8ToUTF16(\"some title\"),\n base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n NULL, \/\/ No file types\n 0, \/\/ Hence no file type index.\n FILE_PATH_LITERAL(\"txt\"));\n EXPECT_EQ(\"chrome-extension\", url.scheme());\n EXPECT_EQ(\"hhaomjibdihmijegdhdafkllkbggdgoj\", url.host());\n EXPECT_EQ(\"\/main.html\", url.path());\n \/\/ Confirm that \"%20\" is used instead of \"+\" in the query.\n EXPECT_TRUE(url.query().find(\"+\") == std::string::npos);\n EXPECT_TRUE(url.query().find(\"%20\") != std::string::npos);\n \/\/ The escaped query is hard to read. Pretty print the escaped JSON.\n EXPECT_EQ(\"{\\n\"\n \" \\\"defaultExtension\\\": \\\"txt\\\",\\n\"\n \" \\\"defaultPath\\\": \\\"foo.txt\\\",\\n\"\n \" \\\"shouldReturnLocalPath\\\": true,\\n\"\n \" \\\"title\\\": \\\"some title\\\",\\n\"\n \" \\\"type\\\": \\\"open-file\\\"\\n\"\n \"}\\n\",\n PrettyPrintEscapedJson(url.query()));\n}\n\nTEST(FileManagerUrlUtilTest,\n GetFileManagerMainPageUrlWithParams_WithFileTypes) {\n \/\/ Create a FileTypeInfo which looks like:\n \/\/ extensions: [[\"htm\", \"html\"], [\"txt\"]]\n \/\/ descriptions: [\"HTML\", \"TEXT\"]\n ui::SelectFileDialog::FileTypeInfo file_types;\n file_types.extensions.push_back(std::vector());\n file_types.extensions[0].push_back(FILE_PATH_LITERAL(\"htm\"));\n file_types.extensions[0].push_back(FILE_PATH_LITERAL(\"html\"));\n file_types.extensions.push_back(std::vector());\n file_types.extensions[1].push_back(FILE_PATH_LITERAL(\"txt\"));\n file_types.extension_description_overrides.push_back(\n base::UTF8ToUTF16(\"HTML\"));\n file_types.extension_description_overrides.push_back(\n base::UTF8ToUTF16(\"TEXT\"));\n \/\/ \"shouldReturnLocalPath\" will be false if drive is supported.\n file_types.support_drive = true;\n\n const GURL url = GetFileManagerMainPageUrlWithParams(\n ui::SelectFileDialog::SELECT_OPEN_FILE,\n base::UTF8ToUTF16(\"some title\"),\n base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n &file_types,\n 1, \/\/ The file type index is 1-based.\n FILE_PATH_LITERAL(\"txt\"));\n EXPECT_EQ(\"chrome-extension\", url.scheme());\n EXPECT_EQ(\"hhaomjibdihmijegdhdafkllkbggdgoj\", url.host());\n EXPECT_EQ(\"\/main.html\", url.path());\n \/\/ Confirm that \"%20\" is used instead of \"+\" in the query.\n EXPECT_TRUE(url.query().find(\"+\") == std::string::npos);\n EXPECT_TRUE(url.query().find(\"%20\") != std::string::npos);\n \/\/ The escaped query is hard to read. Pretty print the escaped JSON.\n EXPECT_EQ(\"{\\n\"\n \" \\\"defaultExtension\\\": \\\"txt\\\",\\n\"\n \" \\\"defaultPath\\\": \\\"foo.txt\\\",\\n\"\n \" \\\"includeAllFiles\\\": false,\\n\"\n \" \\\"shouldReturnLocalPath\\\": false,\\n\"\n \" \\\"title\\\": \\\"some title\\\",\\n\"\n \" \\\"type\\\": \\\"open-file\\\",\\n\"\n \" \\\"typeList\\\": [ {\\n\"\n \" \\\"description\\\": \\\"HTML\\\",\\n\"\n \" \\\"extensions\\\": [ \\\"htm\\\", \\\"html\\\" ],\\n\"\n \" \\\"selected\\\": true\\n\"\n \" }, {\\n\"\n \" \\\"description\\\": \\\"TEXT\\\",\\n\"\n \" \\\"extensions\\\": [ \\\"txt\\\" ],\\n\"\n \" \\\"selected\\\": false\\n\"\n \" } ]\\n\"\n \"}\\n\",\n PrettyPrintEscapedJson(url.query()));\n}\n\nTEST(FileManagerUrlUtilTest, GetMediaPlayerUrl) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"mediaplayer.html\",\n GetMediaPlayerUrl().spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetActionChoiceUrl_RegularMode) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"action_choice.html#\/foo.txt\",\n GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n false).spec());\n}\n\nTEST(FileManagerUrlUtilTest, GetActionChoiceUrl_AdvancedMode) {\n EXPECT_EQ(\"chrome-extension:\/\/hhaomjibdihmijegdhdafkllkbggdgoj\/\"\n \"action_choice.html?advanced-mode#\/foo.txt\",\n GetActionChoiceUrl(base::FilePath::FromUTF8Unsafe(\"foo.txt\"),\n true).spec());\n}\n\n} \/\/ namespace\n} \/\/ namespace util\n} \/\/ namespace file_manager\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (c) 2008 Werner Mayer *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include \n#endif\n\n#include \"Workbench.h\"\n#include \n#include \n\n\nusing namespace FemGui;\n\n#if 0 \/\/ needed for Qt's lupdate utility\n qApp->translate(\"Workbench\", \"FEM\");\n qApp->translate(\"Workbench\", \"&FEM\");\n#endif\n\n\/\/\/ @namespace FemGui @class Workbench\nTYPESYSTEM_SOURCE(FemGui::Workbench, Gui::StdWorkbench)\n\nWorkbench::Workbench()\n{\n}\n\nWorkbench::~Workbench()\n{\n}\n\nvoid Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) const\n{\n StdWorkbench::setupContextMenu( recipient, item );\n *item << \"Separator\"\n << \"FEM_MeshClear\"\n << \"FEM_MeshPrintInfo\";\n}\n\nGui::ToolBarItem* Workbench::setupToolBars() const\n{\n Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\n Gui::ToolBarItem* model = new Gui::ToolBarItem(root);\n model->setCommand(\"Model\");\n *model << \"FEM_Analysis\"\n << \"Separator\"\n << \"FEM_MaterialSolid\"\n << \"FEM_MaterialFluid\"\n << \"FEM_MaterialMechanicalNonlinear\"\n << \"FEM_ElementGeometry1D\"\n << \"FEM_ElementRotation1D\"\n << \"FEM_ElementGeometry2D\"\n << \"FEM_ElementFluid1D\";\n\n Gui::ToolBarItem* mech = new Gui::ToolBarItem(root);\n mech->setCommand(\"Mechanical Constraints\");\n *mech << \"FEM_ConstraintFixed\"\n << \"FEM_ConstraintDisplacement\"\n << \"FEM_ConstraintPlaneRotation\"\n << \"FEM_ConstraintContact\"\n << \"FEM_ConstraintTransform\"\n << \"Separator\"\n << \"FEM_ConstraintForce\"\n << \"FEM_ConstraintPressure\"\n << \"FEM_ConstraintSelfWeight\";\n\n Gui::ToolBarItem* thermal = new Gui::ToolBarItem(root);\n thermal->setCommand(\"Thermal Constraints\");\n *thermal << \"FEM_ConstraintInitialTemperature\"\n << \"Separator\"\n << \"FEM_ConstraintTemperature\"\n << \"FEM_ConstraintHeatflux\";\n\n Gui::ToolBarItem* mesh = new Gui::ToolBarItem(root);\n mesh->setCommand(\"Mesh\");\n#ifdef FCWithNetgen\n *mesh << \"FEM_MeshNetgenFromShape\";\n#endif\n *mesh << \"FEM_MeshGmshFromShape\"\n << \"Separator\"\n << \"FEM_MeshBoundaryLayer\"\n << \"FEM_MeshRegion\"\n << \"FEM_MeshGroup\"\n << \"Separator\"\n << \"FEM_FEMMesh2Mesh\";\n\n Gui::ToolBarItem* fluid = new Gui::ToolBarItem(root);\n fluid->setCommand(\"Fluid Constraints\");\n *fluid << \"FEM_ConstraintInitialFlowVelocity\"\n << \"Separator\"\n << \"FEM_ConstraintFluidBoundary\"\n << \"FEM_ConstraintFlowVelocity\";\n\n Gui::ToolBarItem* electrostat = new Gui::ToolBarItem(root);\n electrostat->setCommand(\"Electrostatic Constraints\");\n *electrostat << \"FEM_ConstraintElectrostaticPotential\";\n\n Gui::ToolBarItem* solve = new Gui::ToolBarItem(root);\n solve->setCommand(\"Solve\");\n *solve << \"FEM_SolverCalculixCxxtools\"\n << \"FEM_SolverCalculiX\"\n << \"FEM_SolverElmer\"\n << \"Separator\"\n << \"FEM_EquationHeat\"\n << \"FEM_EquationElasticity\"\n << \"FEM_EquationFluxsolver\"\n << \"FEM_EquationElectrostatic\"\n << \"FEM_EquationFlow\"\n << \"Separator\"\n << \"FEM_SolverControl\"\n << \"FEM_SolverRun\";\n\n Gui::ToolBarItem* results = new Gui::ToolBarItem(root);\n results->setCommand(\"Results\");\n *results << \"FEM_ResultsPurge\"\n << \"FEM_ResultShow\";\n\n#ifdef FC_USE_VTK\n *results << \"Separator\"\n << \"FEM_PostApplyChanges\"\n << \"FEM_PostPipelineFromResult\"\n << \"Separator\"\n << \"FEM_PostCreateClipFilter\"\n << \"FEM_PostCreateScalarClipFilter\"\n << \"FEM_PostCreateCutFilter\"\n << \"FEM_PostCreateWarpVectorFilter\"\n << \"FEM_PostCreateDataAlongLineFilter\"\n << \"FEM_PostCreateLinearizedStressesFilter\"\n << \"FEM_PostCreateDataAtPointFilter\"\n << \"Separator\"\n << \"FEM_PostCreateFunctions\";\n#endif\n\n return root;\n}\n\nGui::MenuItem* Workbench::setupMenuBar() const\n{\n Gui::MenuItem* root = StdWorkbench::setupMenuBar();\n Gui::MenuItem* item = root->findItem(\"&Windows\");\n\n Gui::MenuItem* elec = new Gui::MenuItem;\n elec->setCommand(\"&Electrostatic Constraints\");\n *elec << \"FEM_ConstraintElectrostaticPotential\";\n\n Gui::MenuItem* mech = new Gui::MenuItem;\n mech->setCommand(\"&Mechanical Constraints\");\n *mech << \"FEM_ConstraintFixed\"\n << \"FEM_ConstraintDisplacement\"\n << \"FEM_ConstraintPlaneRotation\"\n << \"FEM_ConstraintContact\"\n << \"FEM_ConstraintTransform\"\n << \"Separator\"\n << \"FEM_ConstraintForce\"\n << \"FEM_ConstraintPressure\"\n << \"FEM_ConstraintSelfWeight\"\n << \"Separator\"\n << \"FEM_ConstraintBearing\"\n << \"FEM_ConstraintGear\"\n << \"FEM_ConstraintPulley\";\n\n Gui::MenuItem* thermal = new Gui::MenuItem;\n thermal->setCommand(\"&Thermal Constraints\");\n *thermal << \"FEM_ConstraintInitialTemperature\"\n << \"Separator\"\n << \"FEM_ConstraintHeatflux\"\n << \"FEM_ConstraintTemperature\"\n << \"FEM_ConstraintBodyHeatSource\";\n\n Gui::MenuItem* fluid = new Gui::MenuItem;\n fluid->setCommand(\"&Fluid Constraints\");\n *fluid << \"FEM_ConstraintInitialFlowVelocity\"\n << \"Separator\"\n << \"FEM_ConstraintFluidBoundary\"\n << \"FEM_ConstraintFlowVelocity\";\n\n Gui::MenuItem* model = new Gui::MenuItem;\n root->insertItem(item, model);\n model->setCommand(\"M&odel\");\n *model << \"FEM_Analysis\"\n << \"Separator\"\n << \"FEM_MaterialSolid\"\n << \"FEM_MaterialFluid\"\n << \"FEM_MaterialMechanicalNonlinear\"\n << \"FEM_ElementGeometry1D\"\n << \"FEM_ElementRotation1D\"\n << \"FEM_ElementGeometry2D\"\n << \"FEM_ElementFluid1D\"\n << \"Separator\"\n << elec\n << fluid\n << mech\n << thermal;\n\n Gui::MenuItem* mesh = new Gui::MenuItem;\n root->insertItem(item, mesh);\n mesh->setCommand(\"M&esh\");\n#ifdef FCWithNetgen\n *mesh << \"FEM_MeshNetgenFromShape\";\n#endif\n *mesh << \"FEM_MeshGmshFromShape\"\n << \"Separator\"\n << \"FEM_MeshBoundaryLayer\"\n << \"FEM_MeshRegion\"\n << \"FEM_MeshGroup\"\n << \"Separator\"\n << \"FEM_CreateNodesSet\"\n << \"FEM_FEMMesh2Mesh\";\n\n Gui::MenuItem* solve = new Gui::MenuItem;\n root->insertItem(item, solve);\n solve->setCommand(\"&Solve\");\n *solve << \"FEM_SolverCalculixCxxtools\"\n << \"FEM_SolverCalculiX\"\n << \"FEM_SolverElmer\"\n << \"FEM_SolverZ88\"\n << \"Separator\"\n << \"FEM_EquationHeat\"\n << \"FEM_EquationElasticity\"\n << \"FEM_EquationElectrostatic\"\n << \"FEM_EquationFluxsolver\"\n << \"FEM_EquationFlow\"\n << \"Separator\"\n << \"FEM_SolverControl\"\n << \"FEM_SolverRun\";\n\n Gui::MenuItem* results = new Gui::MenuItem;\n root->insertItem(item, results);\n results->setCommand(\"&Results\");\n *results << \"FEM_ResultsPurge\"\n << \"FEM_ResultShow\";\n\n#ifdef FC_USE_VTK\n *results << \"Separator\"\n << \"FEM_PostApplyChanges\"\n << \"FEM_PostPipelineFromResult\"\n << \"Separator\"\n << \"FEM_PostCreateClipFilter\"\n << \"FEM_PostCreateScalarClipFilter\"\n << \"FEM_PostCreateCutFilter\"\n << \"FEM_PostCreateWarpVectorFilter\"\n << \"FEM_PostCreateDataAlongLineFilter\"\n << \"FEM_PostCreateLinearizedStressesFilter\"\n << \"FEM_PostCreateDataAtPointFilter\"\n << \"Separator\"\n << \"FEM_PostCreateFunctions\";\n#endif\n\n return root;\n}\nFEM: menue entries, add submenue for materials\/***************************************************************************\n * Copyright (c) 2008 Werner Mayer *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include \n#endif\n\n#include \"Workbench.h\"\n#include \n#include \n\n\nusing namespace FemGui;\n\n#if 0 \/\/ needed for Qt's lupdate utility\n qApp->translate(\"Workbench\", \"FEM\");\n qApp->translate(\"Workbench\", \"&FEM\");\n#endif\n\n\/\/\/ @namespace FemGui @class Workbench\nTYPESYSTEM_SOURCE(FemGui::Workbench, Gui::StdWorkbench)\n\nWorkbench::Workbench()\n{\n}\n\nWorkbench::~Workbench()\n{\n}\n\nvoid Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) const\n{\n StdWorkbench::setupContextMenu( recipient, item );\n *item << \"Separator\"\n << \"FEM_MeshClear\"\n << \"FEM_MeshPrintInfo\";\n}\n\nGui::ToolBarItem* Workbench::setupToolBars() const\n{\n Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\n Gui::ToolBarItem* model = new Gui::ToolBarItem(root);\n model->setCommand(\"Model\");\n *model << \"FEM_Analysis\"\n << \"Separator\"\n << \"FEM_MaterialSolid\"\n << \"FEM_MaterialFluid\"\n << \"FEM_MaterialMechanicalNonlinear\"\n << \"FEM_ElementGeometry1D\"\n << \"FEM_ElementRotation1D\"\n << \"FEM_ElementGeometry2D\"\n << \"FEM_ElementFluid1D\";\n\n Gui::ToolBarItem* mech = new Gui::ToolBarItem(root);\n mech->setCommand(\"Mechanical Constraints\");\n *mech << \"FEM_ConstraintFixed\"\n << \"FEM_ConstraintDisplacement\"\n << \"FEM_ConstraintPlaneRotation\"\n << \"FEM_ConstraintContact\"\n << \"FEM_ConstraintTransform\"\n << \"Separator\"\n << \"FEM_ConstraintForce\"\n << \"FEM_ConstraintPressure\"\n << \"FEM_ConstraintSelfWeight\";\n\n Gui::ToolBarItem* thermal = new Gui::ToolBarItem(root);\n thermal->setCommand(\"Thermal Constraints\");\n *thermal << \"FEM_ConstraintInitialTemperature\"\n << \"Separator\"\n << \"FEM_ConstraintTemperature\"\n << \"FEM_ConstraintHeatflux\";\n\n Gui::ToolBarItem* mesh = new Gui::ToolBarItem(root);\n mesh->setCommand(\"Mesh\");\n#ifdef FCWithNetgen\n *mesh << \"FEM_MeshNetgenFromShape\";\n#endif\n *mesh << \"FEM_MeshGmshFromShape\"\n << \"Separator\"\n << \"FEM_MeshBoundaryLayer\"\n << \"FEM_MeshRegion\"\n << \"FEM_MeshGroup\"\n << \"Separator\"\n << \"FEM_FEMMesh2Mesh\";\n\n Gui::ToolBarItem* fluid = new Gui::ToolBarItem(root);\n fluid->setCommand(\"Fluid Constraints\");\n *fluid << \"FEM_ConstraintInitialFlowVelocity\"\n << \"Separator\"\n << \"FEM_ConstraintFluidBoundary\"\n << \"FEM_ConstraintFlowVelocity\";\n\n Gui::ToolBarItem* electrostat = new Gui::ToolBarItem(root);\n electrostat->setCommand(\"Electrostatic Constraints\");\n *electrostat << \"FEM_ConstraintElectrostaticPotential\";\n\n Gui::ToolBarItem* solve = new Gui::ToolBarItem(root);\n solve->setCommand(\"Solve\");\n *solve << \"FEM_SolverCalculixCxxtools\"\n << \"FEM_SolverCalculiX\"\n << \"FEM_SolverElmer\"\n << \"Separator\"\n << \"FEM_EquationHeat\"\n << \"FEM_EquationElasticity\"\n << \"FEM_EquationFluxsolver\"\n << \"FEM_EquationElectrostatic\"\n << \"FEM_EquationFlow\"\n << \"Separator\"\n << \"FEM_SolverControl\"\n << \"FEM_SolverRun\";\n\n Gui::ToolBarItem* results = new Gui::ToolBarItem(root);\n results->setCommand(\"Results\");\n *results << \"FEM_ResultsPurge\"\n << \"FEM_ResultShow\";\n\n#ifdef FC_USE_VTK\n *results << \"Separator\"\n << \"FEM_PostApplyChanges\"\n << \"FEM_PostPipelineFromResult\"\n << \"Separator\"\n << \"FEM_PostCreateClipFilter\"\n << \"FEM_PostCreateScalarClipFilter\"\n << \"FEM_PostCreateCutFilter\"\n << \"FEM_PostCreateWarpVectorFilter\"\n << \"FEM_PostCreateDataAlongLineFilter\"\n << \"FEM_PostCreateLinearizedStressesFilter\"\n << \"FEM_PostCreateDataAtPointFilter\"\n << \"Separator\"\n << \"FEM_PostCreateFunctions\";\n#endif\n\n return root;\n}\n\nGui::MenuItem* Workbench::setupMenuBar() const\n{\n Gui::MenuItem* root = StdWorkbench::setupMenuBar();\n Gui::MenuItem* item = root->findItem(\"&Windows\");\n\n Gui::MenuItem* material = new Gui::MenuItem;\n material->setCommand(\"Materials\");\n *material << \"FEM_MaterialSolid\"\n << \"FEM_MaterialFluid\"\n << \"FEM_MaterialMechanicalNonlinear\";\n\n Gui::MenuItem* elec = new Gui::MenuItem;\n elec->setCommand(\"&Electrostatic Constraints\");\n *elec << \"FEM_ConstraintElectrostaticPotential\";\n\n Gui::MenuItem* mech = new Gui::MenuItem;\n mech->setCommand(\"&Mechanical Constraints\");\n *mech << \"FEM_ConstraintFixed\"\n << \"FEM_ConstraintDisplacement\"\n << \"FEM_ConstraintPlaneRotation\"\n << \"FEM_ConstraintContact\"\n << \"FEM_ConstraintTransform\"\n << \"Separator\"\n << \"FEM_ConstraintForce\"\n << \"FEM_ConstraintPressure\"\n << \"FEM_ConstraintSelfWeight\"\n << \"Separator\"\n << \"FEM_ConstraintBearing\"\n << \"FEM_ConstraintGear\"\n << \"FEM_ConstraintPulley\";\n\n Gui::MenuItem* thermal = new Gui::MenuItem;\n thermal->setCommand(\"&Thermal Constraints\");\n *thermal << \"FEM_ConstraintInitialTemperature\"\n << \"Separator\"\n << \"FEM_ConstraintHeatflux\"\n << \"FEM_ConstraintTemperature\"\n << \"FEM_ConstraintBodyHeatSource\";\n\n Gui::MenuItem* fluid = new Gui::MenuItem;\n fluid->setCommand(\"&Fluid Constraints\");\n *fluid << \"FEM_ConstraintInitialFlowVelocity\"\n << \"Separator\"\n << \"FEM_ConstraintFluidBoundary\"\n << \"FEM_ConstraintFlowVelocity\";\n\n Gui::MenuItem* model = new Gui::MenuItem;\n root->insertItem(item, model);\n model->setCommand(\"M&odel\");\n *model << \"FEM_Analysis\"\n << \"Separator\"\n << material\n << \"Separator\"\n << \"FEM_ElementGeometry1D\"\n << \"FEM_ElementRotation1D\"\n << \"FEM_ElementGeometry2D\"\n << \"FEM_ElementFluid1D\"\n << \"Separator\"\n << elec\n << fluid\n << mech\n << thermal;\n\n Gui::MenuItem* mesh = new Gui::MenuItem;\n root->insertItem(item, mesh);\n mesh->setCommand(\"M&esh\");\n#ifdef FCWithNetgen\n *mesh << \"FEM_MeshNetgenFromShape\";\n#endif\n *mesh << \"FEM_MeshGmshFromShape\"\n << \"Separator\"\n << \"FEM_MeshBoundaryLayer\"\n << \"FEM_MeshRegion\"\n << \"FEM_MeshGroup\"\n << \"Separator\"\n << \"FEM_CreateNodesSet\"\n << \"FEM_FEMMesh2Mesh\";\n\n Gui::MenuItem* solve = new Gui::MenuItem;\n root->insertItem(item, solve);\n solve->setCommand(\"&Solve\");\n *solve << \"FEM_SolverCalculixCxxtools\"\n << \"FEM_SolverCalculiX\"\n << \"FEM_SolverElmer\"\n << \"FEM_SolverZ88\"\n << \"Separator\"\n << \"FEM_EquationHeat\"\n << \"FEM_EquationElasticity\"\n << \"FEM_EquationElectrostatic\"\n << \"FEM_EquationFluxsolver\"\n << \"FEM_EquationFlow\"\n << \"Separator\"\n << \"FEM_SolverControl\"\n << \"FEM_SolverRun\";\n\n Gui::MenuItem* results = new Gui::MenuItem;\n root->insertItem(item, results);\n results->setCommand(\"&Results\");\n *results << \"FEM_ResultsPurge\"\n << \"FEM_ResultShow\";\n\n#ifdef FC_USE_VTK\n *results << \"Separator\"\n << \"FEM_PostApplyChanges\"\n << \"FEM_PostPipelineFromResult\"\n << \"Separator\"\n << \"FEM_PostCreateClipFilter\"\n << \"FEM_PostCreateScalarClipFilter\"\n << \"FEM_PostCreateCutFilter\"\n << \"FEM_PostCreateWarpVectorFilter\"\n << \"FEM_PostCreateDataAlongLineFilter\"\n << \"FEM_PostCreateLinearizedStressesFilter\"\n << \"FEM_PostCreateDataAtPointFilter\"\n << \"Separator\"\n << \"FEM_PostCreateFunctions\";\n#endif\n\n return root;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"snarkfront.hpp\"\n\nusing namespace snarkfront;\nusing namespace std;\n\nvoid printUsage(const char* exeName) {\n cout << \"usage: \" << exeName\n << \" -p BN128|Edwards\"\n \" -b 256|512\"\n \" -d tree_depth\"\n \" -i leaf_number\"\n << endl;\n\n exit(EXIT_FAILURE);\n}\n\ntemplate \nvoid runTest(const size_t treeDepth,\n const size_t leafNumber)\n{\n BUNDLE bundle(treeDepth);\n\n while (! bundle.isFull()) {\n const typename BUNDLE::DigType leaf{bundle.treeSize()};\n\n bundle.addLeaf(\n leaf,\n leafNumber == bundle.treeSize());\n }\n\n if (leafNumber >= bundle.treeSize()) {\n cout << \"leaf number \" << leafNumber\n << \" is larger than \" << bundle.treeSize()\n << endl;\n\n exit(EXIT_FAILURE);\n }\n\n const auto& leaf = bundle.authLeaf().front();\n const auto& authPath = bundle.authPath().front();\n\n cout << \"leaf \" << leafNumber << \" child bits \";\n for (int i = authPath.childBits().size() - 1; i >= 0; --i) {\n cout << authPath.childBits()[i];\n }\n cout << endl;\n\n cout << \"root path\" << endl;\n for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {\n cout << \"[\" << i << \"] \"\n << asciiHex(authPath.rootPath()[i], true) << endl;\n }\n\n cout << \"siblings\" << endl;\n for (int i = authPath.siblings().size() - 1; i >= 0; --i) {\n cout << \"[\" << i << \"] \"\n << asciiHex(authPath.siblings()[i], true) << endl;\n }\n\n typename ZK_PATH::DigType rt;\n bless(rt, authPath.rootHash());\n\n end_input();\n\n typename ZK_PATH::DigType zkLeaf;\n bless(zkLeaf, leaf);\n\n ZK_PATH zkAuthPath(authPath);\n zkAuthPath.updatePath(zkLeaf);\n\n assert_true(rt == zkAuthPath.rootHash());\n\n cout << \"variable count \" << variable_count() << endl;\n}\n\ntemplate \nbool runTest(const string& shaBits,\n const size_t treeDepth,\n const size_t leafNumber)\n{\n typedef typename PAIRING::Fr FR;\n\n if (nameSHA256(shaBits)) {\n runTest, \/\/ count could be size_t\n zk::MerkleAuthPath_SHA256>(\n treeDepth,\n leafNumber);\n\n } else if (nameSHA512(shaBits)) {\n runTest, \/\/ count could be size_t\n zk::MerkleAuthPath_SHA512>(\n treeDepth,\n leafNumber);\n }\n\n GenericProgressBar progress1(cerr), progress2(cerr, 50);\n\n cerr << \"generate key pair\";\n const auto key = keypair(progress2);\n cerr << endl;\n\n const auto in = input();\n\n cerr << \"generate proof\";\n const auto p = proof(key, progress2);\n cerr << endl;\n\n cerr << \"verify proof \";\n const bool proofOK = verify(key, in, p, progress1);\n cerr << endl;\n\n return proofOK;\n}\n\nint main(int argc, char *argv[])\n{\n Getopt cmdLine(argc, argv, \"pb\", \"di\", \"\");\n if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);\n\n const auto\n pairing = cmdLine.getString('p'),\n shaBits = cmdLine.getString('b');\n\n const auto\n treeDepth = cmdLine.getNumber('d'),\n leafNumber = cmdLine.getNumber('i');\n\n if (!validPairingName(pairing) ||\n !(nameSHA256(shaBits) || nameSHA512(shaBits)) ||\n -1 == treeDepth ||\n -1 == leafNumber)\n printUsage(argv[0]);\n\n bool result;\n\n if (pairingBN128(pairing)) {\n \/\/ Barreto-Naehrig 128 bits\n init_BN128();\n result = runTest(shaBits, treeDepth, leafNumber);\n\n } else if (pairingEdwards(pairing)) {\n \/\/ Edwards 80 bits\n init_Edwards();\n result = runTest(shaBits, treeDepth, leafNumber);\n }\n\n cout << \"proof verification \" << (result ? \"OK\" : \"FAIL\") << endl;\n\n exit(EXIT_SUCCESS);\n}\nreturn EXIT_SUCCESS in main()#include \n#include \n#include \n#include \n#include \n#include \n#include \"snarkfront.hpp\"\n\nusing namespace snarkfront;\nusing namespace std;\n\nvoid printUsage(const char* exeName) {\n cout << \"usage: \" << exeName\n << \" -p BN128|Edwards\"\n \" -b 256|512\"\n \" -d tree_depth\"\n \" -i leaf_number\"\n << endl;\n\n exit(EXIT_FAILURE);\n}\n\ntemplate \nvoid runTest(const size_t treeDepth,\n const size_t leafNumber)\n{\n BUNDLE bundle(treeDepth);\n\n while (! bundle.isFull()) {\n const typename BUNDLE::DigType leaf{bundle.treeSize()};\n\n bundle.addLeaf(\n leaf,\n leafNumber == bundle.treeSize());\n }\n\n if (leafNumber >= bundle.treeSize()) {\n cout << \"leaf number \" << leafNumber\n << \" is larger than \" << bundle.treeSize()\n << endl;\n\n exit(EXIT_FAILURE);\n }\n\n const auto& leaf = bundle.authLeaf().front();\n const auto& authPath = bundle.authPath().front();\n\n cout << \"leaf \" << leafNumber << \" child bits \";\n for (int i = authPath.childBits().size() - 1; i >= 0; --i) {\n cout << authPath.childBits()[i];\n }\n cout << endl;\n\n cout << \"root path\" << endl;\n for (int i = authPath.rootPath().size() - 1; i >= 0; --i) {\n cout << \"[\" << i << \"] \"\n << asciiHex(authPath.rootPath()[i], true) << endl;\n }\n\n cout << \"siblings\" << endl;\n for (int i = authPath.siblings().size() - 1; i >= 0; --i) {\n cout << \"[\" << i << \"] \"\n << asciiHex(authPath.siblings()[i], true) << endl;\n }\n\n typename ZK_PATH::DigType rt;\n bless(rt, authPath.rootHash());\n\n end_input();\n\n typename ZK_PATH::DigType zkLeaf;\n bless(zkLeaf, leaf);\n\n ZK_PATH zkAuthPath(authPath);\n zkAuthPath.updatePath(zkLeaf);\n\n assert_true(rt == zkAuthPath.rootHash());\n\n cout << \"variable count \" << variable_count() << endl;\n}\n\ntemplate \nbool runTest(const string& shaBits,\n const size_t treeDepth,\n const size_t leafNumber)\n{\n typedef typename PAIRING::Fr FR;\n\n if (nameSHA256(shaBits)) {\n runTest, \/\/ count could be size_t\n zk::MerkleAuthPath_SHA256>(\n treeDepth,\n leafNumber);\n\n } else if (nameSHA512(shaBits)) {\n runTest, \/\/ count could be size_t\n zk::MerkleAuthPath_SHA512>(\n treeDepth,\n leafNumber);\n }\n\n GenericProgressBar progress1(cerr), progress2(cerr, 50);\n\n cerr << \"generate key pair\";\n const auto key = keypair(progress2);\n cerr << endl;\n\n const auto in = input();\n\n cerr << \"generate proof\";\n const auto p = proof(key, progress2);\n cerr << endl;\n\n cerr << \"verify proof \";\n const bool proofOK = verify(key, in, p, progress1);\n cerr << endl;\n\n return proofOK;\n}\n\nint main(int argc, char *argv[])\n{\n Getopt cmdLine(argc, argv, \"pb\", \"di\", \"\");\n if (!cmdLine || cmdLine.empty()) printUsage(argv[0]);\n\n const auto\n pairing = cmdLine.getString('p'),\n shaBits = cmdLine.getString('b');\n\n const auto\n treeDepth = cmdLine.getNumber('d'),\n leafNumber = cmdLine.getNumber('i');\n\n if (!validPairingName(pairing) ||\n !(nameSHA256(shaBits) || nameSHA512(shaBits)) ||\n -1 == treeDepth ||\n -1 == leafNumber)\n printUsage(argv[0]);\n\n bool result;\n\n if (pairingBN128(pairing)) {\n \/\/ Barreto-Naehrig 128 bits\n init_BN128();\n result = runTest(shaBits, treeDepth, leafNumber);\n\n } else if (pairingEdwards(pairing)) {\n \/\/ Edwards 80 bits\n init_Edwards();\n result = runTest(shaBits, treeDepth, leafNumber);\n }\n\n cout << \"proof verification \" << (result ? \"OK\" : \"FAIL\") << endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/TODO: Utilisation des UBOs\n\nNzLight::NzLight(nzLightType type) :\nm_type(type),\nm_color(NzColor::White),\nm_boundingVolumeUpdated(false),\nm_ambientFactor((type == nzLightType_Directional) ? 0.2f : 0.f),\nm_attenuation(0.9f),\nm_diffuseFactor(1.f),\nm_innerAngle(15.f),\nm_outerAngle(45.f),\nm_radius(5.f)\n{\n}\n\nNzLight::NzLight(const NzLight& light) :\nNzSceneNode(light),\nm_type(light.m_type),\nm_boundingVolume(light.m_boundingVolume),\nm_color(light.m_color),\nm_boundingVolumeUpdated(light.m_boundingVolumeUpdated),\nm_ambientFactor(light.m_ambientFactor),\nm_attenuation(light.m_attenuation),\nm_diffuseFactor(light.m_diffuseFactor),\nm_innerAngle(light.m_innerAngle),\nm_outerAngle(light.m_outerAngle),\nm_radius(light.m_radius)\n{\n}\n\nvoid NzLight::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const\n{\n\trenderQueue->AddLight(this);\n}\n\nvoid NzLight::Enable(const NzShaderProgram* program, unsigned int lightUnit) const\n{\n\t\/*\n\tstruct Light\n\t{\n\t\tint type;\n\t\tvec4 color;\n\t\tvec2 factors;\n\n\t\tvec4 parameters1;\n\t\tvec4 parameters2;\n\t\tvec2 parameters3;\n\t};\n\n\tDirectional\n\t-P1: vec3 direction\n\n\tPoint\n\t-P1: vec3 position + float attenuation\n\t-P2: float invRadius\n\n\tSpot\n\t-P1: vec3 position + float attenuation\n\t-P2: vec3 direction + float invRadius\n\t-P3: float cosInnerAngle + float cosOuterAngle\n\t*\/\n\n\t\/\/\/TODO: Optimiser\n\tint typeLocation = program->GetUniformLocation(\"Lights[0].type\");\n\tint colorLocation = program->GetUniformLocation(\"Lights[0].color\");\n\tint factorsLocation = program->GetUniformLocation(\"Lights[0].factors\");\n\tint parameters1Location = program->GetUniformLocation(\"Lights[0].parameters1\");\n\tint parameters2Location = program->GetUniformLocation(\"Lights[0].parameters2\");\n\tint parameters3Location = program->GetUniformLocation(\"Lights[0].parameters3\");\n\n\tif (lightUnit > 0)\n\t{\n\t\tint type2Location = program->GetUniformLocation(\"Lights[1].type\");\n\t\tint offset = lightUnit * (type2Location - typeLocation); \/\/ type2Location - typeLocation donne la taille de la structure\n\n\t\t\/\/ On applique cet offset\n\t\ttypeLocation += offset;\n\t\tcolorLocation += offset;\n\t\tfactorsLocation += offset;\n\t\tparameters1Location += offset;\n\t\tparameters2Location += offset;\n\t\tparameters3Location += offset;\n\t}\n\n\tprogram->SendInteger(typeLocation, m_type);\n\tprogram->SendColor(colorLocation, m_color);\n\tprogram->SendVector(factorsLocation, NzVector2f(m_ambientFactor, m_diffuseFactor));\n\n\tif (!m_derivedUpdated)\n\t\tUpdateDerived();\n\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedRotation * NzVector3f::Forward()));\n\t\t\tbreak;\n\n\t\tcase nzLightType_Point:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));\n\t\t\tprogram->SendVector(parameters2Location, NzVector4f(1.f\/m_radius, 0.f, 0.f, 0.f));\n\t\t\tbreak;\n\n\t\tcase nzLightType_Spot:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));\n\t\t\tprogram->SendVector(parameters2Location, NzVector4f(m_derivedRotation * NzVector3f::Forward(), 1.f\/m_radius));\n\t\t\tprogram->SendVector(parameters3Location, NzVector2f(std::cos(NzDegreeToRadian(m_innerAngle)), std::cos(NzDegreeToRadian(m_outerAngle))));\n\t\t\tbreak;\n\t}\n}\n\nfloat NzLight::GetAmbientFactor() const\n{\n\treturn m_ambientFactor;\n}\n\nfloat NzLight::GetAttenuation() const\n{\n\treturn m_attenuation;\n}\n\nconst NzBoundingVolumef& NzLight::GetBoundingVolume() const\n{\n\tif (!m_boundingVolumeUpdated)\n\t\tUpdateBoundingVolume();\n\n\treturn m_boundingVolume;\n}\n\nNzColor NzLight::GetColor() const\n{\n\treturn m_color;\n}\n\nfloat NzLight::GetDiffuseFactor() const\n{\n\treturn m_diffuseFactor;\n}\n\nfloat NzLight::GetInnerAngle() const\n{\n\treturn m_innerAngle;\n}\n\nnzLightType NzLight::GetLightType() const\n{\n\treturn m_type;\n}\n\nfloat NzLight::GetOuterAngle() const\n{\n\treturn m_outerAngle;\n}\n\nfloat NzLight::GetRadius() const\n{\n\treturn m_radius;\n}\n\nnzSceneNodeType NzLight::GetSceneNodeType() const\n{\n\treturn nzSceneNodeType_Light;\n}\n\nbool NzLight::IsDrawable() const\n{\n\treturn true;\n}\n\nvoid NzLight::SetAmbientFactor(float factor)\n{\n\tm_ambientFactor = factor;\n}\n\nvoid NzLight::SetAttenuation(float attenuation)\n{\n\tm_attenuation = attenuation;\n}\n\nvoid NzLight::SetColor(const NzColor& color)\n{\n\tm_color = color;\n}\n\nvoid NzLight::SetDiffuseFactor(float factor)\n{\n\tm_diffuseFactor = factor;\n}\n\nvoid NzLight::SetInnerAngle(float innerAngle)\n{\n\tm_innerAngle = innerAngle;\n}\n\nvoid NzLight::SetLightType(nzLightType type)\n{\n\tm_type = type;\n}\n\nvoid NzLight::SetOuterAngle(float outerAngle)\n{\n\tm_outerAngle = outerAngle;\n\n\tm_boundingVolume.MakeNull();\n\tm_boundingVolumeUpdated = false;\n}\n\nvoid NzLight::SetRadius(float radius)\n{\n\tm_radius = radius;\n\n\tm_boundingVolume.MakeNull();\n\tm_boundingVolumeUpdated = false;\n}\n\nNzLight& NzLight::operator=(const NzLight& light)\n{\n\tNzSceneNode::operator=(light);\n\n\tm_ambientFactor = light.m_ambientFactor;\n\tm_attenuation = light.m_attenuation;\n\tm_boundingVolume = light.m_boundingVolume;\n\tm_boundingVolumeUpdated = light.m_boundingVolumeUpdated;\n\tm_color = light.m_color;\n\tm_diffuseFactor = light.m_diffuseFactor;\n\tm_innerAngle = light.m_innerAngle;\n\tm_outerAngle = light.m_outerAngle;\n\tm_radius = light.m_radius;\n\tm_type = light.m_type;\n\n\treturn *this;\n}\n\nvoid NzLight::Disable(const NzShaderProgram* program, unsigned int lightUnit)\n{\n\t\/\/\/TODO: Optimiser\n\tprogram->SendInteger(program->GetUniformLocation(\"Lights[\" + NzString::Number(lightUnit) + \"].type\"), -1);\n}\n\nbool NzLight::FrustumCull(const NzFrustumf& frustum)\n{\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\treturn true; \/\/ Toujours visible\n\n\t\tcase nzLightType_Point:\n\t\t\tif (!m_derivedUpdated)\n\t\t\t\tUpdateDerived();\n\n\t\t\t\/\/ Un test sphérique est bien plus rapide et précis que celui de la bounding box\n\t\t\treturn frustum.Contains(NzSpheref(m_derivedPosition, m_radius));\n\n\t\tcase nzLightType_Spot:\n\t\t\tif (!m_boundingVolumeUpdated)\n\t\t\t\tUpdateBoundingVolume();\n\n\t\t\treturn frustum.Contains(m_boundingVolume);\n\t}\n\n\tNazaraError(\"Invalid light type (0x\" + NzString::Number(m_type, 16) + ')');\n\treturn false;\n}\n\nvoid NzLight::Invalidate()\n{\n\tNzSceneNode::Invalidate();\n\n\tm_boundingVolumeUpdated = false;\n}\n\nvoid NzLight::Register()\n{\n}\n\nvoid NzLight::Unregister()\n{\n}\n\nvoid NzLight::UpdateBoundingVolume() const\n{\n\tif (m_boundingVolume.IsNull())\n\t{\n\t\tswitch (m_type)\n\t\t{\n\t\t\tcase nzLightType_Directional:\n\t\t\t\tm_boundingVolume.MakeInfinite();\n\t\t\t\tm_boundingVolumeUpdated = true;\n\t\t\t\treturn; \/\/ Rien d'autre à faire\n\n\t\t\tcase nzLightType_Point:\n\t\t\t{\n\t\t\t\tNzVector3f radius(m_radius);\n\t\t\t\tm_boundingVolume.Set(-radius, radius);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase nzLightType_Spot:\n\t\t\t{\n\t\t\t\t\/\/ On forme une boite sur l'origine\n\t\t\t\tNzBoxf box(NzVector3f::Zero());\n\n\t\t\t\t\/\/ On calcule le reste des points\n\t\t\t\tfloat height = m_radius;\n\t\t\t\tNzVector3f base(NzVector3f::Forward()*height);\n\n\t\t\t\t\/\/ Il nous faut maintenant le rayon du cercle projeté à cette distance\n\t\t\t\t\/\/ Tangente = Opposé\/Adjaçent <=> Opposé = Adjaçent*Tangente\n\t\t\t\tfloat radius = height*std::tan(NzDegreeToRadian(m_outerAngle));\n\t\t\t\tNzVector3f lExtend = NzVector3f::Left()*radius;\n\t\t\t\tNzVector3f uExtend = NzVector3f::Up()*radius;\n\n\t\t\t\t\/\/ Et on ajoute ensuite les quatres extrémités de la pyramide\n\t\t\t\tbox.ExtendTo(base + lExtend + uExtend);\n\t\t\t\tbox.ExtendTo(base + lExtend - uExtend);\n\t\t\t\tbox.ExtendTo(base - lExtend + uExtend);\n\t\t\t\tbox.ExtendTo(base - lExtend - uExtend);\n\n\t\t\t\tm_boundingVolume.Set(box);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\tbreak;\n\n\t\tcase nzLightType_Point:\n\t\t\tif (!m_derivedUpdated)\n\t\t\t\tUpdateDerived();\n\n\t\t\tm_boundingVolume.Update(NzMatrix4f::Translate(m_derivedPosition)); \/\/ Notre BoundingBox ne changera que selon la position\n\t\t\tbreak;\n\n\t\tcase nzLightType_Spot:\n\t\t\tif (!m_transformMatrixUpdated)\n\t\t\t\tUpdateTransformMatrix();\n\n\t\t\tm_boundingVolume.Update(m_transformMatrix);\n\t\t\tbreak;\n\t}\n\n\tm_boundingVolumeUpdated = true;\n}\nFixed SpotLight bounding volume computation\/\/ Copyright (C) 2013 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/TODO: Utilisation des UBOs\n\nNzLight::NzLight(nzLightType type) :\nm_type(type),\nm_color(NzColor::White),\nm_boundingVolumeUpdated(false),\nm_ambientFactor((type == nzLightType_Directional) ? 0.2f : 0.f),\nm_attenuation(0.9f),\nm_diffuseFactor(1.f),\nm_innerAngle(15.f),\nm_outerAngle(45.f),\nm_radius(5.f)\n{\n}\n\nNzLight::NzLight(const NzLight& light) :\nNzSceneNode(light),\nm_type(light.m_type),\nm_boundingVolume(light.m_boundingVolume),\nm_color(light.m_color),\nm_boundingVolumeUpdated(light.m_boundingVolumeUpdated),\nm_ambientFactor(light.m_ambientFactor),\nm_attenuation(light.m_attenuation),\nm_diffuseFactor(light.m_diffuseFactor),\nm_innerAngle(light.m_innerAngle),\nm_outerAngle(light.m_outerAngle),\nm_radius(light.m_radius)\n{\n}\n\nvoid NzLight::AddToRenderQueue(NzAbstractRenderQueue* renderQueue) const\n{\n\trenderQueue->AddLight(this);\n}\n\nvoid NzLight::Enable(const NzShaderProgram* program, unsigned int lightUnit) const\n{\n\t\/*\n\tstruct Light\n\t{\n\t\tint type;\n\t\tvec4 color;\n\t\tvec2 factors;\n\n\t\tvec4 parameters1;\n\t\tvec4 parameters2;\n\t\tvec2 parameters3;\n\t};\n\n\tDirectional\n\t-P1: vec3 direction\n\n\tPoint\n\t-P1: vec3 position + float attenuation\n\t-P2: float invRadius\n\n\tSpot\n\t-P1: vec3 position + float attenuation\n\t-P2: vec3 direction + float invRadius\n\t-P3: float cosInnerAngle + float cosOuterAngle\n\t*\/\n\n\t\/\/\/TODO: Optimiser\n\tint typeLocation = program->GetUniformLocation(\"Lights[0].type\");\n\tint colorLocation = program->GetUniformLocation(\"Lights[0].color\");\n\tint factorsLocation = program->GetUniformLocation(\"Lights[0].factors\");\n\tint parameters1Location = program->GetUniformLocation(\"Lights[0].parameters1\");\n\tint parameters2Location = program->GetUniformLocation(\"Lights[0].parameters2\");\n\tint parameters3Location = program->GetUniformLocation(\"Lights[0].parameters3\");\n\n\tif (lightUnit > 0)\n\t{\n\t\tint type2Location = program->GetUniformLocation(\"Lights[1].type\");\n\t\tint offset = lightUnit * (type2Location - typeLocation); \/\/ type2Location - typeLocation donne la taille de la structure\n\n\t\t\/\/ On applique cet offset\n\t\ttypeLocation += offset;\n\t\tcolorLocation += offset;\n\t\tfactorsLocation += offset;\n\t\tparameters1Location += offset;\n\t\tparameters2Location += offset;\n\t\tparameters3Location += offset;\n\t}\n\n\tprogram->SendInteger(typeLocation, m_type);\n\tprogram->SendColor(colorLocation, m_color);\n\tprogram->SendVector(factorsLocation, NzVector2f(m_ambientFactor, m_diffuseFactor));\n\n\tif (!m_derivedUpdated)\n\t\tUpdateDerived();\n\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedRotation * NzVector3f::Forward()));\n\t\t\tbreak;\n\n\t\tcase nzLightType_Point:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));\n\t\t\tprogram->SendVector(parameters2Location, NzVector4f(1.f\/m_radius, 0.f, 0.f, 0.f));\n\t\t\tbreak;\n\n\t\tcase nzLightType_Spot:\n\t\t\tprogram->SendVector(parameters1Location, NzVector4f(m_derivedPosition, m_attenuation));\n\t\t\tprogram->SendVector(parameters2Location, NzVector4f(m_derivedRotation * NzVector3f::Forward(), 1.f\/m_radius));\n\t\t\tprogram->SendVector(parameters3Location, NzVector2f(std::cos(NzDegreeToRadian(m_innerAngle)), std::cos(NzDegreeToRadian(m_outerAngle))));\n\t\t\tbreak;\n\t}\n}\n\nfloat NzLight::GetAmbientFactor() const\n{\n\treturn m_ambientFactor;\n}\n\nfloat NzLight::GetAttenuation() const\n{\n\treturn m_attenuation;\n}\n\nconst NzBoundingVolumef& NzLight::GetBoundingVolume() const\n{\n\tif (!m_boundingVolumeUpdated)\n\t\tUpdateBoundingVolume();\n\n\treturn m_boundingVolume;\n}\n\nNzColor NzLight::GetColor() const\n{\n\treturn m_color;\n}\n\nfloat NzLight::GetDiffuseFactor() const\n{\n\treturn m_diffuseFactor;\n}\n\nfloat NzLight::GetInnerAngle() const\n{\n\treturn m_innerAngle;\n}\n\nnzLightType NzLight::GetLightType() const\n{\n\treturn m_type;\n}\n\nfloat NzLight::GetOuterAngle() const\n{\n\treturn m_outerAngle;\n}\n\nfloat NzLight::GetRadius() const\n{\n\treturn m_radius;\n}\n\nnzSceneNodeType NzLight::GetSceneNodeType() const\n{\n\treturn nzSceneNodeType_Light;\n}\n\nbool NzLight::IsDrawable() const\n{\n\treturn true;\n}\n\nvoid NzLight::SetAmbientFactor(float factor)\n{\n\tm_ambientFactor = factor;\n}\n\nvoid NzLight::SetAttenuation(float attenuation)\n{\n\tm_attenuation = attenuation;\n}\n\nvoid NzLight::SetColor(const NzColor& color)\n{\n\tm_color = color;\n}\n\nvoid NzLight::SetDiffuseFactor(float factor)\n{\n\tm_diffuseFactor = factor;\n}\n\nvoid NzLight::SetInnerAngle(float innerAngle)\n{\n\tm_innerAngle = innerAngle;\n}\n\nvoid NzLight::SetLightType(nzLightType type)\n{\n\tm_type = type;\n}\n\nvoid NzLight::SetOuterAngle(float outerAngle)\n{\n\tm_outerAngle = outerAngle;\n\n\tm_boundingVolume.MakeNull();\n\tm_boundingVolumeUpdated = false;\n}\n\nvoid NzLight::SetRadius(float radius)\n{\n\tm_radius = radius;\n\n\tm_boundingVolume.MakeNull();\n\tm_boundingVolumeUpdated = false;\n}\n\nNzLight& NzLight::operator=(const NzLight& light)\n{\n\tNzSceneNode::operator=(light);\n\n\tm_ambientFactor = light.m_ambientFactor;\n\tm_attenuation = light.m_attenuation;\n\tm_boundingVolume = light.m_boundingVolume;\n\tm_boundingVolumeUpdated = light.m_boundingVolumeUpdated;\n\tm_color = light.m_color;\n\tm_diffuseFactor = light.m_diffuseFactor;\n\tm_innerAngle = light.m_innerAngle;\n\tm_outerAngle = light.m_outerAngle;\n\tm_radius = light.m_radius;\n\tm_type = light.m_type;\n\n\treturn *this;\n}\n\nvoid NzLight::Disable(const NzShaderProgram* program, unsigned int lightUnit)\n{\n\t\/\/\/TODO: Optimiser\n\tprogram->SendInteger(program->GetUniformLocation(\"Lights[\" + NzString::Number(lightUnit) + \"].type\"), -1);\n}\n\nbool NzLight::FrustumCull(const NzFrustumf& frustum)\n{\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\treturn true; \/\/ Toujours visible\n\n\t\tcase nzLightType_Point:\n\t\t\tif (!m_derivedUpdated)\n\t\t\t\tUpdateDerived();\n\n\t\t\t\/\/ Un test sphérique est bien plus rapide et précis que celui de la bounding box\n\t\t\treturn frustum.Contains(NzSpheref(m_derivedPosition, m_radius));\n\n\t\tcase nzLightType_Spot:\n\t\t\tif (!m_boundingVolumeUpdated)\n\t\t\t\tUpdateBoundingVolume();\n\n\t\t\treturn frustum.Contains(m_boundingVolume);\n\t}\n\n\tNazaraError(\"Invalid light type (0x\" + NzString::Number(m_type, 16) + ')');\n\treturn false;\n}\n\nvoid NzLight::Invalidate()\n{\n\tNzSceneNode::Invalidate();\n\n\tm_boundingVolumeUpdated = false;\n}\n\nvoid NzLight::Register()\n{\n}\n\nvoid NzLight::Unregister()\n{\n}\n\nvoid NzLight::UpdateBoundingVolume() const\n{\n\tif (m_boundingVolume.IsNull())\n\t{\n\t\tswitch (m_type)\n\t\t{\n\t\t\tcase nzLightType_Directional:\n\t\t\t\tm_boundingVolume.MakeInfinite();\n\t\t\t\tm_boundingVolumeUpdated = true;\n\t\t\t\treturn; \/\/ Rien d'autre à faire\n\n\t\t\tcase nzLightType_Point:\n\t\t\t{\n\t\t\t\tNzVector3f radius(m_radius);\n\t\t\t\tm_boundingVolume.Set(-radius, radius);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase nzLightType_Spot:\n\t\t\t{\n\t\t\t\t\/\/ On forme une boite sur l'origine\n\t\t\t\tNzBoxf box(NzVector3f::Zero());\n\n\t\t\t\t\/\/ On calcule le reste des points\n\t\t\t\tNzVector3f base(NzVector3f::Forward()*m_radius);\n\n\t\t\t\t\/\/ Il nous faut maintenant le rayon du cercle projeté à cette distance\n\t\t\t\t\/\/ Tangente = Opposé\/Adjaçent <=> Opposé = Adjaçent*Tangente\n\t\t\t\tfloat radius = m_radius*std::tan(NzDegreeToRadian(m_outerAngle));\n\t\t\t\tNzVector3f lExtend = NzVector3f::Left()*radius;\n\t\t\t\tNzVector3f uExtend = NzVector3f::Up()*radius;\n\n\t\t\t\t\/\/ Et on ajoute ensuite les quatres extrémités de la pyramide\n\t\t\t\tbox.ExtendTo(base + lExtend + uExtend);\n\t\t\t\tbox.ExtendTo(base + lExtend - uExtend);\n\t\t\t\tbox.ExtendTo(base - lExtend + uExtend);\n\t\t\t\tbox.ExtendTo(base - lExtend - uExtend);\n\n\t\t\t\tm_boundingVolume.Set(box);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (m_type)\n\t{\n\t\tcase nzLightType_Directional:\n\t\t\tbreak;\n\n\t\tcase nzLightType_Point:\n\t\t\tif (!m_derivedUpdated)\n\t\t\t\tUpdateDerived();\n\n\t\t\tm_boundingVolume.Update(NzMatrix4f::Translate(m_derivedPosition)); \/\/ Notre BoundingBox ne changera que selon la position\n\t\t\tbreak;\n\n\t\tcase nzLightType_Spot:\n\t\t\tif (!m_derivedUpdated)\n\t\t\t\tUpdateDerived();\n\n\t\t\tm_boundingVolume.Update(NzMatrix4f::Transform(m_derivedPosition, m_derivedRotation));\n\t\t\tbreak;\n\t}\n\n\tm_boundingVolumeUpdated = true;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2014 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct NzSceneImpl\n{\n\tNzSceneImpl(NzScene* scene) :\n\troot(scene)\n\t{\n\t}\n\n\tstd::unique_ptr background;\n\tstd::unique_ptr renderTechnique;\n\tstd::vector updateList;\n\tstd::vector visibleUpdateList;\n\tNzClock updateClock;\n\tNzColor ambientColor = NzColor(25,25,25);\n\tNzSceneRoot root;\n\tNzAbstractViewer* viewer;\n\tbool update;\n\tfloat frameTime;\n\tfloat updateTime;\n\tint renderTechniqueRanking;\n\tunsigned int updatePerSecond = 60;\n};\n\nNzScene::NzScene()\n{\n\tm_impl = new NzSceneImpl(this);\n\tm_impl->background.reset(new NzColorBackground);\n\tm_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(-1, &m_impl->renderTechniqueRanking));\n}\n\nNzScene::~NzScene()\n{\n\tdelete m_impl;\n}\n\nvoid NzScene::AddToVisibilityList(NzUpdatable* object)\n{\n\tm_impl->visibleUpdateList.push_back(object);\n}\n\nvoid NzScene::Cull()\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!m_impl->viewer)\n\t{\n\t\tNazaraError(\"No viewer\");\n\t\treturn;\n\t}\n\t#endif\n\n\tNzAbstractRenderQueue* renderQueue = m_impl->renderTechnique->GetRenderQueue();\n\trenderQueue->Clear(false);\n\n\tm_impl->visibleUpdateList.clear();\n\n\t\/\/ Frustum culling\n\tRecursiveFrustumCull(m_impl->renderTechnique->GetRenderQueue(), m_impl->viewer->GetFrustum(), &m_impl->root);\n\n\t\/\/\/TODO: Occlusion culling\n\n\t\/\/\/TODO: Light culling\n}\n\nvoid NzScene::Draw()\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!m_impl->viewer)\n\t{\n\t\tNazaraError(\"No viewer\");\n\t\treturn;\n\t}\n\t#endif\n\n\tm_impl->viewer->ApplyView();\n\n\ttry\n\t{\n\t\tNzErrorFlags errFlags(nzErrorFlag_ThrowException);\n\t\tm_impl->renderTechnique->Clear(this);\n\t\tm_impl->renderTechnique->Draw(this);\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tNzString oldName = m_impl->renderTechnique->GetName();\n\t\tm_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(m_impl->renderTechniqueRanking-1, &m_impl->renderTechniqueRanking));\n\t\tNazaraError(\"Render technique \\\"\" + oldName + \"\\\" failed, switched to \\\"\" + m_impl->renderTechnique->GetName() + '\"');\n\t\treturn;\n\t}\n}\n\nNzColor NzScene::GetAmbientColor() const\n{\n\treturn m_impl->ambientColor;\n}\n\nNzAbstractBackground* NzScene::GetBackground() const\n{\n\treturn m_impl->background.get();\n}\n\nNzAbstractRenderTechnique* NzScene::GetRenderTechnique() const\n{\n\treturn m_impl->renderTechnique.get();\n}\n\nNzSceneNode& NzScene::GetRoot() const\n{\n\treturn m_impl->root;\n}\n\nNzAbstractViewer* NzScene::GetViewer() const\n{\n\treturn m_impl->viewer;\n}\n\nfloat NzScene::GetUpdateTime() const\n{\n\treturn m_impl->updateTime;\n}\n\nunsigned int NzScene::GetUpdatePerSecond() const\n{\n\treturn m_impl->updatePerSecond;\n}\n\nvoid NzScene::RegisterForUpdate(NzUpdatable* object)\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!object)\n\t{\n\t\tNazaraError(\"Invalid object\");\n\t\treturn;\n\t}\n\t#endif\n\n\tm_impl->updateList.push_back(object);\n}\n\nvoid NzScene::SetAmbientColor(const NzColor& color)\n{\n\tm_impl->ambientColor = color;\n}\n\nvoid NzScene::SetBackground(NzAbstractBackground* background)\n{\n\tm_impl->background.reset(background);\n}\n\nvoid NzScene::SetRenderTechnique(NzAbstractRenderTechnique* renderTechnique)\n{\n\tm_impl->renderTechnique.reset(renderTechnique);\n}\n\nvoid NzScene::SetViewer(NzAbstractViewer* viewer)\n{\n\tm_impl->viewer = viewer;\n}\n\nvoid NzScene::SetViewer(NzAbstractViewer& viewer)\n{\n\tSetViewer(&viewer);\n}\n\nvoid NzScene::SetUpdatePerSecond(unsigned int updatePerSecond)\n{\n\tm_impl->updatePerSecond = updatePerSecond;\n}\n\nvoid NzScene::UnregisterForUpdate(NzUpdatable* object)\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!object)\n\t{\n\t\tNazaraError(\"Invalid object\");\n\t\treturn;\n\t}\n\t#endif\n\n\tauto it = std::find(m_impl->updateList.begin(), m_impl->updateList.end(), object);\n\tif (it != m_impl->updateList.end())\n\t\tm_impl->updateList.erase(it);\n}\n\nvoid NzScene::Update()\n{\n\tm_impl->update = (m_impl->updatePerSecond == 0 || m_impl->updateClock.GetMilliseconds() > 1000\/m_impl->updatePerSecond);\n\tif (m_impl->update)\n\t{\n\t\tm_impl->updateTime = m_impl->updateClock.GetSeconds();\n\t\tm_impl->updateClock.Restart();\n\n\t\tfor (NzUpdatable* updatable : m_impl->updateList)\n\t\t\t\/\/\/TODO: Multihreading\n\t\t\tupdatable->Update();\n\t}\n}\n\nvoid NzScene::UpdateVisible()\n{\n\tif (m_impl->update)\n\t{\n\t\tfor (NzUpdatable* node : m_impl->visibleUpdateList)\n\t\t\tnode->Update();\n\t}\n}\n\nNzScene::operator const NzSceneNode&() const\n{\n\treturn m_impl->root;\n}\n\nvoid NzScene::RecursiveFrustumCull(NzAbstractRenderQueue* renderQueue, const NzFrustumf& frustum, NzNode* node)\n{\n\tfor (NzNode* child : node->GetChilds())\n\t{\n\t\tif (child->GetNodeType() == nzNodeType_Scene)\n\t\t{\n\t\t\tNzSceneNode* sceneNode = static_cast(child);\n\n\t\t\t\/\/\/TODO: Empêcher le rendu des enfants si le parent est cullé selon un flag\n\t\t\tsceneNode->UpdateVisibility(frustum);\n\t\t\tif (sceneNode->IsVisible())\n\t\t\t\tsceneNode->AddToRenderQueue(renderQueue);\n\t\t}\n\n\t\tif (child->HasChilds())\n\t\t\tRecursiveFrustumCull(renderQueue, frustum, child);\n\t}\n}\nOptimized Scenes configuration\/\/ Copyright (C) 2014 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct NzSceneImpl\n{\n\tNzSceneImpl(NzScene* scene) :\n\troot(scene)\n\t{\n\t}\n\n\tstd::unique_ptr background;\n\tstd::unique_ptr renderTechnique;\n\tstd::vector updateList;\n\tstd::vector visibleUpdateList;\n\tNzClock updateClock;\n\tNzColor ambientColor = NzColor(25,25,25);\n\tNzSceneRoot root;\n\tNzAbstractViewer* viewer = nullptr;\n\tbool update;\n\tfloat frameTime;\n\tfloat updateTime;\n\tint renderTechniqueRanking;\n\tunsigned int updatePerSecond = 60;\n};\n\nNzScene::NzScene()\n{\n\tm_impl = new NzSceneImpl(this);\n}\n\nNzScene::~NzScene()\n{\n\tdelete m_impl;\n}\n\nvoid NzScene::AddToVisibilityList(NzUpdatable* object)\n{\n\tm_impl->visibleUpdateList.push_back(object);\n}\n\nvoid NzScene::Cull()\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!m_impl->viewer)\n\t{\n\t\tNazaraError(\"No viewer\");\n\t\treturn;\n\t}\n\t#endif\n\n\tif (!m_impl->renderTechnique)\n\t\tm_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(-1, &m_impl->renderTechniqueRanking));\n\n\tNzAbstractRenderQueue* renderQueue = m_impl->renderTechnique->GetRenderQueue();\n\trenderQueue->Clear(false);\n\n\tm_impl->visibleUpdateList.clear();\n\n\t\/\/ Frustum culling\n\tRecursiveFrustumCull(renderQueue, m_impl->viewer->GetFrustum(), &m_impl->root);\n\n\t\/\/\/TODO: Occlusion culling\n\n\t\/\/\/TODO: Light culling\n}\n\nvoid NzScene::Draw()\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!m_impl->viewer)\n\t{\n\t\tNazaraError(\"No viewer\");\n\t\treturn;\n\t}\n\t#endif\n\n\tm_impl->viewer->ApplyView();\n\n\tif (!m_impl->background)\n\t\tm_impl->background.reset(new NzColorBackground);\n\n\ttry\n\t{\n\t\tNzErrorFlags errFlags(nzErrorFlag_ThrowException);\n\t\tm_impl->renderTechnique->Clear(this);\n\t\tm_impl->renderTechnique->Draw(this);\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tNzString oldName = m_impl->renderTechnique->GetName();\n\t\tm_impl->renderTechnique.reset(NzRenderTechniques::GetByRanking(m_impl->renderTechniqueRanking-1, &m_impl->renderTechniqueRanking));\n\t\tNazaraError(\"Render technique \\\"\" + oldName + \"\\\" failed, switched to \\\"\" + m_impl->renderTechnique->GetName() + '\"');\n\t\treturn;\n\t}\n}\n\nNzColor NzScene::GetAmbientColor() const\n{\n\treturn m_impl->ambientColor;\n}\n\nNzAbstractBackground* NzScene::GetBackground() const\n{\n\treturn m_impl->background.get();\n}\n\nNzAbstractRenderTechnique* NzScene::GetRenderTechnique() const\n{\n\treturn m_impl->renderTechnique.get();\n}\n\nNzSceneNode& NzScene::GetRoot() const\n{\n\treturn m_impl->root;\n}\n\nNzAbstractViewer* NzScene::GetViewer() const\n{\n\treturn m_impl->viewer;\n}\n\nfloat NzScene::GetUpdateTime() const\n{\n\treturn m_impl->updateTime;\n}\n\nunsigned int NzScene::GetUpdatePerSecond() const\n{\n\treturn m_impl->updatePerSecond;\n}\n\nvoid NzScene::RegisterForUpdate(NzUpdatable* object)\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!object)\n\t{\n\t\tNazaraError(\"Invalid object\");\n\t\treturn;\n\t}\n\t#endif\n\n\tm_impl->updateList.push_back(object);\n}\n\nvoid NzScene::SetAmbientColor(const NzColor& color)\n{\n\tm_impl->ambientColor = color;\n}\n\nvoid NzScene::SetBackground(NzAbstractBackground* background)\n{\n\tm_impl->background.reset(background);\n}\n\nvoid NzScene::SetRenderTechnique(NzAbstractRenderTechnique* renderTechnique)\n{\n\tm_impl->renderTechnique.reset(renderTechnique);\n}\n\nvoid NzScene::SetViewer(NzAbstractViewer* viewer)\n{\n\tm_impl->viewer = viewer;\n}\n\nvoid NzScene::SetViewer(NzAbstractViewer& viewer)\n{\n\tSetViewer(&viewer);\n}\n\nvoid NzScene::SetUpdatePerSecond(unsigned int updatePerSecond)\n{\n\tm_impl->updatePerSecond = updatePerSecond;\n}\n\nvoid NzScene::UnregisterForUpdate(NzUpdatable* object)\n{\n\t#if NAZARA_GRAPHICS_SAFE\n\tif (!object)\n\t{\n\t\tNazaraError(\"Invalid object\");\n\t\treturn;\n\t}\n\t#endif\n\n\tauto it = std::find(m_impl->updateList.begin(), m_impl->updateList.end(), object);\n\tif (it != m_impl->updateList.end())\n\t\tm_impl->updateList.erase(it);\n}\n\nvoid NzScene::Update()\n{\n\tm_impl->update = (m_impl->updatePerSecond == 0 || m_impl->updateClock.GetMilliseconds() > 1000\/m_impl->updatePerSecond);\n\tif (m_impl->update)\n\t{\n\t\tm_impl->updateTime = m_impl->updateClock.GetSeconds();\n\t\tm_impl->updateClock.Restart();\n\n\t\tfor (NzUpdatable* updatable : m_impl->updateList)\n\t\t\t\/\/\/TODO: Multihreading\n\t\t\tupdatable->Update();\n\t}\n}\n\nvoid NzScene::UpdateVisible()\n{\n\tif (m_impl->update)\n\t{\n\t\tfor (NzUpdatable* node : m_impl->visibleUpdateList)\n\t\t\tnode->Update();\n\t}\n}\n\nNzScene::operator const NzSceneNode&() const\n{\n\treturn m_impl->root;\n}\n\nvoid NzScene::RecursiveFrustumCull(NzAbstractRenderQueue* renderQueue, const NzFrustumf& frustum, NzNode* node)\n{\n\tfor (NzNode* child : node->GetChilds())\n\t{\n\t\tif (child->GetNodeType() == nzNodeType_Scene)\n\t\t{\n\t\t\tNzSceneNode* sceneNode = static_cast(child);\n\n\t\t\t\/\/\/TODO: Empêcher le rendu des enfants si le parent est cullé selon un flag\n\t\t\tsceneNode->UpdateVisibility(frustum);\n\t\t\tif (sceneNode->IsVisible())\n\t\t\t\tsceneNode->AddToRenderQueue(renderQueue);\n\t\t}\n\n\t\tif (child->HasChilds())\n\t\t\tRecursiveFrustumCull(renderQueue, frustum, child);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/#define DEBUG\n#include \n\n#include \n#include \n#include \"tests.h\"\n#include \"core\/function_obj.h\"\n#include \"core\/type.h\"\n#include \"core\/type_helper.h\"\n\/* TODO\n\tAdd function inpterpeting and execution DONE\n\tAdd varible interpeting and memmory system. DONE\n\tAdd syntax checking and error reporting PARTERLY\n\tAdd polyargument functions\n Verify that exception system does not intoduce memmory leaks\n\n*\/\n\n\nbool menu(memory::memory& mem,math_func::function_interface& func)\n{\n\tstd::cout << \"PRINT VARIABLES [1]\\nEMPTY VARIABLE TABLE[2]\\nPRINT FUNCS[3]\\nPRINT BUILD INFO[4]\\nPRINT HELP[5]\\nRUN TESTS [6]\\nEXIT [7]\\nMenu> \";\n\tstd::string input;\n\tstd::getline(std::cin, input);\n\tif (input == \"1\")\n\t{\n\t\tstd::vector vars = mem.allVars();\n\t\tfor (unsigned int i = 0; i < vars.size(); i++)\n\t\t{\n\t\t\tstd::cout <<\"Variable \"<toString() << \"\\n\";\n\t\t}\n\t\tif (vars.size() == 0)\n\t\t{\n\t\t\tstd::cout << \"TABLE EMPTY\\n\";\n\t\t}\n\n\t\treturn false;\n\t}\n\telse if (input == \"2\")\n\t{\n\t\tmem.empty();\n\t\treturn false;\n\t}\n\telse if (input == \"3\")\n\t{\n\t\tfunc.display();\n\n\t}\n\telse if (input == \"4\")\n\t{\n\t\tutil::buildInfo();\n\t\treturn false;\n\t}\n\telse if (input == \"5\")\n\t{\n\t\tutil::help();\n\t\treturn false;\n\t}\n\telse if (input == \"6\")\n\t{\n\t\tstd::string exr = \"x=(sqrt(sqrt(5*5)^2)*100)\/5*(sin(PI)^2+cos(PI)^2)\";\n\t\ttest::profileInterpreter(exr);\n\/\/\t\ttest::profileInterpreterVM(exr);\n\t\treturn false;\n\t}\n\telse if (input == \"7\")\n\t{\n\t\t\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"Unkown input, try again\\n\";\n\t\treturn menu(mem,func);\n\t}\n\treturn false;\n}\nint main(int argc, char* argv[])\n{\n \n\n\t\n\t{\n\n#ifndef DEBUG\n\t\terr_redirect err; \/\/remove cerr stream\n#endif\n\t\tstd::cout << std::setprecision(20);\n\t\t\n\t\tinterpreter inter; \n\t\tstd::string expression = \"\";\n\t\n\tmemory::memory mem; \/\/Create memory unit\n\toperators::operators_interface oper;\n\tmath_func::function_interface functions; \/\/Create function unit\n\n\t\/\/init and load operators\n\toper.load(operators::std_operators);\n\tinter.setOperator(&oper);\n\n\t\/\/Init and load memory unit\n\tmem.set(\"PI\", 3.14159f, true, true); \/\/Add constat variable PI with value 3.14\n\tinter.setMemory(&mem); \/\/Assign memory unit to interpreter\n\t\n\t\/\/init and load func unit\n\tfunctions.load(math_func::std_math_trig_func); \/\/ Load std_math_trig_funct into function unit\n\tfunctions.load(math_func::std_math_func);\n\tfunctions.load(math_func::std_math_num_func);\n\tfunctions.load(math_func::mathlibra_data_constructors);\n\tinter.setFunction(&functions);\n\tauto my_manager = plugin::get_platform_specific_manager();\n\tif(my_manager != nullptr)\n\t{\n\ttry\n\t{\tmy_manager->loadPlugins(&functions);\n\n\t}\n\tcatch (exception& e)\n\t{\n\n\t\tstd::cout << \"[\\n Exception: \" << e.what() << \"\\n\";\n\t\tstd::cout << \" Description: \" << e.desc() << \"\\n]\\n\";\n\t}\n\t}\n#if defined(CORAX_VM_EXEC)\n\tCoraxVM::corax_program prgm;\n\tCoraxVM::Corax_program_builder_module prgm_builder(&inter);\n\tCoraxVM::corax_runtime runtime;\n#endif\n\n\n\tbool exit = false;\n std::cout << \"Calculator backend test\\nLukas Rahmn 2016\\n\\nEnter an expression or write menu to open the menu\\n\\n\";\n\tdo\n\t{\n\n\t\tstd::cout << \"> \";\n\t\tstd::getline(std::cin, expression);\n\t\tif (expression == \"menu\")\n\t\t{\n\t\t\texit = menu(mem,functions);\n\t\t}\n\t\telse\n\t\t{\n\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tinter.set(expression.c_str(), expression.size());\n\t\t\t\tinter.interpret();\n#if defined(SYNTAX_TREE_EXEC)\n\t\t\t\t\t\n\t\t\t\t\tmem.set(\"ans\",inter.exec());\n\t\t\t\t\t\n#elif defined(CORAX_VM_EXEC)\n\t\t\t\t\tprgm_builder.create_program(&prgm);\n\t\t\t\t\tmem.set(\"ans\", runtime.run(&prgm));\n#else\n#error \"WARNING, no execution enviroment selected\"\n#endif\n\t\t\t\t\tstd::cout << expression << \" = \" << mem.get(\"ans\")->toString() << std::endl;\n\t\t\t\t\n\n\t\t\t}\n\n\t\t\tcatch (exception& e)\n\t\t\t{\n\n\t\t\t\tstd::cout << \"[\\n Exception: \" << e.what() << \"\\n\";\n\t\t\t\tstd::cout << \" Description: \" << e.desc() << \"\\n]\\n\";\n\t\t\t}\n\t\t\t\/*catch (...)\n\t\t\t{\n\t\t\tstd::cout << \"Catched unknown exception\\n\";\n\t\t\t}*\/\n\t\t}\n\t} while (!exit);\n\t\t}\n\tdebug::check_tree_mem_leak();\t\t\n\treturn 0;\n\n}\nUpdated tester to support sytanx 'menu #number' instead of just menu\/\/#define DEBUG\n#include \n\n#include \n#include \n#include \"tests.h\"\n#include \"core\/function_obj.h\"\n#include \"core\/type.h\"\n#include \"core\/type_helper.h\"\n\/* TODO\n\tAdd function inpterpeting and execution DONE\n\tAdd varible interpeting and memmory system. DONE\n\tAdd syntax checking and error reporting PARTERLY\n\tAdd polyargument functions\n Verify that exception system does not intoduce memmory leaks\n\n*\/\nstd::vector split(std::string str,char delim)\n{\n std::vector strs;\n strs.push_back(std::string());\n for(auto s = str.begin(); s < str.end(); s++)\n {\n if(*s==delim)\n {\n strs.push_back(std::string());\n } \n else\n {\n strs.back().push_back(*s);\n }\n }\n if(strs.back().size() == 0)\n {\n strs.pop_back();\n }\n return strs;\n}\n\nbool menu(memory::memory& mem,math_func::function_interface& func,std::string input)\n{\n if(input.size() == 0)\n {\n\t std::cout << \"PRINT VARIABLES [1]\\nEMPTY VARIABLE TABLE[2]\\nPRINT FUNCS[3]\\nPRINT BUILD INFO[4]\\nPRINT HELP[5]\\nRUN TESTS [6]\\nEXIT [7]\\nMenu> \";\n\t std::getline(std::cin, input);\n }\n\tif (input == \"1\")\n\t{\n\t\tstd::vector vars = mem.allVars();\n\t\tfor (unsigned int i = 0; i < vars.size(); i++)\n\t\t{\n\t\t\tstd::cout <<\"Variable \"<toString() << \"\\n\";\n\t\t}\n\t\tif (vars.size() == 0)\n\t\t{\n\t\t\tstd::cout << \"TABLE EMPTY\\n\";\n\t\t}\n\n\t\treturn false;\n\t}\n\telse if (input == \"2\")\n\t{\n\t\tmem.empty();\n\t\treturn false;\n\t}\n\telse if (input == \"3\")\n\t{\n\t\tfunc.display();\n\n\t}\n\telse if (input == \"4\")\n\t{\n\t\tutil::buildInfo();\n\t\treturn false;\n\t}\n\telse if (input == \"5\")\n\t{\n\t\tutil::help();\n\t\treturn false;\n\t}\n\telse if (input == \"6\")\n\t{\n\t\tstd::string exr = \"x=(sqrt(sqrt(5*5)^2)*100)\/5*(sin(PI)^2+cos(PI)^2)\";\n\t\ttest::profileInterpreter(exr);\n\/\/\t\ttest::profileInterpreterVM(exr);\n\t\treturn false;\n\t}\n\telse if (input == \"7\")\n\t{\n\t\t\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tstd::cout << \"Unkown input, try again\\n\";\n\t\treturn menu(mem,func,\"\");\n\t}\n\treturn false;\n}\nint main(int argc, char* argv[])\n{\n \n\n\t\n\t{\n\n#ifndef DEBUG\n\t\terr_redirect err; \/\/remove cerr stream\n#endif\n\t\tstd::cout << std::setprecision(20);\n\t\t\n\t\tinterpreter inter; \n\t\tstd::string expression = \"\";\n\t\n\tmemory::memory mem; \/\/Create memory unit\n\toperators::operators_interface oper;\n\tmath_func::function_interface functions; \/\/Create function unit\n\n\t\/\/init and load operators\n\toper.load(operators::std_operators);\n\tinter.setOperator(&oper);\n\n\t\/\/Init and load memory unit\n\tmem.set(\"PI\", 3.14159f, true, true); \/\/Add constat variable PI with value 3.14\n\tinter.setMemory(&mem); \/\/Assign memory unit to interpreter\n\t\n\t\/\/init and load func unit\n\tfunctions.load(math_func::std_math_trig_func); \/\/ Load std_math_trig_funct into function unit\n\tfunctions.load(math_func::std_math_func);\n\tfunctions.load(math_func::std_math_num_func);\n\tfunctions.load(math_func::mathlibra_data_constructors);\n\tinter.setFunction(&functions);\n\tauto my_manager = plugin::get_platform_specific_manager();\n\tif(my_manager != nullptr)\n\t{\n\ttry\n\t{\tmy_manager->loadPlugins(&functions);\n\n\t}\n\tcatch (exception& e)\n\t{\n\n\t\tstd::cout << \"[\\n Exception: \" << e.what() << \"\\n\";\n\t\tstd::cout << \" Description: \" << e.desc() << \"\\n]\\n\";\n\t}\n\t}\n#if defined(CORAX_VM_EXEC)\n\tCoraxVM::corax_program prgm;\n\tCoraxVM::Corax_program_builder_module prgm_builder(&inter);\n\tCoraxVM::corax_runtime runtime;\n#endif\n\n\n\tbool exit = false;\n std::cout << \"Calculator backend test\\nLukas Rahmn 2016\\n\\nEnter an expression or write menu to open the menu\\n\\n\";\n\tdo\n\t{\n\n\t\tstd::cout << \"> \";\n\t\tstd::getline(std::cin, expression);\n std::vector arg=split(expression,' ');\n if(arg.size() == 1 && arg[0] == \"menu\") \n\t\t{\n\t\t\texit = menu(mem,functions,\"\");\n\t\t}\n else if(arg.size() == 2 && arg[0] == \"menu\")\n {\n exit = menu(mem,functions,arg[1]); \n }\n\t\telse\n\t\t{\n\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tinter.set(expression.c_str(), expression.size());\n\t\t\t\tinter.interpret();\n#if defined(SYNTAX_TREE_EXEC)\n\t\t\t\t\t\n\t\t\t\t\tmem.set(\"ans\",inter.exec());\n\t\t\t\t\t\n#elif defined(CORAX_VM_EXEC)\n\t\t\t\t\tprgm_builder.create_program(&prgm);\n\t\t\t\t\tmem.set(\"ans\", runtime.run(&prgm));\n#else\n#error \"WARNING, no execution enviroment selected\"\n#endif\n\t\t\t\t\tstd::cout << expression << \" = \" << mem.get(\"ans\")->toString() << std::endl;\n\t\t\t\t\n\n\t\t\t}\n\n\t\t\tcatch (exception& e)\n\t\t\t{\n\n\t\t\t\tstd::cout << \"[\\n Exception: \" << e.what() << \"\\n\";\n\t\t\t\tstd::cout << \" Description: \" << e.desc() << \"\\n]\\n\";\n\t\t\t}\n\t\t\t\/*catch (...)\n\t\t\t{\n\t\t\tstd::cout << \"Catched unknown exception\\n\";\n\t\t\t}*\/\n\t\t}\n\t} while (!exit);\n\t\t}\n\tdebug::check_tree_mem_leak();\t\t\n\treturn 0;\n\n}\n<|endoftext|>"} {"text":"#include \"OpenGLRenderer.hpp\"\n#include \n\nOpenGLRenderer::OpenGLRenderer(Window window) {\n \/\/ Setup glfw window.\n window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n window.setWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n window.setWindowHint(GLFW_RESIZABLE, GL_FALSE);\n std::string windowTitle = \"OpenGL\";\n window.createWindow(windowTitle);\n}\n\nOpenGLRenderer::~OpenGLRenderer() {\n \n}\nSetup GLEW.#include \n#include \"OpenGLRenderer.hpp\"\n\n\nOpenGLRenderer::OpenGLRenderer(Window window) {\n \/\/ Setup glfw window.\n window.setWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n window.setWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n window.setWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n window.setWindowHint(GLFW_RESIZABLE, GL_FALSE);\n std::string windowTitle = \"OpenGL\";\n window.createWindow(windowTitle);\n\n \/\/ Setup GLEW\n glewExperimental = true;\n if(glewInit() != GLEW_OK){\n\n }\n}\n\nOpenGLRenderer::~OpenGLRenderer() {\n \n}\n<|endoftext|>"} {"text":"#include \"CbcConfig.h\"\n\n\/\/ CBC_VERSION_MAJOR defined for Cbc > 2.5\n#ifndef CBC_VERSION_MAJOR\n#include \"OsiCbcSolverInterface_2_5.cpp\"\n#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8\n#include \"OsiCbcSolverInterface_2_8.cpp\"\n#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9\n#include \"OsiCbcSolverInterface_2_9.cpp\"\n#else\n#error \"Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version.\"\n#endif\n\n\n#ifdef __APPLE__\n\/\/ for some reason these symbol doesn't exist in the mac binaries\nvoid _OsiSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb,\n double colub, double obj, std::string name) {\n \/\/ just ignore the name\n addCol(vec, collb, colub, obj);\n}\n#endifannoyed#include \"CbcConfig.h\"\n\n\/\/ CBC_VERSION_MAJOR defined for Cbc > 2.5\n#ifndef CBC_VERSION_MAJOR\n#include \"OsiCbcSolverInterface_2_5.cpp\"\n#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR <= 8\n#include \"OsiCbcSolverInterface_2_8.cpp\"\n#elif CBC_VERSION_MAJOR == 2 && CBC_VERSION_MINOR == 9\n#include \"OsiCbcSolverInterface_2_9.cpp\"\n#else\n#error \"Cyclus cannot yet handle your version of CoinCBC. Please open an issue with your CoinCBC version.\"\n#endif\n\n\n#ifdef __APPLE__\n\/\/ for some reason these symbol doesn't exist in the mac binaries\nvoid OsiCbcSolverInterface::addCol(CoinPackedVectorBase const& vec, double collb,\n double colub, double obj, std::string name) {\n \/\/ just ignore the name\n addCol(vec, collb, colub, obj);\n}\n#endif<|endoftext|>"} {"text":"\/* This file is part of the Vc library.\n\n Copyright (C) 2010 Matthias Kretz \n\n Vc is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation, either version 3 of\n the License, or (at your option) any later version.\n\n Vc is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU 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 Vc. If not, see .\n\n*\/\n\n#include \n#include \"unittest.h\"\n#include \n#include \n\nusing namespace Vc;\n\ntemplate void testNumber(double n)\n{\n typedef typename V1::EntryType T1;\n typedef typename V2::EntryType T2;\n\n const T1 n1 = static_cast(n);\n const T2 n2 = static_cast(n);\n\n V1 v1;\n V2 v2;\n\n v1 = n1;\n v2 = static_cast(v1);\n \/\/std::cerr << v1 << v2 << std::endl;\n COMPARE(static_cast(v2), v1);\n\n v2 = n2;\n v1 = static_cast(v2);\n \/\/std::cerr << v1 << v2 << std::endl;\n COMPARE(static_cast(v1), v2);\n}\n\ntemplate void testCast2()\n{\n typedef typename V1::EntryType T1;\n typedef typename V2::EntryType T2;\n\n const double max = std::min(\n static_cast(std::numeric_limits::max()),\n static_cast(std::numeric_limits::max()));\n const double min = std::max(\n std::numeric_limits::is_integer ?\n static_cast(std::numeric_limits::min()) :\n static_cast(-std::numeric_limits::max()),\n std::numeric_limits::is_integer ?\n static_cast(std::numeric_limits::min()) :\n static_cast(-std::numeric_limits::max())\n );\n\n testNumber(0.);\n testNumber(1.);\n testNumber(2.);\n testNumber(max);\n testNumber(min);\n}\n\ntemplate void testCast()\n{\n testCast2();\n}\n\n#define _CONCAT(A, B) A ## _ ## B\n#define CONCAT(A, B) _CONCAT(A, B)\ntemplate\nstruct T2Helper\n{\n typedef T1 V1;\n typedef T2 V2;\n};\n\nint main(int argc, char **argv)\n{\n initTest(argc, argv);\n\n#define TEST(v1, v2) \\\n typedef T2Helper CONCAT(v1, v2); \\\n runTest(testCast)\n\n TEST(float_v, float_v);\n TEST(float_v, int_v);\n TEST(float_v, uint_v);\n \/\/ needs special handling for different Size:\n \/\/TEST(float_v, double_v);\n \/\/TEST(float_v, short_v);\n \/\/TEST(float_v, ushort_v);\n\n TEST(int_v, float_v);\n TEST(int_v, int_v);\n TEST(int_v, uint_v);\n\n TEST(uint_v, float_v);\n TEST(uint_v, int_v);\n TEST(uint_v, uint_v);\n\n TEST(ushort_v, sfloat_v);\n TEST(ushort_v, short_v);\n TEST(ushort_v, ushort_v);\n\n TEST(short_v, sfloat_v);\n TEST(short_v, short_v);\n TEST(short_v, ushort_v);\n\n TEST(sfloat_v, sfloat_v);\n TEST(sfloat_v, short_v);\n TEST(sfloat_v, ushort_v);\n#undef TEST\n\n return 0;\n}\nmaximum of int loses precision in float and gets rounded to nearest, thus breaking the test. Fix the test\/* This file is part of the Vc library.\n\n Copyright (C) 2010 Matthias Kretz \n\n Vc is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation, either version 3 of\n the License, or (at your option) any later version.\n\n Vc is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU 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 Vc. If not, see .\n\n*\/\n\n#include \n#include \"unittest.h\"\n#include \n#include \n\nusing namespace Vc;\n\ntemplate void testNumber(double n)\n{\n typedef typename V1::EntryType T1;\n typedef typename V2::EntryType T2;\n\n const T1 n1 = static_cast(n);\n const T2 n2 = static_cast(n);\n\n V1 v1;\n V2 v2;\n\n v1 = n1;\n v2 = static_cast(v1);\n \/\/std::cerr << v1 << v2 << std::endl;\n COMPARE(static_cast(v2), v1);\n\n v2 = n2;\n v1 = static_cast(v2);\n \/\/std::cerr << v1 << v2 << std::endl;\n COMPARE(static_cast(v1), v2);\n}\n\ntemplate double maxHelper()\n{\n return static_cast(std::numeric_limits::max());\n}\n\ntemplate<> double maxHelper()\n{\n const int intDigits = std::numeric_limits::digits;\n const int floatDigits = std::numeric_limits::digits;\n return static_cast(((int(1) << floatDigits) - 1) << (intDigits - floatDigits));\n}\n\ntemplate void testCast2()\n{\n typedef typename V1::EntryType T1;\n typedef typename V2::EntryType T2;\n\n const double max = std::min(maxHelper(), maxHelper());\n const double min = std::max(\n std::numeric_limits::is_integer ?\n static_cast(std::numeric_limits::min()) :\n static_cast(-std::numeric_limits::max()),\n std::numeric_limits::is_integer ?\n static_cast(std::numeric_limits::min()) :\n static_cast(-std::numeric_limits::max())\n );\n\n testNumber(0.);\n testNumber(1.);\n testNumber(2.);\n testNumber(max);\n testNumber(min);\n}\n\ntemplate void testCast()\n{\n testCast2();\n}\n\n#define _CONCAT(A, B) A ## _ ## B\n#define CONCAT(A, B) _CONCAT(A, B)\ntemplate\nstruct T2Helper\n{\n typedef T1 V1;\n typedef T2 V2;\n};\n\nint main(int argc, char **argv)\n{\n initTest(argc, argv);\n\n#define TEST(v1, v2) \\\n typedef T2Helper CONCAT(v1, v2); \\\n runTest(testCast)\n\n TEST(float_v, float_v);\n TEST(float_v, int_v);\n TEST(float_v, uint_v);\n \/\/ needs special handling for different Size:\n \/\/TEST(float_v, double_v);\n \/\/TEST(float_v, short_v);\n \/\/TEST(float_v, ushort_v);\n\n TEST(int_v, float_v);\n TEST(int_v, int_v);\n TEST(int_v, uint_v);\n\n TEST(uint_v, float_v);\n TEST(uint_v, int_v);\n TEST(uint_v, uint_v);\n\n TEST(ushort_v, sfloat_v);\n TEST(ushort_v, short_v);\n TEST(ushort_v, ushort_v);\n\n TEST(short_v, sfloat_v);\n TEST(short_v, short_v);\n TEST(short_v, ushort_v);\n\n TEST(sfloat_v, sfloat_v);\n TEST(sfloat_v, short_v);\n TEST(sfloat_v, ushort_v);\n#undef TEST\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nnamespace\n{\n static const unsigned int getUniqueID()\n {\n static unsigned int id = 0;\n\n return ++id;\n }\n}\n\nnamespace uth\n{\n RenderTarget::RenderTarget()\n : m_camera(nullptr),\n m_shader(nullptr),\n m_defaultCamera(),\n m_defaultShader(),\n m_viewport(),\n m_uniqueID(getUniqueID())\n {\n\n }\n\n\n bool RenderTarget::Bind()\n {\n updateUniforms();\n\n static unsigned int lastID = 0;\n\n if (lastID != m_uniqueID)\n return bind();\n else\n return true;\n }\n\n void RenderTarget::Clear(const float r, const float g, const float b, const float a)\n {\n bind();\n\n uth::Graphics::Clear(r, g, b, a);\n }\n\n void RenderTarget::SetCamera(Camera* camera)\n {\n m_camera = camera;\n }\n\n Camera& RenderTarget::GetCamera()\n {\n static bool set = false;\n\n if (!set)\n {\n m_defaultCamera.SetSize(GetSize());\n m_defaultCamera.SetPosition(0, 0);\n set = true;\n }\n\n if (m_camera)\n return *m_camera;\n\n return m_defaultCamera;\n }\n\n void RenderTarget::SetShader(Shader* shader)\n {\n m_shader = shader;\n }\n\n Shader& RenderTarget::GetShader()\n {\n static bool loaded = false;\n\n if (!loaded)\n {\n bool compiled = m_defaultShader.LoadShader(\"Shaders\/vertexshader.vert\", \"Shaders\/fragmentshader.frag\");\n assert(compiled);\n loaded = true;\n }\n\n if (m_shader)\n return *m_shader;\n\n return m_defaultShader;\n }\n\n void RenderTarget::SetViewport(const umath::rectangle& rect)\n {\n m_viewport = rect;\n }\n\n const umath::rectangle& RenderTarget::GetViewport() const\n {\n return m_viewport;\n }\n\n void RenderTarget::updateUniforms()\n {\n if (m_shader)\n {\n m_shader->SetUniform(\"unifProjection\", m_camera ? m_camera->GetProjectionTransform() : m_defaultCamera.GetProjectionTransform());\n\n }\n else\n {\n m_defaultShader.SetUniform(\"unifProjection\", m_camera ? m_camera->GetProjectionTransform() : m_defaultCamera.GetProjectionTransform());\n\n }\n }\n}Update the last used id...#include \n#include \n#include \n#include \n\n\nnamespace\n{\n static const unsigned int getUniqueID()\n {\n static unsigned int id = 0;\n\n return ++id;\n }\n}\n\nnamespace uth\n{\n RenderTarget::RenderTarget()\n : m_camera(nullptr),\n m_shader(nullptr),\n m_defaultCamera(),\n m_defaultShader(),\n m_viewport(),\n m_uniqueID(getUniqueID())\n {\n\n }\n\n\n bool RenderTarget::Bind()\n {\n updateUniforms();\n\n static unsigned int lastID = 0;\n\n if (lastID != m_uniqueID)\n {\n lastID = m_uniqueID;\n return bind();\n }\n else\n return true;\n }\n\n void RenderTarget::Clear(const float r, const float g, const float b, const float a)\n {\n bind();\n\n uth::Graphics::Clear(r, g, b, a);\n }\n\n void RenderTarget::SetCamera(Camera* camera)\n {\n m_camera = camera;\n }\n\n Camera& RenderTarget::GetCamera()\n {\n static bool set = false;\n\n if (!set)\n {\n m_defaultCamera.SetSize(GetSize());\n m_defaultCamera.SetPosition(0, 0);\n set = true;\n }\n\n if (m_camera)\n return *m_camera;\n\n return m_defaultCamera;\n }\n\n void RenderTarget::SetShader(Shader* shader)\n {\n m_shader = shader;\n }\n\n Shader& RenderTarget::GetShader()\n {\n static bool loaded = false;\n\n if (!loaded)\n {\n bool compiled = m_defaultShader.LoadShader(\"Shaders\/vertexshader.vert\", \"Shaders\/fragmentshader.frag\");\n assert(compiled);\n loaded = true;\n }\n\n if (m_shader)\n return *m_shader;\n\n return m_defaultShader;\n }\n\n void RenderTarget::SetViewport(const umath::rectangle& rect)\n {\n m_viewport = rect;\n }\n\n const umath::rectangle& RenderTarget::GetViewport() const\n {\n return m_viewport;\n }\n\n void RenderTarget::updateUniforms()\n {\n if (m_shader)\n {\n m_shader->SetUniform(\"unifProjection\", m_camera ? m_camera->GetProjectionTransform() : m_defaultCamera.GetProjectionTransform());\n\n }\n else\n {\n m_defaultShader.SetUniform(\"unifProjection\", m_camera ? m_camera->GetProjectionTransform() : m_defaultCamera.GetProjectionTransform());\n\n }\n }\n}<|endoftext|>"} {"text":"\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n int evalRPN(vector& tokens) {\n if (tokens.empty()) {\n return 0;\n }\n stack s;\n for (const auto& tok : tokens) {\n if (!is_operator(tok)) {\n s.emplace(tok);\n } else {\n auto y = stoi(s.top());\n s.pop();\n auto x = stoi(s.top());\n s.pop();\n if (tok[0] == '+') {\n x += y;\n } else if (tok[0] == '-') {\n x -= y;\n } else if (tok[0] == '*') {\n x *= y;\n } else {\n x \/= y;\n }\n s.emplace(to_string(x));\n }\n }\n return stoi(s.top());\n }\n\nprivate:\n bool is_operator(const string& op) {\n return op.length() == 1 && string(\"+-*\/\").find(op) != string::npos;\n }\n};\nUpdate evaluate-reverse-polish-notation.cpp\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n int evalRPN(vector& tokens) {\n if (tokens.empty()) {\n return 0;\n }\n stack s;\n for (const auto& tok : tokens) {\n if (!is_operator(tok)) {\n s.emplace(tok);\n } else {\n auto&& y = stoi(s.top());\n s.pop();\n auto&& x = stoi(s.top());\n s.pop();\n if (tok[0] == '+') {\n x += y;\n } else if (tok[0] == '-') {\n x -= y;\n } else if (tok[0] == '*') {\n x *= y;\n } else {\n x \/= y;\n }\n s.emplace(to_string(x));\n }\n }\n return stoi(s.top());\n }\n\nprivate:\n bool is_operator(const string& op) {\n return op.length() == 1 && string(\"+-*\/\").find(op) != string::npos;\n }\n};\n<|endoftext|>"} {"text":"\/\/ Time: O(2^n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n string minAbbreviation(string target, vector& dictionary) {\n vector bits_dict;\n int bit_candidates = 0;\n dict_to_bits_dict(target, dictionary, &bits_dict, &bit_candidates);\n\n int min_len = numeric_limits::max(), min_abbr = 0;\n dfs(target, bit_candidates, 1, 0, &bits_dict, &min_len, &min_abbr);\n\n return bits_to_abbr(target, min_abbr);\n }\n\nprivate:\n void dfs(const string& target, int bit_candidates, int bits, int mask,\n vector *bits_dict, int *min_len, int *min_abbr) {\n\n const auto len = abbr_len(target, mask);\n if (len >= *min_len) {\n return;\n }\n\n bool match = true;\n for (const auto& d : *bits_dict) {\n if ((mask & d) == 0) {\n match = false;\n break;\n }\n }\n if (match) {\n *min_len = len;\n *min_abbr = mask;\n } else {\n for (int b = bits; b < (1 << target.length()); b <<= 1) {\n if (bit_candidates & b) {\n dfs(target, bit_candidates, b << 1, mask | b, bits_dict, min_len, min_abbr);\n }\n }\n }\n }\n\n void dict_to_bits_dict(const string& target, const vector& dictionary,\n vector *bits_dict, int *bit_candidates) {\n for (const auto& w : dictionary) {\n int word = 0;\n if (w.length() != target.length()) {\n continue;\n }\n for (int i = target.length() - 1, bit = 1; i >= 0; --i, bit <<= 1) {\n if (target[i] != w[i]) {\n word |= bit;\n }\n }\n bits_dict->emplace_back(word);\n *bit_candidates |= word;\n }\n }\n\n int abbr_len(const string& target, int mask) {\n int count = 0;\n for (int b = 1; b < (1 << target.length());) {\n if ((mask & b) == 0) {\n for (; b < (1 << target.length()) && (mask & b) == 0; b <<= 1);\n } else {\n b <<= 1;\n }\n ++count;\n }\n return count;\n }\n\n string bits_to_abbr(const string& target, int min_abbr) {\n vector tmp;\n for (int i = target.length() - 1, pre = i; i >= 0; --i, min_abbr >>= 1) {\n if (min_abbr & 1) {\n if (pre - i > 0) {\n tmp.emplace_back(to_string(pre - i));\n }\n pre = i - 1;\n tmp.emplace_back(string(1, target[i]));\n } else if (i == 0) {\n tmp.emplace_back(to_string(pre - i + 1));\n }\n }\n reverse(tmp.begin(), tmp.end());\n\n string abbr;\n for (const auto& s : tmp) {\n abbr += s;\n }\n return abbr;\n }\n};\nUpdate minimum-unique-word-abbreviation.cpp\/\/ Time: O(2^n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n string minAbbreviation(string target, vector& dictionary) {\n vector bits_dict;\n int bit_candidates = 0;\n dict_to_bits_dict(target, dictionary, &bits_dict, &bit_candidates);\n\n int min_len = numeric_limits::max(), min_abbr = 0;\n dfs(target, bit_candidates, 1, 0, &bits_dict, &min_len, &min_abbr);\n\n return bits_to_abbr(target, min_abbr);\n }\n\nprivate:\n void dfs(const string& target, int bit_candidates, int bits, int mask,\n vector *bits_dict, int *min_len, int *min_abbr) {\n\n const auto len = abbr_len(target, mask);\n if (len >= *min_len) {\n return;\n }\n\n bool match = true;\n for (const auto& d : *bits_dict) {\n if ((mask & d) == 0) {\n match = false;\n break;\n }\n }\n if (match) {\n *min_len = len;\n *min_abbr = mask;\n } else {\n for (int b = bits; b < (1 << target.length()); b <<= 1) {\n if (bit_candidates & b) {\n dfs(target, bit_candidates, b << 1, mask | b, bits_dict, min_len, min_abbr);\n }\n }\n }\n }\n\n void dict_to_bits_dict(const string& target, const vector& dictionary,\n vector *bits_dict, int *bit_candidates) {\n for (const auto& w : dictionary) {\n int bits = 0;\n if (w.length() != target.length()) {\n continue;\n }\n for (int i = target.length() - 1, bit = 1; i >= 0; --i, bit <<= 1) {\n if (target[i] != w[i]) {\n bits |= bit;\n }\n }\n bits_dict->emplace_back(bits);\n *bit_candidates |= bits;\n }\n }\n\n int abbr_len(const string& target, int mask) {\n int count = 0;\n for (int b = 1; b < (1 << target.length());) {\n if ((mask & b) == 0) {\n for (; b < (1 << target.length()) && (mask & b) == 0; b <<= 1);\n } else {\n b <<= 1;\n }\n ++count;\n }\n return count;\n }\n\n string bits_to_abbr(const string& target, int min_abbr) {\n vector tmp;\n for (int i = target.length() - 1, pre = i; i >= 0; --i, min_abbr >>= 1) {\n if (min_abbr & 1) {\n if (pre - i > 0) {\n tmp.emplace_back(to_string(pre - i));\n }\n pre = i - 1;\n tmp.emplace_back(string(1, target[i]));\n } else if (i == 0) {\n tmp.emplace_back(to_string(pre - i + 1));\n }\n }\n reverse(tmp.begin(), tmp.end());\n\n string abbr;\n for (const auto& s : tmp) {\n abbr += s;\n }\n return abbr;\n }\n};\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkOpenGLCamera.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \n\n#include \"vtkRenderWindow.h\"\n#include \"vtkOpenGLRenderer.h\"\n#include \"vtkOpenGLCamera.h\"\n#include \n\n\n\/\/ Description:\n\/\/ Implement base class method.\nvoid vtkOpenGLCamera::Render(vtkRenderer *ren)\n{\n float aspect[2];\n float *vport;\n float *bg_color;\n int left,right,bottom,top;\n int *size;\n vtkMatrix4x4 matrix;\n\n \/\/ get the bounds of the window \n size = (ren->GetRenderWindow())->GetSize();\n \n \/\/ find out if we should stereo render\n this->Stereo = (ren->GetRenderWindow())->GetStereoRender();\n vport = ren->GetViewport();\n\n left = (int)(vport[0]*(size[0] -1));\n right = (int)(vport[2]*(size[0] - 1));\n\n \/\/ if were on a stereo renderer draw to special parts of screen\n#ifndef sparc\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n\tif (this->LeftEye) \n\t {\n\t bottom = (int)(532 + (1023-532)*vport[1]);\n\t top = (int)(532 + (1023-532)*vport[3]);\n\t }\n\telse\n\t {\n\t bottom = (int)(491*vport[1]);\n\t top = (int)(491*vport[3]);\n\t }\n\tbreak;\n default:\n\tbottom = (int)(vport[1]*(size[1] -1));\n\ttop = (int)(vport[3]*(size[1] - 1));\n }\n }\n else\n {\n bottom = (int)(vport[1]*(size[1] -1));\n top = (int)(vport[3]*(size[1] - 1));\n }\n#else\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n if (this->LeftEye)\n {\n glDrawBuffer(GL_BACK_LEFT);\n }\n else\n {\n glDrawBuffer(GL_BACK_RIGHT);\n }\n break;\n default:\n break;\n }\n }\n else\n {\n if (ren->GetRenderWindow()->GetDoubleBuffer())\n {\n glDrawBuffer(GL_BACK);\n }\n else\n {\n glDrawBuffer(GL_FRONT);\n }\n }\n \n \/\/ we will set this for all modes on the sparc\n bottom = (int)(vport[1]*(size[1] -1));\n top = (int)(vport[3]*(size[1] - 1));\n#endif\n \n glViewport(left,bottom,(right-left+1),(top-bottom+1));\n glEnable( GL_SCISSOR_TEST );\n glScissor( left, bottom,(right-left+1),(top-bottom+1)); \n \n \/* for stereo we have to fiddle with aspect *\/\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n#ifndef sparc\n\taspect[0] = (float)(right-left+1)\/(float)(2.0*(top-bottom+1));\n#else\n\taspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n#endif\n\taspect[1] = 1.0;\n\tbreak;\n default:\n\taspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n\taspect[1] = 1.0;\n }\n }\n else\n {\n aspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n aspect[1] = 1.0;\n }\n \n ren->SetAspect(aspect);\n\n glMatrixMode( GL_PROJECTION);\n matrix = this->GetPerspectiveTransform(aspect[0]\/aspect[1],-1,1);\n matrix.Transpose();\n \/\/ insert camera view transformation \n glLoadMatrixf(matrix[0]);\n\n \/\/ since lookat modifies the model view matrix do a push \n \/\/ first and set the mmode. This will be undone in the \n \/\/ render action after the actors! message sis sent \n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n\n matrix = this->GetViewTransform();\n matrix.Transpose();\n \n \/\/ insert camera view transformation \n glMultMatrixf(matrix[0]);\n\n \/\/ get the background color\n bg_color = ren->GetBackground();\n\n if ((ren->GetRenderWindow())->GetErase()) \n {\n glClearColor( ((GLclampf)(bg_color[0])),\n\t\t ((GLclampf)(bg_color[1])),\n\t\t ((GLclampf)(bg_color[2])),\n\t\t ((GLclampf)(1.0)) );\n \n glClearDepth( (GLclampd)( 1.0 ) );\n vtkDebugMacro(<< \"glClear\\n\");\n glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n }\n\n \/\/ if we have a stereo renderer, draw other eye next time \n if (this->Stereo)\n {\n if (this->LeftEye) this->LeftEye = 0;\n else this->LeftEye = 1;\n }\n}\nENH: added win32 quad buffer support - ken\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkOpenGLCamera.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \n\n#include \"vtkRenderWindow.h\"\n#include \"vtkOpenGLRenderer.h\"\n#include \"vtkOpenGLCamera.h\"\n#include \n\n\n\/\/ Description:\n\/\/ Implement base class method.\nvoid vtkOpenGLCamera::Render(vtkRenderer *ren)\n{\n float aspect[2];\n float *vport;\n float *bg_color;\n int left,right,bottom,top;\n int *size;\n vtkMatrix4x4 matrix;\n\n \/\/ get the bounds of the window \n size = (ren->GetRenderWindow())->GetSize();\n \n \/\/ find out if we should stereo render\n this->Stereo = (ren->GetRenderWindow())->GetStereoRender();\n vport = ren->GetViewport();\n\n left = (int)(vport[0]*(size[0] -1));\n right = (int)(vport[2]*(size[0] - 1));\n\n \/\/ if were on a stereo renderer draw to special parts of screen\n#if defined(sparc) || defined( _WIN32)\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n if (this->LeftEye)\n {\n glDrawBuffer(GL_BACK_LEFT);\n }\n else\n {\n glDrawBuffer(GL_BACK_RIGHT);\n }\n break;\n default:\n break;\n }\n }\n else\n {\n if (ren->GetRenderWindow()->GetDoubleBuffer())\n {\n glDrawBuffer(GL_BACK);\n }\n else\n {\n glDrawBuffer(GL_FRONT);\n }\n }\n \n \/\/ we will set this for all modes on the sparc\n bottom = (int)(vport[1]*(size[1] -1));\n top = (int)(vport[3]*(size[1] - 1));\n#else\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n\tif (this->LeftEye) \n\t {\n\t bottom = (int)(532 + (1023-532)*vport[1]);\n\t top = (int)(532 + (1023-532)*vport[3]);\n\t }\n\telse\n\t {\n\t bottom = (int)(491*vport[1]);\n\t top = (int)(491*vport[3]);\n\t }\n\tbreak;\n default:\n\tbottom = (int)(vport[1]*(size[1] -1));\n\ttop = (int)(vport[3]*(size[1] - 1));\n }\n }\n else\n {\n bottom = (int)(vport[1]*(size[1] -1));\n top = (int)(vport[3]*(size[1] - 1));\n }\n#endif\n \n glViewport(left,bottom,(right-left+1),(top-bottom+1));\n glEnable( GL_SCISSOR_TEST );\n glScissor( left, bottom,(right-left+1),(top-bottom+1)); \n \n \/* for stereo we have to fiddle with aspect *\/\n if (this->Stereo)\n {\n switch ((ren->GetRenderWindow())->GetStereoType())\n {\n case VTK_STEREO_CRYSTAL_EYES:\n#if defined(sparc) || defined(_WIN32)\n\taspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n#else\n\taspect[0] = (float)(right-left+1)\/(float)(2.0*(top-bottom+1));\n#endif\n\taspect[1] = 1.0;\n\tbreak;\n default:\n\taspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n\taspect[1] = 1.0;\n }\n }\n else\n {\n aspect[0] = (float)(right-left+1)\/(float)(top-bottom+1);\n aspect[1] = 1.0;\n }\n \n ren->SetAspect(aspect);\n\n glMatrixMode( GL_PROJECTION);\n matrix = this->GetPerspectiveTransform(aspect[0]\/aspect[1],-1,1);\n matrix.Transpose();\n \/\/ insert camera view transformation \n glLoadMatrixf(matrix[0]);\n\n \/\/ since lookat modifies the model view matrix do a push \n \/\/ first and set the mmode. This will be undone in the \n \/\/ render action after the actors! message sis sent \n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n\n matrix = this->GetViewTransform();\n matrix.Transpose();\n \n \/\/ insert camera view transformation \n glMultMatrixf(matrix[0]);\n\n \/\/ get the background color\n bg_color = ren->GetBackground();\n\n if ((ren->GetRenderWindow())->GetErase()) \n {\n glClearColor( ((GLclampf)(bg_color[0])),\n\t\t ((GLclampf)(bg_color[1])),\n\t\t ((GLclampf)(bg_color[2])),\n\t\t ((GLclampf)(1.0)) );\n \n glClearDepth( (GLclampd)( 1.0 ) );\n vtkDebugMacro(<< \"glClear\\n\");\n glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));\n }\n\n \/\/ if we have a stereo renderer, draw other eye next time \n if (this->Stereo)\n {\n if (this->LeftEye) this->LeftEye = 0;\n else this->LeftEye = 1;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * MpdAudioSource.cpp\n *\n * Created on: Jul 30, 2015\n * Author: dpayne\n *\/\n\n#include \"Source\/MpdAudioSource.h\"\n#include \"Utils\/Logger.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace\n{\nstatic const int32_t k_read_attempts = 100;\nstatic const int64_t k_read_attempt_sleep_interval_nanosecs =\n 1L * 1000000L; \/\/ 1 millisecond\nstatic struct timespec k_read_attempt_sleep_timespec = {\n 0, k_read_attempt_sleep_interval_nanosecs};\n}\n\nvis::MpdAudioSource::MpdAudioSource(const Settings *const settings)\n : m_settings{settings}\n{\n open_mpd_fifo();\n}\n\nbool vis::MpdAudioSource::open_mpd_fifo()\n{\n m_mpd_fifo_fd = ::open(m_settings->get_mpd_fifo_path().c_str(), O_RDONLY);\n\n if (m_mpd_fifo_fd < 0)\n {\n VIS_LOG(vis::LogLevel::WARN, \"Error reading file: %s\", strerror(errno));\n m_mpd_fifo_fd = -1;\n return false;\n }\n\n auto flags = fcntl(m_mpd_fifo_fd, F_GETFL, 0);\n fcntl(m_mpd_fifo_fd, F_SETFL, flags | O_NONBLOCK);\n\n return true;\n}\n\nbool vis::MpdAudioSource::read(pcm_stereo_sample *buffer,\n const uint32_t buffer_size)\n{\n \/\/ try to re-open the stream if it has been closed\n if (m_mpd_fifo_fd < 0)\n {\n open_mpd_fifo();\n }\n\n size_t buffer_size_bytes =\n static_cast(sizeof(pcm_stereo_sample) * buffer_size);\n size_t bytes_left = buffer_size_bytes;\n\n if (m_mpd_fifo_fd >= 0)\n {\n auto attempts = 0;\n while (bytes_left > 0)\n {\n \/\/ Read buffer\n int64_t bytes_read = ::read(m_mpd_fifo_fd, buffer, bytes_left);\n\n \/\/ No bytes left\n if (bytes_read == 0)\n {\n VIS_LOG(vis::LogLevel::WARN, \"Could not read any bytes\");\n return false;\n }\n \/\/ Error reading file. Since non-blocking is set, it's possible\n \/\/ there's not enough data yet\n else if (bytes_read == -1)\n {\n auto error_code = errno;\n\n \/\/ EAGAIN means data is not ready yet\n if (error_code == EAGAIN)\n {\n\n \/\/ Try up to k_read_attempts before quiting\n if (attempts > k_read_attempts)\n {\n VIS_LOG(vis::LogLevel::WARN,\n \"Could not finish reading \"\n \"buffer, bytes read: %d \"\n \"buffer size: \",\n bytes_read, buffer_size_bytes);\n\n \/\/ zero out buffer\n memset(buffer, 0, buffer_size_bytes);\n ::close(m_mpd_fifo_fd);\n m_mpd_fifo_fd = -1;\n return false;\n }\n\n nanosleep(&k_read_attempt_sleep_timespec, NULL);\n ++attempts;\n }\n else\n {\n VIS_LOG(vis::LogLevel::WARN, \"Error reading file: %d %s\",\n error_code, strerror(error_code));\n }\n }\n \/\/ Bytes were read fine, continue until buffer is full\n else\n {\n bytes_left -= static_cast(bytes_read);\n }\n }\n\n \/\/ Success fully read entire buffer\n return true;\n }\n\n return false;\n}\n\nvis::MpdAudioSource::~MpdAudioSource()\n{\n if (m_mpd_fifo_fd >= 0)\n {\n ::close(m_mpd_fifo_fd);\n }\n}\nFixed build on linux\/*\n * MpdAudioSource.cpp\n *\n * Created on: Jul 30, 2015\n * Author: dpayne\n *\/\n\n#include \"Source\/MpdAudioSource.h\"\n#include \"Utils\/Logger.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _LINUX\n#include \n#endif\n\nnamespace\n{\nstatic const int32_t k_read_attempts = 100;\nstatic const int64_t k_read_attempt_sleep_interval_nanosecs =\n 1L * 1000000L; \/\/ 1 millisecond\nstatic struct timespec k_read_attempt_sleep_timespec = {\n 0, k_read_attempt_sleep_interval_nanosecs};\n}\n\nvis::MpdAudioSource::MpdAudioSource(const Settings *const settings)\n : m_settings{settings}\n{\n open_mpd_fifo();\n}\n\nbool vis::MpdAudioSource::open_mpd_fifo()\n{\n m_mpd_fifo_fd = ::open(m_settings->get_mpd_fifo_path().c_str(), O_RDONLY);\n\n if (m_mpd_fifo_fd < 0)\n {\n VIS_LOG(vis::LogLevel::WARN, \"Error reading file: %s\", strerror(errno));\n m_mpd_fifo_fd = -1;\n return false;\n }\n\n auto flags = fcntl(m_mpd_fifo_fd, F_GETFL, 0);\n fcntl(m_mpd_fifo_fd, F_SETFL, flags | O_NONBLOCK);\n\n return true;\n}\n\nbool vis::MpdAudioSource::read(pcm_stereo_sample *buffer,\n const uint32_t buffer_size)\n{\n \/\/ try to re-open the stream if it has been closed\n if (m_mpd_fifo_fd < 0)\n {\n open_mpd_fifo();\n }\n\n size_t buffer_size_bytes =\n static_cast(sizeof(pcm_stereo_sample) * buffer_size);\n size_t bytes_left = buffer_size_bytes;\n\n if (m_mpd_fifo_fd >= 0)\n {\n auto attempts = 0;\n while (bytes_left > 0)\n {\n \/\/ Read buffer\n int64_t bytes_read = ::read(m_mpd_fifo_fd, buffer, bytes_left);\n\n \/\/ No bytes left\n if (bytes_read == 0)\n {\n VIS_LOG(vis::LogLevel::WARN, \"Could not read any bytes\");\n return false;\n }\n \/\/ Error reading file. Since non-blocking is set, it's possible\n \/\/ there's not enough data yet\n else if (bytes_read == -1)\n {\n auto error_code = errno;\n\n \/\/ EAGAIN means data is not ready yet\n if (error_code == EAGAIN)\n {\n\n \/\/ Try up to k_read_attempts before quiting\n if (attempts > k_read_attempts)\n {\n VIS_LOG(vis::LogLevel::WARN,\n \"Could not finish reading \"\n \"buffer, bytes read: %d \"\n \"buffer size: \",\n bytes_read, buffer_size_bytes);\n\n \/\/ zero out buffer\n memset(buffer, 0, buffer_size_bytes);\n ::close(m_mpd_fifo_fd);\n m_mpd_fifo_fd = -1;\n return false;\n }\n\n nanosleep(&k_read_attempt_sleep_timespec, NULL);\n ++attempts;\n }\n else\n {\n VIS_LOG(vis::LogLevel::WARN, \"Error reading file: %d %s\",\n error_code, strerror(error_code));\n }\n }\n \/\/ Bytes were read fine, continue until buffer is full\n else\n {\n bytes_left -= static_cast(bytes_read);\n }\n }\n\n \/\/ Success fully read entire buffer\n return true;\n }\n\n return false;\n}\n\nvis::MpdAudioSource::~MpdAudioSource()\n{\n if (m_mpd_fifo_fd >= 0)\n {\n ::close(m_mpd_fifo_fd);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __SYSTEMC_CORE_EXT_SC_MODULE_HH__\n#define __SYSTEMC_CORE_EXT_SC_MODULE_HH__\n\n#include \n\n#include \"sc_object.hh\"\n#include \"sc_sensitive.hh\"\n#include \"sc_time.hh\"\n\nnamespace sc_core\n{\n\ntemplate \nclass sc_in;\ntemplate \nclass sc_out;\ntemplate \nclass sc_inout;\ntemplate \nclass sc_signal_in_if;\n\nclass sc_event;\nclass sc_event_and_list;\nclass sc_event_or_list;\nclass sc_module_name;\n\nclass sc_bind_proxy\n{\n public:\n sc_bind_proxy(const sc_interface &interface);\n sc_bind_proxy(const sc_port_base &port);\n};\n\nextern const sc_bind_proxy SC_BIND_PROXY_NIL;\n\nclass sc_module : public sc_object\n{\n public:\n virtual ~sc_module();\n\n virtual const char *kind() const;\n\n void operator () (const sc_bind_proxy &p001,\n const sc_bind_proxy &p002 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p003 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p004 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p005 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p006 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p007 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p008 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p009 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p010 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p011 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p012 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p013 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p014 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p015 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p016 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p017 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p018 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p019 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p020 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p021 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p022 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p023 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p024 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p025 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p026 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p027 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p028 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p029 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p030 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p031 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p032 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p033 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p034 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p035 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p036 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p037 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p038 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p039 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p040 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p041 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p042 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p043 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p044 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p045 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p046 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p047 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p048 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p049 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p050 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p051 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p052 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p053 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p054 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p055 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p056 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p057 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p058 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p059 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p060 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p061 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p062 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p063 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p064 = SC_BIND_PROXY_NIL);\n\n virtual const std::vector &get_child_objects() const;\n virtual const std::vector &get_child_events() const;\n\n protected:\n sc_module(const sc_module_name &);\n sc_module();\n\n void reset_signal_is(const sc_in &, bool);\n void reset_signal_is(const sc_inout &, bool);\n void reset_signal_is(const sc_out &, bool);\n void reset_signal_is(const sc_signal_in_if &, bool);\n\n void async_reset_signal_is(const sc_in &, bool);\n void async_reset_signal_is(const sc_inout &, bool);\n void async_reset_signal_is(const sc_out &, bool);\n void async_reset_signal_is(const sc_signal_in_if &, bool);\n\n sc_sensitive sensitive;\n\n void dont_initialize();\n void set_stack_size(size_t);\n\n void next_trigger();\n void next_trigger(const sc_event &);\n void next_trigger(const sc_event_or_list &);\n void next_trigger(const sc_event_and_list &);\n void next_trigger(const sc_time &);\n void next_trigger(double, sc_time_unit);\n void next_trigger(const sc_time &, const sc_event &);\n void next_trigger(double, sc_time_unit, const sc_event &);\n void next_trigger(const sc_time &, const sc_event_or_list &);\n void next_trigger(double, sc_time_unit, const sc_event_or_list &);\n void next_trigger(const sc_time &, const sc_event_and_list &);\n void next_trigger(double, sc_time_unit, const sc_event_and_list &);\n\n void wait();\n void wait(int);\n void wait(const sc_event &);\n void wait(const sc_event_or_list &);\n void wait(const sc_event_and_list &);\n void wait(const sc_time &);\n void wait(double, sc_time_unit);\n void wait(const sc_time &, const sc_event &);\n void wait(double, sc_time_unit, const sc_event &);\n void wait(const sc_time &, const sc_event_or_list &);\n void wait(double, sc_time_unit, const sc_event_or_list &);\n void wait(const sc_time &, const sc_event_and_list &);\n void wait(double, sc_time_unit, const sc_event_and_list &);\n\n virtual void before_end_of_elaboration() {}\n virtual void end_of_elaboration() {}\n virtual void start_of_simulation() {}\n virtual void end_of_simulation() {}\n\n private:\n \/\/ Disabled\n sc_module(const sc_module &) : sc_object() {};\n sc_module &operator = (const sc_module &) { return *this; }\n};\n\nvoid next_trigger();\nvoid next_trigger(const sc_event &);\nvoid next_trigger(const sc_event_or_list &);\nvoid next_trigger(const sc_event_and_list &);\nvoid next_trigger(const sc_time &);\nvoid next_trigger(double, sc_time_unit);\nvoid next_trigger(const sc_time &, const sc_event &);\nvoid next_trigger(double, sc_time_unit, const sc_event &);\nvoid next_trigger(const sc_time &, const sc_event_or_list &);\nvoid next_trigger(double, sc_time_unit, const sc_event_or_list &);\nvoid next_trigger(const sc_time &, const sc_event_and_list &);\nvoid next_trigger(double, sc_time_unit, const sc_event_and_list &);\n\nvoid wait();\nvoid wait(int);\nvoid wait(const sc_event &);\nvoid wait(const sc_event_or_list &);\nvoid wait(const sc_event_and_list &);\nvoid wait(const sc_time &);\nvoid wait(double, sc_time_unit);\nvoid wait(const sc_time &, const sc_event &);\nvoid wait(double, sc_time_unit, const sc_event &);\nvoid wait(const sc_time &, const sc_event_or_list &);\nvoid wait(double, sc_time_unit, const sc_event_or_list &);\nvoid wait(const sc_time &, const sc_event_and_list &);\nvoid wait(double, sc_time_unit, const sc_event_and_list &);\n\n#define SC_MODULE(name) struct name : ::sc_core::sc_module\n\n#define SC_CTOR(name) \\\n typedef name SC_CURRENT_USER_MODULE; \\\n name(::sc_core::sc_module_name)\n\n#define SC_HAS_PROCESS(name) typedef name SC_CURRENT_USER_MODULE\n\n#define SC_METHOD(name) \/* Implementation defined *\/\n#define SC_THREAD(name) \/* Implementation defined *\/\n#define SC_CTHREAD(name, clk) \/* Implementation defined *\/\n\nconst char *sc_gen_unique_name(const char *);\n\ntypedef sc_module sc_behavior;\ntypedef sc_module sc_channel;\n\nbool sc_start_of_simulation_invoked();\nbool sc_end_of_simulation_invoked();\n\n} \/\/ namespace sc_core\n\n#endif \/\/__SYSTEMC_EXT_CORE_SC_MODULE_HH__\nsystemc: Add the deprecated sc_module::end_module function.\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __SYSTEMC_CORE_EXT_SC_MODULE_HH__\n#define __SYSTEMC_CORE_EXT_SC_MODULE_HH__\n\n#include \n\n#include \"sc_object.hh\"\n#include \"sc_sensitive.hh\"\n#include \"sc_time.hh\"\n\nnamespace sc_core\n{\n\ntemplate \nclass sc_in;\ntemplate \nclass sc_out;\ntemplate \nclass sc_inout;\ntemplate \nclass sc_signal_in_if;\n\nclass sc_event;\nclass sc_event_and_list;\nclass sc_event_or_list;\nclass sc_module_name;\n\nclass sc_bind_proxy\n{\n public:\n sc_bind_proxy(const sc_interface &interface);\n sc_bind_proxy(const sc_port_base &port);\n};\n\nextern const sc_bind_proxy SC_BIND_PROXY_NIL;\n\nclass sc_module : public sc_object\n{\n public:\n virtual ~sc_module();\n\n virtual const char *kind() const;\n\n void operator () (const sc_bind_proxy &p001,\n const sc_bind_proxy &p002 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p003 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p004 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p005 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p006 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p007 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p008 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p009 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p010 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p011 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p012 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p013 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p014 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p015 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p016 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p017 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p018 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p019 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p020 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p021 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p022 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p023 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p024 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p025 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p026 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p027 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p028 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p029 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p030 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p031 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p032 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p033 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p034 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p035 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p036 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p037 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p038 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p039 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p040 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p041 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p042 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p043 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p044 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p045 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p046 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p047 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p048 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p049 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p050 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p051 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p052 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p053 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p054 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p055 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p056 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p057 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p058 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p059 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p060 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p061 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p062 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p063 = SC_BIND_PROXY_NIL,\n const sc_bind_proxy &p064 = SC_BIND_PROXY_NIL);\n\n virtual const std::vector &get_child_objects() const;\n virtual const std::vector &get_child_events() const;\n\n protected:\n sc_module(const sc_module_name &);\n sc_module();\n\n \/* Deprecated, but used in the regression tests. *\/\n void end_module() {}\n\n void reset_signal_is(const sc_in &, bool);\n void reset_signal_is(const sc_inout &, bool);\n void reset_signal_is(const sc_out &, bool);\n void reset_signal_is(const sc_signal_in_if &, bool);\n\n void async_reset_signal_is(const sc_in &, bool);\n void async_reset_signal_is(const sc_inout &, bool);\n void async_reset_signal_is(const sc_out &, bool);\n void async_reset_signal_is(const sc_signal_in_if &, bool);\n\n sc_sensitive sensitive;\n\n void dont_initialize();\n void set_stack_size(size_t);\n\n void next_trigger();\n void next_trigger(const sc_event &);\n void next_trigger(const sc_event_or_list &);\n void next_trigger(const sc_event_and_list &);\n void next_trigger(const sc_time &);\n void next_trigger(double, sc_time_unit);\n void next_trigger(const sc_time &, const sc_event &);\n void next_trigger(double, sc_time_unit, const sc_event &);\n void next_trigger(const sc_time &, const sc_event_or_list &);\n void next_trigger(double, sc_time_unit, const sc_event_or_list &);\n void next_trigger(const sc_time &, const sc_event_and_list &);\n void next_trigger(double, sc_time_unit, const sc_event_and_list &);\n\n void wait();\n void wait(int);\n void wait(const sc_event &);\n void wait(const sc_event_or_list &);\n void wait(const sc_event_and_list &);\n void wait(const sc_time &);\n void wait(double, sc_time_unit);\n void wait(const sc_time &, const sc_event &);\n void wait(double, sc_time_unit, const sc_event &);\n void wait(const sc_time &, const sc_event_or_list &);\n void wait(double, sc_time_unit, const sc_event_or_list &);\n void wait(const sc_time &, const sc_event_and_list &);\n void wait(double, sc_time_unit, const sc_event_and_list &);\n\n virtual void before_end_of_elaboration() {}\n virtual void end_of_elaboration() {}\n virtual void start_of_simulation() {}\n virtual void end_of_simulation() {}\n\n private:\n \/\/ Disabled\n sc_module(const sc_module &) : sc_object() {};\n sc_module &operator = (const sc_module &) { return *this; }\n};\n\nvoid next_trigger();\nvoid next_trigger(const sc_event &);\nvoid next_trigger(const sc_event_or_list &);\nvoid next_trigger(const sc_event_and_list &);\nvoid next_trigger(const sc_time &);\nvoid next_trigger(double, sc_time_unit);\nvoid next_trigger(const sc_time &, const sc_event &);\nvoid next_trigger(double, sc_time_unit, const sc_event &);\nvoid next_trigger(const sc_time &, const sc_event_or_list &);\nvoid next_trigger(double, sc_time_unit, const sc_event_or_list &);\nvoid next_trigger(const sc_time &, const sc_event_and_list &);\nvoid next_trigger(double, sc_time_unit, const sc_event_and_list &);\n\nvoid wait();\nvoid wait(int);\nvoid wait(const sc_event &);\nvoid wait(const sc_event_or_list &);\nvoid wait(const sc_event_and_list &);\nvoid wait(const sc_time &);\nvoid wait(double, sc_time_unit);\nvoid wait(const sc_time &, const sc_event &);\nvoid wait(double, sc_time_unit, const sc_event &);\nvoid wait(const sc_time &, const sc_event_or_list &);\nvoid wait(double, sc_time_unit, const sc_event_or_list &);\nvoid wait(const sc_time &, const sc_event_and_list &);\nvoid wait(double, sc_time_unit, const sc_event_and_list &);\n\n#define SC_MODULE(name) struct name : ::sc_core::sc_module\n\n#define SC_CTOR(name) \\\n typedef name SC_CURRENT_USER_MODULE; \\\n name(::sc_core::sc_module_name)\n\n#define SC_HAS_PROCESS(name) typedef name SC_CURRENT_USER_MODULE\n\n#define SC_METHOD(name) \/* Implementation defined *\/\n#define SC_THREAD(name) \/* Implementation defined *\/\n#define SC_CTHREAD(name, clk) \/* Implementation defined *\/\n\nconst char *sc_gen_unique_name(const char *);\n\ntypedef sc_module sc_behavior;\ntypedef sc_module sc_channel;\n\nbool sc_start_of_simulation_invoked();\nbool sc_end_of_simulation_invoked();\n\n} \/\/ namespace sc_core\n\n#endif \/\/__SYSTEMC_EXT_CORE_SC_MODULE_HH__\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Danni on 09.06.15.\n\/\/\n\n#include \"TweeCompiler.h\"\n#include \"ZAssemblyGenerator.h\"\n#include \"exceptions.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstatic const string PASSAGE_GLOB = \"PASSAGE_PTR\",\n JUMP_TABLE_LABEL = \"JUMP_TABLE_START\",\n JUMP_TABLE_END_LABEL = \"JUMP_TABLE_END\",\n MAIN_ROUTINE = \"main\",\n USER_INPUT = \"USER_INPUT\",\n READ_BEGIN = \"READ_BEGIN\";\n\nstatic const unsigned int ZSCII_NUM_OFFSET = 49;\n\n\/\/#define ZAS_DEBUG\n\nvoid maskString(std::string& string) {\n std::replace( string.begin(), string.end(), ' ', '_');\n}\n\nstring routineNameForPassageName(std::string passageName) {\n stringstream ss;\n maskString(passageName);\n ss << \"R_\" << passageName;\n return ss.str();\n}\n\n\nstring routineNameForPassage(Passage& passage) {\n return routineNameForPassageName(passage.getHead().getName());\n}\n\nstring labelForPassage(Passage& passage) {\n stringstream ss;\n string passageName = passage.getHead().getName();\n maskString(passageName);\n ss << \"L_\" << passageName;\n return ss.str();\n}\n\nvoid TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) {\n ZAssemblyGenerator assgen(out);\n vector passages = tweeFile.getPassages();\n\n {\n int i = 0;\n for (auto passage = passages.begin(); passage != passages.end(); ++passage) {\n passageName2id[passage->getHead().getName()] = i;\n i++;\n }\n }\n\n \/\/ main routine\n {\n \/\/ globals\n assgen.addGlobal(PASSAGE_GLOB)\n .addGlobal(USER_INPUT);\n\n \/\/ call start routine first\n assgen.addRoutine(MAIN_ROUTINE)\n .markStart()\n .call(routineNameForPassageName(\"start\"), PASSAGE_GLOB)\n .addLabel(JUMP_TABLE_LABEL);\n\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n int passageId = passageName2id.at(passage->getHead().getName());\n\n assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage));\n }\n\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n assgen.addLabel(labelForPassage(*passage))\n .call(routineNameForPassage(*passage), PASSAGE_GLOB)\n .jump(JUMP_TABLE_LABEL);\n }\n\n assgen.addLabel(JUMP_TABLE_END_LABEL);\n\n assgen.quit();\n }\n\n \/\/ passage routines\n {\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n const vector>& bodyParts = passage->getBody().getBodyParts();\n\n \/\/ declare passage routine\n assgen.addRoutine(routineNameForPassage(*passage));\n\n assgen.println(string(\"***** \") + passage->getHead().getName() + string(\" *****\"));\n\n \/\/ print passage contents\n for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) {\n BodyPart* bodyPart = it->get();\n if(Text* text = dynamic_cast(bodyPart)) {\n assgen.print(text->getContent());\n } else if (FormattedText * formText = dynamic_cast(bodyPart)) {\n assgen.setTextStyle(formText->isItalic(), formText->isBold(), formText->isUnderlined());\n assgen.print(formText->getContent());\n assgen.setTextStyle(false, false, false);\n } else if (Variable * variable = dynamic_cast(bodyPart)) {\n assgen.variable(variable->getName());\n }\n }\n\n assgen.newline();\n\n vector links;\n \/\/ get links from passage\n for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it)\n {\n BodyPart* bodyPart = it->get();\n if(Link* link = dynamic_cast(bodyPart)) {\n links.push_back(link);\n }\n }\n\n \/\/ present choices to user\n assgen.println(\"Select one of the following options\");\n int i = 1;\n for (auto link = links.begin(); link != links.end(); link++) {\n assgen.println(string(\" \") + to_string(i) + string(\") \") + (*link)->getTarget() );\n i++;\n }\n\n assgen.addLabel(READ_BEGIN);\n\n \/\/ read user input\n assgen.read_char(USER_INPUT);\n\n \/\/ jump to according link selection\n i = 0;\n for (auto link = links.begin(); link != links.end(); link++) {\n string label = string(\"L\") + to_string(i);\n assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label);\n\n i++;\n }\n\n \/\/ no proper selection was made\n assgen.jump(READ_BEGIN);\n\n i = 0;\n for (auto link = links.begin(); link != links.end(); link++) {\n string label = string(\"L\") + to_string(i);\n try {\n int targetPassageId = passageName2id.at((*link)->getTarget());\n assgen.addLabel(label);\n #ifdef ZAS_DEBUG\n assgen.print(string(\"selected \") + to_string(targetPassageId) );\n #endif\n assgen.ret(to_string(targetPassageId));\n } catch (const out_of_range &err) {\n cerr << \"could not find passage for link target \\\"\" << (*link)->getTarget() << \"\\\"\" << endl;\n throw TweeDocumentException();\n }\n i++;\n }\n }\n }\n}\nUpdate TweeCompiler.cpp\/\/\n\/\/ Created by Danni on 09.06.15.\n\/\/\n\n#include \"TweeCompiler.h\"\n#include \"ZAssemblyGenerator.h\"\n#include \"exceptions.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstatic const string PASSAGE_GLOB = \"PASSAGE_PTR\",\n JUMP_TABLE_LABEL = \"JUMP_TABLE_START\",\n JUMP_TABLE_END_LABEL = \"JUMP_TABLE_END\",\n MAIN_ROUTINE = \"main\",\n USER_INPUT = \"USER_INPUT\",\n READ_BEGIN = \"READ_BEGIN\";\n\nstatic const unsigned int ZSCII_NUM_OFFSET = 49;\n\n\/\/#define ZAS_DEBUG\n\nvoid maskString(std::string& string) {\n std::replace( string.begin(), string.end(), ' ', '_');\n}\n\nstring routineNameForPassageName(std::string passageName) {\n stringstream ss;\n maskString(passageName);\n ss << \"R_\" << passageName;\n return ss.str();\n}\n\n\nstring routineNameForPassage(Passage& passage) {\n return routineNameForPassageName(passage.getHead().getName());\n}\n\nstring labelForPassage(Passage& passage) {\n stringstream ss;\n string passageName = passage.getHead().getName();\n maskString(passageName);\n ss << \"L_\" << passageName;\n return ss.str();\n}\n\nvoid TweeCompiler::compile(TweeFile &tweeFile, std::ostream &out) {\n ZAssemblyGenerator assgen(out);\n vector passages = tweeFile.getPassages();\n\n {\n int i = 0;\n for (auto passage = passages.begin(); passage != passages.end(); ++passage) {\n passageName2id[passage->getHead().getName()] = i;\n i++;\n }\n }\n\n \/\/ main routine\n {\n \/\/ globals\n assgen.addGlobal(PASSAGE_GLOB)\n .addGlobal(USER_INPUT);\n\n \/\/ call start routine first\n assgen.addRoutine(MAIN_ROUTINE)\n .markStart()\n .call(routineNameForPassageName(\"start\"), PASSAGE_GLOB)\n .addLabel(JUMP_TABLE_LABEL);\n\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n int passageId = passageName2id.at(passage->getHead().getName());\n\n assgen.jumpEquals(ZAssemblyGenerator::makeArgs({std::to_string(passageId), PASSAGE_GLOB}), labelForPassage(*passage));\n }\n\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n assgen.addLabel(labelForPassage(*passage))\n .call(routineNameForPassage(*passage), PASSAGE_GLOB)\n .jump(JUMP_TABLE_LABEL);\n }\n\n assgen.addLabel(JUMP_TABLE_END_LABEL);\n\n assgen.quit();\n }\n\n \/\/ passage routines\n {\n for(auto passage = passages.begin(); passage != passages.end(); ++passage) {\n const vector>& bodyParts = passage->getBody().getBodyParts();\n\n \/\/ declare passage routine\n assgen.addRoutine(routineNameForPassage(*passage));\n\n assgen.println(string(\"***** \") + passage->getHead().getName() + string(\" *****\"));\n\n \/\/ print passage contents\n for(auto it = bodyParts.begin(); it != bodyParts.end(); it++) {\n BodyPart* bodyPart = it->get();\n if(Text* text = dynamic_cast(bodyPart)) {\n assgen.print(text->getContent());\n } else if(Newline* text = dynamic_cast(bodyPart)) {\n assgen.newline();\n } else if (Variable * variable = dynamic_cast(bodyPart)) {\n assgen.variable(variable->getName());\n }\n }\n\n assgen.newline();\n\n vector links;\n \/\/ get links from passage\n for(auto it = bodyParts.begin(); it != bodyParts.end(); ++it)\n {\n BodyPart* bodyPart = it->get();\n if(Link* link = dynamic_cast(bodyPart)) {\n links.push_back(link);\n }\n }\n\n \/\/ present choices to user\n assgen.println(\"Select one of the following options\");\n int i = 1;\n for (auto link = links.begin(); link != links.end(); link++) {\n assgen.println(string(\" \") + to_string(i) + string(\") \") + (*link)->getTarget() );\n i++;\n }\n\n assgen.addLabel(READ_BEGIN);\n\n \/\/ read user input\n assgen.read_char(USER_INPUT);\n\n \/\/ jump to according link selection\n i = 0;\n for (auto link = links.begin(); link != links.end(); link++) {\n string label = string(\"L\") + to_string(i);\n assgen.jumpEquals(ZAssemblyGenerator::makeArgs({to_string(ZSCII_NUM_OFFSET + i), USER_INPUT}), label);\n\n i++;\n }\n\n \/\/ no proper selection was made\n assgen.jump(READ_BEGIN);\n\n i = 0;\n for (auto link = links.begin(); link != links.end(); link++) {\n string label = string(\"L\") + to_string(i);\n try {\n int targetPassageId = passageName2id.at((*link)->getTarget());\n assgen.addLabel(label);\n #ifdef ZAS_DEBUG\n assgen.print(string(\"selected \") + to_string(targetPassageId) );\n #endif\n assgen.ret(to_string(targetPassageId));\n } catch (const out_of_range &err) {\n cerr << \"could not find passage for link target \\\"\" << (*link)->getTarget() << \"\\\"\" << endl;\n throw TweeDocumentException();\n }\n i++;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/**\n * \\file TransistorClassAFilter.cpp\n *\/\n\n#include \"TransistorClassAFilter.h\"\n\n#include \n\n#include \n#include \n\nnamespace ATK\n{\n template \n class TransistorClassAFilter::TransistorClassAFunction\n {\n const DataType_ Rp;\n const DataType_ Rg1;\n const DataType_ Rg2;\n const DataType_ Ro;\n const DataType_ Rk;\n const DataType_ VBias;\n const DataType_ Cg;\n const DataType_ Co;\n const DataType_ Ck;\n \n const DataType_ Is;\n const DataType_ Vt;\n const DataType_ Br;\n const DataType_ Bf;\n \n DataType ickeq;\n DataType icgeq;\n DataType icoeq;\n \n DataType_ Lb(const std::pair& exp)\n {\n return Is * ((exp.first - 1) \/ Bf + (exp.second - 1) \/ Br);\n }\n \n DataType_ Lb_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * (exp.first \/ Bf + exp.second \/ Br);\n }\n \n DataType_ Lb_Vce(const std::pair& exp)\n {\n return -Is \/ Vt * (exp.second \/ Br);\n }\n \n DataType_ Lc(const std::pair& exp)\n {\n return Is * ((exp.first - exp.second) - (exp.second - 1) \/ Br);\n }\n \n DataType_ Lc_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * ((exp.first - exp.second) - exp.second \/ Br);\n }\n \n DataType_ Lc_Vce(const std::pair& exp)\n {\n return Is \/ Vt * (exp.second + exp.second \/ Br);\n }\n\n public:\n typedef DataType_ DataType;\n typedef Eigen::Matrix Vector;\n typedef Eigen::Matrix Matrix;\n\n std::pair exp_y0;\n\n TransistorClassAFunction(DataType dt, DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Cg, DataType Co, DataType Ck, DataType Is, DataType Vt, DataType Br, DataType Bf, const std::vector& default_output)\n :Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Cg(2 \/ dt * Cg), Co(2 \/ dt * Co), Ck(2 \/ dt * Ck), Is(Is), Vt(Vt), Br(Br), Bf(Bf), ickeq(2 \/ dt * Ck * default_output[1]), icgeq(2 \/ dt * -Cg * default_output[4]), icoeq(-2 \/ dt * Co * default_output[2])\n {\n }\n\n Vector estimate(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)\n {\n Vector y0 = Vector::Zero();\n for(int j = 0; j < 4; ++j)\n {\n y0.data()[j] = output[j][i-1];\n }\n\n return y0;\n }\n \n void update_state(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)\n {\n ickeq = 2 * Ck * output[1][i] - ickeq;\n icgeq = 2 * Cg * (input[0][i] - output[4][i]) - icgeq;\n icoeq = -2 * Co * output[2][i] - icoeq;\n }\n \n std::pair operator()(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output, const Vector& y1)\n {\n std::pair exp_y1 = std::make_pair(std::exp((y1(3) - y1(0)) \/ Vt), std::exp((y1(3) - y1(2)) \/ Vt));\n \n auto Ib = Lb(exp_y1);\n auto Ic = Lc(exp_y1);\n \n auto Ib_Vbe = Lb_Vbe(exp_y1);\n auto Ib_Vbc = Lb_Vce(exp_y1);\n\n auto Ic_Vbe = Lc_Vbe(exp_y1);\n auto Ic_Vbc = Lc_Vce(exp_y1);\n\n auto f1 = Ib + Ic + ickeq - y1(0) * (1\/Rk + Ck);\n auto f2 = icoeq + (y1(1) + y1(2)) \/ Ro + y1(1) * Co;\n auto f3 = Ic + (y1(1) + y1(2)) \/ Ro + (y1(2) - VBias) \/ Rp;\n auto f4 = Ib + icgeq + y1(3) \/ Rg2 + (y1(3) - VBias) \/ Rg1 + (y1(3) - input[0][i]) * Cg;\n \n Vector F(Vector::Zero());\n F << f1,\n f2,\n f3,\n f4;\n\n Matrix M(Matrix::Zero());\n M << -(Ib_Vbe + Ic_Vbe) - (1\/Rk + Ck), 0, -(Ib_Vbc + Ic_Vbc), (Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc),\n 0, 1\/Ro + Co, 1\/Ro, 0,\n -Ic_Vbe, 1\/Ro, -Ic_Vbc + 1\/Ro + 1\/Rp, (Ic_Vbe + Ic_Vbc),\n -Ib_Vbe, 0, -Ib_Vbc, (Ib_Vbc + Ib_Vbe) + 1\/Rg2 + 1\/Rg1 + Cg;\n\n return std::make_pair(F, M);\n }\n\n };\n \n template \n class TransistorClassAInitialFunction\n {\n const DataType_ Rp;\n const DataType_ Rg1;\n const DataType_ Rg2;\n const DataType_ Ro;\n const DataType_ Rk;\n const DataType_ VBias;\n \n const DataType_ Is;\n const DataType_ Vt;\n const DataType_ Br;\n const DataType_ Bf;\n \n DataType_ Lb(const std::pair& exp)\n {\n return Is * ((exp.first - 1) \/ Bf + (exp.second - 1) \/ Br);\n }\n \n DataType_ Lb_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * (exp.first \/ Bf + exp.second \/ Br);\n }\n \n DataType_ Lb_Vce(const std::pair& exp)\n {\n return -Is \/ Vt * (exp.second \/ Br);\n }\n \n DataType_ Lc(const std::pair& exp)\n {\n return Is * ((exp.first - exp.second) - (exp.second - 1) \/ Br);\n }\n \n DataType_ Lc_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * ((exp.first - exp.second) - exp.second \/ Br);\n }\n \n DataType_ Lc_Vce(const std::pair& exp)\n {\n return Is \/ Vt * (exp.second + exp.second \/ Br);\n }\n \n public:\n typedef DataType_ DataType;\n typedef Eigen::Matrix Vector;\n typedef Eigen::Matrix Matrix;\n \n TransistorClassAInitialFunction(DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Is, DataType Vt, DataType Br, DataType Bf)\n :Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Is(Is), Vt(Vt), Br(Br), Bf(Bf)\n {\n }\n \n std::pair operator()(const Vector& y1)\n {\n std::pair exp_y1 = std::make_pair(std::exp((y1(2) - y1(1)) \/ Vt), std::exp((y1(2) - y1(0)) \/ Vt));\n \n auto Ib = Lb(exp_y1);\n auto Ic = Lc(exp_y1);\n \n auto Ib_Vbe = Lb_Vbe(exp_y1);\n auto Ib_Vbc = Lb_Vce(exp_y1);\n \n auto Ic_Vbe = Lc_Vbe(exp_y1);\n auto Ic_Vbc = Lc_Vce(exp_y1);\n \n Vector F(Vector::Zero());\n auto R = 1\/(1\/Rg1 + 1\/Rg2);\n F << y1(0) - VBias + Ic * Rp, y1(1) - (Ib + Ic) * Rk, Ib * R + y1(2) - VBias \/ Rg1 * R;\n \n Matrix M(Matrix::Zero());\n M << 1 - Ic_Vbc * Rp, -Ic_Vbe * Rp, (Ic_Vbe + Ic_Vbc) * Rp,\n (Ib_Vbc + Ic_Vbc) * Rk, 1 + (Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc) * Rk, -(Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc) * Rk,\n -Ib_Vbc * R, -Ib_Vbe * R, 1 + (Ib_Vbe + Ib_Vbc) * R;\n\n return std::make_pair(F, M);\n }\n };\n\n template \n TransistorClassAFilter::TransistorClassAFilter(DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Cg, DataType Co, DataType Ck, DataType Is, DataType Vt, DataType Br, DataType Bf)\n :Parent(1, 5), Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Cg(Cg), Co(Co), Ck(Ck), Is(Is), Vt(Vt), Br(Br), Bf(Bf)\n {\n input_delay = output_delay = 1;\n }\n \n template \n TransistorClassAFilter::TransistorClassAFilter(TransistorClassAFilter&& other)\n :Parent(std::move(other)), Rp(other.Rp), Rg1(other.Rg1), Rg2(other.Rg2), Ro(other.Ro), Rk(other.Rk), VBias(other.VBias), Cg(other.Cg), Co(other.Co), Ck(other.Ck), Is(other.Is), Vt(other.Vt), Br(other.Br), Bf(other.Bf)\n {\n \n }\n\n template \n TransistorClassAFilter::~TransistorClassAFilter()\n {\n }\n \n template\n void TransistorClassAFilter::setup()\n {\n Parent::setup();\n optimizer.reset(new VectorizedNewtonRaphson(TransistorClassAFunction(static_cast(1. \/ input_sampling_rate),\n Rp, Rg1, Rg2, Ro, Rk, \/\/R\n VBias, \/\/ VBias\n Cg, Co, Ck, \/\/ C\n Is, Vt, Br, Bf, \/\/ transistor\n default_output)));\n }\n\n template\n void TransistorClassAFilter::full_setup()\n {\n Parent::full_setup();\n \/\/ setup default_output\n\n SimplifiedVectorizedNewtonRaphson, 3, 10> custom(TransistorClassAInitialFunction(\n Rp, Rg1, Rg2, Ro, Rk, \/\/R\n VBias, \/\/ VBias\n Is, Vt, Br, Bf \/\/ transistor\n ));\n \n auto stable = custom.optimize();\n\n default_output[0] = 0;\n default_output[1] = stable(1);\n default_output[2] = -stable(0);\n default_output[3] = stable(0);\n default_output[4] = stable(2);\n\n setup();\n }\n\n template\n void TransistorClassAFilter::process_impl(int64_t size) const\n {\n assert(input_sampling_rate == output_sampling_rate);\n\n for(int64_t i = 0; i < size; ++i)\n {\n optimizer->optimize(i, converted_inputs.data(), outputs.data() + 1);\n outputs[0][i] = outputs[2][i] + outputs[3][i];\n optimizer->get_function().update_state(i, converted_inputs.data(), outputs.data());\n }\n }\n\n template\n TransistorClassAFilter TransistorClassAFilter::build_standard_filter()\n {\n return TransistorClassAFilter(1e3, 15e3, 1.5e3, 22e3, 100, \/\/R\n 5, \/\/ VBias\n 3.3e-6, 1e-6, 160e-6, \/\/ C\n 1e-12, 26e-3, 1, 100 \/\/ transistor\n);\n }\n\n template class TransistorClassAFilter;\n template class TransistorClassAFilter;\n}\nDon't need that call\/**\n * \\file TransistorClassAFilter.cpp\n *\/\n\n#include \"TransistorClassAFilter.h\"\n\n#include \n\n#include \n#include \n\nnamespace ATK\n{\n template \n class TransistorClassAFilter::TransistorClassAFunction\n {\n const DataType_ Rp;\n const DataType_ Rg1;\n const DataType_ Rg2;\n const DataType_ Ro;\n const DataType_ Rk;\n const DataType_ VBias;\n const DataType_ Cg;\n const DataType_ Co;\n const DataType_ Ck;\n \n const DataType_ Is;\n const DataType_ Vt;\n const DataType_ Br;\n const DataType_ Bf;\n \n DataType ickeq;\n DataType icgeq;\n DataType icoeq;\n \n DataType_ Lb(const std::pair& exp)\n {\n return Is * ((exp.first - 1) \/ Bf + (exp.second - 1) \/ Br);\n }\n \n DataType_ Lb_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * (exp.first \/ Bf + exp.second \/ Br);\n }\n \n DataType_ Lb_Vce(const std::pair& exp)\n {\n return -Is \/ Vt * (exp.second \/ Br);\n }\n \n DataType_ Lc(const std::pair& exp)\n {\n return Is * ((exp.first - exp.second) - (exp.second - 1) \/ Br);\n }\n \n DataType_ Lc_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * ((exp.first - exp.second) - exp.second \/ Br);\n }\n \n DataType_ Lc_Vce(const std::pair& exp)\n {\n return Is \/ Vt * (exp.second + exp.second \/ Br);\n }\n\n public:\n typedef DataType_ DataType;\n typedef Eigen::Matrix Vector;\n typedef Eigen::Matrix Matrix;\n\n std::pair exp_y0;\n\n TransistorClassAFunction(DataType dt, DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Cg, DataType Co, DataType Ck, DataType Is, DataType Vt, DataType Br, DataType Bf, const std::vector& default_output)\n :Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Cg(2 \/ dt * Cg), Co(2 \/ dt * Co), Ck(2 \/ dt * Ck), Is(Is), Vt(Vt), Br(Br), Bf(Bf), ickeq(2 \/ dt * Ck * default_output[1]), icgeq(2 \/ dt * -Cg * default_output[4]), icoeq(-2 \/ dt * Co * default_output[2])\n {\n }\n\n Vector estimate(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)\n {\n Vector y0 = Vector::Zero();\n for(int j = 0; j < 4; ++j)\n {\n y0.data()[j] = output[j][i-1];\n }\n\n return y0;\n }\n \n void update_state(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output)\n {\n ickeq = 2 * Ck * output[1][i] - ickeq;\n icgeq = 2 * Cg * (input[0][i] - output[4][i]) - icgeq;\n icoeq = -2 * Co * output[2][i] - icoeq;\n }\n \n std::pair operator()(int64_t i, const DataType* const * ATK_RESTRICT input, DataType* const * ATK_RESTRICT output, const Vector& y1)\n {\n std::pair exp_y1 = std::make_pair(std::exp((y1(3) - y1(0)) \/ Vt), std::exp((y1(3) - y1(2)) \/ Vt));\n \n auto Ib = Lb(exp_y1);\n auto Ic = Lc(exp_y1);\n \n auto Ib_Vbe = Lb_Vbe(exp_y1);\n auto Ib_Vbc = Lb_Vce(exp_y1);\n\n auto Ic_Vbe = Lc_Vbe(exp_y1);\n auto Ic_Vbc = Lc_Vce(exp_y1);\n\n auto f1 = Ib + Ic + ickeq - y1(0) * (1\/Rk + Ck);\n auto f2 = icoeq + (y1(1) + y1(2)) \/ Ro + y1(1) * Co;\n auto f3 = Ic + (y1(1) + y1(2)) \/ Ro + (y1(2) - VBias) \/ Rp;\n auto f4 = Ib + icgeq + y1(3) \/ Rg2 + (y1(3) - VBias) \/ Rg1 + (y1(3) - input[0][i]) * Cg;\n \n Vector F(Vector::Zero());\n F << f1,\n f2,\n f3,\n f4;\n\n Matrix M(Matrix::Zero());\n M << -(Ib_Vbe + Ic_Vbe) - (1\/Rk + Ck), 0, -(Ib_Vbc + Ic_Vbc), (Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc),\n 0, 1\/Ro + Co, 1\/Ro, 0,\n -Ic_Vbe, 1\/Ro, -Ic_Vbc + 1\/Ro + 1\/Rp, (Ic_Vbe + Ic_Vbc),\n -Ib_Vbe, 0, -Ib_Vbc, (Ib_Vbc + Ib_Vbe) + 1\/Rg2 + 1\/Rg1 + Cg;\n\n return std::make_pair(F, M);\n }\n\n };\n \n template \n class TransistorClassAInitialFunction\n {\n const DataType_ Rp;\n const DataType_ Rg1;\n const DataType_ Rg2;\n const DataType_ Ro;\n const DataType_ Rk;\n const DataType_ VBias;\n \n const DataType_ Is;\n const DataType_ Vt;\n const DataType_ Br;\n const DataType_ Bf;\n \n DataType_ Lb(const std::pair& exp)\n {\n return Is * ((exp.first - 1) \/ Bf + (exp.second - 1) \/ Br);\n }\n \n DataType_ Lb_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * (exp.first \/ Bf + exp.second \/ Br);\n }\n \n DataType_ Lb_Vce(const std::pair& exp)\n {\n return -Is \/ Vt * (exp.second \/ Br);\n }\n \n DataType_ Lc(const std::pair& exp)\n {\n return Is * ((exp.first - exp.second) - (exp.second - 1) \/ Br);\n }\n \n DataType_ Lc_Vbe(const std::pair& exp)\n {\n return Is \/ Vt * ((exp.first - exp.second) - exp.second \/ Br);\n }\n \n DataType_ Lc_Vce(const std::pair& exp)\n {\n return Is \/ Vt * (exp.second + exp.second \/ Br);\n }\n \n public:\n typedef DataType_ DataType;\n typedef Eigen::Matrix Vector;\n typedef Eigen::Matrix Matrix;\n \n TransistorClassAInitialFunction(DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Is, DataType Vt, DataType Br, DataType Bf)\n :Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Is(Is), Vt(Vt), Br(Br), Bf(Bf)\n {\n }\n \n std::pair operator()(const Vector& y1)\n {\n std::pair exp_y1 = std::make_pair(std::exp((y1(2) - y1(1)) \/ Vt), std::exp((y1(2) - y1(0)) \/ Vt));\n \n auto Ib = Lb(exp_y1);\n auto Ic = Lc(exp_y1);\n \n auto Ib_Vbe = Lb_Vbe(exp_y1);\n auto Ib_Vbc = Lb_Vce(exp_y1);\n \n auto Ic_Vbe = Lc_Vbe(exp_y1);\n auto Ic_Vbc = Lc_Vce(exp_y1);\n \n Vector F(Vector::Zero());\n auto R = 1\/(1\/Rg1 + 1\/Rg2);\n F << y1(0) - VBias + Ic * Rp, y1(1) - (Ib + Ic) * Rk, Ib * R + y1(2) - VBias \/ Rg1 * R;\n \n Matrix M(Matrix::Zero());\n M << 1 - Ic_Vbc * Rp, -Ic_Vbe * Rp, (Ic_Vbe + Ic_Vbc) * Rp,\n (Ib_Vbc + Ic_Vbc) * Rk, 1 + (Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc) * Rk, -(Ib_Vbe + Ic_Vbe + Ib_Vbc + Ic_Vbc) * Rk,\n -Ib_Vbc * R, -Ib_Vbe * R, 1 + (Ib_Vbe + Ib_Vbc) * R;\n\n return std::make_pair(F, M);\n }\n };\n\n template \n TransistorClassAFilter::TransistorClassAFilter(DataType Rp, DataType Rg1, DataType Rg2, DataType Ro, DataType Rk, DataType VBias, DataType Cg, DataType Co, DataType Ck, DataType Is, DataType Vt, DataType Br, DataType Bf)\n :Parent(1, 5), Rp(Rp), Rg1(Rg1), Rg2(Rg2), Ro(Ro), Rk(Rk), VBias(VBias), Cg(Cg), Co(Co), Ck(Ck), Is(Is), Vt(Vt), Br(Br), Bf(Bf)\n {\n input_delay = output_delay = 1;\n }\n \n template \n TransistorClassAFilter::TransistorClassAFilter(TransistorClassAFilter&& other)\n :Parent(std::move(other)), Rp(other.Rp), Rg1(other.Rg1), Rg2(other.Rg2), Ro(other.Ro), Rk(other.Rk), VBias(other.VBias), Cg(other.Cg), Co(other.Co), Ck(other.Ck), Is(other.Is), Vt(other.Vt), Br(other.Br), Bf(other.Bf)\n {\n \n }\n\n template \n TransistorClassAFilter::~TransistorClassAFilter()\n {\n }\n \n template\n void TransistorClassAFilter::setup()\n {\n Parent::setup();\n optimizer.reset(new VectorizedNewtonRaphson(TransistorClassAFunction(static_cast(1. \/ input_sampling_rate),\n Rp, Rg1, Rg2, Ro, Rk, \/\/R\n VBias, \/\/ VBias\n Cg, Co, Ck, \/\/ C\n Is, Vt, Br, Bf, \/\/ transistor\n default_output)));\n }\n\n template\n void TransistorClassAFilter::full_setup()\n {\n Parent::full_setup();\n \/\/ setup default_output\n\n SimplifiedVectorizedNewtonRaphson, 3, 10> custom(TransistorClassAInitialFunction(\n Rp, Rg1, Rg2, Ro, Rk, \/\/R\n VBias, \/\/ VBias\n Is, Vt, Br, Bf \/\/ transistor\n ));\n \n auto stable = custom.optimize();\n\n default_output[0] = 0;\n default_output[1] = stable(1);\n default_output[2] = -stable(0);\n default_output[3] = stable(0);\n default_output[4] = stable(2);\n }\n\n template\n void TransistorClassAFilter::process_impl(int64_t size) const\n {\n assert(input_sampling_rate == output_sampling_rate);\n\n for(int64_t i = 0; i < size; ++i)\n {\n optimizer->optimize(i, converted_inputs.data(), outputs.data() + 1);\n outputs[0][i] = outputs[2][i] + outputs[3][i];\n optimizer->get_function().update_state(i, converted_inputs.data(), outputs.data());\n }\n }\n\n template\n TransistorClassAFilter TransistorClassAFilter::build_standard_filter()\n {\n return TransistorClassAFilter(1e3, 15e3, 1.5e3, 22e3, 100, \/\/R\n 5, \/\/ VBias\n 3.3e-6, 1e-6, 160e-6, \/\/ C\n 1e-12, 26e-3, 1, 100 \/\/ transistor\n);\n }\n\n template class TransistorClassAFilter;\n template class TransistorClassAFilter;\n}\n<|endoftext|>"} {"text":"\/**\n * @file vcs_species_thermo.cpp\n * Implementation for the VCS_SPECIES_THERMO object.\n *\/\n\/*\n * $Id: vcs_species_thermo.cpp,v 1.18 2008\/12\/17 16:34:18 hkmoffa Exp $\n *\/\n\/*\n * Copywrite (2005) Sandia Corporation. Under the terms of \n * Contract DE-AC04-94AL85000 with Sandia Corporation, the\n * U.S. Government retains certain rights in this software.\n *\/\n\n\n\n#include \"vcs_solve.h\"\n#include \"vcs_species_thermo.h\"\n#include \"vcs_defs.h\"\n#include \"vcs_VolPhase.h\"\n\n#include \"vcs_Exception.h\"\n#include \"vcs_internal.h\"\n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace VCSnonideal {\n\n\nVCS_SPECIES_THERMO::VCS_SPECIES_THERMO(int indexPhase, \n\t\t\t\t int indexSpeciesPhase) :\n \n IndexPhase(indexPhase),\n IndexSpeciesPhase(indexSpeciesPhase),\n OwningPhase(0),\n SS0_Model(VCS_SS0_CONSTANT),\n SS0_feSave(0.0), \n SS0_TSave(-90.0),\n SS0_T0(273.15),\n SS0_H0(0.0),\n SS0_S0(0.0),\n SS0_Cp0(0.0),\n SS0_Pref(1.01325E5),\n SS0_Params(0),\n SSStar_Model(VCS_SSSTAR_CONSTANT),\n SSStar_Params(0),\n Activity_Coeff_Model(VCS_AC_CONSTANT),\n Activity_Coeff_Params(0),\n SSStar_Vol_Model(VCS_SSVOL_IDEALGAS),\n SSStar_Vol_Params(0),\n SSStar_Vol0(-1.0),\n UseCanteraCalls(false),\n m_VCS_UnitsFormat(VCS_UNITS_UNITLESS)\n{\n SS0_Pref = 1.01325E5;\n}\n\n\n\/******************************************************************************\n *\n * destructor\n *\/\nVCS_SPECIES_THERMO::~VCS_SPECIES_THERMO() \n{\n}\n\n\/*****************************************************************************\n *\n * Copy Constructor VCS_SPECIES_THERMO\n *\/\nVCS_SPECIES_THERMO::VCS_SPECIES_THERMO(const VCS_SPECIES_THERMO& b) :\n IndexPhase(b.IndexPhase),\n IndexSpeciesPhase(b.IndexSpeciesPhase),\n OwningPhase(b.OwningPhase),\n SS0_Model(b.SS0_Model),\n SS0_feSave(b.SS0_feSave),\n SS0_TSave(b.SS0_TSave),\n SS0_T0(b.SS0_T0),\n SS0_H0(b.SS0_H0),\n SS0_S0(b.SS0_S0),\n SS0_Cp0(b.SS0_Cp0),\n SS0_Pref(b.SS0_Pref),\n SS0_Params(0),\n SSStar_Model(b.SSStar_Model),\n SSStar_Params(0),\n Activity_Coeff_Model(b.Activity_Coeff_Model),\n Activity_Coeff_Params(0),\n SSStar_Vol_Model(b.SSStar_Vol_Model),\n SSStar_Vol_Params(0),\n SSStar_Vol0(b.SSStar_Vol0),\n UseCanteraCalls(b.UseCanteraCalls),\n m_VCS_UnitsFormat(b.m_VCS_UnitsFormat)\n{\n\n switch (SS0_Model) {\n \n default:\n \n SS0_Params = 0;\n break;\n }\n}\n\n\/*****************************************************************************\n *\n * Assignment operator for VCS_SPECIES_THERMO\n *\/\nVCS_SPECIES_THERMO& \nVCS_SPECIES_THERMO::operator=(const VCS_SPECIES_THERMO& b)\n{\n if (&b != this) {\n IndexPhase = b.IndexPhase;\n IndexSpeciesPhase = b.IndexSpeciesPhase;\n OwningPhase = b.OwningPhase;\n SS0_Model = b.SS0_Model;\n SS0_feSave = b.SS0_feSave;\n SS0_TSave = b.SS0_TSave;\n SS0_T0 = b.SS0_T0;\n SS0_H0 = b.SS0_H0;\n SS0_S0 = b.SS0_S0;\n SS0_Cp0 = b.SS0_Cp0;\n SS0_Pref = b.SS0_Pref;\n SSStar_Model = b.SSStar_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n SSStar_Params = b.SSStar_Params;\n Activity_Coeff_Model = b.Activity_Coeff_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n Activity_Coeff_Params = b.Activity_Coeff_Params;\n SSStar_Vol_Model = b.SSStar_Vol_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n SSStar_Vol_Params = b.SSStar_Vol_Params; \n SSStar_Vol0 = b.SSStar_Vol0;\n UseCanteraCalls = b.UseCanteraCalls;\n m_VCS_UnitsFormat = b.m_VCS_UnitsFormat;\n }\n return *this;\n}\n\n\/******************************************************************************\n *\n * duplMyselfAsVCS_SPECIES_THERMO(): (virtual)\n *\n * This routine can duplicate inherited objects given a base class\n * pointer. It relies on valid copy constructors.\n *\/\n\nVCS_SPECIES_THERMO* VCS_SPECIES_THERMO::duplMyselfAsVCS_SPECIES_THERMO() {\n VCS_SPECIES_THERMO* ptr = new VCS_SPECIES_THERMO(*this);\n return ptr;\n}\n\n\n\/**************************************************************************\n *\n * GStar_R_calc();\n *\n * This function calculates the standard state Gibbs free energy\n * for species, kspec, at the solution temperature TKelvin and\n * solution pressure, Pres.\n * \n *\n * Input\n * kglob = species global index.\n * TKelvin = Temperature in Kelvin\n * pres = pressure is given in units specified by if__ variable.\n *\n *\n * Output\n * return value = standard state free energy in units of Kelvin.\n *\/\ndouble VCS_SPECIES_THERMO::GStar_R_calc(int kglob, double TKelvin, \n\t\t\t\t\tdouble pres)\n{\n char yo[] = \"VCS_SPECIES_THERMO::GStar_R_calc \";\n double fe, T;\n fe = G0_R_calc(kglob, TKelvin);\n T = TKelvin;\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_TP(TKelvin, pres);\n fe = OwningPhase->GStar_calc_one(kspec);\n double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);\n fe \/= R;\n } else {\n double pref = SS0_Pref;\n switch(SSStar_Model) {\n case VCS_SSSTAR_CONSTANT:\n break;\n case VCS_SSSTAR_IDEAL_GAS:\n fe += T * log( pres\/ pref );\t \n break;\n default:\n plogf(\"%sERROR: unknown SSStar model\\n\", yo);\n exit(EXIT_FAILURE);\n }\n }\n return fe;\n}\n \n\/**************************************************************************\n *\n * VolStar_calc:\n *\n * This function calculates the standard state molar volume\n * for species, kspec, at the temperature TKelvin and pressure, Pres,\n * \n * Input\n *\n * Output\n * return value = standard state volume in m**3 per kmol.\n * (VCS_UNITS_MKS) \n *\/\ndouble VCS_SPECIES_THERMO::\nVolStar_calc(int kglob, double TKelvin, double presPA)\n{\n char yo[] = \"VCS_SPECIES_THERMO::VStar_calc \";\n double vol, T;\n \n T = TKelvin;\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_TP(TKelvin, presPA);\n vol = OwningPhase->VolStar_calc_one(kspec);\n } else {\n switch(SSStar_Vol_Model) {\n case VCS_SSVOL_CONSTANT:\n vol = SSStar_Vol0;\n break;\n case VCS_SSVOL_IDEALGAS:\n \/\/ R J\/kmol\/K (2006 CODATA value)\n vol= 8314.47215 * T \/ presPA;\n break;\n default: \n plogf(\"%sERROR: unknown SSVol model\\n\", yo);\n exit(EXIT_FAILURE);\n } \n }\n return vol;\n} \n\n\/**************************************************************************\n *\n * G0_R_calc:\n *\n * This function calculates the naught state Gibbs free energy\n * for species, kspec, at the temperature TKelvin\n *\n * Input\n * kglob = species global index.\n * TKelvin = Temperature in Kelvin\n *\n * Output\n * return value = naught state free energy in Kelvin.\n *\/\ndouble VCS_SPECIES_THERMO::G0_R_calc(int kglob, double TKelvin)\n{\n#ifdef DEBUG_MODE\n char yo[] = \"VS_SPECIES_THERMO::G0_R_calc \";\n#endif\n double fe, H, S;\n if (SS0_Model == VCS_SS0_CONSTANT) {\n fe = SS0_feSave; \n return fe;\n }\n if (TKelvin == SS0_TSave) {\n fe = SS0_feSave;\n return fe;\n }\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_T(TKelvin);\n fe = OwningPhase->G0_calc_one(kspec);\n double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);\n fe \/= R;\n } else {\n switch (SS0_Model) {\n case VCS_SS0_CONSTANT:\n fe = SS0_feSave;\n break;\n case VCS_SS0_CONSTANT_CP:\n H = SS0_H0 + (TKelvin - SS0_T0) * SS0_Cp0;\n S = SS0_Cp0 + SS0_Cp0 * log((TKelvin \/ SS0_T0));\n fe = H - TKelvin * S;\n break;\n default:\n#ifdef DEBUG_MODE\n plogf(\"%sERROR: unknown model\\n\", yo);\n#endif\n exit(EXIT_FAILURE);\n }\n }\n SS0_feSave = fe;\n SS0_TSave = TKelvin;\n return fe;\n} \n\n\/**************************************************************************\n *\n * eval_ac:\n *\n * This function evaluates the activity coefficient\n * for species, kspec\n *\n * Input\n * kglob -> integer value of the species in the global \n * species list within VCS_GLOB. Phase and local species id\n * can be looked up within object.\n * \n * Note, T, P and mole fractions are obtained from the\n * single private instance of VCS_GLOB\n * \n *\n * Output\n * return value = activity coefficient for species kspec\n *\/\ndouble VCS_SPECIES_THERMO::eval_ac(int kglob)\n{\n#ifdef DEBUG_MODE\n char yo[] = \"VCS_SPECIES_THERMO::eval_ac \";\n#endif\n double ac;\n \/*\n * Activity coefficients are frequently evaluated on a per phase\n * basis. If they are, then the currPhAC[] boolean may be used\n * to reduce repeated work. Just set currPhAC[iph], when the \n * activity coefficients for all species in the phase are reevaluated.\n *\/\n if (UseCanteraCalls) {\n int kspec = IndexSpeciesPhase;\n ac = OwningPhase->AC_calc_one(kspec);\n } else {\n switch (Activity_Coeff_Model) {\n case VCS_AC_CONSTANT:\n ac = 1.0;\n break;\n default:\n#ifdef DEBUG_MODE\n plogf(\"%sERROR: unknown model\\n\", yo);\n#endif\n exit(EXIT_FAILURE);\n }\n }\n return ac;\n}\n\n\/*****************************************************************************\/\n}\nTook out a warning message on vc++\/**\n * @file vcs_species_thermo.cpp\n * Implementation for the VCS_SPECIES_THERMO object.\n *\/\n\/*\n * $Id: vcs_species_thermo.cpp,v 1.18 2008\/12\/17 16:34:18 hkmoffa Exp $\n *\/\n\/*\n * Copywrite (2005) Sandia Corporation. Under the terms of \n * Contract DE-AC04-94AL85000 with Sandia Corporation, the\n * U.S. Government retains certain rights in this software.\n *\/\n\n\n\n#include \"vcs_solve.h\"\n#include \"vcs_species_thermo.h\"\n#include \"vcs_defs.h\"\n#include \"vcs_VolPhase.h\"\n\n#include \"vcs_Exception.h\"\n#include \"vcs_internal.h\"\n\n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace VCSnonideal {\n\n\nVCS_SPECIES_THERMO::VCS_SPECIES_THERMO(int indexPhase, \n\t\t\t\t int indexSpeciesPhase) :\n \n IndexPhase(indexPhase),\n IndexSpeciesPhase(indexSpeciesPhase),\n OwningPhase(0),\n SS0_Model(VCS_SS0_CONSTANT),\n SS0_feSave(0.0), \n SS0_TSave(-90.0),\n SS0_T0(273.15),\n SS0_H0(0.0),\n SS0_S0(0.0),\n SS0_Cp0(0.0),\n SS0_Pref(1.01325E5),\n SS0_Params(0),\n SSStar_Model(VCS_SSSTAR_CONSTANT),\n SSStar_Params(0),\n Activity_Coeff_Model(VCS_AC_CONSTANT),\n Activity_Coeff_Params(0),\n SSStar_Vol_Model(VCS_SSVOL_IDEALGAS),\n SSStar_Vol_Params(0),\n SSStar_Vol0(-1.0),\n UseCanteraCalls(false),\n m_VCS_UnitsFormat(VCS_UNITS_UNITLESS)\n{\n SS0_Pref = 1.01325E5;\n}\n\n\n\/******************************************************************************\n *\n * destructor\n *\/\nVCS_SPECIES_THERMO::~VCS_SPECIES_THERMO() \n{\n}\n\n\/*****************************************************************************\n *\n * Copy Constructor VCS_SPECIES_THERMO\n *\/\nVCS_SPECIES_THERMO::VCS_SPECIES_THERMO(const VCS_SPECIES_THERMO& b) :\n IndexPhase(b.IndexPhase),\n IndexSpeciesPhase(b.IndexSpeciesPhase),\n OwningPhase(b.OwningPhase),\n SS0_Model(b.SS0_Model),\n SS0_feSave(b.SS0_feSave),\n SS0_TSave(b.SS0_TSave),\n SS0_T0(b.SS0_T0),\n SS0_H0(b.SS0_H0),\n SS0_S0(b.SS0_S0),\n SS0_Cp0(b.SS0_Cp0),\n SS0_Pref(b.SS0_Pref),\n SS0_Params(0),\n SSStar_Model(b.SSStar_Model),\n SSStar_Params(0),\n Activity_Coeff_Model(b.Activity_Coeff_Model),\n Activity_Coeff_Params(0),\n SSStar_Vol_Model(b.SSStar_Vol_Model),\n SSStar_Vol_Params(0),\n SSStar_Vol0(b.SSStar_Vol0),\n UseCanteraCalls(b.UseCanteraCalls),\n m_VCS_UnitsFormat(b.m_VCS_UnitsFormat)\n{\n \n SS0_Params = 0;\n}\n\n\/*****************************************************************************\n *\n * Assignment operator for VCS_SPECIES_THERMO\n *\/\nVCS_SPECIES_THERMO& \nVCS_SPECIES_THERMO::operator=(const VCS_SPECIES_THERMO& b)\n{\n if (&b != this) {\n IndexPhase = b.IndexPhase;\n IndexSpeciesPhase = b.IndexSpeciesPhase;\n OwningPhase = b.OwningPhase;\n SS0_Model = b.SS0_Model;\n SS0_feSave = b.SS0_feSave;\n SS0_TSave = b.SS0_TSave;\n SS0_T0 = b.SS0_T0;\n SS0_H0 = b.SS0_H0;\n SS0_S0 = b.SS0_S0;\n SS0_Cp0 = b.SS0_Cp0;\n SS0_Pref = b.SS0_Pref;\n SSStar_Model = b.SSStar_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n SSStar_Params = b.SSStar_Params;\n Activity_Coeff_Model = b.Activity_Coeff_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n Activity_Coeff_Params = b.Activity_Coeff_Params;\n SSStar_Vol_Model = b.SSStar_Vol_Model;\n \/*\n * shallow copy because function is undeveloped.\n *\/\n SSStar_Vol_Params = b.SSStar_Vol_Params; \n SSStar_Vol0 = b.SSStar_Vol0;\n UseCanteraCalls = b.UseCanteraCalls;\n m_VCS_UnitsFormat = b.m_VCS_UnitsFormat;\n }\n return *this;\n}\n\n\/******************************************************************************\n *\n * duplMyselfAsVCS_SPECIES_THERMO(): (virtual)\n *\n * This routine can duplicate inherited objects given a base class\n * pointer. It relies on valid copy constructors.\n *\/\n\nVCS_SPECIES_THERMO* VCS_SPECIES_THERMO::duplMyselfAsVCS_SPECIES_THERMO() {\n VCS_SPECIES_THERMO* ptr = new VCS_SPECIES_THERMO(*this);\n return ptr;\n}\n\n\n\/**************************************************************************\n *\n * GStar_R_calc();\n *\n * This function calculates the standard state Gibbs free energy\n * for species, kspec, at the solution temperature TKelvin and\n * solution pressure, Pres.\n * \n *\n * Input\n * kglob = species global index.\n * TKelvin = Temperature in Kelvin\n * pres = pressure is given in units specified by if__ variable.\n *\n *\n * Output\n * return value = standard state free energy in units of Kelvin.\n *\/\ndouble VCS_SPECIES_THERMO::GStar_R_calc(int kglob, double TKelvin, \n\t\t\t\t\tdouble pres)\n{\n char yo[] = \"VCS_SPECIES_THERMO::GStar_R_calc \";\n double fe, T;\n fe = G0_R_calc(kglob, TKelvin);\n T = TKelvin;\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_TP(TKelvin, pres);\n fe = OwningPhase->GStar_calc_one(kspec);\n double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);\n fe \/= R;\n } else {\n double pref = SS0_Pref;\n switch(SSStar_Model) {\n case VCS_SSSTAR_CONSTANT:\n break;\n case VCS_SSSTAR_IDEAL_GAS:\n fe += T * log( pres\/ pref );\t \n break;\n default:\n plogf(\"%sERROR: unknown SSStar model\\n\", yo);\n exit(EXIT_FAILURE);\n }\n }\n return fe;\n}\n \n\/**************************************************************************\n *\n * VolStar_calc:\n *\n * This function calculates the standard state molar volume\n * for species, kspec, at the temperature TKelvin and pressure, Pres,\n * \n * Input\n *\n * Output\n * return value = standard state volume in m**3 per kmol.\n * (VCS_UNITS_MKS) \n *\/\ndouble VCS_SPECIES_THERMO::\nVolStar_calc(int kglob, double TKelvin, double presPA)\n{\n char yo[] = \"VCS_SPECIES_THERMO::VStar_calc \";\n double vol, T;\n \n T = TKelvin;\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_TP(TKelvin, presPA);\n vol = OwningPhase->VolStar_calc_one(kspec);\n } else {\n switch(SSStar_Vol_Model) {\n case VCS_SSVOL_CONSTANT:\n vol = SSStar_Vol0;\n break;\n case VCS_SSVOL_IDEALGAS:\n \/\/ R J\/kmol\/K (2006 CODATA value)\n vol= 8314.47215 * T \/ presPA;\n break;\n default: \n plogf(\"%sERROR: unknown SSVol model\\n\", yo);\n exit(EXIT_FAILURE);\n } \n }\n return vol;\n} \n\n\/**************************************************************************\n *\n * G0_R_calc:\n *\n * This function calculates the naught state Gibbs free energy\n * for species, kspec, at the temperature TKelvin\n *\n * Input\n * kglob = species global index.\n * TKelvin = Temperature in Kelvin\n *\n * Output\n * return value = naught state free energy in Kelvin.\n *\/\ndouble VCS_SPECIES_THERMO::G0_R_calc(int kglob, double TKelvin)\n{\n#ifdef DEBUG_MODE\n char yo[] = \"VS_SPECIES_THERMO::G0_R_calc \";\n#endif\n double fe, H, S;\n if (SS0_Model == VCS_SS0_CONSTANT) {\n fe = SS0_feSave; \n return fe;\n }\n if (TKelvin == SS0_TSave) {\n fe = SS0_feSave;\n return fe;\n }\n if (UseCanteraCalls) {\n AssertThrowVCS(m_VCS_UnitsFormat == VCS_UNITS_MKS, \"Possible inconsistency\");\n int kspec = IndexSpeciesPhase;\n OwningPhase->setState_T(TKelvin);\n fe = OwningPhase->G0_calc_one(kspec);\n double R = vcsUtil_gasConstant(m_VCS_UnitsFormat);\n fe \/= R;\n } else {\n switch (SS0_Model) {\n case VCS_SS0_CONSTANT:\n fe = SS0_feSave;\n break;\n case VCS_SS0_CONSTANT_CP:\n H = SS0_H0 + (TKelvin - SS0_T0) * SS0_Cp0;\n S = SS0_Cp0 + SS0_Cp0 * log((TKelvin \/ SS0_T0));\n fe = H - TKelvin * S;\n break;\n default:\n#ifdef DEBUG_MODE\n plogf(\"%sERROR: unknown model\\n\", yo);\n#endif\n exit(EXIT_FAILURE);\n }\n }\n SS0_feSave = fe;\n SS0_TSave = TKelvin;\n return fe;\n} \n\n\/**************************************************************************\n *\n * eval_ac:\n *\n * This function evaluates the activity coefficient\n * for species, kspec\n *\n * Input\n * kglob -> integer value of the species in the global \n * species list within VCS_GLOB. Phase and local species id\n * can be looked up within object.\n * \n * Note, T, P and mole fractions are obtained from the\n * single private instance of VCS_GLOB\n * \n *\n * Output\n * return value = activity coefficient for species kspec\n *\/\ndouble VCS_SPECIES_THERMO::eval_ac(int kglob)\n{\n#ifdef DEBUG_MODE\n char yo[] = \"VCS_SPECIES_THERMO::eval_ac \";\n#endif\n double ac;\n \/*\n * Activity coefficients are frequently evaluated on a per phase\n * basis. If they are, then the currPhAC[] boolean may be used\n * to reduce repeated work. Just set currPhAC[iph], when the \n * activity coefficients for all species in the phase are reevaluated.\n *\/\n if (UseCanteraCalls) {\n int kspec = IndexSpeciesPhase;\n ac = OwningPhase->AC_calc_one(kspec);\n } else {\n switch (Activity_Coeff_Model) {\n case VCS_AC_CONSTANT:\n ac = 1.0;\n break;\n default:\n#ifdef DEBUG_MODE\n plogf(\"%sERROR: unknown model\\n\", yo);\n#endif\n exit(EXIT_FAILURE);\n }\n }\n return ac;\n}\n\n\/*****************************************************************************\/\n}\n<|endoftext|>"} {"text":"\/\/ Copyright © 2010-2015 The CefSharp Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n\n#include \"Stdafx.h\"\n#include \"Internals\/CefRequestWrapper.h\"\n#include \"Internals\/CefResponseWrapper.h\"\n#include \"Internals\/CefCallbackWrapper.h\"\n#include \"ResourceHandlerWrapper.h\"\n#include \"Internals\/TypeConversion.h\"\n\nusing namespace System::Runtime::InteropServices;\nusing namespace System::IO;\n\nnamespace CefSharp\n{\n bool ResourceHandlerWrapper::ProcessRequest(CefRefPtr request, CefRefPtr callback)\n {\n _callbackWrapper = gcnew CefCallbackWrapper(callback);\n\n \/\/ If we already have a non-null _request\n \/\/ dispose it via delete before using the parameter for the rest\n \/\/ of this object's lifetime. This ought to be sensible to do\n \/\/ because the contained data ought to be nearly identical.\n delete _request;\n\n _request = gcnew CefRequestWrapper(request);\n\n AutoLock lock_scope(_syncRoot);\n\n return _handler->ProcessRequestAsync(_request, _callbackWrapper);\n }\n\n void ResourceHandlerWrapper::GetResponseHeaders(CefRefPtr response, int64& response_length, CefString& redirectUrl)\n {\n String^ newRedistUrl;\n\n CefResponseWrapper responseWrapper(response);\n\n _stream = _handler->GetResponse(%responseWrapper, response_length, newRedistUrl);\n\n redirectUrl = StringUtils::ToNative(newRedistUrl);\n }\n\n bool ResourceHandlerWrapper::ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr callback)\n {\n bool hasData = false;\n\n AutoLock lock_scope(_syncRoot);\n\n if (static_cast(_stream) == nullptr)\n {\n bytes_read = 0;\n }\n else\n {\n array^ buffer = gcnew array(bytes_to_read);\n bytes_read = _stream->Read(buffer, 0, bytes_to_read);\n pin_ptr src = &buffer[0];\n memcpy(data_out, static_cast(src), bytes_read);\n \/\/ must return false when the response is complete\n hasData = bytes_read > 0;\n \/\/TODO: Fix this\n \/*if (!hasData && _closeStream)\n {\n _stream->Close();\n }*\/\n }\n\n return hasData;\n }\n\n bool ResourceHandlerWrapper::CanGetCookie(const CefCookie& cookie)\n {\n \/\/Default value is true\n return true;\n }\n\n bool ResourceHandlerWrapper::CanSetCookie(const CefCookie& cookie)\n {\n \/\/Default value is true\n return true;\n }\n\n void ResourceHandlerWrapper::Cancel()\n {\n \/\/TODO: Fix this\n \/*if (static_cast(_stream) != nullptr && _closeStream)\n {\n _stream->Close();\n }*\/\n _stream = nullptr;\n\n \/\/ Do not dispose here; since CEF 2537 the ResourceHandlerWrapper pointer is\n \/\/ referenced after Cancel and disposal would cause an access violation.\n \/\/delete this;\n }\n\n int64 ResourceHandlerWrapper::SizeFromStream()\n {\n if (static_cast(_stream) == nullptr)\n {\n return 0;\n }\n\n if (_stream->CanSeek)\n {\n _stream->Seek(0, System::IO::SeekOrigin::End);\n int64 length = static_cast(_stream->Position);\n _stream->Seek(0, System::IO::SeekOrigin::Begin);\n return length;\n }\n return -1;\n }\n}Fix typo - newRedirectUrl\/\/ Copyright © 2010-2015 The CefSharp Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n\n#include \"Stdafx.h\"\n#include \"Internals\/CefRequestWrapper.h\"\n#include \"Internals\/CefResponseWrapper.h\"\n#include \"Internals\/CefCallbackWrapper.h\"\n#include \"ResourceHandlerWrapper.h\"\n#include \"Internals\/TypeConversion.h\"\n\nusing namespace System::Runtime::InteropServices;\nusing namespace System::IO;\n\nnamespace CefSharp\n{\n bool ResourceHandlerWrapper::ProcessRequest(CefRefPtr request, CefRefPtr callback)\n {\n _callbackWrapper = gcnew CefCallbackWrapper(callback);\n\n \/\/ If we already have a non-null _request\n \/\/ dispose it via delete before using the parameter for the rest\n \/\/ of this object's lifetime. This ought to be sensible to do\n \/\/ because the contained data ought to be nearly identical.\n delete _request;\n\n _request = gcnew CefRequestWrapper(request);\n\n AutoLock lock_scope(_syncRoot);\n\n return _handler->ProcessRequestAsync(_request, _callbackWrapper);\n }\n\n void ResourceHandlerWrapper::GetResponseHeaders(CefRefPtr response, int64& response_length, CefString& redirectUrl)\n {\n String^ newRedirectUrl;\n\n CefResponseWrapper responseWrapper(response);\n\n _stream = _handler->GetResponse(%responseWrapper, response_length, newRedirectUrl);\n\n redirectUrl = StringUtils::ToNative(newRedirectUrl);\n }\n\n bool ResourceHandlerWrapper::ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, CefRefPtr callback)\n {\n bool hasData = false;\n\n AutoLock lock_scope(_syncRoot);\n\n if (static_cast(_stream) == nullptr)\n {\n bytes_read = 0;\n }\n else\n {\n array^ buffer = gcnew array(bytes_to_read);\n bytes_read = _stream->Read(buffer, 0, bytes_to_read);\n pin_ptr src = &buffer[0];\n memcpy(data_out, static_cast(src), bytes_read);\n \/\/ must return false when the response is complete\n hasData = bytes_read > 0;\n \/\/TODO: Fix this\n \/*if (!hasData && _closeStream)\n {\n _stream->Close();\n }*\/\n }\n\n return hasData;\n }\n\n bool ResourceHandlerWrapper::CanGetCookie(const CefCookie& cookie)\n {\n \/\/Default value is true\n return true;\n }\n\n bool ResourceHandlerWrapper::CanSetCookie(const CefCookie& cookie)\n {\n \/\/Default value is true\n return true;\n }\n\n void ResourceHandlerWrapper::Cancel()\n {\n \/\/TODO: Fix this\n \/*if (static_cast(_stream) != nullptr && _closeStream)\n {\n _stream->Close();\n }*\/\n _stream = nullptr;\n\n \/\/ Do not dispose here; since CEF 2537 the ResourceHandlerWrapper pointer is\n \/\/ referenced after Cancel and disposal would cause an access violation.\n \/\/delete this;\n }\n\n int64 ResourceHandlerWrapper::SizeFromStream()\n {\n if (static_cast(_stream) == nullptr)\n {\n return 0;\n }\n\n if (_stream->CanSeek)\n {\n _stream->Seek(0, System::IO::SeekOrigin::End);\n int64 length = static_cast(_stream->Position);\n _stream->Seek(0, System::IO::SeekOrigin::Begin);\n return length;\n }\n return -1;\n }\n}<|endoftext|>"} {"text":"\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file ConfiguredConsumer.hxx\n *\n * Consumer class that uses CDI configuration and a GPIO template structure to\n * export a single bit as two event consumers to OpenLCB.\n *\n * @author Balazs Racz\n * @date 13 June 2015\n *\/\n\n#ifndef _NMRANET_CONFIGUREDCONSUMER_HXX_\n#define _NMRANET_CONFIGUREDCONSUMER_HXX_\n\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/ConfigRepresentation.hxx\"\n#include \"utils\/ConfigUpdateListener.hxx\"\n\nnamespace nmranet\n{\n\nBEGIN_GROUP(ConsumerConfig, base);\nEXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry, Name(\"Event On\"),\n Description(\"Receiving this event ID will turn the output on.\"));\nEXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry,\n Name(\"Event Off\"),\n Description(\"Receiving this event ID will turn the output off.\"));\nEND_GROUP(ConsumerConfig, event_off);\n\nclass ConfiguredConsumer : public ConfigUpdateListener\n{\npublic:\n using Impl = GPIOBit;\n\n template \n ConfiguredConsumer(Node *node, const ConsumerConfig &cfg, const HW &)\n : impl_(node, 0, 0, &HW::get, &HW::set)\n , consumer_(&impl_)\n , cfg_(cfg)\n {\n ConfigUpdateService::instance()->register_update_listener(this);\n }\n\n UpdateAction apply_configuration(\n int fd, bool initial_load, BarrierNotifiable *done)\n {\n AutoNotify n(done);\n EventId cfg_event_on = cfg_.event_on().read(fd);\n EventId cfg_event_off = cfg_.event_off().read(fd);\n if (cfg_event_off != impl_.event_off() ||\n cfg_event_on != impl_.event_on())\n {\n auto saved_setter = impl_.setter_;\n auto saved_getter = impl_.getter_;\n auto saved_node = impl_.node();\n \/\/ Need to reinitialize the consumer. We do this with in-place\n \/\/ destruction and construction.\n consumer_.~BitEventConsumer();\n impl_.~Impl();\n new (&impl_) Impl(saved_node, cfg_event_on, cfg_event_off,\n saved_getter, saved_setter);\n new (&consumer_) BitEventConsumer(&impl_);\n return REINIT_NEEDED; \/\/ Causes events identify.\n }\n return UPDATED;\n }\n\n \/\/\/@TODO(balazs.racz): implement\n void factory_reset(int fd) OVERRIDE\n {\n }\n\nprivate:\n Impl impl_;\n BitEventConsumer consumer_;\n const ConsumerConfig cfg_;\n};\n\n} \/\/ namespace nmranet\n\n#endif \/\/ _NMRANET_CONFIGUREDCONSUMER_HXX_\nFixes formatting.\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file ConfiguredConsumer.hxx\n *\n * Consumer class that uses CDI configuration and a GPIO template structure to\n * export a single bit as two event consumers to OpenLCB.\n *\n * @author Balazs Racz\n * @date 13 June 2015\n *\/\n\n#ifndef _NMRANET_CONFIGUREDCONSUMER_HXX_\n#define _NMRANET_CONFIGUREDCONSUMER_HXX_\n\n#include \"nmranet\/EventHandlerTemplates.hxx\"\n#include \"nmranet\/ConfigRepresentation.hxx\"\n#include \"utils\/ConfigUpdateListener.hxx\"\n#include \"utils\/ConfigUpdateService.hxx\"\n\nnamespace nmranet\n{\n\nBEGIN_GROUP(ConsumerConfig, base);\nEXTEND_GROUP(ConsumerConfig, base, event_on, EventConfigEntry, \/\/\n Name(\"Event On\"),\n Description(\"Receiving this event ID will turn the output on.\"));\nEXTEND_GROUP(ConsumerConfig, event_on, event_off, EventConfigEntry, \/\/\n Name(\"Event Off\"),\n Description(\"Receiving this event ID will turn the output off.\"));\nEND_GROUP(ConsumerConfig, event_off);\n\nclass ConfiguredConsumer : public ConfigUpdateListener\n{\npublic:\n using Impl = GPIOBit;\n\n template \n ConfiguredConsumer(Node *node, const ConsumerConfig &cfg, const HW &)\n : impl_(node, 0, 0, &HW::get, &HW::set)\n , consumer_(&impl_)\n , cfg_(cfg)\n {\n ConfigUpdateService::instance()->register_update_listener(this);\n }\n\n UpdateAction apply_configuration(\n int fd, bool initial_load, BarrierNotifiable *done)\n {\n AutoNotify n(done);\n EventId cfg_event_on = cfg_.event_on().read(fd);\n EventId cfg_event_off = cfg_.event_off().read(fd);\n if (cfg_event_off != impl_.event_off() ||\n cfg_event_on != impl_.event_on())\n {\n auto saved_setter = impl_.setter_;\n auto saved_getter = impl_.getter_;\n auto saved_node = impl_.node();\n \/\/ Need to reinitialize the consumer. We do this with in-place\n \/\/ destruction and construction.\n consumer_.~BitEventConsumer();\n impl_.~Impl();\n new (&impl_) Impl(saved_node, cfg_event_on, cfg_event_off,\n saved_getter, saved_setter);\n new (&consumer_) BitEventConsumer(&impl_);\n return REINIT_NEEDED; \/\/ Causes events identify.\n }\n return UPDATED;\n }\n\n \/\/\/@TODO(balazs.racz): implement\n void factory_reset(int fd) OVERRIDE\n {\n }\n\nprivate:\n Impl impl_;\n BitEventConsumer consumer_;\n const ConsumerConfig cfg_;\n};\n\n} \/\/ namespace nmranet\n\n#endif \/\/ _NMRANET_CONFIGUREDCONSUMER_HXX_\n<|endoftext|>"} {"text":"moved memleak into projectm-test<|endoftext|>"} {"text":"\/\/ Copyright 2012 Luis Pedro Coelho \n\/\/ License: MIT (see COPYING.MIT file)\n\n#include \"base.h\"\n#include \"_png.h\"\n#include \"tools.h\"\n\n#include \n\n#include \n#include \n\nnamespace {\n\nvoid throw_error(png_structp png_ptr, png_const_charp error_msg) {\n throw CannotReadError(error_msg);\n}\n\nclass png_holder {\n public:\n png_holder(int m)\n :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0))\n ,png_info(0)\n ,mode(holder_mode(m))\n { }\n ~png_holder() {\n png_infopp pp = (png_info ? &png_info : 0);\n if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0);\n else png_destroy_write_struct(&png_ptr, pp);\n }\n void create_info() {\n png_info = png_create_info_struct(png_ptr);\n if (!png_info) throw \"error\";\n }\n\n png_structp png_ptr;\n png_infop png_info;\n enum holder_mode { read_mode, write_mode } mode;\n};\n\nvoid read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) {\n byte_source* s = static_cast(png_get_io_ptr(png_ptr));\n const size_t actual = s->read(reinterpret_cast(buffer), n);\n if (actual != n) {\n throw CannotReadError();\n }\n}\n\nvoid write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) {\n byte_sink* s = static_cast(png_get_io_ptr(png_ptr));\n const size_t actual = s->write(reinterpret_cast(buffer), n);\n if (actual != n) {\n throw CannotReadError();\n }\n}\nvoid flush_source(png_structp png_ptr) {\n byte_sink* s = static_cast(png_get_io_ptr(png_ptr));\n s->flush();\n}\n\nint color_type_of(Image* im) {\n if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY;\n if (im->ndims() != 3) throw CannotWriteError();\n if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB;\n if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA;\n throw CannotWriteError();\n}\n}\nstd::auto_ptr PNGFormat::read(byte_source* src, ImageFactory* factory) {\n png_holder p(png_holder::read_mode);\n png_set_read_fn(p.png_ptr, src, read_from_source);\n p.create_info();\n png_read_info(p.png_ptr, p.png_info);\n \n const int w = png_get_image_width (p.png_ptr, p.png_info);\n const int h = png_get_image_height(p.png_ptr, p.png_info);\n int bit_depth = png_get_bit_depth(p.png_ptr, p.png_info);\n if (bit_depth != 8 && bit_depth != 16) {\n throw CannotReadError(\"Cannot read this bit depth and color combination\");\n }\n int d = -1;\n switch (png_get_color_type(p.png_ptr, p.png_info)) {\n case PNG_COLOR_TYPE_PALETTE:\n png_set_palette_to_rgb(p.png_ptr);\n case PNG_COLOR_TYPE_RGB:\n d = 3;\n break;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n d = 4;\n break;\n case PNG_COLOR_TYPE_GRAY:\n if (bit_depth < 8) {\n png_set_expand_gray_1_2_4_to_8(p.png_ptr);\n bit_depth = 8;\n }\n d = -1;\n break;\n default:\n throw CannotReadError(\"Unhandled color type\");\n }\n\n std::auto_ptr output(factory->create(bit_depth, h, w, d));\n std::vector rowps = allrows(*output);\n png_read_image(p.png_ptr, &rowps[0]);\n\n return output;\n}\n\nvoid PNGFormat::write(Image* input, byte_sink* output) {\n png_holder p(png_holder::write_mode);\n p.create_info();\n png_set_write_fn(p.png_ptr, output, write_to_source, flush_source);\n const int height = input->dim(0);\n const int width = input->dim(1);\n const int bit_depth = 8;\n const int color_type = color_type_of(input);\n\n png_set_IHDR(p.png_ptr, p.png_info, width, height,\n bit_depth, color_type, PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n png_write_info(p.png_ptr, p.png_info);\n\n std::vector rowps = allrows(*input);\n png_write_image(p.png_ptr, &rowps[0]);\n png_write_end(p.png_ptr, p.png_info);\n}\n\n\nENH More checks and error messages\/\/ Copyright 2012 Luis Pedro Coelho \n\/\/ License: MIT (see COPYING.MIT file)\n\n#include \"base.h\"\n#include \"_png.h\"\n#include \"tools.h\"\n\n#include \n\n#include \n#include \n\nnamespace {\n\nvoid throw_error(png_structp png_ptr, png_const_charp error_msg) {\n throw CannotReadError(error_msg);\n}\n\nclass png_holder {\n public:\n png_holder(int m)\n :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0))\n ,png_info(0)\n ,mode(holder_mode(m))\n { }\n ~png_holder() {\n png_infopp pp = (png_info ? &png_info : 0);\n if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0);\n else png_destroy_write_struct(&png_ptr, pp);\n }\n void create_info() {\n png_info = png_create_info_struct(png_ptr);\n if (!png_info) throw \"error\";\n }\n\n png_structp png_ptr;\n png_infop png_info;\n enum holder_mode { read_mode, write_mode } mode;\n};\n\nvoid read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) {\n byte_source* s = static_cast(png_get_io_ptr(png_ptr));\n const size_t actual = s->read(reinterpret_cast(buffer), n);\n if (actual != n) {\n throw CannotReadError();\n }\n}\n\nvoid write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) {\n byte_sink* s = static_cast(png_get_io_ptr(png_ptr));\n const size_t actual = s->write(reinterpret_cast(buffer), n);\n if (actual != n) {\n throw CannotReadError();\n }\n}\nvoid flush_source(png_structp png_ptr) {\n byte_sink* s = static_cast(png_get_io_ptr(png_ptr));\n s->flush();\n}\n\nint color_type_of(Image* im) {\n if (im->nbits() != 8) throw CannotWriteError(\"Image must be 8 bits for PNG saving\");\n if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY;\n if (im->ndims() != 3) throw CannotWriteError(\"Image must be either 2 or 3 dimensional\");\n if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB;\n if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA;\n throw CannotWriteError();\n}\n}\nstd::auto_ptr PNGFormat::read(byte_source* src, ImageFactory* factory) {\n png_holder p(png_holder::read_mode);\n png_set_read_fn(p.png_ptr, src, read_from_source);\n p.create_info();\n png_read_info(p.png_ptr, p.png_info);\n \n const int w = png_get_image_width (p.png_ptr, p.png_info);\n const int h = png_get_image_height(p.png_ptr, p.png_info);\n int bit_depth = png_get_bit_depth(p.png_ptr, p.png_info);\n if (bit_depth != 8 && bit_depth != 16) {\n throw CannotReadError(\"Cannot read this bit depth and color combination\");\n }\n int d = -1;\n switch (png_get_color_type(p.png_ptr, p.png_info)) {\n case PNG_COLOR_TYPE_PALETTE:\n png_set_palette_to_rgb(p.png_ptr);\n case PNG_COLOR_TYPE_RGB:\n d = 3;\n break;\n case PNG_COLOR_TYPE_RGB_ALPHA:\n d = 4;\n break;\n case PNG_COLOR_TYPE_GRAY:\n if (bit_depth < 8) {\n png_set_expand_gray_1_2_4_to_8(p.png_ptr);\n bit_depth = 8;\n }\n d = -1;\n break;\n default:\n throw CannotReadError(\"Unhandled color type\");\n }\n\n std::auto_ptr output(factory->create(bit_depth, h, w, d));\n std::vector rowps = allrows(*output);\n png_read_image(p.png_ptr, &rowps[0]);\n\n return output;\n}\n\nvoid PNGFormat::write(Image* input, byte_sink* output) {\n png_holder p(png_holder::write_mode);\n p.create_info();\n png_set_write_fn(p.png_ptr, output, write_to_source, flush_source);\n const int height = input->dim(0);\n const int width = input->dim(1);\n const int bit_depth = 8;\n const int color_type = color_type_of(input);\n\n png_set_IHDR(p.png_ptr, p.png_info, width, height,\n bit_depth, color_type, PNG_INTERLACE_NONE,\n PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n png_write_info(p.png_ptr, p.png_info);\n\n std::vector rowps = allrows(*input);\n png_write_image(p.png_ptr, &rowps[0]);\n png_write_end(p.png_ptr, p.png_info);\n}\n\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbStandardFilterWatcher.h\"\n\nnamespace otb\n{\n\nStandardFilterWatcher\n::StandardFilterWatcher(itk::ProcessObject* process,\n const char *comment)\n : FilterWatcherBase(process, comment)\n{\n m_StarsCount = 50;\n}\n\nStandardFilterWatcher\n::StandardFilterWatcher( const StandardFilterWatcher& watch)\n{\n \/\/ Initialize state\n m_StarsCount = watch.m_StarsCount;\n}\n\nvoid\nStandardFilterWatcher\n::operator=(const StandardFilterWatcher &watch)\n{\n \/\/ Initialize state\n m_StarsCount = watch.m_StarsCount;\n}\n\nvoid\nStandardFilterWatcher\n::ShowProgress()\n{\n if (m_Process)\n {\n int progressPercent = static_cast(m_Process->GetProgress()*100);\n std::string stars(static_cast(m_Process->GetProgress()*m_StarsCount),'*');\n std::string blanks(static_cast(m_StarsCount - m_Process->GetProgress()*m_StarsCount),' ');\n std::cout << \"\\rProcessing progress:\" << progressPercent << \"% [\" << stars << blanks << \"]\" << std::flush;\n }\n}\n\nvoid\nStandardFilterWatcher\n::StartFilter()\n{\n m_TimeProbe.Start();\n std::cout << (m_Process.GetPointer() ? m_Process->GetNameOfClass() : \"None\")\n << \" \\\"\" << m_Comment << \"\\\" \" << std::endl;\n}\n\nvoid\nStandardFilterWatcher\n::EndFilter()\n{\n m_TimeProbe.Stop();\n std::cout << std::endl << \"Filter took \"\n << m_TimeProbe.GetMeanTime()\n << \" seconds.\" << std::endl;\n}\n\n} \/\/ end namespace otb\nBUG: Fixed a bug on string creation for standard filter watcher\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbStandardFilterWatcher.h\"\n\nnamespace otb\n{\n\nStandardFilterWatcher\n::StandardFilterWatcher(itk::ProcessObject* process,\n const char *comment)\n : FilterWatcherBase(process, comment)\n{\n m_StarsCount = 50;\n}\n\nStandardFilterWatcher\n::StandardFilterWatcher( const StandardFilterWatcher& watch)\n{\n \/\/ Initialize state\n m_StarsCount = watch.m_StarsCount;\n}\n\nvoid\nStandardFilterWatcher\n::operator=(const StandardFilterWatcher &watch)\n{\n \/\/ Initialize state\n m_StarsCount = watch.m_StarsCount;\n}\n\nvoid\nStandardFilterWatcher\n::ShowProgress()\n{\n if (m_Process)\n {\n int progressPercent = static_cast(m_Process->GetProgress()*100);\n int nbStars = static_cast(m_Process->GetProgress()*m_StarsCount);\n int nbBlanks = m_StarsCount - nbStars;\n\n if(nbBlanks < 0)\n {\n nbBlanks = 0;\n }\n\n if(nbStars > m_StarsCount)\n {\n nbStars = m_StarsCount;\n }\n\n if(progressPercent > 100)\n {\n progressPercent = 100;\n }\n\n std::string stars(nbStars,'*');\n std::string blanks(nbBlanks,' ');\n std::cout << \"\\rProcessing progress: \" << progressPercent << \"% [\" << stars << blanks<< \"]\" << std::flush;\n }\n}\n\nvoid\nStandardFilterWatcher\n::StartFilter()\n{\n m_TimeProbe.Start();\n std::cout << (m_Process.GetPointer() ? m_Process->GetNameOfClass() : \"None\")\n << \" \\\"\" << m_Comment << \"\\\" \" << std::endl;\n}\n\nvoid\nStandardFilterWatcher\n::EndFilter()\n{\n m_TimeProbe.Stop();\n std::cout << std::endl << \"Filter took \"\n << m_TimeProbe.GetMeanTime()\n << \" seconds.\" << std::endl;\n}\n} \/\/ end namespace otb\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pages.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: kz $ $Date: 2008-03-06 18:49:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _PAGES_HXX_\n#define _PAGES_HXX_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace desktop\n{\nclass WelcomePage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n svt::OWizardMachine *m_pParent;\n sal_Bool m_bLicenseNeedsAcceptance;\n enum OEMType\n {\n OEM_NONE, OEM_NORMAL, OEM_EXTENDED\n };\n OEMType checkOEM();\n bool bIsEvalVersion;\n bool bNoEvalText;\n void checkEval();\n\n\npublic:\n WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance );\nprotected:\n virtual void ActivatePage();\n};\n\nclass LicenseView : public MultiLineEdit, public SfxListener\n{\n BOOL mbEndReached;\n Link maEndReachedHdl;\n Link maScrolledHdl;\n\npublic:\n LicenseView( Window* pParent, const ResId& rResId );\n ~LicenseView();\n\n void ScrollDown( ScrollType eScroll );\n\n BOOL IsEndReached() const;\n BOOL EndReached() const { return mbEndReached; }\n void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }\n\n void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; }\n const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }\n\n void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; }\n const Link& GetScrolledHdl() const { return maScrolledHdl; }\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\nprotected:\n using MultiLineEdit::Notify;\n};\n\nclass LicensePage : public svt::OWizardPage\n{\nprivate:\n svt::OWizardMachine *m_pParent;\n FixedText m_ftHead;\n FixedText m_ftBody1;\n FixedText m_ftBody1Txt;\n FixedText m_ftBody2;\n FixedText m_ftBody2Txt;\n LicenseView m_mlLicense;\n PushButton m_pbDown;\n sal_Bool m_bLicenseRead;\npublic:\n LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath );\nprivate:\n DECL_LINK(PageDownHdl, PushButton*);\n DECL_LINK(EndReachedHdl, LicenseView*);\n DECL_LINK(ScrolledHdl, LicenseView*);\nprotected:\n virtual bool canAdvance() const;\n virtual void ActivatePage();\n};\n\nclass MigrationPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n CheckBox m_cbMigration;\n sal_Bool m_bMigrationDone;\npublic:\n MigrationPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\nprotected:\n virtual void ActivatePage();\n};\n\nclass UserPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n FixedText m_ftFirst;\n Edit m_edFirst;\n FixedText m_ftLast;\n Edit m_edLast;\n FixedText m_ftInitials;\n Edit m_edInitials;\n FixedText m_ftFather;\n Edit m_edFather;\n LanguageType m_lang;\n\npublic:\n UserPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\nprotected:\n virtual void ActivatePage();\n};\n\nclass UpdateCheckPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n CheckBox m_cbUpdateCheck;\npublic:\n UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\nprotected:\n virtual void ActivatePage();\n};\n\n\nclass RegistrationPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHeader;\n FixedText m_ftBody;\n FixedImage m_fiImage;\n RadioButton m_rbNow;\n RadioButton m_rbLater;\n RadioButton m_rbNever;\n RadioButton m_rbReg;\n FixedLine m_flSeparator;\n FixedText m_ftEnd;\n\n sal_Bool m_bNeverVisible;\n\n void updateButtonStates();\n void impl_retrieveConfigurationData();\n\nprotected:\n virtual bool canAdvance() const;\n virtual void ActivatePage();\n\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\npublic:\n RegistrationPage( Window* parent, const ResId& resid);\n\n enum RegistrationMode\n {\n rmNow, \/\/ register now\n rmLater, \/\/ register later\n rmNever, \/\/ register never\n rmAlready \/\/ already registered\n };\n\n RegistrationMode getRegistrationMode() const;\n void prepareSingleMode();\n inline String getSingleModeTitle() const { return m_ftHeader.GetText(); }\n\n static bool hasReminderDateCome();\n static void executeSingleMode();\n};\n\n} \/\/ namespace desktop\n\n#endif \/\/ #ifndef _PAGES_HXX_\n\nINTEGRATION: CWS newregdlg (1.11.20); FILE MERGED 2008\/03\/05 13:34:10 pb 1.11.20.2: fix: #i86683# syntax error fixed 2008\/03\/05 13:22:25 pb 1.11.20.1: fix: #i86683# Registration tabpage changed\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pages.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 08:46:31 $\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 _PAGES_HXX_\n#define _PAGES_HXX_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace desktop\n{\nclass WelcomePage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n svt::OWizardMachine *m_pParent;\n sal_Bool m_bLicenseNeedsAcceptance;\n enum OEMType\n {\n OEM_NONE, OEM_NORMAL, OEM_EXTENDED\n };\n OEMType checkOEM();\n bool bIsEvalVersion;\n bool bNoEvalText;\n void checkEval();\n\n\npublic:\n WelcomePage( svt::OWizardMachine* parent, const ResId& resid, sal_Bool bLicenseNeedsAcceptance );\nprotected:\n virtual void ActivatePage();\n};\n\nclass LicenseView : public MultiLineEdit, public SfxListener\n{\n BOOL mbEndReached;\n Link maEndReachedHdl;\n Link maScrolledHdl;\n\npublic:\n LicenseView( Window* pParent, const ResId& rResId );\n ~LicenseView();\n\n void ScrollDown( ScrollType eScroll );\n\n BOOL IsEndReached() const;\n BOOL EndReached() const { return mbEndReached; }\n void SetEndReached( BOOL bEnd ) { mbEndReached = bEnd; }\n\n void SetEndReachedHdl( const Link& rHdl ) { maEndReachedHdl = rHdl; }\n const Link& GetAutocompleteHdl() const { return maEndReachedHdl; }\n\n void SetScrolledHdl( const Link& rHdl ) { maScrolledHdl = rHdl; }\n const Link& GetScrolledHdl() const { return maScrolledHdl; }\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\nprotected:\n using MultiLineEdit::Notify;\n};\n\nclass LicensePage : public svt::OWizardPage\n{\nprivate:\n svt::OWizardMachine *m_pParent;\n FixedText m_ftHead;\n FixedText m_ftBody1;\n FixedText m_ftBody1Txt;\n FixedText m_ftBody2;\n FixedText m_ftBody2Txt;\n LicenseView m_mlLicense;\n PushButton m_pbDown;\n sal_Bool m_bLicenseRead;\npublic:\n LicensePage( svt::OWizardMachine* parent, const ResId& resid, const rtl::OUString &rLicensePath );\nprivate:\n DECL_LINK(PageDownHdl, PushButton*);\n DECL_LINK(EndReachedHdl, LicenseView*);\n DECL_LINK(ScrolledHdl, LicenseView*);\nprotected:\n virtual bool canAdvance() const;\n virtual void ActivatePage();\n};\n\nclass MigrationPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n CheckBox m_cbMigration;\n sal_Bool m_bMigrationDone;\npublic:\n MigrationPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\nprotected:\n virtual void ActivatePage();\n};\n\nclass UserPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n FixedText m_ftFirst;\n Edit m_edFirst;\n FixedText m_ftLast;\n Edit m_edLast;\n FixedText m_ftInitials;\n Edit m_edInitials;\n FixedText m_ftFather;\n Edit m_edFather;\n LanguageType m_lang;\n\npublic:\n UserPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\nprotected:\n virtual void ActivatePage();\n};\n\nclass UpdateCheckPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHead;\n FixedText m_ftBody;\n CheckBox m_cbUpdateCheck;\npublic:\n UpdateCheckPage( svt::OWizardMachine* parent, const ResId& resid);\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\nprotected:\n virtual void ActivatePage();\n};\n\n\nclass RegistrationPage : public svt::OWizardPage\n{\nprivate:\n FixedText m_ftHeader;\n FixedText m_ftBody;\n RadioButton m_rbNow;\n RadioButton m_rbLater;\n RadioButton m_rbNever;\n FixedLine m_flSeparator;\n FixedText m_ftEnd;\n\n sal_Bool m_bNeverVisible;\n\n void updateButtonStates();\n void impl_retrieveConfigurationData();\n\nprotected:\n virtual bool canAdvance() const;\n virtual void ActivatePage();\n\n virtual sal_Bool commitPage( CommitPageReason _eReason );\n\npublic:\n RegistrationPage( Window* parent, const ResId& resid);\n\n enum RegistrationMode\n {\n rmNow, \/\/ register now\n rmLater, \/\/ register later\n rmNever \/\/ register never\n };\n\n RegistrationMode getRegistrationMode() const;\n void prepareSingleMode();\n inline String getSingleModeTitle() const { return m_ftHeader.GetText(); }\n\n static bool hasReminderDateCome();\n static void executeSingleMode();\n};\n\n} \/\/ namespace desktop\n\n#endif \/\/ #ifndef _PAGES_HXX_\n\n<|endoftext|>"} {"text":"\/*\nCopyright (C) 2011 by Ivan Safrin\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#include \"PolyGLSLProgram.h\"\n#include \"PolyVector3.h\"\n#include \"PolyVector2.h\"\n#include \"PolyColor.h\"\n#include \"PolyLogger.h\"\n#include \"PolyCoreServices.h\"\n#include \"PolyLogger.h\"\n\n#ifdef _WINDOWS\n#include \n\n\/\/ Some shader functions that aren't defined in glext\/wglext\nextern PFNGLGETSHADERIVPROC glGetShaderiv;\nextern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;\n\n#endif\n\n#include \"PolyGLHeaders.h\"\n\nusing std::vector;\n\n#ifdef _WINDOWS\nextern PFNGLUSEPROGRAMPROC glUseProgram;\nextern PFNGLUNIFORM1IPROC glUniform1i;\nextern PFNGLACTIVETEXTUREPROC glActiveTexture;\nextern PFNGLCREATESHADERPROC glCreateShader;\nextern PFNGLSHADERSOURCEPROC glShaderSource;\nextern PFNGLCOMPILESHADERPROC glCompileShader;\nextern PFNGLCREATEPROGRAMPROC glCreateProgram;\nextern PFNGLATTACHSHADERPROC glAttachShader;\nextern PFNGLLINKPROGRAMPROC glLinkProgram;\nextern PFNGLDETACHSHADERPROC glDetachShader;\nextern PFNGLDELETESHADERPROC glDeleteShader;\nextern PFNGLDELETEPROGRAMPROC glDeleteProgram;\n#ifndef _MINGW\nextern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;\n#endif\n#endif\n\nusing namespace Polycode;\n\nGLSLProgram::GLSLProgram(String fileName, int type) : ShaderProgram(type) {\n\tprogram = -1;\n\tthis->fileName = fileName;\n\treloadProgram();\n}\n\nGLSLProgram::~GLSLProgram() {\n\tglDeleteShader(program);\n}\n\nvoid GLSLProgram::reloadProgram() {\n\tif(program != -1)\n\t\tglDeleteShader(program);\n\t\t\n\tOSFILE *file = OSBasics::open(fileName, \"r\");\n\tOSBasics::seek(file, 0, SEEK_END);\t\n\tlong progsize = OSBasics::tell(file);\n\tOSBasics::seek(file, 0, SEEK_SET);\n\tchar *buffer = (char*)malloc(progsize+1);\n\tmemset(buffer, 0, progsize+1);\n\tOSBasics::read(buffer, progsize, 1, file);\n\tOSBasics::close(file);\n\t\n\tif(type == GLSLProgram::TYPE_VERT) {\n\t\tprogram = glCreateShader(GL_VERTEX_SHADER);\n\t} else {\n\t\tprogram = glCreateShader(GL_FRAGMENT_SHADER);\n\t}\n\t\n\tglShaderSource(program, 1, (const GLchar**)&buffer, 0);\n\tglCompileShader(program);\t\n\t\n\tGLint compiled = true;\n glGetShaderiv(program, GL_COMPILE_STATUS, &compiled);\n if(!compiled) {\n GLint length;\n GLchar* log;\n glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);\n log = (GLchar*)malloc(length);\n glGetShaderInfoLog(program, length, &length, log);\n\t\tprintf(\"GLSL ERROR: %s\\n\", log);\n\t\tCoreServices::getInstance()->getLogger()->logBroadcast(\"GLSL ERROR:\" + String(log));\n free(log);\n }\t\n\tfree(buffer);\n}Fixed a missing header.\/*\nCopyright (C) 2011 by Ivan Safrin\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#include \"PolyGLSLProgram.h\"\n#include \"PolyVector3.h\"\n#include \"PolyVector2.h\"\n#include \"PolyColor.h\"\n#include \"PolyLogger.h\"\n#include \"PolyCoreServices.h\"\n#include \"PolyLogger.h\"\n#include \"PolyGLHeaders.h\"\n\n#ifdef _WINDOWS\n#include \n\n\/\/ Some shader functions that aren't defined in glext\/wglext\nextern PFNGLGETSHADERIVPROC glGetShaderiv;\nextern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog;\n\n#endif\n\n#include \"PolyGLHeaders.h\"\n\nusing std::vector;\n\n#ifdef _WINDOWS\nextern PFNGLUSEPROGRAMPROC glUseProgram;\nextern PFNGLUNIFORM1IPROC glUniform1i;\nextern PFNGLACTIVETEXTUREPROC glActiveTexture;\nextern PFNGLCREATESHADERPROC glCreateShader;\nextern PFNGLSHADERSOURCEPROC glShaderSource;\nextern PFNGLCOMPILESHADERPROC glCompileShader;\nextern PFNGLCREATEPROGRAMPROC glCreateProgram;\nextern PFNGLATTACHSHADERPROC glAttachShader;\nextern PFNGLLINKPROGRAMPROC glLinkProgram;\nextern PFNGLDETACHSHADERPROC glDetachShader;\nextern PFNGLDELETESHADERPROC glDeleteShader;\nextern PFNGLDELETEPROGRAMPROC glDeleteProgram;\n#ifndef _MINGW\nextern PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocation;\n#endif\n#endif\n\nusing namespace Polycode;\n\nGLSLProgram::GLSLProgram(String fileName, int type) : ShaderProgram(type) {\n\tprogram = -1;\n\tthis->fileName = fileName;\n\treloadProgram();\n}\n\nGLSLProgram::~GLSLProgram() {\n\tglDeleteShader(program);\n}\n\nvoid GLSLProgram::reloadProgram() {\n\tif(program != -1)\n\t\tglDeleteShader(program);\n\t\t\n\tOSFILE *file = OSBasics::open(fileName, \"r\");\n\tOSBasics::seek(file, 0, SEEK_END);\t\n\tlong progsize = OSBasics::tell(file);\n\tOSBasics::seek(file, 0, SEEK_SET);\n\tchar *buffer = (char*)malloc(progsize+1);\n\tmemset(buffer, 0, progsize+1);\n\tOSBasics::read(buffer, progsize, 1, file);\n\tOSBasics::close(file);\n\t\n\tif(type == GLSLProgram::TYPE_VERT) {\n\t\tprogram = glCreateShader(GL_VERTEX_SHADER);\n\t} else {\n\t\tprogram = glCreateShader(GL_FRAGMENT_SHADER);\n\t}\n\t\n\tglShaderSource(program, 1, (const GLchar**)&buffer, 0);\n\tglCompileShader(program);\t\n\t\n\tGLint compiled = true;\n glGetShaderiv(program, GL_COMPILE_STATUS, &compiled);\n if(!compiled) {\n GLint length;\n GLchar* log;\n glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);\n log = (GLchar*)malloc(length);\n glGetShaderInfoLog(program, length, &length, log);\n\t\tprintf(\"GLSL ERROR: %s\\n\", log);\n\t\tCoreServices::getInstance()->getLogger()->logBroadcast(\"GLSL ERROR:\" + String(log));\n free(log);\n }\t\n\tfree(buffer);\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkSplineVtkMapper3D.h\"\n#include \n#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\nmitk::SplineVtkMapper3D::SplineVtkMapper3D()\n: m_SplinesAvailable (false), m_SplinesAddedToAssembly(false) \n{\n m_SplinesActor = vtkActor::New();\n m_SplineAssembly = vtkPropAssembly::New();\n m_SplineResolution = 500;\n}\n\n\nmitk::SplineVtkMapper3D::~SplineVtkMapper3D()\n{\n m_SplinesActor->Delete();\n m_SplineAssembly->Delete();\n}\n\nvtkProp*\nmitk::SplineVtkMapper3D::GetProp()\n{\n if (GetDataTreeNode() == NULL)\n return NULL; \n\n \/\/to assign User Transforms in superclass\n Superclass::GetProp();\n\n m_SplinesActor->SetUserTransform( GetDataTreeNode()->GetVtkTransform() );\n \n return m_SplineAssembly;\n}\n\n\nvoid\nmitk::SplineVtkMapper3D::GenerateData()\n{\n Superclass::GenerateData();\n\n \/\/ only update spline if UpdateSpline has not been called from\n \/\/ external, e.g. by the SplineMapper2D.\n if ( m_SplineUpdateTime < m_LastUpdateTime ) \n {\n UpdateSpline();\n this->ApplyProperties();\n }\n\n if ( m_SplinesAvailable )\n {\n if ( ! m_SplinesAddedToAssembly )\n {\n m_SplineAssembly->AddPart( m_SplinesActor );\n m_SplinesAddedToAssembly = true;\n }\n }\n else\n {\n if ( m_SplinesAddedToAssembly )\n {\n m_SplineAssembly->RemovePart( m_SplinesActor );\n m_SplinesAddedToAssembly = false; \n }\n }\n}\n\n\nvoid mitk::SplineVtkMapper3D::GenerateData( mitk::BaseRenderer* renderer )\n{\n if ( IsVisible( renderer ) == false )\n {\n m_SplinesActor->VisibilityOff();\n m_SplineAssembly->VisibilityOff();\n }\n else\n {\n m_SplinesActor->VisibilityOn();\n m_SplineAssembly->VisibilityOn();\n\n \/\/remove the PointsAssembly if it was added insuperclass. No need to display points and spline!\n if(m_SplineAssembly->GetParts()->IsItemPresent(m_PointsAssembly))\n m_SplineAssembly->RemovePart(m_PointsAssembly);\n this->ApplyProperties();\n \n }\n}\n\n\nvoid mitk::SplineVtkMapper3D::ApplyProperties()\n{\n\/\/todo: only call if needed and properties have been changed!!!\n\n\n \/\/vtk changed the type of rgba during releases. Due to that, the following convert is done\n vtkFloatingPointType rgba[ 4 ] = {1.0f, 1.0f, 1.0f, 1.0f};\/\/white\n\n \/\/getting the color from DataTreeNode\n float temprgba[4];\n this->GetDataTreeNode()->GetColor( &temprgba[0], NULL );\n \/\/convert to rgba, what ever type it has!\n rgba[0] = temprgba[0]; rgba[1] = temprgba[1]; rgba[2] = temprgba[2]; rgba[3] = temprgba[3];\n \/\/finaly set the color inside the actor\n m_SplinesActor->GetProperty()->SetColor( rgba );\n\n float lineWidth;\n if (dynamic_cast(this->GetDataTreeNode()->GetProperty(\"linewidth\").GetPointer()) == NULL)\n lineWidth = 1.0;\n else\n lineWidth = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"linewidth\").GetPointer())->GetValue();\n m_SplinesActor->GetProperty()->SetLineWidth(lineWidth);\n}\n\n\nbool mitk::SplineVtkMapper3D::SplinesAreAvailable()\n{\n return m_SplinesAvailable;\n}\n\n\nvtkPolyData* mitk::SplineVtkMapper3D::GetSplinesPolyData()\n{\n Mapper::Update(NULL);\n if ( m_SplinesAvailable )\n return ( dynamic_cast( m_SplinesActor->GetMapper() ) )->GetInput();\n else\n return NULL;\n}\n\nvtkActor* mitk::SplineVtkMapper3D::GetSplinesActor()\n{\n Mapper::Update(NULL);\n if ( m_SplinesAvailable )\n return m_SplinesActor;\n else\n return vtkActor::New();\n}\n\nunsigned long mitk::SplineVtkMapper3D::GetLastUpdateTime() const\n{\n return m_LastUpdateTime.GetMTime();\n}\n\nvoid mitk::SplineVtkMapper3D::UpdateSpline()\n{\n mitk::PointSet::Pointer input = const_cast( this->GetInput( ) );\n\/\/ input->Update();\/\/already done in superclass\n\n \/\/ Number of points on the spline\n unsigned int numberOfOutputPoints = m_SplineResolution;\n unsigned int numberOfInputPoints = input->GetSize();\n\n\n if ( numberOfInputPoints >= 2 )\n {\n m_SplinesAvailable = true;\n vtkCardinalSpline* splineX = vtkCardinalSpline::New();\n vtkCardinalSpline* splineY = vtkCardinalSpline::New();\n vtkCardinalSpline* splineZ = vtkCardinalSpline::New();\n unsigned int index = 0;\n mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = input->GetPointSet()->GetPoints();\n for ( mitk::PointSet::DataType::PointsContainer::Iterator it = pointsContainer->Begin(); it != pointsContainer->End(); ++it, ++index )\n \/\/for ( unsigned int i = 0 ; i < numberOfInputPoints; ++i )\n {\n mitk::PointSet::PointType point = it->Value();\n splineX->AddPoint( index, point[ 0 ] );\n splineY->AddPoint( index, point[ 1 ] );\n splineZ->AddPoint( index, point[ 2 ] );\n }\n vtkPoints* points = vtkPoints::New();\n vtkPolyData* profileData = vtkPolyData::New();\n\n\n \/\/ Interpolate x, y and z by using the three spline filters and\n \/\/ create new points\n double t = 0.0f;\n for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )\n {\n t = ( ( ( ( double ) numberOfInputPoints ) - 1.0f ) \/ ( ( ( double ) numberOfOutputPoints ) - 1.0f ) ) * ( ( double ) i );\n points->InsertPoint( i, splineX->Evaluate( t ), splineY->Evaluate( t ), splineZ->Evaluate( t ) ) ;\n }\n\n \/\/ Create the polyline.\n vtkCellArray* lines = vtkCellArray::New();\n lines->InsertNextCell( numberOfOutputPoints );\n for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )\n lines->InsertCellPoint( i );\n\n profileData->SetPoints( points );\n profileData->SetLines( lines );\n\n \/\/ Add thickness to the resulting line.\n \/\/vtkTubeFilter* profileTubes = vtkTubeFilter::New();\n \/\/profileTubes->SetNumberOfSides(8);\n \/\/profileTubes->SetInput(profileData);\n \/\/profileTubes->SetRadius(.005);\n\n vtkPolyDataMapper* profileMapper = vtkPolyDataMapper::New();\n profileMapper->SetInput( profileData );\n\n m_SplinesActor->SetMapper( profileMapper );\n }\n else\n {\n m_SplinesAvailable = false;\n }\n m_SplineUpdateTime.Modified();\n}\n\nFIX: removed problematic call to Mapper::Update(NULL) leading to spurious segmentation faults.\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkSplineVtkMapper3D.h\"\n#include \n#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\nmitk::SplineVtkMapper3D::SplineVtkMapper3D()\n: m_SplinesAvailable (false), m_SplinesAddedToAssembly(false) \n{\n m_SplinesActor = vtkActor::New();\n m_SplineAssembly = vtkPropAssembly::New();\n m_SplineResolution = 500;\n}\n\n\nmitk::SplineVtkMapper3D::~SplineVtkMapper3D()\n{\n m_SplinesActor->Delete();\n m_SplineAssembly->Delete();\n}\n\nvtkProp*\nmitk::SplineVtkMapper3D::GetProp()\n{\n if (GetDataTreeNode() == NULL)\n return NULL; \n\n \/\/to assign User Transforms in superclass\n Superclass::GetProp();\n\n m_SplinesActor->SetUserTransform( GetDataTreeNode()->GetVtkTransform() );\n \n return m_SplineAssembly;\n}\n\n\nvoid\nmitk::SplineVtkMapper3D::GenerateData()\n{\n Superclass::GenerateData();\n\n \/\/ only update spline if UpdateSpline has not been called from\n \/\/ external, e.g. by the SplineMapper2D.\n if ( m_SplineUpdateTime < m_LastUpdateTime ) \n {\n UpdateSpline();\n this->ApplyProperties();\n }\n\n if ( m_SplinesAvailable )\n {\n if ( ! m_SplinesAddedToAssembly )\n {\n m_SplineAssembly->AddPart( m_SplinesActor );\n m_SplinesAddedToAssembly = true;\n }\n }\n else\n {\n if ( m_SplinesAddedToAssembly )\n {\n m_SplineAssembly->RemovePart( m_SplinesActor );\n m_SplinesAddedToAssembly = false; \n }\n }\n}\n\n\nvoid mitk::SplineVtkMapper3D::GenerateData( mitk::BaseRenderer* renderer )\n{\n if ( IsVisible( renderer ) == false )\n {\n m_SplinesActor->VisibilityOff();\n m_SplineAssembly->VisibilityOff();\n }\n else\n {\n m_SplinesActor->VisibilityOn();\n m_SplineAssembly->VisibilityOn();\n\n \/\/remove the PointsAssembly if it was added insuperclass. No need to display points and spline!\n if(m_SplineAssembly->GetParts()->IsItemPresent(m_PointsAssembly))\n m_SplineAssembly->RemovePart(m_PointsAssembly);\n this->ApplyProperties();\n \n }\n}\n\n\nvoid mitk::SplineVtkMapper3D::ApplyProperties()\n{\n\/\/todo: only call if needed and properties have been changed!!!\n\n\n \/\/vtk changed the type of rgba during releases. Due to that, the following convert is done\n vtkFloatingPointType rgba[ 4 ] = {1.0f, 1.0f, 1.0f, 1.0f};\/\/white\n\n \/\/getting the color from DataTreeNode\n float temprgba[4];\n this->GetDataTreeNode()->GetColor( &temprgba[0], NULL );\n \/\/convert to rgba, what ever type it has!\n rgba[0] = temprgba[0]; rgba[1] = temprgba[1]; rgba[2] = temprgba[2]; rgba[3] = temprgba[3];\n \/\/finaly set the color inside the actor\n m_SplinesActor->GetProperty()->SetColor( rgba );\n\n float lineWidth;\n if (dynamic_cast(this->GetDataTreeNode()->GetProperty(\"linewidth\").GetPointer()) == NULL)\n lineWidth = 1.0;\n else\n lineWidth = dynamic_cast(this->GetDataTreeNode()->GetProperty(\"linewidth\").GetPointer())->GetValue();\n m_SplinesActor->GetProperty()->SetLineWidth(lineWidth);\n}\n\n\nbool mitk::SplineVtkMapper3D::SplinesAreAvailable()\n{\n return m_SplinesAvailable;\n}\n\n\nvtkPolyData* mitk::SplineVtkMapper3D::GetSplinesPolyData()\n{\n if ( m_SplinesAvailable )\n return ( dynamic_cast( m_SplinesActor->GetMapper() ) )->GetInput();\n else\n return NULL;\n}\n\nvtkActor* mitk::SplineVtkMapper3D::GetSplinesActor()\n{\n if ( m_SplinesAvailable )\n return m_SplinesActor;\n else\n return vtkActor::New();\n}\n\nunsigned long mitk::SplineVtkMapper3D::GetLastUpdateTime() const\n{\n return m_LastUpdateTime.GetMTime();\n}\n\nvoid mitk::SplineVtkMapper3D::UpdateSpline()\n{\n mitk::PointSet::Pointer input = const_cast( this->GetInput( ) );\n\/\/ input->Update();\/\/already done in superclass\n\n \/\/ Number of points on the spline\n unsigned int numberOfOutputPoints = m_SplineResolution;\n unsigned int numberOfInputPoints = input->GetSize();\n\n\n if ( numberOfInputPoints >= 2 )\n {\n m_SplinesAvailable = true;\n vtkCardinalSpline* splineX = vtkCardinalSpline::New();\n vtkCardinalSpline* splineY = vtkCardinalSpline::New();\n vtkCardinalSpline* splineZ = vtkCardinalSpline::New();\n unsigned int index = 0;\n mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = input->GetPointSet()->GetPoints();\n for ( mitk::PointSet::DataType::PointsContainer::Iterator it = pointsContainer->Begin(); it != pointsContainer->End(); ++it, ++index )\n \/\/for ( unsigned int i = 0 ; i < numberOfInputPoints; ++i )\n {\n mitk::PointSet::PointType point = it->Value();\n splineX->AddPoint( index, point[ 0 ] );\n splineY->AddPoint( index, point[ 1 ] );\n splineZ->AddPoint( index, point[ 2 ] );\n }\n vtkPoints* points = vtkPoints::New();\n vtkPolyData* profileData = vtkPolyData::New();\n\n\n \/\/ Interpolate x, y and z by using the three spline filters and\n \/\/ create new points\n double t = 0.0f;\n for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )\n {\n t = ( ( ( ( double ) numberOfInputPoints ) - 1.0f ) \/ ( ( ( double ) numberOfOutputPoints ) - 1.0f ) ) * ( ( double ) i );\n points->InsertPoint( i, splineX->Evaluate( t ), splineY->Evaluate( t ), splineZ->Evaluate( t ) ) ;\n }\n\n \/\/ Create the polyline.\n vtkCellArray* lines = vtkCellArray::New();\n lines->InsertNextCell( numberOfOutputPoints );\n for ( unsigned int i = 0; i < numberOfOutputPoints; ++i )\n lines->InsertCellPoint( i );\n\n profileData->SetPoints( points );\n profileData->SetLines( lines );\n\n \/\/ Add thickness to the resulting line.\n \/\/vtkTubeFilter* profileTubes = vtkTubeFilter::New();\n \/\/profileTubes->SetNumberOfSides(8);\n \/\/profileTubes->SetInput(profileData);\n \/\/profileTubes->SetRadius(.005);\n\n vtkPolyDataMapper* profileMapper = vtkPolyDataMapper::New();\n profileMapper->SetInput( profileData );\n\n m_SplinesActor->SetMapper( profileMapper );\n }\n else\n {\n m_SplinesAvailable = false;\n }\n m_SplineUpdateTime.Modified();\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.17 2007\/01\/30 11:55:33 brun Exp $\n\/\/ Author: Fons Rademakers 12\/02\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootContextMenu \/\/\n\/\/ \/\/\n\/\/ This class provides an interface to context sensitive popup menus. \/\/\n\/\/ These menus pop up when the user hits the right mouse button, and \/\/\n\/\/ are destroyed when the menu pops downs. \/\/\n\/\/ The picture below shows a canvas with a pop-up menu. \/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/ The picture below shows a canvas with a pop-up menu and a dialog box.\/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootContextMenu.h\"\n#include \"TROOT.h\"\n#include \"TGClient.h\"\n#include \"TList.h\"\n#include \"TContextMenu.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"TCanvas.h\"\n#include \"TDataMember.h\"\n#include \"TToggle.h\"\n#include \"TRootDialog.h\"\n#include \"TDataType.h\"\n#include \"TCanvas.h\"\n#include \"TBrowser.h\"\n#include \"TRootCanvas.h\"\n#include \"TRootBrowser.h\"\n#include \"TClassMenuItem.h\"\n#include \"TObjectSpy.h\"\n\nenum EContextMenu {\n kToggleStart = 1000, \/\/ first id of toggle menu items\n kToggleListStart = 2000, \/\/ first id of toggle list menu items\n kUserFunctionStart = 3000 \/\/ first id of user added functions\/methods, etc...\n};\n\n\nClassImp(TRootContextMenu)\n\n\/\/______________________________________________________________________________\nTRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)\n : TGPopupMenu(gClient->GetDefaultRoot()), TContextMenuImp(c)\n{\n \/\/ Create context menu.\n\n fDialog = 0;\n fTrash = new TList;\n\n \/\/ Context menu handles its own messages\n Associate(this);\n}\n\n\/\/______________________________________________________________________________\nTRootContextMenu::~TRootContextMenu()\n{\n \/\/ Delete a context menu.\n\n delete fDialog;\n if (fTrash) fTrash->Delete();\n delete fTrash;\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::DisplayPopup(Int_t x, Int_t y)\n{\n \/\/ Display context popup menu for currently selected object.\n\n if (fClient->IsEditable()) return;\n\n \/\/ delete menu items releated to previous object and reset menu size\n if (fEntryList) fEntryList->Delete();\n if (fTrash) fTrash->Delete();\n fMenuHeight = 6;\n fMenuWidth = 8;\n\n \/\/ delete previous dialog\n if (fDialog) {\n delete fDialog;\n fDialog = 0;\n }\n\n \/\/ add menu items to popup menu\n CreateMenu(fContextMenu->GetSelectedObject());\n\n int xx, yy, topx = 0, topy = 0;\n UInt_t w, h;\n\n if (fContextMenu->GetSelectedCanvas())\n gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),\n topx, topy, w, h);\n\n xx = topx + x + 1;\n yy = topy + y + 1;\n\n PlaceMenu(xx, yy, kFALSE, kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::CreateMenu(TObject *object)\n{\n \/\/ Create the context menu depending on the selected object.\n\n if (fClient->IsEditable()) return;\n\n int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;\n int userfunction = kUserFunctionStart;\n\n \/\/ Add a title\n AddLabel(fContextMenu->CreatePopupTitle(object));\n AddSeparator();\n\n \/\/ Get list of menu items from the selected object's class\n TList *menuItemList = object->IsA()->GetMenuList();\n\n TClassMenuItem *menuItem;\n TIter nextItem(menuItemList);\n\n while ((menuItem = (TClassMenuItem*) nextItem())) {\n switch (menuItem->GetType()) {\n case TClassMenuItem::kPopupSeparator:\n AddSeparator();\n break;\n case TClassMenuItem::kPopupStandardList:\n {\n \/\/ Standard list of class methods. Rebuild from scratch.\n \/\/ Get linked list of objects menu items (i.e. member functions\n \/\/ with the token *MENU in their comment fields.\n TList *methodList = new TList;\n object->IsA()->GetMenuItems(methodList);\n\n TMethod *method;\n TClass *classPtr = 0;\n TIter next(methodList);\n\n while ((method = (TMethod*) next())) {\n if (classPtr != method->GetClass()) {\n AddSeparator();\n classPtr = method->GetClass();\n }\n\n TDataMember *m;\n EMenuItemKind menuKind = method->IsMenuItem();\n switch (menuKind) {\n case kMenuDialog:\n AddEntry(method->GetName(), entry++, method);\n break;\n case kMenuSubMenu:\n if ((m = method->FindDataMember())) {\n if (m->GetterMethod()) {\n TGPopupMenu *r = new TGPopupMenu(gClient->GetDefaultRoot());\n AddPopup(method->GetName(), r);\n fTrash->Add(r);\n TIter nxt(m->GetOptions());\n TOptionListItem *it;\n while ((it = (TOptionListItem*) nxt())) {\n char *name = it->fOptName;\n Long_t val = it->fValue;\n\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(val);\n fTrash->Add(t);\n\n r->AddSeparator();\n r->AddEntry(name, togglelist++, t);\n if (t->GetState()) r->CheckEntry(togglelist-1);\n\n }\n } else {\n AddEntry(method->GetName(), entry++, method);\n }\n }\n break;\n\n case kMenuToggle:\n {\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n }\n break;\n\n default:\n break;\n }\n }\n delete methodList;\n }\n break;\n case TClassMenuItem::kPopupUserFunction:\n {\n if (menuItem->IsToggle()) {\n if (object) {\n TMethod* method =\n object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n } else {\n Warning(\"Dialog\",\"Cannot use toggle for a global function\");\n }\n } else {\n const char* menuItemTitle = menuItem->GetTitle();\n if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();\n AddEntry(menuItemTitle,userfunction++,menuItem);\n }\n }\n break;\n default:\n break;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TMethod *method)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"method\".\n\n Dialog(object,(TFunction*)method);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TFunction *function)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"function\".\n \/\/ function may be a global function or a method\n\n Int_t selfobjpos;\n\n if (!function) return;\n\n \/\/ Position, if it exists, of the argument that correspond to the object itself\n if (fContextMenu->GetSelectedMenuItem())\n selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();\n else selfobjpos = -1;\n\n const TGWindow *w;\n if (fContextMenu->GetSelectedCanvas()) {\n TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();\n \/\/ Embedded canvas has no canvasimp that is a TGFrame\n if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) {\n w = fClient->GetWindowById(gVirtualX->GetWindowID(c->GetCanvasID()));\n if (!w) w = (TRootCanvas *) c->GetCanvasImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n } else if (fContextMenu->GetBrowser()) {\n TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();\n w = (TRootBrowser *) b->GetBrowserImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));\n\n \/\/ iterate through all arguments and create apropriate input-data objects:\n \/\/ inputlines, option menus...\n TMethodArg *argument = 0;\n\n TIter next(function->GetListOfMethodArgs());\n Int_t argpos = 0;\n\n while ((argument = (TMethodArg *) next())) {\n \/\/ Do not input argument for self object\n if (selfobjpos != argpos) {\n Text_t *argname = fContextMenu->CreateArgumentTitle(argument);\n const Text_t *type = argument->GetTypeName();\n TDataType *datatype = gROOT->GetType(type);\n Text_t basictype[32];\n\n if (datatype) {\n strcpy(basictype, datatype->GetTypeName());\n } else {\n TClass *cl = TClass::GetClass(type);\n if (strncmp(type, \"enum\", 4) && (cl && !(cl->Property() & kIsEnum)))\n Warning(\"Dialog\", \"data type is not basic type, assuming (int)\");\n strcpy(basictype, \"int\");\n }\n\n if (strchr(argname, '*')) {\n strcat(basictype, \"*\");\n }\n\n TDataMember *m = argument->GetDataMember();\n if (m && m->GetterMethod(object->IsA())) {\n\n \/\/ Get the current value and form it as a text:\n\n Text_t val[256];\n\n if (!strncmp(basictype, \"char*\", 5)) {\n Text_t *tdefval;\n m->GetterMethod()->Execute(object, \"\", &tdefval);\n strncpy(val, tdefval, 255);\n } else if (!strncmp(basictype, \"float\", 5) ||\n !strncmp(basictype, \"double\", 6)) {\n Double_t ddefval;\n m->GetterMethod()->Execute(object, \"\", ddefval);\n sprintf(val, \"%g\", ddefval);\n } else if (!strncmp(basictype, \"char\", 4) ||\n !strncmp(basictype, \"bool\", 4) ||\n !strncmp(basictype, \"int\", 3) ||\n !strncmp(basictype, \"long\", 4) ||\n !strncmp(basictype, \"short\", 5)) {\n Long_t ldefval;\n m->GetterMethod()->Execute(object, \"\", ldefval);\n sprintf(val, \"%li\", ldefval);\n }\n\n \/\/ Find out whether we have options ...\n\n TList *opt;\n if ((opt = m->GetOptions())) {\n Warning(\"Dialog\", \"option menu not yet implemented\", opt);\n#if 0\n TMotifOptionMenu *o= new TMotifOptionMenu(argname);\n TIter nextopt(opt);\n TOptionListItem *it = 0;\n while ((it = (TOptionListItem*) nextopt())) {\n Text_t *name = it->fOptName;\n Text_t *label = it->fOptLabel;\n Long_t value = it->fValue;\n if (value != -9999) {\n Text_t val[256];\n sprintf(val, \"%li\", value);\n o->AddItem(name, val);\n }else\n o->AddItem(name, label);\n }\n o->SetData(val);\n fDialog->Add(o);\n#endif\n } else {\n \/\/ we haven't got options - textfield ...\n fDialog->Add(argname, val, type);\n }\n } else { \/\/ if m not found ...\n\n char val[256] = \"\";\n const char *tval = argument->GetDefault();\n if (tval) strncpy(val, tval, 255);\n fDialog->Add(argname, val, type);\n }\n }\n argpos++;\n }\n\n fDialog->Popup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)\n{\n \/\/ Handle context menu messages.\n \n TObjectSpy savedPad;\n if (GetContextMenu()->GetSelectedPad()) {\n savedPad.SetObject(gPad);\n gPad = GetContextMenu()->GetSelectedPad();\n }\n\n switch (GET_MSG(msg)) {\n\n case kC_COMMAND:\n\n switch (GET_SUBMSG(msg)) {\n\n case kCM_MENU:\n \n if (parm1 < kToggleStart) {\n TMethod *m = (TMethod *) parm2;\n GetContextMenu()->Action(m);\n } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {\n TToggle *t = (TToggle *) parm2;\n GetContextMenu()->Action(t);\n } else if (parm1 >= kToggleListStart && parm1GetState() == 0)\n t->SetState(1);\n } else {\n TClassMenuItem *mi = (TClassMenuItem*)parm2;\n GetContextMenu()->Action(mi);\n }\n break;\n\n case kCM_BUTTON:\n if (parm1 == 1) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n if (parm1 == 2) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n }\n if (parm1 == 3) {\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n case kC_TEXTENTRY:\n\n switch (GET_SUBMSG(msg)) {\n\n case kTE_ENTER:\n {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n default:\n break;\n }\n\n if (savedPad.GetObject()) gPad = (TVirtualPad*) savedPad.GetObject();\n\n return kTRUE;\n}\n- additional fix in TRootContextMenu::Dialog to avoid side effects\/\/ @(#)root\/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.18 2007\/02\/05 11:55:38 antcheva Exp $\n\/\/ Author: Fons Rademakers 12\/02\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootContextMenu \/\/\n\/\/ \/\/\n\/\/ This class provides an interface to context sensitive popup menus. \/\/\n\/\/ These menus pop up when the user hits the right mouse button, and \/\/\n\/\/ are destroyed when the menu pops downs. \/\/\n\/\/ The picture below shows a canvas with a pop-up menu. \/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/ The picture below shows a canvas with a pop-up menu and a dialog box.\/\/\n\/\/ \/\/\n\/\/Begin_Html End_Html \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootContextMenu.h\"\n#include \"TROOT.h\"\n#include \"TGClient.h\"\n#include \"TList.h\"\n#include \"TContextMenu.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TClass.h\"\n#include \"TVirtualX.h\"\n#include \"TCanvas.h\"\n#include \"TDataMember.h\"\n#include \"TToggle.h\"\n#include \"TRootDialog.h\"\n#include \"TDataType.h\"\n#include \"TCanvas.h\"\n#include \"TBrowser.h\"\n#include \"TRootCanvas.h\"\n#include \"TRootBrowser.h\"\n#include \"TClassMenuItem.h\"\n#include \"TObjectSpy.h\"\n\nenum EContextMenu {\n kToggleStart = 1000, \/\/ first id of toggle menu items\n kToggleListStart = 2000, \/\/ first id of toggle list menu items\n kUserFunctionStart = 3000 \/\/ first id of user added functions\/methods, etc...\n};\n\n\nClassImp(TRootContextMenu)\n\n\/\/______________________________________________________________________________\nTRootContextMenu::TRootContextMenu(TContextMenu *c, const char *)\n : TGPopupMenu(gClient->GetDefaultRoot()), TContextMenuImp(c)\n{\n \/\/ Create context menu.\n\n fDialog = 0;\n fTrash = new TList;\n\n \/\/ Context menu handles its own messages\n Associate(this);\n}\n\n\/\/______________________________________________________________________________\nTRootContextMenu::~TRootContextMenu()\n{\n \/\/ Delete a context menu.\n\n delete fDialog;\n if (fTrash) fTrash->Delete();\n delete fTrash;\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::DisplayPopup(Int_t x, Int_t y)\n{\n \/\/ Display context popup menu for currently selected object.\n\n if (fClient->IsEditable()) return;\n\n \/\/ delete menu items releated to previous object and reset menu size\n if (fEntryList) fEntryList->Delete();\n if (fTrash) fTrash->Delete();\n fMenuHeight = 6;\n fMenuWidth = 8;\n\n \/\/ delete previous dialog\n if (fDialog) {\n delete fDialog;\n fDialog = 0;\n }\n\n \/\/ add menu items to popup menu\n CreateMenu(fContextMenu->GetSelectedObject());\n\n int xx, yy, topx = 0, topy = 0;\n UInt_t w, h;\n\n if (fContextMenu->GetSelectedCanvas())\n gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(),\n topx, topy, w, h);\n\n xx = topx + x + 1;\n yy = topy + y + 1;\n\n PlaceMenu(xx, yy, kFALSE, kTRUE);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::CreateMenu(TObject *object)\n{\n \/\/ Create the context menu depending on the selected object.\n\n if (fClient->IsEditable()) return;\n\n int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart;\n int userfunction = kUserFunctionStart;\n\n \/\/ Add a title\n AddLabel(fContextMenu->CreatePopupTitle(object));\n AddSeparator();\n\n \/\/ Get list of menu items from the selected object's class\n TList *menuItemList = object->IsA()->GetMenuList();\n\n TClassMenuItem *menuItem;\n TIter nextItem(menuItemList);\n\n while ((menuItem = (TClassMenuItem*) nextItem())) {\n switch (menuItem->GetType()) {\n case TClassMenuItem::kPopupSeparator:\n AddSeparator();\n break;\n case TClassMenuItem::kPopupStandardList:\n {\n \/\/ Standard list of class methods. Rebuild from scratch.\n \/\/ Get linked list of objects menu items (i.e. member functions\n \/\/ with the token *MENU in their comment fields.\n TList *methodList = new TList;\n object->IsA()->GetMenuItems(methodList);\n\n TMethod *method;\n TClass *classPtr = 0;\n TIter next(methodList);\n\n while ((method = (TMethod*) next())) {\n if (classPtr != method->GetClass()) {\n AddSeparator();\n classPtr = method->GetClass();\n }\n\n TDataMember *m;\n EMenuItemKind menuKind = method->IsMenuItem();\n switch (menuKind) {\n case kMenuDialog:\n AddEntry(method->GetName(), entry++, method);\n break;\n case kMenuSubMenu:\n if ((m = method->FindDataMember())) {\n if (m->GetterMethod()) {\n TGPopupMenu *r = new TGPopupMenu(gClient->GetDefaultRoot());\n AddPopup(method->GetName(), r);\n fTrash->Add(r);\n TIter nxt(m->GetOptions());\n TOptionListItem *it;\n while ((it = (TOptionListItem*) nxt())) {\n char *name = it->fOptName;\n Long_t val = it->fValue;\n\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(val);\n fTrash->Add(t);\n\n r->AddSeparator();\n r->AddEntry(name, togglelist++, t);\n if (t->GetState()) r->CheckEntry(togglelist-1);\n\n }\n } else {\n AddEntry(method->GetName(), entry++, method);\n }\n }\n break;\n\n case kMenuToggle:\n {\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n }\n break;\n\n default:\n break;\n }\n }\n delete methodList;\n }\n break;\n case TClassMenuItem::kPopupUserFunction:\n {\n if (menuItem->IsToggle()) {\n if (object) {\n TMethod* method =\n object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs());\n TToggle *t = new TToggle;\n t->SetToggledObject(object, method);\n t->SetOnValue(1);\n fTrash->Add(t);\n\n AddEntry(method->GetName(), toggle++, t);\n if (t->GetState()) CheckEntry(toggle-1);\n } else {\n Warning(\"Dialog\",\"Cannot use toggle for a global function\");\n }\n } else {\n const char* menuItemTitle = menuItem->GetTitle();\n if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName();\n AddEntry(menuItemTitle,userfunction++,menuItem);\n }\n }\n break;\n default:\n break;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TMethod *method)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"method\".\n\n Dialog(object,(TFunction*)method);\n}\n\n\/\/______________________________________________________________________________\nvoid TRootContextMenu::Dialog(TObject *object, TFunction *function)\n{\n \/\/ Create dialog object with OK and Cancel buttons. This dialog\n \/\/ prompts for the arguments of \"function\".\n \/\/ function may be a global function or a method\n\n Int_t selfobjpos;\n\n if (!function) return;\n\n \/\/ Position, if it exists, of the argument that correspond to the object itself\n if (fContextMenu->GetSelectedMenuItem())\n selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos();\n else selfobjpos = -1;\n\n const TGWindow *w;\n if (fContextMenu->GetSelectedCanvas()) {\n TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas();\n \/\/ Embedded canvas has no canvasimp that is a TGFrame\n if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) {\n w = fClient->GetWindowById(gVirtualX->GetWindowID(c->GetCanvasID()));\n if (!w) w = (TRootCanvas *) c->GetCanvasImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n } else if (fContextMenu->GetBrowser()) {\n TBrowser *b = (TBrowser *) fContextMenu->GetBrowser();\n w = (TRootBrowser *) b->GetBrowserImp();\n } else {\n w = gClient->GetDefaultRoot();\n }\n fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function));\n\n \/\/ iterate through all arguments and create apropriate input-data objects:\n \/\/ inputlines, option menus...\n TMethodArg *argument = 0;\n\n TIter next(function->GetListOfMethodArgs());\n Int_t argpos = 0;\n\n while ((argument = (TMethodArg *) next())) {\n \/\/ Do not input argument for self object\n if (selfobjpos != argpos) {\n Text_t *argname = fContextMenu->CreateArgumentTitle(argument);\n const Text_t *type = argument->GetTypeName();\n TDataType *datatype = gROOT->GetType(type);\n const Text_t *charstar = \"char*\";\n Text_t basictype[32];\n\n if (datatype) {\n strcpy(basictype, datatype->GetTypeName());\n } else {\n TClass *cl = TClass::GetClass(type);\n if (strncmp(type, \"enum\", 4) && (cl && !(cl->Property() & kIsEnum)))\n Warning(\"Dialog\", \"data type is not basic type, assuming (int)\");\n strcpy(basictype, \"int\");\n }\n\n if (strchr(argname, '*')) {\n strcat(basictype, \"*\");\n if (!strncmp(type, \"char\", 4)) \n type = charstar;\n }\n \n TDataMember *m = argument->GetDataMember();\n if (m && m->GetterMethod(object->IsA())) {\n\n \/\/ Get the current value and form it as a text:\n\n Text_t val[256];\n\n if (!strncmp(basictype, \"char*\", 5)) {\n Text_t *tdefval;\n m->GetterMethod()->Execute(object, \"\", &tdefval);\n strncpy(val, tdefval, 255);\n } else if (!strncmp(basictype, \"float\", 5) ||\n !strncmp(basictype, \"double\", 6)) {\n Double_t ddefval;\n m->GetterMethod()->Execute(object, \"\", ddefval);\n sprintf(val, \"%g\", ddefval);\n } else if (!strncmp(basictype, \"char\", 4) ||\n !strncmp(basictype, \"bool\", 4) ||\n !strncmp(basictype, \"int\", 3) ||\n !strncmp(basictype, \"long\", 4) ||\n !strncmp(basictype, \"short\", 5)) {\n Long_t ldefval;\n m->GetterMethod()->Execute(object, \"\", ldefval);\n sprintf(val, \"%li\", ldefval);\n }\n\n \/\/ Find out whether we have options ...\n\n TList *opt;\n if ((opt = m->GetOptions())) {\n Warning(\"Dialog\", \"option menu not yet implemented\", opt);\n#if 0\n TMotifOptionMenu *o= new TMotifOptionMenu(argname);\n TIter nextopt(opt);\n TOptionListItem *it = 0;\n while ((it = (TOptionListItem*) nextopt())) {\n Text_t *name = it->fOptName;\n Text_t *label = it->fOptLabel;\n Long_t value = it->fValue;\n if (value != -9999) {\n Text_t val[256];\n sprintf(val, \"%li\", value);\n o->AddItem(name, val);\n }else\n o->AddItem(name, label);\n }\n o->SetData(val);\n fDialog->Add(o);\n#endif\n } else {\n \/\/ we haven't got options - textfield ...\n fDialog->Add(argname, val, type);\n }\n } else { \/\/ if m not found ...\n\n char val[256] = \"\";\n const char *tval = argument->GetDefault();\n if (tval) strncpy(val, tval, 255);\n fDialog->Add(argname, val, type);\n }\n }\n argpos++;\n }\n\n fDialog->Popup();\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2)\n{\n \/\/ Handle context menu messages.\n \n TObjectSpy savedPad;\n if (GetContextMenu()->GetSelectedPad()) {\n savedPad.SetObject(gPad);\n gPad = GetContextMenu()->GetSelectedPad();\n }\n\n switch (GET_MSG(msg)) {\n\n case kC_COMMAND:\n\n switch (GET_SUBMSG(msg)) {\n\n case kCM_MENU:\n \n if (parm1 < kToggleStart) {\n TMethod *m = (TMethod *) parm2;\n GetContextMenu()->Action(m);\n } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) {\n TToggle *t = (TToggle *) parm2;\n GetContextMenu()->Action(t);\n } else if (parm1 >= kToggleListStart && parm1GetState() == 0)\n t->SetState(1);\n } else {\n TClassMenuItem *mi = (TClassMenuItem*)parm2;\n GetContextMenu()->Action(mi);\n }\n break;\n\n case kCM_BUTTON:\n if (parm1 == 1) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n if (parm1 == 2) {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n }\n if (parm1 == 3) {\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n case kC_TEXTENTRY:\n\n switch (GET_SUBMSG(msg)) {\n\n case kTE_ENTER:\n {\n const char *args = fDialog->GetParameters();\n GetContextMenu()->Execute((char *)args);\n delete fDialog;\n fDialog = 0;\n }\n break;\n\n default:\n break;\n }\n break;\n\n default:\n break;\n }\n\n if (savedPad.GetObject()) gPad = (TVirtualPad*) savedPad.GetObject();\n\n return kTRUE;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen \n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * 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 Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"MediaLibraryTester.h\"\n\n#include \"Album.h\"\n#include \"AlbumTrack.h\"\n#include \"Artist.h\"\n#include \"Device.h\"\n#include \"Playlist.h\"\n#include \"Genre.h\"\n#include \"Media.h\"\n#include \"Folder.h\"\n#include \"Show.h\"\n#include \"mocks\/FileSystem.h\"\n#include \"parser\/Task.h\"\n\n\nMediaLibraryTester::MediaLibraryTester( const std::string& dbPath,\n const std::string& mlFolderPath )\n : MediaLibrary( dbPath, mlFolderPath )\n , dummyDevice( new mock::NoopDevice )\n , dummyDirectory( new mock::NoopDirectory )\n{\n}\n\nvoid MediaLibraryTester::onDbConnectionReady( sqlite::Connection* dbConn )\n{\n deleteAllTables( dbConn );\n}\n\nstd::shared_ptr MediaLibraryTester::media( int64_t id )\n{\n return std::static_pointer_cast( MediaLibrary::media( id ) );\n}\n\nFolderPtr MediaLibraryTester::folder( const std::string& mrl ) const\n{\n return Folder::fromMrl( this, mrl, Folder::BannedType::No );\n}\n\nFolderPtr MediaLibraryTester::folder( int64_t id ) const\n{\n return MediaLibrary::folder( id );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( const std::string& path, IMedia::Type type )\n{\n return addFile( std::make_shared( path ),\n dummyFolder, dummyDirectory, IFile::Type::Main, type );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( std::shared_ptr file, IMedia::Type type )\n{\n return addFile( std::move( file ), dummyFolder, dummyDirectory,\n IFile::Type::Main, type );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( std::shared_ptr fileFs,\n std::shared_ptr parentFolder,\n std::shared_ptr parentFolderFs,\n IFile::Type fileType,\n IMedia::Type type )\n{\n LOG_INFO( \"Adding \", fileFs->mrl() );\n auto mptr = Media::create( this, type, parentFolder->deviceId(), parentFolder->id(),\n fileFs->name(), -1 );\n if ( mptr == nullptr )\n {\n LOG_ERROR( \"Failed to add media \", fileFs->mrl(), \" to the media library\" );\n return nullptr;\n }\n \/\/ For now, assume all media are made of a single file\n auto file = mptr->addFile( *fileFs, parentFolder->id(),\n parentFolderFs->device()->isRemovable(), fileType );\n if ( file == nullptr )\n {\n LOG_ERROR( \"Failed to add file \", fileFs->mrl(), \" to media #\", mptr->id() );\n Media::destroy( this, mptr->id() );\n return nullptr;\n }\n return mptr;\n}\n\nvoid MediaLibraryTester::addLocalFsFactory()\n{\n if ( fsFactory != nullptr )\n {\n m_fsHolder.addFsFactory( fsFactory );\n }\n else\n {\n MediaLibrary::addLocalFsFactory();\n }\n}\n\nvoid MediaLibraryTester::deleteAlbum( int64_t albumId )\n{\n Album::destroy( this, albumId );\n}\n\nstd::shared_ptr MediaLibraryTester::createGenre( const std::string& name )\n{\n return Genre::create( this, name );\n}\n\nvoid MediaLibraryTester::deleteGenre( int64_t genreId )\n{\n Genre::destroy( this, genreId );\n}\n\nvoid MediaLibraryTester::deleteArtist( int64_t artistId )\n{\n Artist::destroy( this, artistId );\n}\n\nvoid MediaLibraryTester::deleteShow( int64_t showId )\n{\n Show::destroy( this, showId );\n}\n\nstd::shared_ptr MediaLibraryTester::addDevice( const std::string& uuid,\n const std::string& scheme,\n bool isRemovable )\n{\n return Device::create( this, uuid, scheme, isRemovable, false );\n}\n\nvoid MediaLibraryTester::setFsFactory( std::shared_ptr fsf )\n{\n fsFactory = fsf;\n}\n\nstd::shared_ptr MediaLibraryTester::albumTrack( int64_t id )\n{\n return AlbumTrack::fetch( this, id );\n}\n\nstd::vector MediaLibraryTester::files()\n{\n static const std::string req = \"SELECT * FROM \" + Media::Table::Name + \" WHERE is_present != 0\";\n return Media::fetchAll( this, req );\n}\n\nstd::shared_ptr MediaLibraryTester::device( const std::string& uuid,\n const std::string& scheme )\n{\n return Device::fromUuid( this, uuid, scheme );\n}\n\nvoid MediaLibraryTester::onDiscoveredFile(std::shared_ptr fileFs,\n std::shared_ptr parentFolder,\n std::shared_ptr parentFolderFs,\n IFile::Type fileType)\n{\n addFile( fileFs, parentFolder, parentFolderFs, fileType, IMedia::Type::Unknown );\n}\n\nvoid MediaLibraryTester::populateNetworkFsFactories()\n{\n}\n\nMediaPtr MediaLibraryTester::addMedia( const std::string& mrl, IMedia::Type type )\n{\n return addFile( mrl, type );\n}\n\nvoid MediaLibraryTester::deleteMedia( int64_t mediaId )\n{\n Media::destroy( this, mediaId );\n}\n\nbool MediaLibraryTester::outdateAllDevices()\n{\n std::string req = \"UPDATE \" + Device::Table::Name + \" SET last_seen = 1\";\n return sqlite::Tools::executeUpdate( getConn(), req );\n}\n\nbool MediaLibraryTester::setMediaInsertionDate( int64_t mediaId, time_t t )\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET insertion_date = ? \"\n \"WHERE id_media = ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, mediaId, t );\n}\n\nbool MediaLibraryTester::outdateAllExternalMedia()\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET last_played_date = 1 \"\n \"WHERE import_type != ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, Media::ImportType::Internal );\n}\n\nbool MediaLibraryTester::setMediaType(int64_t mediaId, IMedia::Type type)\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET type = ? WHERE id_media = ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, type, mediaId );\n}\n\nuint32_t MediaLibraryTester::countNbThumbnails()\n{\n sqlite::Statement stmt{\n getConn()->handle(),\n \"SELECT COUNT(*) FROM \" + Thumbnail::Table::Name\n };\n uint32_t res;\n stmt.execute();\n auto row = stmt.row();\n row >> res;\n return res;\n}\n\nuint32_t MediaLibraryTester::countNbTasks()\n{\n sqlite::Statement stmt{\n getConn()->handle(),\n \"SELECT COUNT(*) FROM \" + parser::Task::Table::Name\n };\n uint32_t res;\n stmt.execute();\n auto row = stmt.row();\n row >> res;\n return res;\n}\n\nbool MediaLibraryTester::setupDummyFolder()\n{\n \/\/ We create a dummy device in database, and a dummy folder.\n \/\/ This allows us to have a DB setup which is equivalent to an real one\n \/\/ File need to have a parent folder to be considered non-external, and a\n \/\/ folder needs to have a parent device.\n \/\/ However, if we just add a dummy device to DB and be done with it, when\n \/\/ the media library refreshes the devices, it will not find the device we\n \/\/ inserted and will mark it as missing, which will cause all its media to\n \/\/ be marked missing as well, which tends to make the tests fail\n std::shared_ptr device;\n try\n {\n device = Device::create( this, mock::FileSystemFactory::NoopDeviceUuid,\n \"file:\/\/\", false, false );\n if ( device == nullptr )\n return false;\n }\n catch ( const sqlite::errors::ConstraintUnique& )\n {\n \/\/ Most test cases call Reload() which will end up calling setupDummyFolder\n \/\/ again. We don't want the UNIQUE constraint to terminate the test.\n \/\/ Let's assume that this folder will be the first create folder\n dummyFolder = Folder::fetch( this, 1 );\n return true;\n }\n dummyFolder = Folder::create( this, \".\/\", 0, *device, *dummyDevice );\n if ( dummyFolder == nullptr || dummyFolder->id() != 1 )\n return false;\n return true;\n}\n\nvoid MediaLibraryTester::deleteAllTables( sqlite::Connection* dbConn )\n{\n MediaLibrary::deleteAllTables( dbConn );\n}\nunitests: MediaLibraryTester: Fix setMediaInsertionDate helper\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen \n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * 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 Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"MediaLibraryTester.h\"\n\n#include \"Album.h\"\n#include \"AlbumTrack.h\"\n#include \"Artist.h\"\n#include \"Device.h\"\n#include \"Playlist.h\"\n#include \"Genre.h\"\n#include \"Media.h\"\n#include \"Folder.h\"\n#include \"Show.h\"\n#include \"mocks\/FileSystem.h\"\n#include \"parser\/Task.h\"\n\n\nMediaLibraryTester::MediaLibraryTester( const std::string& dbPath,\n const std::string& mlFolderPath )\n : MediaLibrary( dbPath, mlFolderPath )\n , dummyDevice( new mock::NoopDevice )\n , dummyDirectory( new mock::NoopDirectory )\n{\n}\n\nvoid MediaLibraryTester::onDbConnectionReady( sqlite::Connection* dbConn )\n{\n deleteAllTables( dbConn );\n}\n\nstd::shared_ptr MediaLibraryTester::media( int64_t id )\n{\n return std::static_pointer_cast( MediaLibrary::media( id ) );\n}\n\nFolderPtr MediaLibraryTester::folder( const std::string& mrl ) const\n{\n return Folder::fromMrl( this, mrl, Folder::BannedType::No );\n}\n\nFolderPtr MediaLibraryTester::folder( int64_t id ) const\n{\n return MediaLibrary::folder( id );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( const std::string& path, IMedia::Type type )\n{\n return addFile( std::make_shared( path ),\n dummyFolder, dummyDirectory, IFile::Type::Main, type );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( std::shared_ptr file, IMedia::Type type )\n{\n return addFile( std::move( file ), dummyFolder, dummyDirectory,\n IFile::Type::Main, type );\n}\n\nstd::shared_ptr MediaLibraryTester::addFile( std::shared_ptr fileFs,\n std::shared_ptr parentFolder,\n std::shared_ptr parentFolderFs,\n IFile::Type fileType,\n IMedia::Type type )\n{\n LOG_INFO( \"Adding \", fileFs->mrl() );\n auto mptr = Media::create( this, type, parentFolder->deviceId(), parentFolder->id(),\n fileFs->name(), -1 );\n if ( mptr == nullptr )\n {\n LOG_ERROR( \"Failed to add media \", fileFs->mrl(), \" to the media library\" );\n return nullptr;\n }\n \/\/ For now, assume all media are made of a single file\n auto file = mptr->addFile( *fileFs, parentFolder->id(),\n parentFolderFs->device()->isRemovable(), fileType );\n if ( file == nullptr )\n {\n LOG_ERROR( \"Failed to add file \", fileFs->mrl(), \" to media #\", mptr->id() );\n Media::destroy( this, mptr->id() );\n return nullptr;\n }\n return mptr;\n}\n\nvoid MediaLibraryTester::addLocalFsFactory()\n{\n if ( fsFactory != nullptr )\n {\n m_fsHolder.addFsFactory( fsFactory );\n }\n else\n {\n MediaLibrary::addLocalFsFactory();\n }\n}\n\nvoid MediaLibraryTester::deleteAlbum( int64_t albumId )\n{\n Album::destroy( this, albumId );\n}\n\nstd::shared_ptr MediaLibraryTester::createGenre( const std::string& name )\n{\n return Genre::create( this, name );\n}\n\nvoid MediaLibraryTester::deleteGenre( int64_t genreId )\n{\n Genre::destroy( this, genreId );\n}\n\nvoid MediaLibraryTester::deleteArtist( int64_t artistId )\n{\n Artist::destroy( this, artistId );\n}\n\nvoid MediaLibraryTester::deleteShow( int64_t showId )\n{\n Show::destroy( this, showId );\n}\n\nstd::shared_ptr MediaLibraryTester::addDevice( const std::string& uuid,\n const std::string& scheme,\n bool isRemovable )\n{\n return Device::create( this, uuid, scheme, isRemovable, false );\n}\n\nvoid MediaLibraryTester::setFsFactory( std::shared_ptr fsf )\n{\n fsFactory = fsf;\n}\n\nstd::shared_ptr MediaLibraryTester::albumTrack( int64_t id )\n{\n return AlbumTrack::fetch( this, id );\n}\n\nstd::vector MediaLibraryTester::files()\n{\n static const std::string req = \"SELECT * FROM \" + Media::Table::Name + \" WHERE is_present != 0\";\n return Media::fetchAll( this, req );\n}\n\nstd::shared_ptr MediaLibraryTester::device( const std::string& uuid,\n const std::string& scheme )\n{\n return Device::fromUuid( this, uuid, scheme );\n}\n\nvoid MediaLibraryTester::onDiscoveredFile(std::shared_ptr fileFs,\n std::shared_ptr parentFolder,\n std::shared_ptr parentFolderFs,\n IFile::Type fileType)\n{\n addFile( fileFs, parentFolder, parentFolderFs, fileType, IMedia::Type::Unknown );\n}\n\nvoid MediaLibraryTester::populateNetworkFsFactories()\n{\n}\n\nMediaPtr MediaLibraryTester::addMedia( const std::string& mrl, IMedia::Type type )\n{\n return addFile( mrl, type );\n}\n\nvoid MediaLibraryTester::deleteMedia( int64_t mediaId )\n{\n Media::destroy( this, mediaId );\n}\n\nbool MediaLibraryTester::outdateAllDevices()\n{\n std::string req = \"UPDATE \" + Device::Table::Name + \" SET last_seen = 1\";\n return sqlite::Tools::executeUpdate( getConn(), req );\n}\n\nbool MediaLibraryTester::setMediaInsertionDate( int64_t mediaId, time_t t )\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET insertion_date = ? \"\n \"WHERE id_media = ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, t, mediaId );\n}\n\nbool MediaLibraryTester::outdateAllExternalMedia()\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET last_played_date = 1 \"\n \"WHERE import_type != ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, Media::ImportType::Internal );\n}\n\nbool MediaLibraryTester::setMediaType(int64_t mediaId, IMedia::Type type)\n{\n std::string req = \"UPDATE \" + Media::Table::Name + \" SET type = ? WHERE id_media = ?\";\n return sqlite::Tools::executeUpdate( getConn(), req, type, mediaId );\n}\n\nuint32_t MediaLibraryTester::countNbThumbnails()\n{\n sqlite::Statement stmt{\n getConn()->handle(),\n \"SELECT COUNT(*) FROM \" + Thumbnail::Table::Name\n };\n uint32_t res;\n stmt.execute();\n auto row = stmt.row();\n row >> res;\n return res;\n}\n\nuint32_t MediaLibraryTester::countNbTasks()\n{\n sqlite::Statement stmt{\n getConn()->handle(),\n \"SELECT COUNT(*) FROM \" + parser::Task::Table::Name\n };\n uint32_t res;\n stmt.execute();\n auto row = stmt.row();\n row >> res;\n return res;\n}\n\nbool MediaLibraryTester::setupDummyFolder()\n{\n \/\/ We create a dummy device in database, and a dummy folder.\n \/\/ This allows us to have a DB setup which is equivalent to an real one\n \/\/ File need to have a parent folder to be considered non-external, and a\n \/\/ folder needs to have a parent device.\n \/\/ However, if we just add a dummy device to DB and be done with it, when\n \/\/ the media library refreshes the devices, it will not find the device we\n \/\/ inserted and will mark it as missing, which will cause all its media to\n \/\/ be marked missing as well, which tends to make the tests fail\n std::shared_ptr device;\n try\n {\n device = Device::create( this, mock::FileSystemFactory::NoopDeviceUuid,\n \"file:\/\/\", false, false );\n if ( device == nullptr )\n return false;\n }\n catch ( const sqlite::errors::ConstraintUnique& )\n {\n \/\/ Most test cases call Reload() which will end up calling setupDummyFolder\n \/\/ again. We don't want the UNIQUE constraint to terminate the test.\n \/\/ Let's assume that this folder will be the first create folder\n dummyFolder = Folder::fetch( this, 1 );\n return true;\n }\n dummyFolder = Folder::create( this, \".\/\", 0, *device, *dummyDevice );\n if ( dummyFolder == nullptr || dummyFolder->id() != 1 )\n return false;\n return true;\n}\n\nvoid MediaLibraryTester::deleteAllTables( sqlite::Connection* dbConn )\n{\n MediaLibrary::deleteAllTables( dbConn );\n}\n<|endoftext|>"} {"text":"#ifndef INSANITY_ENUMERATION_KEY_MAP\n#define INSANITY_ENUMERATION_KEY_MAP\n\n#include \"Constants.hpp\"\n\nnamespace Insanity\n{\n\ttypedef u16 EKey;\n\n\t\/\/this only maps a common English keyboard. Other keyboards might not be laid out the same way.\n\t\/\/I'd suggest allowing remapping keys in game.\n\tclass INSANITY_API EKeyMap final\n\t{\n\tprivate:\n\t\tvirtual void __enumclass() = 0;\n\tpublic:\n\t\tstatic const EKey Backspace;\n\t\tstatic const EKey Tab;\n\t\tstatic const EKey Clear;\n\t\tstatic const EKey Enter;\n\t\tstatic const EKey Shift; \/\/Seems to be received instead of more specific Right\/Left\n\t\tstatic const EKey Control; \/\/as Shift\n\t\tstatic const EKey Alt; \/\/as Shift\n\t\tstatic const EKey Pause;\n\t\tstatic const EKey CapsLock;\n\t\tstatic const EKey Escape;\n\t\tstatic const EKey Spacebar;\n\t\tstatic const EKey PageUp;\n\t\tstatic const EKey PageDown;\n\t\tstatic const EKey End;\n\t\tstatic const EKey Home;\n\t\tstatic const EKey LeftArrow;\n\t\tstatic const EKey UpArrow;\n\t\tstatic const EKey RightArrow;\n\t\tstatic const EKey DownArrow;\n\t\tstatic const EKey PrintScreen;\n\t\tstatic const EKey Insert;\n\t\tstatic const EKey Delete;\n\t\t\/\/ zero through nine are all mapped to numbers equivalent to their ASCII values.\n\t\t\/\/ catch A through Z using uppercase character literals.\n\t\t\/\/could put in enumerations for those, and make this an enum class.\n\t\tstatic const EKey A;\n\t\tstatic const EKey B;\n\t\tstatic const EKey C;\n\t\tstatic const EKey D;\n\t\tstatic const EKey E;\n\t\tstatic const EKey F;\n\t\tstatic const EKey G;\n\t\tstatic const EKey H;\n\t\tstatic const EKey I;\n\t\tstatic const EKey J;\n\t\tstatic const EKey K;\n\t\tstatic const EKey L;\n\t\tstatic const EKey M;\n\t\tstatic const EKey N;\n\t\tstatic const EKey O;\n\t\tstatic const EKey P;\n\t\tstatic const EKey Q;\n\t\tstatic const EKey R;\n\t\tstatic const EKey S;\n\t\tstatic const EKey T;\n\t\tstatic const EKey U;\n\t\tstatic const EKey V;\n\t\tstatic const EKey W;\n\t\tstatic const EKey X;\n\t\tstatic const EKey Y;\n\t\tstatic const EKey Z;\n\t\tstatic const EKey Zero;\n\t\tstatic const EKey One;\n\t\tstatic const EKey Two;\n\t\tstatic const EKey Three;\n\t\tstatic const EKey Four;\n\t\tstatic const EKey Five;\n\t\tstatic const EKey Six;\n\t\tstatic const EKey Seven;\n\t\tstatic const EKey Eight;\n\t\tstatic const EKey Nine;\n\t\tstatic const EKey LeftSuper;\n\t\tstatic const EKey RightSuper;\n\t\t\/\/what key is this? The one that looks like an arrow and menu.\n\t\tstatic const EKey Applications;\n\t\tstatic const EKey Numpad0;\n\t\tstatic const EKey Numpad1;\n\t\tstatic const EKey Numpad2;\n\t\tstatic const EKey Numpad3;\n\t\tstatic const EKey Numpad4;\n\t\tstatic const EKey Numpad5;\n\t\tstatic const EKey Numpad6;\n\t\tstatic const EKey Numpad7;\n\t\tstatic const EKey Numpad8;\n\t\tstatic const EKey Numpad9;\n\t\tstatic const EKey Multiply;\n\t\tstatic const EKey Add;\n\t\tstatic const EKey Subtract;\n\t\tstatic const EKey Decimal;\n\t\tstatic const EKey Divide;\n\t\tstatic const EKey F1;\n\t\tstatic const EKey F2;\n\t\tstatic const EKey F3;\n\t\tstatic const EKey F4;\n\t\tstatic const EKey F5;\n\t\tstatic const EKey F6;\n\t\tstatic const EKey F7;\n\t\tstatic const EKey F8;\n\t\tstatic const EKey F9;\n\t\tstatic const EKey F10;\n\t\tstatic const EKey F11;\n\t\tstatic const EKey F12;\n\t\t\/\/the only keyboard I've seen with function keys past 12 is a Mac keyboard\n\t\tstatic const EKey F13;\n\t\tstatic const EKey F14;\n\t\tstatic const EKey F15;\n\t\tstatic const EKey F16;\n\t\t\/\/even the Mac keyboard I have only goes this far (16)\n\t\tstatic const EKey F17;\n\t\tstatic const EKey F18;\n\t\tstatic const EKey F19;\n\t\tstatic const EKey F20;\n\t\tstatic const EKey F21;\n\t\tstatic const EKey F22;\n\t\tstatic const EKey F23;\n\t\tstatic const EKey F24;\n\t\tstatic const EKey NumLock;\n\t\tstatic const EKey ScrollLock;\n\t\t\/\/the following are not used, at least on my keyboard. Pressing either shift key sends only Shift, for instance.\n\t\tstatic const EKey LeftShift;\n\t\tstatic const EKey RightShift;\n\t\tstatic const EKey LeftControl;\n\t\tstatic const EKey RightControl;\n\t\tstatic const EKey LeftAlt;\n\t\tstatic const EKey RightAlt;\n\t\t\/\/end unused region\n\t\tstatic const EKey Semicolon;\n\t\tstatic const EKey Equals;\n\t\tstatic const EKey Comma;\n\t\tstatic const EKey Minus;\n\t\tstatic const EKey Period;\n\t\tstatic const EKey Slash;\n\t\tstatic const EKey Backquote;\n\t\tstatic const EKey LeftSquareBracket;\n\t\tstatic const EKey Backslash;\n\t\tstatic const EKey RightSquareBracket;\n\t\tstatic const EKey Quote;\n\t};\n}\n\n#endifChange the way EKeyMap is made noninstantiable#ifndef INSANITY_ENUMERATION_KEY_MAP\n#define INSANITY_ENUMERATION_KEY_MAP\n\n#include \"Constants.hpp\"\n\nnamespace Insanity\n{\n\ttypedef u16 EKey;\n\n\t\/\/this only maps a common English keyboard. Other keyboards might not be laid out the same way.\n\t\/\/I'd suggest allowing remapping keys in game.\n\tclass INSANITY_API EKeyMap final\n\t{\n\tprivate:\n\tpublic:\n\t\tEKeyMap() = delete;\n\t\tEKeyMap(EKeyMap const&) = delete;\n\t\tEKeyMap(EKeyMap &&) = delete;\n\t\t~EKeyMap() = delete;\n\t\tEKeyMap & operator=(EKeyMap const&) = delete;\n\t\tEKeyMap & operator=(EKeyMap &&) = delete;\n\n\t\tstatic const EKey Backspace;\n\t\tstatic const EKey Tab;\n\t\tstatic const EKey Clear;\n\t\tstatic const EKey Enter;\n\t\tstatic const EKey Shift; \/\/Seems to be received instead of more specific Right\/Left\n\t\tstatic const EKey Control; \/\/as Shift\n\t\tstatic const EKey Alt; \/\/as Shift\n\t\tstatic const EKey Pause;\n\t\tstatic const EKey CapsLock;\n\t\tstatic const EKey Escape;\n\t\tstatic const EKey Spacebar;\n\t\tstatic const EKey PageUp;\n\t\tstatic const EKey PageDown;\n\t\tstatic const EKey End;\n\t\tstatic const EKey Home;\n\t\tstatic const EKey LeftArrow;\n\t\tstatic const EKey UpArrow;\n\t\tstatic const EKey RightArrow;\n\t\tstatic const EKey DownArrow;\n\t\tstatic const EKey PrintScreen;\n\t\tstatic const EKey Insert;\n\t\tstatic const EKey Delete;\n\t\t\/\/ zero through nine are all mapped to numbers equivalent to their ASCII values.\n\t\t\/\/ catch A through Z using uppercase character literals.\n\t\t\/\/could put in enumerations for those, and make this an enum class.\n\t\tstatic const EKey A;\n\t\tstatic const EKey B;\n\t\tstatic const EKey C;\n\t\tstatic const EKey D;\n\t\tstatic const EKey E;\n\t\tstatic const EKey F;\n\t\tstatic const EKey G;\n\t\tstatic const EKey H;\n\t\tstatic const EKey I;\n\t\tstatic const EKey J;\n\t\tstatic const EKey K;\n\t\tstatic const EKey L;\n\t\tstatic const EKey M;\n\t\tstatic const EKey N;\n\t\tstatic const EKey O;\n\t\tstatic const EKey P;\n\t\tstatic const EKey Q;\n\t\tstatic const EKey R;\n\t\tstatic const EKey S;\n\t\tstatic const EKey T;\n\t\tstatic const EKey U;\n\t\tstatic const EKey V;\n\t\tstatic const EKey W;\n\t\tstatic const EKey X;\n\t\tstatic const EKey Y;\n\t\tstatic const EKey Z;\n\t\tstatic const EKey Zero;\n\t\tstatic const EKey One;\n\t\tstatic const EKey Two;\n\t\tstatic const EKey Three;\n\t\tstatic const EKey Four;\n\t\tstatic const EKey Five;\n\t\tstatic const EKey Six;\n\t\tstatic const EKey Seven;\n\t\tstatic const EKey Eight;\n\t\tstatic const EKey Nine;\n\t\tstatic const EKey LeftSuper;\n\t\tstatic const EKey RightSuper;\n\t\t\/\/what key is this? The one that looks like an arrow and menu.\n\t\tstatic const EKey Applications;\n\t\tstatic const EKey Numpad0;\n\t\tstatic const EKey Numpad1;\n\t\tstatic const EKey Numpad2;\n\t\tstatic const EKey Numpad3;\n\t\tstatic const EKey Numpad4;\n\t\tstatic const EKey Numpad5;\n\t\tstatic const EKey Numpad6;\n\t\tstatic const EKey Numpad7;\n\t\tstatic const EKey Numpad8;\n\t\tstatic const EKey Numpad9;\n\t\tstatic const EKey Multiply;\n\t\tstatic const EKey Add;\n\t\tstatic const EKey Subtract;\n\t\tstatic const EKey Decimal;\n\t\tstatic const EKey Divide;\n\t\tstatic const EKey F1;\n\t\tstatic const EKey F2;\n\t\tstatic const EKey F3;\n\t\tstatic const EKey F4;\n\t\tstatic const EKey F5;\n\t\tstatic const EKey F6;\n\t\tstatic const EKey F7;\n\t\tstatic const EKey F8;\n\t\tstatic const EKey F9;\n\t\tstatic const EKey F10;\n\t\tstatic const EKey F11;\n\t\tstatic const EKey F12;\n\t\t\/\/the only keyboard I've seen with function keys past 12 is a Mac keyboard\n\t\tstatic const EKey F13;\n\t\tstatic const EKey F14;\n\t\tstatic const EKey F15;\n\t\tstatic const EKey F16;\n\t\t\/\/even the Mac keyboard I have only goes this far (16)\n\t\tstatic const EKey F17;\n\t\tstatic const EKey F18;\n\t\tstatic const EKey F19;\n\t\tstatic const EKey F20;\n\t\tstatic const EKey F21;\n\t\tstatic const EKey F22;\n\t\tstatic const EKey F23;\n\t\tstatic const EKey F24;\n\t\tstatic const EKey NumLock;\n\t\tstatic const EKey ScrollLock;\n\t\t\/\/the following are not used, at least on my keyboard. Pressing either shift key sends only Shift, for instance.\n\t\tstatic const EKey LeftShift;\n\t\tstatic const EKey RightShift;\n\t\tstatic const EKey LeftControl;\n\t\tstatic const EKey RightControl;\n\t\tstatic const EKey LeftAlt;\n\t\tstatic const EKey RightAlt;\n\t\t\/\/end unused region\n\t\tstatic const EKey Semicolon;\n\t\tstatic const EKey Equals;\n\t\tstatic const EKey Comma;\n\t\tstatic const EKey Minus;\n\t\tstatic const EKey Period;\n\t\tstatic const EKey Slash;\n\t\tstatic const EKey Backquote;\n\t\tstatic const EKey LeftSquareBracket;\n\t\tstatic const EKey Backslash;\n\t\tstatic const EKey RightSquareBracket;\n\t\tstatic const EKey Quote;\n\t};\n}\n\n#endif<|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 \"ExpansionManager.h\"\n\n#include \"MacroImportHelper.h\"\n#include \"StaticStuff.h\"\n\nnamespace CppImport {\n\nExpansionManager::ExpansionManager(ClangHelper* clang, AstMapping* astMapping, DefinitionManager* definitionManager,\n\t\t\t\t\t\t\t\t\t\t\t LexicalHelper* lexicalHelper)\n\t: clang_(clang), astMapping_(astMapping), definitionManager_(definitionManager), lexicalHelper_(lexicalHelper) {}\n\nvoid ExpansionManager::addMacroExpansion(clang::SourceRange sourceRange, const clang::MacroDirective* macroDirective,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const clang::MacroArgs* macroArguments)\n{\n\tif (definitionManager_->isPartialEnd(macroDirective))\n\t{\n\t\t\/*\n\t\t * if the to be registered expansion's definition is a partial end macro then we are not going to generate a\n\t\t * meta definition for this expansion.\n\t\t * instead we remember that we are currently not in an xMacro body.\n\t\t *\/\n\t\tcurrentXMacroParent = nullptr;\n\t\treturn;\n\t}\n\n\t\/\/ build new macro expansion entry from the provided information\n\tauto entry = new MacroExpansion();\n\tentry->range = sourceRange;\n\tentry->definition = macroDirective;\n\tentry->parent = expansion(sourceRange.getBegin());\n\tif (entry->parent) entry->parent->children.append(entry);\n\n\t\/\/ handle xMacro data members\n\tif (definitionManager_->isPartialBegin(macroDirective) && !currentXMacroParent)\n\t\t\/*\n\t\t * if the definition of this expansion is a partial begin macro we remember that we are now in a xMacro body.\n\t\t * we check whether we are not already in a xMacro body because we want to remember the .h part (the first one) of\n\t\t * the xMacro begins (the potential .cpp part could overwrite the stored information otherwise).\n\t\t *\/\n\t\tcurrentXMacroParent = entry;\n\telse if (currentXMacroParent && !entry->parent)\n\t{\n\t\t\/*\n\t\t * if we are in a xMacro body and the current expansion is not a top level expansion then this expansion is a\n\t\t * xMacro child of the stored xMacro expansion.\n\t\t *\/\n\t\tentry->xMacroParent = currentXMacroParent;\n\t\tcurrentXMacroParent->xMacroChildren.append(entry);\n\t}\n\n\tentry->metaCall =\n\t\t\tnew OOModel::MetaCallExpression(definitionManager_->definitionName(entry->definition));\n\n\tif (!macroDirective->getMacroInfo()->isObjectLike()) \/\/ only function like macros have braces in their signature to parse\n\t{\n\t\t\/\/ extract everything in parentheses of the expansion signature using a regular expression\n\t\tQRegularExpression regex (\"\\\\((.*)\\\\)\", QRegularExpression::DotMatchesEverythingOption);\n\t\tauto argumentsString = lexicalHelper_->unexpandedSpelling(sourceRange);\n\t\tauto match = regex.match(argumentsString);\n\t\tauto arguments = match.captured(1).split(\",\");\n\n\t\t\/\/ by default initialize meta call arguments to be reference expressions with the raw spelling at this expansion\n\t\tfor (auto i = 0; i < clang_->argumentNames(entry->definition).size(); i++)\n\t\t{\n\t\t\tauto actualArg = macroArguments->getUnexpArgument((unsigned int)i);\n\t\t\tentry->metaCall->arguments()->append(new OOModel::ReferenceExpression(arguments[i]));\n\t\t\tentry->argumentLocs.append(actualArg->getLocation());\n\t\t}\n\t}\n\n\texpansions_.append(entry);\n}\n\nvoid ExpansionManager::clear()\n{\n\texpansionCache_.clear();\n\texpansions_.clear();\n}\n\nQVector ExpansionManager::topLevelExpansions()\n{\n\tQVector result;\n\tfor (auto expansion : expansions_)\n\t\tif (!expansion->parent)\n\t\t\tresult.append(expansion);\n\n\treturn result;\n}\n\n\nMacroExpansion*ExpansionManager::expansion(clang::SourceLocation loc)\n{\n\tMacroExpansion* expansion = immediateExpansion(loc);\n\tMacroExpansion* last = expansion;\n\n\tif (expansion)\n\t{\n\t\tdo\n\t\t{\n\t\t\tlast = expansion;\n\t\t\tloc = clang_->sourceManager()->getImmediateExpansionRange(loc).first;\n\t\t\texpansion = immediateExpansion(loc);\n\t\t} while (expansion && expansion->isChildOf(last));\n\t}\n\n\treturn last;\n}\n\nMacroExpansion*ExpansionManager::immediateExpansion(clang::SourceLocation loc)\n{\n\tauto expansion = clang_->immediateMacroLocation(loc);\n\tfor (auto i = 0; i < expansions_.size(); i++)\n\t\tif (expansions_[i]->range.getBegin() == expansion) return expansions_[i];\n\n\t\/*\n\t * if we have not found an immediate expansion for loc then we try again using the found immediateExpansionLoc.\n\t * this can happen in case of token concatenation or stringifycation where the first expansion location would point\n\t * to the location of the concatenated token or stringifycation result.\n\t *\/\n\texpansion = clang_->immediateMacroLocation(expansion);\n\tfor (auto i = 0; i < expansions_.size(); i++)\n\t\tif (expansions_[i]->range.getBegin() == expansion) return expansions_[i];\n\n\treturn nullptr;\n}\n\n\nQSet ExpansionManager::expansion(Model::Node* node)\n{\n\tQ_ASSERT(node);\n\n\tif (!expansionCache_.contains(node))\n\t{\n\t\texpansionCache_[node] = {};\n\n\t\tif (auto n = astMapping_->closestParentWithAstMapping(node))\n\t\t\tif (astMapping_->contains(n))\n\t\t\t\tfor (auto range : astMapping_->get(n))\n\t\t\t\t{\n\t\t\t\t\tauto exp = expansion(range.getBegin());\n\t\t\t\t\tif (exp)\texpansionCache_[node].insert(exp);\n\t\t\t\t}\n\t}\n\n\treturn expansionCache_[node];\n}\n\n\nQVector ExpansionManager::tLExpansionTLNodes(MacroExpansion* expansion)\n{\n\tQ_ASSERT(expansion);\n\tQ_ASSERT(!expansion->parent); \/\/ ensure expansion is a top level expansion\n\n\tQVector allTLExpansionNodes;\n\tfor (auto node : astMapping_->nodes())\n\t\tfor (auto range : astMapping_->get(node))\n\t\t\t\/\/ for all mapped nodes check whether any of their ranges expand to the top level macro range\n\t\t\tif (clang_->sourceManager()->getExpansionLoc(range.getBegin()) == expansion->range.getBegin())\n\t\t\t{\n\t\t\t\tallTLExpansionNodes.append(node);\n\t\t\t\tbreak;\n\t\t\t}\n\n\tQVector result = StaticStuff::topLevelNodes(allTLExpansionNodes);\n\tStaticStuff::orderNodes(result);\n\treturn result;\n}\n\n\nQVector ExpansionManager::nTLExpansionTLNodes(MacroExpansion* exp)\n{\n\tQ_ASSERT(exp);\n\n\tQVector allNTLExpansionNodes;\n\tfor (auto node : astMapping_->nodes())\n\t\tif (expansion(node).contains(exp))\n\t\t\tallNTLExpansionNodes.append(node);\n\n\tQVector result = StaticStuff::topLevelNodes(allNTLExpansionNodes);\n\tStaticStuff::orderNodes(result);\n\treturn result;\n}\n\n}\nfix too long line\/***********************************************************************************************************************\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 \"ExpansionManager.h\"\n\n#include \"MacroImportHelper.h\"\n#include \"StaticStuff.h\"\n\nnamespace CppImport {\n\nExpansionManager::ExpansionManager(ClangHelper* clang, AstMapping* astMapping, DefinitionManager* definitionManager,\n\t\t\t\t\t\t\t\t\t\t\t LexicalHelper* lexicalHelper)\n\t: clang_(clang), astMapping_(astMapping), definitionManager_(definitionManager), lexicalHelper_(lexicalHelper) {}\n\nvoid ExpansionManager::addMacroExpansion(clang::SourceRange sourceRange, const clang::MacroDirective* macroDirective,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const clang::MacroArgs* macroArguments)\n{\n\tif (definitionManager_->isPartialEnd(macroDirective))\n\t{\n\t\t\/*\n\t\t * if the to be registered expansion's definition is a partial end macro then we are not going to generate a\n\t\t * meta definition for this expansion.\n\t\t * instead we remember that we are currently not in an xMacro body.\n\t\t *\/\n\t\tcurrentXMacroParent = nullptr;\n\t\treturn;\n\t}\n\n\t\/\/ build new macro expansion entry from the provided information\n\tauto entry = new MacroExpansion();\n\tentry->range = sourceRange;\n\tentry->definition = macroDirective;\n\tentry->parent = expansion(sourceRange.getBegin());\n\tif (entry->parent) entry->parent->children.append(entry);\n\n\t\/\/ handle xMacro data members\n\tif (definitionManager_->isPartialBegin(macroDirective) && !currentXMacroParent)\n\t\t\/*\n\t\t * if the definition of this expansion is a partial begin macro we remember that we are now in a xMacro body.\n\t\t * we check whether we are not already in a xMacro body because we want to remember the .h part (the first one) of\n\t\t * the xMacro begins (the potential .cpp part could overwrite the stored information otherwise).\n\t\t *\/\n\t\tcurrentXMacroParent = entry;\n\telse if (currentXMacroParent && !entry->parent)\n\t{\n\t\t\/*\n\t\t * if we are in a xMacro body and the current expansion is not a top level expansion then this expansion is a\n\t\t * xMacro child of the stored xMacro expansion.\n\t\t *\/\n\t\tentry->xMacroParent = currentXMacroParent;\n\t\tcurrentXMacroParent->xMacroChildren.append(entry);\n\t}\n\n\tentry->metaCall =\n\t\t\tnew OOModel::MetaCallExpression(definitionManager_->definitionName(entry->definition));\n\n\t\/\/ only function like macros have braces in their signature to parse\n\tif (!macroDirective->getMacroInfo()->isObjectLike())\n\t{\n\t\t\/\/ extract everything in parentheses of the expansion signature using a regular expression\n\t\tQRegularExpression regex (\"\\\\((.*)\\\\)\", QRegularExpression::DotMatchesEverythingOption);\n\t\tauto argumentsString = lexicalHelper_->unexpandedSpelling(sourceRange);\n\t\tauto match = regex.match(argumentsString);\n\t\tauto arguments = match.captured(1).split(\",\");\n\n\t\t\/\/ by default initialize meta call arguments to be reference expressions with the raw spelling at this expansion\n\t\tfor (auto i = 0; i < clang_->argumentNames(entry->definition).size(); i++)\n\t\t{\n\t\t\tauto actualArg = macroArguments->getUnexpArgument((unsigned int)i);\n\t\t\tentry->metaCall->arguments()->append(new OOModel::ReferenceExpression(arguments[i]));\n\t\t\tentry->argumentLocs.append(actualArg->getLocation());\n\t\t}\n\t}\n\n\texpansions_.append(entry);\n}\n\nvoid ExpansionManager::clear()\n{\n\texpansionCache_.clear();\n\texpansions_.clear();\n}\n\nQVector ExpansionManager::topLevelExpansions()\n{\n\tQVector result;\n\tfor (auto expansion : expansions_)\n\t\tif (!expansion->parent)\n\t\t\tresult.append(expansion);\n\n\treturn result;\n}\n\n\nMacroExpansion*ExpansionManager::expansion(clang::SourceLocation loc)\n{\n\tMacroExpansion* expansion = immediateExpansion(loc);\n\tMacroExpansion* last = expansion;\n\n\tif (expansion)\n\t{\n\t\tdo\n\t\t{\n\t\t\tlast = expansion;\n\t\t\tloc = clang_->sourceManager()->getImmediateExpansionRange(loc).first;\n\t\t\texpansion = immediateExpansion(loc);\n\t\t} while (expansion && expansion->isChildOf(last));\n\t}\n\n\treturn last;\n}\n\nMacroExpansion*ExpansionManager::immediateExpansion(clang::SourceLocation loc)\n{\n\tauto expansion = clang_->immediateMacroLocation(loc);\n\tfor (auto i = 0; i < expansions_.size(); i++)\n\t\tif (expansions_[i]->range.getBegin() == expansion) return expansions_[i];\n\n\t\/*\n\t * if we have not found an immediate expansion for loc then we try again using the found immediateExpansionLoc.\n\t * this can happen in case of token concatenation or stringifycation where the first expansion location would point\n\t * to the location of the concatenated token or stringifycation result.\n\t *\/\n\texpansion = clang_->immediateMacroLocation(expansion);\n\tfor (auto i = 0; i < expansions_.size(); i++)\n\t\tif (expansions_[i]->range.getBegin() == expansion) return expansions_[i];\n\n\treturn nullptr;\n}\n\n\nQSet ExpansionManager::expansion(Model::Node* node)\n{\n\tQ_ASSERT(node);\n\n\tif (!expansionCache_.contains(node))\n\t{\n\t\texpansionCache_[node] = {};\n\n\t\tif (auto n = astMapping_->closestParentWithAstMapping(node))\n\t\t\tif (astMapping_->contains(n))\n\t\t\t\tfor (auto range : astMapping_->get(n))\n\t\t\t\t{\n\t\t\t\t\tauto exp = expansion(range.getBegin());\n\t\t\t\t\tif (exp)\texpansionCache_[node].insert(exp);\n\t\t\t\t}\n\t}\n\n\treturn expansionCache_[node];\n}\n\n\nQVector ExpansionManager::tLExpansionTLNodes(MacroExpansion* expansion)\n{\n\tQ_ASSERT(expansion);\n\tQ_ASSERT(!expansion->parent); \/\/ ensure expansion is a top level expansion\n\n\tQVector allTLExpansionNodes;\n\tfor (auto node : astMapping_->nodes())\n\t\tfor (auto range : astMapping_->get(node))\n\t\t\t\/\/ for all mapped nodes check whether any of their ranges expand to the top level macro range\n\t\t\tif (clang_->sourceManager()->getExpansionLoc(range.getBegin()) == expansion->range.getBegin())\n\t\t\t{\n\t\t\t\tallTLExpansionNodes.append(node);\n\t\t\t\tbreak;\n\t\t\t}\n\n\tQVector result = StaticStuff::topLevelNodes(allTLExpansionNodes);\n\tStaticStuff::orderNodes(result);\n\treturn result;\n}\n\n\nQVector ExpansionManager::nTLExpansionTLNodes(MacroExpansion* exp)\n{\n\tQ_ASSERT(exp);\n\n\tQVector allNTLExpansionNodes;\n\tfor (auto node : astMapping_->nodes())\n\t\tif (expansion(node).contains(exp))\n\t\t\tallNTLExpansionNodes.append(node);\n\n\tQVector result = StaticStuff::topLevelNodes(allNTLExpansionNodes);\n\tStaticStuff::orderNodes(result);\n\treturn result;\n}\n\n}\n<|endoftext|>"} {"text":"\n#include \"stdafx.h\"\n\n#include \"bind2thread.h\"\n#include \"taskify.h\"\n\nclass test_taskify : public ::testing::Test {\nprotected:\n\n\ttest_taskify() {\n\t}\n\tvirtual void SetUp() {\n\t\tthread.reset(new ThreadWithTasks());\n\t}\n\tvirtual void TearDown() {\n\t\ttearDown();\n\t}\n\tvoid awaitTasksDone() {\n\t\tthread->sync().get();\n\t}\n\tvoid tearDown()\t{\n\t\tthread->stop();\n\t\tif (thread->joinable()) {\n\t\t\tthread->join();\n\t\t}\n\t}\n\tTaskDispatcherPtr secondThread() const {\n\t\treturn thread->dispatcher();\n\t}\n\n\t\/\/ DATA \n\n\tstd::shared_ptr thread;\n\n};\n\n\nclass TestTaskifyException : public std::exception {\npublic:\n\tTestTaskifyException(const char * what) : mWhat(what) {\n\t}\n\tvirtual const char * what() const override {\n\t\treturn mWhat;\n\t}\nprivate:\n\tconst char * mWhat;\n};\n\n\/\/exception immediatelly\n\/\/translate error immediatelly->best practices to link own errors with exception system\n\nstatic void async_file_sizes_cr( const std::function< void(int) >& foo, int size) {\n\tfoo(size); \n}\n\nstatic void async_file_sizes( std::function< void(int) > foo, int size) {\n\tfoo(size);\n}\n\nstatic void async_exception(std::function< void(int) > foo, const char* what ) {\n\tthrow TestTaskifyException (what);\n}\n\nstatic void async_exception_ptr(std::function< void(int) > foo, std::function< void(const std::exception_ptr&) > onException, const char* what) {\n\ttry {\n\t\tthrow TestTaskifyException(what);\n\t}\n\tcatch (...) {\n\t\tonException( std::current_exception()); \n\t}\n}\n\n\nstatic void async_delayed_file_sizes(std::function< void(int) > foo, int size) {\n\tpost2current( std::bind(foo, size));\n}\n\nstatic void async_delayed_file_sizes_2nd_thread( const TaskDispatcherPtr& workerThread, const std::function< void(int) >& foo, int size) {\n\tworkerThread->postex( bind2current(foo, size));\n}\n\n\nTEST_F(test_taskify, callbackImmediately) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t( taskify( async_file_sizes, placeholders::CALLBACK, 3 )); \n\t\t\tsize_t sizes = std::get<0>( t.get());\n\t\t\tEXPECT_EQ(sizes, 3);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, callbackDelayed ) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t(taskify(async_delayed_file_sizes, placeholders::CALLBACK, 4));\n\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\tEXPECT_EQ(sizes, 4);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, callbackFrom2ndThread ) { \n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\tTaskDispatcherPtr secondThread = this->secondThread();\n\n\tpost2current([dispatcher, secondThread] {\n\t\tmake_task([dispatcher, secondThread]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t( taskify( async_delayed_file_sizes_2nd_thread, secondThread, placeholders::CALLBACK, 4));\n\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\tEXPECT_EQ(sizes, 4);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, exceptionImmediately) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tconst char *resultingWhat = 0;\n\t\t\tstd::exception r;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tTask< boost::future< std::tuple > > t(taskify(async_exception, placeholders::CALLBACK, \"exceptionImmediately\"));\n\t\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\t}\n\t\t\tcatch (std::exception& e)\n\t\t\t{\n\t\t\t\tresultingWhat = e.what();\n\t\t\t}\n\t\t\tEXPECT_EQ( std::string(resultingWhat), std::string(\"exceptionImmediately\"));\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\n\nTEST_F(test_taskify, exceptionWithinCallback ) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tconst char *resultingWhat = 0;\n\t\t\tauto&& t( taskify( async_exception_ptr, placeholders::CALLBACK, placeholders::EXCEPTION_PTR, \"exceptionWithinCallback\" ));\n\t\t\ttry\n\t\t\t{\n\t\t\t\tt.get();\n\t\t\t}\n\t\t\tcatch (std::exception& e)\n\t\t\t{\n\t\t\t\tresultingWhat = e.what();\n\t\t\t}\n\t\t\tEXPECT_EQ(std::string(resultingWhat), std::string(\"exceptionWithinCallback\"));\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\ncompile fix for gcc\n#include \"stdafx.h\"\n\n#include \"bind2thread.h\"\n#include \"taskify.h\"\n\nclass test_taskify : public ::testing::Test {\nprotected:\n\n\ttest_taskify() {\n\t}\n\tvirtual void SetUp() {\n\t\tthread.reset(new ThreadWithTasks());\n\t}\n\tvirtual void TearDown() {\n\t\ttearDown();\n\t}\n\tvoid awaitTasksDone() {\n\t\tthread->sync().get();\n\t}\n\tvoid tearDown()\t{\n\t\tthread->stop();\n\t\tif (thread->joinable()) {\n\t\t\tthread->join();\n\t\t}\n\t}\n\tTaskDispatcherPtr secondThread() const {\n\t\treturn thread->dispatcher();\n\t}\n\n\t\/\/ DATA \n\n\tstd::shared_ptr thread;\n\n};\n\n\nclass TestTaskifyException : public std::exception {\npublic:\n\tTestTaskifyException(const char * what) : mWhat(what) {\n\t}\n#ifdef _GLIBCXX_USE_NOEXCEPT \n\tvirtual const char * what() const _GLIBCXX_USE_NOEXCEPT override{\n#else\n\tvirtual const char * what() const override {\n#endif\n\t\treturn mWhat;\n\t}\nprivate:\n\tconst char * mWhat;\n};\n\n\/\/exception immediatelly\n\/\/translate error immediatelly->best practices to link own errors with exception system\n\nstatic void async_file_sizes_cr( const std::function< void(int) >& foo, int size) {\n\tfoo(size); \n}\n\nstatic void async_file_sizes( std::function< void(int) > foo, int size) {\n\tfoo(size);\n}\n\nstatic void async_exception(std::function< void(int) > foo, const char* what ) {\n\tthrow TestTaskifyException (what);\n}\n\nstatic void async_exception_ptr(std::function< void(int) > foo, std::function< void(const std::exception_ptr&) > onException, const char* what) {\n\ttry {\n\t\tthrow TestTaskifyException(what);\n\t}\n\tcatch (...) {\n\t\tonException( std::current_exception()); \n\t}\n}\n\n\nstatic void async_delayed_file_sizes(std::function< void(int) > foo, int size) {\n\tpost2current( std::bind(foo, size));\n}\n\nstatic void async_delayed_file_sizes_2nd_thread( const TaskDispatcherPtr& workerThread, const std::function< void(int) >& foo, int size) {\n\tworkerThread->postex( bind2current(foo, size));\n}\n\n\nTEST_F(test_taskify, callbackImmediately) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t( taskify( async_file_sizes, placeholders::CALLBACK, 3 )); \n\t\t\tsize_t sizes = std::get<0>( t.get());\n\t\t\tEXPECT_EQ(sizes, 3);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, callbackDelayed ) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t(taskify(async_delayed_file_sizes, placeholders::CALLBACK, 4));\n\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\tEXPECT_EQ(sizes, 4);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, callbackFrom2ndThread ) { \n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\tTaskDispatcherPtr secondThread = this->secondThread();\n\n\tpost2current([dispatcher, secondThread] {\n\t\tmake_task([dispatcher, secondThread]\n\t\t{\n\t\t\tTask< boost::future< std::tuple > > t( taskify( async_delayed_file_sizes_2nd_thread, secondThread, placeholders::CALLBACK, 4));\n\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\tEXPECT_EQ(sizes, 4);\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\nTEST_F(test_taskify, exceptionImmediately) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tconst char *resultingWhat = 0;\n\t\t\tstd::exception r;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tTask< boost::future< std::tuple > > t(taskify(async_exception, placeholders::CALLBACK, \"exceptionImmediately\"));\n\t\t\t\tsize_t sizes = std::get<0>(t.get());\n\t\t\t}\n\t\t\tcatch (std::exception& e)\n\t\t\t{\n\t\t\t\tresultingWhat = e.what();\n\t\t\t}\n\t\t\tEXPECT_EQ( std::string(resultingWhat), std::string(\"exceptionImmediately\"));\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\n\nTEST_F(test_taskify, exceptionWithinCallback ) {\n\n\tstd::shared_ptr dispatcher(TaskDispatcher4StdThread::create());\n\n\tpost2current([dispatcher] {\n\t\tmake_task([dispatcher]\n\t\t{\n\t\t\tconst char *resultingWhat = 0;\n\t\t\tauto&& t( taskify( async_exception_ptr, placeholders::CALLBACK, placeholders::EXCEPTION_PTR, \"exceptionWithinCallback\" ));\n\t\t\ttry\n\t\t\t{\n\t\t\t\tt.get();\n\t\t\t}\n\t\t\tcatch (std::exception& e)\n\t\t\t{\n\t\t\t\tresultingWhat = e.what();\n\t\t\t}\n\t\t\tEXPECT_EQ(std::string(resultingWhat), std::string(\"exceptionWithinCallback\"));\n\t\t\tdispatcher->stop();\n\t\t}\n\t\t);\n\t});\n\n\tdispatcher->run();\n\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace kgr {\n\ntemplate\nstruct Dependency {\n\tusing DependenciesTypes = std::tuple;\n};\n\nusing NoDependencies = Dependency<>;\n\nstruct Single {\n\tusing ParentTypes = std::tuple<>;\n};\n\ntemplate\nstruct Service;\n\ntemplate\nstruct Overrides : Single {\n\tusing ParentTypes = std::tuple;\n};\n\nnamespace detail {\n\ntemplate\nstruct seq { };\n\ntemplate\nstruct seq_gen : seq_gen { };\n\ntemplate\nstruct seq_gen<0, S...> {\n\tusing type = seq;\n};\n\ntemplate \nusing tuple_seq = typename seq_gen::value>::type;\n\ntemplate \nusing enable_if_t = typename std::enable_if::type;\n\nstruct Holder {\n\tvirtual ~Holder() {\n\t\t\n\t}\n};\n\ntemplate\nstruct InstanceHolder : Holder {\n\tInstanceHolder(std::shared_ptr instance) : _instance{instance} {}\n\t\n\tstd::shared_ptr getInstance() const {\n\t\treturn _instance;\n\t}\n\t\nprivate:\n\tstd::shared_ptr _instance;\n};\n\ntemplate\nstruct CallbackHolder : Holder {\n\tusing callback_t = std::function(Args...)>;\n\n\tCallbackHolder(callback_t callback) : _callback{callback} {}\n\t\n\tcallback_t getCallback() const {\n\t\treturn _callback;\n\t}\nprivate:\n\tcallback_t _callback;\n};\n\n} \/\/ namespace detail\n\nstruct Container : std::enable_shared_from_this {\n\ttemplate\n\tvoid instance(std::shared_ptr service) {\n\t\tstatic_assert(std::is_base_of>::value, \"instance only accept Single Service instance.\");\n\t\tcall_save_instance(service, detail::tuple_seq::ParentTypes>{});\n\t}\n\t\n\ttemplate\n\tvoid instance() {\n\t\tstatic_assert(std::is_base_of>::value, \"instance only accept Single Service instance.\");\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\tinstance(make_service(detail::tuple_seq{}, dependencies));\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(!std::is_abstract::value && !std::is_base_of::value), std::shared_ptr> service() {\n\t\treturn get_service();\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(std::is_same::value), std::shared_ptr> service() {\n\t\treturn shared_from_this();\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(std::is_base_of::value && !std::is_same::value), std::shared_ptr> service() {\n\t\tauto service = std::dynamic_pointer_cast(shared_from_this());\n\t\tif (service) {\n\t\t\treturn service;\n\t\t} else {\n\t\t\treturn nullptr;\n\t\t}\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t::value, std::shared_ptr> service() {\n\t\tauto it = _services.find(typeid(T).name());\n\t\tif (it != _services.end()) {\n\t\t\tauto holder = dynamic_cast*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getInstance();\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\t\n\ttemplate\n\tvoid callback(U callback) {\n\t\tstatic_assert(!std::is_base_of>::value, \"instance does not accept Single Service.\");\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tsave_callback(detail::tuple_seq{}, callback);\n\t}\n\t\n\tvirtual void init(){}\n\t\nprivate:\n\ttemplate\n\tdetail::enable_if_t>::value, std::shared_ptr> get_service() {\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto it = _services.find(typeid(T).name());\n\t\tif (it == _services.end()) {\n\t\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\t\tauto service = make_service(detail::tuple_seq{}, dependencies);\n\t\t\tinstance(service);\n\t\t\treturn service;\n\t\t} else {\n\t\t\tauto holder = dynamic_cast*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getInstance();\n\t\t\t} else {\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t}\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t>::value, std::shared_ptr> get_service() {\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\tauto service = make_service(detail::tuple_seq{}, dependencies);\n\t\t\n\t\treturn service;\n\t}\n\t\n\ttemplate\n\tvoid call_save_instance(std::shared_ptr service, detail::seq) {\n\t\tsave_instance::ParentTypes>::type...>(service);\n\t}\n\t\n\ttemplate\n\tstd::tuple::type>...> dependency(detail::seq) {\n\t\treturn std::make_tuple(service::type>()...);\n\t}\n\t\n\ttemplate\n\tstd::shared_ptr callback_make_service(detail::seq seq, Tuple dependencies) const {\n\t\tauto it = _callbacks.find(typeid(T).name());\n\t\tif (it != _callbacks.end()) {\n\t\t\tauto holder = dynamic_cast::type...>*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getCallback()(std::get(dependencies)...);\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\t\n\ttemplate\n\tstd::shared_ptr make_service(detail::seq seq, Tuple dependencies) const {\n\t\tauto service = callback_make_service(seq, dependencies);\n\t\tif (service) {\n\t\t\treturn service;\n\t\t}\n\t\treturn std::make_shared(std::get(dependencies)...);\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr service) {\n\t\tsave_instance(service);\n\t\tsave_instance(service);\n\t}\n\t\n\ttemplate\n\tvoid save_instance (std::shared_ptr service) {\n\t\t_services[typeid(T).name()] = std::unique_ptr>(new detail::InstanceHolder(service));\n\t}\n\t\n\ttemplate\n\tvoid save_callback (detail::seq, U callback) {\n\t\t_callbacks[typeid(T).name()] = std::unique_ptr::type>...>>(new detail::CallbackHolder::type>...>(callback));\n\t}\n\t\n\tstd::unordered_map> _callbacks;\n\tstd::unordered_map> _services;\n};\n\ntemplate\nstd::shared_ptr make_container(Args&& ...args) {\n\tstatic_assert(std::is_base_of::value, \"make_container only accept container types.\");\n\tauto container = std::make_shared(std::forward(args)...);\n\tcontainer->init();\n\treturn container;\n}\n\n} \/\/ namespace kgr\n\nRemove check for service#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace kgr {\n\ntemplate\nstruct Dependency {\n\tusing DependenciesTypes = std::tuple;\n};\n\nusing NoDependencies = Dependency<>;\n\nstruct Single {\n\tusing ParentTypes = std::tuple<>;\n};\n\ntemplate\nstruct Service;\n\ntemplate\nstruct Overrides : Single {\n\tusing ParentTypes = std::tuple;\n};\n\nnamespace detail {\n\ntemplate\nstruct seq { };\n\ntemplate\nstruct seq_gen : seq_gen { };\n\ntemplate\nstruct seq_gen<0, S...> {\n\tusing type = seq;\n};\n\ntemplate \nusing tuple_seq = typename seq_gen::value>::type;\n\ntemplate \nusing enable_if_t = typename std::enable_if::type;\n\nstruct Holder {\n\tvirtual ~Holder() {\n\t\t\n\t}\n};\n\ntemplate\nstruct InstanceHolder : Holder {\n\tInstanceHolder(std::shared_ptr instance) : _instance{instance} {}\n\t\n\tstd::shared_ptr getInstance() const {\n\t\treturn _instance;\n\t}\n\t\nprivate:\n\tstd::shared_ptr _instance;\n};\n\ntemplate\nstruct CallbackHolder : Holder {\n\tusing callback_t = std::function(Args...)>;\n\n\tCallbackHolder(callback_t callback) : _callback{callback} {}\n\t\n\tcallback_t getCallback() const {\n\t\treturn _callback;\n\t}\nprivate:\n\tcallback_t _callback;\n};\n\n} \/\/ namespace detail\n\nstruct Container : std::enable_shared_from_this {\n\ttemplate\n\tvoid instance(std::shared_ptr service) {\n\t\tstatic_assert(std::is_base_of>::value, \"instance only accept Single Service instance.\");\n\t\tcall_save_instance(service, detail::tuple_seq::ParentTypes>{});\n\t}\n\t\n\ttemplate\n\tvoid instance() {\n\t\tstatic_assert(std::is_base_of>::value, \"instance only accept Single Service instance.\");\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\tinstance(make_service(detail::tuple_seq{}, dependencies));\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(!std::is_abstract::value && !std::is_base_of::value), std::shared_ptr> service() {\n\t\treturn get_service();\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(std::is_same::value), std::shared_ptr> service() {\n\t\treturn shared_from_this();\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(std::is_base_of::value && !std::is_same::value), std::shared_ptr> service() {\n\t\treturn std::dynamic_pointer_cast(shared_from_this());\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t::value, std::shared_ptr> service() {\n\t\tauto it = _services.find(typeid(T).name());\n\t\tif (it != _services.end()) {\n\t\t\tauto holder = dynamic_cast*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getInstance();\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\t\n\ttemplate\n\tvoid callback(U callback) {\n\t\tstatic_assert(!std::is_base_of>::value, \"instance does not accept Single Service.\");\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tsave_callback(detail::tuple_seq{}, callback);\n\t}\n\t\n\tvirtual void init(){}\n\t\nprivate:\n\ttemplate\n\tdetail::enable_if_t>::value, std::shared_ptr> get_service() {\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto it = _services.find(typeid(T).name());\n\t\tif (it == _services.end()) {\n\t\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\t\tauto service = make_service(detail::tuple_seq{}, dependencies);\n\t\t\tinstance(service);\n\t\t\treturn service;\n\t\t} else {\n\t\t\tauto holder = dynamic_cast*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getInstance();\n\t\t\t} else {\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t}\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t>::value, std::shared_ptr> get_service() {\n\t\tusing DependenciesTypes = typename Service::DependenciesTypes;\n\t\tauto dependencies = dependency(detail::tuple_seq{});\n\t\tauto service = make_service(detail::tuple_seq{}, dependencies);\n\t\t\n\t\treturn service;\n\t}\n\t\n\ttemplate\n\tvoid call_save_instance(std::shared_ptr service, detail::seq) {\n\t\tsave_instance::ParentTypes>::type...>(service);\n\t}\n\t\n\ttemplate\n\tstd::tuple::type>...> dependency(detail::seq) {\n\t\treturn std::make_tuple(service::type>()...);\n\t}\n\t\n\ttemplate\n\tstd::shared_ptr callback_make_service(detail::seq seq, Tuple dependencies) const {\n\t\tauto it = _callbacks.find(typeid(T).name());\n\t\tif (it != _callbacks.end()) {\n\t\t\tauto holder = dynamic_cast::type...>*>(it->second.get());\n\t\t\tif (holder) {\n\t\t\t\treturn holder->getCallback()(std::get(dependencies)...);\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\t\n\ttemplate\n\tstd::shared_ptr make_service(detail::seq seq, Tuple dependencies) const {\n\t\tauto service = callback_make_service(seq, dependencies);\n\t\tif (service) {\n\t\t\treturn service;\n\t\t}\n\t\treturn std::make_shared(std::get(dependencies)...);\n\t}\n\t\n\ttemplate\n\tdetail::enable_if_t<(sizeof...(Others) > 0), void> save_instance(std::shared_ptr service) {\n\t\tsave_instance(service);\n\t\tsave_instance(service);\n\t}\n\t\n\ttemplate\n\tvoid save_instance (std::shared_ptr service) {\n\t\t_services[typeid(T).name()] = std::unique_ptr>(new detail::InstanceHolder(service));\n\t}\n\t\n\ttemplate\n\tvoid save_callback (detail::seq, U callback) {\n\t\t_callbacks[typeid(T).name()] = std::unique_ptr::type>...>>(new detail::CallbackHolder::type>...>(callback));\n\t}\n\t\n\tstd::unordered_map> _callbacks;\n\tstd::unordered_map> _services;\n};\n\ntemplate\nstd::shared_ptr make_container(Args&& ...args) {\n\tstatic_assert(std::is_base_of::value, \"make_container only accept container types.\");\n\tauto container = std::make_shared(std::forward(args)...);\n\tcontainer->init();\n\treturn container;\n}\n\n} \/\/ namespace kgr\n\n<|endoftext|>"} {"text":"#ifndef STDC11_HH\n#define STDC11_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* **\n * This file is juste a set of convenient standard methods from std11 such\n * as smart pointer and other stuff.\n *\/\n\n#define sign_form(T) typename std::make_signed::type\n#define sign_form_(T) std::make_signed::type\n\nnamespace std\n{\n\n template< typename T >\n inline T convert(const std::string& str)\n {\n std::istringstream iss(str);\n T obj;\n\n iss >> std::ws >> obj >> std::ws;\n\n if(!iss.eof())\n throw \"dammit!\";\n\n return obj; \n }\n const double PI = 3.14159265;\n\n template\n bool is_signed_cast_safe(T a)\n {\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n static_assert(!std::numeric_limits::is_signed, \"type must be unsigned\");\n\n typedef typename std::make_signed::type signed_T;\n typedef typename std::make_unsigned::type unsigned_T;\n\n return a < (unsigned_T) std::numeric_limits::max() ;\n \/\/&& a < (unsigned)std::numeric_limits::type>::max();\n }\n\n template\n bool is_cast_lossless(T a)\n {\n if(std::numeric_limits::digits >= std::numeric_limits::digits)\n return true;\n\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n\n return a <= static_cast(std::numeric_limits::max()) && \n a >= static_cast(std::numeric_limits::min());\n }\n\n template \n struct IF;\n template \n struct IF\n {\n typedef T2 res;\n };\n template \n struct IF\n {\n typedef T1 res;\n };\n\n template \n std::string to_string (T num)\n {\n std::ostringstream ss;\n ss << std::setprecision(3) << num;\n return ss.str();\n }\n\n template\n T round(T v)\n {\n return ::round(v);\n }\n\n template\n void tokenize(const std::string &str,\n ContainerT &tokens,\n const std::string &delimiters = \" \",\n bool trimEmpty = false)\n {\n std::string::size_type pos, lastPos = 0;\n while(true)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n break;\n else\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*pos-lastPos ));\n lastPos = pos + 1;\n }\n }\n\n}\n\n#endif\n\nFix tokenize#ifndef STDC11_HH\n#define STDC11_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* **\n * This file is juste a set of convenient standard methods from std11 such\n * as smart pointer and other stuff.\n *\/\n\n#define sign_form(T) typename std::make_signed::type\n#define sign_form_(T) std::make_signed::type\n\nnamespace std\n{\n\n template< typename T >\n inline T convert(const std::string& str)\n {\n std::istringstream iss(str);\n T obj;\n\n iss >> std::ws >> obj >> std::ws;\n\n if(!iss.eof())\n throw \"dammit!\";\n\n return obj; \n }\n const double PI = 3.14159265;\n\n template\n bool is_signed_cast_safe(T a)\n {\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n static_assert(!std::numeric_limits::is_signed, \"type must be unsigned\");\n\n typedef typename std::make_signed::type signed_T;\n typedef typename std::make_unsigned::type unsigned_T;\n\n return a < (unsigned_T) std::numeric_limits::max() ;\n \/\/&& a < (unsigned)std::numeric_limits::type>::max();\n }\n\n template\n bool is_cast_lossless(T a)\n {\n if(std::numeric_limits::digits >= std::numeric_limits::digits)\n return true;\n\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n\n return a <= static_cast(std::numeric_limits::max()) && \n a >= static_cast(std::numeric_limits::min());\n }\n\n template \n struct IF;\n template \n struct IF\n {\n typedef T2 res;\n };\n template \n struct IF\n {\n typedef T1 res;\n };\n\n template \n std::string to_string (T num)\n {\n std::ostringstream ss;\n ss << std::setprecision(3) << num;\n return ss.str();\n }\n\n template\n T round(T v)\n {\n return ::round(v);\n }\n\n template\n void tokenize(const std::string &str,\n ContainerT &tokens,\n const std::string &delimiters = \" \",\n bool trimEmpty = false)\n {\n std::string::size_type pos, lastPos = 0;\n while(true)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n if(lastPos != str.length())\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(str.length()-lastPos) ));\n break;\n }\n else\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(pos-lastPos) ));\n lastPos = pos + 1;\n }\n }\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"Update Euler Totient.cpp<|endoftext|>"} {"text":"\/\/ DESCRIPTION: GenericSLM device adapter\n\/\/ COPYRIGHT: 2009-2016 Regents of the University of California\n\/\/ 2016 Open Imaging, Inc.\n\/\/\n\/\/ AUTHOR: Arthur Edelstein, arthuredelstein@gmail.com, 3\/17\/2009\n\/\/ Mark Tsuchida (refactor\/rewrite), 2016\n\/\/\n\/\/ LICENSE: This file is distributed under the BSD license.\n\/\/ License text is included with the source distribution.\n\/\/\n\/\/ This file is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/ IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n\n#include \"GenericSLM.h\"\n\n#include \"Monitors.h\"\n#include \"OffscreenBuffer.h\"\n#include \"SLMWindow.h\"\n#include \"SleepBlocker.h\"\n\n#include \"ModuleInterface.h\"\n#include \"DeviceUtils.h\"\n\n#include \n\n#include \n\n\nconst char* g_GenericSLMName = \"GenericSLM\";\nconst char* g_PropName_GraphicsPort = \"GraphicsPort\";\nconst char* g_PropName_Inversion = \"Inversion\";\nconst char* g_PropName_MonoColor = \"MonochromeColor\";\n\n\nMODULE_API void InitializeModuleData()\n{\n RegisterDevice(g_GenericSLMName, MM::SLMDevice,\n \"Spatial light modulator controlled through computer graphics output\");\n}\n\n\nMODULE_API MM::Device* CreateDevice(const char* deviceName)\n{\n if (deviceName == 0)\n return 0;\n\n if (strcmp(deviceName, g_GenericSLMName) == 0)\n {\n GenericSLM* pGenericSLM = new GenericSLM(g_GenericSLMName);\n return pGenericSLM;\n }\n\n return 0;\n}\n\n\nMODULE_API void DeleteDevice(MM::Device* pDevice)\n{\n delete pDevice;\n}\n\n\nGenericSLM::GenericSLM(const char* name) :\n name_(name),\n window_(0),\n offscreen_(0),\n sleepBlocker_(0),\n shouldBlitInverted_(false),\n invert_(false),\n inversionStr_(\"Off\"),\n monoColor_(SLM_COLOR_WHITE),\n monoColorStr_(\"White\")\n{\n SetErrorText(DEVICE_ERR, \"An error occurred\");\n \/\/ TODO We can do better than that\n\n availableMonitors_ = GetMonitorNames(true, false);\n\n \/\/ Create pre-init properties\n\n CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);\n CreateProperty(MM::g_Keyword_Description, \"SLM controlled by computer display adapter output\", MM::String, true);\n\n CreateStringProperty(g_PropName_GraphicsPort, \"Undefined\", false, 0, true);\n AddAllowedValue(g_PropName_GraphicsPort, \"Undefined\", 0); \/\/ Prevent empty list\n for (unsigned i = 0; i < availableMonitors_.size(); ++i)\n {\n AddAllowedValue(g_PropName_GraphicsPort,\n availableMonitors_[i].c_str(), i + 1);\n }\n\n CreateStringProperty(g_PropName_Inversion, inversionStr_.c_str(), false,\n new CPropertyAction(this, &GenericSLM::OnInversion), false);\n AddAllowedValue(g_PropName_Inversion, \"Off\", 0);\n AddAllowedValue(g_PropName_Inversion, \"On\", 1);\n\n CreateProperty(g_PropName_MonoColor, monoColorStr_.c_str(), MM::String, false,\n new CPropertyAction(this, &GenericSLM::OnMonochromeColor), false);\n AddAllowedValue(g_PropName_MonoColor, \"White\", SLM_COLOR_WHITE);\n AddAllowedValue(g_PropName_MonoColor, \"Red\", SLM_COLOR_RED);\n AddAllowedValue(g_PropName_MonoColor, \"Green\", SLM_COLOR_GREEN);\n AddAllowedValue(g_PropName_MonoColor, \"Blue\", SLM_COLOR_BLUE);\n AddAllowedValue(g_PropName_MonoColor, \"Cyan\", SLM_COLOR_CYAN);\n AddAllowedValue(g_PropName_MonoColor, \"Magenta\", SLM_COLOR_MAGENTA);\n AddAllowedValue(g_PropName_MonoColor, \"Yellow\", SLM_COLOR_YELLOW);\n}\n\n\nGenericSLM::~GenericSLM()\n{\n Shutdown();\n}\n\n\nvoid GenericSLM::GetName(char* name) const\n{\n CDeviceUtils::CopyLimitedString(name, name_.c_str());\n}\n\n\nint GenericSLM::Initialize()\n{\n Shutdown();\n\n long index;\n int err = GetCurrentPropertyData(g_PropName_GraphicsPort, index);\n if (err != DEVICE_OK)\n return err;\n if (index == 0)\n return DEVICE_ERR; \/\/ TODO \"Graphics port not selected\"\n monitorName_ = availableMonitors_[index - 1];\n\n if (!DetachMonitorFromDesktop(monitorName_))\n {\n monitorName_ = \"\";\n return DEVICE_ERR; \/\/ TODO \"Cannot detach monitor from desktop\"\n }\n\n std::vector otherAttachedMonitors(GetMonitorNames(false, true));\n\n LONG posX, posY;\n GetRightmostMonitorTopRight(otherAttachedMonitors, posX, posY);\n\n if (!AttachMonitorToDesktop(monitorName_, posX, posY))\n {\n monitorName_ = \"\";\n return DEVICE_ERR; \/\/ TODO \"Cannot attach monitor to desktop\"\n }\n\n LONG x, y, w, h;\n GetMonitorRect(monitorName_, x, y, w, h);\n\n window_ = new SLMWindow(\"MM_SLM\", x, y, w, h);\n window_->Show();\n\n offscreen_ = new OffscreenBuffer(window_->GetDC(), w, h);\n\n RECT mouseClipRect;\n if (GetBoundingRect(otherAttachedMonitors, mouseClipRect))\n sleepBlocker_ = new SleepBlocker(mouseClipRect);\n else\n sleepBlocker_ = new SleepBlocker();\n sleepBlocker_->Start();\n\n return DEVICE_OK;\n}\n\n\nint GenericSLM::Shutdown()\n{\n if (sleepBlocker_)\n {\n sleepBlocker_->Stop();\n delete sleepBlocker_;\n sleepBlocker_ = 0;\n }\n\n if (offscreen_)\n {\n delete offscreen_;\n offscreen_ = 0;\n }\n\n if (window_)\n {\n delete window_;\n window_ = 0;\n }\n\n if (!monitorName_.empty())\n {\n DetachMonitorFromDesktop(monitorName_);\n monitorName_ = \"\";\n }\n\n return DEVICE_OK;\n}\n\n\nbool GenericSLM::Busy()\n{\n \/\/ TODO We _could_ make the wait for vertical sync asynchronous\n \/\/ (Make sure first that Projector knows to wait for non-busy)\n return false;\n}\n\n\nunsigned int GenericSLM::GetWidth()\n{\n return offscreen_ ? offscreen_->GetWidth() : 0;\n}\n\n\nunsigned int GenericSLM::GetHeight()\n{\n return offscreen_ ? offscreen_->GetHeight() : 0;\n}\n\n\nunsigned int GenericSLM::GetNumberOfComponents()\n{\n return 3;\n}\n\n\nunsigned int GenericSLM::GetBytesPerPixel()\n{\n return 4;\n}\n\n\nint GenericSLM::SetExposure(double)\n{\n \/\/ ignore for now.\n return DEVICE_OK;\n}\n\n\ndouble GenericSLM::GetExposure()\n{\n return 0;\n}\n\n\nint GenericSLM::SetImage(unsigned char* pixels)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n offscreen_->DrawImage(pixels, monoColor_, invert_);\n return DEVICE_OK;\n}\n\n\nint GenericSLM::SetImage(unsigned int* pixels)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n offscreen_->DrawImage(pixels);\n shouldBlitInverted_ = invert_;\n return DEVICE_OK;\n}\n\n\nint GenericSLM::SetPixelsTo(unsigned char intensity)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n intensity ^= (invert_ ? 0xff : 0x00);\n\n unsigned char redMask = (monoColor_ & SLM_COLOR_RED) ? 0xff : 0x00;\n unsigned char greenMask = (monoColor_ & SLM_COLOR_GREEN) ? 0xff : 0x00;\n unsigned char blueMask = (monoColor_ & SLM_COLOR_BLUE) ? 0xff : 0x00;\n\n COLORREF color(RGB(intensity & redMask,\n intensity & greenMask,\n intensity & blueMask));\n\n offscreen_->FillWithColor(color);\n shouldBlitInverted_ = false;\n return DisplayImage();\n}\n\n\nint GenericSLM::SetPixelsTo(unsigned char red, unsigned char green, unsigned char blue)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n unsigned char xorMask = invert_ ? 0xff : 0x00;\n\n COLORREF color(RGB(red ^ xorMask, green ^ xorMask, blue ^ xorMask));\n\n offscreen_->FillWithColor(color);\n shouldBlitInverted_ = false;\n return DisplayImage();\n}\n\n\nint GenericSLM::DisplayImage()\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n HDC onscreenDC = window_->GetDC();\n DWORD op = shouldBlitInverted_ ? NOTSRCCOPY : SRCCOPY;\n\n refreshWaiter_.WaitForVerticalBlank();\n offscreen_->BlitTo(onscreenDC, op);\n return DEVICE_OK;\n}\n\n\nint GenericSLM::OnInversion(MM::PropertyBase* pProp, MM::ActionType eAct)\n{\n if (eAct == MM::BeforeGet)\n {\n pProp->Set(inversionStr_.c_str());\n }\n else if (eAct == MM::AfterSet)\n {\n pProp->Get(inversionStr_);\n long data;\n int ret = GetPropertyData(g_PropName_Inversion, inversionStr_.c_str(),\n data);\n if (ret != DEVICE_OK)\n return ret;\n invert_ = (data != 0);\n }\n\n return DEVICE_OK;\n}\n\n\nint GenericSLM::OnMonochromeColor(MM::PropertyBase* pProp, MM::ActionType eAct)\n{\n if (eAct == MM::BeforeGet)\n {\n pProp->Set(monoColorStr_.c_str());\n }\n else if (eAct == MM::AfterSet)\n {\n pProp->Get(monoColorStr_);\n long data;\n int ret = GetPropertyData(g_PropName_MonoColor,\n monoColorStr_.c_str(), data);\n if (ret != DEVICE_OK)\n return ret;\n monoColor_ = (SLMColor)data;\n }\n\n return DEVICE_OK;\n}\nGenericSLM: Add a simple test mode\/\/ DESCRIPTION: GenericSLM device adapter\n\/\/ COPYRIGHT: 2009-2016 Regents of the University of California\n\/\/ 2016 Open Imaging, Inc.\n\/\/\n\/\/ AUTHOR: Arthur Edelstein, arthuredelstein@gmail.com, 3\/17\/2009\n\/\/ Mark Tsuchida (refactor\/rewrite), 2016\n\/\/\n\/\/ LICENSE: This file is distributed under the BSD license.\n\/\/ License text is included with the source distribution.\n\/\/\n\/\/ This file is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/ IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.\n\n#include \"GenericSLM.h\"\n\n#include \"Monitors.h\"\n#include \"OffscreenBuffer.h\"\n#include \"SLMWindow.h\"\n#include \"SleepBlocker.h\"\n\n#include \"ModuleInterface.h\"\n#include \"DeviceUtils.h\"\n\n#include \n\n#include \n\n\nconst char* g_GenericSLMName = \"GenericSLM\";\nconst char* g_PropName_GraphicsPort = \"GraphicsPort\";\nconst char* g_PropName_Inversion = \"Inversion\";\nconst char* g_PropName_MonoColor = \"MonochromeColor\";\n\n\nMODULE_API void InitializeModuleData()\n{\n RegisterDevice(g_GenericSLMName, MM::SLMDevice,\n \"Spatial light modulator controlled through computer graphics output\");\n}\n\n\nMODULE_API MM::Device* CreateDevice(const char* deviceName)\n{\n if (deviceName == 0)\n return 0;\n\n if (strcmp(deviceName, g_GenericSLMName) == 0)\n {\n GenericSLM* pGenericSLM = new GenericSLM(g_GenericSLMName);\n return pGenericSLM;\n }\n\n return 0;\n}\n\n\nMODULE_API void DeleteDevice(MM::Device* pDevice)\n{\n delete pDevice;\n}\n\n\nGenericSLM::GenericSLM(const char* name) :\n name_(name),\n window_(0),\n offscreen_(0),\n sleepBlocker_(0),\n shouldBlitInverted_(false),\n invert_(false),\n inversionStr_(\"Off\"),\n monoColor_(SLM_COLOR_WHITE),\n monoColorStr_(\"White\")\n{\n SetErrorText(DEVICE_ERR, \"An error occurred\");\n \/\/ TODO We can do better than that\n\n availableMonitors_ = GetMonitorNames(true, false);\n\n \/\/ Create pre-init properties\n\n CreateProperty(MM::g_Keyword_Name, name_.c_str(), MM::String, true);\n CreateProperty(MM::g_Keyword_Description, \"SLM controlled by computer display adapter output\", MM::String, true);\n\n CreateStringProperty(g_PropName_GraphicsPort, \"Test128x128\", false, 0, true);\n AddAllowedValue(g_PropName_GraphicsPort, \"Test128x128\", 0); \/\/ Prevent empty list\n for (unsigned i = 0; i < availableMonitors_.size(); ++i)\n {\n AddAllowedValue(g_PropName_GraphicsPort,\n availableMonitors_[i].c_str(), i + 1);\n }\n\n CreateStringProperty(g_PropName_Inversion, inversionStr_.c_str(), false,\n new CPropertyAction(this, &GenericSLM::OnInversion), false);\n AddAllowedValue(g_PropName_Inversion, \"Off\", 0);\n AddAllowedValue(g_PropName_Inversion, \"On\", 1);\n\n CreateProperty(g_PropName_MonoColor, monoColorStr_.c_str(), MM::String, false,\n new CPropertyAction(this, &GenericSLM::OnMonochromeColor), false);\n AddAllowedValue(g_PropName_MonoColor, \"White\", SLM_COLOR_WHITE);\n AddAllowedValue(g_PropName_MonoColor, \"Red\", SLM_COLOR_RED);\n AddAllowedValue(g_PropName_MonoColor, \"Green\", SLM_COLOR_GREEN);\n AddAllowedValue(g_PropName_MonoColor, \"Blue\", SLM_COLOR_BLUE);\n AddAllowedValue(g_PropName_MonoColor, \"Cyan\", SLM_COLOR_CYAN);\n AddAllowedValue(g_PropName_MonoColor, \"Magenta\", SLM_COLOR_MAGENTA);\n AddAllowedValue(g_PropName_MonoColor, \"Yellow\", SLM_COLOR_YELLOW);\n}\n\n\nGenericSLM::~GenericSLM()\n{\n Shutdown();\n}\n\n\nvoid GenericSLM::GetName(char* name) const\n{\n CDeviceUtils::CopyLimitedString(name, name_.c_str());\n}\n\n\nint GenericSLM::Initialize()\n{\n Shutdown();\n\n long index;\n int err = GetCurrentPropertyData(g_PropName_GraphicsPort, index);\n if (err != DEVICE_OK)\n return err;\n if (index > 0) \/\/ Unless test mode\n monitorName_ = availableMonitors_[index - 1];\n\n if (!monitorName_.empty() && !DetachMonitorFromDesktop(monitorName_))\n {\n monitorName_ = \"\";\n return DEVICE_ERR; \/\/ TODO \"Cannot detach monitor from desktop\"\n }\n\n std::vector otherAttachedMonitors(GetMonitorNames(false, true));\n\n LONG posX, posY;\n GetRightmostMonitorTopRight(otherAttachedMonitors, posX, posY);\n\n if (!monitorName_.empty() &&\n !AttachMonitorToDesktop(monitorName_, posX, posY))\n {\n monitorName_ = \"\";\n return DEVICE_ERR; \/\/ TODO \"Cannot attach monitor to desktop\"\n }\n\n LONG x, y, w, h;\n if (!monitorName_.empty())\n {\n GetMonitorRect(monitorName_, x, y, w, h);\n }\n else \/\/ Test mode\n {\n x = y = 0;\n w = h = 128;\n }\n\n window_ = new SLMWindow(\"MM_SLM\", x, y, w, h);\n window_->Show();\n\n offscreen_ = new OffscreenBuffer(window_->GetDC(), w, h);\n\n RECT mouseClipRect;\n if (GetBoundingRect(otherAttachedMonitors, mouseClipRect))\n sleepBlocker_ = new SleepBlocker(mouseClipRect);\n else\n sleepBlocker_ = new SleepBlocker();\n sleepBlocker_->Start();\n\n return DEVICE_OK;\n}\n\n\nint GenericSLM::Shutdown()\n{\n if (sleepBlocker_)\n {\n sleepBlocker_->Stop();\n delete sleepBlocker_;\n sleepBlocker_ = 0;\n }\n\n if (offscreen_)\n {\n delete offscreen_;\n offscreen_ = 0;\n }\n\n if (window_)\n {\n delete window_;\n window_ = 0;\n }\n\n if (!monitorName_.empty())\n {\n DetachMonitorFromDesktop(monitorName_);\n monitorName_ = \"\";\n }\n\n return DEVICE_OK;\n}\n\n\nbool GenericSLM::Busy()\n{\n \/\/ TODO We _could_ make the wait for vertical sync asynchronous\n \/\/ (Make sure first that Projector knows to wait for non-busy)\n return false;\n}\n\n\nunsigned int GenericSLM::GetWidth()\n{\n return offscreen_ ? offscreen_->GetWidth() : 0;\n}\n\n\nunsigned int GenericSLM::GetHeight()\n{\n return offscreen_ ? offscreen_->GetHeight() : 0;\n}\n\n\nunsigned int GenericSLM::GetNumberOfComponents()\n{\n return 3;\n}\n\n\nunsigned int GenericSLM::GetBytesPerPixel()\n{\n return 4;\n}\n\n\nint GenericSLM::SetExposure(double)\n{\n \/\/ ignore for now.\n return DEVICE_OK;\n}\n\n\ndouble GenericSLM::GetExposure()\n{\n return 0;\n}\n\n\nint GenericSLM::SetImage(unsigned char* pixels)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n offscreen_->DrawImage(pixels, monoColor_, invert_);\n return DEVICE_OK;\n}\n\n\nint GenericSLM::SetImage(unsigned int* pixels)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n offscreen_->DrawImage(pixels);\n shouldBlitInverted_ = invert_;\n return DEVICE_OK;\n}\n\n\nint GenericSLM::SetPixelsTo(unsigned char intensity)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n intensity ^= (invert_ ? 0xff : 0x00);\n\n unsigned char redMask = (monoColor_ & SLM_COLOR_RED) ? 0xff : 0x00;\n unsigned char greenMask = (monoColor_ & SLM_COLOR_GREEN) ? 0xff : 0x00;\n unsigned char blueMask = (monoColor_ & SLM_COLOR_BLUE) ? 0xff : 0x00;\n\n COLORREF color(RGB(intensity & redMask,\n intensity & greenMask,\n intensity & blueMask));\n\n offscreen_->FillWithColor(color);\n shouldBlitInverted_ = false;\n return DisplayImage();\n}\n\n\nint GenericSLM::SetPixelsTo(unsigned char red, unsigned char green, unsigned char blue)\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n unsigned char xorMask = invert_ ? 0xff : 0x00;\n\n COLORREF color(RGB(red ^ xorMask, green ^ xorMask, blue ^ xorMask));\n\n offscreen_->FillWithColor(color);\n shouldBlitInverted_ = false;\n return DisplayImage();\n}\n\n\nint GenericSLM::DisplayImage()\n{\n if (!offscreen_)\n return DEVICE_ERR;\n\n HDC onscreenDC = window_->GetDC();\n DWORD op = shouldBlitInverted_ ? NOTSRCCOPY : SRCCOPY;\n\n refreshWaiter_.WaitForVerticalBlank();\n offscreen_->BlitTo(onscreenDC, op);\n return DEVICE_OK;\n}\n\n\nint GenericSLM::OnInversion(MM::PropertyBase* pProp, MM::ActionType eAct)\n{\n if (eAct == MM::BeforeGet)\n {\n pProp->Set(inversionStr_.c_str());\n }\n else if (eAct == MM::AfterSet)\n {\n pProp->Get(inversionStr_);\n long data;\n int ret = GetPropertyData(g_PropName_Inversion, inversionStr_.c_str(),\n data);\n if (ret != DEVICE_OK)\n return ret;\n invert_ = (data != 0);\n }\n\n return DEVICE_OK;\n}\n\n\nint GenericSLM::OnMonochromeColor(MM::PropertyBase* pProp, MM::ActionType eAct)\n{\n if (eAct == MM::BeforeGet)\n {\n pProp->Set(monoColorStr_.c_str());\n }\n else if (eAct == MM::AfterSet)\n {\n pProp->Get(monoColorStr_);\n long data;\n int ret = GetPropertyData(g_PropName_MonoColor,\n monoColorStr_.c_str(), data);\n if (ret != DEVICE_OK)\n return ret;\n monoColor_ = (SLMColor)data;\n }\n\n return DEVICE_OK;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ generateSimulatedData.cpp\n\/\/ cPWP\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#include \"generateSimulatedData.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) {\n std::ofstream genomeOut(genomeOutFile);\n genomeOut << \">Fake_scaffold0\";\n \/\/ Set up the random number generator:\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(0, 1);\n \n \n std::string genomeString; \/\/ Will store the genome\n \n\n for (int position; position < totalBases; position++) {\n float rando = dis(gen);\n if (rando < gcContent) {\n if (dis(gen) < 0.50) {\n genomeString += \"C\";\n } else {\n genomeString += \"G\";\n }\n } else {\n if (dis(gen) < 0.50) {\n genomeString += \"A\";\n } else {\n genomeString += \"T\";\n }\n }\n }\n \n int baseCounter = 0;\n for(char& singleBase : genomeString) {\n if (baseCounter % 80 == 0) {\n genomeOut << \"\\n\";\n }\n genomeOut << singleBase;\n baseCounter++;\n }\n \n \/\/ Now index the genome for bwa \n std::cout << \"**********\\nChecking if processor is available to run bwa index...\";\n if (system(NULL)) puts (\"OK\");\n else exit (EXIT_FAILURE);\n std::string bwaIndexCommand = \"bwa index \" + genomeOutFile;\n system(bwaIndexCommand);\n if (system((bwaIndexCommand).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaIndexCommand << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaIndexCommand << \"\\n**********\\n\";\n }\n return 0;\n}\n\n\n\nint generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {\n\/*\/\/ supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed\n \n So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).\n*\/\n\n std::ofstream bamsFile;\n bamsFile.open(\"bamlist.txt\", std::ios::out | std::ios::app);\n \n \n std::cout << \"**********\\nChecking if processor is available to run pirs...\";\n if (system(NULL)) puts (\"OK\");\n else exit (EXIT_FAILURE);\n \n int pirsInd = 0;\n while(pirsInd <= numIndividuals) {\n double mutRate = pirsInd * mutationRateStepSize;\n \/\/ Covert the mutation rate into a string for the system command\n std::ostringstream mutStr;\n mutStr << mutRate;\n std::string mutRateString = mutStr.str();\n \n std::cout << \"**********\\nGenerating reference genome for individual \" << pirsInd << \" using a mutation rate of \" << mutRateString << \" from the reference genome\\n**********\\n\";\n \n \/\/ Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names\n std::ostringstream pirsIndSS;\n std::ostringstream pirsIndNumSS;\n pirsIndSS << \"ind\" << pirsInd;\n pirsIndNumSS << pirsInd;\n std::string pirsIndNum = pirsIndNumSS.str();\n std::string indName = pirsIndSS.str();\n std::string pirsGenomeSTDOUT = indName + \"_genome.stdout\";\n std::string pirsGenomeSTDERR = indName + \"_genome.stderr\";\n \n \/\/ Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize\n \/\/ For this individual, we are not simulating any polymorphisms. So instead of the diploid pirs simulate command, we can use a haploid simulate command on the original reference\n std::string pirsSimSTDOUT = indName + \"_reads.stdout\";\n std::string pirsSimSTDERR = indName + \"_reads.stderr\";\n std::string indReadsPrefix = indName + \"_reads\";\n \n if (pirsInd == 0) {\n std::string pirsSimulateCommandToRun = \"pirs simulate \" + reference + \" -l \" + readLengths + \" -x \" + depth + \" -m \" + libFragmentSize + \" -v \" + stdevLibFragmentSize + \" --no-substitution-errors --no-indel-errors --no-gc-content-bias -o \" + indReadsPrefix + \" >\" + pirsSimSTDOUT + \" 2>\" + pirsSimSTDERR;\n if (system((pirsSimulateCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n }\n } else {\n std::string pirsCommandToRun = \"pirs diploid -s \" + mutRateString + \" -d 0.00 -v 0.00 -S 1234 -o \" + indName + \" \" + reference + \" >\" + pirsGenomeSTDOUT + \" 2>\" + pirsGenomeSTDERR;\n if (system((pirsCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsCommandToRun << \"\\n**********\\n\";\n }\n \/\/ The following file is output by the pirs diploid command:\n std::string mutatedChromosome = indName + \".snp.fa\";\n \n \/\/ After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the\n std::string pirsSimSTDOUT = indName + \"_reads.stdout\";\n std::string pirsSimSTDERR = indName + \"_reads.stderr\";\n std::string indReadsPrefix = indName + \"_reads\";\n std::string pirsSimulateCommandToRun = \"pirs simulate --diploid \" + reference + \" \" + mutatedChromosome + \" -l \" + readLengths + \" -x \" + depth + \" -m \" + libFragmentSize + \" -v \" + stdevLibFragmentSize + \" --no-substitution-errors --no-indel-errors --no-gc-content-bias -o \" + indReadsPrefix + \" >\" + pirsSimSTDOUT + \" 2>\" + pirsSimSTDERR;\n if (system((pirsSimulateCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n }\n }\n \/\/ Generate the bwa mem command and then run it using a system call\n std::string R1 = indReadsPrefix + \"_\" + readLengths + \"_\" + libFragmentSize + \"_1.fq\";\n std::string R2 = indReadsPrefix + \"_\" + readLengths + \"_\" + libFragmentSize + \"_2.fq\";\n std::string bamOut = \"ind\" + pirsIndNum + \".bam\";\n std::string bwaCommandToRun = \"bwa mem -t \" + threads + \" \" + reference + \" \" + R1 + \" \" + R2 + \" | samtools view -bS - | samtools sort -T temp -o \" + bamOut + \" -\";\n if (system((bwaCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n }\n bamsFile << bamOut << std::endl;\n\n \n pirsInd++; \/\/ Move on to the next individual\n }\n \n \/* Implementation with wgsim\n std::cout << \"**********\\nChecking if processor is available to run wgsim...\";\n if (system(NULL)) puts (\"Ok\");\n else exit (EXIT_FAILURE);\n \n int step = 0;\n while(step <= numIndividuals) {\n double mutRate = step * mutationRateStepSize;\n \/\/ Covert the mutation rate into a string for the system command\n std::ostringstream mutStrs;\n mutStrs << mutRate;\n std::string mutRateString = mutStrs.str();\n \n std::cout << \"**********\\nGenerating sequence reads for individual \" << step << \" using a mutation rate of \" << mutRateString << \" from the reference genome\\n**********\\n\";\n \n \/\/ Get the number of the individual as a string\n std::ostringstream stepString;\n stepString << step;\n std::string ind = stepString.str();\n \n \/\/ Generate the output file names as strings\n std::string R1out = \"ind\" + ind + \"_R1.fastq\";\n std::string R2out = \"ind\" + ind + \"_R2.fastq\";\n std::string polymorphismFile = \"ind\" + ind + \"_polymorphisms.txt\";\n \n \/\/ Generate the wgsim command and then run it using a system call\n std::string wgsimCommandToRun = \"wgsim -N \" + numReadPairs + \" -r \" + mutRateString + \" -R 0.00 -X 0.00 -d \" + libFragmentSize + \" -s \" + stdevLibFragmentSize + \" -1 \" + readLengths + \" -2 \" + readLengths + \" -S \" + randomSeed + \" -e0 \" + reference + \" \" + R1out + \" \" + R2out + \" > \" + polymorphismFile; \/\/ No indels, no probability of indel extension, no base call error rates\n if (system((wgsimCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << wgsimCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << wgsimCommandToRun << \"\\n**********\\n\";\n\n }\n \n \/\/ Generate the bwa mem command and then run it using a system call\n std::string bamOut = \"ind\" + ind + \".bam\";\n std::string bwaCommandToRun = \"bwa mem -t \" + threads + \" \" + reference + \" \" + R1out + \" \" + R2out + \" | samtools view -bS - | samtools sort -T temp -o \" + bamOut + \" -\";\n if (system((bwaCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n }\n bamsFile << bamOut << std::endl;\n step++; \/\/ Move on to the next individual\n }\n *\/\n bamsFile.close();\n return 0;\n}\n\n\n\/*\n \/home\/evan\/bin\/angsd0.613\/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1\n \n*\/\n\n\n\/*\n wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt\n wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq\n \n bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq\n bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq\n \n samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam\n samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam\n \n echo -e \"1XcoverageNoErrNoMutSorted.bam\\n1XcoverageNoErr1PercentDivergentSorted.bam\" > bamlist2sim.txt\n \n \/home\/evan\/bin\/angsd0.613\/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &\n \n*\/\n\n\n\n\n\n\/*\n Usage: wgsim [options] \n \n Options:\n -e FLOAT base error rate [0.000]\n -d INT outer distance between the two ends [500]\n -s INT standard deviation [50]\n -N INT number of read pairs [1000000]\n -1 INT length of the first read [70]\n -2 INT length of the second read [70]\n -r FLOAT rate of mutations [0.0010]\n -R FLOAT fraction of indels [0.15]\n -X FLOAT probability an indel is extended [0.30]\n -S INT seed for random generator [-1]\n -h haplotype mode\n \n *\/\n\nMinor change\/\/\n\/\/ generateSimulatedData.cpp\n\/\/ cPWP\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#include \"generateSimulatedData.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) {\n std::ofstream genomeOut(genomeOutFile);\n genomeOut << \">Fake_scaffold0\";\n \/\/ Set up the random number generator:\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(0, 1);\n \n \n std::string genomeString; \/\/ Will store the genome\n \n\n for (int position; position < totalBases; position++) {\n float rando = dis(gen);\n if (rando < gcContent) {\n if (dis(gen) < 0.50) {\n genomeString += \"C\";\n } else {\n genomeString += \"G\";\n }\n } else {\n if (dis(gen) < 0.50) {\n genomeString += \"A\";\n } else {\n genomeString += \"T\";\n }\n }\n }\n \n int baseCounter = 0;\n for(char& singleBase : genomeString) {\n if (baseCounter % 80 == 0) {\n genomeOut << \"\\n\";\n }\n genomeOut << singleBase;\n baseCounter++;\n }\n \n \/\/ Now index the genome for bwa\n std::cout << \"**********\\nChecking if processor is available to run bwa index...\";\n if (system(NULL)) puts (\"OK\");\n else exit (EXIT_FAILURE);\n std::string bwaIndexCommand = \"bwa index \" + genomeOutFile;\n if (system((bwaIndexCommand).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaIndexCommand << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaIndexCommand << \"\\n**********\\n\";\n }\n return 0;\n}\n\n\n\nint generateReadsAndMap (int numIndividuals, double mutationRateStepSize, std::string libFragmentSize, std::string stdevLibFragmentSize, std::string depth, std::string readLengths, std::string randomSeed, std::string reference, std::string threads) {\n\/*\/\/ supply 1) number of individuals, 2) the mutation rate steps between them, 3) the base error rate, 4) the average library fragment size, 5) the standard deviation of the library fragment size, 6) the number of read pairs for each individual, 7) read lengths (per read), 8) random number generator seed\n \n So, for instance, if numIndividuals is 5, and mutationRateSteps is 0.01, then there will be four individuals generated with mutation rate steps of 0.01, 0.02, 0.03, and 0.04 away from the reference genome. Individual 0 is created as being identical to the reference genome (mutation rate parameter set to 0.00).\n*\/\n\n std::ofstream bamsFile;\n bamsFile.open(\"bamlist.txt\", std::ios::out | std::ios::app);\n \n \n std::cout << \"**********\\nChecking if processor is available to run pirs...\";\n if (system(NULL)) puts (\"OK\");\n else exit (EXIT_FAILURE);\n \n int pirsInd = 0;\n while(pirsInd <= numIndividuals) {\n double mutRate = pirsInd * mutationRateStepSize;\n \/\/ Covert the mutation rate into a string for the system command\n std::ostringstream mutStr;\n mutStr << mutRate;\n std::string mutRateString = mutStr.str();\n \n std::cout << \"**********\\nGenerating reference genome for individual \" << pirsInd << \" using a mutation rate of \" << mutRateString << \" from the reference genome\\n**********\\n\";\n \n \/\/ Since we're identifying individuals by the looping variable (an int), we need to convert that to a string to use it in the file names\n std::ostringstream pirsIndSS;\n std::ostringstream pirsIndNumSS;\n pirsIndSS << \"ind\" << pirsInd;\n pirsIndNumSS << pirsInd;\n std::string pirsIndNum = pirsIndNumSS.str();\n std::string indName = pirsIndSS.str();\n std::string pirsGenomeSTDOUT = indName + \"_genome.stdout\";\n std::string pirsGenomeSTDERR = indName + \"_genome.stderr\";\n \n \/\/ Simulate the other strand of the mutated reference genome. On the first individual it should be identical to the reference (because mutStr = 0 * mutationRateStepSize\n \/\/ For this individual, we are not simulating any polymorphisms. So instead of the diploid pirs simulate command, we can use a haploid simulate command on the original reference\n std::string pirsSimSTDOUT = indName + \"_reads.stdout\";\n std::string pirsSimSTDERR = indName + \"_reads.stderr\";\n std::string indReadsPrefix = indName + \"_reads\";\n \n if (pirsInd == 0) {\n std::string pirsSimulateCommandToRun = \"pirs simulate \" + reference + \" -l \" + readLengths + \" -x \" + depth + \" -m \" + libFragmentSize + \" -v \" + stdevLibFragmentSize + \" --no-substitution-errors --no-indel-errors --no-gc-content-bias -o \" + indReadsPrefix + \" >\" + pirsSimSTDOUT + \" 2>\" + pirsSimSTDERR;\n if (system((pirsSimulateCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n }\n } else {\n std::string pirsCommandToRun = \"pirs diploid -s \" + mutRateString + \" -d 0.00 -v 0.00 -S 1234 -o \" + indName + \" \" + reference + \" >\" + pirsGenomeSTDOUT + \" 2>\" + pirsGenomeSTDERR;\n if (system((pirsCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsCommandToRun << \"\\n**********\\n\";\n }\n \/\/ The following file is output by the pirs diploid command:\n std::string mutatedChromosome = indName + \".snp.fa\";\n \n \/\/ After generating the mutated strand for each individual, we simulate reads from both strands for each individual. Parameterize the\n std::string pirsSimSTDOUT = indName + \"_reads.stdout\";\n std::string pirsSimSTDERR = indName + \"_reads.stderr\";\n std::string indReadsPrefix = indName + \"_reads\";\n std::string pirsSimulateCommandToRun = \"pirs simulate --diploid \" + reference + \" \" + mutatedChromosome + \" -l \" + readLengths + \" -x \" + depth + \" -m \" + libFragmentSize + \" -v \" + stdevLibFragmentSize + \" --no-substitution-errors --no-indel-errors --no-gc-content-bias -o \" + indReadsPrefix + \" >\" + pirsSimSTDOUT + \" 2>\" + pirsSimSTDERR;\n if (system((pirsSimulateCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << pirsSimulateCommandToRun << \"\\n**********\\n\";\n }\n }\n \/\/ Generate the bwa mem command and then run it using a system call\n std::string R1 = indReadsPrefix + \"_\" + readLengths + \"_\" + libFragmentSize + \"_1.fq\";\n std::string R2 = indReadsPrefix + \"_\" + readLengths + \"_\" + libFragmentSize + \"_2.fq\";\n std::string bamOut = \"ind\" + pirsIndNum + \".bam\";\n std::string bwaCommandToRun = \"bwa mem -t \" + threads + \" \" + reference + \" \" + R1 + \" \" + R2 + \" | samtools view -bS - | samtools sort -T temp -o \" + bamOut + \" -\";\n if (system((bwaCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n }\n bamsFile << bamOut << std::endl;\n\n \n pirsInd++; \/\/ Move on to the next individual\n }\n \n \/* Implementation with wgsim\n std::cout << \"**********\\nChecking if processor is available to run wgsim...\";\n if (system(NULL)) puts (\"Ok\");\n else exit (EXIT_FAILURE);\n \n int step = 0;\n while(step <= numIndividuals) {\n double mutRate = step * mutationRateStepSize;\n \/\/ Covert the mutation rate into a string for the system command\n std::ostringstream mutStrs;\n mutStrs << mutRate;\n std::string mutRateString = mutStrs.str();\n \n std::cout << \"**********\\nGenerating sequence reads for individual \" << step << \" using a mutation rate of \" << mutRateString << \" from the reference genome\\n**********\\n\";\n \n \/\/ Get the number of the individual as a string\n std::ostringstream stepString;\n stepString << step;\n std::string ind = stepString.str();\n \n \/\/ Generate the output file names as strings\n std::string R1out = \"ind\" + ind + \"_R1.fastq\";\n std::string R2out = \"ind\" + ind + \"_R2.fastq\";\n std::string polymorphismFile = \"ind\" + ind + \"_polymorphisms.txt\";\n \n \/\/ Generate the wgsim command and then run it using a system call\n std::string wgsimCommandToRun = \"wgsim -N \" + numReadPairs + \" -r \" + mutRateString + \" -R 0.00 -X 0.00 -d \" + libFragmentSize + \" -s \" + stdevLibFragmentSize + \" -1 \" + readLengths + \" -2 \" + readLengths + \" -S \" + randomSeed + \" -e0 \" + reference + \" \" + R1out + \" \" + R2out + \" > \" + polymorphismFile; \/\/ No indels, no probability of indel extension, no base call error rates\n if (system((wgsimCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << wgsimCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << wgsimCommandToRun << \"\\n**********\\n\";\n\n }\n \n \/\/ Generate the bwa mem command and then run it using a system call\n std::string bamOut = \"ind\" + ind + \".bam\";\n std::string bwaCommandToRun = \"bwa mem -t \" + threads + \" \" + reference + \" \" + R1out + \" \" + R2out + \" | samtools view -bS - | samtools sort -T temp -o \" + bamOut + \" -\";\n if (system((bwaCommandToRun).c_str()) != 0) {\n std::cout << \"**********\\nFailure running the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n exit(EXIT_FAILURE);\n } else {\n std::cout << \"**********\\nExecuted the following command: \" << bwaCommandToRun << \"\\n**********\\n\";\n }\n bamsFile << bamOut << std::endl;\n step++; \/\/ Move on to the next individual\n }\n *\/\n bamsFile.close();\n return 0;\n}\n\n\n\/*\n \/home\/evan\/bin\/angsd0.613\/angsd -bam bamlist272.txt -out 272torts_allCounts_minmapq20minq30 -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 272tortsangsdMapQ30_allSites.log 2>&1\n \n*\/\n\n\n\/*\n wgsim -N 10000000 -r 0.01 -R 0.00 -X 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq > 1perc_polymorphisms.txt\n wgsim -N 10000000 -r 0.00 -1 100 -2 100 -S11 -e0 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq\n \n bwa mem -t 10 lgv2.fasta r1_noerrnomut_10mil.fq r2_noerrnomut_10mil.fq\n bwa mem -t 10 lgv2.fasta r1_noerr1percDivergent_10mil.fq r2_noerr1percDivergent_10mil.fq\n \n samtools sort -T noMut -o 1XcoverageNoErrNoMutSorted.bam 1XcoverageNoErrNoMut.bam\n samtools sort -T mut -o 1XcoverageNoErr1PercentDivergentSorted.bam 1XcoverageNoErr1PercDivergent.bam\n \n echo -e \"1XcoverageNoErrNoMutSorted.bam\\n1XcoverageNoErr1PercentDivergentSorted.bam\" > bamlist2sim.txt\n \n \/home\/evan\/bin\/angsd0.613\/angsd -bam bamlist2sim.txt -out 2tortsim1perDiv -uniqueOnly 1 -only_proper_pairs 1 -remove_bads 1 -doCounts 1 -nThreads 8 -dumpCounts 4 -doMaf 1 -doMajorMinor 2 -GL 2 -minMapQ 20 -minQ 30 > 2tortANGSD.log 2>&1 &\n \n*\/\n\n\n\n\n\n\/*\n Usage: wgsim [options] \n \n Options:\n -e FLOAT base error rate [0.000]\n -d INT outer distance between the two ends [500]\n -s INT standard deviation [50]\n -N INT number of read pairs [1000000]\n -1 INT length of the first read [70]\n -2 INT length of the second read [70]\n -r FLOAT rate of mutations [0.0010]\n -R FLOAT fraction of indels [0.15]\n -X FLOAT probability an indel is extended [0.30]\n -S INT seed for random generator [-1]\n -h haplotype mode\n \n *\/\n\n<|endoftext|>"} {"text":"\/** feature-selection.cc ---\n *\n * Copyright (C) 2011 OpenCog Foundation\n *\n * Author: Nil Geisweiller \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 v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"feature-selection.h\"\n#include \"..\/feature_optimization.h\"\n#include \"..\/feature_scorer.h\"\n\nusing namespace boost::program_options;\nusing boost::lexical_cast;\nusing boost::assign::list_of;\nusing namespace std;\nusing namespace opencog;\nusing namespace combo;\n\nconst static unsigned max_filename_size = 255;\n\n\/**\n * Display error message about unsupported type and exit\n *\/\nvoid unsupported_type_exit(const type_tree& tt) {\n std::cerr << \"error: type \" << tt << \"currently not supported\" << std::endl;\n exit(1);\n}\nvoid unsupported_type_exit(type_node type) {\n unsupported_type_exit(type_tree(type));\n}\n\nint main(int argc, char** argv) {\n\n unsigned long rand_seed;\n string log_level;\n string log_file;\n bool log_file_dep_opt;\n feature_selection_parameters fs_params;\n\n \/\/ Declare the supported options.\n options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Produce help message.\\n\")\n (opt_desc_str(rand_seed_opt).c_str(),\n value(&rand_seed)->default_value(1),\n \"Random seed.\\n\")\n (opt_desc_str(algo_opt).c_str(),\n value(&fs_params.algorithm)->default_value(hc),\n string(\"Feature selection algorithm. Supported algorithms are \").append(un).append(\" for univariate, \").append(sa).append(\" for simulated annealing, \").append(hc).append(\" for hillclimbing, \").append(inc).append(\" for incremental.\").c_str())\n (opt_desc_str(input_data_file_opt).c_str(),\n value(&fs_params.input_file),\n \"Input table file, DSV file using comman, whitespace or tabulation as seperator.\\n\")\n (opt_desc_str(output_file_opt).c_str(),\n value(&fs_params.output_file),\n \"File where to save the results. If empty then it outputs on the stdout.\\n\")\n (opt_desc_str(initial_feature_opt).c_str(), value >(&fs_params.initial_features),\n \"Initial feature to search from. This option can be used as many times as features to include in the initial feature set. An initial feature set close to the one maximizing the feature quality measure can greatly increase feature selection speed.\\n\")\n (opt_desc_str(max_evals_opt).c_str(),\n value(&fs_params.max_evals)->default_value(10000),\n \"Maximum number of fitness function evaluations.\\n\")\n (opt_desc_str(log_level_opt).c_str(),\n value(&log_level)->default_value(\"DEBUG\"),\n \"Log level, possible levels are NONE, ERROR, WARN, INFO, DEBUG, FINE. Case does not matter.\\n\")\n (opt_desc_str(log_file_dep_opt_opt).c_str(),\n string(\"The name of the log is determined by the options, for instance if feature-selection is called with -r 123 the log name is feature-selection_random-seed_123.log. Note that the name will be truncated in order not to be longer than \").append(lexical_cast(max_filename_size)).append(\" characters.\\n\").c_str())\n (opt_desc_str(log_file_opt).c_str(),\n value(&log_file)->default_value(default_log_file),\n string(\"File name where to write the log. This option is overwritten by \").append(log_file_dep_opt_opt.first).append(\".\\n\").c_str())\n (opt_desc_str(cache_size_opt).c_str(),\n value(&fs_params.cache_size)->default_value(1000000),\n \"Cache size, so that identical candidates are not re-evaluated, 0 means no cache.\\n\")\n (opt_desc_str(complexity_penalty_intensity_opt).c_str(),\n value(&fs_params.cpi)->default_value(0.0),\n \"Intensity of the feature complexity penalty, in [0,+Inf), 0 means no complexity penalty.\\n\")\n (opt_desc_str(confidence_penalty_intensity_opt).c_str(),\n value(&fs_params.confi)->default_value(1.0),\n \"Intensity of the confidence penalty, in [0,+Inf), 0 means no confidence penalty. This parameter influences how much importance we attribute to the confidence of the feature quality measure. The less samples in the data set, the more features the less confidence in the feature set quality measure.\\n\")\n (opt_desc_str(resources_opt).c_str(),\n value(&fs_params.resources)->default_value(10000),\n \"Resources allocated to the learning algorithm that take in input the selected features. More resource means that the feature set can be larger (as long as it has enough confidence). In this case the algo is supposed to be MOSES and the resources is the number of evaluations.\\n\")\n (opt_desc_str(max_score_opt).c_str(),\n value(&fs_params.max_score)->default_value(1),\n \"For MOSES based algorithms. The max score to reach, once reached feature selection halts.\\n\")\n (opt_desc_str(hc_fraction_of_remaining_opt).c_str(),\n value(&fs_params.hc_fraction_of_remaining)->default_value(10),\n \"Hillclimbing parameter. Determine the fraction of the remaining number of eval to use for the current iteration.\\n\")\n (opt_desc_str(inc_intensity_opt).c_str(),\n value(&fs_params.inc_intensity)->default_value(0),\n \"Incremental Selection parameter. Value between 0 and 1. 0 means all features are selected, 1 corresponds to the stronger selection pressure, probably no features are selected at 1.\\n\")\n (opt_desc_str(inc_target_size_opt).c_str(),\n value(&fs_params.inc_target_size)->default_value(0),\n \"Incremental Selection parameter. The number of features to attempt to select. This option overwrites feature-selection-intensity. 0 means disabled.\\n\")\n (opt_desc_str(inc_target_size_epsilon_opt).c_str(),\n value(&fs_params.inc_target_size_epsilon)->default_value(0.001),\n \"Incremental Selection parameter. Error interval tolerated to control the automatically adjust feature selection intensity when using option -C.\\n\")\n (opt_desc_str(inc_redundant_intensity_opt).c_str(),\n value(&fs_params.inc_rintensity)->default_value(0.1),\n \"Incremental Selection parameter. Value between 0 and 1. 0 means no redundant features are discarded, 1 means redudant features are maximally discarded. This option is only active when feature selection is active.\\n\")\n (opt_desc_str(inc_interaction_terms_opt).c_str(),\n value(&fs_params.inc_interaction_terms)->default_value(1),\n \"Incremental Selection parameter. Maximum number of interaction terms considered during feature selection. Higher values make the feature selection more accurate but is computationally expensive.\\n\")\n ;\n\n variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n notify(vm);\n\n \/\/ set flags\n log_file_dep_opt = vm.count(log_file_dep_opt_opt.first) > 0;\n\n \/\/ help\n if (vm.count(\"help\") || argc == 1) {\n cout << desc << std::endl;\n return 1;\n }\n\n \/\/ set log\n if(log_file_dep_opt) {\n std::set ignore_opt = list_of(log_file_dep_opt_opt.first);\n log_file = determine_log_name(default_log_file_prefix,\n vm, ignore_opt,\n std::string(\".\").append(default_log_file_suffix));\n }\n\n type_node inferred_type = inferDataType(fs_params.input_file);\n\n \/\/ remove log_file\n remove(log_file.c_str());\n logger().setFilename(log_file);\n logger().setLevel(logger().getLevelFromString(log_level));\n logger().setBackTraceLevel(Logger::ERROR);\n\n \/\/ init random generator\n MT19937RandGen rng(rand_seed);\n\n \/\/ Logger\n logger().info(\"Start feature-selection, read input file\");\n \/\/ ~Logger\n\n if(inferred_type == id::boolean_type) {\n \/\/ read input_data_file file\n truth_table table(fs_params.input_file);\n feature_selection(table, fs_params, rng);\n } else {\n unsupported_type_exit(inferred_type);\n }\n}\nimproved feature-selection log\/** feature-selection.cc ---\n *\n * Copyright (C) 2011 OpenCog Foundation\n *\n * Author: Nil Geisweiller \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 v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\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 Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"feature-selection.h\"\n#include \"..\/feature_optimization.h\"\n#include \"..\/feature_scorer.h\"\n\nusing namespace boost::program_options;\nusing boost::lexical_cast;\nusing boost::assign::list_of;\nusing namespace std;\nusing namespace opencog;\nusing namespace combo;\n\nconst static unsigned max_filename_size = 255;\n\n\/**\n * Display error message about unsupported type and exit\n *\/\nvoid unsupported_type_exit(const type_tree& tt) {\n std::cerr << \"error: type \" << tt << \"currently not supported\" << std::endl;\n exit(1);\n}\nvoid unsupported_type_exit(type_node type) {\n unsupported_type_exit(type_tree(type));\n}\n\nint main(int argc, char** argv) {\n\n unsigned long rand_seed;\n string log_level;\n string log_file;\n bool log_file_dep_opt;\n feature_selection_parameters fs_params;\n\n \/\/ Declare the supported options.\n options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Produce help message.\\n\")\n (opt_desc_str(rand_seed_opt).c_str(),\n value(&rand_seed)->default_value(1),\n \"Random seed.\\n\")\n (opt_desc_str(algo_opt).c_str(),\n value(&fs_params.algorithm)->default_value(hc),\n string(\"Feature selection algorithm. Supported algorithms are \").append(un).append(\" for univariate, \").append(sa).append(\" for simulated annealing, \").append(hc).append(\" for hillclimbing, \").append(inc).append(\" for incremental.\").c_str())\n (opt_desc_str(input_data_file_opt).c_str(),\n value(&fs_params.input_file),\n \"Input table file, DSV file using comman, whitespace or tabulation as seperator.\\n\")\n (opt_desc_str(output_file_opt).c_str(),\n value(&fs_params.output_file),\n \"File where to save the results. If empty then it outputs on the stdout.\\n\")\n (opt_desc_str(initial_feature_opt).c_str(), value >(&fs_params.initial_features),\n \"Initial feature to search from. This option can be used as many times as features to include in the initial feature set. An initial feature set close to the one maximizing the feature quality measure can greatly increase feature selection speed.\\n\")\n (opt_desc_str(max_evals_opt).c_str(),\n value(&fs_params.max_evals)->default_value(10000),\n \"Maximum number of fitness function evaluations.\\n\")\n (opt_desc_str(log_level_opt).c_str(),\n value(&log_level)->default_value(\"DEBUG\"),\n \"Log level, possible levels are NONE, ERROR, WARN, INFO, DEBUG, FINE. Case does not matter.\\n\")\n (opt_desc_str(log_file_dep_opt_opt).c_str(),\n string(\"The name of the log is determined by the options, for instance if feature-selection is called with -r 123 the log name is feature-selection_random-seed_123.log. Note that the name will be truncated in order not to be longer than \").append(lexical_cast(max_filename_size)).append(\" characters.\\n\").c_str())\n (opt_desc_str(log_file_opt).c_str(),\n value(&log_file)->default_value(default_log_file),\n string(\"File name where to write the log. This option is overwritten by \").append(log_file_dep_opt_opt.first).append(\".\\n\").c_str())\n (opt_desc_str(cache_size_opt).c_str(),\n value(&fs_params.cache_size)->default_value(1000000),\n \"Cache size, so that identical candidates are not re-evaluated, 0 means no cache.\\n\")\n (opt_desc_str(complexity_penalty_intensity_opt).c_str(),\n value(&fs_params.cpi)->default_value(0.0),\n \"Intensity of the feature complexity penalty, in [0,+Inf), 0 means no complexity penalty.\\n\")\n (opt_desc_str(confidence_penalty_intensity_opt).c_str(),\n value(&fs_params.confi)->default_value(1.0),\n \"Intensity of the confidence penalty, in [0,+Inf), 0 means no confidence penalty. This parameter influences how much importance we attribute to the confidence of the feature quality measure. The less samples in the data set, the more features the less confidence in the feature set quality measure.\\n\")\n (opt_desc_str(resources_opt).c_str(),\n value(&fs_params.resources)->default_value(10000),\n \"Resources allocated to the learning algorithm that take in input the selected features. More resource means that the feature set can be larger (as long as it has enough confidence). In this case the algo is supposed to be MOSES and the resources is the number of evaluations.\\n\")\n (opt_desc_str(max_score_opt).c_str(),\n value(&fs_params.max_score)->default_value(1),\n \"For MOSES based algorithms. The max score to reach, once reached feature selection halts.\\n\")\n (opt_desc_str(hc_fraction_of_remaining_opt).c_str(),\n value(&fs_params.hc_fraction_of_remaining)->default_value(10),\n \"Hillclimbing parameter. Determine the fraction of the remaining number of eval to use for the current iteration.\\n\")\n (opt_desc_str(inc_intensity_opt).c_str(),\n value(&fs_params.inc_intensity)->default_value(0),\n \"Incremental Selection parameter. Value between 0 and 1. 0 means all features are selected, 1 corresponds to the stronger selection pressure, probably no features are selected at 1.\\n\")\n (opt_desc_str(inc_target_size_opt).c_str(),\n value(&fs_params.inc_target_size)->default_value(0),\n \"Incremental Selection parameter. The number of features to attempt to select. This option overwrites feature-selection-intensity. 0 means disabled.\\n\")\n (opt_desc_str(inc_target_size_epsilon_opt).c_str(),\n value(&fs_params.inc_target_size_epsilon)->default_value(0.001),\n \"Incremental Selection parameter. Error interval tolerated to control the automatically adjust feature selection intensity when using option -C.\\n\")\n (opt_desc_str(inc_redundant_intensity_opt).c_str(),\n value(&fs_params.inc_rintensity)->default_value(0.1),\n \"Incremental Selection parameter. Value between 0 and 1. 0 means no redundant features are discarded, 1 means redudant features are maximally discarded. This option is only active when feature selection is active.\\n\")\n (opt_desc_str(inc_interaction_terms_opt).c_str(),\n value(&fs_params.inc_interaction_terms)->default_value(1),\n \"Incremental Selection parameter. Maximum number of interaction terms considered during feature selection. Higher values make the feature selection more accurate but is computationally expensive.\\n\")\n ;\n\n variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n notify(vm);\n\n \/\/ set flags\n log_file_dep_opt = vm.count(log_file_dep_opt_opt.first) > 0;\n\n \/\/ help\n if (vm.count(\"help\") || argc == 1) {\n cout << desc << std::endl;\n return 1;\n }\n\n \/\/ set log\n if(log_file_dep_opt) {\n std::set ignore_opt = list_of(log_file_dep_opt_opt.first);\n log_file = determine_log_name(default_log_file_prefix,\n vm, ignore_opt,\n std::string(\".\").append(default_log_file_suffix));\n }\n\n type_node inferred_type = inferDataType(fs_params.input_file);\n\n \/\/ remove log_file\n remove(log_file.c_str());\n logger().setFilename(log_file);\n logger().setLevel(logger().getLevelFromString(log_level));\n logger().setBackTraceLevel(Logger::ERROR);\n\n \/\/ init random generator\n MT19937RandGen rng(rand_seed);\n\n \/\/ Logger\n logger().info(\"Read input file %s\", fs_params.input_file.c_str());\n \/\/ ~Logger\n\n if(inferred_type == id::boolean_type) {\n \/\/ read input_data_file file\n truth_table table(fs_params.input_file);\n feature_selection(table, fs_params, rng);\n } else {\n unsupported_type_exit(inferred_type);\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_desktop.hxx\"\n\n#include \"dp_gui_shared.hxx\"\n#include \"dp_gui.h\"\n#include \"dp_gui_theextmgr.hxx\"\n#include \"cppuhelper\/implbase2.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"unotools\/configmgr.hxx\"\n#include \"comphelper\/servicedecl.hxx\"\n#include \"comphelper\/unwrapargs.hxx\"\n#include \n#include \"vcl\/svapp.hxx\"\n#include \"vcl\/msgbox.hxx\"\n#include \"com\/sun\/star\/lang\/XServiceInfo.hpp\"\n#include \"com\/sun\/star\/task\/XJobExecutor.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XAsynchronousExecutableDialog.hpp\"\n\n#include \"boost\/bind.hpp\"\n#include \"license_dialog.hxx\"\n#include \"dp_gui_dialog2.hxx\"\n\nusing namespace ::dp_misc;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nusing ::rtl::OUString;\n\nnamespace css = ::com::sun::star;\nnamespace dp_gui {\n\n\/\/==============================================================================\nclass MyApp : public Application, private boost::noncopyable\n{\npublic:\n MyApp();\n virtual ~MyApp();\n\n \/\/ Application\n virtual void Main();\n};\n\n\/\/______________________________________________________________________________\nMyApp::~MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nMyApp::MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid MyApp::Main()\n{\n}\n\n\/\/##############################################################################\n\nnamespace\n{\n struct ProductName\n : public rtl::Static< String, ProductName > {};\n struct Version\n : public rtl::Static< String, Version > {};\n struct AboutBoxVersion\n : public rtl::Static< String, AboutBoxVersion > {};\n struct OOOVendor\n : public rtl::Static< String, OOOVendor > {};\n struct Extension\n : public rtl::Static< String, Extension > {};\n}\n\nvoid ReplaceProductNameHookProc( String& rStr )\n{\n static int nAll = 0, nPro = 0;\n\n nAll++;\n if ( rStr.SearchAscii( \"%PRODUCT\" ) != STRING_NOTFOUND )\n {\n String &rProductName = ProductName::get();\n String &rVersion = Version::get();\n String &rAboutBoxVersion = AboutBoxVersion::get();\n String &rExtension = Extension::get();\n String &rOOOVendor = OOOVendor::get();\n\n if ( !rProductName.Len() )\n {\n rtl::OUString aTmp;\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n aRet >>= aTmp;\n rProductName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n rVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::ABOUTBOXPRODUCTVERSION );\n aRet >>= aTmp;\n rOOOVendor = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::OOOVENDOR );\n aRet >>= aTmp;\n rAboutBoxVersion = aTmp;\n\n\n if ( !rExtension.Len() )\n {\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );\n aRet >>= aTmp;\n rExtension = aTmp;\n }\n }\n\n nPro++;\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", rProductName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", rVersion );\n rStr.SearchAndReplaceAllAscii( \"%ABOUTBOXPRODUCTVERSION\", rAboutBoxVersion );\n rStr.SearchAndReplaceAllAscii( \"%OOOVENDOR\", rOOOVendor );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTEXTENSION\", rExtension );\n }\n}\n\n\/\/==============================================================================\nclass ServiceImpl\n : public ::cppu::WeakImplHelper2\n{\n Reference const m_xComponentContext;\n boost::optional< Reference > \/* const *\/ m_parent;\n boost::optional \/* const *\/ m_view;\n \/* if true then this service is running in an unopkg process and not in an office process *\/\n boost::optional \/* const *\/ m_unopkg;\n boost::optional m_extensionURL;\n OUString m_initialTitle;\n bool m_bShowUpdateOnly;\n\npublic:\n ServiceImpl( Sequence const & args,\n Reference const & xComponentContext );\n\n \/\/ XAsynchronousExecutableDialog\n virtual void SAL_CALL setDialogTitle( OUString const & aTitle )\n throw (RuntimeException);\n virtual void SAL_CALL startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException);\n\n \/\/ XJobExecutor\n virtual void SAL_CALL trigger( OUString const & event )\n throw (RuntimeException);\n};\n\n\/\/______________________________________________________________________________\nServiceImpl::ServiceImpl( Sequence const& args,\n Reference const& xComponentContext)\n : m_xComponentContext(xComponentContext),\n m_bShowUpdateOnly( false )\n{\n try {\n comphelper::unwrapArgs( args, m_parent, m_view, m_unopkg );\n return;\n } catch (css::lang::IllegalArgumentException & ) {\n }\n try {\n comphelper::unwrapArgs( args, m_extensionURL);\n } catch (css::lang::IllegalArgumentException & ) {\n }\n\n ResHookProc pProc = ResMgr::GetReadStringHook();\n if ( !pProc )\n ResMgr::SetReadStringHook( ReplaceProductNameHookProc );\n}\n\n\/\/ XAsynchronousExecutableDialog\n\/\/______________________________________________________________________________\nvoid ServiceImpl::setDialogTitle( OUString const & title )\n throw (RuntimeException)\n{\n if ( dp_gui::TheExtensionManager::s_ExtMgr.is() )\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::TheExtensionManager > dialog(\n ::dp_gui::TheExtensionManager::get( m_xComponentContext,\n m_parent ? *m_parent : Reference(),\n m_extensionURL ? *m_extensionURL : OUString() ) );\n dialog->SetText( title );\n }\n else\n m_initialTitle = title;\n}\n\n\/\/______________________________________________________________________________\nvoid ServiceImpl::startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException)\n{\n bool bCloseDialog = true; \/\/ only used if m_bShowUpdateOnly is true\n ::std::auto_ptr app;\n \/\/ToDo: synchronize access to s_dialog !!!\n if (! dp_gui::TheExtensionManager::s_ExtMgr.is())\n {\n const bool bAppUp = (GetpApp() != 0);\n bool bOfficePipePresent;\n try {\n bOfficePipePresent = dp_misc::office_is_running();\n }\n catch (Exception & exc) {\n if (bAppUp) {\n const vos::OGuard guard( Application::GetSolarMutex() );\n std::auto_ptr box(\n new ErrorBox( Application::GetActiveTopWindow(),\n WB_OK, exc.Message ) );\n box->Execute();\n }\n throw;\n }\n\n if (! bOfficePipePresent) {\n OSL_ASSERT( ! bAppUp );\n app.reset( new MyApp );\n if (! InitVCL( Reference(\n m_xComponentContext->getServiceManager(),\n UNO_QUERY_THROW ) ))\n throw RuntimeException( OUSTR(\"Cannot initialize VCL!\"),\n static_cast(this) );\n AllSettings as = app->GetSettings();\n OUString slang;\n if (! (::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::LOCALE ) >>= slang))\n throw RuntimeException( OUSTR(\"Cannot determine language!\"),\n static_cast(this) );\n as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );\n app->SetSettings( as );\n String sTitle = ::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::PRODUCTNAME).get()\n + String(static_cast(' '))\n + ::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::PRODUCTVERSION).get();\n app->SetDisplayName(sTitle);\n }\n }\n else\n {\n \/\/ When m_bShowUpdateOnly is set, we are inside the office and the user clicked\n \/\/ the update notification icon in the menu bar. We must not close the extensions\n \/\/ dialog after displaying the update dialog when it has been visible before\n if ( m_bShowUpdateOnly )\n bCloseDialog = ! dp_gui::TheExtensionManager::s_ExtMgr->isVisible();\n }\n\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::TheExtensionManager > myExtMgr(\n ::dp_gui::TheExtensionManager::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference(),\n m_extensionURL ? *m_extensionURL : OUString() ) );\n myExtMgr->createDialog( false );\n if (m_initialTitle.getLength() > 0) {\n myExtMgr->SetText( m_initialTitle );\n m_initialTitle = OUString();\n }\n if ( m_bShowUpdateOnly )\n {\n myExtMgr->checkUpdates( true, !bCloseDialog );\n if ( bCloseDialog )\n myExtMgr->Close();\n else\n myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );\n }\n else\n {\n myExtMgr->Show();\n myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );\n }\n }\n\n if (app.get() != 0) {\n Application::Execute();\n DeInitVCL();\n }\n\n if (xListener.is())\n xListener->dialogClosed(\n ui::dialogs::DialogClosedEvent(\n static_cast< ::cppu::OWeakObject * >(this),\n sal_Int16(0)) );\n}\n\n\/\/ XJobExecutor\n\/\/______________________________________________________________________________\nvoid ServiceImpl::trigger( OUString const &rEvent ) throw (RuntimeException)\n{\n if ( rEvent == OUSTR(\"SHOW_UPDATE_DIALOG\") )\n m_bShowUpdateOnly = true;\n else\n m_bShowUpdateOnly = false;\n\n startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );\n}\n\nnamespace sdecl = comphelper::service_decl;\nsdecl::class_ > serviceSI;\nsdecl::ServiceDecl const serviceDecl(\n serviceSI,\n \"com.sun.star.comp.deployment.ui.PackageManagerDialog\",\n \"com.sun.star.deployment.ui.PackageManagerDialog\" );\n\nsdecl::class_ > licenseSI;\nsdecl::ServiceDecl const licenseDecl(\n licenseSI,\n \"com.sun.star.comp.deployment.ui.LicenseDialog\",\n \"com.sun.star.deployment.ui.LicenseDialog\" );\n\nsdecl::class_ > updateSI;\nsdecl::ServiceDecl const updateDecl(\n updateSI,\n \"com.sun.star.comp.deployment.ui.UpdateRequiredDialog\",\n \"com.sun.star.deployment.ui.UpdateRequiredDialog\" );\n} \/\/ namespace dp_gui\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nsal_Bool SAL_CALL component_writeInfo(\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_writeInfoHelper(\n pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );\n}\n\nvoid * SAL_CALL component_getFactory(\n sal_Char const * pImplName,\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_getFactoryHelper(\n pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );\n}\n\n} \/\/ extern \"C\"\ncws l10ntooling18: #i110394# confused assignment\/*************************************************************************\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_desktop.hxx\"\n\n#include \"dp_gui_shared.hxx\"\n#include \"dp_gui.h\"\n#include \"dp_gui_theextmgr.hxx\"\n#include \"cppuhelper\/implbase2.hxx\"\n#include \"cppuhelper\/implementationentry.hxx\"\n#include \"unotools\/configmgr.hxx\"\n#include \"comphelper\/servicedecl.hxx\"\n#include \"comphelper\/unwrapargs.hxx\"\n#include \n#include \"vcl\/svapp.hxx\"\n#include \"vcl\/msgbox.hxx\"\n#include \"com\/sun\/star\/lang\/XServiceInfo.hpp\"\n#include \"com\/sun\/star\/task\/XJobExecutor.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XAsynchronousExecutableDialog.hpp\"\n\n#include \"boost\/bind.hpp\"\n#include \"license_dialog.hxx\"\n#include \"dp_gui_dialog2.hxx\"\n\nusing namespace ::dp_misc;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nusing ::rtl::OUString;\n\nnamespace css = ::com::sun::star;\nnamespace dp_gui {\n\n\/\/==============================================================================\nclass MyApp : public Application, private boost::noncopyable\n{\npublic:\n MyApp();\n virtual ~MyApp();\n\n \/\/ Application\n virtual void Main();\n};\n\n\/\/______________________________________________________________________________\nMyApp::~MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nMyApp::MyApp()\n{\n}\n\n\/\/______________________________________________________________________________\nvoid MyApp::Main()\n{\n}\n\n\/\/##############################################################################\n\nnamespace\n{\n struct ProductName\n : public rtl::Static< String, ProductName > {};\n struct Version\n : public rtl::Static< String, Version > {};\n struct AboutBoxVersion\n : public rtl::Static< String, AboutBoxVersion > {};\n struct OOOVendor\n : public rtl::Static< String, OOOVendor > {};\n struct Extension\n : public rtl::Static< String, Extension > {};\n}\n\nvoid ReplaceProductNameHookProc( String& rStr )\n{\n static int nAll = 0, nPro = 0;\n\n nAll++;\n if ( rStr.SearchAscii( \"%PRODUCT\" ) != STRING_NOTFOUND )\n {\n String &rProductName = ProductName::get();\n String &rVersion = Version::get();\n String &rAboutBoxVersion = AboutBoxVersion::get();\n String &rExtension = Extension::get();\n String &rOOOVendor = OOOVendor::get();\n\n if ( !rProductName.Len() )\n {\n rtl::OUString aTmp;\n Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );\n aRet >>= aTmp;\n rProductName = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );\n aRet >>= aTmp;\n rVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::ABOUTBOXPRODUCTVERSION );\n aRet >>= aTmp;\n rAboutBoxVersion = aTmp;\n\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::OOOVENDOR );\n aRet >>= aTmp;\n rOOOVendor = aTmp;\n\n if ( !rExtension.Len() )\n {\n aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );\n aRet >>= aTmp;\n rExtension = aTmp;\n }\n }\n\n nPro++;\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTNAME\", rProductName );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTVERSION\", rVersion );\n rStr.SearchAndReplaceAllAscii( \"%ABOUTBOXPRODUCTVERSION\", rAboutBoxVersion );\n rStr.SearchAndReplaceAllAscii( \"%OOOVENDOR\", rOOOVendor );\n rStr.SearchAndReplaceAllAscii( \"%PRODUCTEXTENSION\", rExtension );\n }\n}\n\n\/\/==============================================================================\nclass ServiceImpl\n : public ::cppu::WeakImplHelper2\n{\n Reference const m_xComponentContext;\n boost::optional< Reference > \/* const *\/ m_parent;\n boost::optional \/* const *\/ m_view;\n \/* if true then this service is running in an unopkg process and not in an office process *\/\n boost::optional \/* const *\/ m_unopkg;\n boost::optional m_extensionURL;\n OUString m_initialTitle;\n bool m_bShowUpdateOnly;\n\npublic:\n ServiceImpl( Sequence const & args,\n Reference const & xComponentContext );\n\n \/\/ XAsynchronousExecutableDialog\n virtual void SAL_CALL setDialogTitle( OUString const & aTitle )\n throw (RuntimeException);\n virtual void SAL_CALL startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException);\n\n \/\/ XJobExecutor\n virtual void SAL_CALL trigger( OUString const & event )\n throw (RuntimeException);\n};\n\n\/\/______________________________________________________________________________\nServiceImpl::ServiceImpl( Sequence const& args,\n Reference const& xComponentContext)\n : m_xComponentContext(xComponentContext),\n m_bShowUpdateOnly( false )\n{\n try {\n comphelper::unwrapArgs( args, m_parent, m_view, m_unopkg );\n return;\n } catch (css::lang::IllegalArgumentException & ) {\n }\n try {\n comphelper::unwrapArgs( args, m_extensionURL);\n } catch (css::lang::IllegalArgumentException & ) {\n }\n\n ResHookProc pProc = ResMgr::GetReadStringHook();\n if ( !pProc )\n ResMgr::SetReadStringHook( ReplaceProductNameHookProc );\n}\n\n\/\/ XAsynchronousExecutableDialog\n\/\/______________________________________________________________________________\nvoid ServiceImpl::setDialogTitle( OUString const & title )\n throw (RuntimeException)\n{\n if ( dp_gui::TheExtensionManager::s_ExtMgr.is() )\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::TheExtensionManager > dialog(\n ::dp_gui::TheExtensionManager::get( m_xComponentContext,\n m_parent ? *m_parent : Reference(),\n m_extensionURL ? *m_extensionURL : OUString() ) );\n dialog->SetText( title );\n }\n else\n m_initialTitle = title;\n}\n\n\/\/______________________________________________________________________________\nvoid ServiceImpl::startExecuteModal(\n Reference< ui::dialogs::XDialogClosedListener > const & xListener )\n throw (RuntimeException)\n{\n bool bCloseDialog = true; \/\/ only used if m_bShowUpdateOnly is true\n ::std::auto_ptr app;\n \/\/ToDo: synchronize access to s_dialog !!!\n if (! dp_gui::TheExtensionManager::s_ExtMgr.is())\n {\n const bool bAppUp = (GetpApp() != 0);\n bool bOfficePipePresent;\n try {\n bOfficePipePresent = dp_misc::office_is_running();\n }\n catch (Exception & exc) {\n if (bAppUp) {\n const vos::OGuard guard( Application::GetSolarMutex() );\n std::auto_ptr box(\n new ErrorBox( Application::GetActiveTopWindow(),\n WB_OK, exc.Message ) );\n box->Execute();\n }\n throw;\n }\n\n if (! bOfficePipePresent) {\n OSL_ASSERT( ! bAppUp );\n app.reset( new MyApp );\n if (! InitVCL( Reference(\n m_xComponentContext->getServiceManager(),\n UNO_QUERY_THROW ) ))\n throw RuntimeException( OUSTR(\"Cannot initialize VCL!\"),\n static_cast(this) );\n AllSettings as = app->GetSettings();\n OUString slang;\n if (! (::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::LOCALE ) >>= slang))\n throw RuntimeException( OUSTR(\"Cannot determine language!\"),\n static_cast(this) );\n as.SetUILanguage( MsLangId::convertIsoStringToLanguage( slang ) );\n app->SetSettings( as );\n String sTitle = ::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::PRODUCTNAME).get()\n + String(static_cast(' '))\n + ::utl::ConfigManager::GetDirectConfigProperty(\n ::utl::ConfigManager::PRODUCTVERSION).get();\n app->SetDisplayName(sTitle);\n }\n }\n else\n {\n \/\/ When m_bShowUpdateOnly is set, we are inside the office and the user clicked\n \/\/ the update notification icon in the menu bar. We must not close the extensions\n \/\/ dialog after displaying the update dialog when it has been visible before\n if ( m_bShowUpdateOnly )\n bCloseDialog = ! dp_gui::TheExtensionManager::s_ExtMgr->isVisible();\n }\n\n {\n const ::vos::OGuard guard( Application::GetSolarMutex() );\n ::rtl::Reference< ::dp_gui::TheExtensionManager > myExtMgr(\n ::dp_gui::TheExtensionManager::get(\n m_xComponentContext,\n m_parent ? *m_parent : Reference(),\n m_extensionURL ? *m_extensionURL : OUString() ) );\n myExtMgr->createDialog( false );\n if (m_initialTitle.getLength() > 0) {\n myExtMgr->SetText( m_initialTitle );\n m_initialTitle = OUString();\n }\n if ( m_bShowUpdateOnly )\n {\n myExtMgr->checkUpdates( true, !bCloseDialog );\n if ( bCloseDialog )\n myExtMgr->Close();\n else\n myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );\n }\n else\n {\n myExtMgr->Show();\n myExtMgr->ToTop( TOTOP_RESTOREWHENMIN );\n }\n }\n\n if (app.get() != 0) {\n Application::Execute();\n DeInitVCL();\n }\n\n if (xListener.is())\n xListener->dialogClosed(\n ui::dialogs::DialogClosedEvent(\n static_cast< ::cppu::OWeakObject * >(this),\n sal_Int16(0)) );\n}\n\n\/\/ XJobExecutor\n\/\/______________________________________________________________________________\nvoid ServiceImpl::trigger( OUString const &rEvent ) throw (RuntimeException)\n{\n if ( rEvent == OUSTR(\"SHOW_UPDATE_DIALOG\") )\n m_bShowUpdateOnly = true;\n else\n m_bShowUpdateOnly = false;\n\n startExecuteModal( Reference< ui::dialogs::XDialogClosedListener >() );\n}\n\nnamespace sdecl = comphelper::service_decl;\nsdecl::class_ > serviceSI;\nsdecl::ServiceDecl const serviceDecl(\n serviceSI,\n \"com.sun.star.comp.deployment.ui.PackageManagerDialog\",\n \"com.sun.star.deployment.ui.PackageManagerDialog\" );\n\nsdecl::class_ > licenseSI;\nsdecl::ServiceDecl const licenseDecl(\n licenseSI,\n \"com.sun.star.comp.deployment.ui.LicenseDialog\",\n \"com.sun.star.deployment.ui.LicenseDialog\" );\n\nsdecl::class_ > updateSI;\nsdecl::ServiceDecl const updateDecl(\n updateSI,\n \"com.sun.star.comp.deployment.ui.UpdateRequiredDialog\",\n \"com.sun.star.deployment.ui.UpdateRequiredDialog\" );\n} \/\/ namespace dp_gui\n\nextern \"C\" {\n\nvoid SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nsal_Bool SAL_CALL component_writeInfo(\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_writeInfoHelper(\n pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );\n}\n\nvoid * SAL_CALL component_getFactory(\n sal_Char const * pImplName,\n lang::XMultiServiceFactory * pServiceManager,\n registry::XRegistryKey * pRegistryKey )\n{\n return component_getFactoryHelper(\n pImplName, pServiceManager, pRegistryKey, dp_gui::serviceDecl, dp_gui::licenseDecl, dp_gui::updateDecl );\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cybertron_topology_message.h\"\n#include \"channel_msg_factory.h\"\n#include \"cybertron\/proto\/topology_change.pb.h\"\n#include \"cybertron_channel_message.h\"\n#include \"screen.h\"\n\n#include \n#include \n#include \n\nconstexpr int SecondColumnOffset = 4;\n\nCybertronTopologyMessage::CybertronTopologyMessage()\n : RenderableMessage(),\n second_column_(SecondColumnType::MessageFrameRatio),\n pages_(1),\n page_item_count_(24),\n page_index_(0),\n col1_width_(8),\n all_channels_map_() {}\n\nCybertronTopologyMessage::~CybertronTopologyMessage(void) {\n apollo::cybertron::Shutdown();\n for (auto item : all_channels_map_) {\n if (!ChannelMessage::isErrorCode(item.second)) {\n delete item.second;\n }\n }\n}\n\nRenderableMessage* CybertronTopologyMessage::Child(int lineNo) const {\n RenderableMessage* ret = nullptr;\n --lineNo;\n\n if (lineNo > -1 && lineNo < page_item_count_) {\n int i = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (i < page_index_ * page_item_count_) {\n ++iter;\n ++i;\n }\n\n for (i = 0; iter != all_channels_map_.cend(); ++iter) {\n if (i == lineNo) {\n if (!ChannelMessage::isErrorCode(iter->second)) {\n ret = iter->second;\n }\n break;\n }\n ++i;\n }\n }\n return ret;\n}\n\nvoid CybertronTopologyMessage::TopologyChanged(\n const apollo::cybertron::proto::ChangeMsg& changeMsg) {\n const std::string& nodeName = changeMsg.role_attr().node_name();\n const std::string& channelName = changeMsg.role_attr().channel_name();\n const std::string& msgTypeName = changeMsg.role_attr().message_type();\n\n if ((int)channelName.length() > col1_width_) {\n col1_width_ = channelName.length();\n }\n\n if (::apollo::cybertron::proto::OperateType::OPT_JOIN ==\n changeMsg.operate_type()) {\n if (ChannelMsgFactory::Instance()->isFromHere(nodeName)) {\n return;\n }\n\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type() ||\n ::apollo::cybertron::proto::RoleType::ROLE_READER ==\n changeMsg.role_type()) {\n if (::apollo::cybertron::proto::ChangeType::CHANGE_CHANNEL ==\n changeMsg.change_type()) {\n auto iter = all_channels_map_.find(channelName);\n\n if (iter == all_channels_map_.cend()) {\n ChannelMessage* channelMsg =\n ChannelMsgFactory::Instance()->CreateChannelMessage(msgTypeName,\n channelName);\n\n if (!ChannelMessage::isErrorCode(channelMsg)) {\n channelMsg->set_parent(this);\n channelMsg->set_message_type(msgTypeName);\n\n channelMsg->add_reader(channelMsg->NodeName());\n\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n channelMsg->add_writer(nodeName);\n } else {\n channelMsg->add_reader(nodeName);\n }\n }\n\n all_channels_map_[channelName] = channelMsg;\n } else {\n if (!ChannelMessage::isErrorCode(iter->second)) {\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n iter->second->add_writer(nodeName);\n }\n if (::apollo::cybertron::proto::RoleType::ROLE_READER ==\n changeMsg.role_type()) {\n iter->second->add_reader(nodeName);\n }\n }\n }\n }\n }\n } else {\n if (::apollo::cybertron::proto::ChangeType::CHANGE_CHANNEL ==\n changeMsg.change_type()) {\n auto iter = all_channels_map_.find(channelName);\n\n if (iter != all_channels_map_.cend() &&\n !ChannelMessage::isErrorCode(iter->second)) {\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n iter->second->del_writer(nodeName);\n }\n if (::apollo::cybertron::proto::RoleType::ROLE_READER ==\n changeMsg.role_type()) {\n iter->second->del_reader(nodeName);\n }\n }\n }\n }\n}\n\nvoid CybertronTopologyMessage::ChangeState(const Screen* s, int key) {\n switch (key) {\n case 'f':\n case 'F':\n second_column_ = SecondColumnType::MessageFrameRatio;\n break;\n\n case 't':\n case 'T':\n second_column_ = SecondColumnType::MessageType;\n break;\n\n case CTRL('d'):\n case KEY_NPAGE:\n ++page_index_;\n if (page_index_ >= pages_) page_index_ = pages_ - 1;\n break;\n\n case CTRL('u'):\n case KEY_PPAGE:\n --page_index_;\n if (page_index_ < 1) page_index_ = 0;\n break;\n\n case ' ': {\n ChannelMessage* child =\n static_cast(Child(s->highlight_line_no()));\n if (child) {\n child->set_enabled(!child->is_enabled());\n }\n }\n\n default:;\n }\n}\n\nvoid CybertronTopologyMessage::Render(const Screen* s, int key) {\n page_item_count_ = s->Height() - 1;\n pages_ = all_channels_map_.size() \/ page_item_count_ + 1;\n ChangeState(s, key);\n\n unsigned y = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (y < page_index_ * page_item_count_) {\n ++iter;\n ++y;\n }\n\n y = 0;\n page_item_count_++;\n\n s->AddStr(0, y, Screen::WHITE_BLACK, \"Channels\");\n\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK,\n \"TypeName\");\n break;\n case SecondColumnType::MessageFrameRatio:\n s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK,\n \"FrameRatio\");\n break;\n }\n\n ++y;\n\n Screen::ColorPair color;\n std::ostringstream outStr;\n\n for (; iter != all_channels_map_.cend() && y < page_item_count_;\n ++iter, ++y) {\n color = Screen::RED_BLACK;\n\n if (!ChannelMessage::isErrorCode(iter->second)) {\n if (iter->second->is_enabled() && iter->second->has_message_come())\n color = Screen::GREEN_BLACK;\n }\n\n s->SetCurrentColor(color);\n s->AddStr(0, y, iter->first.c_str());\n\n if (!ChannelMessage::isErrorCode(iter->second)) {\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, y,\n iter->second->message_type().c_str());\n break;\n case SecondColumnType::MessageFrameRatio: {\n outStr.str(\"\");\n outStr << std::fixed << std::setprecision(2)\n << iter->second->frame_ratio();\n s->AddStr(col1_width_ + SecondColumnOffset, y, outStr.str().c_str());\n } break;\n }\n } else {\n ChannelMessage::ErrorCode errcode =\n ChannelMessage::castPtr2ErrorCode(iter->second);\n s->AddStr(col1_width_ + SecondColumnOffset, y,\n ChannelMessage::errCode2Str(errcode));\n }\n s->ClearCurrentColor(color);\n }\n}\nframework: fix multi-monitors parse message problem\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cybertron_topology_message.h\"\n#include \"channel_msg_factory.h\"\n#include \"cybertron\/message\/message_traits.h\"\n#include \"cybertron\/proto\/topology_change.pb.h\"\n#include \"cybertron_channel_message.h\"\n#include \"screen.h\"\n\n#include \n#include \n#include \n\nconstexpr int SecondColumnOffset = 4;\n\nCybertronTopologyMessage::CybertronTopologyMessage()\n : RenderableMessage(),\n second_column_(SecondColumnType::MessageFrameRatio),\n pages_(1),\n page_item_count_(24),\n page_index_(0),\n col1_width_(8),\n all_channels_map_() {}\n\nCybertronTopologyMessage::~CybertronTopologyMessage(void) {\n apollo::cybertron::Shutdown();\n for (auto item : all_channels_map_) {\n if (!ChannelMessage::isErrorCode(item.second)) {\n delete item.second;\n }\n }\n}\n\nRenderableMessage* CybertronTopologyMessage::Child(int lineNo) const {\n RenderableMessage* ret = nullptr;\n --lineNo;\n\n if (lineNo > -1 && lineNo < page_item_count_) {\n int i = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (i < page_index_ * page_item_count_) {\n ++iter;\n ++i;\n }\n\n for (i = 0; iter != all_channels_map_.cend(); ++iter) {\n if (i == lineNo) {\n if (!ChannelMessage::isErrorCode(iter->second)) {\n ret = iter->second;\n }\n break;\n }\n ++i;\n }\n }\n return ret;\n}\n\nvoid CybertronTopologyMessage::TopologyChanged(\n const apollo::cybertron::proto::ChangeMsg& changeMsg) {\n const std::string& nodeName = changeMsg.role_attr().node_name();\n const std::string& channelName = changeMsg.role_attr().channel_name();\n const std::string& msgTypeName = changeMsg.role_attr().message_type();\n\n if ((int)channelName.length() > col1_width_) {\n col1_width_ = channelName.length();\n }\n\n if (::apollo::cybertron::proto::OperateType::OPT_JOIN ==\n changeMsg.operate_type()) {\n if (ChannelMsgFactory::Instance()->isFromHere(nodeName)) {\n return;\n }\n\n ChannelMessage* channelMsg = nullptr;\n\n auto iter = all_channels_map_.find(channelName);\n if (iter == all_channels_map_.cend()) {\n channelMsg = ChannelMsgFactory::Instance()->CreateChannelMessage(\n msgTypeName, channelName);\n\n if (!ChannelMessage::isErrorCode(channelMsg)) {\n channelMsg->set_parent(this);\n channelMsg->set_message_type(msgTypeName);\n channelMsg->add_reader(channelMsg->NodeName());\n }\n\n all_channels_map_[channelName] = channelMsg;\n } else {\n channelMsg = iter->second;\n }\n\n if (!ChannelMessage::isErrorCode(channelMsg)) {\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n channelMsg->add_writer(nodeName);\n } else {\n channelMsg->add_reader(nodeName);\n }\n\n if (msgTypeName != apollo::cybertron::message::MessageType<\n apollo::cybertron::message::RawMessage>()) {\n channelMsg->set_message_type(msgTypeName);\n }\n }\n\n } else {\n auto iter = all_channels_map_.find(channelName);\n\n if (iter != all_channels_map_.cend() &&\n !ChannelMessage::isErrorCode(iter->second)) {\n if (::apollo::cybertron::proto::RoleType::ROLE_WRITER ==\n changeMsg.role_type()) {\n iter->second->del_writer(nodeName);\n } else {\n iter->second->del_reader(nodeName);\n }\n }\n }\n}\n\nvoid CybertronTopologyMessage::ChangeState(const Screen* s, int key) {\n switch (key) {\n case 'f':\n case 'F':\n second_column_ = SecondColumnType::MessageFrameRatio;\n break;\n\n case 't':\n case 'T':\n second_column_ = SecondColumnType::MessageType;\n break;\n\n case CTRL('d'):\n case KEY_NPAGE:\n ++page_index_;\n if (page_index_ >= pages_) page_index_ = pages_ - 1;\n break;\n\n case CTRL('u'):\n case KEY_PPAGE:\n --page_index_;\n if (page_index_ < 1) page_index_ = 0;\n break;\n\n case ' ': {\n ChannelMessage* child =\n static_cast(Child(s->highlight_line_no()));\n if (child) {\n child->set_enabled(!child->is_enabled());\n }\n }\n\n default:;\n }\n}\n\nvoid CybertronTopologyMessage::Render(const Screen* s, int key) {\n page_item_count_ = s->Height() - 1;\n pages_ = all_channels_map_.size() \/ page_item_count_ + 1;\n ChangeState(s, key);\n\n unsigned y = 0;\n\n auto iter = all_channels_map_.cbegin();\n while (y < page_index_ * page_item_count_) {\n ++iter;\n ++y;\n }\n\n y = 0;\n page_item_count_++;\n\n s->AddStr(0, y, Screen::WHITE_BLACK, \"Channels\");\n\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK,\n \"TypeName\");\n break;\n case SecondColumnType::MessageFrameRatio:\n s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK,\n \"FrameRatio\");\n break;\n }\n\n ++y;\n\n Screen::ColorPair color;\n std::ostringstream outStr;\n\n for (; iter != all_channels_map_.cend() && y < page_item_count_;\n ++iter, ++y) {\n color = Screen::RED_BLACK;\n\n if (!ChannelMessage::isErrorCode(iter->second)) {\n if (iter->second->is_enabled() && iter->second->has_message_come())\n color = Screen::GREEN_BLACK;\n }\n\n s->SetCurrentColor(color);\n s->AddStr(0, y, iter->first.c_str());\n\n if (!ChannelMessage::isErrorCode(iter->second)) {\n switch (second_column_) {\n case SecondColumnType::MessageType:\n s->AddStr(col1_width_ + SecondColumnOffset, y,\n iter->second->message_type().c_str());\n break;\n case SecondColumnType::MessageFrameRatio: {\n outStr.str(\"\");\n outStr << std::fixed << std::setprecision(2)\n << iter->second->frame_ratio();\n s->AddStr(col1_width_ + SecondColumnOffset, y, outStr.str().c_str());\n } break;\n }\n } else {\n ChannelMessage::ErrorCode errcode =\n ChannelMessage::castPtr2ErrorCode(iter->second);\n s->AddStr(col1_width_ + SecondColumnOffset, y,\n ChannelMessage::errCode2Str(errcode));\n }\n s->ClearCurrentColor(color);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace testing;\nusing namespace folly;\nusing namespace wangle;\nusing namespace folly::test;\nusing namespace std::chrono;\n\nclass FilePollerTest : public testing::Test {\n public:\n void createFile() { File(tmpFile, O_CREAT); }\n\n TemporaryDirectory tmpDir;\n fs::path tmpFilePath{tmpDir.path() \/ \"file-poller\"};\n std::string tmpFile{tmpFilePath.string()};\n};\n\nvoid updateModifiedTime(\n const std::string& path,\n bool forward = true,\n system_clock::time_point timeDiff = system_clock::time_point(seconds(10))) {\n struct stat64 currentFileStat;\n std::array newTimes;\n\n if (stat64(path.c_str(), ¤tFileStat) < 0) {\n throw std::runtime_error(\"Failed to stat file: \" + path);\n }\n\n newTimes[0] = currentFileStat.st_atim;\n newTimes[1] = currentFileStat.st_mtim;\n auto secVal = time_point_cast(timeDiff).time_since_epoch().count();\n auto nsecVal =\n (time_point_cast(timeDiff).time_since_epoch() % (long)1e9)\n .count();\n if (forward) {\n newTimes[1].tv_sec += secVal;\n newTimes[1].tv_nsec += nsecVal;\n } else {\n newTimes[1].tv_sec -= secVal;\n newTimes[1].tv_nsec -= nsecVal;\n }\n\n if (utimensat(AT_FDCWD, path.c_str(), newTimes.data(), 0) < 0) {\n throw std::runtime_error(\"Failed to set time for file: \" + path);\n }\n}\n\nTEST_F(FilePollerTest, TestUpdateFile) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile);\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestUpdateFileSubSecond) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile, true, system_clock::time_point(milliseconds(10)));\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestUpdateFileBackwards) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile, false);\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestCreateFile) {\n Baton<> baton;\n bool updated = false;\n createFile();\n remove(tmpFile.c_str());\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n File(creat(tmpFile.c_str(), O_RDONLY));\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestDeleteFile) {\n Baton<> baton;\n bool updated = false;\n createFile();\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n remove(tmpFile.c_str());\n ASSERT_FALSE(baton.try_wait_for(seconds(1)));\n ASSERT_FALSE(updated);\n}\n\nstruct UpdateSyncState {\n std::mutex m;\n std::condition_variable cv;\n bool updated{false};\n\n void updateTriggered() {\n std::unique_lock lk(m);\n updated = true;\n cv.notify_one();\n }\n\n void waitForUpdate(bool expect = true) {\n std::unique_lock lk(m);\n cv.wait_for(lk, milliseconds(100), [&] { return updated; });\n ASSERT_EQ(updated, expect);\n updated = false;\n }\n};\n\nclass TestFile {\n public:\n TestFile(bool exists, system_clock::time_point modTime)\n : exists_(exists), modTime_(modTime) {}\n\n void update(bool e, system_clock::time_point t) {\n std::unique_lock lk(m);\n exists_ = e;\n modTime_ = t;\n }\n\n FilePoller::FileModificationData toFileModData() {\n std::unique_lock lk(m);\n return FilePoller::FileModificationData(exists_, modTime_);\n }\n\n const std::string name{\"fakeFile\"};\n private:\n bool exists_{false};\n system_clock::time_point modTime_;\n std::mutex m;\n\n};\n\nclass NoDiskPoller : public FilePoller {\n public:\n explicit NoDiskPoller(TestFile& testFile)\n : FilePoller(milliseconds(10)), testFile_(testFile) {}\n\n protected:\n FilePoller::FileModificationData\n getFileModData(const std::string& path) noexcept override {\n EXPECT_EQ(path, testFile_.name);\n return testFile_.toFileModData();\n }\n\n private:\n TestFile& testFile_;\n};\n\nstruct PollerWithState {\n explicit PollerWithState(TestFile& testFile) {\n poller = std::make_unique(testFile);\n poller->addFileToTrack(testFile.name, [&] {\n state.updateTriggered();\n });\n }\n\n void waitForUpdate(bool expect = true) {\n ASSERT_NO_FATAL_FAILURE(state.waitForUpdate(expect));\n }\n\n std::unique_ptr poller;\n UpdateSyncState state;\n};\n\nTEST_F(FilePollerTest, TestTwoUpdatesAndDelete) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState poller(testFile);\n\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n\n testFile.update(false, system_clock::time_point(seconds(0)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));\n}\n\nTEST_F(FilePollerTest, TestFileCreatedLate) {\n TestFile testFile(\n false,\n system_clock::time_point(seconds(0))); \/\/ not created yet\n PollerWithState poller(testFile);\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));\n\n testFile.update(true, system_clock::time_point(seconds(1)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n}\n\nTEST_F(FilePollerTest, TestMultiplePollers) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState p1(testFile);\n PollerWithState p2(testFile);\n\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());\n\n testFile.update(true, system_clock::time_point(seconds(1)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());\n\n \/\/ clear one of the pollers and make sure the other is still\n \/\/ getting them\n p2.poller.reset();\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate(false));\n}\n\nTEST(FilePoller, TestFork) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState p1(testFile);\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n \/\/ nuke singleton\n folly::SingletonVault::singleton()->destroyInstances();\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n}\nFix mod bug in FilePollerTest\/*\n * Copyright 2017-present Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace testing;\nusing namespace folly;\nusing namespace wangle;\nusing namespace folly::test;\nusing namespace std::chrono;\n\nclass FilePollerTest : public testing::Test {\n public:\n void createFile() { File(tmpFile, O_CREAT); }\n\n TemporaryDirectory tmpDir;\n fs::path tmpFilePath{tmpDir.path() \/ \"file-poller\"};\n std::string tmpFile{tmpFilePath.string()};\n};\n\nvoid updateModifiedTime(\n const std::string& path,\n bool forward = true,\n nanoseconds timeDiffNano = seconds(10)) {\n struct stat64 currentFileStat;\n std::array newTimes;\n\n if (stat64(path.c_str(), ¤tFileStat) < 0) {\n throw std::runtime_error(\"Failed to stat file: \" + path);\n }\n\n newTimes[0] = currentFileStat.st_atim;\n newTimes[1] = currentFileStat.st_mtim;\n auto secVal = duration_cast(timeDiffNano).count();\n auto nsecVal = timeDiffNano.count();\n if (forward) {\n newTimes[1].tv_sec += secVal;\n newTimes[1].tv_nsec += nsecVal;\n } else {\n newTimes[1].tv_sec -= secVal;\n newTimes[1].tv_nsec -= nsecVal;\n }\n \/\/ 0 <= tv_nsec < 1e9\n newTimes[1].tv_nsec %= (long)1e9;\n if (newTimes[1].tv_nsec < 0) {\n newTimes[1].tv_nsec *= -1;\n }\n\n if (utimensat(AT_FDCWD, path.c_str(), newTimes.data(), 0) < 0) {\n throw std::runtime_error(\"Failed to set time for file: \" + path);\n }\n}\n\nTEST_F(FilePollerTest, TestUpdateFile) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile);\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestUpdateFileSubSecond) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile, true, milliseconds(10));\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestUpdateFileBackwards) {\n createFile();\n Baton<> baton;\n bool updated = false;\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n updateModifiedTime(tmpFile, false);\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestCreateFile) {\n Baton<> baton;\n bool updated = false;\n createFile();\n remove(tmpFile.c_str());\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n File(creat(tmpFile.c_str(), O_RDONLY));\n ASSERT_TRUE(baton.try_wait_for(seconds(5)));\n ASSERT_TRUE(updated);\n}\n\nTEST_F(FilePollerTest, TestDeleteFile) {\n Baton<> baton;\n bool updated = false;\n createFile();\n FilePoller poller(milliseconds(1));\n poller.addFileToTrack(tmpFile, [&]() {\n updated = true;\n baton.post();\n });\n remove(tmpFile.c_str());\n ASSERT_FALSE(baton.try_wait_for(seconds(1)));\n ASSERT_FALSE(updated);\n}\n\nstruct UpdateSyncState {\n std::mutex m;\n std::condition_variable cv;\n bool updated{false};\n\n void updateTriggered() {\n std::unique_lock lk(m);\n updated = true;\n cv.notify_one();\n }\n\n void waitForUpdate(bool expect = true) {\n std::unique_lock lk(m);\n cv.wait_for(lk, seconds(1), [&] { return updated; });\n ASSERT_EQ(updated, expect);\n updated = false;\n }\n};\n\nclass TestFile {\n public:\n TestFile(bool exists, system_clock::time_point modTime)\n : exists_(exists), modTime_(modTime) {}\n\n void update(bool e, system_clock::time_point t) {\n std::unique_lock lk(m);\n exists_ = e;\n modTime_ = t;\n }\n\n FilePoller::FileModificationData toFileModData() {\n std::unique_lock lk(m);\n return FilePoller::FileModificationData(exists_, modTime_);\n }\n\n const std::string name{\"fakeFile\"};\n private:\n bool exists_{false};\n system_clock::time_point modTime_;\n std::mutex m;\n\n};\n\nclass NoDiskPoller : public FilePoller {\n public:\n explicit NoDiskPoller(TestFile& testFile)\n : FilePoller(milliseconds(10)), testFile_(testFile) {}\n\n protected:\n FilePoller::FileModificationData\n getFileModData(const std::string& path) noexcept override {\n EXPECT_EQ(path, testFile_.name);\n return testFile_.toFileModData();\n }\n\n private:\n TestFile& testFile_;\n};\n\nstruct PollerWithState {\n explicit PollerWithState(TestFile& testFile) {\n poller = std::make_unique(testFile);\n poller->addFileToTrack(testFile.name, [&] {\n state.updateTriggered();\n });\n }\n\n void waitForUpdate(bool expect = true) {\n ASSERT_NO_FATAL_FAILURE(state.waitForUpdate(expect));\n }\n\n std::unique_ptr poller;\n UpdateSyncState state;\n};\n\nTEST_F(FilePollerTest, TestTwoUpdatesAndDelete) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState poller(testFile);\n\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n\n testFile.update(false, system_clock::time_point(seconds(0)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));\n}\n\nTEST_F(FilePollerTest, TestFileCreatedLate) {\n TestFile testFile(\n false,\n system_clock::time_point(seconds(0))); \/\/ not created yet\n PollerWithState poller(testFile);\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));\n\n testFile.update(true, system_clock::time_point(seconds(1)));\n ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());\n}\n\nTEST_F(FilePollerTest, TestMultiplePollers) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState p1(testFile);\n PollerWithState p2(testFile);\n\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());\n\n testFile.update(true, system_clock::time_point(seconds(1)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());\n\n \/\/ clear one of the pollers and make sure the other is still\n \/\/ getting them\n p2.poller.reset();\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate(false));\n}\n\nTEST(FilePoller, TestFork) {\n TestFile testFile(true, system_clock::time_point(seconds(1)));\n PollerWithState p1(testFile);\n testFile.update(true, system_clock::time_point(seconds(2)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n \/\/ nuke singleton\n folly::SingletonVault::singleton()->destroyInstances();\n testFile.update(true, system_clock::time_point(seconds(3)));\n ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());\n}\n<|endoftext|>"} {"text":"\/***********************************************************************\n created: Sep 18 2016\n author: Georger Araujo \n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2015 Paul D Turner & The CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n\n\/**************************************************************************\n* The following libs (and corresponding headers) are needed to compile and to link:\n* CEGUIBase\n* CEGUIOpenGLRenderer\n* CEGUICoreWindowRendererSet\n* default CEGUI xml parser (and dependencies)\n* sfml-graphics\n* sfml-main\n* sfml-window\n* sfml-system\n* OpengGL\n* glm headers (as part of CEGUIBase)\n***************************************************************************\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"sfml_keycodes_to_cegui_mappings.h\"\n\n\nconst int WIDTH = 800;\nconst int HEIGHT = 600;\n\n\n\/\/ Convert SFML2 keyboard code to CEGUI key code\nCEGUI::Key::Scan toCEGUIKey(const sf::Keyboard::Key & ro_key)\n{\n return static_cast(sfKeyToCEGUIKey[static_cast(ro_key)]);\n}\n\n\n\/\/ Convert SFML2 mouse button to CEGUI mouse button\nCEGUI::MouseButton toCEGUIButton(const sf::Mouse::Button & ro_button)\n{\n using namespace CEGUI;\n\n switch(ro_button)\n {\n case sf::Mouse::Left :\n return LeftButton;\n\n case sf::Mouse::Middle :\n return MiddleButton;\n\n case sf::Mouse::Right :\n return RightButton;\n\n case sf::Mouse::XButton1 :\n return X1Button;\n\n case sf::Mouse::XButton2 :\n return X2Button;\n\n default :\n return NoButton;\n }\n}\n\n\nvoid initCEGUI()\n{\n using namespace CEGUI;\n\n \/\/ create renderer and enable extra states\n OpenGL3Renderer & cegui_renderer = OpenGL3Renderer::create(Sizef(WIDTH, HEIGHT));\n cegui_renderer.enableExtraStateSettings(true);\n\n \/\/ create CEGUI system object\n CEGUI::System::create(cegui_renderer);\n\n \/\/ setup resource directories\n DefaultResourceProvider * rp = static_cast(\n System::getSingleton().getResourceProvider());\n rp->setResourceGroupDirectory(\"schemes\", \"datafiles\/schemes\/\");\n rp->setResourceGroupDirectory(\"imagesets\", \"datafiles\/imagesets\/\");\n rp->setResourceGroupDirectory(\"fonts\", \"datafiles\/fonts\/\");\n rp->setResourceGroupDirectory(\"layouts\", \"datafiles\/layouts\/\");\n rp->setResourceGroupDirectory(\"looknfeels\", \"datafiles\/looknfeel\/\");\n rp->setResourceGroupDirectory(\"lua_scripts\", \"datafiles\/lua_scripts\/\");\n rp->setResourceGroupDirectory(\"schemas\", \"datafiles\/xml_schemas\/\");\n\n \/\/ set default resource groups\n ImageManager::setImagesetDefaultResourceGroup(\"imagesets\");\n Font::setDefaultResourceGroup(\"fonts\");\n Scheme::setDefaultResourceGroup(\"schemes\");\n WidgetLookManager::setDefaultResourceGroup(\"looknfeels\");\n WindowManager::setDefaultResourceGroup(\"layouts\");\n ScriptModule::setDefaultResourceGroup(\"lua_scripts\");\n\n XMLParser * parser = System::getSingleton().getXMLParser();\n\n if (parser->isPropertyPresent(\"SchemaDefaultResourceGroup\"))\n parser->setProperty(\"SchemaDefaultResourceGroup\", \"schemas\");\n\n \/\/ load TaharezLook scheme and DejaVuSans-10 font\n SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\", \"schemes\");\n FontManager::getSingleton().createFromFile(\"DejaVuSans-10.font\");\n\n \/\/ set default font and cursor image and tooltip type\n System::getSingleton().getDefaultGUIContext().setDefaultFont(\"DejaVuSans-10\");\n System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage(\"TaharezLook\/MouseArrow\");\n System::getSingleton().getDefaultGUIContext().setDefaultTooltipType(\"TaharezLook\/Tooltip\");\n}\n\n\nvoid initWindows()\n{\n using namespace CEGUI;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Add your gui initialisation code in here.\n \/\/ You can use the following code as an inspiration for\n \/\/ creating your own windows.\n \/\/ But you should preferably use layout loading because you won't\n \/\/ have to recompile everytime you change the layout.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ load layout\n Window * root = WindowManager::getSingleton().loadLayoutFromFile(\"application_templates.layout\");\n System::getSingleton().getDefaultGUIContext().setRootWindow(root);\n}\n\n\nbool guiHandleEvent(const sf::Event & ro_event, const sf::Window & ro_window)\n{\n switch(ro_event.type)\n {\n case sf::Event::TextEntered :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(ro_event.text.unicode);\n\n case sf::Event::KeyPressed :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(toCEGUIKey(ro_event.key.code));\n\n case sf::Event::KeyReleased :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(toCEGUIKey(ro_event.key.code));\n\n case sf::Event::MouseMoved :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(\n static_cast(sf::Mouse::getPosition(ro_window).x),\n static_cast(sf::Mouse::getPosition(ro_window).y));\n\n case sf::Event::MouseButtonPressed :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(\n toCEGUIButton(ro_event.mouseButton.button));\n\n case sf::Event::MouseButtonReleased :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(\n toCEGUIButton(ro_event.mouseButton.button));\n\n case sf::Event::MouseWheelMoved :\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(\n static_cast(ro_event.mouseWheel.delta));\n\n default :\n return false;\n }\n\n return false;\n}\n\n\nint main()\n{\n \/\/ See http:\/\/www.sfml-dev.org\/tutorials\/2.4\/window-opengl.php\n\n \/\/ Create the window\n sf::Window window(\n sf::VideoMode(WIDTH, HEIGHT),\n \"SFML + OpenGL + CEGUI\",\n sf::Style::Default,\n sf::ContextSettings(32, 0, 0, 3, 2, sf::ContextSettings::Core));\n window.setMouseCursorVisible(false);\n window.setVerticalSyncEnabled(false);\n\n \/\/ Set GL clear color\n glClearColor(0, 0, 0, 255);\n\n \/\/ Init CEGUI\n initCEGUI();\n\n \/\/ Notify system of the window size\n CEGUI::System::getSingleton().notifyDisplaySizeChanged(CEGUI::Sizef(WIDTH, HEIGHT));\n\n \/\/ Initialise windows and setup layout\n initWindows();\n\n CEGUI::OpenGL3Renderer * renderer =\n static_cast(CEGUI::System::getSingleton().getRenderer());\n\n \/\/ Run the main loop\n sf::Clock clock;\n bool running = true;\n\n while(running)\n {\n \/\/ Handle events\n sf::Event event;\n\n while(window.pollEvent(event))\n {\n if (guiHandleEvent(event, window))\n continue;\n\n if (event.type == sf::Event::Closed)\n {\n \/\/ End the program\n running = false;\n }\n else if (event.type == sf::Event::Resized)\n {\n \/\/ Adjust the viewport when the window is resized\n glViewport(0, 0, event.size.width, event.size.height);\n }\n }\n\n \/\/ Clear the buffers\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ Inject time pulses\n const float time_elapsed = clock.restart().asSeconds();\n CEGUI::System::getSingleton().injectTimePulse(time_elapsed);\n CEGUI::System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed);\n\n \/\/ Draw...\n\n \/\/ Draw GUI\n CEGUI::System::getSingleton().renderAllGUIContexts();\n\n \/\/ End the current frame (internally swaps the front and back buffers)\n window.display();\n }\n\n \/\/ Destroy system and renderer\n CEGUI::System::destroy();\n CEGUI::OpenGL3Renderer::destroy(*renderer);\n renderer = 0;\n\n return 0;\n}\nFix coding style\/***********************************************************************\n created: Sep 18 2016\n author: Georger Araujo \n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2016 Paul D Turner & The CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n\n\/**************************************************************************\n* The following libs (and corresponding headers) are needed to compile and to link:\n* CEGUIBase\n* CEGUIOpenGLRenderer\n* CEGUICoreWindowRendererSet\n* default CEGUI xml parser (and dependencies)\n* sfml-graphics\n* sfml-main\n* sfml-window\n* sfml-system\n* OpengGL\n* glm headers (as part of CEGUIBase)\n***************************************************************************\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"sfml_keycodes_to_cegui_mappings.h\"\n\n\nconst int WIDTH = 800;\nconst int HEIGHT = 600;\n\n\n\/\/ Convert SFML2 keyboard code to CEGUI key code\nCEGUI::Key::Scan toCEGUIKey(const sf::Keyboard::Key& ro_key)\n{\n return static_cast(sfKeyToCEGUIKey[static_cast(ro_key)]);\n}\n\n\n\/\/ Convert SFML2 mouse button to CEGUI mouse button\nCEGUI::MouseButton toCEGUIButton(const sf::Mouse::Button& ro_button)\n{\n using namespace CEGUI;\n\n switch (ro_button)\n {\n case sf::Mouse::Left:\n return LeftButton;\n\n case sf::Mouse::Middle:\n return MiddleButton;\n\n case sf::Mouse::Right:\n return RightButton;\n\n case sf::Mouse::XButton1:\n return X1Button;\n\n case sf::Mouse::XButton2:\n return X2Button;\n\n default:\n return NoButton;\n }\n}\n\n\nvoid initCEGUI()\n{\n using namespace CEGUI;\n\n \/\/ create renderer and enable extra states\n OpenGL3Renderer& cegui_renderer = OpenGL3Renderer::create(Sizef(WIDTH, HEIGHT));\n cegui_renderer.enableExtraStateSettings(true);\n\n \/\/ create CEGUI system object\n CEGUI::System::create(cegui_renderer);\n\n \/\/ setup resource directories\n DefaultResourceProvider* rp = static_cast(\n System::getSingleton().getResourceProvider());\n rp->setResourceGroupDirectory(\"schemes\", \"datafiles\/schemes\/\");\n rp->setResourceGroupDirectory(\"imagesets\", \"datafiles\/imagesets\/\");\n rp->setResourceGroupDirectory(\"fonts\", \"datafiles\/fonts\/\");\n rp->setResourceGroupDirectory(\"layouts\", \"datafiles\/layouts\/\");\n rp->setResourceGroupDirectory(\"looknfeels\", \"datafiles\/looknfeel\/\");\n rp->setResourceGroupDirectory(\"lua_scripts\", \"datafiles\/lua_scripts\/\");\n rp->setResourceGroupDirectory(\"schemas\", \"datafiles\/xml_schemas\/\");\n\n \/\/ set default resource groups\n ImageManager::setImagesetDefaultResourceGroup(\"imagesets\");\n Font::setDefaultResourceGroup(\"fonts\");\n Scheme::setDefaultResourceGroup(\"schemes\");\n WidgetLookManager::setDefaultResourceGroup(\"looknfeels\");\n WindowManager::setDefaultResourceGroup(\"layouts\");\n ScriptModule::setDefaultResourceGroup(\"lua_scripts\");\n\n XMLParser* parser = System::getSingleton().getXMLParser();\n\n if (parser->isPropertyPresent(\"SchemaDefaultResourceGroup\"))\n parser->setProperty(\"SchemaDefaultResourceGroup\", \"schemas\");\n\n \/\/ load TaharezLook scheme and DejaVuSans-10 font\n SchemeManager::getSingleton().createFromFile(\"TaharezLook.scheme\", \"schemes\");\n FontManager::getSingleton().createFromFile(\"DejaVuSans-10.font\");\n\n \/\/ set default font and cursor image and tooltip type\n System::getSingleton().getDefaultGUIContext().setDefaultFont(\"DejaVuSans-10\");\n System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage(\"TaharezLook\/MouseArrow\");\n System::getSingleton().getDefaultGUIContext().setDefaultTooltipType(\"TaharezLook\/Tooltip\");\n}\n\n\nvoid initWindows()\n{\n using namespace CEGUI;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Add your gui initialisation code in here.\n \/\/ You can use the following code as an inspiration for\n \/\/ creating your own windows.\n \/\/ But you should preferably use layout loading because you won't\n \/\/ have to recompile everytime you change the layout.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ load layout\n Window* root = WindowManager::getSingleton().loadLayoutFromFile(\"application_templates.layout\");\n System::getSingleton().getDefaultGUIContext().setRootWindow(root);\n}\n\n\nbool guiHandleEvent(const sf::Event& ro_event, const sf::Window& ro_window)\n{\n switch (ro_event.type)\n {\n case sf::Event::TextEntered:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(ro_event.text.unicode);\n\n case sf::Event::KeyPressed:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(toCEGUIKey(ro_event.key.code));\n\n case sf::Event::KeyReleased:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(toCEGUIKey(ro_event.key.code));\n\n case sf::Event::MouseMoved:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(\n static_cast(sf::Mouse::getPosition(ro_window).x),\n static_cast(sf::Mouse::getPosition(ro_window).y));\n\n case sf::Event::MouseButtonPressed:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(\n toCEGUIButton(ro_event.mouseButton.button));\n\n case sf::Event::MouseButtonReleased:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(\n toCEGUIButton(ro_event.mouseButton.button));\n\n case sf::Event::MouseWheelMoved:\n return CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(\n static_cast(ro_event.mouseWheel.delta));\n\n default:\n return false;\n }\n\n return false;\n}\n\n\nint main()\n{\n \/\/ See http:\/\/www.sfml-dev.org\/tutorials\/2.4\/window-opengl.php\n\n \/\/ Create the window\n sf::Window window(\n sf::VideoMode(WIDTH, HEIGHT),\n \"SFML + OpenGL + CEGUI\",\n sf::Style::Default,\n sf::ContextSettings(0, 0, 0, 3, 2, sf::ContextSettings::Core));\n window.setMouseCursorVisible(false);\n window.setVerticalSyncEnabled(false);\n\n \/\/ Set GL clear color\n glClearColor(0, 0, 0, 255);\n\n \/\/ Init CEGUI\n initCEGUI();\n\n \/\/ Notify system of the window size\n CEGUI::System::getSingleton().notifyDisplaySizeChanged(CEGUI::Sizef(WIDTH, HEIGHT));\n\n \/\/ Initialise windows and setup layout\n initWindows();\n\n CEGUI::OpenGL3Renderer* renderer =\n static_cast(CEGUI::System::getSingleton().getRenderer());\n\n \/\/ Run the main loop\n sf::Clock clock;\n bool running = true;\n\n while (running)\n {\n \/\/ Handle events\n sf::Event event;\n\n while (window.pollEvent(event))\n {\n if (guiHandleEvent(event, window))\n continue;\n\n if (event.type == sf::Event::Closed)\n {\n \/\/ End the program\n running = false;\n }\n else if (event.type == sf::Event::Resized)\n {\n \/\/ Adjust the viewport when the window is resized\n glViewport(0, 0, event.size.width, event.size.height);\n }\n }\n\n \/\/ Clear the buffers\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ Inject time pulses\n const float time_elapsed = clock.restart().asSeconds();\n CEGUI::System::getSingleton().injectTimePulse(time_elapsed);\n CEGUI::System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed);\n\n \/\/ Draw...\n\n \/\/ Draw GUI\n CEGUI::System::getSingleton().renderAllGUIContexts();\n\n \/\/ End the current frame (internally swaps the front and back buffers)\n window.display();\n }\n\n \/\/ Destroy system and renderer\n CEGUI::System::destroy();\n CEGUI::OpenGL3Renderer::destroy(*renderer);\n renderer = 0;\n\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"cell_id.hpp\"\n\n#include \"..\/storage\/defines.hpp\" \/\/ just for file extensions\n\n#include \"..\/geometry\/point2d.hpp\"\n#include \"..\/geometry\/rect2d.hpp\"\n\n#include \"..\/coding\/file_container.hpp\"\n\n#include \"..\/base\/base.hpp\"\n\n#include \"..\/std\/string.hpp\"\n#include \"..\/std\/vector.hpp\"\n#include \"..\/std\/array.hpp\"\n\n#include \n\nclass ArrayByteSource;\nclass FeatureBase;\n\n\/\/\/ Used for serialization\\deserialization of features during --generate_features.\nclass FeatureBuilder1\n{\npublic:\n FeatureBuilder1();\n\n \/\/\/ @name Geometry manipulating functions.\n \/\/@{\n \/\/\/ Set center (origin) point of feature.\n void SetCenter(m2::PointD const & p);\n\n \/\/\/ Add point to geometry.\n void AddPoint(m2::PointD const & p);\n\n \/\/\/ Set that featue is area and get ownership of holes.\n void SetAreaAddHoles(list > & holes);\n \/\/@}\n\n void AddName(string const & name);\n\n static const int m_maxTypesCount = 7;\n\n template \n inline void AddTypes(TIter beg, TIter end)\n {\n int const count = min(static_cast(m_maxTypesCount), static_cast(distance(beg, end)));\n m_Types.assign(beg, beg + count);\n }\n inline void SetType(uint32_t type)\n {\n m_Types.clear();\n m_Types.push_back(type);\n }\n\n void AddLayer(int32_t layer);\n\n typedef vector buffer_t;\n\n \/\/\/ @name Serialization.\n \/\/@{\n void Serialize(buffer_t & data) const;\n void SerializeBase(buffer_t & data) const;\n\n void Deserialize(buffer_t & data);\n \/\/@}\n\n \/\/\/@name Selectors.\n \/\/@{\n inline m2::RectD GetLimitRect() const { return m_LimitRect; }\n\n \/\/\/ Get common parameters of feature.\n FeatureBase GetFeatureBase() const;\n\n bool IsGeometryClosed() const;\n\n inline size_t GetPointsCount() const { return m_Geometry.size(); }\n\n template \n void ForEachPointRef(ToDo & toDo) const\n {\n for_each(m_Geometry.begin(), m_Geometry.end(), boost::bind(ref(toDo), _1));\n }\n \/\/@}\n\nprotected:\n\n \/\/\/ @name For diagnostic use only.\n \/\/@{\n bool operator == (FeatureBuilder1 const &) const;\n\n bool CheckValid() const;\n \/\/@}\n\n typedef vector points_t;\n\n uint8_t GetHeader() const;\n\n \/\/\/ Name. Can be empty. Check HEADER_HAS_NAME.\n string m_Name;\n\n \/\/\/ Feature classificator-types. Can not be empty.\n vector m_Types;\n\n \/\/\/ Drawable layer of feature. Can be empty, Check HEADER_HAS_LAYER.\n int32_t m_Layer;\n\n m2::RectD m_LimitRect;\n\n \/\/\/ Can be one of the following:\n \/\/\/ - point in point-feature\n \/\/\/ - origin point of text [future] in line-feature\n \/\/\/ - origin point of text or symbol in area-feature\n m2::PointD m_Center; \/\/ Check HEADER_HAS_POINT\n\n \/\/\/ Can be one of the following:\n \/\/\/ - geometry in line-feature\n \/\/\/ - boundary in area-feature\n points_t m_Geometry; \/\/ Check HEADER_IS_LINE\n\n \/\/\/ List of holes in area-feature.\n list m_Holes; \/\/ Check HEADER_IS_AREA\n\n bool m_bArea; \/\/\/< this is area-feature\n bool m_bHasCenter; \/\/\/< m_center exists\n};\n\n\/\/\/ Used for serialization of features during final pass.\nclass FeatureBuilder2 : public FeatureBuilder1\n{\n typedef FeatureBuilder1 base_type;\n\n typedef vector offsets_t;\n\n static void SerializeOffsets(uint32_t mask, offsets_t const & offsets, buffer_t & buffer);\n\npublic:\n\n struct buffers_holder_t\n {\n offsets_t m_lineOffset; \/\/ in\n offsets_t m_trgOffset; \/\/ in\n uint32_t m_lineMask, m_trgMask;\n\n base_type::buffer_t m_buffer; \/\/ out\n\n buffers_holder_t() : m_lineMask(0), m_trgMask(0) {}\n };\n\n bool IsDrawableLikeLine(int lowS, int highS) const;\n bool IsDrawableLikeArea() const { return m_bArea; }\n\n points_t const & GetGeometry() const { return m_Geometry; }\n list const & GetHoles() const { return m_Holes; }\n\n \/\/\/ @name Overwrite from base_type.\n \/\/@{\n void Serialize(buffers_holder_t & data);\n \/\/@}\n};\n\n\/\/\/ Base feature class for storing common data (without geometry).\nclass FeatureBase\n{\n static const int m_maxTypesCount = 7;\npublic:\n enum FeatureType\n {\n FEATURE_TYPE_POINT = 0,\n FEATURE_TYPE_LINE = 1,\n FEATURE_TYPE_AREA = 2\n };\n\n FeatureBase() : m_Offset(0) {}\n\n typedef vector buffer_t;\n\n inline FeatureType GetFeatureType() const\n {\n uint8_t const h = Header();\n if (h & HEADER_IS_AREA)\n return FEATURE_TYPE_AREA;\n else if (h & HEADER_IS_LINE)\n return FEATURE_TYPE_LINE;\n else\n {\n ASSERT ( h & HEADER_HAS_POINT, () );\n return FEATURE_TYPE_POINT;\n }\n }\n\n inline uint32_t GetTypesCount() const\n {\n return Header() & m_maxTypesCount;\n }\n\n inline int32_t GetLayer() const\n {\n if (!(Header() & HEADER_HAS_LAYER))\n return 0;\n if (!m_bLayerParsed)\n ParseLayer();\n return m_Layer;\n }\n\n inline string GetName() const\n {\n if (!(Header() & HEADER_HAS_NAME))\n return string();\n if (!m_bNameParsed)\n ParseName();\n return m_Name;\n }\n\n inline m2::RectD GetLimitRect() const\n {\n ASSERT ( m_bGeometryParsed || m_bTrianglesParsed, () );\n return m_LimitRect;\n }\n\n class GetTypesFn\n {\n public:\n uint32_t m_types[m_maxTypesCount];\n int m_size;\n\n GetTypesFn() : m_size(0) {}\n void operator() (uint32_t t)\n {\n m_types[m_size++] = t;\n }\n };\n\n template \n void ForEachTypeRef(FunctorT & f) const\n {\n if (!m_bTypesParsed)\n ParseTypes();\n\n uint32_t const typeCount = GetTypesCount();\n for (size_t i = 0; i < typeCount; ++i)\n f(m_Types[i]);\n }\n\n enum\n {\n HEADER_HAS_LAYER = 1U << 7,\n HEADER_HAS_NAME = 1U << 6,\n HEADER_IS_AREA = 1U << 5,\n HEADER_IS_LINE = 1U << 4,\n HEADER_HAS_POINT = 1U << 3\n };\n\n void InitFeatureBuilder(FeatureBuilder1 & fb) const;\n\nprotected:\n void Deserialize(buffer_t & data, uint32_t offset = 0);\n string DebugString() const;\n\nprotected:\n\n buffer_t m_Data;\n uint32_t m_Offset;\n\n friend class FeatureBuilder1;\n\n void SetHeader(uint8_t h);\n\n inline char const * DataPtr() const { return &m_Data[m_Offset]; }\n inline uint8_t Header() const { return static_cast(*DataPtr()); }\n uint32_t CalcOffset(ArrayByteSource const & source) const;\n\n mutable uint32_t m_Types[m_maxTypesCount];\n mutable int32_t m_Layer;\n mutable string m_Name;\n mutable m2::PointD m_Center;\n\n mutable m2::RectD m_LimitRect;\n\n mutable uint32_t m_LayerOffset;\n mutable uint32_t m_NameOffset;\n mutable uint32_t m_CenterOffset;\n mutable uint32_t m_GeometryOffset;\n mutable uint32_t m_TrianglesOffset;\n\n mutable bool m_bTypesParsed;\n mutable bool m_bLayerParsed;\n mutable bool m_bNameParsed;\n mutable bool m_bCenterParsed;\n mutable bool m_bGeometryParsed;\n mutable bool m_bTrianglesParsed;\n\n void ParseTypes() const;\n void ParseLayer() const;\n void ParseName() const;\n void ParseCenter() const;\n\n void ParseAll() const;\n};\n\n\/\/\/ Working feature class with geometry.\nclass FeatureType : public FeatureBase\n{\n typedef FeatureBase base_type;\n\npublic:\n struct read_source_t\n {\n buffer_t m_data;\n uint32_t m_offset;\n\n FilesContainerR m_cont;\n\n read_source_t(FilesContainerR const & cont) : m_offset(0), m_cont(cont) {}\n\n void assign(char const * data, uint32_t size)\n {\n m_data.assign(data, data + size);\n }\n };\n\n FeatureType() {}\n FeatureType(read_source_t & src);\n\n void Deserialize(read_source_t & src);\n\n \/\/\/ @name Geometry.\n \/\/@{\n m2::RectD GetLimitRect(int scale) const;\n\n bool IsEmptyGeometry(int scale) const;\n\n template \n void ForEachPointRef(FunctorT & f, int scale) const\n {\n if (!m_bGeometryParsed)\n ParseGeometry(scale);\n\n if (m_Geometry.empty())\n {\n CHECK ( Header() & HEADER_HAS_POINT, (\"Call ForEachPoint for empty geometry\") );\n f(CoordPointT(m_Center.x, m_Center.y));\n }\n else\n {\n for (size_t i = 0; i < m_Geometry.size(); ++i)\n f(CoordPointT(m_Geometry[i].x, m_Geometry[i].y));\n }\n }\n\n template \n void ForEachPoint(FunctorT f, int scale) const\n {\n ForEachPointRef(f, scale);\n }\n\n template \n void ForEachTriangleRef(FunctorT & f, int scale) const\n {\n if (!m_bTrianglesParsed)\n ParseTriangles(scale);\n\n for (size_t i = 0; i < m_Triangles.size();)\n {\n f(m_Triangles[i], m_Triangles[i+1], m_Triangles[i+2]);\n i += 3;\n }\n }\n\n template \n void ForEachTriangleExRef(FunctorT & f, int scale) const\n {\n f.StartPrimitive(m_Triangles.size());\n ForEachTriangleRef(f, scale);\n f.EndPrimitive();\n }\n \/\/@}\n\n \/\/\/ For test cases only.\n string DebugString(int scale) const;\n\nprivate:\n void ParseOffsets() const;\n void ParseGeometry(int scale) const;\n void ParseTriangles(int scale) const;\n\n void ParseAll(int scale) const;\n\n mutable vector m_Geometry;\n mutable vector m_Triangles;\n\n FilesContainerR * m_cont;\n\n mutable bool m_bOffsetsParsed;\n\n typedef array offsets_t; \/\/ should be synhronized with ARRAY_SIZE(g_arrScales)\n\n static void ReadOffsetsImpl(ArrayByteSource & src, offsets_t & offsets);\n\n static uint32_t const m_invalidOffset = uint32_t(-1);\n\n uint32_t GetOffset(int scale, offsets_t const & offset) const;\n\n mutable offsets_t m_lineOffsets, m_trgOffsets;\n};\nMinor fixes connected with code convensions.#pragma once\n\n#include \"cell_id.hpp\"\n\n#include \"..\/storage\/defines.hpp\" \/\/ just for file extensions\n\n#include \"..\/geometry\/point2d.hpp\"\n#include \"..\/geometry\/rect2d.hpp\"\n\n#include \"..\/coding\/file_container.hpp\"\n\n#include \"..\/base\/base.hpp\"\n\n#include \"..\/std\/string.hpp\"\n#include \"..\/std\/vector.hpp\"\n#include \"..\/std\/array.hpp\"\n#include \"..\/std\/bind.hpp\"\n\nclass ArrayByteSource;\nclass FeatureBase;\n\n\/\/\/ Used for serialization\\deserialization of features during --generate_features.\nclass FeatureBuilder1\n{\npublic:\n FeatureBuilder1();\n\n \/\/\/ @name Geometry manipulating functions.\n \/\/@{\n \/\/\/ Set center (origin) point of feature.\n void SetCenter(m2::PointD const & p);\n\n \/\/\/ Add point to geometry.\n void AddPoint(m2::PointD const & p);\n\n \/\/\/ Set that featue is area and get ownership of holes.\n void SetAreaAddHoles(list > & holes);\n \/\/@}\n\n void AddName(string const & name);\n\n static const int m_maxTypesCount = 7;\n\n template \n inline void AddTypes(TIter beg, TIter end)\n {\n \/\/ !WTF! with GCC\n int const count = min(static_cast(m_maxTypesCount), static_cast(distance(beg, end)));\n m_Types.assign(beg, beg + count);\n }\n inline void SetType(uint32_t type)\n {\n m_Types.clear();\n m_Types.push_back(type);\n }\n\n void AddLayer(int32_t layer);\n\n typedef vector buffer_t;\n\n \/\/\/ @name Serialization.\n \/\/@{\n void Serialize(buffer_t & data) const;\n void SerializeBase(buffer_t & data) const;\n\n void Deserialize(buffer_t & data);\n \/\/@}\n\n \/\/\/@name Selectors.\n \/\/@{\n inline m2::RectD GetLimitRect() const { return m_LimitRect; }\n\n \/\/\/ Get common parameters of feature.\n FeatureBase GetFeatureBase() const;\n\n bool IsGeometryClosed() const;\n\n inline size_t GetPointsCount() const { return m_Geometry.size(); }\n\n template \n void ForEachPointRef(ToDo & toDo) const\n {\n for_each(m_Geometry.begin(), m_Geometry.end(), bind(ref(toDo), _1));\n }\n \/\/@}\n\nprotected:\n\n \/\/\/ @name For diagnostic use only.\n \/\/@{\n bool operator == (FeatureBuilder1 const &) const;\n\n bool CheckValid() const;\n \/\/@}\n\n typedef vector points_t;\n\n uint8_t GetHeader() const;\n\n \/\/\/ Name. Can be empty. Check HEADER_HAS_NAME.\n string m_Name;\n\n \/\/\/ Feature classificator-types. Can not be empty.\n vector m_Types;\n\n \/\/\/ Drawable layer of feature. Can be empty, Check HEADER_HAS_LAYER.\n int32_t m_Layer;\n\n m2::RectD m_LimitRect;\n\n \/\/\/ Can be one of the following:\n \/\/\/ - point in point-feature\n \/\/\/ - origin point of text [future] in line-feature\n \/\/\/ - origin point of text or symbol in area-feature\n m2::PointD m_Center; \/\/ Check HEADER_HAS_POINT\n\n \/\/\/ Can be one of the following:\n \/\/\/ - geometry in line-feature\n \/\/\/ - boundary in area-feature\n points_t m_Geometry; \/\/ Check HEADER_IS_LINE\n\n \/\/\/ List of holes in area-feature.\n list m_Holes; \/\/ Check HEADER_IS_AREA\n\n bool m_bArea; \/\/\/< this is area-feature\n bool m_bHasCenter; \/\/\/< m_center exists\n};\n\n\/\/\/ Used for serialization of features during final pass.\nclass FeatureBuilder2 : public FeatureBuilder1\n{\n typedef FeatureBuilder1 base_type;\n\n typedef vector offsets_t;\n\n static void SerializeOffsets(uint32_t mask, offsets_t const & offsets, buffer_t & buffer);\n\npublic:\n\n struct buffers_holder_t\n {\n offsets_t m_lineOffset; \/\/ in\n offsets_t m_trgOffset; \/\/ in\n uint32_t m_lineMask, m_trgMask;\n\n base_type::buffer_t m_buffer; \/\/ out\n\n buffers_holder_t() : m_lineMask(0), m_trgMask(0) {}\n };\n\n bool IsDrawableLikeLine(int lowS, int highS) const;\n bool IsDrawableLikeArea() const { return m_bArea; }\n\n points_t const & GetGeometry() const { return m_Geometry; }\n list const & GetHoles() const { return m_Holes; }\n\n \/\/\/ @name Overwrite from base_type.\n \/\/@{\n void Serialize(buffers_holder_t & data);\n \/\/@}\n};\n\n\/\/\/ Base feature class for storing common data (without geometry).\nclass FeatureBase\n{\n static const int m_maxTypesCount = 7;\npublic:\n enum FeatureType\n {\n FEATURE_TYPE_POINT = 0,\n FEATURE_TYPE_LINE = 1,\n FEATURE_TYPE_AREA = 2\n };\n\n FeatureBase() : m_Offset(0) {}\n\n typedef vector buffer_t;\n\n inline FeatureType GetFeatureType() const\n {\n uint8_t const h = Header();\n if (h & HEADER_IS_AREA)\n return FEATURE_TYPE_AREA;\n else if (h & HEADER_IS_LINE)\n return FEATURE_TYPE_LINE;\n else\n {\n ASSERT ( h & HEADER_HAS_POINT, () );\n return FEATURE_TYPE_POINT;\n }\n }\n\n inline uint32_t GetTypesCount() const\n {\n return Header() & m_maxTypesCount;\n }\n\n inline int32_t GetLayer() const\n {\n if (!(Header() & HEADER_HAS_LAYER))\n return 0;\n if (!m_bLayerParsed)\n ParseLayer();\n return m_Layer;\n }\n\n inline string GetName() const\n {\n if (!(Header() & HEADER_HAS_NAME))\n return string();\n if (!m_bNameParsed)\n ParseName();\n return m_Name;\n }\n\n inline m2::RectD GetLimitRect() const\n {\n ASSERT ( m_bGeometryParsed || m_bTrianglesParsed, () );\n return m_LimitRect;\n }\n\n class GetTypesFn\n {\n public:\n uint32_t m_types[m_maxTypesCount];\n int m_size;\n\n GetTypesFn() : m_size(0) {}\n void operator() (uint32_t t)\n {\n m_types[m_size++] = t;\n }\n };\n\n template \n void ForEachTypeRef(FunctorT & f) const\n {\n if (!m_bTypesParsed)\n ParseTypes();\n\n uint32_t const typeCount = GetTypesCount();\n for (size_t i = 0; i < typeCount; ++i)\n f(m_Types[i]);\n }\n\n enum\n {\n HEADER_HAS_LAYER = 1U << 7,\n HEADER_HAS_NAME = 1U << 6,\n HEADER_IS_AREA = 1U << 5,\n HEADER_IS_LINE = 1U << 4,\n HEADER_HAS_POINT = 1U << 3\n };\n\n void InitFeatureBuilder(FeatureBuilder1 & fb) const;\n\nprotected:\n void Deserialize(buffer_t & data, uint32_t offset = 0);\n string DebugString() const;\n\nprotected:\n\n buffer_t m_Data;\n uint32_t m_Offset;\n\n friend class FeatureBuilder1;\n\n void SetHeader(uint8_t h);\n\n inline char const * DataPtr() const { return &m_Data[m_Offset]; }\n inline uint8_t Header() const { return static_cast(*DataPtr()); }\n uint32_t CalcOffset(ArrayByteSource const & source) const;\n\n mutable uint32_t m_Types[m_maxTypesCount];\n mutable int32_t m_Layer;\n mutable string m_Name;\n mutable m2::PointD m_Center;\n\n mutable m2::RectD m_LimitRect;\n\n mutable uint32_t m_LayerOffset;\n mutable uint32_t m_NameOffset;\n mutable uint32_t m_CenterOffset;\n mutable uint32_t m_GeometryOffset;\n mutable uint32_t m_TrianglesOffset;\n\n mutable bool m_bTypesParsed;\n mutable bool m_bLayerParsed;\n mutable bool m_bNameParsed;\n mutable bool m_bCenterParsed;\n mutable bool m_bGeometryParsed;\n mutable bool m_bTrianglesParsed;\n\n void ParseTypes() const;\n void ParseLayer() const;\n void ParseName() const;\n void ParseCenter() const;\n\n void ParseAll() const;\n};\n\n\/\/\/ Working feature class with geometry.\nclass FeatureType : public FeatureBase\n{\n typedef FeatureBase base_type;\n\npublic:\n struct read_source_t\n {\n buffer_t m_data;\n uint32_t m_offset;\n\n FilesContainerR m_cont;\n\n read_source_t(FilesContainerR const & cont) : m_offset(0), m_cont(cont) {}\n\n void assign(char const * data, uint32_t size)\n {\n m_data.assign(data, data + size);\n }\n };\n\n FeatureType() {}\n FeatureType(read_source_t & src);\n\n void Deserialize(read_source_t & src);\n\n \/\/\/ @name Geometry.\n \/\/@{\n m2::RectD GetLimitRect(int scale) const;\n\n bool IsEmptyGeometry(int scale) const;\n\n template \n void ForEachPointRef(FunctorT & f, int scale) const\n {\n if (!m_bGeometryParsed)\n ParseGeometry(scale);\n\n if (m_Geometry.empty())\n {\n CHECK ( Header() & HEADER_HAS_POINT, (\"Call ForEachPoint for empty geometry\") );\n f(CoordPointT(m_Center.x, m_Center.y));\n }\n else\n {\n for (size_t i = 0; i < m_Geometry.size(); ++i)\n f(CoordPointT(m_Geometry[i].x, m_Geometry[i].y));\n }\n }\n\n template \n void ForEachPoint(FunctorT f, int scale) const\n {\n ForEachPointRef(f, scale);\n }\n\n template \n void ForEachTriangleRef(FunctorT & f, int scale) const\n {\n if (!m_bTrianglesParsed)\n ParseTriangles(scale);\n\n for (size_t i = 0; i < m_Triangles.size();)\n {\n f(m_Triangles[i], m_Triangles[i+1], m_Triangles[i+2]);\n i += 3;\n }\n }\n\n template \n void ForEachTriangleExRef(FunctorT & f, int scale) const\n {\n f.StartPrimitive(m_Triangles.size());\n ForEachTriangleRef(f, scale);\n f.EndPrimitive();\n }\n \/\/@}\n\n \/\/\/ For test cases only.\n string DebugString(int scale) const;\n\nprivate:\n void ParseOffsets() const;\n void ParseGeometry(int scale) const;\n void ParseTriangles(int scale) const;\n\n void ParseAll(int scale) const;\n\n mutable vector m_Geometry;\n mutable vector m_Triangles;\n\n FilesContainerR * m_cont;\n\n mutable bool m_bOffsetsParsed;\n\n typedef array offsets_t; \/\/ should be synhronized with ARRAY_SIZE(g_arrScales)\n\n static void ReadOffsetsImpl(ArrayByteSource & src, offsets_t & offsets);\n\n static uint32_t const m_invalidOffset = uint32_t(-1);\n\n uint32_t GetOffset(int scale, offsets_t const & offset) const;\n\n mutable offsets_t m_lineOffsets, m_trgOffsets;\n};\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"indexer\/feature_data.hpp\"\n#include \"indexer\/ftypes_mapping.hpp\"\n\n#include \"coding\/csv_file_reader.hpp\"\n\n#include \"platform\/platform.hpp\"\n\n#include \"base\/assert.hpp\"\n#include \"base\/logging.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace ftraits\n{\ntemplate \nclass TraitsBase\n{\npublic:\n static Value GetValue(feature::TypesHolder const & types)\n {\n static Base instance;\n auto const it = instance.m_matcher.Find(types);\n if (!instance.m_matcher.IsValid(it))\n return notFound;\n\n return it->second;\n }\n\nprotected:\n ftypes::HashMapMatcher m_matcher;\n};\n\nenum UGCType\n{\n UGCTYPE_NONE = 0u,\n UGCTYPE_RATING = 1u << 0, \/\/ 1\n UGCTYPE_REVIEWS = 1u << 1, \/\/ 2\n UGCTYPE_DETAILS = 1u << 2 \/\/ 4\n};\n\nusing UGCTypeMask = unsigned;\n\nclass UGC : public TraitsBase\n{\n friend class TraitsBase;\n\n std::array const m_masks = {{UGCTYPE_RATING, UGCTYPE_REVIEWS, UGCTYPE_DETAILS}};\n\n UGC()\n {\n coding::CSVReader const reader;\n auto const filePath = GetPlatform().ReadPathForFile(\"ugc_types.csv\", \"wr\");\n reader.ReadLineByLine(filePath, [this](std::vector const & line) {\n auto const lineSize = line.size();\n ASSERT_EQUAL(lineSize, 4, ());\n ASSERT_EQUAL(lineSize - 1, m_masks.size(), ());\n\n UGCTypeMask maskType = UGCTYPE_NONE;\n for (size_t i = 1; i < lineSize; i++)\n {\n int flag;\n if (!strings::to_int(line[i], flag))\n {\n LOG(LERROR, (\"File ugc_types.csv must contain a bit mask of supported ugc traits!\"));\n return;\n }\n\n if (flag)\n maskType |= m_masks[i - 1];\n }\n\n auto const & typeInfo = line.front();\n std::istringstream iss(typeInfo);\n std::vector types{std::istream_iterator(iss),\n std::istream_iterator()};\n\n m_matcher.AppendType(types, maskType);\n });\n }\n\npublic:\n static bool IsUGCAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) != UGCTYPE_NONE;\n }\n static bool IsRatingAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_RATING;\n }\n static bool IsReviewsAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_REVIEWS;\n }\n static bool IsDetailsAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_DETAILS;\n }\n};\n\nenum class WheelchairAvailability\n{\n No,\n Yes,\n Limited\n};\n\ninline std::string DebugPrint(WheelchairAvailability wheelchair)\n{\n switch (wheelchair)\n {\n case WheelchairAvailability::No: return \"No\";\n case WheelchairAvailability::Yes: return \"Yes\";\n case WheelchairAvailability::Limited: return \"Limited\";\n }\n}\n\nclass Wheelchair\n : public TraitsBase\n{\n friend class TraitsBase;\n\n using TypesInitializer = std::initializer_list>;\n\n Wheelchair()\n {\n m_matcher.Append({{\"wheelchair\", \"no\"}}, WheelchairAvailability::No);\n m_matcher.Append({{\"wheelchair\", \"yes\"}}, WheelchairAvailability::Yes);\n m_matcher.Append({{\"wheelchair\", \"limited\"}},\n WheelchairAvailability::Limited);\n }\n};\n\n} \/\/ namespace ftraits\nRemoved const from csv reader object#pragma once\n\n#include \"indexer\/feature_data.hpp\"\n#include \"indexer\/ftypes_mapping.hpp\"\n\n#include \"coding\/csv_file_reader.hpp\"\n\n#include \"platform\/platform.hpp\"\n\n#include \"base\/assert.hpp\"\n#include \"base\/logging.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace ftraits\n{\ntemplate \nclass TraitsBase\n{\npublic:\n static Value GetValue(feature::TypesHolder const & types)\n {\n static Base instance;\n auto const it = instance.m_matcher.Find(types);\n if (!instance.m_matcher.IsValid(it))\n return notFound;\n\n return it->second;\n }\n\nprotected:\n ftypes::HashMapMatcher m_matcher;\n};\n\nenum UGCType\n{\n UGCTYPE_NONE = 0u,\n UGCTYPE_RATING = 1u << 0, \/\/ 1\n UGCTYPE_REVIEWS = 1u << 1, \/\/ 2\n UGCTYPE_DETAILS = 1u << 2 \/\/ 4\n};\n\nusing UGCTypeMask = unsigned;\n\nclass UGC : public TraitsBase\n{\n friend class TraitsBase;\n\n std::array const m_masks = {{UGCTYPE_RATING, UGCTYPE_REVIEWS, UGCTYPE_DETAILS}};\n\n UGC()\n {\n coding::CSVReader reader;\n auto const filePath = GetPlatform().ReadPathForFile(\"ugc_types.csv\", \"wr\");\n reader.ReadLineByLine(filePath, [this](std::vector const & line) {\n auto const lineSize = line.size();\n ASSERT_EQUAL(lineSize, 4, ());\n ASSERT_EQUAL(lineSize - 1, m_masks.size(), ());\n\n UGCTypeMask maskType = UGCTYPE_NONE;\n for (size_t i = 1; i < lineSize; i++)\n {\n int flag;\n if (!strings::to_int(line[i], flag))\n {\n LOG(LERROR, (\"File ugc_types.csv must contain a bit mask of supported ugc traits!\"));\n return;\n }\n\n if (flag)\n maskType |= m_masks[i - 1];\n }\n\n auto const & typeInfo = line.front();\n std::istringstream iss(typeInfo);\n std::vector types{std::istream_iterator(iss),\n std::istream_iterator()};\n\n m_matcher.AppendType(types, maskType);\n });\n }\n\npublic:\n static bool IsUGCAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) != UGCTYPE_NONE;\n }\n static bool IsRatingAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_RATING;\n }\n static bool IsReviewsAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_REVIEWS;\n }\n static bool IsDetailsAvailable(feature::TypesHolder const & types)\n {\n return GetValue(types) & UGCTYPE_DETAILS;\n }\n};\n\nenum class WheelchairAvailability\n{\n No,\n Yes,\n Limited\n};\n\ninline std::string DebugPrint(WheelchairAvailability wheelchair)\n{\n switch (wheelchair)\n {\n case WheelchairAvailability::No: return \"No\";\n case WheelchairAvailability::Yes: return \"Yes\";\n case WheelchairAvailability::Limited: return \"Limited\";\n }\n}\n\nclass Wheelchair\n : public TraitsBase\n{\n friend class TraitsBase;\n\n using TypesInitializer = std::initializer_list>;\n\n Wheelchair()\n {\n m_matcher.Append({{\"wheelchair\", \"no\"}}, WheelchairAvailability::No);\n m_matcher.Append({{\"wheelchair\", \"yes\"}}, WheelchairAvailability::Yes);\n m_matcher.Append({{\"wheelchair\", \"limited\"}},\n WheelchairAvailability::Limited);\n }\n};\n\n} \/\/ namespace ftraits\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer_multirotor.cpp\n *\n * Multi-rotor mixers.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"mixer.h\"\n\n\/\/ This file is generated by the multi_tables script which is invoked during the build process\n#include \"mixer_multirotor.generated.h\"\n\n#define debug(fmt, args...)\tdo { } while(0)\n\/\/#define debug(fmt, args...)\tdo { printf(\"[mixer] \" fmt \"\\n\", ##args); } while(0)\n\/\/#include \n\/\/#define debug(fmt, args...)\tlowsyslog(fmt \"\\n\", ##args)\n\n\/*\n * Clockwise: 1\n * Counter-clockwise: -1\n *\/\n\nnamespace\n{\n\nfloat constrain(float val, float min, float max)\n{\n\treturn (val < min) ? min : ((val > max) ? max : val);\n}\n\n} \/\/ anonymous namespace\n\nMultirotorMixer::MultirotorMixer(ControlCallback control_cb,\n\t\t\t\t uintptr_t cb_handle,\n\t\t\t\t MultirotorGeometry geometry,\n\t\t\t\t float roll_scale,\n\t\t\t\t float pitch_scale,\n\t\t\t\t float yaw_scale,\n\t\t\t\t float idle_speed) :\n\tMixer(control_cb, cb_handle),\n\t_roll_scale(roll_scale),\n\t_pitch_scale(pitch_scale),\n\t_yaw_scale(yaw_scale),\n\t_idle_speed(-1.0f + idle_speed * 2.0f),\t\/* shift to output range here to avoid runtime calculation *\/\n\t_limits_pub(),\n\t_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),\n\t_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])\n{\n}\n\nMultirotorMixer::~MultirotorMixer()\n{\n}\n\nMultirotorMixer *\nMultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)\n{\n\tMultirotorGeometry geometry;\n\tchar geomname[8];\n\tint s[4];\n\tint used;\n\n\t\/* enforce that the mixer ends with space or a new line *\/\n\tfor (int i = buflen - 1; i >= 0; i--) {\n\t\tif (buf[i] == '\\0')\n\t\t\tcontinue;\n\n\t\t\/* require a space or newline at the end of the buffer, fail on printable chars *\/\n\t\tif (buf[i] == ' ' || buf[i] == '\\n' || buf[i] == '\\r') {\n\t\t\t\/* found a line ending or space, so no split symbols \/ numbers. good. *\/\n\t\t\tbreak;\n\t\t} else {\n\t\t\tdebug(\"simple parser rejected: No newline \/ space at end of buf. (#%d\/%d: 0x%02x)\", i, buflen-1, buf[i]);\n\t\t\treturn nullptr;\n\t\t}\n\n\t}\n\n\tif (sscanf(buf, \"R: %s %d %d %d %d%n\", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {\n\t\tdebug(\"multirotor parse failed on '%s'\", buf);\n\t\treturn nullptr;\n\t}\n\n\tif (used > (int)buflen) {\n\t\tdebug(\"OVERFLOW: multirotor spec used %d of %u\", used, buflen);\n\t\treturn nullptr;\n\t}\n\n\tbuf = skipline(buf, buflen);\n\tif (buf == nullptr) {\n\t\tdebug(\"no line ending, line is incomplete\");\n\t\treturn nullptr;\n\t}\n\n\tdebug(\"remaining in buf: %d, first char: %c\", buflen, buf[0]);\n\n\tif (!strcmp(geomname, \"4+\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_PLUS;\n\n\t} else if (!strcmp(geomname, \"4x\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_X;\n\n\t} else if (!strcmp(geomname, \"4v\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_V;\n\n\t} else if (!strcmp(geomname, \"4w\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_WIDE;\n\n\t} else if (!strcmp(geomname, \"4dc\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_DEADCAT;\n\n\t} else if (!strcmp(geomname, \"6+\")) {\n\t\tgeometry = MultirotorGeometry::HEX_PLUS;\n\n\t} else if (!strcmp(geomname, \"6x\")) {\n\t\tgeometry = MultirotorGeometry::HEX_X;\n\n\t} else if (!strcmp(geomname, \"6c\")) {\n\t\tgeometry = MultirotorGeometry::HEX_COX;\n\n\t} else if (!strcmp(geomname, \"8+\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_PLUS;\n\n\t} else if (!strcmp(geomname, \"8x\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_X;\n\t\t\n\t} else if (!strcmp(geomname, \"8c\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_COX;\n\n\t} else if (!strcmp(geomname, \"2-\")) {\n\t\tgeometry = MultirotorGeometry::TWIN_ENGINE;\n\n\t} else if (!strcmp(geomname, \"3y\")) {\n\t\tgeometry = MultirotorGeometry::TRI_Y;\n\n\t} else {\n\t\tdebug(\"unrecognised geometry '%s'\", geomname);\n\t\treturn nullptr;\n\t}\n\n\tdebug(\"adding multirotor mixer '%s'\", geomname);\n\n\treturn new MultirotorMixer(\n\t\t control_cb,\n\t\t cb_handle,\n\t\t geometry,\n\t\t s[0] \/ 10000.0f,\n\t\t s[1] \/ 10000.0f,\n\t\t s[2] \/ 10000.0f,\n\t\t s[3] \/ 10000.0f);\n}\n\nunsigned\nMultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)\n{\n\tfloat\t\troll = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);\n\t\/\/lowsyslog(\"roll: %d, get_control0: %d, %d\\n\", (int)(roll), (int)(get_control(0, 0)), (int)(_roll_scale));\n\tfloat\t\tpitch = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);\n\tfloat\t\tyaw = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);\n\tfloat\t\tthrust = constrain(get_control(0, 3), 0.0f, 1.0f);\n\t\/\/lowsyslog(\"thrust: %d, get_control3: %d\\n\", (int)(thrust), (int)(get_control(0, 3)));\n\tfloat\t\tmin_out = 0.0f;\n\tfloat\t\tmax_out = 0.0f;\n\n\tif (status_reg != NULL) {\n\t\t(*status_reg) = 0;\n\t}\n\n\t\/* perform initial mix pass yielding unbounded outputs, ignore yaw *\/\n\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\tfloat out = roll * _rotors[i].roll_scale +\n\t\t\t pitch * _rotors[i].pitch_scale +\n\t\t\t thrust;\n\n\t\tout *= _rotors[i].out_scale;\n\n\t\t\/* limit yaw if it causes outputs clipping *\/\n\t\tif (out >= 0.0f && out < -yaw * _rotors[i].yaw_scale) {\n\t\t\tyaw = -out \/ _rotors[i].yaw_scale;\n\t\t\tif(status_reg != NULL) {\n\t\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;\n\t\t\t}\n\t\t}\n\n\t\t\/* calculate min and max output values *\/\n\t\tif (out < min_out) {\n\t\t\tmin_out = out;\n\t\t}\n\t\tif (out > max_out) {\n\t\t\tmax_out = out;\n\t\t}\n\n\t\toutputs[i] = out;\n\t}\n\n\t\/* scale down roll\/pitch controls if some outputs are negative, don't add yaw, keep total thrust *\/\n\tif (min_out < 0.0f) {\n\t\tfloat scale_in = thrust \/ (thrust - min_out);\n\n\t\tmax_out = 0.0f;\n\n\t\t\/* mix again with adjusted controls *\/\n\t\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\t\tfloat out = scale_in * (roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) + thrust;\n\n\t\t\t\/* update max output value *\/\n\t\t\tif (out > max_out) {\n\t\t\t\tmax_out = out;\n\t\t\t}\n\n\t\t\toutputs[i] = out;\n\t\t}\n\n\t\tif(status_reg != NULL) {\n\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;\n\t\t}\n\n\t} else {\n\t\t\/* roll\/pitch mixed without lower side limiting, add yaw control *\/\n\t\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\t\toutputs[i] += yaw * _rotors[i].yaw_scale;\n\t\t}\n\t}\n\n\t\/* scale down all outputs if some outputs are too large, reduce total thrust *\/\n\tfloat scale_out;\n\tif (max_out > 1.0f) {\n\t\tscale_out = 1.0f \/ max_out;\n\n\t\tif(status_reg != NULL) {\n\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;\n\t\t}\n\n\t} else {\n\t\tscale_out = 1.0f;\n\t}\n\n\t\/* scale outputs to range _idle_speed..1, and do final limiting *\/\n\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\toutputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed) * scale_out), _idle_speed, 1.0f);\n\t}\n\n\treturn _rotor_count;\n}\n\nvoid\nMultirotorMixer::groups_required(uint32_t &groups)\n{\n\t\/* XXX for now, hardcoded to indexes 0-3 in control group zero *\/\n\tgroups |= (1 << 0);\n}\n\nimplemented new mixer strategy\/****************************************************************************\n *\n * Copyright (C) 2012 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file mixer_multirotor.cpp\n *\n * Multi-rotor mixers.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"mixer.h\"\n\n\/\/ This file is generated by the multi_tables script which is invoked during the build process\n#include \"mixer_multirotor.generated.h\"\n\n#define debug(fmt, args...)\tdo { } while(0)\n\/\/#define debug(fmt, args...)\tdo { printf(\"[mixer] \" fmt \"\\n\", ##args); } while(0)\n\/\/#include \n\/\/#define debug(fmt, args...)\tlowsyslog(fmt \"\\n\", ##args)\n\n\/*\n * Clockwise: 1\n * Counter-clockwise: -1\n *\/\n\nnamespace\n{\n\nfloat constrain(float val, float min, float max)\n{\n\treturn (val < min) ? min : ((val > max) ? max : val);\n}\n\n} \/\/ anonymous namespace\n\nMultirotorMixer::MultirotorMixer(ControlCallback control_cb,\n\t\t\t\t uintptr_t cb_handle,\n\t\t\t\t MultirotorGeometry geometry,\n\t\t\t\t float roll_scale,\n\t\t\t\t float pitch_scale,\n\t\t\t\t float yaw_scale,\n\t\t\t\t float idle_speed) :\n\tMixer(control_cb, cb_handle),\n\t_roll_scale(roll_scale),\n\t_pitch_scale(pitch_scale),\n\t_yaw_scale(yaw_scale),\n\t_idle_speed(-1.0f + idle_speed * 2.0f),\t\/* shift to output range here to avoid runtime calculation *\/\n\t_limits_pub(),\n\t_rotor_count(_config_rotor_count[(MultirotorGeometryUnderlyingType)geometry]),\n\t_rotors(_config_index[(MultirotorGeometryUnderlyingType)geometry])\n{\n}\n\nMultirotorMixer::~MultirotorMixer()\n{\n}\n\nMultirotorMixer *\nMultirotorMixer::from_text(Mixer::ControlCallback control_cb, uintptr_t cb_handle, const char *buf, unsigned &buflen)\n{\n\tMultirotorGeometry geometry;\n\tchar geomname[8];\n\tint s[4];\n\tint used;\n\n\t\/* enforce that the mixer ends with space or a new line *\/\n\tfor (int i = buflen - 1; i >= 0; i--) {\n\t\tif (buf[i] == '\\0')\n\t\t\tcontinue;\n\n\t\t\/* require a space or newline at the end of the buffer, fail on printable chars *\/\n\t\tif (buf[i] == ' ' || buf[i] == '\\n' || buf[i] == '\\r') {\n\t\t\t\/* found a line ending or space, so no split symbols \/ numbers. good. *\/\n\t\t\tbreak;\n\t\t} else {\n\t\t\tdebug(\"simple parser rejected: No newline \/ space at end of buf. (#%d\/%d: 0x%02x)\", i, buflen-1, buf[i]);\n\t\t\treturn nullptr;\n\t\t}\n\n\t}\n\n\tif (sscanf(buf, \"R: %s %d %d %d %d%n\", geomname, &s[0], &s[1], &s[2], &s[3], &used) != 5) {\n\t\tdebug(\"multirotor parse failed on '%s'\", buf);\n\t\treturn nullptr;\n\t}\n\n\tif (used > (int)buflen) {\n\t\tdebug(\"OVERFLOW: multirotor spec used %d of %u\", used, buflen);\n\t\treturn nullptr;\n\t}\n\n\tbuf = skipline(buf, buflen);\n\tif (buf == nullptr) {\n\t\tdebug(\"no line ending, line is incomplete\");\n\t\treturn nullptr;\n\t}\n\n\tdebug(\"remaining in buf: %d, first char: %c\", buflen, buf[0]);\n\n\tif (!strcmp(geomname, \"4+\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_PLUS;\n\n\t} else if (!strcmp(geomname, \"4x\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_X;\n\n\t} else if (!strcmp(geomname, \"4v\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_V;\n\n\t} else if (!strcmp(geomname, \"4w\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_WIDE;\n\n\t} else if (!strcmp(geomname, \"4dc\")) {\n\t\tgeometry = MultirotorGeometry::QUAD_DEADCAT;\n\n\t} else if (!strcmp(geomname, \"6+\")) {\n\t\tgeometry = MultirotorGeometry::HEX_PLUS;\n\n\t} else if (!strcmp(geomname, \"6x\")) {\n\t\tgeometry = MultirotorGeometry::HEX_X;\n\n\t} else if (!strcmp(geomname, \"6c\")) {\n\t\tgeometry = MultirotorGeometry::HEX_COX;\n\n\t} else if (!strcmp(geomname, \"8+\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_PLUS;\n\n\t} else if (!strcmp(geomname, \"8x\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_X;\n\t\t\n\t} else if (!strcmp(geomname, \"8c\")) {\n\t\tgeometry = MultirotorGeometry::OCTA_COX;\n\n\t} else if (!strcmp(geomname, \"2-\")) {\n\t\tgeometry = MultirotorGeometry::TWIN_ENGINE;\n\n\t} else if (!strcmp(geomname, \"3y\")) {\n\t\tgeometry = MultirotorGeometry::TRI_Y;\n\n\t} else {\n\t\tdebug(\"unrecognised geometry '%s'\", geomname);\n\t\treturn nullptr;\n\t}\n\n\tdebug(\"adding multirotor mixer '%s'\", geomname);\n\n\treturn new MultirotorMixer(\n\t\t control_cb,\n\t\t cb_handle,\n\t\t geometry,\n\t\t s[0] \/ 10000.0f,\n\t\t s[1] \/ 10000.0f,\n\t\t s[2] \/ 10000.0f,\n\t\t s[3] \/ 10000.0f);\n}\n\nunsigned\nMultirotorMixer::mix(float *outputs, unsigned space, uint16_t *status_reg)\n{\n\t\/* Summary of mixing strategy:\n\t1) mix roll, pitch and thrust without yaw.\n\t2) if some outputs violate range [0,1] then try to shift all outputs to minimize violation ->\n\t\tincrease or decrease total thrust (boost). The total increase or decrease of thrust is limited\n\t\t(max_thrust_diff). If after the shift some outputs still violate the bounds then scale roll & pitch.\n\t\tIn case there is violation at the lower and upper bound then try to shift such that violation is equal\n\t\ton both sides.\n\t3) mix in yaw and scale if it leads to limit violation.\n\t4) scale all outputs to range [idle_speed,1]\n\t*\/\n\n\tfloat\t\troll = constrain(get_control(0, 0) * _roll_scale, -1.0f, 1.0f);\n\tfloat\t\tpitch = constrain(get_control(0, 1) * _pitch_scale, -1.0f, 1.0f);\n\tfloat\t\tyaw = constrain(get_control(0, 2) * _yaw_scale, -1.0f, 1.0f);\n\tfloat\t\tthrust = constrain(get_control(0, 3), 0.0f, 1.0f);\n\tfloat\t\tmin_out = 0.0f;\n\tfloat\t\tmax_out = 0.0f;\n\n\t\/\/ clean register for saturation status flags\n\tif (status_reg != NULL) {\n\t\t(*status_reg) = 0;\n\t}\n\t\/\/ thrust boost parameters\n\tfloat thrust_increase_factor = 1.5f;\n\tfloat thrust_decrease_factor = 0.6f;\n\n\t\/* perform initial mix pass yielding unbounded outputs, ignore yaw *\/\n\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\tfloat out = roll * _rotors[i].roll_scale +\n\t\t\t pitch * _rotors[i].pitch_scale +\n\t\t\t thrust;\n\n\t\tout *= _rotors[i].out_scale;\n\n\t\t\/* calculate min and max output values *\/\n\t\tif (out < min_out) {\n\t\t\tmin_out = out;\n\t\t}\n\t\tif (out > max_out) {\n\t\t\tmax_out = out;\n\t\t}\n\n\t\toutputs[i] = out;\n\t}\n\n\tfloat boost = 0.0f;\t\t\t\t\/\/ value added to demanded thrust (can also be negative)\n\tfloat roll_pitch_scale = 1.0f;\t\/\/ scale for demanded roll and pitch\n\n\tif(min_out < 0.0f && max_out < 1.0f && -min_out <= 1.0f - max_out) {\n\t\tfloat max_thrust_diff = thrust * thrust_increase_factor - thrust;\n\t\tif(max_thrust_diff >= -min_out) {\n\t\t\tboost = -min_out;\n\t\t}\n\t\telse {\n\t\t\tboost = max_thrust_diff;\n\t\t\troll_pitch_scale = (thrust + boost)\/(thrust - min_out);\n\t\t}\n\t}\n\telse if (max_out > 1.0f && min_out > 0.0f && min_out >= max_out - 1.0f) {\n\t\tfloat max_thrust_diff = thrust - thrust_decrease_factor*thrust;\n\t\tif(max_thrust_diff >= max_out - 1.0f) {\n\t\t\tboost = -(max_out - 1.0f);\n\t\t} else {\n\t\t\tboost = -max_thrust_diff;\n\t\t\troll_pitch_scale = (1 - (thrust + boost))\/(max_out - thrust);\n\t\t}\n\t}\n\telse if (min_out < 0.0f && max_out < 1.0f && -min_out > 1.0f - max_out) {\n\t\tfloat max_thrust_diff = thrust * thrust_increase_factor - thrust;\n\t\tboost = constrain(-min_out - (1.0f - max_out)\/2.0f,0.0f, max_thrust_diff);\n\t\troll_pitch_scale = (thrust + boost)\/(thrust - min_out);\n\t}\n\telse if (max_out > 1.0f && min_out > 0.0f && min_out < max_out - 1.0f ) {\n\t\tfloat max_thrust_diff = thrust - thrust_decrease_factor*thrust;\n\t\tboost = constrain(-(max_out - 1.0f - min_out)\/2.0f, -max_thrust_diff, 0.0f);\n\t\troll_pitch_scale = (1 - (thrust + boost))\/(max_out - thrust);\n\t}\n\telse if (min_out < 0.0f && max_out > 1.0f) {\n\t\tboost = constrain(-(max_out - 1.0f + min_out)\/2.0f, thrust_decrease_factor*thrust - thrust, thrust_increase_factor*thrust - thrust);\n\t\troll_pitch_scale = (thrust + boost)\/(thrust - min_out);\n\t}\n\n\t\/\/ notify if saturation has occurred\n\tif(min_out < 0.0f) {\n\t\tif(status_reg != NULL) {\n\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_LOWER_LIMIT;\n\t\t}\n\t}\n\tif(max_out > 0.0f) {\n\t\tif(status_reg != NULL) {\n\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_UPPER_LIMIT;\n\t\t}\n\t}\n\n\t\/\/ mix again but now with thrust boost, scale roll\/pitch and also add yaw\n\tfor(unsigned i = 0; i < _rotor_count; i++) {\n\t\tfloat out = (roll * _rotors[i].roll_scale +\n\t\t\t pitch * _rotors[i].pitch_scale) * roll_pitch_scale +\n\t\t\t\tyaw * _rotors[i].yaw_scale +\n\t\t\t thrust + boost;\n\n\t\tout *= _rotors[i].out_scale;\n\n\t\t\/\/ scale yaw if it violates limits. inform about yaw limit reached\n\t\tif(out < 0.0f) {\n\t\t\tyaw = -((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *\n\t\t\t\troll_pitch_scale + thrust + boost)\/_rotors[i].yaw_scale;\n\t\t\tif(status_reg != NULL) {\n\t\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;\n\t\t\t}\n\t\t}\n\t\telse if(out > 1.0f) {\n\t\t\tyaw = (1.0f - ((roll * _rotors[i].roll_scale + pitch * _rotors[i].pitch_scale) *\n\t\t\t\troll_pitch_scale + thrust + boost))\/_rotors[i].yaw_scale;\n\t\t\tif(status_reg != NULL) {\n\t\t\t\t(*status_reg) |= PX4IO_P_STATUS_MIXER_YAW_LIMIT;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* last mix, add yaw and scale outputs to range idle_speed...1 *\/\n\tfor (unsigned i = 0; i < _rotor_count; i++) {\n\t\toutputs[i] = (roll * _rotors[i].roll_scale +\n\t\t\t pitch * _rotors[i].pitch_scale) * roll_pitch_scale +\n\t\t\t\tyaw * _rotors[i].yaw_scale +\n\t\t\t thrust + boost;\n\n\t\toutputs[i] = constrain(_idle_speed + (outputs[i] * (1.0f - _idle_speed)), _idle_speed, 1.0f);\n\t}\n\n\treturn _rotor_count;\n}\n\nvoid\nMultirotorMixer::groups_required(uint32_t &groups)\n{\n\t\/* XXX for now, hardcoded to indexes 0-3 in control group zero *\/\n\tgroups |= (1 << 0);\n}\n\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n\n#include \"logging\/logging_tests_util.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Logging Test \n\/\/===--------------------------------------------------------------------===\/\/\n\nstd::string aries_log_file_name = \"aries.log\";\n\n\/**\n * @brief writing a simple log with multiple threads\n *\/\nTEST(AriesLoggingTest, writing_logfile) {\n\n std::ifstream log_file(aries_log_file_name.c_str());\n\n \/\/ Reset the log file if exists\n if( log_file.good() ){\n EXPECT_TRUE(std::remove(aries_log_file_name.c_str()) == 0 );\n }\n\n \/\/ Prepare a simple log file\n if( LoggingTestsUtil::PrepareLogFile(LOGGING_TYPE_ARIES) == true){\n }else{\n LOG_ERROR(\"Could not prepare log file\");\n }\n}\n\n\/**\n * @brief recovery test\n *\/\nTEST(AriesLoggingTest, recovery) {\n\n std::ifstream log_file(aries_log_file_name.c_str());\n\n \/\/ Do recovery if the log file exists\n if( log_file.good() ){\n LoggingTestsUtil::CheckAriesRecovery();\n }else{\n LOG_ERROR(\"Could not check recovery\");\n }\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\nTemporary fix for aries logging test#include \"gtest\/gtest.h\"\n\n#include \"logging\/logging_tests_util.h\"\n#include \"backend\/common\/logger.h\"\n\n#include \n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Logging Test \n\/\/===--------------------------------------------------------------------===\/\/\n\nstd::string aries_log_file_name = \"aries.log\";\n\n\/**\n * @brief writing a simple log with multiple threads\n *\/\nTEST(AriesLoggingTest, writing_logfile) {\n\n std::ifstream log_file(aries_log_file_name.c_str());\n\n \/\/ Reset the log file if exists\n if( log_file.good() ){\n EXPECT_TRUE(std::remove(aries_log_file_name.c_str()) == 0 );\n }\n\n \/* TODO: Fix this infinite sleep\n \/\/ Prepare a simple log file\n if( LoggingTestsUtil::PrepareLogFile(LOGGING_TYPE_ARIES) == true){\n }else{\n LOG_ERROR(\"Could not prepare log file\");\n }\n *\/\n}\n\n\/**\n * @brief recovery test\n *\/\nTEST(AriesLoggingTest, recovery) {\n\n std::ifstream log_file(aries_log_file_name.c_str());\n\n \/\/ Do recovery if the log file exists\n if( log_file.good() ){\n LoggingTestsUtil::CheckAriesRecovery();\n }else{\n LOG_ERROR(\"Could not check recovery\");\n }\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"\/\/ $Id: petsc_nonlinear_solver.C,v 1.7 2005-02-02 20:51:17 benkirk Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"libmesh_common.h\"\n\n#ifdef HAVE_PETSC\n\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"petsc_nonlinear_solver.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_matrix.h\"\n\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/ \n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n# if (((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)) || \\\n ((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1)))\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n \n \/\/-------------------------------------------------------------------\n \/\/ this function is called by PETSc at the end of each nonlinear step \n PetscErrorCode\n __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)\n {\n \/\/int ierr=0;\n \n std::cout << \" NL conv: step \" << its\n\t << std::scientific\n\t \/\/<< \", |u|_oo = \" << 0\n\t << \", |resid|_2 = \" << fnorm\n << std::endl;\n\n \/\/return ierr;\n return 0;\n }\n\n\n\n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the residual at X\n PetscErrorCode\n __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)\n {\n int ierr=0;\n\n assert (x != NULL);\n assert (r != NULL);\n assert (ctx != NULL);\n \n PetscNonlinearSolver* solver =\n static_cast*> (ctx);\n \n PetscVector X_global(x), R(r);\n PetscVector X_local(X_global.size());\n\n X_global.localize (X_local);\n \n if (solver->residual != NULL) solver->residual (X_local, R);\n if (solver->matvec != NULL) solver->matvec (X_local, &R, NULL);\n\n R.close();\n \n\/\/ std::cout << \"X.size()=\" << X_global.size()\n\/\/ \t << \", R.size()=\" << R.size()\n\/\/ \t << std::endl;\n \n return ierr;\n }\n\n\n \n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the Jacobian at X\n PetscErrorCode\n __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)\n {\n int ierr=0;\n \n assert (ctx != NULL);\n \n PetscNonlinearSolver* solver =\n static_cast*> (ctx);\n \n PetscMatrix PC(*pc);\n PetscMatrix Jac(*jac);\n PetscVector X_global(x);\n PetscVector X_local (X_global.size());\n\n X_global.localize (X_local);\n\n if (solver->jacobian != NULL) solver->jacobian (X_local, PC);\n if (solver->matvec != NULL) solver->matvec (X_local, NULL, &PC);\n \n PC.close();\n Jac.close();\n \n *msflag = SAME_NONZERO_PATTERN;\n \n\/\/ here();\n \n\/\/ std::cout << \"X.size()=\" << X_global.size()\n\/\/ \t << std::endl;\n \n return ierr;\n }\n \n} \/\/ end extern \"C\"\n\/\/---------------------------------------------------------------------\n\n\n\n\/\/---------------------------------------------------------------------\n\/\/ PetscNonlinearSolver<> methods\ntemplate \nvoid PetscNonlinearSolver::clear ()\n{\n if (this->initialized())\n {\n this->_is_initialized = false;\n\n int ierr=0;\n\n ierr = SNESDestroy(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate \nvoid PetscNonlinearSolver::init ()\n{ \n \/\/ Initialize the data structures if not done so already.\n if (!this->initialized())\n {\n this->_is_initialized = true;\n \n int ierr=0;\n \n ierr = SNESCreate(PETSC_COMM_WORLD,&_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate \nstd::pair \nPetscNonlinearSolver::solve (SparseMatrix& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\tNumericVector& x_in, \/\/ Solution vector\n\t\t\t\tNumericVector& r_in, \/\/ Residual vector\n\t\t\t\tconst double, \/\/ Stopping tolerance\n\t\t\t\tconst unsigned int) \n{\n \/\/this->init ();\n\n\/\/ std::cout << \"x.size()=\" << x_in.size()\n\/\/ \t << \", r.size()=\" << r_in.size()\n\/\/ \t << std::endl;\n \n PetscMatrix* jac = dynamic_cast*>(&jac_in);\n PetscVector* x = dynamic_cast*>(&x_in);\n PetscVector* r = dynamic_cast*>(&r_in);\n\n \/\/ We cast to pointers so we can be sure that they succeeded\n \/\/ by comparing the result against NULL.\n assert(jac != NULL); assert(jac->mat() != NULL);\n assert(x != NULL); assert(x->vec() != NULL);\n assert(r != NULL); assert(r->vec() != NULL);\n \n int ierr=0;\n int n_iterations =0;\n\n \/\/Mat A = jac->mat();\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n \/\/ Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,\n \/\/ the last one being a pointer to an int to hold the number of iterations required.\n# if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1)\n ierr = SNESSolve (_snes, x->vec(), &n_iterations);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n#else \t \n ierr = SNESSolve (_snes, x->vec());\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n#endif\n\n\/\/ if (A != jac->mat())\n\/\/ {\n\/\/ ierr = MatDestroy(A);\n\/\/ CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\/\/ }\n \t \n ierr = SNESDestroy(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n \/\/ return the # of its. and the final residual norm. Note that\n \/\/ n_iterations may be zero for PETSc versions 2.2.x and greater.\n return std::make_pair(n_iterations, 0.);\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscNonlinearSolver;\n \n\n\n#endif \/\/ #ifdef HAVE_PETSC\ncode cleanup\/\/ $Id: petsc_nonlinear_solver.C,v 1.8 2005-02-04 13:36:39 benkirk Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"libmesh_common.h\"\n\n#ifdef HAVE_PETSC\n\n\n\/\/ C++ includes\n\n\/\/ Local Includes\n#include \"petsc_nonlinear_solver.h\"\n#include \"petsc_vector.h\"\n#include \"petsc_matrix.h\"\n\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Functions with C linkage to pass to PETSc. PETSc will call these\n\/\/ methods as needed.\n\/\/ \n\/\/ Since they must have C linkage they have no knowledge of a namespace.\n\/\/ Give them an obscure name to avoid namespace pollution.\nextern \"C\"\n{\n \/\/ Older versions of PETSc do not have the different int typedefs.\n \/\/ On 64-bit machines, PetscInt may actually be a long long int.\n \/\/ This change occurred in Petsc-2.2.1.\n# if (((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)) || \\\n ((PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1)))\n typedef int PetscErrorCode;\n typedef int PetscInt;\n#endif\n \n \/\/-------------------------------------------------------------------\n \/\/ this function is called by PETSc at the end of each nonlinear step \n PetscErrorCode\n __libmesh_petsc_snes_monitor (SNES, PetscInt its, PetscReal fnorm, void *)\n {\n \/\/int ierr=0;\n\n if (its > 0)\n std::cout << \" NL step \" << its\n\t\t<< std::scientific\n\t\t<< \", |residual|_2 = \" << fnorm\n\t\t<< std::endl;\n\n \/\/return ierr;\n return 0;\n }\n\n\n\n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the residual at X\n PetscErrorCode\n __libmesh_petsc_snes_residual (SNES, Vec x, Vec r, void *ctx)\n {\n int ierr=0;\n\n assert (x != NULL);\n assert (r != NULL);\n assert (ctx != NULL);\n \n PetscNonlinearSolver* solver =\n static_cast*> (ctx);\n \n PetscVector X_global(x), R(r);\n PetscVector X_local(X_global.size());\n\n X_global.localize (X_local);\n \n if (solver->residual != NULL) solver->residual (X_local, R);\n if (solver->matvec != NULL) solver->matvec (X_local, &R, NULL);\n\n R.close();\n \n return ierr;\n }\n\n\n \n \/\/---------------------------------------------------------------\n \/\/ this function is called by PETSc to evaluate the Jacobian at X\n PetscErrorCode\n __libmesh_petsc_snes_jacobian (SNES, Vec x, Mat *jac, Mat *pc, MatStructure *msflag, void *ctx)\n {\n int ierr=0;\n \n assert (ctx != NULL);\n \n PetscNonlinearSolver* solver =\n static_cast*> (ctx);\n \n PetscMatrix PC(*pc);\n PetscMatrix Jac(*jac);\n PetscVector X_global(x);\n PetscVector X_local (X_global.size());\n\n X_global.localize (X_local);\n\n if (solver->jacobian != NULL) solver->jacobian (X_local, PC);\n if (solver->matvec != NULL) solver->matvec (X_local, NULL, &PC);\n \n PC.close();\n Jac.close();\n \n *msflag = SAME_NONZERO_PATTERN;\n \n return ierr;\n }\n \n} \/\/ end extern \"C\"\n\/\/---------------------------------------------------------------------\n\n\n\n\/\/---------------------------------------------------------------------\n\/\/ PetscNonlinearSolver<> methods\ntemplate \nvoid PetscNonlinearSolver::clear ()\n{\n if (this->initialized())\n {\n this->_is_initialized = false;\n\n int ierr=0;\n\n ierr = SNESDestroy(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate \nvoid PetscNonlinearSolver::init ()\n{ \n \/\/ Initialize the data structures if not done so already.\n if (!this->initialized())\n {\n this->_is_initialized = true;\n \n int ierr=0;\n \n ierr = SNESCreate(PETSC_COMM_WORLD,&_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n }\n}\n\n\n\ntemplate \nstd::pair \nPetscNonlinearSolver::solve (SparseMatrix& jac_in, \/\/ System Jacobian Matrix\n\t\t\t\tNumericVector& x_in, \/\/ Solution vector\n\t\t\t\tNumericVector& r_in, \/\/ Residual vector\n\t\t\t\tconst double, \/\/ Stopping tolerance\n\t\t\t\tconst unsigned int) \n{\n \/\/this->init ();\n\n\/\/ std::cout << \"x.size()=\" << x_in.size()\n\/\/ \t << \", r.size()=\" << r_in.size()\n\/\/ \t << std::endl;\n \n PetscMatrix* jac = dynamic_cast*>(&jac_in);\n PetscVector* x = dynamic_cast*>(&x_in);\n PetscVector* r = dynamic_cast*>(&r_in);\n\n \/\/ We cast to pointers so we can be sure that they succeeded\n \/\/ by comparing the result against NULL.\n assert(jac != NULL); assert(jac->mat() != NULL);\n assert(x != NULL); assert(x->vec() != NULL);\n assert(r != NULL); assert(r->vec() != NULL);\n \n int ierr=0;\n int n_iterations =0;\n\n \/\/Mat A = jac->mat();\n\n ierr = SNESCreate(PETSC_COMM_WORLD,&_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetMonitor (_snes, __libmesh_petsc_snes_monitor,\n\t\t\t this, PETSC_NULL);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetFunction (_snes, r->vec(), __libmesh_petsc_snes_residual, this);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n ierr = SNESSetJacobian (_snes, jac->mat(), jac->mat(), __libmesh_petsc_snes_jacobian, this);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n ierr = SNESSetFromOptions(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\n \/\/ Older versions (at least up to 2.1.5) of SNESSolve took 3 arguments,\n \/\/ the last one being a pointer to an int to hold the number of iterations required.\n# if (PETSC_VERSION_MAJOR == 2) && (PETSC_VERSION_MINOR <= 1)\n ierr = SNESSolve (_snes, x->vec(), &n_iterations);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n#else \t \n ierr = SNESSolve (_snes, x->vec());\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n#endif\n\n\/\/ if (A != jac->mat())\n\/\/ {\n\/\/ ierr = MatDestroy(A);\n\/\/ CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\/\/ }\n \t \n ierr = SNESDestroy(_snes);\n CHKERRABORT(PETSC_COMM_WORLD,ierr);\n\t \n \/\/ return the # of its. and the final residual norm. Note that\n \/\/ n_iterations may be zero for PETSc versions 2.2.x and greater.\n return std::make_pair(n_iterations, 0.);\n}\n\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class PetscNonlinearSolver;\n \n\n\n#endif \/\/ #ifdef HAVE_PETSC\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Kaveh Vahedipour\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"FailedLeader.h\"\n\n#include \"Agency\/Agent.h\"\n#include \"Agency\/Job.h\"\n#include \"Agency\/JobContext.h\"\n\n#include \n#include \n\nusing namespace arangodb::consensus;\n\nFailedLeader::FailedLeader(Node const& snapshot, AgentInterface* agent,\n std::string const& jobId, std::string const& creator,\n std::string const& database,\n std::string const& collection,\n std::string const& shard, std::string const& from)\n : Job(NOTFOUND, snapshot, agent, jobId, creator), _database(database),\n _collection(collection), _shard(shard), _from(from) {}\n\nFailedLeader::FailedLeader(\n Node const& snapshot, AgentInterface* agent, JOB_STATUS status,\n std::string const& jobId) : Job(status, snapshot, agent, jobId) {\n \n \/\/ Get job details from agency:\n try {\n std::string path = pos[status] + _jobId + \"\/\";\n _database = _snapshot(path + \"database\").getString();\n _collection = _snapshot(path + \"collection\").getString();\n _from = _snapshot(path + \"fromServer\").getString();\n try {\n \/\/ set only if already started\n _to = _snapshot(path + \"toServer\").getString();\n } catch (...) {}\n _shard = _snapshot(path + \"shard\").getString();\n _creator = _snapshot(path + \"creator\").getString();\n _created = stringToTimepoint(_snapshot(path + \"timeCreated\").getString());\n } catch (std::exception const& e) {\n std::stringstream err;\n err << \"Failed to find job \" << _jobId << \" in agency: \" << e.what();\n LOG_TOPIC(ERR, Logger::SUPERVISION) << err.str();\n finish(\"\", _shard, false, err.str());\n _status = FAILED;\n }\n \n}\n\nFailedLeader::~FailedLeader() {}\n\nvoid FailedLeader::run() {\n runHelper(\"\", _shard);\n}\n\nvoid FailedLeader::rollback() {\n\n \/\/ Create new plan servers (exchange _to and _from)\n std::string planPath\n = planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n auto const& planned = _snapshot(planPath).slice();\n\n VPackBuilder rb;\n if (!_to.empty()) {\n { VPackArrayBuilder r(&rb);\n for (auto const i : VPackArrayIterator(planned)) {\n TRI_ASSERT(i.isString());\n auto istr = i.copyString();\n if (istr == _from) {\n rb.add(VPackValue(_to));\n } else if (istr == _to) {\n rb.add(VPackValue(_from));\n } else {\n rb.add(i);\n }\n }\n }\n } else {\n rb.add(planned);\n }\n \n auto cs = clones(_snapshot, _database, _collection, _shard);\n \n \/\/ Transactions\n auto payload = std::make_shared();\n { VPackObjectBuilder b(payload.get());\n for (auto const c : cs) {\n payload->add(planColPrefix + _database + \"\/\" + c.collection + \"\/shards\/\" +\n c.shard, rb.slice());\n }\n }\n\n finish(\"\", _shard, false, \"Timed out.\", payload);\n \n}\n\n\nbool FailedLeader::create(std::shared_ptr b) {\n\n using namespace std::chrono;\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Create failedLeader for \" + _shard + \" from \" + _from;\n \n _jb = std::make_shared();\n { VPackArrayBuilder transaction(_jb.get());\n { VPackObjectBuilder operations(_jb.get());\n \/\/ Todo entry\n _jb->add(VPackValue(toDoPrefix + _jobId));\n { VPackObjectBuilder todo(_jb.get());\n _jb->add(\"creator\", VPackValue(_creator));\n _jb->add(\"type\", VPackValue(\"failedLeader\"));\n _jb->add(\"database\", VPackValue(_database));\n _jb->add(\"collection\", VPackValue(_collection));\n _jb->add(\"shard\", VPackValue(_shard));\n _jb->add(\"fromServer\", VPackValue(_from));\n _jb->add(\"jobId\", VPackValue(_jobId));\n _jb->add(\n \"timeCreated\", VPackValue(timepointToString(system_clock::now())));\n }}}\n write_ret_t res = singleWriteTransaction(_agent, *_jb); \n return (res.accepted && res.indices.size() == 1 && res.indices[0]);\n \n}\n\n\nbool FailedLeader::start() {\n\n std::vector existing =\n _snapshot.exists(planColPrefix + _database + \"\/\" + _collection + \"\/\" +\n \"distributeShardsLike\");\n \n \/\/ Fail if got distributeShardsLike\n if (existing.size() == 5) {\n finish(\"\", _shard, false, \"Collection has distributeShardsLike\");\n return false;\n }\n \/\/ Fail if collection gone\n else if (existing.size() < 4) { \n finish(\"\", _shard, true, \"Collection \" + _collection + \" gone\");\n return false;\n }\n\n \/\/ Get healthy in Sync follower common to all prototype + clones\n auto commonHealthyInSync =\n findNonblockedCommonHealthyInSyncFollower(\n _snapshot, _database, _collection, _shard);\n if (commonHealthyInSync.empty()) {\n return false;\n } else {\n _to = commonHealthyInSync;\n }\n \n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Start failedLeader for \" + _shard + \" from \" + _from + \" to \" + _to; \n \n using namespace std::chrono;\n\n \/\/ Current servers vector\n auto const& current =\n _snapshot(\n curColPrefix + _database + \"\/\" + _collection + \"\/\" + _shard + \"\/servers\")\n .slice();\n \/\/ Planned servers vector\n std::string planPath\n = planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n auto const& planned = _snapshot(planPath).slice();\n\n \/\/ Get todo entry\n Builder todo;\n { VPackArrayBuilder t(&todo);\n if (_jb == nullptr) {\n try {\n _snapshot(toDoPrefix + _jobId).toBuilder(todo);\n } catch (std::exception const&) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Failed to get key \" + toDoPrefix + _jobId\n + \" from agency snapshot\";\n return false;\n }\n } else {\n todo.add(_jb->slice()[0].get(toDoPrefix + _jobId));\n }}\n\n \/\/ New plan vector excluding _to and _from\n std::vector planv;\n for (auto const& i : VPackArrayIterator(planned)) {\n auto s = i.copyString();\n if (s != _from && s != _to) {\n planv.push_back(s);\n }\n }\n\n \/\/ Additional follower, if applicable\n auto additionalFollower = randomIdleGoodAvailableServer(_snapshot, planned);\n if (!additionalFollower.empty()) {\n planv.push_back(additionalFollower);\n }\n\n \/\/ Transactions\n Builder pending;\n \n { VPackArrayBuilder transactions(&pending);\n { VPackArrayBuilder transaction(&pending);\n \n \/\/ Operations ----------------------------------------------------------\n { VPackObjectBuilder operations(&pending);\n \/\/ Add pending entry\n pending.add(VPackValue(pendingPrefix + _jobId));\n { VPackObjectBuilder ts(&pending);\n pending.add(\"timeStarted\", \/\/ start\n VPackValue(timepointToString(system_clock::now())));\n pending.add(\"toServer\", VPackValue(_to)); \/\/ toServer\n for (auto const& obj : VPackObjectIterator(todo.slice()[0])) {\n pending.add(obj.key.copyString(), obj.value);\n }\n }\n addRemoveJobFromSomewhere(pending, \"ToDo\", _jobId);\n \/\/ DB server vector -------\n Builder ns;\n { VPackArrayBuilder servers(&ns);\n ns.add(VPackValue(_to)); \n for (auto const& i : VPackArrayIterator(current)) {\n std::string s = i.copyString();\n if (s != _from && s != _to) {\n ns.add(i);\n planv.erase(\n std::remove(planv.begin(), planv.end(), s), planv.end());\n }\n }\n ns.add(VPackValue(_from));\n for (auto const& i : planv) {\n ns.add(VPackValue(i));\n }\n }\n for (auto const& clone :\n clones(_snapshot, _database, _collection, _shard)) {\n pending.add(\n planColPrefix + _database + \"\/\"\n + clone.collection + \"\/shards\/\" + clone.shard, ns.slice());\n }\n addBlockShard(pending, _shard, _jobId);\n addIncreasePlanVersion(pending);\n }\n \/\/ Preconditions -------------------------------------------------------\n { VPackObjectBuilder preconditions(&pending);\n \/\/ Failed condition persists\n pending.add(VPackValue(healthPrefix + _from + \"\/Status\"));\n { VPackObjectBuilder stillExists(&pending);\n pending.add(\"old\", VPackValue(\"FAILED\")); }\n \/\/ Destination server still in good condition\n addPreconditionServerGood(pending, _to);\n \/\/ Server list in plan still as before\n addPreconditionUnchanged(pending, planPath, planned);\n \/\/ Destination server should not be blocked by another job\n addPreconditionServerNotBlocked(pending, _to);\n \/\/ Shard to be handled is block by another job\n addPreconditionShardNotBlocked(pending, _shard);\n } \/\/ Preconditions -----------------------------------------------------\n }\n }\n\n \/\/ Abort job blocking server if abortable\n try {\n std::string jobId = _snapshot(blockedShardsPrefix + _shard).getString();\n if (!abortable(_snapshot, jobId)) {\n return false;\n } else {\n JobContext(PENDING, jobId, _snapshot, _agent).abort();\n }\n } catch (...) {}\n \n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader transaction: \" << pending.toJson();\n \n trans_ret_t res = generalTransaction(_agent, pending);\n \n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader result: \" << res.result->toJson();\n\n\n \/\/ Something went south. Let's see\n auto result = res.result->slice()[0];\n\n if (res.accepted && result.isNumber()) {\n return true;\n }\n\n TRI_ASSERT(result.isObject());\n\n if (!res.accepted) { \/\/ lost leadership\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Leadership lost! Job \" << _jobId << \" handed off.\";\n }\n \n if (result.isObject()) {\n\n \/\/ Still failing _from?\n auto slice = result.get(\n std::vector({\n agencyPrefix, \"Supervision\", \"Health\", _from, \"Status\"}));\n if (!slice.isString() || slice.copyString() != \"FAILED\") {\n finish(\"\", _shard, false, \"Server \" + _from + \" no longer failing.\");\n return false;\n }\n\n \/\/ Still healthy _to?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"Health\", _to, \"Status\"}));\n if (!slice.isString() || slice.copyString() != \"GOOD\") {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Will not failover from \" << _from << \" to \" << _to\n << \" as target server is no longer in good condition. Will retry.\";\n return false;\n }\n\n \/\/ Snapshot and plan still in sync with respect to server list?\n slice = result.get(\n std::vector({agencyPrefix, \"Plan\", \"Collections\", _database,\n _collection, \"shards\", _shard}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Plan no longer holds the expected server list. Will retry.\";\n }\n\n \/\/ To server blocked by other job?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"DBServers\", _to}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Destination server \" << _to << \" meanwhile is blocked by job \" <<\n slice.copyString();\n }\n\n \/\/ This shard blocked by other job?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"Shards\", _shard}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Shard \" << _shard << \" meanwhile is blocked by job \" <<\n slice.copyString();\n }\n }\n \n return false;\n \n}\n\nJOB_STATUS FailedLeader::status() {\n\n if(!_snapshot.has(planColPrefix + _database + \"\/\" + _collection)) {\n finish(\"\", _shard, true, \"Collection \" + _collection + \" gone\");\n return FINISHED;\n }\n\n \/\/ Timedout after 77 minutes\n if (std::chrono::system_clock::now() - _created > std::chrono::seconds(4620)) {\n rollback();\n }\n\n if (_status != PENDING) {\n return _status;\n }\n\n Node const& job = _snapshot(pendingPrefix + _jobId);\n std::string database = job(\"database\").toJson(),\n shard = job(\"shard\").toJson();\n \n bool done = false;\n for (auto const& clone : clones(_snapshot, _database, _collection, _shard)) {\n auto sub = database + \"\/\" + clone.collection;\n if(_snapshot(planColPrefix + sub + \"\/shards\/\" + clone.shard).slice()[0] !=\n _snapshot(curColPrefix + sub + \"\/\" + clone.shard + \"\/servers\").slice()[0]) {\n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader waiting for \" << sub + \"\/\" + shard;\n break;\n }\n done = true;\n }\n \n if (done) {\n \/\/ Remove shard to \/arango\/Target\/FailedServers\/ array\n Builder del;\n { VPackArrayBuilder a(&del);\n { VPackObjectBuilder o(&del);\n del.add(VPackValue(failedServersPrefix + \"\/\" + _from));\n { VPackObjectBuilder erase(&del);\n del.add(\"op\", VPackValue(\"erase\"));\n del.add(\"val\", VPackValue(_shard));\n }}}\n \n write_ret_t res = singleWriteTransaction(_agent, del);\n if (finish(\"\", shard)) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Finished failedLeader for \" + _shard + \" from \" + _from + \" to \" + _to; \n return FINISHED;\n }\n }\n \n return _status;\n}\n\n\narangodb::Result FailedLeader::abort() {\n \/\/ job is only abortable when it is in ToDo\n if (_status != TODO) {\n return Result(TRI_ERROR_SUPERVISION_GENERAL_FAILURE,\n \"Failed aborting failedFollower job beyond todo stage\");\n } else {\n finish(\"\", \"\", false, \"job aborted\");\n return Result();\n }\n}\n\n\nFix abort conditions of FailedLeader\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Kaveh Vahedipour\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"FailedLeader.h\"\n\n#include \"Agency\/Agent.h\"\n#include \"Agency\/Job.h\"\n#include \"Agency\/JobContext.h\"\n\n#include \n#include \n\nusing namespace arangodb::consensus;\n\nFailedLeader::FailedLeader(Node const& snapshot, AgentInterface* agent,\n std::string const& jobId, std::string const& creator,\n std::string const& database,\n std::string const& collection,\n std::string const& shard, std::string const& from)\n : Job(NOTFOUND, snapshot, agent, jobId, creator), _database(database),\n _collection(collection), _shard(shard), _from(from) {}\n\nFailedLeader::FailedLeader(\n Node const& snapshot, AgentInterface* agent, JOB_STATUS status,\n std::string const& jobId) : Job(status, snapshot, agent, jobId) {\n \n \/\/ Get job details from agency:\n try {\n std::string path = pos[status] + _jobId + \"\/\";\n _database = _snapshot(path + \"database\").getString();\n _collection = _snapshot(path + \"collection\").getString();\n _from = _snapshot(path + \"fromServer\").getString();\n try {\n \/\/ set only if already started\n _to = _snapshot(path + \"toServer\").getString();\n } catch (...) {}\n _shard = _snapshot(path + \"shard\").getString();\n _creator = _snapshot(path + \"creator\").getString();\n _created = stringToTimepoint(_snapshot(path + \"timeCreated\").getString());\n } catch (std::exception const& e) {\n std::stringstream err;\n err << \"Failed to find job \" << _jobId << \" in agency: \" << e.what();\n LOG_TOPIC(ERR, Logger::SUPERVISION) << err.str();\n finish(\"\", _shard, false, err.str());\n _status = FAILED;\n }\n \n}\n\nFailedLeader::~FailedLeader() {}\n\nvoid FailedLeader::run() {\n runHelper(\"\", _shard);\n}\n\nvoid FailedLeader::rollback() {\n\n \/\/ Create new plan servers (exchange _to and _from)\n std::string planPath\n = planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n auto const& planned = _snapshot(planPath).slice();\n\n VPackBuilder rb;\n if (!_to.empty()) {\n { VPackArrayBuilder r(&rb);\n for (auto const i : VPackArrayIterator(planned)) {\n TRI_ASSERT(i.isString());\n auto istr = i.copyString();\n if (istr == _from) {\n rb.add(VPackValue(_to));\n } else if (istr == _to) {\n rb.add(VPackValue(_from));\n } else {\n rb.add(i);\n }\n }\n }\n } else {\n rb.add(planned);\n }\n \n auto cs = clones(_snapshot, _database, _collection, _shard);\n \n \/\/ Transactions\n auto payload = std::make_shared();\n { VPackObjectBuilder b(payload.get());\n for (auto const c : cs) {\n payload->add(planColPrefix + _database + \"\/\" + c.collection + \"\/shards\/\" +\n c.shard, rb.slice());\n }\n }\n\n finish(\"\", _shard, false, \"Timed out.\", payload);\n \n}\n\n\nbool FailedLeader::create(std::shared_ptr b) {\n\n using namespace std::chrono;\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Create failedLeader for \" + _shard + \" from \" + _from;\n \n _jb = std::make_shared();\n { VPackArrayBuilder transaction(_jb.get());\n { VPackObjectBuilder operations(_jb.get());\n \/\/ Todo entry\n _jb->add(VPackValue(toDoPrefix + _jobId));\n { VPackObjectBuilder todo(_jb.get());\n _jb->add(\"creator\", VPackValue(_creator));\n _jb->add(\"type\", VPackValue(\"failedLeader\"));\n _jb->add(\"database\", VPackValue(_database));\n _jb->add(\"collection\", VPackValue(_collection));\n _jb->add(\"shard\", VPackValue(_shard));\n _jb->add(\"fromServer\", VPackValue(_from));\n _jb->add(\"jobId\", VPackValue(_jobId));\n _jb->add(\n \"timeCreated\", VPackValue(timepointToString(system_clock::now())));\n }}}\n write_ret_t res = singleWriteTransaction(_agent, *_jb); \n return (res.accepted && res.indices.size() == 1 && res.indices[0]);\n \n}\n\n\nbool FailedLeader::start() {\n\n std::vector existing =\n _snapshot.exists(planColPrefix + _database + \"\/\" + _collection + \"\/\" +\n \"distributeShardsLike\");\n \n \/\/ Fail if got distributeShardsLike\n if (existing.size() == 5) {\n finish(\"\", _shard, false, \"Collection has distributeShardsLike\");\n return false;\n }\n \/\/ Fail if collection gone\n else if (existing.size() < 4) { \n finish(\"\", _shard, true, \"Collection \" + _collection + \" gone\");\n return false;\n }\n\n \/\/ Get healthy in Sync follower common to all prototype + clones\n auto commonHealthyInSync =\n findNonblockedCommonHealthyInSyncFollower(\n _snapshot, _database, _collection, _shard);\n if (commonHealthyInSync.empty()) {\n return false;\n } else {\n _to = commonHealthyInSync;\n }\n \n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Start failedLeader for \" + _shard + \" from \" + _from + \" to \" + _to; \n \n using namespace std::chrono;\n\n \/\/ Current servers vector\n auto const& current =\n _snapshot(\n curColPrefix + _database + \"\/\" + _collection + \"\/\" + _shard + \"\/servers\")\n .slice();\n \/\/ Planned servers vector\n std::string planPath\n = planColPrefix + _database + \"\/\" + _collection + \"\/shards\/\" + _shard;\n auto const& planned = _snapshot(planPath).slice();\n\n \/\/ Get todo entry\n Builder todo;\n { VPackArrayBuilder t(&todo);\n if (_jb == nullptr) {\n try {\n _snapshot(toDoPrefix + _jobId).toBuilder(todo);\n } catch (std::exception const&) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Failed to get key \" + toDoPrefix + _jobId\n + \" from agency snapshot\";\n return false;\n }\n } else {\n todo.add(_jb->slice()[0].get(toDoPrefix + _jobId));\n }}\n\n \/\/ New plan vector excluding _to and _from\n std::vector planv;\n for (auto const& i : VPackArrayIterator(planned)) {\n auto s = i.copyString();\n if (s != _from && s != _to) {\n planv.push_back(s);\n }\n }\n\n \/\/ Additional follower, if applicable\n auto additionalFollower = randomIdleGoodAvailableServer(_snapshot, planned);\n if (!additionalFollower.empty()) {\n planv.push_back(additionalFollower);\n }\n\n \/\/ Transactions\n Builder pending;\n \n { VPackArrayBuilder transactions(&pending);\n { VPackArrayBuilder transaction(&pending);\n \n \/\/ Operations ----------------------------------------------------------\n { VPackObjectBuilder operations(&pending);\n \/\/ Add pending entry\n pending.add(VPackValue(pendingPrefix + _jobId));\n { VPackObjectBuilder ts(&pending);\n pending.add(\"timeStarted\", \/\/ start\n VPackValue(timepointToString(system_clock::now())));\n pending.add(\"toServer\", VPackValue(_to)); \/\/ toServer\n for (auto const& obj : VPackObjectIterator(todo.slice()[0])) {\n pending.add(obj.key.copyString(), obj.value);\n }\n }\n addRemoveJobFromSomewhere(pending, \"ToDo\", _jobId);\n \/\/ DB server vector -------\n Builder ns;\n { VPackArrayBuilder servers(&ns);\n ns.add(VPackValue(_to)); \n for (auto const& i : VPackArrayIterator(current)) {\n std::string s = i.copyString();\n if (s != _from && s != _to) {\n ns.add(i);\n planv.erase(\n std::remove(planv.begin(), planv.end(), s), planv.end());\n }\n }\n ns.add(VPackValue(_from));\n for (auto const& i : planv) {\n ns.add(VPackValue(i));\n }\n }\n for (auto const& clone :\n clones(_snapshot, _database, _collection, _shard)) {\n pending.add(\n planColPrefix + _database + \"\/\"\n + clone.collection + \"\/shards\/\" + clone.shard, ns.slice());\n }\n addBlockShard(pending, _shard, _jobId);\n addIncreasePlanVersion(pending);\n }\n \/\/ Preconditions -------------------------------------------------------\n { VPackObjectBuilder preconditions(&pending);\n \/\/ Failed condition persists\n pending.add(VPackValue(healthPrefix + _from + \"\/Status\"));\n { VPackObjectBuilder stillExists(&pending);\n pending.add(\"old\", VPackValue(\"FAILED\")); }\n \/\/ Destination server still in good condition\n addPreconditionServerGood(pending, _to);\n \/\/ Server list in plan still as before\n addPreconditionUnchanged(pending, planPath, planned);\n \/\/ Destination server should not be blocked by another job\n addPreconditionServerNotBlocked(pending, _to);\n \/\/ Shard to be handled is block by another job\n addPreconditionShardNotBlocked(pending, _shard);\n } \/\/ Preconditions -----------------------------------------------------\n }\n }\n\n \/\/ Abort job blocking server if abortable\n try {\n std::string jobId = _snapshot(blockedShardsPrefix + _shard).getString();\n if (!abortable(_snapshot, jobId)) {\n return false;\n } else {\n JobContext(PENDING, jobId, _snapshot, _agent).abort();\n }\n } catch (...) {}\n \n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader transaction: \" << pending.toJson();\n \n trans_ret_t res = generalTransaction(_agent, pending);\n \n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader result: \" << res.result->toJson();\n\n\n \/\/ Something went south. Let's see\n auto result = res.result->slice()[0];\n\n if (res.accepted && result.isNumber()) {\n return true;\n }\n\n TRI_ASSERT(result.isObject());\n\n if (!res.accepted) { \/\/ lost leadership\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Leadership lost! Job \" << _jobId << \" handed off.\";\n }\n \n if (result.isObject()) {\n\n \/\/ Still failing _from?\n auto slice = result.get(\n std::vector({\n agencyPrefix, \"Supervision\", \"Health\", _from, \"Status\"}));\n if (slice.isString() && slice.copyString() == \"GOOD\") {\n finish(\"\", _shard, false, \"Server \" + _from + \" no longer failing.\");\n return false;\n }\n\n \/\/ Still healthy _to?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"Health\", _to, \"Status\"}));\n if (slice.isString() && slice.copyString() != \"GOOD\") {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Will not failover from \" << _from << \" to \" << _to\n << \" as target server is no longer in good condition. Will retry.\";\n return false;\n }\n\n \/\/ Snapshot and plan still in sync with respect to server list?\n slice = result.get(\n std::vector({agencyPrefix, \"Plan\", \"Collections\", _database,\n _collection, \"shards\", _shard}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Plan no longer holds the expected server list. Will retry.\";\n }\n\n \/\/ To server blocked by other job?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"DBServers\", _to}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Destination server \" << _to << \" meanwhile is blocked by job \" <<\n slice.copyString();\n }\n\n \/\/ This shard blocked by other job?\n slice = result.get(\n std::vector(\n {agencyPrefix, \"Supervision\", \"Shards\", _shard}));\n if (!slice.isNone()) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Shard \" << _shard << \" meanwhile is blocked by job \" <<\n slice.copyString();\n }\n }\n \n return false;\n \n}\n\nJOB_STATUS FailedLeader::status() {\n\n if(!_snapshot.has(planColPrefix + _database + \"\/\" + _collection)) {\n finish(\"\", _shard, true, \"Collection \" + _collection + \" gone\");\n return FINISHED;\n }\n\n \/\/ Timedout after 77 minutes\n if (std::chrono::system_clock::now() - _created > std::chrono::seconds(4620)) {\n rollback();\n }\n\n if (_status != PENDING) {\n return _status;\n }\n\n Node const& job = _snapshot(pendingPrefix + _jobId);\n std::string database = job(\"database\").toJson(),\n shard = job(\"shard\").toJson();\n \n bool done = false;\n for (auto const& clone : clones(_snapshot, _database, _collection, _shard)) {\n auto sub = database + \"\/\" + clone.collection;\n if(_snapshot(planColPrefix + sub + \"\/shards\/\" + clone.shard).slice()[0] !=\n _snapshot(curColPrefix + sub + \"\/\" + clone.shard + \"\/servers\").slice()[0]) {\n LOG_TOPIC(DEBUG, Logger::SUPERVISION)\n << \"FailedLeader waiting for \" << sub + \"\/\" + shard;\n break;\n }\n done = true;\n }\n \n if (done) {\n \/\/ Remove shard to \/arango\/Target\/FailedServers\/ array\n Builder del;\n { VPackArrayBuilder a(&del);\n { VPackObjectBuilder o(&del);\n del.add(VPackValue(failedServersPrefix + \"\/\" + _from));\n { VPackObjectBuilder erase(&del);\n del.add(\"op\", VPackValue(\"erase\"));\n del.add(\"val\", VPackValue(_shard));\n }}}\n \n write_ret_t res = singleWriteTransaction(_agent, del);\n if (finish(\"\", shard)) {\n LOG_TOPIC(INFO, Logger::SUPERVISION)\n << \"Finished failedLeader for \" + _shard + \" from \" + _from + \" to \" + _to; \n return FINISHED;\n }\n }\n \n return _status;\n}\n\n\narangodb::Result FailedLeader::abort() {\n \/\/ job is only abortable when it is in ToDo\n if (_status != TODO) {\n return Result(TRI_ERROR_SUPERVISION_GENERAL_FAILURE,\n \"Failed aborting failedFollower job beyond todo stage\");\n } else {\n finish(\"\", \"\", false, \"job aborted\");\n return Result();\n }\n}\n\n\n<|endoftext|>"} {"text":"#include \"HPACK.h\"\n#include \"hpack_table.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \"picojson\/picojson.h\"\n#include \n#include \n#include \n\nusing namespace picojson;\n\nTEST(encode_intTest, NormalTest) {\n uint8_t dst[10];\n uint8_t expect[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n \/\/{0x1f, 0xa1, 0x8d, 0xb7, 0x01},\n };\n uint64_t len = encode_int(dst, 1, 1);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));\n len = encode_int(dst, 16, 4);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n \/*\n len = encode_int(dst, 3000000, 5);\n EXPECT_EQ(5, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n *\/\n}\n\nTEST(decode_intTest, NormalTest) {\n uint32_t dst = 0;\n uint8_t data[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n };\n EXPECT_EQ(2, decode_int(dst, data[0], 1));\n EXPECT_EQ(1, dst);\n EXPECT_EQ(2, decode_int(dst, data[1], 4));\n EXPECT_EQ(16, dst);\n}\n\nconst static std::string TestCases[] = {\n \"hpack-test-case\/haskell-http2-naive\/\",\n \"hpack-test-case\/haskell-http2-naive-huffman\/\",\n \"hpack-test-case\/haskell-http2-static\/\",\n \"hpack-test-case\/haskell-http2-static-huffman\/\",\n \"hpack-test-case\/haskell-http2-linear\/\",\n \"hpack-test-case\/haskell-http2-linear-huffman\/\",\n \"hpack-test-case\/go-hpack\/\",\n \"hpack-test-case\/nghttp2\/\",\n \"hpack-test-case\/nghttp2-16384-4096\/\",\n \"hpack-test-case\/nghttp2-change-table-size\/\",\n \"hpack-test-case\/node-http2-hpack\/\",\n};\n\nconst static std::string out_tmp_file = \"filename.txt\";\n\nbool\nread_json_files(std::vector &jsons, const std::string testcase) {\n std::string call_str = \"ls \" + testcase + \" > \" + out_tmp_file;\n int len = call_str.length();\n char call[70];\n memcpy(call, call_str.c_str(), len+1);\n system(call);\n std::ifstream fnames(out_tmp_file);\n if (fnames.fail()) {\n std::cerr << \"fail to open\" << out_tmp_file << std::endl;\n return false;\n }\n\n std::string field;\n while (std::getline(fnames, field)) {\n jsons.push_back(field);\n }\n\n return true;\n}\n\nbool\nread_json_as_pico(value& v, const std::string path) {\n std::ifstream ifs(path);\n\n if (ifs.fail()) {\n std::cerr << \"fail to open\" << std::endl;\n return false;\n }\n std::string str((std::istreambuf_iterator(ifs)),\n std::istreambuf_iterator());\n std::string err = parse(v, str);\n if (! err.empty()) {\n std::cerr << err << std::endl;\n return false;\n }\n return true;\n}\n\nbool\nread_sequence(int& table_size, std::vector

& ans_headers, std::string& wire, array::iterator it_seqno) {\n object obj_in = it_seqno->get();\n if (obj_in[\"header_table_size\"].to_str() != \"null\") {\n table_size = (int)std::stoi(obj_in[\"header_table_size\"].to_str());\n }\n wire = obj_in[\"wire\"].to_str();\n array json_headers = obj_in[\"headers\"].get();\n array::iterator it_headers;\n\n for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {\n object content = it_headers->get();\n object::iterator it = content.begin();\n ans_headers.push_back(header(it->first, it->second.to_str()));\n }\n return true;\n}\n\nbool\nwire2byte(uint8_t *wire_byte, const std::string wire) {\n int len = wire.length();\n for (int i = 0; i < len; i += 2) {\n *(wire_byte+i\/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16);\n }\n return true;\n}\n\nvoid\ndetect_testcase_type(bool &from_header, bool &from_static,\n bool &is_huffman,const std::string testcase) {\n from_header = std::string::npos != testcase.find(\"linear\", 0);\n from_static = from_header || std::string::npos != testcase.find(\"static\", 0);\n if (std::string::npos != testcase.find(\"haskell\", 0)) {\n is_huffman = std::string::npos != testcase.find(\"huffman\", 0);\n } else {\n is_huffman = true;\n }\n}\n\nvoid\nprint_wires(const uint8_t* expect, uint64_t e_len, const uint8_t* actual, uint64_t a_len) {\n std::cout << \"Expect\" << std::endl;\n for (int i = 0; i < e_len; i++) {\n printf(\"%02x\", *(expect+i));\n }\n std::cout << std::endl;\n std::cout << \"Actual\" << std::endl;\n for (int i = 0; i < a_len; i++) {\n printf(\"%02x\", *(actual+i));\n }\n std::cout << std::endl << std::endl;\n}\n\nTEST(encodeTest, NormalTest) {\n for (const std::string testcase : TestCases) {\n std::vector jsons;\n bool err = read_json_files(jsons, testcase);\n if (!err) {\n }\n\n bool from_header, from_static, is_huffman;\n detect_testcase_type(from_header, from_static, is_huffman, testcase);\n std::cout << testcase << \" \" << from_header << from_static << is_huffman << std::endl;\n\n Table* encode_table = new Table();\n Table* decode_table = new Table();\n for (std::string json_file : jsons) {\n value v;\n err = read_json_as_pico(v, testcase + json_file);\n if (!err) {\n }\n\n object obj = v.get();\n array arr = obj[\"cases\"].get();\n array::iterator it_seqno = arr.begin();\n for (int seqno = 0; it_seqno != arr.end(); seqno++, it_seqno++) {\n int table_size = -1;\n std::string wire;\n std::vector
expect_headers;\n err = read_sequence(table_size, expect_headers, wire, it_seqno);\n if (!err) {\n }\n uint8_t *expect_wire = new uint8_t[wire.length()\/2];\n err = wire2byte(expect_wire, wire);\n if (*expect_wire == 0x0e) {\n *expect_wire = 0x08;\n }\n if (!err) {\n }\n\n uint8_t actual_wire[20000];\n int64_t len = hpack_encode(actual_wire, expect_headers, from_static,\n from_header, is_huffman, encode_table, table_size);\n\n int wire_assert = std::memcmp(actual_wire, expect_wire, len);\n if (wire_assert != 0) {\n std::cout << testcase << json_file << \" seqno: \" << seqno << std::endl;\n print_wires(expect_wire, wire.length()\/2, actual_wire, len);\n for (header head : expect_headers) {\n std::cout << head.first << \" \" << head.second << std::endl;\n }\n }\n ASSERT_EQ(wire.length()\/2, len);\n ASSERT_TRUE(0 == wire_assert);\n\n std::vector
actual_headers;\n int64_t cursor = hpack_decode(actual_headers, expect_wire, decode_table, wire.length()\/2);\n ASSERT_EQ(cursor, wire.length()\/2);\n ASSERT_EQ(actual_headers.size(), expect_headers.size());\n for (int i = 0; i < actual_headers.size(); i++) {\n ASSERT_EQ(actual_headers[i], expect_headers[i]);\n }\n\n delete [] expect_wire;\n }\n }\n delete encode_table;\n delete decode_table;\n }\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nchange testname#include \"HPACK.h\"\n#include \"hpack_table.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \"picojson\/picojson.h\"\n#include \n#include \n#include \n\nusing namespace picojson;\n\nTEST(encode_intTest, NormalTest) {\n uint8_t dst[10];\n uint8_t expect[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n \/\/{0x1f, 0xa1, 0x8d, 0xb7, 0x01},\n };\n uint64_t len = encode_int(dst, 1, 1);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[0], len));\n len = encode_int(dst, 16, 4);\n EXPECT_EQ(2, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n \/*\n len = encode_int(dst, 3000000, 5);\n EXPECT_EQ(5, len);\n EXPECT_TRUE(0 == std::memcmp(dst, expect[1], len));\n *\/\n}\n\nTEST(decode_intTest, NormalTest) {\n uint32_t dst = 0;\n uint8_t data[][5] = {\n {0x01, 0x00},\n {0x0f, 0x01},\n };\n EXPECT_EQ(2, decode_int(dst, data[0], 1));\n EXPECT_EQ(1, dst);\n EXPECT_EQ(2, decode_int(dst, data[1], 4));\n EXPECT_EQ(16, dst);\n}\n\nconst static std::string TestCases[] = {\n \"hpack-test-case\/haskell-http2-naive\/\",\n \"hpack-test-case\/haskell-http2-naive-huffman\/\",\n \"hpack-test-case\/haskell-http2-static\/\",\n \"hpack-test-case\/haskell-http2-static-huffman\/\",\n \"hpack-test-case\/haskell-http2-linear\/\",\n \"hpack-test-case\/haskell-http2-linear-huffman\/\",\n \"hpack-test-case\/go-hpack\/\",\n \"hpack-test-case\/nghttp2\/\",\n \"hpack-test-case\/nghttp2-16384-4096\/\",\n \"hpack-test-case\/nghttp2-change-table-size\/\",\n \"hpack-test-case\/node-http2-hpack\/\",\n};\n\nconst static std::string out_tmp_file = \"filename.txt\";\n\nbool\nread_json_files(std::vector &jsons, const std::string testcase) {\n std::string call_str = \"ls \" + testcase + \" > \" + out_tmp_file;\n int len = call_str.length();\n char call[70];\n memcpy(call, call_str.c_str(), len+1);\n system(call);\n std::ifstream fnames(out_tmp_file);\n if (fnames.fail()) {\n std::cerr << \"fail to open\" << out_tmp_file << std::endl;\n return false;\n }\n\n std::string field;\n while (std::getline(fnames, field)) {\n jsons.push_back(field);\n }\n\n return true;\n}\n\nbool\nread_json_as_pico(value& v, const std::string path) {\n std::ifstream ifs(path);\n\n if (ifs.fail()) {\n std::cerr << \"fail to open\" << std::endl;\n return false;\n }\n std::string str((std::istreambuf_iterator(ifs)),\n std::istreambuf_iterator());\n std::string err = parse(v, str);\n if (! err.empty()) {\n std::cerr << err << std::endl;\n return false;\n }\n return true;\n}\n\nbool\nread_sequence(int& table_size, std::vector
& ans_headers, std::string& wire, array::iterator it_seqno) {\n object obj_in = it_seqno->get();\n if (obj_in[\"header_table_size\"].to_str() != \"null\") {\n table_size = (int)std::stoi(obj_in[\"header_table_size\"].to_str());\n }\n wire = obj_in[\"wire\"].to_str();\n array json_headers = obj_in[\"headers\"].get();\n array::iterator it_headers;\n\n for (it_headers = json_headers.begin(); it_headers != json_headers.end(); it_headers++) {\n object content = it_headers->get();\n object::iterator it = content.begin();\n ans_headers.push_back(header(it->first, it->second.to_str()));\n }\n return true;\n}\n\nbool\nwire2byte(uint8_t *wire_byte, const std::string wire) {\n int len = wire.length();\n for (int i = 0; i < len; i += 2) {\n *(wire_byte+i\/2) = (uint8_t)std::stoi(wire.substr(i, 2).c_str(), nullptr, 16);\n }\n return true;\n}\n\nvoid\ndetect_testcase_type(bool &from_header, bool &from_static,\n bool &is_huffman,const std::string testcase) {\n from_header = std::string::npos != testcase.find(\"linear\", 0);\n from_static = from_header || std::string::npos != testcase.find(\"static\", 0);\n if (std::string::npos != testcase.find(\"haskell\", 0)) {\n is_huffman = std::string::npos != testcase.find(\"huffman\", 0);\n } else {\n is_huffman = true;\n }\n}\n\nvoid\nprint_wires(const uint8_t* expect, uint64_t e_len, const uint8_t* actual, uint64_t a_len) {\n std::cout << \"Expect\" << std::endl;\n for (int i = 0; i < e_len; i++) {\n printf(\"%02x\", *(expect+i));\n }\n std::cout << std::endl;\n std::cout << \"Actual\" << std::endl;\n for (int i = 0; i < a_len; i++) {\n printf(\"%02x\", *(actual+i));\n }\n std::cout << std::endl << std::endl;\n}\n\nTEST(HPACKeTest, NormalTest) {\n for (const std::string testcase : TestCases) {\n std::vector jsons;\n bool err = read_json_files(jsons, testcase);\n if (!err) {\n }\n\n bool from_header, from_static, is_huffman;\n detect_testcase_type(from_header, from_static, is_huffman, testcase);\n std::cout << testcase << \" \" << from_header << from_static << is_huffman << std::endl;\n\n Table* encode_table = new Table();\n Table* decode_table = new Table();\n for (std::string json_file : jsons) {\n value v;\n err = read_json_as_pico(v, testcase + json_file);\n if (!err) {\n }\n\n object obj = v.get();\n array arr = obj[\"cases\"].get();\n array::iterator it_seqno = arr.begin();\n for (int seqno = 0; it_seqno != arr.end(); seqno++, it_seqno++) {\n int table_size = -1;\n std::string wire;\n std::vector
expect_headers;\n err = read_sequence(table_size, expect_headers, wire, it_seqno);\n if (!err) {\n }\n uint8_t *expect_wire = new uint8_t[wire.length()\/2];\n err = wire2byte(expect_wire, wire);\n if (*expect_wire == 0x0e) {\n *expect_wire = 0x08;\n }\n if (!err) {\n }\n\n uint8_t actual_wire[20000];\n int64_t len = hpack_encode(actual_wire, expect_headers, from_static,\n from_header, is_huffman, encode_table, table_size);\n\n int wire_assert = std::memcmp(actual_wire, expect_wire, len);\n if (wire_assert != 0) {\n std::cout << testcase << json_file << \" seqno: \" << seqno << std::endl;\n print_wires(expect_wire, wire.length()\/2, actual_wire, len);\n for (header head : expect_headers) {\n std::cout << head.first << \" \" << head.second << std::endl;\n }\n }\n ASSERT_EQ(wire.length()\/2, len);\n ASSERT_TRUE(0 == wire_assert);\n\n std::vector
actual_headers;\n int64_t cursor = hpack_decode(actual_headers, expect_wire, decode_table, wire.length()\/2);\n ASSERT_EQ(cursor, wire.length()\/2);\n ASSERT_EQ(actual_headers.size(), expect_headers.size());\n for (int i = 0; i < actual_headers.size(); i++) {\n ASSERT_EQ(actual_headers[i], expect_headers[i]);\n }\n\n delete [] expect_wire;\n }\n }\n delete encode_table;\n delete decode_table;\n }\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/\/\/ Le Plan:\n\/\/\/ 1. Proof of concept.\n\/\/\/ 2. ???\n\/\/\/ 3. PROFIT!\n\n\/\/ blackhole\/sink\/asynchronous.hpp\n\n#include \n#include \n\n#include \n\n#include \"blackhole\/sink.hpp\"\n\n#include \"blackhole\/detail\/recordbuf.hpp\"\n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\n\nusing detail::recordbuf_t;\n\nclass asynchronous_t : public sink_t {\n struct value_type {\n recordbuf_t record;\n std::string message;\n };\n\n typedef cds::container::VyukovMPSCCycleQueue queue_type;\n\n queue_type queue;\n std::atomic stopped;\n std::unique_ptr wrapped;\n\n std::thread thread;\n\npublic:\n \/\/\/ \\param factor queue capacity factor from which the queue capacity will be generated as\n \/\/\/ a value of `2 << factor`. Must fit in [0; 20] range (64 MB).\n \/\/\/ \\param queue_type\n \/\/\/ \\param overflow_policy [drop silently, drop with error, block]\n \/\/\/\n \/\/\/ \\throw std::invalid_argument if the factor is greater than 20.\n asynchronous_t(std::unique_ptr wrapped, std::size_t factor = 10);\n\n ~asynchronous_t();\n\n auto emit(const record_t& record, const string_view& message) -> void;\n\nprivate:\n auto run() -> void;\n};\n\n} \/\/ namespace sink\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n\n\/\/ src\/sink\/asynchronous.cpp\n\n#include \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 std::exp2(factor);\n}\n\n} \/\/ namespace\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 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 return;\n }\n\n const auto enqueued = queue.enqueue_with([&](value_type& value) {\n value = {recordbuf_t(record), message.to_string()};\n });\n\n \/\/ TODO: If failed, some kind of overflow policy is immediately involved.\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 \/\/ TODO: What to do with exceptions?\n wrapped->emit(result.record.into_view(), result.message);\n } else {\n \/\/ Sleep or CV.\n ::usleep(1000);\n }\n\n if (stopped && !dequeued) {\n return;\n }\n }\n}\n\n} \/\/ namespace sink\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n\n\/\/ unit\/sink\/asynchronous.cpp\n\n#include \n#include \n\n#include \"mocks\/sink.hpp\"\n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\nnamespace {\n\nusing ::testing::_;\nusing ::testing::Invoke;\n\nnamespace mock = testing::mock;\n\nTEST(asynchronous_t, DelegatesEmit) {\n std::unique_ptr wrapped(new mock::sink_t);\n\n EXPECT_CALL(*wrapped, emit(_, string_view(\"formatted message\")))\n .Times(1)\n .WillOnce(Invoke([](const record_t& record, string_view) {\n ASSERT_EQ(1, record.attributes().size());\n EXPECT_EQ((attribute_list{{\"key#1\", {\"value#1\"}}}), record.attributes().at(0).get());\n }));\n\n asynchronous_t sink(std::move(wrapped));\n\n const string_view message(\"unformatted message\");\n const attribute_list attributes{{\"key#1\", {\"value#1\"}}};\n const attribute_pack pack({attributes});\n record_t record(42, message, pack);\n\n sink.emit(record, \"formatted message\");\n}\n\n} \/\/ namespace\n} \/\/ namespace sink\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\nfeat(sink\/asynchronous): add more policies\/\/\/ Le Plan:\n\/\/\/ 1. Proof of concept.\n\/\/\/ 2. ???\n\/\/\/ 3. PROFIT!\n\n\/\/ blackhole\/sink\/asynchronous.hpp\n\n#include \n#include \n\n#include \n\n#include \"blackhole\/sink.hpp\"\n\n#include \"blackhole\/detail\/recordbuf.hpp\"\n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\n\nusing detail::recordbuf_t;\n\n\/\/\/ I can imagine: drop, sleep, wait.\nclass overflow_policy_t {\npublic:\n enum class action_t {\n retry,\n drop\n };\n\npublic:\n \/\/\/ Handles record queue overflow.\n \/\/\/\n \/\/\/ This method is called when the queue is unable to enqueue more items. It's okay to throw\n \/\/\/ exceptions from here, they will be propagated directly to the sink caller.\n virtual auto overflow() -> action_t = 0;\n\n virtual auto wakeup() -> void = 0;\n};\n\nclass asynchronous_t : public sink_t {\n struct value_type {\n recordbuf_t record;\n std::string message;\n };\n\n typedef cds::container::VyukovMPSCCycleQueue queue_type;\n\n queue_type queue;\n std::atomic stopped;\n std::unique_ptr wrapped;\n\n std::unique_ptr overflow_policy;\n\n std::thread thread;\n\npublic:\n \/\/\/ \\param factor queue capacity factor from which the queue capacity will be generated as\n \/\/\/ a value of `2 << factor`. Must fit in [0; 20] range (64 MB).\n \/\/\/ \\param queue_type\n \/\/\/ \\param overflow_policy [drop silently, drop with error, block]\n \/\/\/\n \/\/\/ \\throw std::invalid_argument if the factor is greater than 20.\n asynchronous_t(std::unique_ptr wrapped, std::size_t factor = 10);\n\n \/\/ asynchronous_t(std::unique_ptr sink,\n \/\/ std::unique_ptr filter,\n \/\/ std::unique_ptr overflow_policy,\n \/\/ std::unique_ptr exception_policy,\n \/\/ std::size_t factor = 10);\n\n ~asynchronous_t();\n\n auto emit(const record_t& record, const string_view& message) -> void;\n\nprivate:\n auto run() -> void;\n};\n\n} \/\/ namespace sink\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n\n\/\/ src\/sink\/asynchronous.cpp\n\n#include \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 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 default:\n BOOST_ASSERT(false);\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} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n\n\/\/ unit\/sink\/asynchronous.cpp\n\n#include \n#include \n\n#include \"mocks\/sink.hpp\"\n\nnamespace blackhole {\ninline namespace v1 {\nnamespace experimental {\nnamespace sink {\nnamespace {\n\nusing ::testing::_;\nusing ::testing::Invoke;\n\nnamespace mock = testing::mock;\n\nTEST(asynchronous_t, DelegatesEmit) {\n std::unique_ptr wrapped(new mock::sink_t);\n\n EXPECT_CALL(*wrapped, emit(_, string_view(\"formatted message\")))\n .Times(1)\n .WillOnce(Invoke([](const record_t& record, string_view) {\n ASSERT_EQ(1, record.attributes().size());\n EXPECT_EQ((attribute_list{{\"key#1\", {\"value#1\"}}}), record.attributes().at(0).get());\n }));\n\n asynchronous_t sink(std::move(wrapped));\n\n const string_view message(\"unformatted message\");\n const attribute_list attributes{{\"key#1\", {\"value#1\"}}};\n const attribute_pack pack({attributes});\n record_t record(42, message, pack);\n\n sink.emit(record, \"formatted message\");\n}\n\n} \/\/ namespace\n} \/\/ namespace sink\n} \/\/ namespace experimental\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/ \n\/\/ Test Suite for C-API GEOSCoordSeq\n\n#include \n\/\/ geos\n#include \n\/\/ std\n#include \n#include \n#include \n#include \n\nnamespace tut\n{\n \/\/\n \/\/ Test Group\n \/\/\n\n \/\/ Common data used in test cases.\n struct test_capigeoscoordseq_data\n {\n\n GEOSCoordSequence* cs_;\n\n static void notice(const char *fmt, ...)\n {\n std::fprintf( stdout, \"NOTICE: \");\n\n va_list ap;\n va_start(ap, fmt);\n std::vfprintf(stdout, fmt, ap);\n va_end(ap);\n \n std::fprintf(stdout, \"\\n\");\n }\n\n test_capigeoscoordseq_data() : cs_(0)\n {\n initGEOS(notice, notice);\n } \n\n ~test_capigeoscoordseq_data()\n {\n GEOSCoordSeq_destroy(cs_);\n cs_ = 0;\n finishGEOS();\n }\n\n };\n\n typedef test_group group;\n typedef group::object object;\n\n group test_capigeoscoordseq_group(\"capi::GEOSCoordSeq\");\n\n \/\/\n \/\/ Test Cases\n \/\/\n\n \/\/ Test construction and fill of a 3D CoordinateSequence\n template<>\n template<>\n void object::test<1>()\n {\n cs_ = GEOSCoordSeq_create(5, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 5u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n for (unsigned int i=0; i<5; ++i)\n {\n double x = i*10;\n double y = i*10+1;\n double z = i*10+2;\n\n GEOSCoordSeq_setX(cs_, i, x);\n GEOSCoordSeq_setY(cs_, i, y);\n GEOSCoordSeq_setZ(cs_, i, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getX(cs_, i, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getY(cs_, i, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, i, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n }\n } \n \n \/\/ Test not swapped setX\/setY calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<2>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ X, Y, Z\n GEOSCoordSeq_setX(cs_, 0, x);\n GEOSCoordSeq_setY(cs_, 0, y);\n GEOSCoordSeq_setZ(cs_, 0, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getY(cs_, 0, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getX(cs_, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, 0, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test not swapped setOrdinate calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<3>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ X, Y, Z\n GEOSCoordSeq_setOrdinate(cs_, 0, 0, x);\n GEOSCoordSeq_setOrdinate(cs_, 0, 1, y);\n GEOSCoordSeq_setOrdinate(cs_, 0, 2, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 1, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 2, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test swapped setX calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<4>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ Y, X, Z\n GEOSCoordSeq_setY(cs_, 0, y);\n GEOSCoordSeq_setX(cs_, 0, x);\n GEOSCoordSeq_setZ(cs_, 0, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getY(cs_, 0, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getX(cs_, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, 0, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test swapped setOrdinate calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<5>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ Y, X, Z\n GEOSCoordSeq_setOrdinate(cs_, 0, 1, y);\n GEOSCoordSeq_setOrdinate(cs_, 0, 0, x);\n GEOSCoordSeq_setOrdinate(cs_, 0, 2, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 1, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 2, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n \n} \/\/ namespace tut\n\nAdd test for creating a CoordinateSequence with at least 2 dimension\/\/ $Id$\n\/\/ \n\/\/ Test Suite for C-API GEOSCoordSeq\n\n#include \n\/\/ geos\n#include \n\/\/ std\n#include \n#include \n#include \n#include \n\nnamespace tut\n{\n \/\/\n \/\/ Test Group\n \/\/\n\n \/\/ Common data used in test cases.\n struct test_capigeoscoordseq_data\n {\n\n GEOSCoordSequence* cs_;\n\n static void notice(const char *fmt, ...)\n {\n std::fprintf( stdout, \"NOTICE: \");\n\n va_list ap;\n va_start(ap, fmt);\n std::vfprintf(stdout, fmt, ap);\n va_end(ap);\n \n std::fprintf(stdout, \"\\n\");\n }\n\n test_capigeoscoordseq_data() : cs_(0)\n {\n initGEOS(notice, notice);\n } \n\n ~test_capigeoscoordseq_data()\n {\n GEOSCoordSeq_destroy(cs_);\n cs_ = 0;\n finishGEOS();\n }\n\n };\n\n typedef test_group group;\n typedef group::object object;\n\n group test_capigeoscoordseq_group(\"capi::GEOSCoordSeq\");\n\n \/\/\n \/\/ Test Cases\n \/\/\n\n \/\/ Test construction and fill of a 3D CoordinateSequence\n template<>\n template<>\n void object::test<1>()\n {\n cs_ = GEOSCoordSeq_create(5, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 5u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n for (unsigned int i=0; i<5; ++i)\n {\n double x = i*10;\n double y = i*10+1;\n double z = i*10+2;\n\n GEOSCoordSeq_setX(cs_, i, x);\n GEOSCoordSeq_setY(cs_, i, y);\n GEOSCoordSeq_setZ(cs_, i, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getX(cs_, i, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getY(cs_, i, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, i, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n }\n } \n \n \/\/ Test not swapped setX\/setY calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<2>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ X, Y, Z\n GEOSCoordSeq_setX(cs_, 0, x);\n GEOSCoordSeq_setY(cs_, 0, y);\n GEOSCoordSeq_setZ(cs_, 0, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getY(cs_, 0, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getX(cs_, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, 0, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test not swapped setOrdinate calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<3>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ X, Y, Z\n GEOSCoordSeq_setOrdinate(cs_, 0, 0, x);\n GEOSCoordSeq_setOrdinate(cs_, 0, 1, y);\n GEOSCoordSeq_setOrdinate(cs_, 0, 2, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 1, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 2, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test swapped setX calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<4>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ Y, X, Z\n GEOSCoordSeq_setY(cs_, 0, y);\n GEOSCoordSeq_setX(cs_, 0, x);\n GEOSCoordSeq_setZ(cs_, 0, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getY(cs_, 0, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getX(cs_, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getZ(cs_, 0, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test swapped setOrdinate calls (see bug #133, fixed)\n template<>\n template<>\n void object::test<5>()\n {\n cs_ = GEOSCoordSeq_create(1, 3);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n ensure_equals( dims, 3u );\n\n double x = 10;\n double y = 11;\n double z = 12;\n\n \/\/ Y, X, Z\n GEOSCoordSeq_setOrdinate(cs_, 0, 1, y);\n GEOSCoordSeq_setOrdinate(cs_, 0, 0, x);\n GEOSCoordSeq_setOrdinate(cs_, 0, 2, z);\n\n double xcheck, ycheck, zcheck;\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 1, &ycheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 0, &xcheck) );\n ensure( 0 != GEOSCoordSeq_getOrdinate(cs_, 0, 2, &zcheck) );\n\n ensure_equals( xcheck, x );\n ensure_equals( ycheck, y );\n ensure_equals( zcheck, z );\n } \n\n \/\/ Test getDimensions call (see bug #135)\n template<>\n template<>\n void object::test<6>()\n {\n cs_ = GEOSCoordSeq_create(1, 2);\n \n unsigned int size;\n unsigned int dims;\n\n ensure ( 0 != GEOSCoordSeq_getSize(cs_, &size) );\n ensure_equals( size, 1u );\n\n ensure ( 0 != GEOSCoordSeq_getDimensions(cs_, &dims) );\n\n\t\/\/ The dimension passed to GEOSCoordSeq_create()\n\t\/\/ is a request for a minimum, not a strict mandate\n\t\/\/ for changing actual size.\n\t\/\/\n ensure ( dims >= 2u );\n\n } \n \n} \/\/ namespace tut\n\n<|endoftext|>"} {"text":"#include \"MenuState.h\"\n#include \n#include \"TextureManager.h\"\n#include \"Game.h\"\n#include \"MenuButton.h\"\n\nconst std::string MenuState::s_menuID = \"MENU\";\n\n\/\/function to be called when PLAY button is pressed\nvoid MenuState::s_menuToPlay()\n{\n\tstd::cout << \"Play button clicked\\n\";\n}\n\n\/\/function to be called when EXIT button is pressed\nvoid MenuState::s_exitFromMenu()\n{\n\t\/\/exit the game\n\tTheGame::Instance()->quit();\n}\n\n\/\/update each game object\nvoid MenuState::update()\n{\n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->update();\n\t}\n}\n\n\/\/draw the game objects\nvoid MenuState::render()\n{\n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->draw();\n\t}\n}\n\nbool MenuState::onEnter()\n{\t\n\t\/\/load the play button image\n\tif (!TheTextureManager::Instance()->load(\"assets\/button.png\", \"playbutton\", TheGame::Instance()->getRenderer()))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/load the exit button image\n\tif (!TheTextureManager::Instance()->load(\"assets\/exit.png\", \"exitbutton\", TheGame::Instance()->getRenderer()))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/assign the new textures to game objects named button1 and button2\n\tGameObject* button1 = new MenuButton(new LoaderParams(100, 100, 400, 100, \"playbutton\"), s_menuToPlay);\n\tGameObject* button2 = new MenuButton(new LoaderParams(100, 300, 400, 100, \"exitbutton\"), s_exitFromMenu);\n\n\t\/\/push them in the vector\n\tm_gameObjects.push_back(button1);\n\tm_gameObjects.push_back(button2);\n\n\tstd::cout << \"entering MenuState\\n\";\n\treturn true;\n}\n\nbool MenuState::onExit()\n{\t\n\t\/\/iterate through all the objects and clean \n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->clean();\n\t}\n\tm_gameObjects.clear();\n\n\t\/\/remove the button textures\n\tTheTextureManager::Instance()->clearFromTextureMap(\"playbutton\");\n\tTheTextureManager::Instance()->clearFromTextureMap(\"exitbutton\");\n\n\n\tstd::cout << \"exiting MenuState\\n\";\n\treturn true;\n}s_menuToPlay() function now creates a blank PlayState#include \"MenuState.h\"\n#include \n#include \"TextureManager.h\"\n#include \"Game.h\"\n#include \"MenuButton.h\"\n#include \"PlayState.h\"\n\nconst std::string MenuState::s_menuID = \"MENU\";\n\n\/\/function to be called when PLAY button is pressed\nvoid MenuState::s_menuToPlay()\n{\n\t\/\/change the state to Play State\n\tTheGame::Instance()->getStateMachine()->changeState(new PlayState());\n}\n\n\/\/function to be called when EXIT button is pressed\nvoid MenuState::s_exitFromMenu()\n{\n\t\/\/exit the game\n\tTheGame::Instance()->quit();\n}\n\n\/\/update each game object\nvoid MenuState::update()\n{\n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->update();\n\t}\n}\n\n\/\/draw the game objects\nvoid MenuState::render()\n{\n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->draw();\n\t}\n}\n\nbool MenuState::onEnter()\n{\t\n\t\/\/load the play button image\n\tif (!TheTextureManager::Instance()->load(\"assets\/button.png\", \"playbutton\", TheGame::Instance()->getRenderer()))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/load the exit button image\n\tif (!TheTextureManager::Instance()->load(\"assets\/exit.png\", \"exitbutton\", TheGame::Instance()->getRenderer()))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/assign the new textures to game objects named button1 and button2\n\tGameObject* button1 = new MenuButton(new LoaderParams(100, 100, 400, 100, \"playbutton\"), s_menuToPlay);\n\tGameObject* button2 = new MenuButton(new LoaderParams(100, 300, 400, 100, \"exitbutton\"), s_exitFromMenu);\n\n\t\/\/push them in the vector\n\tm_gameObjects.push_back(button1);\n\tm_gameObjects.push_back(button2);\n\n\tstd::cout << \"entering MenuState\\n\";\n\treturn true;\n}\n\nbool MenuState::onExit()\n{\t\n\t\/\/iterate through all the objects and clean \n\tfor (int i = 0; i < (int)m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->clean();\n\t}\n\tm_gameObjects.clear();\n\n\t\/\/remove the button textures\n\tTheTextureManager::Instance()->clearFromTextureMap(\"playbutton\");\n\tTheTextureManager::Instance()->clearFromTextureMap(\"exitbutton\");\n\n\n\tstd::cout << \"exiting MenuState\\n\";\n\treturn true;\n}<|endoftext|>"} {"text":"\/\/ MolarMass.cpp\n\/\/ This program should loop through the csv file Atomic Masses.csv and sum the masses of elements\n\n#include \n#include \n#include \n\nint main() \n{\n\n\tdouble runningSum = 0, atmMass;\n\tstd::string identifier; \/\/Make this value the value from the SMILE\n\tidentifier = 'H';\n\tstd::string symbol, name, atmNum, str;\n\tstd::ifstream elementInfo(\"atomicmasses.txt\"); \/\/Specifying file to be opened as variable elementInfo\n\t\/\/elementInfo.open(\"\");\n\n\tif (!elementInfo) \n\t{\n\t\tstd::cout << \"Error reading file\\n\";\n\t\tgetline(std::cin, str);\n\t\tstd::cin.get();\n\t\texit(1);\n\t}\n\n\twhile (!elementInfo.eof())\n\t{\n\n\n\t\tgetline(elementInfo, symbol, ',');\n\n\t\t\/\/getline(elementInfo, name, ',');\n\t\t\/\/getline(elementInfo, atmNum, ' ');\n\n\t\tif (symbol == identifier)\n\t\t{\n\t\t\telementInfo >> atmMass;\n\t\t\trunningSum += atmMass;\n\t\t}\n\t}\n\n\telementInfo.close();\n\tstd::cin.get();\t\n}\nUpdate MolarMass.cpp\/\/ MolarMass.cpp\n\/\/ This program should loop through the csv file Atomic Masses.csv and sum the masses of elements\n\n#include \n#include \n#include \n\nint main()\n{\n\n double runningSum = 0, atmMass;\n std::string identifier; \/\/Make this value the value from the SMILE\n identifier = 'H';\n std::string symbol, name, atmNum, str;\n std::ifstream elementInfo; \/\/Specifying file to be opened as variable elementInfo\n elementInfo.open(\"AtomicMasses\");\n\n if (!elementInfo)\n {\n std::cout << \"Error reading file\\n\";\n getline(std::cin, str);\n std::cin.get();\n exit(1);\n }\n\n while (!elementInfo.eof())\n {\n getline(elementInfo, str, '\\n');\n\n elementInfo >> symbol;\n \/\/getline(elementInfo, name, ',');\n \/\/getline(elementInfo, atmNum, ' ');\n\n\n if (symbol == identifier)\n {\n std::cout << \"hi\";\n elementInfo >> atmMass;\n runningSum += atmMass;\n }\n }\n std::cout << runningSum;\n\n elementInfo.close();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Las Venturas Playground. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license, a copy of which can\n\/\/ be found in the LICENSE file.\n\n#include \"plugin\/native_function_manager.h\"\n\n#include \n\n#include \"base\/logging.h\"\n#include \"plugin\/fake_amx.h\"\n#include \"plugin\/sdk\/amx.h\"\n#include \"plugin\/sdk\/plugincommon.h\"\n#include \"third_party\/subhook\/subhook.h\"\n\nnamespace plugin {\n\nnamespace {\n\n\/\/ Type definition of the original amx_Register_t function that is being intercepted.\ntypedef int AMXAPI(*amx_Register_t)(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number);\n\n\/\/ Global instance of the NativeFunctionManager instance, only to be used by amx_Register_hook().\nNativeFunctionManager* g_native_function_manager = nullptr;\n\nint amx_Register_hook(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) {\n return g_native_function_manager->OnRegister(amx, nativelist, number);\n}\n\n} \/\/ namespace\n\nNativeFunctionManager::NativeFunctionManager()\n : fake_amx_(new FakeAMX) {\n g_native_function_manager = this;\n}\n\nNativeFunctionManager::~NativeFunctionManager() {\n g_native_function_manager = nullptr;\n}\n\nbool NativeFunctionManager::Install() {\n if (!pAMXFunctions)\n return true; \/\/ testing\n\n void* current_address = static_cast(pAMXFunctions)[PLUGIN_AMX_EXPORT_Register];\n if (current_address == nullptr) {\n LOG(ERROR) << \"Invalid address found for the amx_Register() function.\";\n return false;\n }\n\n hook_.reset(new SubHook(current_address, (void*) amx_Register_hook));\n if (!hook_->Install()) {\n LOG(ERROR) << \"Unable to install a SubHook for the amx_Register() function.\";\n return false;\n }\n\n return true;\n}\n\nint NativeFunctionManager::OnRegister(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) {\n if (nativelist != nullptr) {\n for (size_t index = 0; ; ++index) {\n if (nativelist[index].func == nullptr || nativelist[index].name == nullptr)\n break;\n\n const std::string native_name(nativelist[index].name);\n\n \/\/ The Pawn interpreter iterates over unresolved functions in the gamemode, and finds them in\n \/\/ the functions that are being registered in the amx_Register() call. This means that the first\n \/\/ function registered for a given name will be used, rather than having later registrations\n \/\/ override previous ones. Simply drop out if a double-registration is observed.\n if (!FunctionExists(native_name))\n native_functions_[native_name] = static_cast(nativelist[index].func);\n }\n }\n\n \/\/ Trampoline back to the original amx_Register function that we intercepted.\n return ((amx_Register_t) hook_->GetTrampoline())(amx, nativelist, number);\n}\n\nbool NativeFunctionManager::FunctionExists(const std::string& function_name) const {\n return native_functions_.find(function_name) != native_functions_.end();\n}\n\nint NativeFunctionManager::CallFunction(const std::string& function_name,\n const char* format, void** arguments) {\n auto function_iter = native_functions_.find(function_name);\n if (function_iter == native_functions_.end()) {\n LOG(WARNING) << \"Attempting to invoke unknown Pawn native \" << function_name << \". Ignoring.\";\n return -1;\n }\n\n AMX* amx = fake_amx_->amx();\n\n size_t param_count = format ? strlen(format) : 0;\n\n params_.resize(param_count + 1);\n params_[0] = param_count * sizeof(cell);\n\n \/\/ Early-return if there are no arguments required for this native invication.\n if (!param_count)\n return function_iter->second(amx, params_.data());\n\n size_t arraySizeParamOffset = 1;\n\n \/\/ The CreateDynamicObjectEx method unfortunately follows a non-sensical parameter order, which\n \/\/ makes it different from every other method that accepts an array (or a string). Thank you.\n if (param_count == 15 && function_name == \"CreateDynamicObjectEx\")\n arraySizeParamOffset = 3;\n\n auto amx_stack = fake_amx_->GetScopedStackModifier();\n DCHECK(arguments);\n\n \/\/ Process the existing parameters, either store them in |params_| or push them on the stack.\n for (size_t i = 0; i < param_count; ++i) {\n switch (format[i]) {\n case 'i':\n params_[i + 1] = *reinterpret_cast(arguments[i]);\n break;\n case 'f':\n params_[i + 1] = amx_ftoc(*reinterpret_cast(arguments[i]));\n break;\n case 'r':\n params_[i + 1] = amx_stack.PushCell(*reinterpret_cast(arguments[i]));\n break;\n case 's':\n params_[i + 1] = amx_stack.PushString(reinterpret_cast(arguments[i]));\n break;\n case 'a':\n if (format[i + arraySizeParamOffset] != 'i') {\n LOG(WARNING) << \"Cannot invoke \" << function_name << \": 'a' parameter must be followed by a 'i'.\";\n return -1;\n }\n\n {\n int32_t size = *reinterpret_cast(arguments[i + arraySizeParamOffset]);\n\n params_[i + 1] = amx_stack.PushArray(reinterpret_cast(arguments[i]), size);\n if (arraySizeParamOffset == 1)\n params_[i + 1 + arraySizeParamOffset] = size;\n }\n\n if (arraySizeParamOffset == 1)\n ++i;\n\n break;\n }\n }\n\n const int return_value = function_iter->second(amx, params_.data());\n\n \/\/ Read back the values which may have been modified by the SA-MP server.\n for (size_t i = 0; i < param_count; ++i) {\n switch (format[i]) {\n case 'r':\n amx_stack.ReadCell(params_[i + 1], reinterpret_cast(arguments[i]));\n break;\n case 'a':\n {\n char* data = reinterpret_cast(arguments[i]);\n int32_t size = *reinterpret_cast(arguments[i + arraySizeParamOffset]);\n\n amx_stack.ReadArray(params_[i + 1], data, size);\n }\n break;\n }\n }\n\n return return_value;\n}\n\n} \/\/ namespace plugin\nUpdate the playgroundjs plugin for the latest streamer plugin syntax\/\/ Copyright 2015 Las Venturas Playground. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license, a copy of which can\n\/\/ be found in the LICENSE file.\n\n#include \"plugin\/native_function_manager.h\"\n\n#include \n\n#include \"base\/logging.h\"\n#include \"plugin\/fake_amx.h\"\n#include \"plugin\/sdk\/amx.h\"\n#include \"plugin\/sdk\/plugincommon.h\"\n#include \"third_party\/subhook\/subhook.h\"\n\nnamespace plugin {\n\nnamespace {\n\n\/\/ Type definition of the original amx_Register_t function that is being intercepted.\ntypedef int AMXAPI(*amx_Register_t)(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number);\n\n\/\/ Global instance of the NativeFunctionManager instance, only to be used by amx_Register_hook().\nNativeFunctionManager* g_native_function_manager = nullptr;\n\nint amx_Register_hook(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) {\n return g_native_function_manager->OnRegister(amx, nativelist, number);\n}\n\n} \/\/ namespace\n\nNativeFunctionManager::NativeFunctionManager()\n : fake_amx_(new FakeAMX) {\n g_native_function_manager = this;\n}\n\nNativeFunctionManager::~NativeFunctionManager() {\n g_native_function_manager = nullptr;\n}\n\nbool NativeFunctionManager::Install() {\n if (!pAMXFunctions)\n return true; \/\/ testing\n\n void* current_address = static_cast(pAMXFunctions)[PLUGIN_AMX_EXPORT_Register];\n if (current_address == nullptr) {\n LOG(ERROR) << \"Invalid address found for the amx_Register() function.\";\n return false;\n }\n\n hook_.reset(new SubHook(current_address, (void*) amx_Register_hook));\n if (!hook_->Install()) {\n LOG(ERROR) << \"Unable to install a SubHook for the amx_Register() function.\";\n return false;\n }\n\n return true;\n}\n\nint NativeFunctionManager::OnRegister(AMX* amx, const AMX_NATIVE_INFO* nativelist, int number) {\n if (nativelist != nullptr) {\n for (size_t index = 0; ; ++index) {\n if (nativelist[index].func == nullptr || nativelist[index].name == nullptr)\n break;\n\n const std::string native_name(nativelist[index].name);\n\n \/\/ The Pawn interpreter iterates over unresolved functions in the gamemode, and finds them in\n \/\/ the functions that are being registered in the amx_Register() call. This means that the first\n \/\/ function registered for a given name will be used, rather than having later registrations\n \/\/ override previous ones. Simply drop out if a double-registration is observed.\n if (!FunctionExists(native_name))\n native_functions_[native_name] = static_cast(nativelist[index].func);\n }\n }\n\n \/\/ Trampoline back to the original amx_Register function that we intercepted.\n return ((amx_Register_t) hook_->GetTrampoline())(amx, nativelist, number);\n}\n\nbool NativeFunctionManager::FunctionExists(const std::string& function_name) const {\n return native_functions_.find(function_name) != native_functions_.end();\n}\n\nint NativeFunctionManager::CallFunction(const std::string& function_name,\n const char* format, void** arguments) {\n auto function_iter = native_functions_.find(function_name);\n if (function_iter == native_functions_.end()) {\n LOG(WARNING) << \"Attempting to invoke unknown Pawn native \" << function_name << \". Ignoring.\";\n return -1;\n }\n\n AMX* amx = fake_amx_->amx();\n\n size_t param_count = format ? strlen(format) : 0;\n\n params_.resize(param_count + 1);\n params_[0] = param_count * sizeof(cell);\n\n \/\/ Early-return if there are no arguments required for this native invication.\n if (!param_count)\n return function_iter->second(amx, params_.data());\n\n size_t arraySizeParamOffset = 1;\n\n \/\/ The CreateDynamicObjectEx method unfortunately follows a non-sensical parameter order, which\n \/\/ makes it different from every other method that accepts an array (or a string). Thank you.\n if (param_count == 17 && function_name == \"CreateDynamicObjectEx\")\n arraySizeParamOffset = 4;\n\n auto amx_stack = fake_amx_->GetScopedStackModifier();\n DCHECK(arguments);\n\n \/\/ Process the existing parameters, either store them in |params_| or push them on the stack.\n for (size_t i = 0; i < param_count; ++i) {\n switch (format[i]) {\n case 'i':\n params_[i + 1] = *reinterpret_cast(arguments[i]);\n break;\n case 'f':\n params_[i + 1] = amx_ftoc(*reinterpret_cast(arguments[i]));\n break;\n case 'r':\n params_[i + 1] = amx_stack.PushCell(*reinterpret_cast(arguments[i]));\n break;\n case 's':\n params_[i + 1] = amx_stack.PushString(reinterpret_cast(arguments[i]));\n break;\n case 'a':\n if (format[i + arraySizeParamOffset] != 'i') {\n LOG(WARNING) << \"Cannot invoke \" << function_name << \": 'a' parameter must be followed by a 'i'.\";\n return -1;\n }\n\n {\n int32_t size = *reinterpret_cast(arguments[i + arraySizeParamOffset]);\n\n params_[i + 1] = amx_stack.PushArray(reinterpret_cast(arguments[i]), size);\n if (arraySizeParamOffset == 1)\n params_[i + 1 + arraySizeParamOffset] = size;\n }\n\n if (arraySizeParamOffset == 1)\n ++i;\n\n break;\n }\n }\n\n const int return_value = function_iter->second(amx, params_.data());\n\n \/\/ Read back the values which may have been modified by the SA-MP server.\n for (size_t i = 0; i < param_count; ++i) {\n switch (format[i]) {\n case 'r':\n amx_stack.ReadCell(params_[i + 1], reinterpret_cast(arguments[i]));\n break;\n case 'a':\n {\n char* data = reinterpret_cast(arguments[i]);\n int32_t size = *reinterpret_cast(arguments[i + arraySizeParamOffset]);\n\n amx_stack.ReadArray(params_[i + 1], data, size);\n }\n break;\n }\n }\n\n return return_value;\n}\n\n} \/\/ namespace plugin\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Implementation of oscillations of neutrinos in matter in a\n\/\/ three-neutrino framework with decoherence.\n\/\/\n\/\/ This class inherits from the PMNS_Fast class\n\/\/\n\/\/ jcoelho@apc.in2p3.fr\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n#include \"PMNS_Deco.h\"\n\nusing namespace OscProb;\n\nusing namespace std;\n\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Constructor. \\sa PMNS_Base::PMNS_Base\n\/\/\/\n\/\/\/ This class is restricted to 3 neutrino flavours.\n\/\/\/\nPMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),\nfRho(3, row(3,0))\n{\n SetStdPath();\n SetGamma(2,0);\n SetGamma(3,0);\n SetGH(true);\n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Nothing to clean.\n\/\/\/\nPMNS_Deco::~PMNS_Deco(){}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set any given decoherence parameter.\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ Requires that j > 0. Will notify you if input is wrong.\n\/\/\/\n\/\/\/ @param j - The second mass index\n\/\/\/ @param val - The absolute value of the parameter\n\/\/\/\nvoid PMNS_Deco::SetGamma(int j, double val){\n\n if(j < 2 || j > 3){\n cout << \"Gamma_\" << j << 1 << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Doing nothing.\" << endl;\n return;\n }\n\n fGotES *= (fGamma[j-1] == val);\n \n fGamma[j-1] = val;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence hierarchy. This will define the relationship:\n\/\/\/\n\/\/\/ \\Gamma_{32} = (\\sqrt{\\Gamma_{31}} \\pm \\sqrt{\\Gamma_{21}})^{2} \n\/\/\/\n\/\/\/ The + (-) sign will be refered to as IH (NH)\n\/\/\/\n\/\/\/ @param isNH - Is the hierarchy normal?\n\/\/\/\nvoid PMNS_Deco::SetGH(bool isNH)\n{\n\n fGamma[0] = isNH ? 1 : -1;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Get any given decoherence parameter.\n\/\/\/\n\/\/\/ Requires that i > j. Will notify you if input is wrong.\n\/\/\/ If i < j, will assume reverse order and swap i and j.\n\/\/\/\n\/\/\/ @param i - The first mass index\n\/\/\/ @param j - The second mass index\n\/\/\/\ndouble PMNS_Deco::GetGamma(int i, int j)\n{\n\n if(i < j){\n cout << \"First argument should be larger than second argument\" << endl;\n cout << \"Setting reverse order (Gamma_\" << j << i << \"). \" << endl;\n int temp = i;\n i = j;\n j = temp;\n }\n if(i<1 || i>3 || i <= j || j < 1){\n cout << \"Gamma_\" << i << j << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Returning 0.\" << endl;\n return 0;\n }\n\n if(j == 1){ \n return fGamma[i-1];\n }\n else {\n return pow( sqrt(fGamma[2]) - fGamma[0]*sqrt(fGamma[1]), 2);\n }\n\n}\n\n\/\/.....................................................................\n\/\/\/ Dot product of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A.B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n for(int k=0; k<3; k++){\n\n out[i][j] += A[i][k] * B[k][j];\n\n }}}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Product of elements of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A * B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += A[i][j] * B[i][j];\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Conjugate transpose matrix.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/\n\/\/\/ @return - A^{\\dagger}\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += conj(A[j][i]);\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/\n\/\/\/ Propagate the current neutrino state through a given path\n\/\/\/ @param p - A neutrino path segment\n\/\/\/\nvoid PMNS_Deco::PropagatePath(NuPath p)\n{\n\n \/\/ Set the neutrino path\n SetCurPath(p);\n\n \/\/ Solve for eigensystem\n SolveHam();\n \n \/\/ Store rotation matrices\n matrix U = fEvec;\n matrix Ut = CTransp(fEvec);\n\n \/\/ Rotate to effective mass basis\n fRho = Dot(Ut, Dot(fRho, U));\n \n \/\/ Compute evolution matrix\n matrix evolve(3, row(3,1));\n \n \/\/ Some ugly way of matching gamma and dmsqr indices\n int maxdm = 0; \n if(fDm[1] > fDm[maxdm]) maxdm = 1;\n if(fDm[2] > fDm[maxdm]) maxdm = 2;\n\n int mindm = 0; \n if(fDm[1] < fDm[mindm]) mindm = 1;\n if(fDm[2] < fDm[mindm]) mindm = 2;\n\n int middm = 0;\n if(middm == maxdm || middm == mindm) middm = 1; \n if(middm == maxdm || middm == mindm) middm = 2; \n\n int maxev = 0; \n if(fEval[1] > fEval[maxev]) maxev = 1;\n if(fEval[2] > fEval[maxev]) maxev = 2;\n\n int minev = 0; \n if(fEval[1] < fEval[minev]) minev = 1;\n if(fEval[2] < fEval[minev]) minev = 2;\n\n int midev = 0;\n if(midev == maxev || midev == minev) midev = 1; \n if(midev == maxev || midev == minev) midev = 2; \n \n int idx[3];\n idx[minev] = mindm;\n idx[midev] = middm;\n idx[maxev] = maxdm;\n \n for(int j=0; j<3; j++){ \n for(int i=0; i\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino starting flavour.\n\/\/\/\nvoid PMNS_Deco::ResetToFlavour(int flv)\n{\n assert(flv>=0 && flv\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino final flavour.\n\/\/\/\n\/\/\/ @return Neutrino oscillation probability\n\/\/\/\ndouble PMNS_Deco::P(int flv)\n{\n assert(flv>=0 && flvFix latex formulas\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Implementation of oscillations of neutrinos in matter in a\n\/\/ three-neutrino framework with decoherence.\n\/\/\n\/\/ This class inherits from the PMNS_Fast class\n\/\/\n\/\/ jcoelho@apc.in2p3.fr\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n\n#include \"PMNS_Deco.h\"\n\nusing namespace OscProb;\n\nusing namespace std;\n\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Constructor. \\sa PMNS_Base::PMNS_Base\n\/\/\/\n\/\/\/ This class is restricted to 3 neutrino flavours.\n\/\/\/\nPMNS_Deco::PMNS_Deco() : PMNS_Fast(), fGamma(),\nfRho(3, row(3,0))\n{\n SetStdPath();\n SetGamma(2,0);\n SetGamma(3,0);\n SetGH(true);\n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Nothing to clean.\n\/\/\/\nPMNS_Deco::~PMNS_Deco(){}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set any given decoherence parameter.\n\/\/\/\n\/\/\/ This will check if value is changing to keep track of whether\n\/\/\/ the eigensystem needs to be recomputed.\n\/\/\/\n\/\/\/ Requires that j > 0. Will notify you if input is wrong.\n\/\/\/\n\/\/\/ @param j - The second mass index\n\/\/\/ @param val - The absolute value of the parameter\n\/\/\/\nvoid PMNS_Deco::SetGamma(int j, double val){\n\n if(j < 2 || j > 3){\n cout << \"Gamma_\" << j << 1 << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Doing nothing.\" << endl;\n return;\n }\n\n fGotES *= (fGamma[j-1] == val);\n \n fGamma[j-1] = val;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Set the decoherence hierarchy. This will define the relationship:\n\/\/\/\n\/\/\/ \\f$\\Gamma_{32} = (\\sqrt{\\Gamma_{31}} \\pm \\sqrt{\\Gamma_{21}})^{2}\\f$\n\/\/\/\n\/\/\/ The + (-) sign will be refered to as IH (NH)\n\/\/\/\n\/\/\/ @param isNH - Is the hierarchy normal?\n\/\/\/\nvoid PMNS_Deco::SetGH(bool isNH)\n{\n\n fGamma[0] = isNH ? 1 : -1;\n \n}\n\n\/\/......................................................................\n\/\/\/\n\/\/\/ Get any given decoherence parameter.\n\/\/\/\n\/\/\/ Requires that i > j. Will notify you if input is wrong.\n\/\/\/ If i < j, will assume reverse order and swap i and j.\n\/\/\/\n\/\/\/ @param i - The first mass index\n\/\/\/ @param j - The second mass index\n\/\/\/\ndouble PMNS_Deco::GetGamma(int i, int j)\n{\n\n if(i < j){\n cout << \"First argument should be larger than second argument\" << endl;\n cout << \"Setting reverse order (Gamma_\" << j << i << \"). \" << endl;\n int temp = i;\n i = j;\n j = temp;\n }\n if(i<1 || i>3 || i <= j || j < 1){\n cout << \"Gamma_\" << i << j << \" not valid for \" << fNumNus;\n cout << \" neutrinos. Returning 0.\" << endl;\n return 0;\n }\n\n if(j == 1){ \n return fGamma[i-1];\n }\n else {\n return pow( sqrt(fGamma[2]) - fGamma[0]*sqrt(fGamma[1]), 2);\n }\n\n}\n\n\/\/.....................................................................\n\/\/\/ Dot product of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A.B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Dot(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n for(int k=0; k<3; k++){\n\n out[i][j] += A[i][k] * B[k][j];\n\n }}}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Product of elements of two matrices.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/ @param B - input matrix B\n\/\/\/\n\/\/\/ @return - matrix A * B\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::Mult(matrix A, matrix B)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += A[i][j] * B[i][j];\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/ Conjugate transpose matrix.\n\/\/\/\n\/\/\/ @param A - input matrix A\n\/\/\/\n\/\/\/ @return - \\f$A^{\\dagger}\\f$\n\/\/\/\nPMNS_Deco::matrix PMNS_Deco::CTransp(matrix A)\n{\n\n matrix out(3, row(3,0));\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n \n out[i][j] += conj(A[j][i]);\n\n }}\n \n return out;\n\n}\n\n\/\/.....................................................................\n\/\/\/\n\/\/\/ Propagate the current neutrino state through a given path\n\/\/\/ @param p - A neutrino path segment\n\/\/\/\nvoid PMNS_Deco::PropagatePath(NuPath p)\n{\n\n \/\/ Set the neutrino path\n SetCurPath(p);\n\n \/\/ Solve for eigensystem\n SolveHam();\n \n \/\/ Store rotation matrices\n matrix U = fEvec;\n matrix Ut = CTransp(fEvec);\n\n \/\/ Rotate to effective mass basis\n fRho = Dot(Ut, Dot(fRho, U));\n \n \/\/ Compute evolution matrix\n matrix evolve(3, row(3,1));\n \n \/\/ Some ugly way of matching gamma and dmsqr indices\n int maxdm = 0; \n if(fDm[1] > fDm[maxdm]) maxdm = 1;\n if(fDm[2] > fDm[maxdm]) maxdm = 2;\n\n int mindm = 0; \n if(fDm[1] < fDm[mindm]) mindm = 1;\n if(fDm[2] < fDm[mindm]) mindm = 2;\n\n int middm = 0;\n if(middm == maxdm || middm == mindm) middm = 1; \n if(middm == maxdm || middm == mindm) middm = 2; \n\n int maxev = 0; \n if(fEval[1] > fEval[maxev]) maxev = 1;\n if(fEval[2] > fEval[maxev]) maxev = 2;\n\n int minev = 0; \n if(fEval[1] < fEval[minev]) minev = 1;\n if(fEval[2] < fEval[minev]) minev = 2;\n\n int midev = 0;\n if(midev == maxev || midev == minev) midev = 1; \n if(midev == maxev || midev == minev) midev = 2; \n \n int idx[3];\n idx[minev] = mindm;\n idx[midev] = middm;\n idx[maxev] = maxdm;\n \n for(int j=0; j<3; j++){ \n for(int i=0; i\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino starting flavour.\n\/\/\/\nvoid PMNS_Deco::ResetToFlavour(int flv)\n{\n assert(flv>=0 && flv\n\/\/\/ 0 = nue, 1 = numu, 2 = nutau\n\/\/\/ 3 = sterile_1, 4 = sterile_2, etc.\n\/\/\/ <\/pre>\n\/\/\/ @param flv - The neutrino final flavour.\n\/\/\/\n\/\/\/ @return Neutrino oscillation probability\n\/\/\/\ndouble PMNS_Deco::P(int flv)\n{\n assert(flv>=0 && flv"} {"text":"\/*\n * Copyright (c) 2003-2007 Rony Shapiro .\n * All rights reserved. Use of the code is allowed under the\n * Artistic License terms, as specified in the LICENSE file\n * distributed with this code, or available from\n * http:\/\/www.opensource.org\/licenses\/artistic-license.php\n *\/\n\/\/ PWHistDlg.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n\n#include \"PasswordSafe.h\"\n#include \"ThisMfcApp.h\"\n#include \"resource.h\"\n#include \"resource3.h\" \/\/ String resources\n#include \"PWHistDlg.h\"\n#include \"corelib\/ItemData.h\"\n#include \"corelib\/PWSprefs.h\"\n\n\n\/\/ CPWHistDlg dialog\n\nIMPLEMENT_DYNAMIC(CPWHistDlg, CDialog)\nCPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly,\n CMyString &HistStr, PWHistList &PWHistList,\n size_t NumPWHistory, size_t &MaxPWHistory,\n BOOL &SavePWHistory)\n: CDialog(CPWHistDlg::IDD, pParent),\n m_IsReadOnly(IsReadOnly),\n m_HistStr(HistStr), m_PWHistList(PWHistList),\n m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory),\n m_SavePWHistory(SavePWHistory),\n m_ClearPWHistory(false),\n m_iSortedColumn(-1), m_bSortAscending(TRUE)\n{\n m_oldMaxPWHistory = m_MaxPWHistory;\n}\n\nCPWHistDlg::~CPWHistDlg()\n{\n}\n\nvoid CPWHistDlg::DoDataExchange(CDataExchange* pDX)\n{\n CDialog::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl);\n DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory);\n DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory);\n DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 255);\n}\n\n\nBEGIN_MESSAGE_MAP(CPWHistDlg, CDialog)\nON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist)\nON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory)\nON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)\nON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)\nON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick)\nON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll)\nEND_MESSAGE_MAP()\n\nBOOL CPWHistDlg::OnInitDialog() \n{\n CDialog::OnInitDialog();\n\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);\n\n BOOL bpwh_count = m_PWHistList.empty() ? FALSE : TRUE;\n GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count);\n GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count);\n\n if (m_IsReadOnly) {\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(FALSE);\n GetDlgItem(IDC_PWHSPIN)->EnableWindow(FALSE);\n GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE);\n GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE); \/\/ overrides count\n }\n\n m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);\n CString cs_text;\n cs_text.LoadString(IDS_SETDATETIME);\n m_PWHistListCtrl.InsertColumn(0, cs_text);\n cs_text.LoadString(IDS_PASSWORD);\n m_PWHistListCtrl.InsertColumn(1, cs_text);\n\n PWHistList::iterator iter;\n DWORD nIdx;\n for (iter = m_PWHistList.begin(), nIdx = 0;\n iter != m_PWHistList.end(); iter++, nIdx++) {\n int nPos;\n const PWHistEntry pwhentry = *iter;\n if (pwhentry.changedate != _T(\"1970-01-01 00:00:00\"))\n nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate);\n else {\n cs_text.LoadString(IDS_UNKNOWN);\n cs_text.Trim();\n nPos = m_PWHistListCtrl.InsertItem(nPos, cs_text);\n }\n m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password);\n m_PWHistListCtrl.SetItemData(nPos, nIdx);\n }\n\n m_PWHistListCtrl.SetRedraw(FALSE);\n for (int i = 0; i < 2; i++) {\n m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);\n int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i);\n m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);\n int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i);\n m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));\n }\n m_PWHistListCtrl.SetRedraw(TRUE);\n\n TCHAR buffer[10];\n#if _MSC_VER >= 1400\n _stprintf_s(buffer, 10, _T(\"%d\"), m_NumPWHistory);\n#else\n _stprintf(buffer, _T(\"%d\"), m_NumPWHistory);\n#endif\n\n CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);\n\n if (m_MaxPWHistory == 0)\n m_MaxPWHistory = PWSprefs::GetInstance()->\n \t\t\tGetPref(PWSprefs::NumPWHistoryDefault);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY));\n pspin->SetRange(1, 255);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxPWHistory);\n \n return TRUE;\n}\n\n\n\/\/ CPWHistDlg message handlers\nvoid CPWHistDlg::OnBnClickedClearPWHist()\n{\n m_ClearPWHistory = true;\n m_PWHistListCtrl.DeleteAllItems();\n}\n\nvoid\nCPWHistDlg::OnOK() \n{\n if (UpdateData(TRUE) != TRUE)\n\t return;\n\n \/* Handle history header.\n * Header is in the form fmmnn, where:\n * f = {0,1} if password history is on\/off\n * mm = 2 digits max size of history list\n * nn = 2 digits current size of history list\n *\n * Special case: history empty and password history off - do nothing\n *\/\n\n\n if (m_ClearPWHistory == TRUE) {\n m_PWHistList.erase(m_PWHistList.begin(), m_PWHistList.end());\n m_HistStr = m_HistStr.Left(5);\n }\n\n if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) {\n TCHAR buffer[6];\n#if _MSC_VER >= 1400\n _stprintf_s\n#else\n _stprintf\n#endif\n (buffer,\n#if _MSC_VER >= 1400\n 6,\n#endif\n _T(\"%1x%02x%02x\"),\n (m_SavePWHistory == FALSE) ? 0 : 1,\n m_MaxPWHistory,\n m_PWHistList.size()\n );\n if (m_HistStr.GetLength() >= 5) {\n for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]);\n } else {\n m_HistStr = buffer;\n }\n }\n CDialog::OnOK();\n}\n\nvoid\nCPWHistDlg::OnCheckedSavePasswordHistory()\n{\n m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck();\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);\n}\n\nvoid\nCPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*)\n{\n LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR;\n ASSERT(lpnmitem != NULL);\n int item = lpnmitem->iItem;\n if (item == -1)\n\t return;\n size_t itempos = size_t(m_PWHistListCtrl.GetItemData(item));\n const PWHistEntry pwhentry = m_PWHistList[itempos];\n app.SetClipboardData(pwhentry.password);\n}\n\nvoid\nCPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)\n{\n HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;\n\n if(phdn->iButton == 0) {\n \/\/ User clicked on header using left mouse button\n if(phdn->iItem == m_iSortedColumn)\n m_bSortAscending = !m_bSortAscending;\n else\n m_bSortAscending = TRUE;\n\n m_iSortedColumn = phdn->iItem;\n m_PWHistListCtrl.SortItems(PWHistCompareFunc, (LPARAM)this);\n\n \/\/ Note: WINVER defines the minimum system level for which this is program compiled and\n \/\/ NOT the level of system it is running on!\n \/\/ In this case, these values are defined in Windows XP and later and supported\n \/\/ by V6 of comctl32.dll (supplied with Windows XP) and later.\n \/\/ They should be ignored by earlier levels of this dll or .....\n \/\/ we can check the dll version (code available on request)!\n\n#if (WINVER < 0x0501)\t\/\/ These are already defined for WinXP and later\n#define HDF_SORTUP 0x0400\n#define HDF_SORTDOWN 0x0200\n#endif\n HDITEM HeaderItem;\n HeaderItem.mask = HDI_FORMAT;\n m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);\n \/\/ Turn off all arrows\n HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);\n \/\/ Turn on the correct arrow\n HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);\n m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);\n }\n\n *pResult = 0;\n}\n\nint CALLBACK CPWHistDlg::PWHistCompareFunc(LPARAM lParam1, LPARAM lParam2,\n LPARAM closure)\n{\n CPWHistDlg *self = (CPWHistDlg*)closure;\n int nSortColumn = self->m_iSortedColumn;\n size_t Lpos = (size_t)lParam1;\n size_t Rpos = (size_t)lParam2;\n const PWHistEntry pLHS = self->m_PWHistList[Lpos];\n const PWHistEntry pRHS = self->m_PWHistList[Rpos];\n CMyString password1, changedate1;\n CMyString password2, changedate2;\n time_t t1, t2;\n\n int iResult;\n switch(nSortColumn) {\n case 0:\n t1 = pLHS.changetttdate;\n t2 = pRHS.changetttdate;\n iResult = ((long) t1 < (long) t2) ? -1 : 1;\n break;\n case 1:\n password1 = pLHS.password;\n password2 = pRHS.password;\n iResult = ((CString)password1).Compare(password2);\n break;\n default:\n iResult = 0; \/\/ should never happen - just keep compiler happy\n ASSERT(FALSE);\n }\n\n if (!self->m_bSortAscending)\n iResult *= -1;\n\n return iResult;\n}\n\nvoid CPWHistDlg::OnBnClickedPwhCopyAll()\n{\n CMyString HistStr;\n PWHistList::iterator iter;\n\n for (iter = m_PWHistList.begin(); iter != m_PWHistList.end(); iter++) {\n const PWHistEntry &ent = *iter;\n HistStr += ent.changedate;\n HistStr += _T(\"\\t\");\n HistStr += ent.password;\n HistStr += _T(\"\\r\\n\");\n }\n app.SetClipboardData(HistStr);\n}\nmurphy.\/*\n * Copyright (c) 2003-2007 Rony Shapiro .\n * All rights reserved. Use of the code is allowed under the\n * Artistic License terms, as specified in the LICENSE file\n * distributed with this code, or available from\n * http:\/\/www.opensource.org\/licenses\/artistic-license.php\n *\/\n\/\/ PWHistDlg.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n\n#include \"PasswordSafe.h\"\n#include \"ThisMfcApp.h\"\n#include \"resource.h\"\n#include \"resource3.h\" \/\/ String resources\n#include \"PWHistDlg.h\"\n#include \"corelib\/ItemData.h\"\n#include \"corelib\/PWSprefs.h\"\n\n\n\/\/ CPWHistDlg dialog\n\nIMPLEMENT_DYNAMIC(CPWHistDlg, CDialog)\nCPWHistDlg::CPWHistDlg(CWnd* pParent, bool IsReadOnly,\n CMyString &HistStr, PWHistList &PWHistList,\n size_t NumPWHistory, size_t &MaxPWHistory,\n BOOL &SavePWHistory)\n: CDialog(CPWHistDlg::IDD, pParent),\n m_IsReadOnly(IsReadOnly),\n m_HistStr(HistStr), m_PWHistList(PWHistList),\n m_NumPWHistory(NumPWHistory), m_MaxPWHistory(MaxPWHistory),\n m_SavePWHistory(SavePWHistory),\n m_ClearPWHistory(false),\n m_iSortedColumn(-1), m_bSortAscending(TRUE)\n{\n m_oldMaxPWHistory = m_MaxPWHistory;\n}\n\nCPWHistDlg::~CPWHistDlg()\n{\n}\n\nvoid CPWHistDlg::DoDataExchange(CDataExchange* pDX)\n{\n CDialog::DoDataExchange(pDX);\n DDX_Control(pDX, IDC_PWHISTORY_LIST, m_PWHistListCtrl);\n DDX_Check(pDX, IDC_SAVE_PWHIST, m_SavePWHistory);\n DDX_Text(pDX, IDC_MAXPWHISTORY, m_MaxPWHistory);\n DDV_MinMaxInt(pDX, m_MaxPWHistory, 1, 255);\n}\n\n\nBEGIN_MESSAGE_MAP(CPWHistDlg, CDialog)\nON_BN_CLICKED(IDC_CLEAR_PWHIST, OnBnClickedClearPWHist)\nON_BN_CLICKED(IDC_SAVE_PWHIST, OnCheckedSavePasswordHistory)\nON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked)\nON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked)\nON_NOTIFY(NM_CLICK, IDC_PWHISTORY_LIST, OnHistListClick)\nON_BN_CLICKED(IDC_PWH_COPY_ALL, OnBnClickedPwhCopyAll)\nEND_MESSAGE_MAP()\n\nBOOL CPWHistDlg::OnInitDialog() \n{\n CDialog::OnInitDialog();\n\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);\n\n BOOL bpwh_count = m_PWHistList.empty() ? FALSE : TRUE;\n GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(bpwh_count);\n GetDlgItem(IDC_PWHISTORY_LIST)->EnableWindow(bpwh_count);\n\n if (m_IsReadOnly) {\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(FALSE);\n GetDlgItem(IDC_PWHSPIN)->EnableWindow(FALSE);\n GetDlgItem(IDC_SAVE_PWHIST)->EnableWindow(FALSE);\n GetDlgItem(IDC_CLEAR_PWHIST)->EnableWindow(FALSE); \/\/ overrides count\n }\n\n m_PWHistListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);\n CString cs_text;\n cs_text.LoadString(IDS_SETDATETIME);\n m_PWHistListCtrl.InsertColumn(0, cs_text);\n cs_text.LoadString(IDS_PASSWORD);\n m_PWHistListCtrl.InsertColumn(1, cs_text);\n\n PWHistList::iterator iter;\n DWORD nIdx;\n for (iter = m_PWHistList.begin(), nIdx = 0;\n iter != m_PWHistList.end(); iter++, nIdx++) {\n int nPos = 0;\n const PWHistEntry pwhentry = *iter;\n if (pwhentry.changedate != _T(\"1970-01-01 00:00:00\"))\n nPos = m_PWHistListCtrl.InsertItem(nPos, pwhentry.changedate);\n else {\n cs_text.LoadString(IDS_UNKNOWN);\n cs_text.Trim();\n nPos = m_PWHistListCtrl.InsertItem(nPos, cs_text);\n }\n m_PWHistListCtrl.SetItemText(nPos, 1, pwhentry.password);\n m_PWHistListCtrl.SetItemData(nPos, nIdx);\n }\n\n m_PWHistListCtrl.SetRedraw(FALSE);\n for (int i = 0; i < 2; i++) {\n m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE);\n int nColumnWidth = m_PWHistListCtrl.GetColumnWidth(i);\n m_PWHistListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER);\n int nHeaderWidth = m_PWHistListCtrl.GetColumnWidth(i);\n m_PWHistListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth));\n }\n m_PWHistListCtrl.SetRedraw(TRUE);\n\n TCHAR buffer[10];\n#if _MSC_VER >= 1400\n _stprintf_s(buffer, 10, _T(\"%d\"), m_NumPWHistory);\n#else\n _stprintf(buffer, _T(\"%d\"), m_NumPWHistory);\n#endif\n\n CSpinButtonCtrl* pspin = (CSpinButtonCtrl *)GetDlgItem(IDC_PWHSPIN);\n\n if (m_MaxPWHistory == 0)\n m_MaxPWHistory = PWSprefs::GetInstance()->\n \t\t\tGetPref(PWSprefs::NumPWHistoryDefault);\n\n pspin->SetBuddy(GetDlgItem(IDC_MAXPWHISTORY));\n pspin->SetRange(1, 255);\n pspin->SetBase(10);\n pspin->SetPos(m_MaxPWHistory);\n \n return TRUE;\n}\n\n\n\/\/ CPWHistDlg message handlers\nvoid CPWHistDlg::OnBnClickedClearPWHist()\n{\n m_ClearPWHistory = true;\n m_PWHistListCtrl.DeleteAllItems();\n}\n\nvoid\nCPWHistDlg::OnOK() \n{\n if (UpdateData(TRUE) != TRUE)\n\t return;\n\n \/* Handle history header.\n * Header is in the form fmmnn, where:\n * f = {0,1} if password history is on\/off\n * mm = 2 digits max size of history list\n * nn = 2 digits current size of history list\n *\n * Special case: history empty and password history off - do nothing\n *\/\n\n\n if (m_ClearPWHistory == TRUE) {\n m_PWHistList.erase(m_PWHistList.begin(), m_PWHistList.end());\n m_HistStr = m_HistStr.Left(5);\n }\n\n if (!(m_HistStr.IsEmpty() && m_SavePWHistory == FALSE)) {\n TCHAR buffer[6];\n#if _MSC_VER >= 1400\n _stprintf_s\n#else\n _stprintf\n#endif\n (buffer,\n#if _MSC_VER >= 1400\n 6,\n#endif\n _T(\"%1x%02x%02x\"),\n (m_SavePWHistory == FALSE) ? 0 : 1,\n m_MaxPWHistory,\n m_PWHistList.size()\n );\n if (m_HistStr.GetLength() >= 5) {\n for (int i = 0; i < 5; i++) m_HistStr.SetAt(i, buffer[i]);\n } else {\n m_HistStr = buffer;\n }\n }\n CDialog::OnOK();\n}\n\nvoid\nCPWHistDlg::OnCheckedSavePasswordHistory()\n{\n m_SavePWHistory = ((CButton*)GetDlgItem(IDC_SAVE_PWHIST))->GetCheck();\n GetDlgItem(IDC_MAXPWHISTORY)->EnableWindow(m_SavePWHistory ? TRUE : FALSE);\n}\n\nvoid\nCPWHistDlg::OnHistListClick(NMHDR* pNMHDR, LRESULT*)\n{\n LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pNMHDR;\n ASSERT(lpnmitem != NULL);\n int item = lpnmitem->iItem;\n if (item == -1)\n\t return;\n size_t itempos = size_t(m_PWHistListCtrl.GetItemData(item));\n const PWHistEntry pwhentry = m_PWHistList[itempos];\n app.SetClipboardData(pwhentry.password);\n}\n\nvoid\nCPWHistDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult)\n{\n HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR;\n\n if(phdn->iButton == 0) {\n \/\/ User clicked on header using left mouse button\n if(phdn->iItem == m_iSortedColumn)\n m_bSortAscending = !m_bSortAscending;\n else\n m_bSortAscending = TRUE;\n\n m_iSortedColumn = phdn->iItem;\n m_PWHistListCtrl.SortItems(PWHistCompareFunc, (LPARAM)this);\n\n \/\/ Note: WINVER defines the minimum system level for which this is program compiled and\n \/\/ NOT the level of system it is running on!\n \/\/ In this case, these values are defined in Windows XP and later and supported\n \/\/ by V6 of comctl32.dll (supplied with Windows XP) and later.\n \/\/ They should be ignored by earlier levels of this dll or .....\n \/\/ we can check the dll version (code available on request)!\n\n#if (WINVER < 0x0501)\t\/\/ These are already defined for WinXP and later\n#define HDF_SORTUP 0x0400\n#define HDF_SORTDOWN 0x0200\n#endif\n HDITEM HeaderItem;\n HeaderItem.mask = HDI_FORMAT;\n m_PWHistListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem);\n \/\/ Turn off all arrows\n HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN);\n \/\/ Turn on the correct arrow\n HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN);\n m_PWHistListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem);\n }\n\n *pResult = 0;\n}\n\nint CALLBACK CPWHistDlg::PWHistCompareFunc(LPARAM lParam1, LPARAM lParam2,\n LPARAM closure)\n{\n CPWHistDlg *self = (CPWHistDlg*)closure;\n int nSortColumn = self->m_iSortedColumn;\n size_t Lpos = (size_t)lParam1;\n size_t Rpos = (size_t)lParam2;\n const PWHistEntry pLHS = self->m_PWHistList[Lpos];\n const PWHistEntry pRHS = self->m_PWHistList[Rpos];\n CMyString password1, changedate1;\n CMyString password2, changedate2;\n time_t t1, t2;\n\n int iResult;\n switch(nSortColumn) {\n case 0:\n t1 = pLHS.changetttdate;\n t2 = pRHS.changetttdate;\n iResult = ((long) t1 < (long) t2) ? -1 : 1;\n break;\n case 1:\n password1 = pLHS.password;\n password2 = pRHS.password;\n iResult = ((CString)password1).Compare(password2);\n break;\n default:\n iResult = 0; \/\/ should never happen - just keep compiler happy\n ASSERT(FALSE);\n }\n\n if (!self->m_bSortAscending)\n iResult *= -1;\n\n return iResult;\n}\n\nvoid CPWHistDlg::OnBnClickedPwhCopyAll()\n{\n CMyString HistStr;\n PWHistList::iterator iter;\n\n for (iter = m_PWHistList.begin(); iter != m_PWHistList.end(); iter++) {\n const PWHistEntry &ent = *iter;\n HistStr += ent.changedate;\n HistStr += _T(\"\\t\");\n HistStr += ent.password;\n HistStr += _T(\"\\r\\n\");\n }\n app.SetClipboardData(HistStr);\n}\n<|endoftext|>"} {"text":"#include \"HalideRuntime.h\"\n#include \"printer.h\"\n#include \"scoped_mutex_lock.h\"\n\n#define USE_AGL 0\n#if USE_AGL\nextern \"C\" void *aglChoosePixelFormat(void *, int, const int *);\nextern \"C\" void *aglCreateContext(void *, void *);\nextern \"C\" int aglGetError();\nextern \"C\" void aglDestroyPixelFormat(void *);\nextern \"C\" unsigned char aglSetCurrentContext(void *);\n#endif\n\nextern \"C\" {\n\n#if !USE_AGL\nnamespace Halide { namespace Runtime { namespace Internal { namespace OpenGL {\n\nWEAK halide_mutex cgl_functions_mutex;\nWEAK bool cgl_initialized = false;\nWEAK int (*CGLChoosePixelFormat)(int *attributes, void **pixel_format_result, int *num_formats);\nWEAK int (*CGLCreateContext)(void *pixel_format, void *share_context, void **context_Result);\nWEAK int (*CGLDestroyPixelFormat)(void *);\nWEAK int (*CGLSetCurrentContext)(void *);\n\n}}}}\n\nusing namespace Halide::Runtime::Internal::OpenGL;\n#endif\n\nWEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) {\n static void *dylib = NULL;\n if (!dylib) {\n dylib = halide_load_library(\n \"\/System\/Library\/Frameworks\/OpenGL.framework\/Versions\/Current\/OpenGL\");\n if (!dylib) return NULL;\n }\n return halide_get_library_symbol(dylib, name);\n}\n\n\/\/ Initialize OpenGL\nWEAK int halide_opengl_create_context(void *user_context) {\n#if USE_AGL\n void *ctx = NULL;\n\n int attrib[] = {4 \/* AGL_RGBA *\/, 0 \/* Sentinel *\/};\n void *pf = aglChoosePixelFormat(NULL, 0, attrib);\n if (!pf) {\n halide_error(user_context, \"Could not create pixel format\\n\");\n return -1;\n }\n ctx = aglCreateContext(pf, NULL);\n if (!ctx || aglGetError()) {\n halide_error(user_context, \"Could not create context\\n\");\n return -1;\n }\n aglDestroyPixelFormat(pf);\n if (!aglSetCurrentContext(ctx)) {\n halide_error(user_context, \"Could not activate OpenGL context\\n\");\n return -1;\n }\n#else\n { \/\/ locking scope\n ScopedMutexLock lock(&cgl_functions_mutex);\n\n if (!cgl_initialized) {\n if ((CGLChoosePixelFormat =\n (int (*)(int *, void **, int *))halide_opengl_get_proc_address(user_context, \"CGLChoosePixelFormat\")) == NULL) {\n return -1;\n }\n if ((CGLCreateContext =\n (int (*)(void *, void *, void**))halide_opengl_get_proc_address(user_context, \"CGLCreateContext\")) == NULL) {\n return -1;\n }\n if ((CGLDestroyPixelFormat =\n (int (*)(void *))halide_opengl_get_proc_address(user_context, \"CGLDestroyPixelFormat\")) == NULL) {\n return -1;\n }\n if ((CGLSetCurrentContext =\n (int (*)(void *))halide_opengl_get_proc_address(user_context, \"CGLSetCurrentContext\")) == NULL) {\n return -1;\n }\n }\n cgl_initialized = true;\n }\n\n void *ctx = NULL;\n int attribs[] = { \/* 5 kCGLPFADoubleBuffer *\/\n 72, \/\/ kCGLPFANoRecovery\n 96, \/\/ kCGLPFAAllowOfflineRenderers\n 99, \/\/ kCGLPFAOpenGLProfile\n 0x1000, \/\/ kCGLOGLPVersion_Legacy -- 0x3200 is kCGLOGLPVersion_3_2_Core -- kCGLOGLPVersion_GL4_Core is 0x4100\n 0 \/\/ sentinel ending list\n };\n\n void *fmt;\n int numFormats = 0;\n if (CGLChoosePixelFormat(attribs, &fmt, &numFormats) != 0) {\n return -1;\n }\n if (CGLCreateContext(fmt, NULL, &ctx) != 0) {\n CGLDestroyPixelFormat(fmt);\n return -1;\n }\n CGLSetCurrentContext(ctx);\n#endif\n return 0;\n}\n\n}\nRemove extern “C” from symbols defined in Halide::Runtime::Internal::OpenGL #include \"HalideRuntime.h\"\n#include \"printer.h\"\n#include \"scoped_mutex_lock.h\"\n\n#define USE_AGL 0\n#if USE_AGL\nextern \"C\" void *aglChoosePixelFormat(void *, int, const int *);\nextern \"C\" void *aglCreateContext(void *, void *);\nextern \"C\" int aglGetError();\nextern \"C\" void aglDestroyPixelFormat(void *);\nextern \"C\" unsigned char aglSetCurrentContext(void *);\n#endif\n\n#if !USE_AGL\nnamespace Halide { namespace Runtime { namespace Internal { namespace OpenGL {\n\nWEAK halide_mutex cgl_functions_mutex;\nWEAK bool cgl_initialized = false;\nWEAK int (*CGLChoosePixelFormat)(int *attributes, void **pixel_format_result, int *num_formats);\nWEAK int (*CGLCreateContext)(void *pixel_format, void *share_context, void **context_Result);\nWEAK int (*CGLDestroyPixelFormat)(void *);\nWEAK int (*CGLSetCurrentContext)(void *);\n\n}}}}\n\nusing namespace Halide::Runtime::Internal::OpenGL;\n#endif\n\nextern \"C\" {\n\nWEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) {\n static void *dylib = NULL;\n if (!dylib) {\n dylib = halide_load_library(\n \"\/System\/Library\/Frameworks\/OpenGL.framework\/Versions\/Current\/OpenGL\");\n if (!dylib) return NULL;\n }\n return halide_get_library_symbol(dylib, name);\n}\n\n\/\/ Initialize OpenGL\nWEAK int halide_opengl_create_context(void *user_context) {\n#if USE_AGL\n void *ctx = NULL;\n\n int attrib[] = {4 \/* AGL_RGBA *\/, 0 \/* Sentinel *\/};\n void *pf = aglChoosePixelFormat(NULL, 0, attrib);\n if (!pf) {\n halide_error(user_context, \"Could not create pixel format\\n\");\n return -1;\n }\n ctx = aglCreateContext(pf, NULL);\n if (!ctx || aglGetError()) {\n halide_error(user_context, \"Could not create context\\n\");\n return -1;\n }\n aglDestroyPixelFormat(pf);\n if (!aglSetCurrentContext(ctx)) {\n halide_error(user_context, \"Could not activate OpenGL context\\n\");\n return -1;\n }\n#else\n { \/\/ locking scope\n ScopedMutexLock lock(&cgl_functions_mutex);\n\n if (!cgl_initialized) {\n if ((CGLChoosePixelFormat =\n (int (*)(int *, void **, int *))halide_opengl_get_proc_address(user_context, \"CGLChoosePixelFormat\")) == NULL) {\n return -1;\n }\n if ((CGLCreateContext =\n (int (*)(void *, void *, void**))halide_opengl_get_proc_address(user_context, \"CGLCreateContext\")) == NULL) {\n return -1;\n }\n if ((CGLDestroyPixelFormat =\n (int (*)(void *))halide_opengl_get_proc_address(user_context, \"CGLDestroyPixelFormat\")) == NULL) {\n return -1;\n }\n if ((CGLSetCurrentContext =\n (int (*)(void *))halide_opengl_get_proc_address(user_context, \"CGLSetCurrentContext\")) == NULL) {\n return -1;\n }\n }\n cgl_initialized = true;\n }\n\n void *ctx = NULL;\n int attribs[] = { \/* 5 kCGLPFADoubleBuffer *\/\n 72, \/\/ kCGLPFANoRecovery\n 96, \/\/ kCGLPFAAllowOfflineRenderers\n 99, \/\/ kCGLPFAOpenGLProfile\n 0x1000, \/\/ kCGLOGLPVersion_Legacy -- 0x3200 is kCGLOGLPVersion_3_2_Core -- kCGLOGLPVersion_GL4_Core is 0x4100\n 0 \/\/ sentinel ending list\n };\n\n void *fmt;\n int numFormats = 0;\n if (CGLChoosePixelFormat(attribs, &fmt, &numFormats) != 0) {\n return -1;\n }\n if (CGLCreateContext(fmt, NULL, &ctx) != 0) {\n CGLDestroyPixelFormat(fmt);\n return -1;\n }\n CGLSetCurrentContext(ctx);\n#endif\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__\n#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__\n\n#include \n#include \n#include \/\/ std::sort\n#include \n\nnamespace stan {\n namespace math {\n \n \/**\n * A comparator that works for any container type that has the\n * brackets operator.\n *\n * @tparam ascending true if sorting in ascending order\n * @tparam C container type\n *\/\n namespace {\n template \n class index_comparator {\n const C& xs_;\n public:\n \/**\n * Construct an index comparator holding a reference\n * to the specified container.\n *\n * @patam xs Container\n *\/\n index_comparator(const C& xs) : xs_(xs) { }\n\n \/**\n * Return true if the value at the first index is sorted in\n * front of the value at the second index; this will depend\n * on the template parameter ascending<\/code>.\n *\n * @param i Index of first value for comparison\n * @param j Index of second value for comparison\n *\/\n bool operator()(int i, int j) const {\n if (ascending)\n return xs_[i-1] < xs_[j-1];\n else\n return xs_[i-1] > xs_[j-1];\n }\n };\n\n \n \/**\n * Return an integer array of indices of the specified container\n * sorting the values in ascending or descending order based on\n * the value of the first template prameter.\n *\n * @tparam ascending true if sort is in ascending order\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices(const C& xs) {\n size_t size = xs.size();\n std::vector idxs;\n idxs.resize(size);\n for (int i = 0; i < size; ++i)\n idxs[i] = i + 1;\n index_comparator comparator(xs);\n std::sort(idxs.begin(), idxs.end(), comparator);\n return idxs;\n }\n \n }\n \n \/**\n * Return a sorted copy of the argument container in ascending order.\n *\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices_asc(const C& xs) {\n return sort_indices(xs);\n }\n\n \/**\n * Return a sorted copy of the argument container in ascending order.\n *\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices_desc(const C& xs) {\n return sort_indices(xs);\n }\n\n\n }\n}\n#endif\nA possible way to use to solve sign-compare warnings#ifndef __STAN__MATH__MATRIX__SORT_INDICES_HPP__\n#define __STAN__MATH__MATRIX__SORT_INDICES_HPP__\n\n#include \n#include \n#include \/\/ std::sort\n#include \n\nnamespace stan {\n namespace math {\n \n \/**\n * A comparator that works for any container type that has the\n * brackets operator.\n *\n * @tparam ascending true if sorting in ascending order\n * @tparam C container type\n *\/\n namespace {\n template \n class index_comparator {\n const C& xs_;\n public:\n \/**\n * Construct an index comparator holding a reference\n * to the specified container.\n *\n * @patam xs Container\n *\/\n index_comparator(const C& xs) : xs_(xs) { }\n\n \/**\n * Return true if the value at the first index is sorted in\n * front of the value at the second index; this will depend\n * on the template parameter ascending<\/code>.\n *\n * @param i Index of first value for comparison\n * @param j Index of second value for comparison\n *\/\n bool operator()(int i, int j) const {\n if (ascending)\n return xs_[i-1] < xs_[j-1];\n else\n return xs_[i-1] > xs_[j-1];\n }\n };\n\n \n \/**\n * Return an integer array of indices of the specified container\n * sorting the values in ascending or descending order based on\n * the value of the first template prameter.\n *\n * @tparam ascending true if sort is in ascending order\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices(const C& xs, const signal size) {\n std::vector idxs;\n idxs.resize(size);\n for (signal i(0); i < size; ++i)\n idxs[i] = i + 1;\n index_comparator comparator(xs);\n std::sort(idxs.begin(), idxs.end(), comparator);\n return idxs;\n }\n \n }\n \n \/**\n * Return a sorted copy of the argument container in ascending order.\n *\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices_asc(const C& xs) {\n return sort_indices(xs, xs.size());\n }\n\n \/**\n * Return a sorted copy of the argument container in ascending order.\n *\n * @tparam C type of container\n * @param xs Container to sort\n * @return sorted version of container\n *\/\n template \n std::vector sort_indices_desc(const C& xs) {\n return sort_indices(xs, xs.size());\n }\n\n\n }\n}\n#endif\n<|endoftext|>"} {"text":"\n#include \"swganh\/command\/command_service.h\"\n\n#include \n\n#include \"anh\/app\/kernel_interface.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"anh\/crc.h\"\n#include \"anh\/event_dispatcher.h\"\n#include \"anh\/database\/database_manager_interface.h\"\n#include \"anh\/service\/service_manager.h\"\n\n#include \"swganh\/command\/command_filter.h\"\n\n#include \"swganh\/messages\/controllers\/command_queue_enqueue.h\"\n#include \"swganh\/messages\/controllers\/command_queue_remove.h\"\n#include \"swganh\/messages\/controllers\/combat_action_message.h\"\n\n#include \"swganh\/object\/creature\/creature.h\"\n#include \"swganh\/object\/object_controller.h\"\n\n#include \"python_command.h\"\n#include \"swganh\/simulation\/simulation_service.h\"\n\nusing namespace anh::app;\nusing namespace anh::service;\nusing namespace std;\nusing namespace swganh::command;\nusing namespace swganh::messages;\nusing namespace swganh::messages::controllers;\nusing namespace swganh::object;\nusing namespace swganh::object::creature;\nusing namespace swganh::scripting;\nusing namespace swganh::simulation;\n\nusing boost::asio::deadline_timer;\nusing boost::posix_time::milliseconds;\n\nCommandService::CommandService(KernelInterface* kernel)\n: BaseService(kernel)\n{}\n\nServiceDescription CommandService::GetServiceDescription()\n{\n ServiceDescription service_description(\n \"CommandService\",\n \"command\",\n \"0.1\",\n \"127.0.0.1\", \n 0, \n 0, \n 0);\n\n return service_description;\n}\n\nvoid CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)\n{\n\tenqueue_filters_.push_back(move(filter));\n}\n\nvoid CommandService::AddCommandProcessFilter(CommandFilter&& filter)\n{\n process_filters_.push_back(move(filter));\n}\n\nvoid CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)\n{\n handlers_[command_crc] = move(handler);\n}\n\nvoid CommandService::EnqueueCommand(\n const shared_ptr& actor,\n\tconst shared_ptr& target,\n CommandQueueEnqueue command)\n{\n bool is_valid;\n uint32_t error = 0, action = 0;\n\n tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);\n \n if (!is_valid)\n {\n LOG(WARNING) << \"Invalid command\";\n SendCommandQueueRemove(actor, command.action_counter, 0.0f, error, action);\n return;\n }\n\tauto object_id = actor->GetObjectId();\n command_queues_[object_id].push(command); \n\n if (!command_queue_timers_[object_id])\n {\n command_queue_timers_[object_id] = make_shared(kernel()->GetIoService());\n command_queue_timers_[object_id]->expires_from_now(\n milliseconds(command_properties_map_[command.command_crc].default_time));\n\n command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));\n }\n}\n\nvoid CommandService::HandleCommandQueueEnqueue(\n const shared_ptr& controller, \n const ObjControllerMessage& message)\n{\n auto actor = dynamic_pointer_cast(controller->GetObject());\n \n CommandQueueEnqueue enqueue;\n enqueue.Deserialize(message.data);\n\n\tauto target = simulation_service_->GetObjectById(enqueue.target_id);\n\n auto find_iter = command_properties_map_.find(enqueue.command_crc);\n\n if (find_iter == command_properties_map_.end())\n {\n LOG(WARNING) << \"Invalid handler requested: \" << hex << enqueue.command_crc;\n return;\n }\n \n if (find_iter->second.add_to_combat_queue)\n {\n EnqueueCommand(actor, target, enqueue);\n }\n else\n {\n ProcessCommand(actor, target, enqueue);\n }\n}\n\nvoid CommandService::HandleCommandQueueRemove(\n const shared_ptr& controller, \n const ObjControllerMessage& message)\n{}\n\nvoid CommandService::ProcessNextCommand(const shared_ptr& actor)\n{\n auto find_iter = command_queues_.find(actor->GetObjectId());\n \n CommandQueueEnqueue command; \n \n if (!find_iter->second.try_pop(command))\n {\n return;\n }\n\n auto target = simulation_service_->GetObjectById(command.target_id);\n\n ProcessCommand(actor, target, command);\n\n command_queue_timers_[actor->GetObjectId()]->expires_from_now(\n milliseconds(command_properties_map_[command.command_crc].default_time));\n\n command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));\n}\n\nvoid CommandService::ProcessCommand(const shared_ptr& actor, const shared_ptr& target, const swganh::messages::controllers::CommandQueueEnqueue& command)\n{ \n auto find_iter = handlers_.find(command.command_crc);\n if (find_iter == handlers_.end())\n {\n LOG(WARNING) << \"No handler for command: \" << std::hex << command.command_crc;\n return;\n }\n \n bool is_valid;\n uint32_t error = 0, action = 0;\n float default_time = 0.0f;\n\n tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);\n \n if (is_valid)\n {\n\t\tfind_iter->second(actor, target, command);\n default_time = command_properties_map_[command.command_crc].default_time \/ 1000;\n } \n \n SendCommandQueueRemove(actor, command.action_counter, default_time, error, action);\n}\n\nvoid CommandService::onStart()\n{\n\tLoadProperties();\n\n simulation_service_ = kernel()->GetServiceManager()\n ->GetService(\"SimulationService\");\n \n simulation_service_->RegisterControllerHandler(0x00000116, [this] (\n const std::shared_ptr& controller, \n const swganh::messages::ObjControllerMessage& message) \n {\n HandleCommandQueueEnqueue(controller, message);\n });\n \n simulation_service_->RegisterControllerHandler(0x00000117, [this] (\n const std::shared_ptr& controller, \n const swganh::messages::ObjControllerMessage& message) \n {\n HandleCommandQueueRemove(controller, message);\n });\n\t\n\tauto event_dispatcher = kernel()->GetEventDispatcher();\n\tevent_dispatcher->Dispatch(\n make_shared>(\"CommandServiceReady\", GetCommandProperties()));\n}\n\nvoid CommandService::LoadProperties()\n{ \n try {\n auto db_manager = kernel()->GetDatabaseManager();\n\n auto conn = db_manager->getConnection(\"galaxy\");\n auto statement = unique_ptr(conn->prepareStatement(\"CALL sp_LoadCommandProperties();\"));\n\n auto result = unique_ptr(statement->executeQuery());\n \n while (result->next())\n {\n CommandProperties properties;\n \n properties.name = result->getString(\"name\");\n\n string tmp = properties.name;\n transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n properties.name_crc = anh::memcrc(tmp);\n\n properties.ability = result->getString(\"ability\");\n properties.ability_crc = anh::memcrc(properties.ability);\n properties.deny_in_states = result->getUInt64(\"deny_in_states\");\n properties.script_hook = result->getString(\"script_hook\");\n properties.fail_script_hook = result->getString(\"fail_script_hook\");\n properties.default_time = result->getUInt64(\"default_time\");\n properties.command_group = result->getUInt(\"command_group\");\n properties.max_range_to_target = result->getDouble(\"max_range_to_target\");\n properties.add_to_combat_queue = result->getUInt(\"add_to_combat_queue\");\n properties.health_cost = result->getUInt(\"health_cost\");\n properties.health_cost_multiplier = result->getUInt(\"health_cost_multiplier\");\n properties.action_cost = result->getUInt(\"action_cost\");\n properties.action_cost_multiplier = result->getUInt(\"action_cost_multiplier\");\n properties.mind_cost = result->getUInt(\"mind_cost\");\n properties.mind_cost_multiplier = result->getUInt(\"mind_cost\");\n properties.damage_multiplier = result->getDouble(\"damage_multiplier\");\n properties.delay_multiplier = result->getDouble(\"delay_multiplier\");\n properties.force_cost = result->getUInt(\"force_cost\");\n properties.force_cost_multiplier = result->getUInt(\"force_cost_multiplier\");\n properties.animation_crc = result->getUInt(\"animation_crc\");\n properties.required_weapon_group = result->getUInt(\"required_weapon_group\");\n properties.combat_spam = result->getString(\"combat_spam\");\n properties.trail1 = result->getUInt(\"trail1\");\n properties.trail2 = result->getUInt(\"trail2\");\n properties.allow_in_posture = result->getUInt(\"allow_in_posture\");\n properties.health_hit_chance = result->getDouble(\"health_hit_chance\");\n properties.action_hit_chance = result->getDouble(\"action_hit_chance\");\n properties.mind_hit_chance = result->getDouble(\"mind_hit_chance\");\n properties.knockdown_hit_chance = result->getDouble(\"knockdown_chance\");\n properties.dizzy_hit_chance = result->getDouble(\"dizzy_chance\");\n properties.blind_chance = result->getDouble(\"blind_chance\");\n properties.stun_chance = result->getDouble(\"stun_chance\");\n properties.intimidate_chance = result->getDouble(\"intimidate_chance\");\n properties.posture_down_chance = result->getDouble(\"posture_down_chance\");\n properties.extended_range = result->getDouble(\"extended_range\");\n properties.cone_angle = result->getDouble(\"cone_angle\");\n properties.deny_in_locomotion = result->getUInt64(\"deny_in_locomotion\");\n \n command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));\n\n RegisterCommandScript(properties);\n }\n\n DLOG(WARNING) << \"Loaded (\" << command_properties_map_.size() << \") Commands\";\n }\n catch(sql::SQLException &e)\n {\n DLOG(ERROR) << \"SQLException at \" << __FILE__ << \" (\" << __LINE__ << \": \" << __FUNCTION__ << \")\";\n DLOG(ERROR) << \"MySQL Error: (\" << e.getErrorCode() << \": \" << e.getSQLState() << \") \" << e.what();\n }\n}\n\nvoid CommandService::RegisterCommandScript(const CommandProperties& properties)\n{\n if (properties.script_hook.length() != 0)\n {\n SetCommandHandler(properties.name_crc, PythonCommand(properties));\n }\n}\n\ntuple CommandService::ValidateCommand(\n const shared_ptr& actor, \n\tconst shared_ptr& target,\n const swganh::messages::controllers::CommandQueueEnqueue& command, \n const CommandProperties& command_properties,\n const std::vector& filters)\n{\n\ttuple result;\n bool all_run = all_of(\n begin(filters),\n end(filters),\n [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool\n {\n result = filter(actor, target, command, command_properties);\n\t\treturn get<0>(result);\n });\n\n return result;\n}\n\nvoid CommandService::SendCommandQueueRemove(\n const shared_ptr& actor,\n uint32_t action_counter,\n float default_time_sec,\n uint32_t error,\n uint32_t action)\n{\n CommandQueueRemove remove;\n remove.action_counter = action_counter;\n remove.timer = default_time_sec;\n remove.error = error;\n remove.action = action;\n\n\tactor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));\n}\nSet a default expiration time and and trigger an async wait if nothing is waiting.\n#include \"swganh\/command\/command_service.h\"\n\n#include \n\n#include \"anh\/app\/kernel_interface.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"anh\/crc.h\"\n#include \"anh\/event_dispatcher.h\"\n#include \"anh\/database\/database_manager_interface.h\"\n#include \"anh\/service\/service_manager.h\"\n\n#include \"swganh\/command\/command_filter.h\"\n\n#include \"swganh\/messages\/controllers\/command_queue_enqueue.h\"\n#include \"swganh\/messages\/controllers\/command_queue_remove.h\"\n#include \"swganh\/messages\/controllers\/combat_action_message.h\"\n\n#include \"swganh\/object\/creature\/creature.h\"\n#include \"swganh\/object\/object_controller.h\"\n\n#include \"python_command.h\"\n#include \"swganh\/simulation\/simulation_service.h\"\n\nusing namespace anh::app;\nusing namespace anh::service;\nusing namespace std;\nusing namespace swganh::command;\nusing namespace swganh::messages;\nusing namespace swganh::messages::controllers;\nusing namespace swganh::object;\nusing namespace swganh::object::creature;\nusing namespace swganh::scripting;\nusing namespace swganh::simulation;\n\nusing boost::asio::deadline_timer;\nusing boost::posix_time::milliseconds;\n\nCommandService::CommandService(KernelInterface* kernel)\n: BaseService(kernel)\n{}\n\nServiceDescription CommandService::GetServiceDescription()\n{\n ServiceDescription service_description(\n \"CommandService\",\n \"command\",\n \"0.1\",\n \"127.0.0.1\", \n 0, \n 0, \n 0);\n\n return service_description;\n}\n\nvoid CommandService::AddCommandEnqueueFilter(CommandFilter&& filter)\n{\n\tenqueue_filters_.push_back(move(filter));\n}\n\nvoid CommandService::AddCommandProcessFilter(CommandFilter&& filter)\n{\n process_filters_.push_back(move(filter));\n}\n\nvoid CommandService::SetCommandHandler(uint32_t command_crc, CommandHandler&& handler)\n{\n handlers_[command_crc] = move(handler);\n}\n\nvoid CommandService::EnqueueCommand(\n const shared_ptr& actor,\n\tconst shared_ptr& target,\n CommandQueueEnqueue command)\n{\n bool is_valid;\n uint32_t error = 0, action = 0;\n\n tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], enqueue_filters_);\n \n if (!is_valid)\n {\n LOG(WARNING) << \"Invalid command\";\n SendCommandQueueRemove(actor, command.action_counter, 0.0f, error, action);\n return;\n }\n\tauto object_id = actor->GetObjectId();\n command_queues_[object_id].push(command); \n\n if (!command_queue_timers_[object_id])\n {\n command_queue_timers_[object_id] = make_shared(kernel()->GetIoService());\n command_queue_timers_[object_id]->expires_at(boost::posix_time::second_clock::universal_time());\n }\n\n if (command_queue_timers_[object_id]->expires_at() <= boost::posix_time::second_clock::universal_time())\n {\n command_queue_timers_[object_id]->expires_from_now(\n milliseconds(command_properties_map_[command.command_crc].default_time));\n command_queue_timers_[object_id]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));\n }\n}\n\nvoid CommandService::HandleCommandQueueEnqueue(\n const shared_ptr& controller, \n const ObjControllerMessage& message)\n{\n auto actor = dynamic_pointer_cast(controller->GetObject());\n \n CommandQueueEnqueue enqueue;\n enqueue.Deserialize(message.data);\n\n\tauto target = simulation_service_->GetObjectById(enqueue.target_id);\n\n auto find_iter = command_properties_map_.find(enqueue.command_crc);\n\n if (find_iter == command_properties_map_.end())\n {\n LOG(WARNING) << \"Invalid handler requested: \" << hex << enqueue.command_crc;\n return;\n }\n \n if (find_iter->second.add_to_combat_queue)\n {\n EnqueueCommand(actor, target, enqueue);\n }\n else\n {\n ProcessCommand(actor, target, enqueue);\n }\n}\n\nvoid CommandService::HandleCommandQueueRemove(\n const shared_ptr& controller, \n const ObjControllerMessage& message)\n{}\n\nvoid CommandService::ProcessNextCommand(const shared_ptr& actor)\n{\n auto find_iter = command_queues_.find(actor->GetObjectId());\n \n CommandQueueEnqueue command; \n \n if (!find_iter->second.try_pop(command))\n {\n return;\n }\n\n auto target = simulation_service_->GetObjectById(command.target_id);\n\n ProcessCommand(actor, target, command);\n \n command_queue_timers_[actor->GetObjectId()]->expires_from_now(\n milliseconds(command_properties_map_[command.command_crc].default_time));\n command_queue_timers_[actor->GetObjectId()]->async_wait(bind(&CommandService::ProcessNextCommand, this, actor));\n}\n\nvoid CommandService::ProcessCommand(const shared_ptr& actor, const shared_ptr& target, const swganh::messages::controllers::CommandQueueEnqueue& command)\n{ \n auto find_iter = handlers_.find(command.command_crc);\n if (find_iter == handlers_.end())\n {\n LOG(WARNING) << \"No handler for command: \" << std::hex << command.command_crc;\n return;\n }\n \n bool is_valid;\n uint32_t error = 0, action = 0;\n float default_time = 0.0f;\n\n tie(is_valid, error, action) = ValidateCommand(actor, target, command, command_properties_map_[command.command_crc], process_filters_);\n \n if (is_valid)\n {\n\t\tfind_iter->second(actor, target, command);\n default_time = command_properties_map_[command.command_crc].default_time \/ 1000;\n } \n \n SendCommandQueueRemove(actor, command.action_counter, default_time, error, action);\n}\n\nvoid CommandService::onStart()\n{\n\tLoadProperties();\n\n simulation_service_ = kernel()->GetServiceManager()\n ->GetService(\"SimulationService\");\n \n simulation_service_->RegisterControllerHandler(0x00000116, [this] (\n const std::shared_ptr& controller, \n const swganh::messages::ObjControllerMessage& message) \n {\n HandleCommandQueueEnqueue(controller, message);\n });\n \n simulation_service_->RegisterControllerHandler(0x00000117, [this] (\n const std::shared_ptr& controller, \n const swganh::messages::ObjControllerMessage& message) \n {\n HandleCommandQueueRemove(controller, message);\n });\n\t\n\tauto event_dispatcher = kernel()->GetEventDispatcher();\n\tevent_dispatcher->Dispatch(\n make_shared>(\"CommandServiceReady\", GetCommandProperties()));\n}\n\nvoid CommandService::LoadProperties()\n{ \n try {\n auto db_manager = kernel()->GetDatabaseManager();\n\n auto conn = db_manager->getConnection(\"galaxy\");\n auto statement = unique_ptr(conn->prepareStatement(\"CALL sp_LoadCommandProperties();\"));\n\n auto result = unique_ptr(statement->executeQuery());\n \n while (result->next())\n {\n CommandProperties properties;\n \n properties.name = result->getString(\"name\");\n\n string tmp = properties.name;\n transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n properties.name_crc = anh::memcrc(tmp);\n\n properties.ability = result->getString(\"ability\");\n properties.ability_crc = anh::memcrc(properties.ability);\n properties.deny_in_states = result->getUInt64(\"deny_in_states\");\n properties.script_hook = result->getString(\"script_hook\");\n properties.fail_script_hook = result->getString(\"fail_script_hook\");\n properties.default_time = result->getUInt64(\"default_time\");\n properties.command_group = result->getUInt(\"command_group\");\n properties.max_range_to_target = result->getDouble(\"max_range_to_target\");\n properties.add_to_combat_queue = result->getUInt(\"add_to_combat_queue\");\n properties.health_cost = result->getUInt(\"health_cost\");\n properties.health_cost_multiplier = result->getUInt(\"health_cost_multiplier\");\n properties.action_cost = result->getUInt(\"action_cost\");\n properties.action_cost_multiplier = result->getUInt(\"action_cost_multiplier\");\n properties.mind_cost = result->getUInt(\"mind_cost\");\n properties.mind_cost_multiplier = result->getUInt(\"mind_cost\");\n properties.damage_multiplier = result->getDouble(\"damage_multiplier\");\n properties.delay_multiplier = result->getDouble(\"delay_multiplier\");\n properties.force_cost = result->getUInt(\"force_cost\");\n properties.force_cost_multiplier = result->getUInt(\"force_cost_multiplier\");\n properties.animation_crc = result->getUInt(\"animation_crc\");\n properties.required_weapon_group = result->getUInt(\"required_weapon_group\");\n properties.combat_spam = result->getString(\"combat_spam\");\n properties.trail1 = result->getUInt(\"trail1\");\n properties.trail2 = result->getUInt(\"trail2\");\n properties.allow_in_posture = result->getUInt(\"allow_in_posture\");\n properties.health_hit_chance = result->getDouble(\"health_hit_chance\");\n properties.action_hit_chance = result->getDouble(\"action_hit_chance\");\n properties.mind_hit_chance = result->getDouble(\"mind_hit_chance\");\n properties.knockdown_hit_chance = result->getDouble(\"knockdown_chance\");\n properties.dizzy_hit_chance = result->getDouble(\"dizzy_chance\");\n properties.blind_chance = result->getDouble(\"blind_chance\");\n properties.stun_chance = result->getDouble(\"stun_chance\");\n properties.intimidate_chance = result->getDouble(\"intimidate_chance\");\n properties.posture_down_chance = result->getDouble(\"posture_down_chance\");\n properties.extended_range = result->getDouble(\"extended_range\");\n properties.cone_angle = result->getDouble(\"cone_angle\");\n properties.deny_in_locomotion = result->getUInt64(\"deny_in_locomotion\");\n \n command_properties_map_.insert(make_pair(properties.name_crc, move(properties)));\n\n RegisterCommandScript(properties);\n }\n\n DLOG(WARNING) << \"Loaded (\" << command_properties_map_.size() << \") Commands\";\n }\n catch(sql::SQLException &e)\n {\n DLOG(ERROR) << \"SQLException at \" << __FILE__ << \" (\" << __LINE__ << \": \" << __FUNCTION__ << \")\";\n DLOG(ERROR) << \"MySQL Error: (\" << e.getErrorCode() << \": \" << e.getSQLState() << \") \" << e.what();\n }\n}\n\nvoid CommandService::RegisterCommandScript(const CommandProperties& properties)\n{\n if (properties.script_hook.length() != 0)\n {\n SetCommandHandler(properties.name_crc, PythonCommand(properties));\n }\n}\n\ntuple CommandService::ValidateCommand(\n const shared_ptr& actor, \n\tconst shared_ptr& target,\n const swganh::messages::controllers::CommandQueueEnqueue& command, \n const CommandProperties& command_properties,\n const std::vector& filters)\n{\n\ttuple result;\n bool all_run = all_of(\n begin(filters),\n end(filters),\n [&result, actor, target, &command, &command_properties] (const CommandFilter& filter)->bool\n {\n result = filter(actor, target, command, command_properties);\n\t\treturn get<0>(result);\n });\n\n return result;\n}\n\nvoid CommandService::SendCommandQueueRemove(\n const shared_ptr& actor,\n uint32_t action_counter,\n float default_time_sec,\n uint32_t error,\n uint32_t action)\n{\n CommandQueueRemove remove;\n remove.action_counter = action_counter;\n remove.timer = default_time_sec;\n remove.error = error;\n remove.action = action;\n\n\tactor->GetController()->Notify(ObjControllerMessage(0x0000000B, remove));\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** Copyright (C) 2014 BlackBerry Limited. All rights reserved.\n**\n** Contact: BlackBerry (qt@blackberry.com)\n** Contact: KDAB (info@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/www.qt.io\/licensing. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\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 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"bardescriptorfilenodemanager.h\"\n\n#include \"bardescriptorfilenode.h\"\n#include \"blackberrydeployconfiguration.h\"\n#include \"blackberrydeployinformation.h\"\n#include \"blackberrycreatepackagestep.h\"\n#include \"blackberryqtversion.h\"\n#include \"bardescriptordocument.h\"\n#include \"qnxconstants.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#include \n\nusing namespace Qnx;\nusing namespace Qnx::Internal;\n\nnamespace {\nconst char SKIP_BAR_DESCRIPTOR_CREATION_KEY[] = \"Qnx.BlackBerry.BarDescriptorFileNodeManager.SkipCreation\";\n}\n\nBarDescriptorFileNodeManager::BarDescriptorFileNodeManager(QObject *parent)\n : QObject(parent)\n{\n connect(ProjectExplorer::ProjectTree::instance(), &ProjectExplorer::ProjectTree::currentProjectChanged,\n this, &BarDescriptorFileNodeManager::setCurrentProject);\n}\n\nvoid BarDescriptorFileNodeManager::setCurrentProject(ProjectExplorer::Project *project)\n{\n if (!project)\n return;\n\n connect(project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),\n this, SLOT(updateBarDescriptorNodes(ProjectExplorer::Target*)), Qt::UniqueConnection);\n\n updateBarDescriptorNodes(project->activeTarget());\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Target *target)\n{\n if (!target)\n return;\n\n \/\/ We are not consistently getting a signal when the current project changes,\n \/\/ so instead use target->project() to get access to the current project\n\n if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target->kit()) != Constants::QNX_BB_OS_TYPE) {\n removeBarDescriptorNodes(target->project());\n return;\n }\n\n updateBarDescriptorNodes(target->project(), true);\n\n QList deployConfigurations = target->deployConfigurations();\n foreach (ProjectExplorer::DeployConfiguration *deployConfiguration, deployConfigurations) {\n BlackBerryDeployConfiguration *bbdc = qobject_cast(deployConfiguration);\n if (!bbdc)\n continue;\n\n connect(bbdc->deploymentInfo(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),\n this, SLOT(handleDeploymentDataChanged()), Qt::UniqueConnection);\n connect(bbdc->deploymentInfo(), SIGNAL(modelReset()),\n this, SLOT(handleDeploymentModelReset()), Qt::UniqueConnection);\n }\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentDataChanged()\n{\n handleDeploymentInfoChanged(false);\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentModelReset()\n{\n handleDeploymentInfoChanged(true);\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentInfoChanged(bool modelReset)\n{\n BlackBerryDeployInformation *deployInfo = qobject_cast(sender());\n QTC_ASSERT(deployInfo, return);\n\n updateBarDescriptorNodes(deployInfo->target()->project(), modelReset);\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Project *project, bool attemptCreate)\n{\n if (!project)\n return;\n\n ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();\n if (!rootProject)\n return;\n\n BlackBerryDeployConfiguration *dc =\n qobject_cast(project->activeTarget()->activeDeployConfiguration());\n if (!dc)\n return;\n\n QList packages = dc->deploymentInfo()->allPackages();\n foreach (const BarPackageDeployInformation &package, packages) {\n ProjectExplorer::ProjectNode *projectNode = rootProject->path() == package.proFilePath ?\n rootProject : findProjectNode(rootProject, package.proFilePath);\n if (!projectNode)\n continue;\n\n if (!QFileInfo::exists(package.appDescriptorPath())) {\n if (!attemptCreate)\n continue;\n\n if (!createBarDescriptor(project, package.appDescriptorPath(), projectNode))\n continue;\n } else {\n \/\/ Update the Qt environment if not matching the one in the deployment settings\n updateBarDescriptor(package.appDescriptorPath(), project->activeTarget());\n }\n\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);\n if (existingNode) {\n if (existingNode->path() != package.appDescriptorPath()) {\n \/\/ Reload the new bar-descriptor document in the existing editor (if there is one)\n Core::IDocument *oldDocument = Core::DocumentModel::documentForFilePath(existingNode->path());\n if (oldDocument) {\n QString errorMessage;\n\n if (!oldDocument->save(&errorMessage)) {\n Core::MessageManager::write(tr(\"Cannot save bar descriptor file: %1\").arg(errorMessage));\n continue;\n } else {\n oldDocument->setFilePath(Utils::FileName::fromString(package.appDescriptorPath()));\n\n if (!oldDocument->reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents))\n Core::MessageManager::write(tr(\"Cannot reload bar descriptor file: %1\").arg(errorMessage));\n }\n }\n\n existingNode->setPath(package.appDescriptorPath());\n }\n } else {\n BarDescriptorFileNode *fileNode = new BarDescriptorFileNode(package.appDescriptorPath());\n projectNode->addFileNodes(QList() << fileNode);\n }\n }\n}\n\nbool BarDescriptorFileNodeManager::createBarDescriptor(ProjectExplorer::Project *project,\n const QString &barDescriptorPath,\n ProjectExplorer::ProjectNode *projectNode)\n{\n const QString projectName = QFileInfo(projectNode->path()).completeBaseName();\n\n QmakeProjectManager::QmakeProFileNode *proFileNode =\n qobject_cast(projectNode);\n QTC_ASSERT(proFileNode, return false);\n const QString targetName = proFileNode->targetInformation().target;\n\n const QFile barDescriptorFile(barDescriptorPath);\n if (barDescriptorFile.exists())\n return false;\n\n bool skipFileCreation = project->namedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY)).toBool();\n\n if (skipFileCreation)\n return false;\n\n QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(Core::ICore::mainWindow(),\n tr(\"Setup Application Descriptor File\"),\n tr(\"You need to set up a bar descriptor file to enable \"\n \"packaging.\\nDo you want Qt Creator to generate it for your project (%1)?\")\n .arg(project->projectFilePath().toUserOutput()),\n tr(\"Don't ask again for this project\"), &skipFileCreation);\n\n if (button != QDialogButtonBox::Yes) {\n project->setNamedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY), skipFileCreation);\n return false;\n }\n\n QString barDescriptorTemplate;\n QtSupport::QtVersionNumber qtVersion =\n QtSupport::QtKitInformation::qtVersion(project->activeTarget()->kit())->qtVersion();\n if (qtVersion >= QtSupport::QtVersionNumber(5, 0, 0))\n barDescriptorTemplate = Core::ICore::resourcePath()\n + QLatin1String(\"\/templates\/wizards\/bb-qt5-bardescriptor\/bar-descriptor.xml\");\n else\n barDescriptorTemplate = Core::ICore::resourcePath()\n + QLatin1String(\"\/templates\/wizards\/bb-bardescriptor\/bar-descriptor.xml\");\n\n Utils::FileReader reader;\n if (!reader.fetch(barDescriptorTemplate)) {\n Core::MessageManager::write(tr(\"Cannot set up application descriptor file: \"\n \"Reading the bar descriptor template failed.\"));\n return false;\n }\n\n QString content = QString::fromUtf8(reader.data());\n content.replace(QLatin1String(\"PROJECTNAME\"), projectName);\n content.replace(QLatin1String(\"TARGETNAME\"), targetName);\n content.replace(QLatin1String(\"ID\"), QLatin1String(\"com.example.\") + projectName);\n\n if (project->projectDirectory().appendPath(QLatin1String(\"qml\")).exists())\n content.replace(QLatin1String(\"<\/qnx>\"),\n QLatin1String(\" qml<\/asset>\\n<\/qnx>\"));\n\n Utils::FileSaver writer(barDescriptorFile.fileName(), QIODevice::WriteOnly);\n writer.write(content.toUtf8());\n if (!writer.finalize()) {\n Core::MessageManager::write(tr(\"Cannot set up application descriptor file: \"\n \"Writing the bar descriptor file failed.\"));\n return false;\n }\n\n \/\/ Check if the Qt environment matches the Qt bundle mode in the deployment step\n updateBarDescriptor(barDescriptorPath, project->activeTarget(), true);\n\n return true;\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptor(const QString &barDescriptorPath,\n ProjectExplorer::Target *target,\n bool skipConfirmation)\n{\n BarDescriptorDocument doc;\n QString errorString;\n if (!doc.open(&errorString, barDescriptorPath)) {\n QMessageBox::warning(Core::ICore::mainWindow(), tr(\"Error\"),\n tr(\"Cannot open BAR application descriptor file\"));\n return;\n }\n\n QList envItems =\n doc.value(BarDescriptorDocument::env).value >();\n\n BlackBerryQtVersion *qtVersion =\n dynamic_cast(QtSupport::QtKitInformation::qtVersion(target->kit()));\n if (!qtVersion)\n return;\n\n ProjectExplorer::BuildStepList *stepList = target->activeDeployConfiguration()->stepList();\n foreach (ProjectExplorer::BuildStep *step, stepList->steps()) {\n BlackBerryCreatePackageStep *createPackageStep = dynamic_cast(step);\n if (createPackageStep) {\n createPackageStep->doUpdateAppDescriptorFile(barDescriptorPath,\n BlackBerryCreatePackageStep::QtEnvironment,\n skipConfirmation);\n }\n }\n}\n\nvoid BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::Project *project)\n{\n if (!project)\n return;\n\n ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();\n if (!rootProject)\n return;\n\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(rootProject);\n if (existingNode)\n rootProject->removeFileNodes(QList() << existingNode);\n\n \/\/ Also remove the bar descriptor nodes for sub-projects\n removeBarDescriptorNodes(rootProject);\n}\n\nvoid BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::ProjectNode *parent)\n{\n QList projectNodes = parent->subProjectNodes();\n foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);\n if (existingNode)\n projectNode->removeFileNodes(QList() << existingNode);\n\n removeBarDescriptorNodes(projectNode);\n }\n}\n\nBarDescriptorFileNode *BarDescriptorFileNodeManager::findBarDescriptorFileNode(ProjectExplorer::ProjectNode *parent) const\n{\n QTC_ASSERT(parent, return 0);\n\n QList fileNodes = parent->fileNodes();\n foreach (ProjectExplorer::FileNode *fileNode, fileNodes) {\n BarDescriptorFileNode *barDescriptorNode = qobject_cast(fileNode);\n if (barDescriptorNode)\n return barDescriptorNode;\n }\n\n return 0;\n}\n\nProjectExplorer::ProjectNode *BarDescriptorFileNodeManager::findProjectNode(ProjectExplorer::ProjectNode *parent,\n const QString &projectFilePath) const\n{\n QTC_ASSERT(parent, return 0);\n\n QList projectNodes = parent->subProjectNodes();\n foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {\n if (projectNode->path() == projectFilePath) {\n return projectNode;\n } else if (!projectNode->subProjectNodes().isEmpty()) {\n ProjectExplorer::ProjectNode *hit = findProjectNode(projectNode, projectFilePath);\n if (hit)\n return hit;\n }\n }\n\n return 0;\n}\nBlackBerry: Make current project behave like it used to\/**************************************************************************\n**\n** Copyright (C) 2014 BlackBerry Limited. All rights reserved.\n**\n** Contact: BlackBerry (qt@blackberry.com)\n** Contact: KDAB (info@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/www.qt.io\/licensing. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\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 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"bardescriptorfilenodemanager.h\"\n\n#include \"bardescriptorfilenode.h\"\n#include \"blackberrydeployconfiguration.h\"\n#include \"blackberrydeployinformation.h\"\n#include \"blackberrycreatepackagestep.h\"\n#include \"blackberryqtversion.h\"\n#include \"bardescriptordocument.h\"\n#include \"qnxconstants.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#include \n#include \n\nusing namespace Qnx;\nusing namespace Qnx::Internal;\n\nnamespace {\nconst char SKIP_BAR_DESCRIPTOR_CREATION_KEY[] = \"Qnx.BlackBerry.BarDescriptorFileNodeManager.SkipCreation\";\n}\n\nBarDescriptorFileNodeManager::BarDescriptorFileNodeManager(QObject *parent)\n : QObject(parent)\n{\n connect(ProjectExplorer::ProjectTree::instance(), &ProjectExplorer::ProjectTree::currentProjectChanged,\n this, &BarDescriptorFileNodeManager::setCurrentProject);\n connect(ProjectExplorer::SessionManager::instance(), &ProjectExplorer::SessionManager::startupProjectChanged,\n this, &BarDescriptorFileNodeManager::setCurrentProject);\n}\n\nvoid BarDescriptorFileNodeManager::setCurrentProject(ProjectExplorer::Project *project)\n{\n if (!project)\n return;\n\n connect(project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),\n this, SLOT(updateBarDescriptorNodes(ProjectExplorer::Target*)), Qt::UniqueConnection);\n\n updateBarDescriptorNodes(project->activeTarget());\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Target *target)\n{\n if (!target)\n return;\n\n \/\/ We are not consistently getting a signal when the current project changes,\n \/\/ so instead use target->project() to get access to the current project\n\n if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target->kit()) != Constants::QNX_BB_OS_TYPE) {\n removeBarDescriptorNodes(target->project());\n return;\n }\n\n updateBarDescriptorNodes(target->project(), true);\n\n QList deployConfigurations = target->deployConfigurations();\n foreach (ProjectExplorer::DeployConfiguration *deployConfiguration, deployConfigurations) {\n BlackBerryDeployConfiguration *bbdc = qobject_cast(deployConfiguration);\n if (!bbdc)\n continue;\n\n connect(bbdc->deploymentInfo(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),\n this, SLOT(handleDeploymentDataChanged()), Qt::UniqueConnection);\n connect(bbdc->deploymentInfo(), SIGNAL(modelReset()),\n this, SLOT(handleDeploymentModelReset()), Qt::UniqueConnection);\n }\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentDataChanged()\n{\n handleDeploymentInfoChanged(false);\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentModelReset()\n{\n handleDeploymentInfoChanged(true);\n}\n\nvoid BarDescriptorFileNodeManager::handleDeploymentInfoChanged(bool modelReset)\n{\n BlackBerryDeployInformation *deployInfo = qobject_cast(sender());\n QTC_ASSERT(deployInfo, return);\n\n updateBarDescriptorNodes(deployInfo->target()->project(), modelReset);\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Project *project, bool attemptCreate)\n{\n if (!project)\n return;\n\n ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();\n if (!rootProject)\n return;\n\n BlackBerryDeployConfiguration *dc =\n qobject_cast(project->activeTarget()->activeDeployConfiguration());\n if (!dc)\n return;\n\n QList packages = dc->deploymentInfo()->allPackages();\n foreach (const BarPackageDeployInformation &package, packages) {\n ProjectExplorer::ProjectNode *projectNode = rootProject->path() == package.proFilePath ?\n rootProject : findProjectNode(rootProject, package.proFilePath);\n if (!projectNode)\n continue;\n\n if (!QFileInfo::exists(package.appDescriptorPath())) {\n if (!attemptCreate)\n continue;\n\n if (!createBarDescriptor(project, package.appDescriptorPath(), projectNode))\n continue;\n } else {\n \/\/ Update the Qt environment if not matching the one in the deployment settings\n updateBarDescriptor(package.appDescriptorPath(), project->activeTarget());\n }\n\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);\n if (existingNode) {\n if (existingNode->path() != package.appDescriptorPath()) {\n \/\/ Reload the new bar-descriptor document in the existing editor (if there is one)\n Core::IDocument *oldDocument = Core::DocumentModel::documentForFilePath(existingNode->path());\n if (oldDocument) {\n QString errorMessage;\n\n if (!oldDocument->save(&errorMessage)) {\n Core::MessageManager::write(tr(\"Cannot save bar descriptor file: %1\").arg(errorMessage));\n continue;\n } else {\n oldDocument->setFilePath(Utils::FileName::fromString(package.appDescriptorPath()));\n\n if (!oldDocument->reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents))\n Core::MessageManager::write(tr(\"Cannot reload bar descriptor file: %1\").arg(errorMessage));\n }\n }\n\n existingNode->setPath(package.appDescriptorPath());\n }\n } else {\n BarDescriptorFileNode *fileNode = new BarDescriptorFileNode(package.appDescriptorPath());\n projectNode->addFileNodes(QList() << fileNode);\n }\n }\n}\n\nbool BarDescriptorFileNodeManager::createBarDescriptor(ProjectExplorer::Project *project,\n const QString &barDescriptorPath,\n ProjectExplorer::ProjectNode *projectNode)\n{\n const QString projectName = QFileInfo(projectNode->path()).completeBaseName();\n\n QmakeProjectManager::QmakeProFileNode *proFileNode =\n qobject_cast(projectNode);\n QTC_ASSERT(proFileNode, return false);\n const QString targetName = proFileNode->targetInformation().target;\n\n const QFile barDescriptorFile(barDescriptorPath);\n if (barDescriptorFile.exists())\n return false;\n\n bool skipFileCreation = project->namedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY)).toBool();\n\n if (skipFileCreation)\n return false;\n\n QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(Core::ICore::mainWindow(),\n tr(\"Setup Application Descriptor File\"),\n tr(\"You need to set up a bar descriptor file to enable \"\n \"packaging.\\nDo you want Qt Creator to generate it for your project (%1)?\")\n .arg(project->projectFilePath().toUserOutput()),\n tr(\"Don't ask again for this project\"), &skipFileCreation);\n\n if (button != QDialogButtonBox::Yes) {\n project->setNamedSettings(QLatin1String(SKIP_BAR_DESCRIPTOR_CREATION_KEY), skipFileCreation);\n return false;\n }\n\n QString barDescriptorTemplate;\n QtSupport::QtVersionNumber qtVersion =\n QtSupport::QtKitInformation::qtVersion(project->activeTarget()->kit())->qtVersion();\n if (qtVersion >= QtSupport::QtVersionNumber(5, 0, 0))\n barDescriptorTemplate = Core::ICore::resourcePath()\n + QLatin1String(\"\/templates\/wizards\/bb-qt5-bardescriptor\/bar-descriptor.xml\");\n else\n barDescriptorTemplate = Core::ICore::resourcePath()\n + QLatin1String(\"\/templates\/wizards\/bb-bardescriptor\/bar-descriptor.xml\");\n\n Utils::FileReader reader;\n if (!reader.fetch(barDescriptorTemplate)) {\n Core::MessageManager::write(tr(\"Cannot set up application descriptor file: \"\n \"Reading the bar descriptor template failed.\"));\n return false;\n }\n\n QString content = QString::fromUtf8(reader.data());\n content.replace(QLatin1String(\"PROJECTNAME\"), projectName);\n content.replace(QLatin1String(\"TARGETNAME\"), targetName);\n content.replace(QLatin1String(\"ID\"), QLatin1String(\"com.example.\") + projectName);\n\n if (project->projectDirectory().appendPath(QLatin1String(\"qml\")).exists())\n content.replace(QLatin1String(\"<\/qnx>\"),\n QLatin1String(\" qml<\/asset>\\n<\/qnx>\"));\n\n Utils::FileSaver writer(barDescriptorFile.fileName(), QIODevice::WriteOnly);\n writer.write(content.toUtf8());\n if (!writer.finalize()) {\n Core::MessageManager::write(tr(\"Cannot set up application descriptor file: \"\n \"Writing the bar descriptor file failed.\"));\n return false;\n }\n\n \/\/ Check if the Qt environment matches the Qt bundle mode in the deployment step\n updateBarDescriptor(barDescriptorPath, project->activeTarget(), true);\n\n return true;\n}\n\nvoid BarDescriptorFileNodeManager::updateBarDescriptor(const QString &barDescriptorPath,\n ProjectExplorer::Target *target,\n bool skipConfirmation)\n{\n BarDescriptorDocument doc;\n QString errorString;\n if (!doc.open(&errorString, barDescriptorPath)) {\n QMessageBox::warning(Core::ICore::mainWindow(), tr(\"Error\"),\n tr(\"Cannot open BAR application descriptor file\"));\n return;\n }\n\n QList envItems =\n doc.value(BarDescriptorDocument::env).value >();\n\n BlackBerryQtVersion *qtVersion =\n dynamic_cast(QtSupport::QtKitInformation::qtVersion(target->kit()));\n if (!qtVersion)\n return;\n\n ProjectExplorer::BuildStepList *stepList = target->activeDeployConfiguration()->stepList();\n foreach (ProjectExplorer::BuildStep *step, stepList->steps()) {\n BlackBerryCreatePackageStep *createPackageStep = dynamic_cast(step);\n if (createPackageStep) {\n createPackageStep->doUpdateAppDescriptorFile(barDescriptorPath,\n BlackBerryCreatePackageStep::QtEnvironment,\n skipConfirmation);\n }\n }\n}\n\nvoid BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::Project *project)\n{\n if (!project)\n return;\n\n ProjectExplorer::ProjectNode *rootProject = project->rootProjectNode();\n if (!rootProject)\n return;\n\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(rootProject);\n if (existingNode)\n rootProject->removeFileNodes(QList() << existingNode);\n\n \/\/ Also remove the bar descriptor nodes for sub-projects\n removeBarDescriptorNodes(rootProject);\n}\n\nvoid BarDescriptorFileNodeManager::removeBarDescriptorNodes(ProjectExplorer::ProjectNode *parent)\n{\n QList projectNodes = parent->subProjectNodes();\n foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {\n BarDescriptorFileNode *existingNode = findBarDescriptorFileNode(projectNode);\n if (existingNode)\n projectNode->removeFileNodes(QList() << existingNode);\n\n removeBarDescriptorNodes(projectNode);\n }\n}\n\nBarDescriptorFileNode *BarDescriptorFileNodeManager::findBarDescriptorFileNode(ProjectExplorer::ProjectNode *parent) const\n{\n QTC_ASSERT(parent, return 0);\n\n QList fileNodes = parent->fileNodes();\n foreach (ProjectExplorer::FileNode *fileNode, fileNodes) {\n BarDescriptorFileNode *barDescriptorNode = qobject_cast(fileNode);\n if (barDescriptorNode)\n return barDescriptorNode;\n }\n\n return 0;\n}\n\nProjectExplorer::ProjectNode *BarDescriptorFileNodeManager::findProjectNode(ProjectExplorer::ProjectNode *parent,\n const QString &projectFilePath) const\n{\n QTC_ASSERT(parent, return 0);\n\n QList projectNodes = parent->subProjectNodes();\n foreach (ProjectExplorer::ProjectNode *projectNode, projectNodes) {\n if (projectNode->path() == projectFilePath) {\n return projectNode;\n } else if (!projectNode->subProjectNodes().isEmpty()) {\n ProjectExplorer::ProjectNode *hit = findProjectNode(projectNode, projectFilePath);\n if (hit)\n return hit;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkAndroidSDKCanvas.h\"\n\n#include \"SkColorFilter.h\"\n#include \"SkDrawLooper.h\"\n#include \"SkPaint.h\"\n#include \"SkPathEffect.h\"\n#include \"SkShader.h\"\n#include \"SkSurface.h\"\n#include \"SkTLazy.h\"\n\nnamespace {\n\n\/** Discard SkShaders not exposed by the Android Java API. *\/\n\nvoid CheckShader(SkPaint* paint) {\n SkShader* shader = paint->getShader();\n if (!shader) {\n return;\n }\n\n if (shader->isAImage()) {\n return;\n }\n if (shader->asACompose(nullptr)) {\n return;\n }\n SkShader::GradientType gtype = shader->asAGradient(nullptr);\n if (gtype == SkShader::kLinear_GradientType ||\n gtype == SkShader::kRadial_GradientType ||\n gtype == SkShader::kSweep_GradientType) {\n return;\n }\n paint->setShader(nullptr);\n}\n\nvoid Filter(SkPaint* paint) {\n\n uint32_t flags = paint->getFlags();\n flags &= ~SkPaint::kLCDRenderText_Flag;\n paint->setFlags(flags);\n\n \/\/ Android doesn't support blend modes above kLighten_Mode\n if (paint->getBlendMode() > SkBlendMode::kLighten) {\n paint->setBlendMode(SkBlendMode::kSrcOver);\n }\n\n \/\/ Force bilinear scaling or none\n if (paint->getFilterQuality() != kNone_SkFilterQuality) {\n paint->setFilterQuality(kLow_SkFilterQuality);\n }\n\n CheckShader(paint);\n\n \/\/ Android SDK only supports mode & matrix color filters\n \/\/ (and, again, no modes above kLighten_Mode).\n SkColorFilter* cf = paint->getColorFilter();\n if (cf) {\n SkColor color;\n SK_XFERMODE_MODE_PARAM mode;\n SkScalar srcColorMatrix[20];\n bool isMode = cf->asColorMode(&color, &mode);\n if (isMode && (int)mode > (int)SkBlendMode::kLighten) {\n paint->setColorFilter(\n SkColorFilter::MakeModeFilter(color, SkBlendMode::kSrcOver));\n } else if (!isMode && !cf->asColorMatrix(srcColorMatrix)) {\n paint->setColorFilter(nullptr);\n }\n }\n\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n SkPathEffect* pe = paint->getPathEffect();\n if (pe && !pe->exposedInAndroidJavaAPI()) {\n paint->setPathEffect(nullptr);\n }\n#endif\n\n \/\/ TODO: Android doesn't support all the flags that can be passed to\n \/\/ blur filters; we need plumbing to get them out.\n\n paint->setImageFilter(nullptr);\n paint->setLooper(nullptr);\n};\n\n} \/\/ namespace\n\n#define FILTER(p) \\\n SkPaint filteredPaint(p); \\\n Filter(&filteredPaint);\n\n#define FILTER_PTR(p) \\\n SkTLazy lazyPaint; \\\n SkPaint* filteredPaint = (SkPaint*) p; \\\n if (p) { \\\n filteredPaint = lazyPaint.set(*p); \\\n Filter(filteredPaint); \\\n }\n\n\nSkAndroidSDKCanvas::SkAndroidSDKCanvas() : fProxyTarget(nullptr) { }\n\nvoid SkAndroidSDKCanvas::reset(SkCanvas* newTarget) { fProxyTarget = newTarget; }\n\nvoid SkAndroidSDKCanvas::onDrawPaint(const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPaint(filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPoints(PointMode pMode,\n size_t count,\n const SkPoint pts[],\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPoints(pMode, count, pts, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawOval(const SkRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawOval(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawArc(const SkRect& r, SkScalar startAngle, SkScalar sweepAngle,\n bool useCenter, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawArc(r, startAngle, sweepAngle, useCenter, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawRect(const SkRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawRect(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawRRect(const SkRRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawRRect(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPath(path, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmap(const SkBitmap& bitmap,\n SkScalar left,\n SkScalar top,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawBitmap(bitmap, left, top, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmapRect(const SkBitmap& bitmap,\n const SkRect* src,\n const SkRect& dst,\n const SkPaint* paint,\n SkCanvas::SrcRectConstraint constraint) {\n FILTER_PTR(paint);\n fProxyTarget->legacy_drawBitmapRect(bitmap, src, dst, filteredPaint, constraint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmapNine(const SkBitmap& bitmap,\n const SkIRect& center,\n const SkRect& dst,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawBitmapNine(bitmap, center, dst, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawVertices(VertexMode vMode,\n int vertexCount,\n const SkPoint vertices[],\n const SkPoint texs[], const SkColor colors[], SK_XFERMODE_PARAM xMode,\n const uint16_t indices[], int indexCount,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawVertices(vMode, vertexCount, vertices, texs, colors,\n xMode, indices, indexCount, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawDRRect(const SkRRect& outer,\n const SkRRect& inner,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawDRRect(outer, inner, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawText(const void* text,\n size_t byteLength,\n SkScalar x,\n SkScalar y,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawText(text, byteLength, x, y, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPosText(const void* text,\n size_t byteLength,\n const SkPoint pos[],\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPosText(text, byteLength, pos, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPosTextH(const void* text,\n size_t byteLength,\n const SkScalar xpos[],\n SkScalar constY,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPosTextH(text, byteLength, xpos, constY, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextOnPath(const void* text,\n size_t byteLength,\n const SkPath& path,\n const SkMatrix* matrix,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextOnPath(text, byteLength, path, matrix, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextRSXform(const void* text, size_t byteLength,\n const SkRSXform xform[], const SkRect* cull,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextRSXform(text, byteLength, xform, cull, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextBlob(const SkTextBlob* blob,\n SkScalar x,\n SkScalar y,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextBlob(blob, x, y, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawPatch(const SkPoint cubics[12],\n const SkColor colors[4],\n const SkPoint texCoords[4],\n SK_XFERMODE_PARAM xmode,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPatch(cubics, colors, texCoords, xmode, filteredPaint);\n}\n\n\nvoid SkAndroidSDKCanvas::onDrawImage(const SkImage* image,\n SkScalar x,\n SkScalar y,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawImage(image, x, y, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawImageRect(const SkImage* image,\n const SkRect* in,\n const SkRect& out,\n const SkPaint* paint,\n SrcRectConstraint constraint) {\n FILTER_PTR(paint);\n fProxyTarget->legacy_drawImageRect(image, in, out, filteredPaint, constraint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawPicture(const SkPicture* picture,\n const SkMatrix* matrix,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawPicture(picture, matrix, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawAtlas(const SkImage* atlas,\n const SkRSXform xform[],\n const SkRect tex[],\n const SkColor colors[],\n int count,\n SK_XFERMODE_MODE_PARAM mode,\n const SkRect* cullRect,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawAtlas(atlas, xform, tex, colors, count, mode, cullRect,\n filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawImageNine(const SkImage* image,\n const SkIRect& center,\n const SkRect& dst,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawImageNine(image, center, dst, filteredPaint);\n}\n\n\nvoid SkAndroidSDKCanvas::onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) {\n fProxyTarget->drawDrawable(drawable, matrix);\n}\n\nSkISize SkAndroidSDKCanvas::getBaseLayerSize() const {\n return fProxyTarget->getBaseLayerSize();\n}\nbool SkAndroidSDKCanvas::getClipBounds(SkRect* rect) const {\n return fProxyTarget->getClipBounds(rect);\n}\nbool SkAndroidSDKCanvas::getClipDeviceBounds(SkIRect* rect) const {\n return fProxyTarget->getClipDeviceBounds(rect);\n}\n\nbool SkAndroidSDKCanvas::isClipEmpty() const { return fProxyTarget->isClipEmpty(); }\nbool SkAndroidSDKCanvas::isClipRect() const { return fProxyTarget->isClipRect(); }\n\nsk_sp SkAndroidSDKCanvas::onNewSurface(const SkImageInfo& info,\n const SkSurfaceProps& props) {\n return fProxyTarget->makeSurface(info, &props);\n}\n\nbool SkAndroidSDKCanvas::onPeekPixels(SkPixmap* pmap) {\n return fProxyTarget->peekPixels(pmap);\n}\n\nbool SkAndroidSDKCanvas::onAccessTopLayerPixels(SkPixmap* pmap) {\n SkASSERT(pmap);\n SkImageInfo info;\n size_t rowBytes;\n const void* addr = fProxyTarget->accessTopLayerPixels(&info, &rowBytes, nullptr);\n if (addr) {\n pmap->reset(info, addr, rowBytes);\n return true;\n }\n return false;\n}\n\nvoid SkAndroidSDKCanvas::willSave() {\n fProxyTarget->save();\n}\n\nSkCanvas::SaveLayerStrategy SkAndroidSDKCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {\n fProxyTarget->saveLayer(rec);\n return SkCanvas::kNoLayer_SaveLayerStrategy;\n}\n\nvoid SkAndroidSDKCanvas::willRestore() {\n fProxyTarget->restore();\n}\n\nvoid SkAndroidSDKCanvas::didRestore() { }\n\nvoid SkAndroidSDKCanvas::didConcat(const SkMatrix& m) {\n fProxyTarget->concat(m);\n}\n\nvoid SkAndroidSDKCanvas::didSetMatrix(const SkMatrix& m) {\n fProxyTarget->setMatrix(m);\n}\n\nvoid SkAndroidSDKCanvas::onClipRect(const SkRect& rect,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipRect(rect, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipRRect(const SkRRect& rrect,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipRRect(rrect, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipPath(const SkPath& path,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipPath(path, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipRegion(const SkRegion& region, ClipOp op) {\n fProxyTarget->clipRegion(region, op);\n}\n\nvoid SkAndroidSDKCanvas::onDiscard() { fProxyTarget->discard(); }\nadd include to remove legacy flag\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkAndroidSDKCanvas.h\"\n\n#include \"SkColorFilter.h\"\n#include \"SkDrawLooper.h\"\n#include \"SkImageFilter.h\"\n#include \"SkPaint.h\"\n#include \"SkPathEffect.h\"\n#include \"SkShader.h\"\n#include \"SkSurface.h\"\n#include \"SkTLazy.h\"\n\nnamespace {\n\n\/** Discard SkShaders not exposed by the Android Java API. *\/\n\nvoid CheckShader(SkPaint* paint) {\n SkShader* shader = paint->getShader();\n if (!shader) {\n return;\n }\n\n if (shader->isAImage()) {\n return;\n }\n if (shader->asACompose(nullptr)) {\n return;\n }\n SkShader::GradientType gtype = shader->asAGradient(nullptr);\n if (gtype == SkShader::kLinear_GradientType ||\n gtype == SkShader::kRadial_GradientType ||\n gtype == SkShader::kSweep_GradientType) {\n return;\n }\n paint->setShader(nullptr);\n}\n\nvoid Filter(SkPaint* paint) {\n\n uint32_t flags = paint->getFlags();\n flags &= ~SkPaint::kLCDRenderText_Flag;\n paint->setFlags(flags);\n\n \/\/ Android doesn't support blend modes above kLighten_Mode\n if (paint->getBlendMode() > SkBlendMode::kLighten) {\n paint->setBlendMode(SkBlendMode::kSrcOver);\n }\n\n \/\/ Force bilinear scaling or none\n if (paint->getFilterQuality() != kNone_SkFilterQuality) {\n paint->setFilterQuality(kLow_SkFilterQuality);\n }\n\n CheckShader(paint);\n\n \/\/ Android SDK only supports mode & matrix color filters\n \/\/ (and, again, no modes above kLighten_Mode).\n SkColorFilter* cf = paint->getColorFilter();\n if (cf) {\n SkColor color;\n SK_XFERMODE_MODE_PARAM mode;\n SkScalar srcColorMatrix[20];\n bool isMode = cf->asColorMode(&color, &mode);\n if (isMode && (int)mode > (int)SkBlendMode::kLighten) {\n paint->setColorFilter(\n SkColorFilter::MakeModeFilter(color, SkBlendMode::kSrcOver));\n } else if (!isMode && !cf->asColorMatrix(srcColorMatrix)) {\n paint->setColorFilter(nullptr);\n }\n }\n\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n SkPathEffect* pe = paint->getPathEffect();\n if (pe && !pe->exposedInAndroidJavaAPI()) {\n paint->setPathEffect(nullptr);\n }\n#endif\n\n \/\/ TODO: Android doesn't support all the flags that can be passed to\n \/\/ blur filters; we need plumbing to get them out.\n\n paint->setImageFilter(nullptr);\n paint->setLooper(nullptr);\n};\n\n} \/\/ namespace\n\n#define FILTER(p) \\\n SkPaint filteredPaint(p); \\\n Filter(&filteredPaint);\n\n#define FILTER_PTR(p) \\\n SkTLazy lazyPaint; \\\n SkPaint* filteredPaint = (SkPaint*) p; \\\n if (p) { \\\n filteredPaint = lazyPaint.set(*p); \\\n Filter(filteredPaint); \\\n }\n\n\nSkAndroidSDKCanvas::SkAndroidSDKCanvas() : fProxyTarget(nullptr) { }\n\nvoid SkAndroidSDKCanvas::reset(SkCanvas* newTarget) { fProxyTarget = newTarget; }\n\nvoid SkAndroidSDKCanvas::onDrawPaint(const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPaint(filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPoints(PointMode pMode,\n size_t count,\n const SkPoint pts[],\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPoints(pMode, count, pts, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawOval(const SkRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawOval(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawArc(const SkRect& r, SkScalar startAngle, SkScalar sweepAngle,\n bool useCenter, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawArc(r, startAngle, sweepAngle, useCenter, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawRect(const SkRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawRect(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawRRect(const SkRRect& r, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawRRect(r, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPath(path, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmap(const SkBitmap& bitmap,\n SkScalar left,\n SkScalar top,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawBitmap(bitmap, left, top, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmapRect(const SkBitmap& bitmap,\n const SkRect* src,\n const SkRect& dst,\n const SkPaint* paint,\n SkCanvas::SrcRectConstraint constraint) {\n FILTER_PTR(paint);\n fProxyTarget->legacy_drawBitmapRect(bitmap, src, dst, filteredPaint, constraint);\n}\nvoid SkAndroidSDKCanvas::onDrawBitmapNine(const SkBitmap& bitmap,\n const SkIRect& center,\n const SkRect& dst,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawBitmapNine(bitmap, center, dst, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawVertices(VertexMode vMode,\n int vertexCount,\n const SkPoint vertices[],\n const SkPoint texs[], const SkColor colors[], SK_XFERMODE_PARAM xMode,\n const uint16_t indices[], int indexCount,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawVertices(vMode, vertexCount, vertices, texs, colors,\n xMode, indices, indexCount, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawDRRect(const SkRRect& outer,\n const SkRRect& inner,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawDRRect(outer, inner, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawText(const void* text,\n size_t byteLength,\n SkScalar x,\n SkScalar y,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawText(text, byteLength, x, y, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPosText(const void* text,\n size_t byteLength,\n const SkPoint pos[],\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPosText(text, byteLength, pos, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawPosTextH(const void* text,\n size_t byteLength,\n const SkScalar xpos[],\n SkScalar constY,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPosTextH(text, byteLength, xpos, constY, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextOnPath(const void* text,\n size_t byteLength,\n const SkPath& path,\n const SkMatrix* matrix,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextOnPath(text, byteLength, path, matrix, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextRSXform(const void* text, size_t byteLength,\n const SkRSXform xform[], const SkRect* cull,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextRSXform(text, byteLength, xform, cull, filteredPaint);\n}\nvoid SkAndroidSDKCanvas::onDrawTextBlob(const SkTextBlob* blob,\n SkScalar x,\n SkScalar y,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawTextBlob(blob, x, y, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawPatch(const SkPoint cubics[12],\n const SkColor colors[4],\n const SkPoint texCoords[4],\n SK_XFERMODE_PARAM xmode,\n const SkPaint& paint) {\n FILTER(paint);\n fProxyTarget->drawPatch(cubics, colors, texCoords, xmode, filteredPaint);\n}\n\n\nvoid SkAndroidSDKCanvas::onDrawImage(const SkImage* image,\n SkScalar x,\n SkScalar y,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawImage(image, x, y, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawImageRect(const SkImage* image,\n const SkRect* in,\n const SkRect& out,\n const SkPaint* paint,\n SrcRectConstraint constraint) {\n FILTER_PTR(paint);\n fProxyTarget->legacy_drawImageRect(image, in, out, filteredPaint, constraint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawPicture(const SkPicture* picture,\n const SkMatrix* matrix,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawPicture(picture, matrix, filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawAtlas(const SkImage* atlas,\n const SkRSXform xform[],\n const SkRect tex[],\n const SkColor colors[],\n int count,\n SK_XFERMODE_MODE_PARAM mode,\n const SkRect* cullRect,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawAtlas(atlas, xform, tex, colors, count, mode, cullRect,\n filteredPaint);\n}\n\nvoid SkAndroidSDKCanvas::onDrawImageNine(const SkImage* image,\n const SkIRect& center,\n const SkRect& dst,\n const SkPaint* paint) {\n FILTER_PTR(paint);\n fProxyTarget->drawImageNine(image, center, dst, filteredPaint);\n}\n\n\nvoid SkAndroidSDKCanvas::onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) {\n fProxyTarget->drawDrawable(drawable, matrix);\n}\n\nSkISize SkAndroidSDKCanvas::getBaseLayerSize() const {\n return fProxyTarget->getBaseLayerSize();\n}\nbool SkAndroidSDKCanvas::getClipBounds(SkRect* rect) const {\n return fProxyTarget->getClipBounds(rect);\n}\nbool SkAndroidSDKCanvas::getClipDeviceBounds(SkIRect* rect) const {\n return fProxyTarget->getClipDeviceBounds(rect);\n}\n\nbool SkAndroidSDKCanvas::isClipEmpty() const { return fProxyTarget->isClipEmpty(); }\nbool SkAndroidSDKCanvas::isClipRect() const { return fProxyTarget->isClipRect(); }\n\nsk_sp SkAndroidSDKCanvas::onNewSurface(const SkImageInfo& info,\n const SkSurfaceProps& props) {\n return fProxyTarget->makeSurface(info, &props);\n}\n\nbool SkAndroidSDKCanvas::onPeekPixels(SkPixmap* pmap) {\n return fProxyTarget->peekPixels(pmap);\n}\n\nbool SkAndroidSDKCanvas::onAccessTopLayerPixels(SkPixmap* pmap) {\n SkASSERT(pmap);\n SkImageInfo info;\n size_t rowBytes;\n const void* addr = fProxyTarget->accessTopLayerPixels(&info, &rowBytes, nullptr);\n if (addr) {\n pmap->reset(info, addr, rowBytes);\n return true;\n }\n return false;\n}\n\nvoid SkAndroidSDKCanvas::willSave() {\n fProxyTarget->save();\n}\n\nSkCanvas::SaveLayerStrategy SkAndroidSDKCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {\n fProxyTarget->saveLayer(rec);\n return SkCanvas::kNoLayer_SaveLayerStrategy;\n}\n\nvoid SkAndroidSDKCanvas::willRestore() {\n fProxyTarget->restore();\n}\n\nvoid SkAndroidSDKCanvas::didRestore() { }\n\nvoid SkAndroidSDKCanvas::didConcat(const SkMatrix& m) {\n fProxyTarget->concat(m);\n}\n\nvoid SkAndroidSDKCanvas::didSetMatrix(const SkMatrix& m) {\n fProxyTarget->setMatrix(m);\n}\n\nvoid SkAndroidSDKCanvas::onClipRect(const SkRect& rect,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipRect(rect, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipRRect(const SkRRect& rrect,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipRRect(rrect, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipPath(const SkPath& path,\n ClipOp op,\n ClipEdgeStyle style) {\n fProxyTarget->clipPath(path, op, style);\n}\n\nvoid SkAndroidSDKCanvas::onClipRegion(const SkRegion& region, ClipOp op) {\n fProxyTarget->clipRegion(region, op);\n}\n\nvoid SkAndroidSDKCanvas::onDiscard() { fProxyTarget->discard(); }\n<|endoftext|>"} {"text":"#include \"HeatTransferFromHeatStructure1Phase.h\"\n#include \"FlowChannel1Phase.h\"\n#include \"HeatStructure.h\"\n#include \"FlowModelSinglePhase.h\"\n#include \"FlowModelTwoPhase.h\"\n#include \"KDTree.h\"\n#include \"THMMesh.h\"\n#include \"libmesh\/fe_interface.h\"\n\nregisterMooseObject(\"THMApp\", HeatTransferFromHeatStructure1Phase);\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"hs\", \"The name of the heat structure component\");\n MooseEnum hs_sides(\"top bottom\");\n params.addRequiredParam(\"hs_side\", hs_sides, \"The side of the heat structure\");\n params.addClassDescription(\"Connects a 1-phase flow channel and a heat structure\");\n return params;\n}\n\nHeatTransferFromHeatStructure1Phase::HeatTransferFromHeatStructure1Phase(\n const InputParameters & parameters)\n : HeatTransferFromTemperature1Phase(parameters),\n _hs_name(getParam(\"hs\")),\n _hs_side(getParam(\"hs_side\"))\n{\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::checkFlowChannelAlignment() const\n{\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n \/\/ master element centroids\n std::vector master_points;\n \/\/ element ids corresponding to the centroids in `master_points`\n std::vector master_elem_ids;\n \/\/ local side number corresponding to the element id in `master_elem_ids`\n std::vector master_elem_sides;\n \/\/ slave element centroids\n std::vector slave_points;\n \/\/ element ids corresponding to the centroids in `slave_points`\n std::vector slave_elem_ids;\n \/\/\/ Map of the element ID and its nearest element ID\n std::map nearest_elem_ids;\n \/\/\/ Map of the element ID and local side number of the nearest element\n std::map nearest_elem_side;\n\n BoundaryID master_bnd_id = _mesh.getBoundaryID(getMasterSideName());\n BoundaryID slave_bnd_id = _mesh.getBoundaryID(getSlaveSideName());\n\n ConstBndElemRange & range = *_mesh.getBoundaryElementRange();\n for (const auto & belem : range)\n {\n const Elem * elem = belem->_elem;\n BoundaryID boundary_id = belem->_bnd_id;\n\n if (boundary_id == master_bnd_id)\n {\n \/\/ 2D elements\n master_elem_ids.push_back(elem->id());\n master_elem_sides.push_back(belem->_side);\n master_points.push_back(elem->centroid());\n nearest_elem_side.insert(std::pair(elem->id(), belem->_side));\n }\n else if (boundary_id == slave_bnd_id)\n {\n if (std::find(slave_elem_ids.begin(), slave_elem_ids.end(), elem->id()) ==\n slave_elem_ids.end())\n {\n \/\/ 1D elements\n slave_elem_ids.push_back(elem->id());\n slave_points.push_back(elem->centroid());\n }\n }\n }\n\n if (master_points.size() > 0 && slave_points.size() > 0)\n {\n \/\/ find the master elements that are nearest to the slave elements\n KDTree kd_tree(master_points, _mesh.getMaxLeafSize());\n for (std::size_t i = 0; i < slave_points.size(); i++)\n {\n unsigned int patch_size = 1;\n std::vector return_index(patch_size);\n kd_tree.neighborSearch(slave_points[i], patch_size, return_index);\n\n nearest_elem_ids.insert(\n std::pair(slave_elem_ids[i], master_elem_ids[return_index[0]]));\n nearest_elem_ids.insert(\n std::pair(master_elem_ids[return_index[0]], slave_elem_ids[i]));\n }\n\n \/\/ Go over all elements in the flow channel. Take the center of each element and project it onto\n \/\/ the heat structure side. Then check that the projected location on the heat structure matches\n \/\/ the location of the original center of the flow channel element\n const std::vector & fch_elem_ids = flow_channel.getElementIDs();\n for (const auto & elem_id : fch_elem_ids)\n {\n const Elem * elem = _mesh.elemPtr(elem_id);\n Point center_pt = elem->centroid();\n\n const dof_id_type & hs_elem_id = nearest_elem_ids.at(elem_id);\n const unsigned int & hs_elem_side = nearest_elem_side.at(hs_elem_id);\n const Elem * neighbor = _mesh.elemPtr(hs_elem_id);\n const Elem * neighbor_side_elem = neighbor->build_side_ptr(hs_elem_side).release();\n unsigned int neighbor_dim = neighbor_side_elem->dim();\n Point ref_pt =\n FEInterface::inverse_map(neighbor_dim, FEType(), neighbor_side_elem, center_pt);\n Point hs_pt = FEInterface::map(neighbor_dim, FEType(), neighbor_side_elem, ref_pt);\n delete neighbor_side_elem;\n\n if (!center_pt.absolute_fuzzy_equals(hs_pt))\n {\n logError(\"The centers of the elements of flow channel '\",\n _flow_channel_name,\n \"' do not equal the centers of the specified heat structure side.\");\n break;\n }\n }\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::check() const\n{\n HeatTransferFromTemperature1Phase::check();\n\n checkComponentOfTypeExistsByName(_hs_name);\n\n if (hasComponentByName(_hs_name))\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n if (hs.getDimension() == 1)\n logError(\"1D heat structures cannot be used; 2D heat structures must be used instead.\");\n\n const Real & P_hs = hs.getUnitPerimeter(_hs_side);\n if (MooseUtils::absoluteFuzzyEqual(P_hs, 0.))\n logError(\"'hs_side' parameter is set to '\",\n _hs_side,\n \"', but this side of the heat structure '\",\n _hs_name,\n \"' has radius of zero.\");\n }\n\n if (hasComponentByName(_hs_name) &&\n hasComponentByName(_flow_channel_name))\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n if (hs.getNumElems() != flow_channel.getNumElems())\n logError(\"The number of elements in component '\",\n _flow_channel_name,\n \"' is \",\n flow_channel.getNumElems(),\n \", but the number of axial elements in component '\",\n _hs_name,\n \"' is \",\n hs.getNumElems(),\n \". They must be the same.\");\n\n if (hs.getLength() != flow_channel.getLength())\n logError(\"The length of component '\",\n _flow_channel_name,\n \"' is \",\n flow_channel.getLength(),\n \", but the length of component '\",\n _hs_name,\n \"' is \",\n hs.getLength(),\n \". They must be the same.\");\n\n checkFlowChannelAlignment();\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::addVariables()\n{\n HeatTransferFromTemperature1Phase::addVariables();\n\n \/\/ wall temperature initial condition\n if (!_app.isRestarting())\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n _sim.addFunctionIC(_T_wall_name, hs.getInitialT(), _flow_channel_name);\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::addMooseObjects()\n{\n HeatTransferFromTemperature1Phase::addMooseObjects();\n\n ExecFlagEnum execute_on(MooseUtils::getDefaultExecFlagEnum());\n execute_on = {EXEC_INITIAL, EXEC_LINEAR, EXEC_NONLINEAR};\n\n const HeatStructure & hs = getComponentByName(_hs_name);\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n const UserObjectName heat_flux_uo_name = genName(name(), \"heat_flux_uo\");\n {\n const std::string class_name = \"HeatFluxFromHeatStructure3EqnUserObject\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"block\") = flow_channel.getSubdomainNames();\n params.set>(\"slave_boundary\") = {getSlaveSideName()};\n params.set(\"master_boundary\") = getMasterSideName();\n params.set>(\"T_wall\") = {_T_wall_name};\n params.set>(\"P_hf\") = {_P_hf_name};\n params.set(\"Hw\") = _Hw_1phase_name;\n params.set(\"T\") = FlowModelSinglePhase::TEMPERATURE;\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set(\"execute_on\") = execute_on;\n _sim.addUserObject(class_name, heat_flux_uo_name, params);\n }\n\n {\n const std::string class_name = \"OneD3EqnEnergyHeatFlux\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"block\") = flow_channel.getSubdomainNames();\n params.set(\"variable\") = FlowModelSinglePhase::RHOEA;\n params.set>(\"P_hf\") = {_P_hf_name};\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set(\"q_uo\") = heat_flux_uo_name;\n _sim.addKernel(class_name, genName(name(), \"heat_flux_kernel\"), params);\n }\n\n {\n const std::string class_name = \"HeatFlux3EqnBC\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"boundary\") = {getMasterSideName()};\n params.set(\"variable\") = HeatConductionModel::TEMPERATURE;\n params.set(\"q_uo\") = heat_flux_uo_name;\n params.set(\"P_hs_unit\") = hs.getUnitPerimeter(_hs_side);\n params.set(\"n_unit\") = hs.getNumberOfUnits();\n params.set(\"hs_coord_system_is_cylindrical\") = hs.isCylindrical();\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set>(\"T_wall\") = {HeatConductionModel::TEMPERATURE};\n _sim.addBoundaryCondition(class_name, genName(name(), \"heat_flux_bc\"), params);\n }\n\n \/\/ Transfer the temperature of the solid onto the flow channel\n {\n std::string class_name = \"VariableValueTransferAux\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set(\"variable\") = _T_wall_name;\n params.set>(\"boundary\") = {getSlaveSideName()};\n params.set(\"paired_boundary\") = getMasterSideName();\n params.set>(\"paired_variable\") =\n std::vector(1, HeatConductionModel::TEMPERATURE);\n _sim.addAuxBoundaryCondition(class_name, genName(name(), \"T_wall_transfer\"), params);\n }\n}\n\nconst BoundaryName &\nHeatTransferFromHeatStructure1Phase::getMasterSideName() const\n{\n const HeatStructure & hs = getComponentByName(_hs_name);\n\n switch (_hs_side)\n {\n case 0:\n if (hs.getTopBoundaryNames().size() > 0)\n return hs.getTopBoundaryNames()[0];\n else\n return THMMesh::INVALID_BOUNDARY_ID;\n\n case 1:\n if (hs.getBottomBoundaryNames().size() > 0)\n return hs.getBottomBoundaryNames()[0];\n else\n return THMMesh::INVALID_BOUNDARY_ID;\n\n default:\n mooseError(name(), \": Unknown side specified in the 'hs_side' parameter.\");\n }\n}\n\nconst BoundaryName &\nHeatTransferFromHeatStructure1Phase::getSlaveSideName() const\n{\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n return flow_channel.getNodesetName();\n}\nRemoving unused #include#include \"HeatTransferFromHeatStructure1Phase.h\"\n#include \"FlowChannel1Phase.h\"\n#include \"HeatStructure.h\"\n#include \"FlowModelSinglePhase.h\"\n#include \"KDTree.h\"\n#include \"THMMesh.h\"\n#include \"libmesh\/fe_interface.h\"\n\nregisterMooseObject(\"THMApp\", HeatTransferFromHeatStructure1Phase);\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"hs\", \"The name of the heat structure component\");\n MooseEnum hs_sides(\"top bottom\");\n params.addRequiredParam(\"hs_side\", hs_sides, \"The side of the heat structure\");\n params.addClassDescription(\"Connects a 1-phase flow channel and a heat structure\");\n return params;\n}\n\nHeatTransferFromHeatStructure1Phase::HeatTransferFromHeatStructure1Phase(\n const InputParameters & parameters)\n : HeatTransferFromTemperature1Phase(parameters),\n _hs_name(getParam(\"hs\")),\n _hs_side(getParam(\"hs_side\"))\n{\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::checkFlowChannelAlignment() const\n{\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n \/\/ master element centroids\n std::vector master_points;\n \/\/ element ids corresponding to the centroids in `master_points`\n std::vector master_elem_ids;\n \/\/ local side number corresponding to the element id in `master_elem_ids`\n std::vector master_elem_sides;\n \/\/ slave element centroids\n std::vector slave_points;\n \/\/ element ids corresponding to the centroids in `slave_points`\n std::vector slave_elem_ids;\n \/\/\/ Map of the element ID and its nearest element ID\n std::map nearest_elem_ids;\n \/\/\/ Map of the element ID and local side number of the nearest element\n std::map nearest_elem_side;\n\n BoundaryID master_bnd_id = _mesh.getBoundaryID(getMasterSideName());\n BoundaryID slave_bnd_id = _mesh.getBoundaryID(getSlaveSideName());\n\n ConstBndElemRange & range = *_mesh.getBoundaryElementRange();\n for (const auto & belem : range)\n {\n const Elem * elem = belem->_elem;\n BoundaryID boundary_id = belem->_bnd_id;\n\n if (boundary_id == master_bnd_id)\n {\n \/\/ 2D elements\n master_elem_ids.push_back(elem->id());\n master_elem_sides.push_back(belem->_side);\n master_points.push_back(elem->centroid());\n nearest_elem_side.insert(std::pair(elem->id(), belem->_side));\n }\n else if (boundary_id == slave_bnd_id)\n {\n if (std::find(slave_elem_ids.begin(), slave_elem_ids.end(), elem->id()) ==\n slave_elem_ids.end())\n {\n \/\/ 1D elements\n slave_elem_ids.push_back(elem->id());\n slave_points.push_back(elem->centroid());\n }\n }\n }\n\n if (master_points.size() > 0 && slave_points.size() > 0)\n {\n \/\/ find the master elements that are nearest to the slave elements\n KDTree kd_tree(master_points, _mesh.getMaxLeafSize());\n for (std::size_t i = 0; i < slave_points.size(); i++)\n {\n unsigned int patch_size = 1;\n std::vector return_index(patch_size);\n kd_tree.neighborSearch(slave_points[i], patch_size, return_index);\n\n nearest_elem_ids.insert(\n std::pair(slave_elem_ids[i], master_elem_ids[return_index[0]]));\n nearest_elem_ids.insert(\n std::pair(master_elem_ids[return_index[0]], slave_elem_ids[i]));\n }\n\n \/\/ Go over all elements in the flow channel. Take the center of each element and project it onto\n \/\/ the heat structure side. Then check that the projected location on the heat structure matches\n \/\/ the location of the original center of the flow channel element\n const std::vector & fch_elem_ids = flow_channel.getElementIDs();\n for (const auto & elem_id : fch_elem_ids)\n {\n const Elem * elem = _mesh.elemPtr(elem_id);\n Point center_pt = elem->centroid();\n\n const dof_id_type & hs_elem_id = nearest_elem_ids.at(elem_id);\n const unsigned int & hs_elem_side = nearest_elem_side.at(hs_elem_id);\n const Elem * neighbor = _mesh.elemPtr(hs_elem_id);\n const Elem * neighbor_side_elem = neighbor->build_side_ptr(hs_elem_side).release();\n unsigned int neighbor_dim = neighbor_side_elem->dim();\n Point ref_pt =\n FEInterface::inverse_map(neighbor_dim, FEType(), neighbor_side_elem, center_pt);\n Point hs_pt = FEInterface::map(neighbor_dim, FEType(), neighbor_side_elem, ref_pt);\n delete neighbor_side_elem;\n\n if (!center_pt.absolute_fuzzy_equals(hs_pt))\n {\n logError(\"The centers of the elements of flow channel '\",\n _flow_channel_name,\n \"' do not equal the centers of the specified heat structure side.\");\n break;\n }\n }\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::check() const\n{\n HeatTransferFromTemperature1Phase::check();\n\n checkComponentOfTypeExistsByName(_hs_name);\n\n if (hasComponentByName(_hs_name))\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n if (hs.getDimension() == 1)\n logError(\"1D heat structures cannot be used; 2D heat structures must be used instead.\");\n\n const Real & P_hs = hs.getUnitPerimeter(_hs_side);\n if (MooseUtils::absoluteFuzzyEqual(P_hs, 0.))\n logError(\"'hs_side' parameter is set to '\",\n _hs_side,\n \"', but this side of the heat structure '\",\n _hs_name,\n \"' has radius of zero.\");\n }\n\n if (hasComponentByName(_hs_name) &&\n hasComponentByName(_flow_channel_name))\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n if (hs.getNumElems() != flow_channel.getNumElems())\n logError(\"The number of elements in component '\",\n _flow_channel_name,\n \"' is \",\n flow_channel.getNumElems(),\n \", but the number of axial elements in component '\",\n _hs_name,\n \"' is \",\n hs.getNumElems(),\n \". They must be the same.\");\n\n if (hs.getLength() != flow_channel.getLength())\n logError(\"The length of component '\",\n _flow_channel_name,\n \"' is \",\n flow_channel.getLength(),\n \", but the length of component '\",\n _hs_name,\n \"' is \",\n hs.getLength(),\n \". They must be the same.\");\n\n checkFlowChannelAlignment();\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::addVariables()\n{\n HeatTransferFromTemperature1Phase::addVariables();\n\n \/\/ wall temperature initial condition\n if (!_app.isRestarting())\n {\n const HeatStructure & hs = getComponentByName(_hs_name);\n _sim.addFunctionIC(_T_wall_name, hs.getInitialT(), _flow_channel_name);\n }\n}\n\nvoid\nHeatTransferFromHeatStructure1Phase::addMooseObjects()\n{\n HeatTransferFromTemperature1Phase::addMooseObjects();\n\n ExecFlagEnum execute_on(MooseUtils::getDefaultExecFlagEnum());\n execute_on = {EXEC_INITIAL, EXEC_LINEAR, EXEC_NONLINEAR};\n\n const HeatStructure & hs = getComponentByName(_hs_name);\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n\n const UserObjectName heat_flux_uo_name = genName(name(), \"heat_flux_uo\");\n {\n const std::string class_name = \"HeatFluxFromHeatStructure3EqnUserObject\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"block\") = flow_channel.getSubdomainNames();\n params.set>(\"slave_boundary\") = {getSlaveSideName()};\n params.set(\"master_boundary\") = getMasterSideName();\n params.set>(\"T_wall\") = {_T_wall_name};\n params.set>(\"P_hf\") = {_P_hf_name};\n params.set(\"Hw\") = _Hw_1phase_name;\n params.set(\"T\") = FlowModelSinglePhase::TEMPERATURE;\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set(\"execute_on\") = execute_on;\n _sim.addUserObject(class_name, heat_flux_uo_name, params);\n }\n\n {\n const std::string class_name = \"OneD3EqnEnergyHeatFlux\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"block\") = flow_channel.getSubdomainNames();\n params.set(\"variable\") = FlowModelSinglePhase::RHOEA;\n params.set>(\"P_hf\") = {_P_hf_name};\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set(\"q_uo\") = heat_flux_uo_name;\n _sim.addKernel(class_name, genName(name(), \"heat_flux_kernel\"), params);\n }\n\n {\n const std::string class_name = \"HeatFlux3EqnBC\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set>(\"boundary\") = {getMasterSideName()};\n params.set(\"variable\") = HeatConductionModel::TEMPERATURE;\n params.set(\"q_uo\") = heat_flux_uo_name;\n params.set(\"P_hs_unit\") = hs.getUnitPerimeter(_hs_side);\n params.set(\"n_unit\") = hs.getNumberOfUnits();\n params.set(\"hs_coord_system_is_cylindrical\") = hs.isCylindrical();\n params.set>(\"rhoA\") = {FlowModelSinglePhase::RHOA};\n params.set>(\"rhouA\") = {FlowModelSinglePhase::RHOUA};\n params.set>(\"rhoEA\") = {FlowModelSinglePhase::RHOEA};\n params.set>(\"T_wall\") = {HeatConductionModel::TEMPERATURE};\n _sim.addBoundaryCondition(class_name, genName(name(), \"heat_flux_bc\"), params);\n }\n\n \/\/ Transfer the temperature of the solid onto the flow channel\n {\n std::string class_name = \"VariableValueTransferAux\";\n InputParameters params = _factory.getValidParams(class_name);\n params.set(\"variable\") = _T_wall_name;\n params.set>(\"boundary\") = {getSlaveSideName()};\n params.set(\"paired_boundary\") = getMasterSideName();\n params.set>(\"paired_variable\") =\n std::vector(1, HeatConductionModel::TEMPERATURE);\n _sim.addAuxBoundaryCondition(class_name, genName(name(), \"T_wall_transfer\"), params);\n }\n}\n\nconst BoundaryName &\nHeatTransferFromHeatStructure1Phase::getMasterSideName() const\n{\n const HeatStructure & hs = getComponentByName(_hs_name);\n\n switch (_hs_side)\n {\n case 0:\n if (hs.getTopBoundaryNames().size() > 0)\n return hs.getTopBoundaryNames()[0];\n else\n return THMMesh::INVALID_BOUNDARY_ID;\n\n case 1:\n if (hs.getBottomBoundaryNames().size() > 0)\n return hs.getBottomBoundaryNames()[0];\n else\n return THMMesh::INVALID_BOUNDARY_ID;\n\n default:\n mooseError(name(), \": Unknown side specified in the 'hs_side' parameter.\");\n }\n}\n\nconst BoundaryName &\nHeatTransferFromHeatStructure1Phase::getSlaveSideName() const\n{\n const FlowChannel1Phase & flow_channel =\n getComponentByName(_flow_channel_name);\n return flow_channel.getNodesetName();\n}\n<|endoftext|>"} {"text":"#include \"inverseIndexStorageUnorderedMap.h\"\n#ifdef OPENMP\n#include \n#endif\n \nInverseIndexStorageUnorderedMap::InverseIndexStorageUnorderedMap(size_t pSizeOfInverseIndex, size_t pMaxBinSize) {\n\tmSignatureStorage = new vector__umapVector(pSizeOfInverseIndex);\n\tmMaxBinSize = pMaxBinSize;\n\tmKeys = new vvsize_t(pSizeOfInverseIndex, vsize_t());\n\tmValues = new vvsize_t(pSizeOfInverseIndex, vsize_t());\n}\nInverseIndexStorageUnorderedMap::~InverseIndexStorageUnorderedMap() {\n\tdelete mSignatureStorage;\n delete mKeys;\n delete mValues;\n}\nsize_t InverseIndexStorageUnorderedMap::size() const {\n\treturn mSignatureStorage->size();\n}\nconst vsize_t* InverseIndexStorageUnorderedMap::getElement(size_t pVectorId, size_t pHashValue) {\n \/\/ std::cout << __LINE__ << std::endl;\n \n\tauto iterator = (*mSignatureStorage)[pVectorId].find(pHashValue);\n\tif (iterator != (*mSignatureStorage)[pVectorId].end()) {\n\t\treturn &(iterator->second);\n\t}\n \/\/ vsize_t foo;\n\treturn NULL;\n \/\/ std::cout << __LINE__ << std::endl;\n \n\t\n}\nvoid InverseIndexStorageUnorderedMap::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) {\n \/\/ std::cout << __LINE__ << std::endl;\n \n#ifdef OPENMP\n#pragma omp critical\n#endif\n {\t\n auto itHashValue_InstanceVector = (*mSignatureStorage)[pVectorId].find(pHashValue);\n \/\/ if for hash function h_i() the given hash values is already stored\n if (itHashValue_InstanceVector != (*mSignatureStorage)[pVectorId].end()) {\n \/\/ insert the instance id if not too many collisions (maxBinSize)\n if (itHashValue_InstanceVector->second.size() && itHashValue_InstanceVector->second.size() < mMaxBinSize) {\n \/\/ insert only if there wasn't any collisions in the past\n if (itHashValue_InstanceVector->second.size() > 0) {\n itHashValue_InstanceVector->second.push_back(pInstance);\n }\n } else { \n \/\/ too many collisions: delete stored ids. empty vector is interpreted as an error code \n \/\/ for too many collisions\n itHashValue_InstanceVector->second.clear();\n }\n } else {\n \/\/ given hash value for the specific hash function was not avaible: insert new hash value\n vsize_t instanceIdVector;\n instanceIdVector.push_back(pInstance);\n (*mSignatureStorage)[pVectorId][pHashValue] = instanceIdVector;\n }\n }\n}\n\ndistributionInverseIndex* InverseIndexStorageUnorderedMap::getDistribution() {\n distributionInverseIndex* retVal = new distributionInverseIndex();\n std::map distribution;\n vsize_t numberOfCreatedHashValuesPerHashFunction;\n vsize_t averageNumberOfValuesPerHashValue;\n vsize_t standardDeviationPerNumberOfValuesPerHashValue;\n size_t meanForNumberHashValues = 0;\n \n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n numberOfCreatedHashValuesPerHashFunction.push_back(it->size());\n meanForNumberHashValues += it->size();\n size_t mean = 0;\n \n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n distribution[itMap->second.size()] += 1;\n mean += itMap->second.size();\n }\n if (it->size() != 0 || mean != 0) {\n mean = mean \/ it->size(); \n }\n averageNumberOfValuesPerHashValue.push_back(mean);\n \n size_t variance = 0;\n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n variance += pow(static_cast(itMap->second.size()) - mean, 2);\n }\n \n variance = variance \/ mSignatureStorage->size();\n int standardDeviation = sqrt(variance);\n standardDeviationPerNumberOfValuesPerHashValue.push_back(standardDeviation);\n }\n \n size_t varianceForNumberOfHashValues = 0;\n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n varianceForNumberOfHashValues += pow(it->size() - meanForNumberHashValues, 2);\n }\n \n retVal->mean = meanForNumberHashValues;\n retVal->standardDeviation = sqrt(varianceForNumberOfHashValues);\n \n retVal->totalCountForOccurenceOfHashValues = distribution;\n retVal->standardDeviationForNumberOfValuesPerHashValue = standardDeviationPerNumberOfValuesPerHashValue;\n retVal->meanForNumberOfValuesPerHashValue = averageNumberOfValuesPerHashValue;\n \n retVal->numberOfCreatedHashValuesPerHashFunction = numberOfCreatedHashValuesPerHashFunction;\n \n return retVal;\n}\nvoid InverseIndexStorageUnorderedMap::prune(int pValue) {\n \/\/ std::cout << __LINE__ << std::endl;\n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n vsize_t elementsToDelete;\n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n if (itMap->second.size() <= pValue) {\n elementsToDelete.push_back(itMap->first);\n }\n \/\/ (*distribution)[itMap->second.size()] += 1;\n }\n for (size_t i = 0; i < elementsToDelete.size(); ++i) {\n it->erase(elementsToDelete[i]);\n }\n elementsToDelete.clear();\n }\n \/\/ std::cout << __LINE__ << std::endl;\n \n}\n\n\/\/ if pRemoveHashFunctionWithLessEntriesAs == 0 remove every hash function \n\/\/ which has less entries than mean+standard deviation\n\/\/ else: remove every hash function which has less entries than pRemoveHashFunctionWithLessEntriesAs\nvoid InverseIndexStorageUnorderedMap::removeHashFunctionWithLessEntriesAs(int pRemoveHashFunctionWithLessEntriesAs) {\n \/\/ std::cout << __LINE__ << std::endl;\n \n if (pRemoveHashFunctionWithLessEntriesAs == 0) {\n int mean = 0;\n int variance = 0;\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n mean += (*mSignatureStorage)[i].size();\n }\n mean = mean \/ mSignatureStorage->size();\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n variance += pow(static_cast((*mSignatureStorage)[i].size()) - mean, 2);\n }\n variance = variance \/ mSignatureStorage->size();\n int standardDeviation = sqrt(variance);\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n if ((*mSignatureStorage)[i].size() < mean + standardDeviation) {\n (*mSignatureStorage)[i].clear();\n }\n }\n } else {\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n if ((*mSignatureStorage)[i].size() < pRemoveHashFunctionWithLessEntriesAs) {\n (*mSignatureStorage)[i].clear();\n }\n }\n }\n \/\/ std::cout << __LINE__ << std::endl;\n \n}extended to not store values with two 00 at the end#include \"inverseIndexStorageUnorderedMap.h\"\n#ifdef OPENMP\n#include \n#endif\n \nInverseIndexStorageUnorderedMap::InverseIndexStorageUnorderedMap(size_t pSizeOfInverseIndex, size_t pMaxBinSize) {\n\tmSignatureStorage = new vector__umapVector(pSizeOfInverseIndex);\n\tmMaxBinSize = pMaxBinSize;\n\tmKeys = new vvsize_t(pSizeOfInverseIndex, vsize_t());\n\tmValues = new vvsize_t(pSizeOfInverseIndex, vsize_t());\n}\nInverseIndexStorageUnorderedMap::~InverseIndexStorageUnorderedMap() {\n\tdelete mSignatureStorage;\n delete mKeys;\n delete mValues;\n}\nsize_t InverseIndexStorageUnorderedMap::size() const {\n\treturn mSignatureStorage->size();\n}\nconst vsize_t* InverseIndexStorageUnorderedMap::getElement(size_t pVectorId, size_t pHashValue) {\n \/\/ std::cout << __LINE__ << std::endl;\n \n\tauto iterator = (*mSignatureStorage)[pVectorId].find(pHashValue);\n\tif (iterator != (*mSignatureStorage)[pVectorId].end()) {\n\t\treturn &(iterator->second);\n\t}\n \/\/ vsize_t foo;\n\treturn NULL;\n \/\/ std::cout << __LINE__ << std::endl;\n \n\t\n}\nvoid InverseIndexStorageUnorderedMap::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) {\n \/\/ std::cout << __LINE__ << std::endl;\n size_t insertValue = pHashValue | 0b11111111111111111111111111111100;\n if (insertValue == 0b11111111111111111111111111111100) {\n return;\n }\n#ifdef OPENMP\n#pragma omp critical\n#endif\n {\t\n auto itHashValue_InstanceVector = (*mSignatureStorage)[pVectorId].find(pHashValue);\n \/\/ if for hash function h_i() the given hash values is already stored\n if (itHashValue_InstanceVector != (*mSignatureStorage)[pVectorId].end()) {\n \/\/ insert the instance id if not too many collisions (maxBinSize)\n if (itHashValue_InstanceVector->second.size() && itHashValue_InstanceVector->second.size() < mMaxBinSize) {\n \/\/ insert only if there wasn't any collisions in the past\n if (itHashValue_InstanceVector->second.size() > 0) {\n itHashValue_InstanceVector->second.push_back(pInstance);\n }\n } else { \n \/\/ too many collisions: delete stored ids. empty vector is interpreted as an error code \n \/\/ for too many collisions\n itHashValue_InstanceVector->second.clear();\n }\n } else {\n \/\/ given hash value for the specific hash function was not avaible: insert new hash value\n vsize_t instanceIdVector;\n instanceIdVector.push_back(pInstance);\n (*mSignatureStorage)[pVectorId][pHashValue] = instanceIdVector;\n }\n }\n}\n\ndistributionInverseIndex* InverseIndexStorageUnorderedMap::getDistribution() {\n distributionInverseIndex* retVal = new distributionInverseIndex();\n std::map distribution;\n vsize_t numberOfCreatedHashValuesPerHashFunction;\n vsize_t averageNumberOfValuesPerHashValue;\n vsize_t standardDeviationPerNumberOfValuesPerHashValue;\n size_t meanForNumberHashValues = 0;\n \n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n numberOfCreatedHashValuesPerHashFunction.push_back(it->size());\n meanForNumberHashValues += it->size();\n size_t mean = 0;\n \n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n distribution[itMap->second.size()] += 1;\n mean += itMap->second.size();\n }\n if (it->size() != 0 || mean != 0) {\n mean = mean \/ it->size(); \n }\n averageNumberOfValuesPerHashValue.push_back(mean);\n \n size_t variance = 0;\n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n variance += pow(static_cast(itMap->second.size()) - mean, 2);\n }\n \n variance = variance \/ mSignatureStorage->size();\n int standardDeviation = sqrt(variance);\n standardDeviationPerNumberOfValuesPerHashValue.push_back(standardDeviation);\n }\n \n size_t varianceForNumberOfHashValues = 0;\n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n varianceForNumberOfHashValues += pow(it->size() - meanForNumberHashValues, 2);\n }\n \n retVal->mean = meanForNumberHashValues;\n retVal->standardDeviation = sqrt(varianceForNumberOfHashValues);\n \n retVal->totalCountForOccurenceOfHashValues = distribution;\n retVal->standardDeviationForNumberOfValuesPerHashValue = standardDeviationPerNumberOfValuesPerHashValue;\n retVal->meanForNumberOfValuesPerHashValue = averageNumberOfValuesPerHashValue;\n \n retVal->numberOfCreatedHashValuesPerHashFunction = numberOfCreatedHashValuesPerHashFunction;\n \n return retVal;\n}\nvoid InverseIndexStorageUnorderedMap::prune(int pValue) {\n \/\/ std::cout << __LINE__ << std::endl;\n for (auto it = mSignatureStorage->begin(); it != mSignatureStorage->end(); ++it) {\n vsize_t elementsToDelete;\n for (auto itMap = it->begin(); itMap != it->end(); ++itMap) {\n if (itMap->second.size() <= pValue) {\n elementsToDelete.push_back(itMap->first);\n }\n \/\/ (*distribution)[itMap->second.size()] += 1;\n }\n for (size_t i = 0; i < elementsToDelete.size(); ++i) {\n it->erase(elementsToDelete[i]);\n }\n elementsToDelete.clear();\n }\n \/\/ std::cout << __LINE__ << std::endl;\n \n}\n\n\/\/ if pRemoveHashFunctionWithLessEntriesAs == 0 remove every hash function \n\/\/ which has less entries than mean+standard deviation\n\/\/ else: remove every hash function which has less entries than pRemoveHashFunctionWithLessEntriesAs\nvoid InverseIndexStorageUnorderedMap::removeHashFunctionWithLessEntriesAs(int pRemoveHashFunctionWithLessEntriesAs) {\n \/\/ std::cout << __LINE__ << std::endl;\n \n if (pRemoveHashFunctionWithLessEntriesAs == 0) {\n int mean = 0;\n int variance = 0;\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n mean += (*mSignatureStorage)[i].size();\n }\n mean = mean \/ mSignatureStorage->size();\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n variance += pow(static_cast((*mSignatureStorage)[i].size()) - mean, 2);\n }\n variance = variance \/ mSignatureStorage->size();\n int standardDeviation = sqrt(variance);\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n if ((*mSignatureStorage)[i].size() < mean + standardDeviation) {\n (*mSignatureStorage)[i].clear();\n }\n }\n } else {\n for (size_t i = 0; i < mSignatureStorage->size(); ++i) {\n if ((*mSignatureStorage)[i].size() < pRemoveHashFunctionWithLessEntriesAs) {\n (*mSignatureStorage)[i].clear();\n }\n }\n }\n \/\/ std::cout << __LINE__ << std::endl;\n \n}<|endoftext|>"} {"text":"#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX600 グループ・8 ビットタイマ(TMR)定義\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/device.hpp\"\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief 8 ビットタイマ(TMR)\r\n\t\t@param[in]\tbase\tベースアドレス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate \r\n\tstruct tmr_t {\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイマカウンタ(TCNT)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw8_t TCNT;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイムコンスタントレジスタ A(TCORA)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw8_t TCORA;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイムコンスタントレジスタ B(TCORB)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw8_t TCORB;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tタイマコントロールレジスタ(TCR)\r\n\t\t\t@param[in]\tofs\tアドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct tcr_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t CCLR;\r\n\t\t\tbit_rw_t OVIE;\r\n\t\t\tbit_rw_t CMIEA;\r\n\t\t\tbit_rw_t CMIEB;\r\n\t\t};\r\n\t\tstatic tcr_t TCR;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tタイマカウンタコントロールレジスタ(TCCR)\r\n\t\t\t@param[in]\tofs\tアドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct tccr_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t CKS;\r\n\t\t\tbits_rw_t CSS;\r\n\t\t\tbit_rw_t TMRIS;\r\n\t\t};\r\n\t\tstatic tccr_t TCCR;\r\n\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief 8 ビットタイマ(TMR)偶数版\r\n\t\t@param[in]\tbase\tベースアドレス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate \r\n\tstruct tmr0246_t : public tmr_t {\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイマカウンタ(TCNTW)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw16_t TCNT16;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイムコンスタントレジスタ A(TCORA)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw16_t TCORA16;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brie\tタイムコンスタントレジスタ B(TCORB)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic rw16_t TCORB16;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tタイマコントロール/ステータスレジスタ(TCSR)\r\n\t\t\t@param[in]\tofs\tアドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct tcsr_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t OSA;\r\n\t\t\tbits_rw_t OSB;\r\n\t\t\tbit_rw_t ADTE;\r\n\t\t};\r\n\t\tstatic tcsr_t TCSR;\r\n\r\n\t};\r\n\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief 8 ビットタイマ(TMR)奇数版\r\n\t\t@param[in]\tbase\tベースアドレス\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate \r\n\tstruct tmr1357_t : public tmr_t {\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\tタイマコントロール/ステータスレジスタ(TCSR)\r\n\t\t\t@param[in]\tofs\tアドレス\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct tcsr_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t OSA;\r\n\t\t\tbits_rw_t OSB;\r\n\t\t};\r\n\t\tstatic tcsr_t TCSR;\r\n\r\n\t};\r\n\r\n\ttypedef tmr0246_t<0x00088200> TMR0;\r\n\ttypedef tmr1357_t<0x00088201> TMR1;\r\n\ttypedef tmr0246_t<0x00088210> TMR2;\r\n\ttypedef tmr1357_t<0x00088211> TMR3;\r\n#if defined(SIG_RX24T) || defined(SIG_RX66T)\r\n\ttypedef tmr0246_t<0x00088220> TMR4;\r\n\ttypedef tmr1357_t<0x00088221> TMR5;\r\n\ttypedef tmr0246_t<0x00088230> TMR6;\r\n\ttypedef tmr1357_t<0x00088231> TMR7;\r\n#endif\r\n}\r\nUpdate: The reality of the template when it is not optimized#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX600 グループ・8 ビットタイマ(TMR)定義\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2016, 2020 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/device.hpp\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8 ビットタイマ(TMR)\n\t\t@param[in]\tbase\tベースアドレス\n\t\t@param[in]\tper\t\tペリフェラル型\n\t\t@param[in]\tINT\t\t割り込み型\n\t\t@param[in]\tcmia\tCMIA 型割り込みベクター\n\t\t@param[in]\tcmib\tCMIB 型割り込みベクター\n\t\t@param[in]\tovi\t\tOVI 型割り込みベクター\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct tmr_t {\n\n\t\tstatic const auto PERIPHERAL = per;\t\t\/\/\/< ペリフェラル型\n\t\tstatic const auto CMIA_VEC = cmia;\t\t\/\/\/< CMIA 割り込みベクタ\n\t\tstatic const auto CMIB_VEC = cmib;\t\t\/\/\/< CMIB 割り込みベクタ\n\t\tstatic const auto OVI_VEC = ovi;\t\t\/\/\/< OVI 割り込みベクタ\n\t\tstatic const uint32_t PCLK = F_PCLKB;\t\/\/\/< PCLK 周波数\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイマカウンタ(TCNT)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw8_t TCNT_;\n\t\tstatic TCNT_ TCNT;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイムコンスタントレジスタ A(TCORA)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw8_t TCORA_;\n\t\tstatic TCORA_ TCORA;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイムコンスタントレジスタ B(TCORB)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw8_t TCORB_;\n\t\tstatic TCORB_ TCORB;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tタイマコントロールレジスタ(TCR)\n\t\t\t@param[in]\tofs\tアドレス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct tcr_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t CCLR;\n\t\t\tbit_rw_t OVIE;\n\t\t\tbit_rw_t CMIEA;\n\t\t\tbit_rw_t CMIEB;\n\t\t};\n\t\ttypedef tcr_t TCR_;\n\t\tstatic TCR_ TCR;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tタイマカウンタコントロールレジスタ(TCCR)\n\t\t\t@param[in]\tofs\tアドレス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct tccr_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t CKS;\n\t\t\tbits_rw_t CSS;\n\t\t\tbit_rw_t TMRIS;\n\t\t};\n\t\ttypedef tccr_t TCCR_;\n\t\tstatic TCCR_ TCCR;\n\t};\n\ttemplate \n\t\ttypename tmr_t::TCNT_ tmr_t::TCNT;\n\ttemplate \n\t\ttypename tmr_t::TCORA_ tmr_t::TCORA;\n\ttemplate \n\t\ttypename tmr_t::TCORB_ tmr_t::TCORB;\n\ttemplate \n\t\ttypename tmr_t::TCR_ tmr_t::TCR;\n\ttemplate \n\t\ttypename tmr_t::TCCR_ tmr_t::TCCR;\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8 ビットタイマ(TMR)偶数版\n\t\t@param[in]\tbase\tベースアドレス\n\t\t@param[in]\tper\t\tペリフェラル型\n\t\t@param[in]\tINT\t\t割り込み型\n\t\t@param[in]\tcmia\tCMIA 型割り込みベクター\n\t\t@param[in]\tcmib\tCMIB 型割り込みベクター\n\t\t@param[in]\tovi\t\tOVI 型割り込みベクター\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct tmr0246_t : public tmr_t {\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイマカウンタ(TCNTW)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw16_t TCNT16_;\n\t\tstatic TCNT16_ TCNT16;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイムコンスタントレジスタ A(TCORA)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw16_t TCORA16_;\n\t\tstatic TCORA16_ TCORA16;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brie\tタイムコンスタントレジスタ B(TCORB)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttypedef rw16_t TCORB16_;\n\t\tstatic TCORB16_ TCORB16;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tタイマコントロール/ステータスレジスタ(TCSR)\n\t\t\t@param[in]\tofs\tアドレス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct tcsr_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t OSA;\n\t\t\tbits_rw_t OSB;\n\t\t\tbit_rw_t ADTE;\n\t\t};\n\t\ttypedef tcsr_t TCSR_;\n\t\tstatic TCSR_ TCSR;\n\t};\n\ttemplate \n\t\ttypename tmr0246_t::TCNT16_ tmr0246_t::TCNT16;\n\ttemplate \n\t\ttypename tmr0246_t::TCORA16_ tmr0246_t::TCORA16;\n\ttemplate \n\t\ttypename tmr0246_t::TCORB16_ tmr0246_t::TCORB16;\n\ttemplate \n\t\ttypename tmr0246_t::TCSR_ tmr0246_t::TCSR;\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8 ビットタイマ(TMR)奇数版\n\t\t@param[in]\tbase\tベースアドレス\n\t\t@param[in]\tper\t\tペリフェラル型\n\t\t@param[in]\tINT\t\t割り込み型\n\t\t@param[in]\tcmia\tCMIA 型割り込みベクター\n\t\t@param[in]\tcmib\tCMIB 型割り込みベクター\n\t\t@param[in]\tovi\t\tOVI 型割り込みベクター\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct tmr1357_t : public tmr_t {\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief\tタイマコントロール/ステータスレジスタ(TCSR)\n\t\t\t@param[in]\tofs\tアドレス\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct tcsr_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t OSA;\n\t\t\tbits_rw_t OSB;\n\t\t};\n\t\ttypedef tcsr_t TCSR_;\n\t\tstatic TCSR_ TCSR;\n\t};\n\ttemplate \n\t\ttypename tmr1357_t::TCSR_ tmr1357_t::TCSR;\n\n\n#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N) || defined(SIG_RX72M)\n\ttypedef tmr0246_t<0x00088200, peripheral::TMR0, ICU::VECTOR_SELB,\n\t\tICU::VECTOR_SELB::CMIA0, ICU::VECTOR_SELB::CMIB0, ICU::VECTOR_SELB::OVI0> TMR0;\n\ttypedef tmr1357_t<0x00088201, peripheral::TMR1, ICU::VECTOR_SELB,\n\t\tICU::VECTOR_SELB::CMIA1, ICU::VECTOR_SELB::CMIB1, ICU::VECTOR_SELB::OVI1> TMR1;\n\ttypedef tmr0246_t<0x00088210, peripheral::TMR2, ICU::VECTOR_SELB,\n\t\tICU::VECTOR_SELB::CMIA2, ICU::VECTOR_SELB::CMIB2, ICU::VECTOR_SELB::OVI2> TMR2;\n\ttypedef tmr1357_t<0x00088211, peripheral::TMR3, ICU::VECTOR_SELB,\n\t\tICU::VECTOR_SELB::CMIA3, ICU::VECTOR_SELB::CMIB3, ICU::VECTOR_SELB::OVI3> TMR3;\n#endif\n\n#if defined(SIG_RX24T) || defined(SIG_RX66T)\n\ttypedef tmr0246_t<0x00088200, peripheral::TMR0, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA0, ICU::VECTOR::CMIB0, ICU::VECTOR::OVI0> TMR0;\n\ttypedef tmr1357_t<0x00088201, peripheral::TMR1, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA1, ICU::VECTOR::CMIB1, ICU::VECTOR::OVI1> TMR1;\n\ttypedef tmr0246_t<0x00088210, peripheral::TMR2, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA2, ICU::VECTOR::CMIB2, ICU::VECTOR::OVI2> TMR2;\n\ttypedef tmr1357_t<0x00088211, peripheral::TMR3, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA3, ICU::VECTOR::CMIB3, ICU::VECTOR::OVI3> TMR3;\n\ttypedef tmr0246_t<0x00088220, peripheral::TMR4, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA4, ICU::VECTOR::CMIB4, ICU::VECTOR::OVI4> TMR4;\n\ttypedef tmr1357_t<0x00088221, peripheral::TMR5, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA5, ICU::VECTOR::CMIB5, ICU::VECTOR::OVI5> TMR5;\n\ttypedef tmr0246_t<0x00088230, peripheral::TMR6, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA6, ICU::VECTOR::CMIB6, ICU::VECTOR::OVI6> TMR6;\n\ttypedef tmr1357_t<0x00088231, peripheral::TMR7, ICU::VECTOR,\n\t\tICU::VECTOR::CMIA7, ICU::VECTOR::CMIB7, ICU::VECTOR::OVI7> TMR7;\n#endif\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstruct FailureUnit {\n\tchar key[16];\n\tuint8_t value;\n};\n\nstatic constexpr FailureUnit failure_units[] = {\n\t{ \"gyro\", vehicle_command_s::FAILURE_UNIT_SENSOR_GYRO},\n\t{ \"accel\", vehicle_command_s::FAILURE_UNIT_SENSOR_ACCEL},\n\t{ \"mag\", vehicle_command_s::FAILURE_UNIT_SENSOR_MAG},\n\t{ \"baro\", vehicle_command_s::FAILURE_UNIT_SENSOR_BARO},\n\t{ \"gps\", vehicle_command_s::FAILURE_UNIT_SENSOR_GPS},\n\t{ \"optical_flow\", vehicle_command_s::FAILURE_UNIT_SENSOR_OPTICAL_FLOW},\n\t{ \"vio\", vehicle_command_s::FAILURE_UNIT_SENSOR_VIO},\n\t{ \"distance_sensor\", vehicle_command_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR},\n\t{ \"airspeed\", vehicle_command_s::FAILURE_UNIT_SENSOR_AIRSPEED},\n\t{ \"battery\", vehicle_command_s::FAILURE_UNIT_SYSTEM_BATTERY},\n\t{ \"motor\", vehicle_command_s::FAILURE_UNIT_SYSTEM_MOTOR},\n\t{ \"servo\", vehicle_command_s::FAILURE_UNIT_SYSTEM_SERVO},\n\t{ \"avoidance\", vehicle_command_s::FAILURE_UNIT_SYSTEM_AVOIDANCE},\n\t{ \"rc_signal\", vehicle_command_s::FAILURE_UNIT_SYSTEM_RC_SIGNAL},\n\t{ \"mavlink_signal\", vehicle_command_s::FAILURE_UNIT_SYSTEM_MAVLINK_SIGNAL},\n};\n\nstruct FailureType {\n\tchar key[14];\n\tuint8_t value;\n};\n\nstatic constexpr FailureType failure_types[] = {\n\t{ \"ok\", vehicle_command_s::FAILURE_TYPE_OK},\n\t{ \"off\", vehicle_command_s::FAILURE_TYPE_OFF},\n\t{ \"stuck\", vehicle_command_s::FAILURE_TYPE_STUCK},\n\t{ \"garbage\", vehicle_command_s::FAILURE_TYPE_GARBAGE},\n\t{ \"wrong\", vehicle_command_s::FAILURE_TYPE_WRONG},\n\t{ \"slow\", vehicle_command_s::FAILURE_TYPE_SLOW},\n\t{ \"delayed\", vehicle_command_s::FAILURE_TYPE_DELAYED},\n\t{ \"intermittent\", vehicle_command_s::FAILURE_TYPE_INTERMITTENT},\n};\n\n\nstatic void print_usage()\n{\n\tPRINT_MODULE_DESCRIPTION(\n\t\tR\"DESCR_STR(\n### Description\nInject failures into system.\n\n### Implementation\nThis system command sends a vehicle command over uORB to trigger failure.\n\n### Examples\nTest the GPS failsafe by stopping GPS:\n\nfailure gps off\n)DESCR_STR\");\n\n\tPRINT_MODULE_USAGE_NAME_SIMPLE(\"failure\", \"command\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"help\", \"Show this help text\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"gps|...\", \"Specify component\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"ok|off|...\", \"Specify failure type\");\n\n\tPX4_INFO_RAW(\"\\nComponents:\\n\");\n\tfor (const auto &failure_unit : failure_units) {\n\t\tPX4_INFO_RAW(\"- %s\\n\", failure_unit.key);\n\t}\n\n\tPX4_INFO_RAW(\"\\nFailure types:\\n\");\n\tfor (const auto &failure_type : failure_types) {\n\t\tPX4_INFO_RAW(\"- %s\\n\", failure_type.key);\n\t}\n}\n\n\nint inject_failure(uint8_t unit, uint8_t type)\n{\n\tconst hrt_abstime now = hrt_absolute_time();\n\n\tuORB::Subscription command_ack_sub{ORB_ID(vehicle_command_ack)};\n\n\tuORB::PublicationQueued command_pub{ORB_ID(vehicle_command)};\n\tvehicle_command_s command{};\n\tcommand.timestamp = now;\n\tcommand.command = vehicle_command_s::VEHICLE_CMD_INJECT_FAILURE;\n\tcommand.param1 = static_cast(unit);\n\tcommand.param2 = static_cast(type);\n\tcommand_pub.publish(command);\n\n\tvehicle_command_ack_s ack;\n\twhile (hrt_elapsed_time(&now) < 1000000) {\n\t\tif (!command_ack_sub.update(&ack)) {\n\t\t\tif (ack.command == command.command) {\n\t\t\t\tif (ack.result != vehicle_command_ack_s::VEHICLE_RESULT_ACCEPTED) {\n\t\t\t\t\tPX4_ERR(\"Result: %d\", ack.result);\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpx4_usleep(10000);\n\t}\n\tPX4_ERR(\"Timeout waiting for ack\");\n\treturn 1;\n}\n\nextern \"C\" __EXPORT int failure_main(int argc, char *argv[])\n{\n\tif (argc == 2 && strcmp(argv[1], \"help\") == 0) {\n\t\tprint_usage();\n\t\treturn 0;\n\t}\n\n\tif (argc < 3) {\n\t\tPX4_ERR(\"Not enough arguments.\");\n\t\tprint_usage();\n\t\treturn 1;\n\t}\n\n\tint32_t param = 0;\n\tif (PX4_OK != param_get(param_find(\"SYS_FAILURE_EN\"), ¶m)) {\n\t\tPX4_ERR(\"Could not get param SYS_FAILURE_EN\");\n\t\treturn 1;\n\t}\n\n\tif (param != 1) {\n\t\tPX4_ERR(\"Failure injection disabled by SYS_FAILURE_EN param.\");\n\t\treturn 1;\n\t}\n\n\tconst char *requested_failure_unit = argv[1];\n\tconst char *requested_failure_type = argv[2];\n\n\n\tfor (const auto &failure_unit : failure_units) {\n\t\tif (strncmp(failure_unit.key, requested_failure_unit, sizeof(failure_unit.key)) != 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const auto &failure_type : failure_types) {\n\t\t\tif (strncmp(failure_type.key, requested_failure_type, sizeof(failure_type.key)) != 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treturn inject_failure(failure_unit.value, failure_type.value);\n\t\t}\n\n\t\tPX4_ERR(\"Failure type '%s' not found\", requested_failure_type);\n\t\treturn 1;\n\t}\n\tPX4_ERR(\"Component '%s' not found\", requested_failure_unit);\n\treturn 1;\n}\nfailure: use time literal\/****************************************************************************\n *\n * Copyright (c) 2020 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace time_literals;\n\nstruct FailureUnit {\n\tchar key[16];\n\tuint8_t value;\n};\n\nstatic constexpr FailureUnit failure_units[] = {\n\t{ \"gyro\", vehicle_command_s::FAILURE_UNIT_SENSOR_GYRO},\n\t{ \"accel\", vehicle_command_s::FAILURE_UNIT_SENSOR_ACCEL},\n\t{ \"mag\", vehicle_command_s::FAILURE_UNIT_SENSOR_MAG},\n\t{ \"baro\", vehicle_command_s::FAILURE_UNIT_SENSOR_BARO},\n\t{ \"gps\", vehicle_command_s::FAILURE_UNIT_SENSOR_GPS},\n\t{ \"optical_flow\", vehicle_command_s::FAILURE_UNIT_SENSOR_OPTICAL_FLOW},\n\t{ \"vio\", vehicle_command_s::FAILURE_UNIT_SENSOR_VIO},\n\t{ \"distance_sensor\", vehicle_command_s::FAILURE_UNIT_SENSOR_DISTANCE_SENSOR},\n\t{ \"airspeed\", vehicle_command_s::FAILURE_UNIT_SENSOR_AIRSPEED},\n\t{ \"battery\", vehicle_command_s::FAILURE_UNIT_SYSTEM_BATTERY},\n\t{ \"motor\", vehicle_command_s::FAILURE_UNIT_SYSTEM_MOTOR},\n\t{ \"servo\", vehicle_command_s::FAILURE_UNIT_SYSTEM_SERVO},\n\t{ \"avoidance\", vehicle_command_s::FAILURE_UNIT_SYSTEM_AVOIDANCE},\n\t{ \"rc_signal\", vehicle_command_s::FAILURE_UNIT_SYSTEM_RC_SIGNAL},\n\t{ \"mavlink_signal\", vehicle_command_s::FAILURE_UNIT_SYSTEM_MAVLINK_SIGNAL},\n};\n\nstruct FailureType {\n\tchar key[14];\n\tuint8_t value;\n};\n\nstatic constexpr FailureType failure_types[] = {\n\t{ \"ok\", vehicle_command_s::FAILURE_TYPE_OK},\n\t{ \"off\", vehicle_command_s::FAILURE_TYPE_OFF},\n\t{ \"stuck\", vehicle_command_s::FAILURE_TYPE_STUCK},\n\t{ \"garbage\", vehicle_command_s::FAILURE_TYPE_GARBAGE},\n\t{ \"wrong\", vehicle_command_s::FAILURE_TYPE_WRONG},\n\t{ \"slow\", vehicle_command_s::FAILURE_TYPE_SLOW},\n\t{ \"delayed\", vehicle_command_s::FAILURE_TYPE_DELAYED},\n\t{ \"intermittent\", vehicle_command_s::FAILURE_TYPE_INTERMITTENT},\n};\n\n\nstatic void print_usage()\n{\n\tPRINT_MODULE_DESCRIPTION(\n\t\tR\"DESCR_STR(\n### Description\nInject failures into system.\n\n### Implementation\nThis system command sends a vehicle command over uORB to trigger failure.\n\n### Examples\nTest the GPS failsafe by stopping GPS:\n\nfailure gps off\n)DESCR_STR\");\n\n\tPRINT_MODULE_USAGE_NAME_SIMPLE(\"failure\", \"command\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"help\", \"Show this help text\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"gps|...\", \"Specify component\");\n\tPRINT_MODULE_USAGE_COMMAND_DESCR(\"ok|off|...\", \"Specify failure type\");\n\n\tPX4_INFO_RAW(\"\\nComponents:\\n\");\n\tfor (const auto &failure_unit : failure_units) {\n\t\tPX4_INFO_RAW(\"- %s\\n\", failure_unit.key);\n\t}\n\n\tPX4_INFO_RAW(\"\\nFailure types:\\n\");\n\tfor (const auto &failure_type : failure_types) {\n\t\tPX4_INFO_RAW(\"- %s\\n\", failure_type.key);\n\t}\n}\n\n\nint inject_failure(uint8_t unit, uint8_t type)\n{\n\tconst hrt_abstime now = hrt_absolute_time();\n\n\tuORB::Subscription command_ack_sub{ORB_ID(vehicle_command_ack)};\n\n\tuORB::PublicationQueued command_pub{ORB_ID(vehicle_command)};\n\tvehicle_command_s command{};\n\tcommand.timestamp = now;\n\tcommand.command = vehicle_command_s::VEHICLE_CMD_INJECT_FAILURE;\n\tcommand.param1 = static_cast(unit);\n\tcommand.param2 = static_cast(type);\n\tcommand_pub.publish(command);\n\n\tvehicle_command_ack_s ack;\n\twhile (hrt_elapsed_time(&now) < 1_s) {\n\t\tif (command_ack_sub.update(&ack)) {\n\t\t\tif (ack.command == command.command) {\n\t\t\t\tif (ack.result != vehicle_command_ack_s::VEHICLE_RESULT_ACCEPTED) {\n\t\t\t\t\tPX4_ERR(\"Result: %d\", ack.result);\n\t\t\t\t\treturn 1;\n\t\t\t\t} else {\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpx4_usleep(10000);\n\t}\n\tPX4_ERR(\"Timeout waiting for ack\");\n\treturn 1;\n}\n\nextern \"C\" __EXPORT int failure_main(int argc, char *argv[])\n{\n\tif (argc == 2 && strcmp(argv[1], \"help\") == 0) {\n\t\tprint_usage();\n\t\treturn 0;\n\t}\n\n\tif (argc < 3) {\n\t\tPX4_ERR(\"Not enough arguments.\");\n\t\tprint_usage();\n\t\treturn 1;\n\t}\n\n\tint32_t param = 0;\n\tif (PX4_OK != param_get(param_find(\"SYS_FAILURE_EN\"), ¶m)) {\n\t\tPX4_ERR(\"Could not get param SYS_FAILURE_EN\");\n\t\treturn 1;\n\t}\n\n\tif (param != 1) {\n\t\tPX4_ERR(\"Failure injection disabled by SYS_FAILURE_EN param.\");\n\t\treturn 1;\n\t}\n\n\tconst char *requested_failure_unit = argv[1];\n\tconst char *requested_failure_type = argv[2];\n\n\n\tfor (const auto &failure_unit : failure_units) {\n\t\tif (strncmp(failure_unit.key, requested_failure_unit, sizeof(failure_unit.key)) != 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const auto &failure_type : failure_types) {\n\t\t\tif (strncmp(failure_type.key, requested_failure_type, sizeof(failure_type.key)) != 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treturn inject_failure(failure_unit.value, failure_type.value);\n\t\t}\n\n\t\tPX4_ERR(\"Failure type '%s' not found\", requested_failure_type);\n\t\treturn 1;\n\t}\n\tPX4_ERR(\"Component '%s' not found\", requested_failure_unit);\n\treturn 1;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nclass BladeShooterSystem::BladeShooterSystemImpl{\n\npublic:\n\tBladeShooterSystemImpl(b2World& box2dWorld) : m_box2dWorld(&box2dWorld) {}\n\t~BladeShooterSystemImpl(){}\n\n\tstd::unique_ptr m_box2dWorld;\n\tsf::Clock m_clock;\n\n\tvoid update(std::vector& entities){\n\t\tfor(anax::Entity bladeShooterEntity : entities){\n\t\t\tsf::Time currentTime = m_clock.getElapsedTime();\n\t\t\tauto& bladeShooterComp = bladeShooterEntity.getComponent();\n\t\t\tauto bladeShooterState = bladeShooterComp.bladeShooterState;\n\t\t\tif(bladeShooterState == BladeShooterState::NOT_STARTED){\n\t\t\t\tbladeShooterComp.lastTimeBladeShot = m_clock.getElapsedTime();\n\t\t\t\tbladeShooterComp.bladeShooterState = BladeShooterState::SHOOTING;\n\t\t\t\tcreateBlade(bladeShooterEntity);\n\t\t\t}else if((currentTime - bladeShooterComp.lastTimeBladeShot).asMilliseconds() >= bladeShooterComp.delayBetweenBladeShots.asMilliseconds()){\n\t\t\t\tcreateBlade(bladeShooterEntity);\n\t\t\t\tbladeShooterComp.lastTimeBladeShot = currentTime;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid createBlade(anax::Entity& entity){\n\t\tauto& bladeShooterComp = entity.getComponent();\n\t\tauto& physicsComp = entity.getComponent();\n\t\tb2Body* body = physicsComp.physicsBody;\n\t\tb2Vec2 startingPosition = body->GetPosition();\n\t\tauto& world = entity.getWorld();\n\n\t\tauto bladeEntity = world.createEntity();\n\t\tauto& bladeComp = bladeEntity.addComponent();\n\t\tauto& bladePhysicsComp = bladeEntity.addComponent();\n\t\tauto& texCoordsComp = bladeEntity.addComponent();\n\t\tauto& splitDirectionComp = bladeEntity.addComponent();\n\t\tsplitDirectionComp.splitDirection = SplitDirection::NONE;\n\n\t\tbladeComp.bladeLinearVelocity = bladeShooterComp.bladeLinerVelocty;\n\t\tbladePhysicsComp.physicsBody = createBladeBody(startingPosition, bladeShooterComp.bladeSize);\n\t\tbladeEntity.activate();\n\t}\n\n\tb2Body* createBladeBody(b2Vec2 startingPosition, b2Vec2 shapeSize){\n\t\tb2BodyDef bd;\n\t\tbd.type = b2_dynamicBody;\n\t\tbd.position = startingPosition;\n\t\tb2PolygonShape shape;\n\t\tshape.SetAsBox(shapeSize.x, shapeSize.y);\n\t\tb2FixtureDef fd;\n\t\tfd.shape = &shape;\n\t\tfd.density = 1.0f;\n\t\tfd.filter.categoryBits = GameObjectTag::BLADE;\n\t\tfd.filter.maskBits = ~GameObjectTag::BLADE_SHOOTER | ~GameObjectTag::NINJA_SENSE;\n\n\t\tb2Body* bladeBody = m_box2dWorld->CreateBody(&bd);\n\t\tbladeBody->CreateFixture(&fd);\n\t\treturn bladeBody;\n\t}\n\n};\n\nBladeShooterSystem::BladeShooterSystem(b2World& box2dWorld) : Base(anax::ComponentFilter().requires()), m_impl(new BladeShooterSystemImpl(box2dWorld)) {\n}\n\nBladeShooterSystem::~BladeShooterSystem() {\n}\n\nvoid BladeShooterSystem::update(){\n\tauto entities = getEntities();\n\tm_impl->update(entities);\n}\n\n\n\nBlades are not affected by gravity#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nclass BladeShooterSystem::BladeShooterSystemImpl{\n\npublic:\n\tBladeShooterSystemImpl(b2World& box2dWorld) : m_box2dWorld(&box2dWorld) {}\n\t~BladeShooterSystemImpl(){}\n\n\tstd::unique_ptr m_box2dWorld;\n\tsf::Clock m_clock;\n\n\tvoid update(std::vector& entities){\n\t\tfor(anax::Entity bladeShooterEntity : entities){\n\t\t\tsf::Time currentTime = m_clock.getElapsedTime();\n\t\t\tauto& bladeShooterComp = bladeShooterEntity.getComponent();\n\t\t\tauto bladeShooterState = bladeShooterComp.bladeShooterState;\n\t\t\tif(bladeShooterState == BladeShooterState::NOT_STARTED){\n\t\t\t\tbladeShooterComp.lastTimeBladeShot = m_clock.getElapsedTime();\n\t\t\t\tbladeShooterComp.bladeShooterState = BladeShooterState::SHOOTING;\n\t\t\t\tcreateBlade(bladeShooterEntity);\n\t\t\t}else if((currentTime - bladeShooterComp.lastTimeBladeShot).asMilliseconds() >= bladeShooterComp.delayBetweenBladeShots.asMilliseconds()){\n\t\t\t\tcreateBlade(bladeShooterEntity);\n\t\t\t\tbladeShooterComp.lastTimeBladeShot = currentTime;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid createBlade(anax::Entity& entity){\n\t\tauto& bladeShooterComp = entity.getComponent();\n\t\tauto& physicsComp = entity.getComponent();\n\t\tb2Body* body = physicsComp.physicsBody;\n\t\tb2Vec2 startingPosition = body->GetPosition();\n\t\tauto& world = entity.getWorld();\n\n\t\tauto bladeEntity = world.createEntity();\n\t\tauto& bladeComp = bladeEntity.addComponent();\n\t\tauto& bladePhysicsComp = bladeEntity.addComponent();\n\t\tauto& texCoordsComp = bladeEntity.addComponent();\n\t\tauto& splitDirectionComp = bladeEntity.addComponent();\n\t\tsplitDirectionComp.splitDirection = SplitDirection::NONE;\n\n\t\tbladeComp.bladeLinearVelocity = bladeShooterComp.bladeLinerVelocty;\n\t\tbladePhysicsComp.physicsBody = createBladeBody(startingPosition, bladeShooterComp.bladeSize);\n\t\tbladeEntity.activate();\n\t}\n\n\tb2Body* createBladeBody(b2Vec2 startingPosition, b2Vec2 shapeSize){\n\t\tb2BodyDef bd;\n\t\tbd.type = b2_dynamicBody;\n\t\tbd.position = startingPosition;\n\t\tb2PolygonShape shape;\n\t\tshape.SetAsBox(shapeSize.x, shapeSize.y);\n\t\tb2FixtureDef fd;\n\t\tfd.shape = &shape;\n\t\tfd.density = 1.0f;\n\t\tfd.filter.categoryBits = GameObjectTag::BLADE;\n\t\tfd.filter.maskBits = ~GameObjectTag::BLADE_SHOOTER | ~GameObjectTag::NINJA_SENSE;\n\n\t\tb2Body* bladeBody = m_box2dWorld->CreateBody(&bd);\n\t\tbladeBody->SetGravityScale(0.0f);\n\t\tbladeBody->CreateFixture(&fd);\n\t\treturn bladeBody;\n\t}\n\n};\n\nBladeShooterSystem::BladeShooterSystem(b2World& box2dWorld) : Base(anax::ComponentFilter().requires()), m_impl(new BladeShooterSystemImpl(box2dWorld)) {\n}\n\nBladeShooterSystem::~BladeShooterSystem() {\n}\n\nvoid BladeShooterSystem::update(){\n\tauto entities = getEntities();\n\tm_impl->update(entities);\n}\n\n\n\n<|endoftext|>"} {"text":"Remove unused function<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cntnrsrt.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 20:12:38 $\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 _CNTRSRT_HXX\n#define _CNTRSRT_HXX\n\n#if 0\n***********************************************************************\n*\n* Hier folgt die Beschreibung fuer die exportierten Makros:\n*\n* DECLARE_CONTAINER_SORT( ClassName, Type )\n* IMPL_CONTAINER_SORT( ClassName, Type, SortFunc )\n*\n* Definiert eine von Container abgeleitete Klasse \"ClassName\",\n* in der die Elemente des Typs \"Type\" sortiert enthalten sind.\n* Dazu muss einer Funktion \"SortFunc\" definiert sein, die als\n* Paramter zwei \"const Type&\" erwartet und 0 zurueckgibt, wenn\n* beide gleich sind, -1 wenn der erste Paramter kleiner ist als\n* der zweite und +1 wenn der erste Paramter groesser ist als\n* der zweite.\n*\n* Die Zugriffs-Methoden entsprechen in etwa denen der Container-\n* Klasse, mit Ausnahme von Insert, DeleteAndDestroy und Seek_Entry,\n* der den SV-Pointer-Arrays entsprechen.\n*\n* DECLARE_CONTAINER_SORT_DEL( ClassName, Type )\n* IMPL_CONTAINER_SORT( ClassName, Type, SortFunc )\n*\n* Wie DECLARE_CONTAINER_SORT, nur dass beim Aufruf des Destruktors\n* alle im Conatiner vorhandenen Objekte geloescht werden.\n*\n#endif\n\n#ifndef _CONTNR_HXX \/\/autogen\n#include \n#endif\n\n#define DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ClassName( const ClassName& ); \\\n ClassName& operator =( const ClassName& ); \\\npublic: \\\n Container::Count; \\\n \\\n ClassName( USHORT InitSize, USHORT ReSize ) : \\\n Container( CONTAINER_MAXBLOCKSIZE, InitSize, ReSize ) {} \\\n \\\n BOOL Insert( Type* pObj ); \\\n \\\n Type *Remove( ULONG nPos ) \\\n { return (Type *)Container::Remove( nPos ); } \\\n \\\n Type *Remove( Type* pObj ); \\\n \\\n void DeleteAndDestroy( ULONG nPos ) \\\n { \\\n Type *pObj = Remove( nPos ); \\\n if( pObj ) \\\n delete pObj; \\\n } \\\n \\\n void DeleteAndDestroy() \\\n { while( Count() ) DeleteAndDestroy( 0 ); } \\\n \\\n Type* GetObject( ULONG nPos ) const \\\n { return (Type *)Container::GetObject( nPos ); } \\\n \\\n Type* operator[]( ULONG nPos ) const \\\n { return GetObject(nPos); } \\\n \\\n BOOL Seek_Entry( const Type *pObj, ULONG* pPos ) const; \\\n \\\n ULONG GetPos( const Type* pObj ) const; \\\n\n\n#define DECLARE_CONTAINER_SORT( ClassName, Type ) \\\nclass ClassName : private Container \\\n{ \\\n DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ~ClassName() {} \\\n}; \\\n\n\n#define DECLARE_CONTAINER_SORT_DEL( ClassName, Type ) \\\nclass ClassName : private Container \\\n{ \\\n DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ~ClassName() { DeleteAndDestroy(); } \\\n}; \\\n\n\n#define IMPL_CONTAINER_SORT( ClassName, Type, SortFunc ) \\\nBOOL ClassName::Insert( Type *pObj ) \\\n{ \\\n ULONG nPos; \\\n BOOL bExist; \\\n if( ! ( bExist = Seek_Entry( pObj, &nPos ) ) ) \\\n Container::Insert( pObj, nPos ); \\\n return !bExist; \\\n} \\\n \\\nType *ClassName::Remove( Type* pObj ) \\\n{ \\\n ULONG nPos; \\\n if( Seek_Entry( pObj, &nPos ) ) \\\n return Remove( nPos ); \\\n else \\\n return 0; \\\n} \\\n \\\nULONG ClassName::GetPos( const Type* pObj ) const \\\n{ \\\n ULONG nPos; \\\n if( Seek_Entry( pObj, &nPos ) ) \\\n return nPos; \\\n else \\\n return CONTAINER_ENTRY_NOTFOUND; \\\n} \\\n \\\nBOOL ClassName::Seek_Entry( const Type* pObj, ULONG* pPos ) const \\\n{ \\\n register ULONG nO = Count(), \\\n nM, \\\n nU = 0; \\\n if( nO > 0 ) \\\n { \\\n nO--; \\\n while( nU <= nO ) \\\n { \\\n nM = nU + ( nO - nU ) \/ 2; \\\n int nCmp = SortFunc( *GetObject(nM), *pObj ); \\\n \\\n if( 0 == nCmp ) \\\n { \\\n if( pPos ) *pPos = nM; \\\n return TRUE; \\\n } \\\n else if( nCmp < 0 ) \\\n nU = nM + 1; \\\n else if( nM == 0 ) \\\n { \\\n if( pPos ) *pPos = nU; \\\n return FALSE; \\\n } \\\n else \\\n nO = nM - 1; \\\n } \\\n } \\\n if( pPos ) *pPos = nU; \\\n return FALSE; \\\n} \\\n\n#endif\nINTEGRATION: CWS sb59 (1.3.64); FILE MERGED 2006\/08\/09 11:09:38 sb 1.3.64.2: #i67487 Made code warning-free (wntmsci10). 2006\/08\/09 08:13:11 sb 1.3.64.1: #i67487 Made code warning-free (wntmsci10).\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cntnrsrt.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 15:03:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CNTRSRT_HXX\n#define _CNTRSRT_HXX\n\n#if 0\n***********************************************************************\n*\n* Hier folgt die Beschreibung fuer die exportierten Makros:\n*\n* DECLARE_CONTAINER_SORT( ClassName, Type )\n* IMPL_CONTAINER_SORT( ClassName, Type, SortFunc )\n*\n* Definiert eine von Container abgeleitete Klasse \"ClassName\",\n* in der die Elemente des Typs \"Type\" sortiert enthalten sind.\n* Dazu muss einer Funktion \"SortFunc\" definiert sein, die als\n* Paramter zwei \"const Type&\" erwartet und 0 zurueckgibt, wenn\n* beide gleich sind, -1 wenn der erste Paramter kleiner ist als\n* der zweite und +1 wenn der erste Paramter groesser ist als\n* der zweite.\n*\n* Die Zugriffs-Methoden entsprechen in etwa denen der Container-\n* Klasse, mit Ausnahme von Insert, DeleteAndDestroy und Seek_Entry,\n* der den SV-Pointer-Arrays entsprechen.\n*\n* DECLARE_CONTAINER_SORT_DEL( ClassName, Type )\n* IMPL_CONTAINER_SORT( ClassName, Type, SortFunc )\n*\n* Wie DECLARE_CONTAINER_SORT, nur dass beim Aufruf des Destruktors\n* alle im Conatiner vorhandenen Objekte geloescht werden.\n*\n#endif\n\n#ifndef _CONTNR_HXX \/\/autogen\n#include \n#endif\n\n#define DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ClassName( const ClassName& ); \\\n ClassName& operator =( const ClassName& ); \\\npublic: \\\n using Container::Count; \\\n \\\n ClassName( USHORT InitSize, USHORT ReSize ) : \\\n Container( CONTAINER_MAXBLOCKSIZE, InitSize, ReSize ) {} \\\n \\\n BOOL Insert( Type* pObj ); \\\n \\\n Type *Remove( ULONG nPos ) \\\n { return (Type *)Container::Remove( nPos ); } \\\n \\\n Type *Remove( Type* pObj ); \\\n \\\n void DeleteAndDestroy( ULONG nPos ) \\\n { \\\n Type *pObj = Remove( nPos ); \\\n if( pObj ) \\\n delete pObj; \\\n } \\\n \\\n void DeleteAndDestroy() \\\n { while( Count() ) DeleteAndDestroy( 0 ); } \\\n \\\n Type* GetObject( ULONG nPos ) const \\\n { return (Type *)Container::GetObject( nPos ); } \\\n \\\n Type* operator[]( ULONG nPos ) const \\\n { return GetObject(nPos); } \\\n \\\n BOOL Seek_Entry( const Type *pObj, ULONG* pPos ) const; \\\n \\\n ULONG GetPos( const Type* pObj ) const; \\\n\n\n#define DECLARE_CONTAINER_SORT( ClassName, Type ) \\\nclass ClassName : private Container \\\n{ \\\n DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ~ClassName() {} \\\n}; \\\n\n\n#define DECLARE_CONTAINER_SORT_DEL( ClassName, Type ) \\\nclass ClassName : private Container \\\n{ \\\n DECLARE_CONTAINER_SORT_COMMON( ClassName, Type ) \\\n ~ClassName() { DeleteAndDestroy(); } \\\n}; \\\n\n\n#define IMPL_CONTAINER_SORT( ClassName, Type, SortFunc ) \\\nBOOL ClassName::Insert( Type *pObj ) \\\n{ \\\n ULONG nPos; \\\n BOOL bExist = Seek_Entry( pObj, &nPos ); \\\n if( !bExist ) \\\n Container::Insert( pObj, nPos ); \\\n return !bExist; \\\n} \\\n \\\nType *ClassName::Remove( Type* pObj ) \\\n{ \\\n ULONG nPos; \\\n if( Seek_Entry( pObj, &nPos ) ) \\\n return Remove( nPos ); \\\n else \\\n return 0; \\\n} \\\n \\\nULONG ClassName::GetPos( const Type* pObj ) const \\\n{ \\\n ULONG nPos; \\\n if( Seek_Entry( pObj, &nPos ) ) \\\n return nPos; \\\n else \\\n return CONTAINER_ENTRY_NOTFOUND; \\\n} \\\n \\\nBOOL ClassName::Seek_Entry( const Type* pObj, ULONG* pPos ) const \\\n{ \\\n register ULONG nO = Count(), \\\n nM, \\\n nU = 0; \\\n if( nO > 0 ) \\\n { \\\n nO--; \\\n while( nU <= nO ) \\\n { \\\n nM = nU + ( nO - nU ) \/ 2; \\\n int nCmp = SortFunc( *GetObject(nM), *pObj ); \\\n \\\n if( 0 == nCmp ) \\\n { \\\n if( pPos ) *pPos = nM; \\\n return TRUE; \\\n } \\\n else if( nCmp < 0 ) \\\n nU = nM + 1; \\\n else if( nM == 0 ) \\\n { \\\n if( pPos ) *pPos = nU; \\\n return FALSE; \\\n } \\\n else \\\n nO = nM - 1; \\\n } \\\n } \\\n if( pPos ) *pPos = nU; \\\n return FALSE; \\\n} \\\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\nvoid initialize()\n{\n SelectParams(CBaseChainParams::REGTEST);\n}\n\nvoid test_one_input(const std::vector& buffer)\n{\n const std::string descriptor(buffer.begin(), buffer.end());\n FlatSigningProvider signing_provider;\n std::string error;\n for (const bool require_checksum : {true, false}) {\n Parse(descriptor, signing_provider, error);\n }\n}\nfuzz: fix 17018\/\/ Copyright (c) 2009-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\nvoid initialize()\n{\n SelectParams(CBaseChainParams::REGTEST);\n}\n\nvoid test_one_input(const std::vector& buffer)\n{\n const std::string descriptor(buffer.begin(), buffer.end());\n FlatSigningProvider signing_provider;\n std::string error;\n for (const bool require_checksum : {true, false}) {\n Parse(descriptor, signing_provider, error, require_checksum);\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: filectrl.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:58:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SV_FILECTRL_HXX\n#define _SV_FILECTRL_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include \n#endif\n#ifndef _SV_EDIT_HXX\n#include \n#endif\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n\n\n#define STR_FILECTRL_BUTTONTEXT 333 \/\/ ID-Range?!\n\n\/\/ Flags for FileControl\ntypedef USHORT FileControlMode;\n#define FILECTRL_RESIZEBUTTONBYPATHLEN ((USHORT)0x0001)\/\/if this is set, the button will become small as soon as the Text in the Edit Field is to long to be shown completely\n\n\n\/\/ Flags for internal use of FileControl\ntypedef USHORT FileControlMode_Internal;\n#define FILECTRL_INRESIZE ((USHORT)0x0001)\n#define FILECTRL_ORIGINALBUTTONTEXT ((USHORT)0x0002)\n\n\nclass VclFileDialog;\nclass FileDialog;\nclass FileControl : public Window\n{\nprivate:\n Edit maEdit;\n PushButton maButton;\n\n String maButtonText;\n BOOL mbOpenDlg;\n\n VclFileDialog* mpVclDlg;\n FileDialog* mpFDlg;\n\n Link maDialogCreatedHdl;\n\n FileControlMode mnFlags;\n FileControlMode_Internal mnInternalFlags;\n\nprotected:\n void Resize();\n void GetFocus();\n void StateChanged( StateChangedType nType );\n WinBits ImplInitStyle( WinBits nStyle );\n DECL_LINK( ButtonHdl, PushButton* );\n\npublic:\n FileControl( Window* pParent, WinBits nStyle, FileControlMode = 0 );\n ~FileControl();\n\n Edit& GetEdit() { return maEdit; }\n PushButton& GetButton() { return maButton; }\n\n void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, ULONG nFlags );\n\n void SetOpenDialog( BOOL bOpen ) { mbOpenDlg = bOpen; }\n BOOL IsOpenDialog() const { return mbOpenDlg; }\n\n void SetText( const XubString& rStr );\n XubString GetText() const;\n UniString GetSelectedText() const { return maEdit.GetSelected(); }\n\n void SetSelection( const Selection& rSelection ) { maEdit.SetSelection( rSelection ); }\n Selection GetSelection() const { return maEdit.GetSelection(); }\n\n void SetReadOnly( BOOL bReadOnly = TRUE ) { maEdit.SetReadOnly( bReadOnly ); }\n BOOL IsReadOnly() const { return maEdit.IsReadOnly(); }\n\n \/\/------\n \/\/manipulate the Button-Text:\n XubString GetButtonText() const { return maButtonText; }\n void SetButtonText( const XubString& rStr );\n void ResetButtonText();\n\n \/\/------\n \/\/use this to manipulate the dialog bevore executing it:\n void SetDialogCreatedHdl( const Link& rLink ) { maDialogCreatedHdl = rLink; }\n const Link& GetDialogCreatedHdl() const { return maDialogCreatedHdl; }\n\n \/\/only use the next two methods in 'DialogCreatedHdl' and don't store the dialog-pointer\n VclFileDialog* GetVclFileDialog() const { return mpVclDlg; }\n FileDialog* GetFileDialog() const { return mpFDlg; }\n \/\/------\n};\n\n#endif\n\n#83847# ImplBrowseFile\/*************************************************************************\n *\n * $RCSfile: filectrl.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: fs $ $Date: 2001-09-04 08:57:48 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SV_FILECTRL_HXX\n#define _SV_FILECTRL_HXX\n\n#ifndef _SV_WINDOW_HXX\n#include \n#endif\n#ifndef _SV_EDIT_HXX\n#include \n#endif\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n\n\n#define STR_FILECTRL_BUTTONTEXT 333 \/\/ ID-Range?!\n\n\/\/ Flags for FileControl\ntypedef USHORT FileControlMode;\n#define FILECTRL_RESIZEBUTTONBYPATHLEN ((USHORT)0x0001)\/\/if this is set, the button will become small as soon as the Text in the Edit Field is to long to be shown completely\n\n\n\/\/ Flags for internal use of FileControl\ntypedef USHORT FileControlMode_Internal;\n#define FILECTRL_INRESIZE ((USHORT)0x0001)\n#define FILECTRL_ORIGINALBUTTONTEXT ((USHORT)0x0002)\n\n\nclass VclFileDialog;\nclass FileDialog;\nclass FileControl : public Window\n{\nprivate:\n Edit maEdit;\n PushButton maButton;\n\n String maButtonText;\n BOOL mbOpenDlg;\n\n VclFileDialog* mpVclDlg;\n FileDialog* mpFDlg;\n\n Link maDialogCreatedHdl;\n\n FileControlMode mnFlags;\n FileControlMode_Internal mnInternalFlags;\n\nprivate:\n void ImplBrowseFile( );\n\nprotected:\n void Resize();\n void GetFocus();\n void StateChanged( StateChangedType nType );\n WinBits ImplInitStyle( WinBits nStyle );\n DECL_LINK( ButtonHdl, PushButton* );\n\npublic:\n FileControl( Window* pParent, WinBits nStyle, FileControlMode = 0 );\n ~FileControl();\n\n Edit& GetEdit() { return maEdit; }\n PushButton& GetButton() { return maButton; }\n\n void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, ULONG nFlags );\n\n void SetOpenDialog( BOOL bOpen ) { mbOpenDlg = bOpen; }\n BOOL IsOpenDialog() const { return mbOpenDlg; }\n\n void SetText( const XubString& rStr );\n XubString GetText() const;\n UniString GetSelectedText() const { return maEdit.GetSelected(); }\n\n void SetSelection( const Selection& rSelection ) { maEdit.SetSelection( rSelection ); }\n Selection GetSelection() const { return maEdit.GetSelection(); }\n\n void SetReadOnly( BOOL bReadOnly = TRUE ) { maEdit.SetReadOnly( bReadOnly ); }\n BOOL IsReadOnly() const { return maEdit.IsReadOnly(); }\n\n \/\/------\n \/\/manipulate the Button-Text:\n XubString GetButtonText() const { return maButtonText; }\n void SetButtonText( const XubString& rStr );\n void ResetButtonText();\n\n \/\/------\n \/\/use this to manipulate the dialog bevore executing it:\n void SetDialogCreatedHdl( const Link& rLink ) { maDialogCreatedHdl = rLink; }\n const Link& GetDialogCreatedHdl() const { return maDialogCreatedHdl; }\n\n \/\/only use the next two methods in 'DialogCreatedHdl' and don't store the dialog-pointer\n VclFileDialog* GetVclFileDialog() const { return mpVclDlg; }\n FileDialog* GetFileDialog() const { return mpFDlg; }\n \/\/------\n};\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: templdlg.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: os $ $Date: 2002-11-29 17:21:43 $\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 _SVTOOLS_TEMPLDLG_HXX\n#define _SVTOOLS_TEMPLDLG_HXX\n\n#include \n#include \n#include \n\nstruct SvtTmplDlg_Impl;\n\n\/\/ class SvtDocumentTemplateDialog ---------------------------------------\n\nclass SvtTemplateWindow;\n\nclass SvtDocumentTemplateDialog : public ModalDialog\n{\nprivate:\n FixedLine aLine;\n PushButton aManageBtn;\n PushButton aEditBtn;\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n SvtTmplDlg_Impl* pImpl;\n\n DECL_LINK( SelectHdl_Impl, SvtTemplateWindow* );\n DECL_LINK( DoubleClickHdl_Impl, SvtTemplateWindow* );\n DECL_LINK( NewFolderHdl_Impl, SvtTemplateWindow* );\n DECL_LINK( SendFocusHdl_Impl, SvtTemplateWindow* );\n DECL_LINK( OKHdl_Impl, PushButton* );\n DECL_LINK( OrganizerHdl_Impl, PushButton* );\n DECL_LINK( UpdateHdl_Impl, Timer* );\n\npublic:\n SvtDocumentTemplateDialog( Window* pParent );\n\n \/** ctor for calling the dialog for selection<\/em> only, not for opening<\/em> a document\n

If you use this ctor, the dialog will behave differently in the following areas:\n

  • The Edit<\/em> button will be hidden.<\/li>\n
  • Upon pressing em>Open<\/em>, the selected file will not be opened. Instead, it's\n URL is available (see GetSelectedFileURL<\/method>).<\/li>\n <\/ul>\n\n *\/\n struct SelectOnly { };\n SvtDocumentTemplateDialog( Window* _pParent, SelectOnly );\n\n ~SvtDocumentTemplateDialog();\n\n sal_Bool IsFileSelected( ) const;\n String GetSelectedFileURL( ) const;\n\n void SelectTemplateFolder();\n\nprivate:\n void InitImpl( );\n};\n\n#endif \/\/ _SVTOOLS_TEMPLDLG_HXX\n\nINTEGRATION: CWS visibility03 (1.11.900); FILE MERGED 2005\/03\/24 14:14:03 mhu 1.11.900.1: #i45006# Include svtools\/(svl|svt)dllapi.h, declare symbol visibility with (SVL|SVT)_DLL(PUBLIC|PRIVATE) as appropriate; partial cleanup.\/*************************************************************************\n *\n * $RCSfile: templdlg.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 10:37:35 $\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 _SVTOOLS_TEMPLDLG_HXX\n#define _SVTOOLS_TEMPLDLG_HXX\n\n#ifndef INCLUDED_SVTDLLAPI_H\n#include \"svtools\/svtdllapi.h\"\n#endif\n\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n#ifndef _SV_DIALOG_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n\nstruct SvtTmplDlg_Impl;\n\n\/\/ class SvtDocumentTemplateDialog ---------------------------------------\n\nclass SvtTemplateWindow;\n\nclass SVT_DLLPUBLIC SvtDocumentTemplateDialog : public ModalDialog\n{\nprivate:\n FixedLine aLine;\n PushButton aManageBtn;\n PushButton aEditBtn;\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n SvtTmplDlg_Impl* pImpl;\n\n DECL_DLLPRIVATE_LINK( SelectHdl_Impl, SvtTemplateWindow* );\n DECL_DLLPRIVATE_LINK( DoubleClickHdl_Impl, SvtTemplateWindow* );\n DECL_DLLPRIVATE_LINK( NewFolderHdl_Impl, SvtTemplateWindow* );\n DECL_DLLPRIVATE_LINK( SendFocusHdl_Impl, SvtTemplateWindow* );\n DECL_DLLPRIVATE_LINK( OKHdl_Impl, PushButton* );\n DECL_DLLPRIVATE_LINK( OrganizerHdl_Impl, PushButton* );\n DECL_DLLPRIVATE_LINK( UpdateHdl_Impl, Timer* );\n\npublic:\n SvtDocumentTemplateDialog( Window* pParent );\n\n \/** ctor for calling the dialog for selection<\/em> only, not for opening<\/em> a document\n

    If you use this ctor, the dialog will behave differently in the following areas:\n

    • The Edit<\/em> button will be hidden.<\/li>\n
    • Upon pressing em>Open<\/em>, the selected file will not be opened. Instead, it's\n URL is available (see GetSelectedFileURL<\/method>).<\/li>\n <\/ul>\n\n *\/\n struct SelectOnly { };\n SvtDocumentTemplateDialog( Window* _pParent, SelectOnly );\n\n ~SvtDocumentTemplateDialog();\n\n sal_Bool IsFileSelected( ) const;\n String GetSelectedFileURL( ) const;\n\n void SelectTemplateFolder();\n\nprivate:\n SVT_DLLPRIVATE void InitImpl( );\n};\n\n#endif \/\/ _SVTOOLS_TEMPLDLG_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ifaceids.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-04-11 15:57:50 $\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 _SVX_IFACEIDS_HXX\n#define _SVX_IFACEIDS_HXX\n\n\/\/ -----------------------------------------------------------------------\n\n#include \n\n#define SVX_INTERFACE_BASIDE_DOCSH (SFX_INTERFACE_IDE_START+ 0)\n#define SVX_INTERFACE_BASIDE_VIEWSH (SFX_INTERFACE_IDE_START+ 1)\n#define SVX_INTERFACE_EXTRUSION_BAR (SFX_INTERFACE_IDE_START+ 2)\n#define SVX_INTERFACE_FONTWORK_BAR (SFX_INTERFACE_IDE_START+ 3)\n\n#define HID_INTERFACE_BASIDE_VIEWSH SVX_INTERFACE_BASIDE_VIEWSH\n\n#define SVX_INTERFACE_FORM_SH (SFX_INTERFACE_IDE_END+ 1)\n\n#endif\n\n\nINTEGRATION: CWS changefileheader (1.2.466); FILE MERGED 2008\/03\/31 14:18:13 rt 1.2.466.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: ifaceids.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_IFACEIDS_HXX\n#define _SVX_IFACEIDS_HXX\n\n\/\/ -----------------------------------------------------------------------\n\n#include \n\n#define SVX_INTERFACE_BASIDE_DOCSH (SFX_INTERFACE_IDE_START+ 0)\n#define SVX_INTERFACE_BASIDE_VIEWSH (SFX_INTERFACE_IDE_START+ 1)\n#define SVX_INTERFACE_EXTRUSION_BAR (SFX_INTERFACE_IDE_START+ 2)\n#define SVX_INTERFACE_FONTWORK_BAR (SFX_INTERFACE_IDE_START+ 3)\n\n#define HID_INTERFACE_BASIDE_VIEWSH SVX_INTERFACE_BASIDE_VIEWSH\n\n#define SVX_INTERFACE_FORM_SH (SFX_INTERFACE_IDE_END+ 1)\n\n#endif\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmurl.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:21:31 $\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 _SVX_FMURL_HXX\n#define _SVX_FMURL_HXX\n\n#ifndef _FM_STATIC_HXX_\n#include \"fmstatic.hxx\"\n#endif\n\nnamespace svxform\n{\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORMSLOTS_PREFIX);\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_POSITION);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_RECORDCOUNT);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEFIRST);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEPREV);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVENEXT);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVELAST);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVETONEW);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_UNDO);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_SAVE);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_DELETE);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_REFRESH);\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_UP);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_DOWN);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_AUTO_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_APPLY_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_REMOVE_FILTER);\n\n DECLARE_CONSTASCII_USTRING(FMURL_CONFIRM_DELETION);\n\n DECLARE_CONSTASCII_USTRING(FMURL_COMPONENT_FORMGRIDVIEW);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_CLEARVIEW);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ADDCOLUMN);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ATTACHTOFORM);\n\n DECLARE_CONSTASCII_USTRING(FMARG_ATTACHTO_MASTERFORM);\n DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNTYPE);\n DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNPOS);\n\n} \/\/ namespace svxform\n\n#endif \/\/ _SVX_FMURL_HXX\n\nINTEGRATION: CWS changefileheader (1.4.1254); FILE MERGED 2008\/04\/01 12:49:06 thb 1.4.1254.2: #i85898# Stripping all external header guards 2008\/03\/31 14:22:20 rt 1.4.1254.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: fmurl.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SVX_FMURL_HXX\n#define _SVX_FMURL_HXX\n\n#include \"fmstatic.hxx\"\n\nnamespace svxform\n{\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORMSLOTS_PREFIX);\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_POSITION);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_RECORDCOUNT);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEFIRST);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVEPREV);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVENEXT);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVELAST);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_MOVETONEW);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_UNDO);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_SAVE);\n DECLARE_CONSTASCII_USTRING(FMURL_RECORD_DELETE);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_REFRESH);\n\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_UP);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT_DOWN);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_SORT);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_AUTO_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_APPLY_FILTER);\n DECLARE_CONSTASCII_USTRING(FMURL_FORM_REMOVE_FILTER);\n\n DECLARE_CONSTASCII_USTRING(FMURL_CONFIRM_DELETION);\n\n DECLARE_CONSTASCII_USTRING(FMURL_COMPONENT_FORMGRIDVIEW);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_CLEARVIEW);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ADDCOLUMN);\n DECLARE_CONSTASCII_USTRING(FMURL_GRIDVIEW_ATTACHTOFORM);\n\n DECLARE_CONSTASCII_USTRING(FMARG_ATTACHTO_MASTERFORM);\n DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNTYPE);\n DECLARE_CONSTASCII_USTRING(FMARG_ADDCOL_COLUMNPOS);\n\n} \/\/ namespace svxform\n\n#endif \/\/ _SVX_FMURL_HXX\n\n<|endoftext|>"} {"text":"\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> \n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE websocket_frame_tests\n\n#include \n#include \n#include \n\n#include \"buffered_reader.h\"\n#include \"http_connection.h\"\n#include \"websocket.h\"\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic const uint8_t WS_HEADER_FIN = 0x80;\nstatic const uint8_t WS_HEADER_MASK = 0x80;\nstatic const uint8_t WS_OPCODE_CLOSE = 0x08;\nstatic const uint8_t WS_OPCODE_TEXT = 0x01;\n\nstatic uint8_t write_buffer[5000];\nstatic uint8_t *write_buffer_ptr;\n\nstatic uint8_t read_buffer[5000];\nstatic uint8_t *read_buffer_ptr;\nstatic size_t read_buffer_length;\nstatic uint8_t readback_buffer[5000];\nstatic uint8_t *readback_buffer_ptr;\n\nstatic bool close_called;\nstatic bool text_message_received_called;\n\nstatic void ws_on_error(struct websocket *ws)\n{\n\t(void)ws;\n}\n\nstatic int writev(void *this_ptr, struct buffered_socket_io_vector *io_vec, unsigned int count)\n{\n\t(void)this_ptr;\n\tsize_t complete_length = 0;\n\n\tfor (unsigned int i = 0; i < count; i++) {\n\t\t::memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);\n\t\twrite_buffer_ptr += io_vec[i].iov_len;\n\t\tcomplete_length += io_vec[i].iov_len;\n\t}\n\treturn complete_length;\n}\n\nstatic int read_exactly(void *this_ptr, size_t num, read_handler handler, void *handler_context)\n{\n\t(void)this_ptr;\n\tuint8_t *ptr = read_buffer_ptr;\n\tread_buffer_ptr += num;\n\thandler(handler_context, ptr, num);\n\treturn 0;\n}\n\nstatic bool is_close_frame()\n{\n\tconst uint8_t *ptr = write_buffer;\n\tuint8_t header;\n\t::memcpy(&header, ptr, sizeof(header));\n\tif ((header & WS_HEADER_FIN) != WS_HEADER_FIN) {\n\t\treturn false;\n\t}\n\tif ((header & WS_OPCODE_CLOSE) != WS_OPCODE_CLOSE) {\n\t\treturn false;\n\t}\n\tptr += sizeof(header);\n\n\tuint8_t length;\n\t::memcpy(&length, ptr, sizeof(length));\n\tif ((length & WS_HEADER_MASK) == WS_HEADER_MASK) {\n\t\treturn false;\n\t}\n\tif (length != 2) {\n\t\treturn false;\n\t}\n\tptr += sizeof(length);\n\n\tuint16_t status_code;\n\t::memcpy(&status_code, ptr, sizeof(status_code));\n\tstatus_code = be16toh(status_code);\n\tif (status_code != 1001) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic int close(void *this_ptr)\n{\n\t(void)this_ptr;\n\tclose_called = true;\n\treturn 0;\n}\n\nstatic enum websocket_callback_return text_message_received(struct websocket *s, char *msg, size_t length)\n{\n\t(void)s;\n\t(void)msg;\n\t(void)length;\n\t::strncpy((char *)readback_buffer, msg, length);\n\ttext_message_received_called = true;\n\treturn WS_OK;\n}\n\nstatic void fill_payload(uint8_t *ptr, const uint8_t *payload, uint64_t length, bool shall_mask, uint8_t mask[4])\n{\n\tif (!shall_mask) {\n\t\t::memcpy(ptr, payload, length);\n\t} else {\n\t\tfor (uint64_t i = 0; i < length; i++) {\n\t\t\tuint8_t byte = payload[i] ^ mask[i % 4];\n\t\t\t*ptr = byte;\n\t\t\tptr++;\n\t\t}\n\t}\n}\n\nstatic void prepare_text_message(const char *message, bool shall_mask, uint8_t mask[4])\n{\n\tuint8_t *ptr = read_buffer;\n\tread_buffer_length = 0;\n\tuint8_t header = 0x00;\n\theader |= WS_HEADER_FIN;\n\theader |= WS_OPCODE_TEXT;\n\t::memcpy(ptr, &header, sizeof(header));\n\tptr += sizeof(header);\n\tread_buffer_length += sizeof(header);\n\n\tuint8_t first_length = 0x00;\n\tif (shall_mask) {\n\t\tfirst_length |= WS_HEADER_MASK;\n\t}\n\tuint64_t length = ::strlen(message);\n\tif (length < 126) {\n\t\tfirst_length = first_length | (uint8_t)length;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t} else if (length <= sizeof(uint16_t)) {\n\t\tfirst_length = first_length | 126;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t\tuint16_t len = (uint16_t)length;\n\t\tlen = htobe16(len);\n\t\t::memcpy(ptr, &len, sizeof(len));\n\t\tptr += sizeof(len);\n\t\tread_buffer_length += sizeof(len);\n\t} else {\n\t\tfirst_length = first_length | 127;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t\tlength = htobe64(length);\n\t\t::memcpy(ptr, &length, sizeof(length));\n\t\tptr += sizeof(length);\n\t\tread_buffer_length += sizeof(length);\n\t}\n\n\tif (shall_mask) {\n\t\t::memcpy(ptr, mask, 4);\n\t\tptr += 4;\n\t}\n\n\tfill_payload(ptr, (const uint8_t *)message, length, shall_mask, mask);\n\tread_buffer_length += length;\n}\n\nstruct F {\n\n\tF()\n\t{\n\t\tclose_called = false;\n\t\ttext_message_received_called = false;\n\t\twrite_buffer_ptr = write_buffer;\n\t\tread_buffer_ptr = read_buffer;\n\t\treadback_buffer_ptr = readback_buffer;\n\n\t\tstruct http_connection *connection = alloc_http_connection();\n\t\tconnection->br.writev = writev;\n\t\tconnection->br.read_exactly = read_exactly;\n\t\tconnection->br.close = close;\n\t\twebsocket_init(&ws, connection, true, ws_on_error, \"jet\");\n\t\tws.upgrade_complete = true;\n\t\tws.text_message_received = text_message_received;\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstruct websocket ws;\n};\n\nBOOST_FIXTURE_TEST_CASE(test_close_frame_on_websocket_free, F)\n{\n\twebsocket_free(&ws);\n\tBOOST_CHECK_MESSAGE(is_close_frame(), \"No close frame sent when freeing the websocket!\");\n}\n\nBOOST_FIXTURE_TEST_CASE(test_receive_text_frame, F)\n{\n\tstatic const char *message = \"Hello World!\";\n\tuint8_t mask[4] = {0xaa, 0x55, 0xcc, 0x11};\n\tprepare_text_message(message, true, mask);\n\tws_get_header(&ws, read_buffer_ptr++, read_buffer_length);\n\twebsocket_free(&ws);\n\tBOOST_CHECK_MESSAGE(text_message_received_called, \"Callback for text messages was not called!\");\n\tBOOST_CHECK_MESSAGE(::strcmp(message, (char *)readback_buffer) == 0, \"Did not received the same message as sent!\");\n}\nInitialize fixture with information if websocket is server.\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> \n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE websocket_frame_tests\n\n#include \n#include \n#include \n\n#include \"buffered_reader.h\"\n#include \"http_connection.h\"\n#include \"websocket.h\"\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic const uint8_t WS_HEADER_FIN = 0x80;\nstatic const uint8_t WS_HEADER_MASK = 0x80;\nstatic const uint8_t WS_OPCODE_CLOSE = 0x08;\nstatic const uint8_t WS_OPCODE_TEXT = 0x01;\n\nstatic uint8_t write_buffer[5000];\nstatic uint8_t *write_buffer_ptr;\n\nstatic uint8_t read_buffer[5000];\nstatic uint8_t *read_buffer_ptr;\nstatic size_t read_buffer_length;\nstatic uint8_t readback_buffer[5000];\nstatic uint8_t *readback_buffer_ptr;\n\nstatic bool close_called;\nstatic bool text_message_received_called;\n\nstatic void ws_on_error(struct websocket *ws)\n{\n\t(void)ws;\n}\n\nstatic int writev(void *this_ptr, struct buffered_socket_io_vector *io_vec, unsigned int count)\n{\n\t(void)this_ptr;\n\tsize_t complete_length = 0;\n\n\tfor (unsigned int i = 0; i < count; i++) {\n\t\t::memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);\n\t\twrite_buffer_ptr += io_vec[i].iov_len;\n\t\tcomplete_length += io_vec[i].iov_len;\n\t}\n\treturn complete_length;\n}\n\nstatic int read_exactly(void *this_ptr, size_t num, read_handler handler, void *handler_context)\n{\n\t(void)this_ptr;\n\tuint8_t *ptr = read_buffer_ptr;\n\tread_buffer_ptr += num;\n\thandler(handler_context, ptr, num);\n\treturn 0;\n}\n\nstatic bool is_close_frame()\n{\n\tconst uint8_t *ptr = write_buffer;\n\tuint8_t header;\n\t::memcpy(&header, ptr, sizeof(header));\n\tif ((header & WS_HEADER_FIN) != WS_HEADER_FIN) {\n\t\treturn false;\n\t}\n\tif ((header & WS_OPCODE_CLOSE) != WS_OPCODE_CLOSE) {\n\t\treturn false;\n\t}\n\tptr += sizeof(header);\n\n\tuint8_t length;\n\t::memcpy(&length, ptr, sizeof(length));\n\tif ((length & WS_HEADER_MASK) == WS_HEADER_MASK) {\n\t\treturn false;\n\t}\n\tif (length != 2) {\n\t\treturn false;\n\t}\n\tptr += sizeof(length);\n\n\tuint16_t status_code;\n\t::memcpy(&status_code, ptr, sizeof(status_code));\n\tstatus_code = be16toh(status_code);\n\tif (status_code != 1001) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic int close(void *this_ptr)\n{\n\t(void)this_ptr;\n\tclose_called = true;\n\treturn 0;\n}\n\nstatic enum websocket_callback_return text_message_received(struct websocket *s, char *msg, size_t length)\n{\n\t(void)s;\n\t(void)msg;\n\t(void)length;\n\t::strncpy((char *)readback_buffer, msg, length);\n\ttext_message_received_called = true;\n\treturn WS_OK;\n}\n\nstatic void fill_payload(uint8_t *ptr, const uint8_t *payload, uint64_t length, bool shall_mask, uint8_t mask[4])\n{\n\tif (!shall_mask) {\n\t\t::memcpy(ptr, payload, length);\n\t} else {\n\t\tfor (uint64_t i = 0; i < length; i++) {\n\t\t\tuint8_t byte = payload[i] ^ mask[i % 4];\n\t\t\t*ptr = byte;\n\t\t\tptr++;\n\t\t}\n\t}\n}\n\nstatic void prepare_text_message(const char *message, bool shall_mask, uint8_t mask[4])\n{\n\tuint8_t *ptr = read_buffer;\n\tread_buffer_length = 0;\n\tuint8_t header = 0x00;\n\theader |= WS_HEADER_FIN;\n\theader |= WS_OPCODE_TEXT;\n\t::memcpy(ptr, &header, sizeof(header));\n\tptr += sizeof(header);\n\tread_buffer_length += sizeof(header);\n\n\tuint8_t first_length = 0x00;\n\tif (shall_mask) {\n\t\tfirst_length |= WS_HEADER_MASK;\n\t}\n\tuint64_t length = ::strlen(message);\n\tif (length < 126) {\n\t\tfirst_length = first_length | (uint8_t)length;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t} else if (length <= sizeof(uint16_t)) {\n\t\tfirst_length = first_length | 126;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t\tuint16_t len = (uint16_t)length;\n\t\tlen = htobe16(len);\n\t\t::memcpy(ptr, &len, sizeof(len));\n\t\tptr += sizeof(len);\n\t\tread_buffer_length += sizeof(len);\n\t} else {\n\t\tfirst_length = first_length | 127;\n\t\t::memcpy(ptr, &first_length, sizeof(first_length));\n\t\tptr += sizeof(first_length);\n\t\tread_buffer_length += sizeof(first_length);\n\t\tlength = htobe64(length);\n\t\t::memcpy(ptr, &length, sizeof(length));\n\t\tptr += sizeof(length);\n\t\tread_buffer_length += sizeof(length);\n\t}\n\n\tif (shall_mask) {\n\t\t::memcpy(ptr, mask, 4);\n\t\tptr += 4;\n\t}\n\n\tfill_payload(ptr, (const uint8_t *)message, length, shall_mask, mask);\n\tread_buffer_length += length;\n}\n\nstruct F {\n\n\tF(bool is_server)\n\t{\n\t\tclose_called = false;\n\t\ttext_message_received_called = false;\n\t\twrite_buffer_ptr = write_buffer;\n\t\tread_buffer_ptr = read_buffer;\n\t\treadback_buffer_ptr = readback_buffer;\n\n\t\tstruct http_connection *connection = alloc_http_connection();\n\t\tconnection->br.writev = writev;\n\t\tconnection->br.read_exactly = read_exactly;\n\t\tconnection->br.close = close;\n\t\twebsocket_init(&ws, connection, is_server, ws_on_error, \"jet\");\n\t\tws.upgrade_complete = true;\n\t\tws.text_message_received = text_message_received;\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstruct websocket ws;\n};\n\nBOOST_AUTO_TEST_CASE(test_close_frame_on_websocket_free)\n{\n\tbool is_server = true;\n\tF f(is_server);\n\t\n\twebsocket_free(&f.ws);\n\tBOOST_CHECK_MESSAGE(is_close_frame(), \"No close frame sent when freeing the websocket!\");\n}\n\nBOOST_AUTO_TEST_CASE(test_receive_text_frame)\n{\n\tbool is_server = true;\n\tF f(is_server);\n\t\n\tstatic const char *message = \"Hello World!\";\n\tuint8_t mask[4] = {0xaa, 0x55, 0xcc, 0x11};\n\tprepare_text_message(message, is_server, mask);\n\tws_get_header(&f.ws, read_buffer_ptr++, read_buffer_length);\n\twebsocket_free(&f.ws);\n\tBOOST_CHECK_MESSAGE(text_message_received_called, \"Callback for text messages was not called!\");\n\tBOOST_CHECK_MESSAGE(::strcmp(message, (char *)readback_buffer) == 0, \"Did not received the same message as sent!\");\n}\n<|endoftext|>"} {"text":"\/*\n * Sensitive.cpp\n *\n * Created on: 25\/lug\/2011\n * Author: Massi\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\n\nint main()\n{\n\tRenal::NextCalculator *generic_calculator = new Renal::LaGrangeCalculator();\n\n\tgeneric_calculator->InsertCoords(1., 2.);\n\tgeneric_calculator->InsertCoords(2., 3.);\n\tgeneric_calculator->InsertCoords(3., 4.);\n\n\ttry {\n\t\tif (generic_calculator->BuildFunction()) {\n\t\t\tstd::vector polynom = generic_calculator->GetPolynom();\n\n\t\t\tprintf(\"\\t\\tf(x) = \");\n\t\t\tfor (std::vector::iterator ite = polynom.begin(); ite != polynom.end(); ++ite)\n\t\t\t\tprintf(\"%1.f \", *ite);\n\t\t\tprintf(\"\\n\\n\\n\\n\"); \/* 0 1 1 = x + 1 *\/\n\t\t}\n\t}\n\n\tcatch (Renal::NextException &e) {\n\t\te.PrintMessage();\n\t}\n\n\tgeneric_calculator->Clear();\n\n\tgeneric_calculator->InsertCoords(1., 7.);\n\tgeneric_calculator->InsertCoords(3., 31.);\n\tgeneric_calculator->InsertCoords(5., 71.);\n\n\ttry {\n\t\tif (generic_calculator->BuildFunction()) {\n\t\t\tstd::vector polynom = generic_calculator->GetPolynom();\n\n\t\t\tprintf(\"\\t\\tf(x) = \");\n\t\t\tfor (std::vector::iterator ite = polynom.begin(); ite != polynom.end(); ++ite)\n\t\t\t\tprintf(\"%1.f \", *ite);\n\t\t\tprintf(\"\\n\\n\\n\\n\"); \/* 2 4 1 = 2x^2 + 4x + 1 *\/\n\t\t}\n\t}\n\n\tcatch (Renal::NextException &e) {\n\t\te.PrintMessage();\n\t}\n\n\n\tgeneric_calculator->Clear();\n\n\tgeneric_calculator->InsertCoords(2., 1.);\n\tgeneric_calculator->InsertCoords(4., 2.);\n\tgeneric_calculator->InsertCoords(6., 3.);\n\n\ttry {\n\t\tif (generic_calculator->BuildFunction()) {\n\t\t\tstd::vector polynom = generic_calculator->GetPolynom();\n\n\t\t\tprintf(\"\\t\\tf(x) = \");\n\t\t\tfor (std::vector::iterator ite = polynom.begin(); ite != polynom.end(); ++ite)\n\t\t\t\tprintf(\"%1.2f \", *ite);\n\t\t\tprintf(\"\\n\\n\\n\\n\"); \/* 0 0.5 0 = x\/2 *\/\n\t\t}\n\t}\n\n\tcatch (Renal::NextException &e) {\n\t\te.PrintMessage();\n\t}\n\n\tdelete(generic_calculator);\n\n\treturn 0;\n}\nBetter testing unit\/*\n * Sensitive.cpp\n *\n * Created on: 25\/lug\/2011\n * Author: Massi\n *\/\n\n#include \n#include \n\n\n#include \n#include \n#include \n\nRenal::NextCalculator *generic_calculator;\n\n\nvoid TestWithCoords(std::pair pair1, std::pair pair2, std::pair pair3)\n{\n\tgeneric_calculator->Clear();\n\n\tgeneric_calculator->InsertCoords(pair1);\n\tgeneric_calculator->InsertCoords(pair2);\n\tgeneric_calculator->InsertCoords(pair3);\n\n\ttry {\n\t\tif (generic_calculator->BuildFunction()) {\n\t\t\tstd::vector polynom = generic_calculator->GetPolynom();\n\n\t\t\tprintf(\"\\t\\tf(x) = \");\n\t\t\tfor (std::vector::iterator ite = polynom.begin(); ite != polynom.end(); ++ite)\n\t\t\t\tprintf(\"%.2f \", *ite);\n\t\t\tprintf(\"\\n\\n\\n\\n\"); \/* 0 1 1 = x + 1 *\/\n\t\t}\n\t}\n\n\tcatch (Renal::NextException &e) {\n\t\te.PrintMessage();\n\t}\n\n}\n\n\nint main()\n{\n\tgeneric_calculator = new Renal::LaGrangeCalculator();\n\n\tTestWithCoords(std::pair (1., 2.), std::pair (2., 3.), std::pair (3., 4.)); \/* 0 1 1 = x + 1 *\/\n\tTestWithCoords(std::pair (1., 7.), std::pair (3., 31.), std::pair (5., 71.)); \/* 2 4 1 = 2x^2 + 4x + 1 *\/\n\tTestWithCoords(std::pair (2., 1.), std::pair (4., 2.), std::pair (8., 4.)); \/* 0 0.05 0 = x\/2 *\/\n\tTestWithCoords(std::pair (1., 3.), std::pair (2., 7.), std::pair (3., 13.)); \/* 1 1 1 = x^2 + x + 1 *\/\n\tTestWithCoords(std::pair (1., 30.), std::pair (3., 296.), std::pair (4., 525.)); \/* 32 5 -7 = 32x^2 + 5x - 7 *\/\n\n\tdelete(generic_calculator);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n#define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n\n#include \n#include \n\n#if HAVE_DUNE_PDELAB\n#include \n#endif\n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace BaseFunctionSet {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forwards, to be used in the traits and to allow for specialization\ntemplate \nclass PdelabWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for arbitrary dimension!\");\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for these dimensions!\");\n};\n\n\nnamespace internal {\n\n\n\/\/ forward, to allow for specialization\ntemplate \nclass PdelabWrapperTraits;\n\n\n\/\/! Specialization for dimRange = 1, dimRangeRows = 1\ntemplate \nclass PdelabWrapperTraits\n{\npublic:\n typedef PdelabWrapper derived_type;\n\nprivate:\n typedef PDELab::LocalFunctionSpace PdelabLFSType;\n typedef FiniteElementInterfaceSwitch FESwitchType;\n\npublic:\n typedef typename FESwitchType::Basis BackendType;\n typedef EntityImp EntityType;\n\nprivate:\n friend class PdelabWrapper;\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapperTraits\n{\n static_assert(domainDim == rangeDim, \"Untested!\");\n\npublic:\n typedef PiolaTransformedPdelabWrapper\n derived_type;\n\nprivate:\n typedef PDELab::LocalFunctionSpace PdelabLFSType;\n typedef FiniteElementInterfaceSwitch FESwitchType;\n\npublic:\n typedef typename FESwitchType::Basis BackendType;\n typedef EntityImp EntityType;\n\nprivate:\n friend class PiolaTransformedPdelabWrapper;\n};\n\n\n} \/\/ namespace internal\n\n\n\/\/! Specialization for dimRange = 1, dimRangeRows = 1\ntemplate \nclass PdelabWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, 1, 1>\n{\n typedef PdelabWrapper ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;\n\npublic:\n typedef internal::PdelabWrapperTraits\n Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\nprivate:\n typedef typename Traits::PdelabLFSType PdelabLFSType;\n typedef typename Traits::FESwitchType FESwitchType;\n\npublic:\n typedef Dune::FieldVector DomainType;\n typedef Dune::FieldVector RangeType;\n typedef Dune::FieldMatrix JacobianRangeType;\n\n PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)\n : BaseType(ent)\n , tmp_domain_(0)\n {\n PdelabLFSType* lfs_ptr = new PdelabLFSType(space);\n lfs_ptr->bind(this->entity());\n lfs_ = std::unique_ptr(lfs_ptr);\n backend_ = std::unique_ptr(new BackendType(FESwitchType::basis(lfs_->finiteElement())));\n } \/\/ PdelabWrapper(...)\n\n PdelabWrapper(ThisType&& source) = default;\n PdelabWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const override final\n {\n return backend_->size();\n }\n\n virtual size_t order() const override final\n {\n return backend_->order();\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const override final\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateFunction(xx, ret);\n } \/\/ ... evaluate(...)\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const override final\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateJacobian(xx, ret);\n const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx);\n for (size_t ii = 0; ii < ret.size(); ++ii) {\n jacobian_inverse_transposed.mv(ret[ii][0], tmp_domain_);\n ret[ii][0] = tmp_domain_;\n }\n } \/\/ ... jacobian(...)\n\n using BaseType::jacobian;\n\nprivate:\n mutable DomainType tmp_domain_;\n std::unique_ptr lfs_;\n std::unique_ptr backend_;\n}; \/\/ class PdelabWrapper\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>\n{\n typedef PiolaTransformedPdelabWrapper ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;\n\npublic:\n typedef internal::PiolaTransformedPdelabWrapperTraits Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\nprivate:\n typedef typename Traits::PdelabLFSType PdelabLFSType;\n typedef typename Traits::FESwitchType FESwitchType;\n\npublic:\n using typename BaseType::DomainFieldType;\n using BaseType::dimDomain;\n using typename BaseType::DomainType;\n using typename BaseType::RangeType;\n using typename BaseType::JacobianRangeType;\n\n PiolaTransformedPdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)\n : BaseType(ent)\n , tmp_domain_(DomainFieldType(0))\n , tmp_jacobian_transposed_(DomainFieldType(0))\n , tmp_jacobian_inverse_transposed_(DomainFieldType(0))\n {\n PdelabLFSType* lfs_ptr = new PdelabLFSType(space);\n lfs_ptr->bind(this->entity());\n lfs_ = std::unique_ptr(lfs_ptr);\n backend_ = std::unique_ptr(new BackendType(FESwitchType::basis(lfs_->finiteElement())));\n tmp_ranges_ = std::vector(backend_->size(), RangeType(0));\n tmp_jacobian_ranges_ = std::vector(backend_->size(), JacobianRangeType(0));\n } \/\/ PdelabWrapper(...)\n\n PiolaTransformedPdelabWrapper(ThisType&& source) = default;\n\n PiolaTransformedPdelabWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const override final\n {\n return backend_->size();\n }\n\n virtual size_t order() const override final\n {\n return backend_->order();\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const override final\n {\n assert(lfs_);\n assert(backend_);\n assert(tmp_ranges_.size() >= backend_->size());\n assert(ret.size() >= backend_->size());\n backend_->evaluateFunction(xx, tmp_ranges_);\n const auto geometry = this->entity().geometry();\n tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);\n const DomainFieldType integration_element = geometry.integrationElement(xx);\n for (size_t ii = 0; ii < backend_->size(); ++ii) {\n tmp_jacobian_transposed_.mtv(tmp_ranges_[ii], ret[ii]);\n ret[ii] \/= integration_element;\n }\n } \/\/ ... evaluate(...)\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const override final\n {\n assert(lfs_);\n assert(backend_);\n assert(ret.size() >= backend_->size());\n backend_->evaluateJacobian(xx, tmp_jacobian_ranges_);\n const auto geometry = this->entity().geometry();\n tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);\n tmp_jacobian_inverse_transposed_ = geometry.jacobianInverseTransposed(xx);\n const DomainFieldType integration_element = geometry.integrationElement(xx);\n for (size_t ii = 0; ii < backend_->size(); ++ii) {\n for (size_t jj = 0; jj < dimDomain; ++jj) {\n tmp_jacobian_inverse_transposed_.mv(tmp_jacobian_ranges_[ii][jj], ret[ii][jj]);\n tmp_jacobian_transposed_.mv(ret[ii][jj], tmp_jacobian_ranges_[ii][jj]);\n tmp_jacobian_ranges_[ii][jj] \/= integration_element;\n ret[ii][jj] = tmp_jacobian_ranges_[ii][jj];\n }\n }\n } \/\/ ... jacobian(...)\n\n using BaseType::jacobian;\n\nprivate:\n mutable DomainType tmp_domain_;\n mutable typename EntityType::Geometry::JacobianTransposed tmp_jacobian_transposed_;\n mutable typename EntityType::Geometry::JacobianInverseTransposed tmp_jacobian_inverse_transposed_;\n std::unique_ptr lfs_;\n std::unique_ptr backend_;\n mutable std::vector tmp_ranges_;\n mutable std::vector tmp_jacobian_ranges_;\n}; \/\/ class PiolaTransformedPdelabWrapper\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate \nclass PdelabWrapper\n{\n static_assert(AlwaysFalse::value, \"You are missing dune-pdelab!\");\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n{\n static_assert(AlwaysFalse::value, \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n} \/\/ namespace BaseFunctionSet\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n[basefunctionset.pdelab] use correct types from base\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n#define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n\n#include \n#include \n\n#if HAVE_DUNE_PDELAB\n#include \n#endif\n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace BaseFunctionSet {\n\n#if HAVE_DUNE_PDELAB\n\n\n\/\/ forwards, to be used in the traits and to allow for specialization\ntemplate \nclass PdelabWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for arbitrary dimension!\");\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for these dimensions!\");\n};\n\n\nnamespace internal {\n\n\n\/\/ forward, to allow for specialization\ntemplate \nclass PdelabWrapperTraits;\n\n\n\/\/! Specialization for dimRange = 1, dimRangeRows = 1\ntemplate \nclass PdelabWrapperTraits\n{\npublic:\n typedef PdelabWrapper derived_type;\n\nprivate:\n typedef PDELab::LocalFunctionSpace PdelabLFSType;\n typedef FiniteElementInterfaceSwitch FESwitchType;\n\npublic:\n typedef typename FESwitchType::Basis BackendType;\n typedef EntityImp EntityType;\n\nprivate:\n friend class PdelabWrapper;\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapperTraits\n{\n static_assert(domainDim == rangeDim, \"Untested!\");\n\npublic:\n typedef PiolaTransformedPdelabWrapper\n derived_type;\n\nprivate:\n typedef PDELab::LocalFunctionSpace PdelabLFSType;\n typedef FiniteElementInterfaceSwitch FESwitchType;\n\npublic:\n typedef typename FESwitchType::Basis BackendType;\n typedef EntityImp EntityType;\n\nprivate:\n friend class PiolaTransformedPdelabWrapper;\n};\n\n\n} \/\/ namespace internal\n\n\n\/\/! Specialization for dimRange = 1, dimRangeRows = 1\ntemplate \nclass PdelabWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, 1, 1>\n{\n typedef PdelabWrapper ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, 1, 1> BaseType;\n\npublic:\n typedef internal::PdelabWrapperTraits\n Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\nprivate:\n typedef typename Traits::PdelabLFSType PdelabLFSType;\n typedef typename Traits::FESwitchType FESwitchType;\n\npublic:\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeType RangeType;\n typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)\n : BaseType(ent)\n , tmp_domain_(0)\n {\n PdelabLFSType* lfs_ptr = new PdelabLFSType(space);\n lfs_ptr->bind(this->entity());\n lfs_ = std::unique_ptr(lfs_ptr);\n backend_ = std::unique_ptr(new BackendType(FESwitchType::basis(lfs_->finiteElement())));\n } \/\/ PdelabWrapper(...)\n\n PdelabWrapper(ThisType&& source) = default;\n PdelabWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const override final\n {\n return backend_->size();\n }\n\n virtual size_t order() const override final\n {\n return backend_->order();\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const override final\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateFunction(xx, ret);\n } \/\/ ... evaluate(...)\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const override final\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateJacobian(xx, ret);\n const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx);\n for (size_t ii = 0; ii < ret.size(); ++ii) {\n jacobian_inverse_transposed.mv(ret[ii][0], tmp_domain_);\n ret[ii][0] = tmp_domain_;\n }\n } \/\/ ... jacobian(...)\n\n using BaseType::jacobian;\n\nprivate:\n mutable DomainType tmp_domain_;\n std::unique_ptr lfs_;\n std::unique_ptr backend_;\n}; \/\/ class PdelabWrapper\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>\n{\n typedef PiolaTransformedPdelabWrapper ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;\n\npublic:\n typedef internal::PiolaTransformedPdelabWrapperTraits Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\nprivate:\n typedef typename Traits::PdelabLFSType PdelabLFSType;\n typedef typename Traits::FESwitchType FESwitchType;\n\npublic:\n using typename BaseType::DomainFieldType;\n using BaseType::dimDomain;\n using typename BaseType::DomainType;\n using typename BaseType::RangeType;\n using typename BaseType::JacobianRangeType;\n\n PiolaTransformedPdelabWrapper(const PdelabSpaceType& space, const EntityType& ent)\n : BaseType(ent)\n , tmp_domain_(DomainFieldType(0))\n , tmp_jacobian_transposed_(DomainFieldType(0))\n , tmp_jacobian_inverse_transposed_(DomainFieldType(0))\n {\n PdelabLFSType* lfs_ptr = new PdelabLFSType(space);\n lfs_ptr->bind(this->entity());\n lfs_ = std::unique_ptr(lfs_ptr);\n backend_ = std::unique_ptr(new BackendType(FESwitchType::basis(lfs_->finiteElement())));\n tmp_ranges_ = std::vector(backend_->size(), RangeType(0));\n tmp_jacobian_ranges_ = std::vector(backend_->size(), JacobianRangeType(0));\n } \/\/ PdelabWrapper(...)\n\n PiolaTransformedPdelabWrapper(ThisType&& source) = default;\n\n PiolaTransformedPdelabWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const override final\n {\n return backend_->size();\n }\n\n virtual size_t order() const override final\n {\n return backend_->order();\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const override final\n {\n assert(lfs_);\n assert(backend_);\n assert(tmp_ranges_.size() >= backend_->size());\n assert(ret.size() >= backend_->size());\n backend_->evaluateFunction(xx, tmp_ranges_);\n const auto geometry = this->entity().geometry();\n tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);\n const DomainFieldType integration_element = geometry.integrationElement(xx);\n for (size_t ii = 0; ii < backend_->size(); ++ii) {\n tmp_jacobian_transposed_.mtv(tmp_ranges_[ii], ret[ii]);\n ret[ii] \/= integration_element;\n }\n } \/\/ ... evaluate(...)\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const override final\n {\n assert(lfs_);\n assert(backend_);\n assert(ret.size() >= backend_->size());\n backend_->evaluateJacobian(xx, tmp_jacobian_ranges_);\n const auto geometry = this->entity().geometry();\n tmp_jacobian_transposed_ = geometry.jacobianTransposed(xx);\n tmp_jacobian_inverse_transposed_ = geometry.jacobianInverseTransposed(xx);\n const DomainFieldType integration_element = geometry.integrationElement(xx);\n for (size_t ii = 0; ii < backend_->size(); ++ii) {\n for (size_t jj = 0; jj < dimDomain; ++jj) {\n tmp_jacobian_inverse_transposed_.mv(tmp_jacobian_ranges_[ii][jj], ret[ii][jj]);\n tmp_jacobian_transposed_.mv(ret[ii][jj], tmp_jacobian_ranges_[ii][jj]);\n tmp_jacobian_ranges_[ii][jj] \/= integration_element;\n ret[ii][jj] = tmp_jacobian_ranges_[ii][jj];\n }\n }\n } \/\/ ... jacobian(...)\n\n using BaseType::jacobian;\n\nprivate:\n mutable DomainType tmp_domain_;\n mutable typename EntityType::Geometry::JacobianTransposed tmp_jacobian_transposed_;\n mutable typename EntityType::Geometry::JacobianInverseTransposed tmp_jacobian_inverse_transposed_;\n std::unique_ptr lfs_;\n std::unique_ptr backend_;\n mutable std::vector tmp_ranges_;\n mutable std::vector tmp_jacobian_ranges_;\n}; \/\/ class PiolaTransformedPdelabWrapper\n\n\n#else \/\/ HAVE_DUNE_PDELAB\n\n\ntemplate \nclass PdelabWrapper\n{\n static_assert(AlwaysFalse::value, \"You are missing dune-pdelab!\");\n};\n\n\ntemplate \nclass PiolaTransformedPdelabWrapper\n{\n static_assert(AlwaysFalse::value, \"You are missing dune-pdelab!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_PDELAB\n\n} \/\/ namespace BaseFunctionSet\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagpl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n#include \"GlobalAllocator.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Metrics.hpp\"\n#include \"FlatCombiner.hpp\"\n#include \n#include \n#include \n\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_insert_ops);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_insert_msgs);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_lookup_ops);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_lookup_msgs);\n\n\nnamespace Grappa {\n\ntemplate< typename K, typename V > \nclass GlobalHashMap {\nprotected:\n struct Entry {\n K key;\n V val;\n Entry( K key ) : key(key), val() {}\n Entry( K key, V val): key(key), val(val) {}\n };\n \n struct ResultEntry {\n bool found;\n ResultEntry * next;\n V val;\n };\n \npublic:\n struct Cell { \/\/ TODO: keep first few in the 64-byte block, then go to secondary storage\n std::vector entries;\n \n Cell() : entries() { entries.reserve(10); }\n \n void clear() { entries.clear(); }\n \n std::pair lookup(K key) {\n \n for (auto& e : this->entries) if (e.key == key) return std::pair{true, e.val};\n return std::pair(false,V());\n }\n void insert(const K& key, const V& val) {\n bool found = false;\n for (auto& e : entries) {\n if (e.key == key) {\n e.val = val;\n found = true;\n break;\n }\n }\n if (!found) {\n entries.emplace_back(key, val);\n }\n }\n } GRAPPA_BLOCK_ALIGNED;\nprotected:\n struct Proxy {\n static const size_t LOCAL_HASH_SIZE = 1<<10;\n \n GlobalHashMap * owner;\n std::unordered_map map;\n std::unordered_map lookups;\n \n Proxy(GlobalHashMap * owner): owner(owner)\n , map(LOCAL_HASH_SIZE)\n , lookups(LOCAL_HASH_SIZE)\n {\n clear();\n }\n \n void clear() { map.clear(); lookups.clear(); }\n \n Proxy * clone_fresh() { return locale_new(owner); }\n \n bool is_full() {\n return map.size() >= LOCAL_HASH_SIZE\n || lookups.size() >= LOCAL_HASH_SIZE;\n }\n \n void insert(const K& newk, const V& newv) {\n if (map.count(newk) == 0) {\n map[newk] = newv;\n }\n }\n \n void sync() {\n CompletionEvent ce(map.size()+lookups.size());\n auto cea = make_global(&ce);\n \n for (auto& e : map) { auto& k = e.first; auto& v = e.second;\n ++hashmap_insert_msgs;\n auto cell = owner->base+owner->computeIndex(k);\n send_heap_message(cell.core(), [cell,cea,k,v]{\n cell->insert(k, v);\n complete(cea);\n });\n }\n \n for (auto& e : lookups) { auto k = e.first;\n ++hashmap_lookup_msgs;\n auto re = e.second;\n DVLOG(3) << \"lookup \" << k << \" with re = \" << re;\n auto cell = owner->base+owner->computeIndex(k);\n \n send_heap_message(cell.core(), [cell,k,cea,re]{\n Cell * c = cell.localize();\n bool found = false;\n V val;\n for (auto& e : c->entries) if (e.key == k) {\n found = true;\n val = e.val;\n break;\n }\n send_heap_message(cea.core(), [cea,re,found,val]{\n ResultEntry * r = re;\n while (r != nullptr) {\n r->found = found;\n r->val = val;\n r = r->next;\n }\n complete(cea);\n });\n });\n }\n ce.wait();\n }\n };\n\n \/\/ private members\n GlobalAddress self;\n GlobalAddress< Cell > base;\n size_t capacity;\n \n FlatCombiner proxy;\n\n uint64_t computeIndex(K key) {\n static std::hash hasher;\n return hasher(key) % capacity;\n }\n\n \/\/ for creating local GlobalHashMap\n GlobalHashMap( GlobalAddress self, GlobalAddress base, size_t capacity )\n : self(self), base(base), capacity(capacity)\n , proxy(locale_new(this))\n {\n CHECK_LT(sizeof(self)+sizeof(base)+sizeof(capacity)+sizeof(proxy), 2*block_size);\n }\n \npublic:\n \/\/ for static construction\n GlobalHashMap( ) {}\n \n static GlobalAddress create(size_t total_capacity) {\n auto base = global_alloc(total_capacity);\n auto self = symmetric_global_alloc();\n call_on_all_cores([self,base,total_capacity]{\n new (self.localize()) GlobalHashMap(self, base, total_capacity);\n });\n forall(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });\n return self;\n }\n \n GlobalAddress begin() { return this->base; }\n size_t ncells() { return this->capacity; }\n \n void clear() {\n forall(base, capacity, [](Cell& c){ c.clear(); });\n }\n \n void destroy() {\n auto self = this->self;\n forall(this->base, this->capacity, [](Cell& c){ c.~Cell(); });\n global_free(this->base);\n call_on_all_cores([self]{ self->~GlobalHashMap(); });\n global_free(self);\n }\n \n template< typename F >\n void forall_entries(F visit) {\n forall(base, capacity, [visit](int64_t i, Cell& c){\n \/\/ if cell is not hit then no action\n if (c.entries == nullptr) return;\n DVLOG(3) << \"c<\" << &c << \"> entries:\" << c.entries << \" size: \" << c.entries->size();\n for (Entry& e : *c.entries) {\n visit(e.key, *e.val);\n }\n });\n }\n \n bool lookup(K key, V * val) {\n ++hashmap_lookup_ops;\n if (FLAGS_flat_combining) {\n ResultEntry re{false,nullptr};\n DVLOG(3) << \"lookup[\" << key << \"] = \" << &re;\n \n proxy.combine([&re,key](Proxy& p){\n \/\/ if (p.map.count(key) > 0) {\n \/\/ re.found = true;\n \/\/ re.val = p.map[key];\n \/\/ return FCStatus::SATISFIED;\n \/\/ } else {\n if (p.lookups.count(key) == 0) p.lookups[key] = nullptr;\n re.next = p.lookups[key];\n p.lookups[key] = &re;\n DVLOG(3) << \"p.lookups[\" << key << \"] = \" << &re;\n return FCStatus::BLOCKED;\n \/\/ }\n });\n *val = re.val;\n return re.found;\n } else {\n ++hashmap_lookup_msgs;\n auto result = delegate::call(base+computeIndex(key), [key](Cell* c){\n return c->lookup(key);\n });\n *val = result.second;\n return result.first;\n }\n }\n \n void insert(K key, V val) {\n ++hashmap_insert_ops;\n if (FLAGS_flat_combining) {\n proxy.combine([key,val](Proxy& p){ p.map[key] = val; return FCStatus::BLOCKED; });\n } else {\n ++hashmap_insert_msgs;\n delegate::call(base+computeIndex(key), [key,val](Cell * c) { c->insert(key,val); });\n }\n }\n\n} GRAPPA_BLOCK_ALIGNED;\n\ntemplate< GlobalCompletionEvent * GCE = &impl::local_gce,\n int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG,\n typename T = decltype(nullptr),\n typename V = decltype(nullptr),\n typename F = decltype(nullptr) >\nvoid forall(GlobalAddress> self, F visit) {\n forall(self->begin(), self->ncells(),\n [visit](typename GlobalHashMap::Cell& c){\n for (auto& e : c.entries) {\n visit(e.key, e.val);\n }\n });\n}\n\n} \/\/ namespace Grappa\nGlobalHashMap::insert_async that takes arbitrary lambda (so we can, for instance, insert into a CoreSet value\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagpl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#pragma once\n\n#include \"GlobalAllocator.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Metrics.hpp\"\n#include \"FlatCombiner.hpp\"\n#include \n#include \n#include \n\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_insert_ops);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_insert_msgs);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_lookup_ops);\nGRAPPA_DECLARE_METRIC(SimpleMetric, hashmap_lookup_msgs);\n\n\nnamespace Grappa {\n\ntemplate< typename K, typename V > \nclass GlobalHashMap {\nprotected:\n struct Entry {\n K key;\n V val;\n Entry( K key ) : key(key), val() {}\n Entry( K key, V val): key(key), val(val) {}\n };\n \n struct ResultEntry {\n bool found;\n ResultEntry * next;\n V val;\n };\n \npublic:\n struct Cell { \/\/ TODO: keep first few in the 64-byte block, then go to secondary storage\n std::vector entries;\n \n Cell() : entries() { entries.reserve(10); }\n \n void clear() { entries.clear(); }\n \n std::pair lookup(K key) {\n \n for (auto& e : this->entries) if (e.key == key) return std::pair{true, e.val};\n return std::pair(false,V());\n }\n void insert(const K& key, const V& val) {\n bool found = false;\n for (auto& e : entries) {\n if (e.key == key) {\n e.val = val;\n found = true;\n break;\n }\n }\n if (!found) {\n entries.emplace_back(key, val);\n }\n }\n } GRAPPA_BLOCK_ALIGNED;\nprotected:\n struct Proxy {\n static const size_t LOCAL_HASH_SIZE = 1<<10;\n \n GlobalHashMap * owner;\n std::unordered_map map;\n std::unordered_map lookups;\n \n Proxy(GlobalHashMap * owner): owner(owner)\n , map(LOCAL_HASH_SIZE)\n , lookups(LOCAL_HASH_SIZE)\n {\n clear();\n }\n \n void clear() { map.clear(); lookups.clear(); }\n \n Proxy * clone_fresh() { return locale_new(owner); }\n \n bool is_full() {\n return map.size() >= LOCAL_HASH_SIZE\n || lookups.size() >= LOCAL_HASH_SIZE;\n }\n \n void insert(const K& newk, const V& newv) {\n if (map.count(newk) == 0) {\n map[newk] = newv;\n }\n }\n \n void sync() {\n CompletionEvent ce(map.size()+lookups.size());\n auto cea = make_global(&ce);\n \n for (auto& e : map) { auto& k = e.first; auto& v = e.second;\n ++hashmap_insert_msgs;\n auto cell = owner->base+owner->computeIndex(k);\n send_heap_message(cell.core(), [cell,cea,k,v]{\n cell->insert(k, v);\n complete(cea);\n });\n }\n \n for (auto& e : lookups) { auto k = e.first;\n ++hashmap_lookup_msgs;\n auto re = e.second;\n DVLOG(3) << \"lookup \" << k << \" with re = \" << re;\n auto cell = owner->base+owner->computeIndex(k);\n \n send_heap_message(cell.core(), [cell,k,cea,re]{\n Cell * c = cell.localize();\n bool found = false;\n V val;\n for (auto& e : c->entries) if (e.key == k) {\n found = true;\n val = e.val;\n break;\n }\n send_heap_message(cea.core(), [cea,re,found,val]{\n ResultEntry * r = re;\n while (r != nullptr) {\n r->found = found;\n r->val = val;\n r = r->next;\n }\n complete(cea);\n });\n });\n }\n ce.wait();\n }\n };\n\n \/\/ private members\n GlobalAddress self;\n GlobalAddress< Cell > base;\n size_t capacity;\n \n FlatCombiner proxy;\n\n uint64_t computeIndex(K key) {\n static std::hash hasher;\n return hasher(key) % capacity;\n }\n\n \/\/ for creating local GlobalHashMap\n GlobalHashMap( GlobalAddress self, GlobalAddress base, size_t capacity )\n : self(self), base(base), capacity(capacity)\n , proxy(locale_new(this))\n {\n CHECK_LT(sizeof(self)+sizeof(base)+sizeof(capacity)+sizeof(proxy), 2*block_size);\n }\n \npublic:\n \/\/ for static construction\n GlobalHashMap( ) {}\n \n static GlobalAddress create(size_t total_capacity) {\n auto base = global_alloc(total_capacity);\n auto self = symmetric_global_alloc();\n call_on_all_cores([self,base,total_capacity]{\n new (self.localize()) GlobalHashMap(self, base, total_capacity);\n });\n forall(base, total_capacity, [](int64_t i, Cell& c) { new (&c) Cell(); });\n return self;\n }\n \n GlobalAddress begin() { return this->base; }\n size_t ncells() { return this->capacity; }\n \n void clear() {\n forall(base, capacity, [](Cell& c){ c.clear(); });\n }\n \n void destroy() {\n auto self = this->self;\n forall(this->base, this->capacity, [](Cell& c){ c.~Cell(); });\n global_free(this->base);\n call_on_all_cores([self]{ self->~GlobalHashMap(); });\n global_free(self);\n }\n \n template< typename F >\n void forall_entries(F visit) {\n forall(base, capacity, [visit](int64_t i, Cell& c){\n \/\/ if cell is not hit then no action\n if (c.entries == nullptr) return;\n DVLOG(3) << \"c<\" << &c << \"> entries:\" << c.entries << \" size: \" << c.entries->size();\n for (Entry& e : *c.entries) {\n visit(e.key, *e.val);\n }\n });\n }\n \n bool lookup(K key, V * val) {\n ++hashmap_lookup_ops;\n if (FLAGS_flat_combining) {\n ResultEntry re{false,nullptr};\n DVLOG(3) << \"lookup[\" << key << \"] = \" << &re;\n \n proxy.combine([&re,key](Proxy& p){\n \/\/ if (p.map.count(key) > 0) {\n \/\/ re.found = true;\n \/\/ re.val = p.map[key];\n \/\/ return FCStatus::SATISFIED;\n \/\/ } else {\n if (p.lookups.count(key) == 0) p.lookups[key] = nullptr;\n re.next = p.lookups[key];\n p.lookups[key] = &re;\n DVLOG(3) << \"p.lookups[\" << key << \"] = \" << &re;\n return FCStatus::BLOCKED;\n \/\/ }\n });\n *val = re.val;\n return re.found;\n } else {\n ++hashmap_lookup_msgs;\n auto result = delegate::call(base+computeIndex(key), [key](Cell* c){\n return c->lookup(key);\n });\n *val = result.second;\n return result.first;\n }\n }\n \n void insert(K key, V val) {\n ++hashmap_insert_ops;\n if (FLAGS_flat_combining) {\n proxy.combine([key,val](Proxy& p){ p.map[key] = val; return FCStatus::BLOCKED; });\n } else {\n ++hashmap_insert_msgs;\n delegate::call(base+computeIndex(key), [key,val](Cell * c) { c->insert(key,val); });\n }\n }\n \n template< typename F = nullptr_t >\n void insert_async(K key, F on_insert) {\n ++hashmap_insert_msgs;\n delegate::call(base+computeIndex(key), [=](Cell& c){\n for (auto& e : c.entries) {\n if (e.key == key) {\n on_insert(e.val);\n return;\n }\n }\n c.entries.emplace_back(key);\n on_insert(c.entries.back().val);\n });\n }\n \n} GRAPPA_BLOCK_ALIGNED;\n\ntemplate< GlobalCompletionEvent * GCE = &impl::local_gce,\n int64_t Threshold = impl::USE_LOOP_THRESHOLD_FLAG,\n typename T = decltype(nullptr),\n typename V = decltype(nullptr),\n typename F = decltype(nullptr) >\nvoid forall(GlobalAddress> self, F visit) {\n forall(self->begin(), self->ncells(),\n [visit](typename GlobalHashMap::Cell& c){\n for (auto& e : c.entries) {\n visit(e.key, e.val);\n }\n });\n}\n\n} \/\/ namespace Grappa\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \/\/read, write\n#include \/\/strerror\n#include \n\nclass TcpClient\n{\n\tpublic: \n\t\tint descriptor;\n\t\tbool setup(const char* addr, uint16_t port);\n\t\tbool connection();\n\t\tbool send(const char* data);\n\t\tbool receive();\n\t\tchar receivedData[1024];\n\n\n\tprivate:\n\t\tstruct sockaddr_in server; \n};\n\nbool TcpClient::setup(const char *addr, uint16_t port)\n{\n\tserver.sin_addr.s_addr = inet_addr(addr);\n\tserver.sin_family = AF_INET;\n\tserver.sin_port = htons( port );\n\tdescriptor = socket(AF_INET , SOCK_STREAM , 0);\n\n\tif(descriptor<0)\n\t{\n\t\tstd::cerr <<\"descriptor creation: \"<< strerror(errno) << std::endl;\n\t\treturn false;\n\t}\n\n\telse \n\t{\n\t\treturn true;\n\t} \n}\n\nbool TcpClient::connection()\n{ \n\tif (connect(descriptor , (struct sockaddr *)&server , sizeof(server)) < 0) \n\t{\n\t\tstd::cerr <<\"connection: \"<< strerror(errno) << std::endl;\n\t\treturn false;\n\t}\n\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n\nbool TcpClient::receive()\n{\n memset(receivedData, 0, sizeof(receivedData)); \n\tif( read(descriptor,receivedData,1024)>0)\n\t{\n\t\treturn true;\n\t}\n\telse return false;\n}\n\nbool TcpClient::send(const char* data) \/\/this could be smart string pointer\n{\n\tconst size_t len = sizeof(data);\n\twrite(descriptor , data , len);\n\treturn true;\n}\nesthetic correction |#include \n#include \n#include \n#include \n#include \/\/read, write\n#include \/\/strerror\n#include \n\nclass TcpClient\n{\n\tpublic: \n\t\tint descriptor;\n\t\tbool setup(const char* addr, uint16_t port);\n\t\tbool connection();\n\t\tbool send(const char* data);\n\t\tbool receive();\n\t\tchar receivedData[1024];\n\n\n\tprivate:\n\t\tstruct sockaddr_in server; \n};\n\nbool TcpClient::setup(const char *addr, uint16_t port)\n{\n\tserver.sin_addr.s_addr = inet_addr(addr);\n\tserver.sin_family = AF_INET;\n\tserver.sin_port = htons( port );\n\tdescriptor = socket(AF_INET , SOCK_STREAM , 0);\n\n\tif(descriptor<0)\n\t{\n\t\tstd::cerr <<\"descriptor creation: \"<< strerror(errno) << std::endl;\n\t\treturn false;\n\t}\n\n\telse \n\t{\n\t\treturn true;\n\t} \n}\n\nbool TcpClient::connection()\n{ \n\tif (connect(descriptor , (struct sockaddr *)&server , sizeof(server)) < 0) \n\t{\n\t\tstd::cerr <<\"connection: \"<< strerror(errno) << std::endl;\n\t\treturn false;\n\t}\n\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n\nbool TcpClient::receive()\n{\n memset(receivedData, 0, sizeof(receivedData)); \n\tif( read(descriptor,receivedData,1024)>0)\n\t{\n\t\treturn true;\n\t}\n\telse return false;\n}\n\nbool TcpClient::send(const char* data) \/\/this could be smart string pointer\n{\n\twrite(descriptor , data , strlen(data));\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\/\/ StdAir\n#include \n#include \n#include \n#include \n#include \n\/\/ TRAVEL-CCM\n#include \n\nnamespace TRAVELCCM {\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n const stdair::TravelSolutionStruct* PriceOrientedModel::\n chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,\n const stdair::BookingRequestStruct& iBookingRequest) {\n stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;\n\n \/\/ Get the willingness-to-pay of the customer\n const stdair::WTP_T& lWTP = iBookingRequest.getWTP();\n\n stdair::Fare_T lLowestFare = std::numeric_limits::max();\n \/\/ Browse the travel solution list and choose the cheapest one.\n for (stdair::TravelSolutionList_T::iterator itTS =\n ioTravelSolutionList.begin(); itTS != ioTravelSolutionList.end();\n ++itTS) {\n stdair::TravelSolutionStruct& lCurrentTS = *itTS;\n\n const stdair::FareOptionList_T& lFareOptionList =\n lCurrentTS.getFareOptionList();\n for (stdair::FareOptionList_T::const_iterator itFO =\n lFareOptionList.begin(); itFO != lFareOptionList.end(); ++itFO) {\n const stdair::FareOptionStruct& lCurrentFO = *itFO;\n\n \/\/ Check the availability.\n const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();\n const stdair::ClassList_StringList_T& lClassPath =\n lCurrentFO.getClassPath();\n const stdair::ClassAvailabilityMapHolder_T& lClassAvailabilityMapHolder =\n lCurrentTS.getClassAvailabilityMapHolder();\n bool lAvlSuff = true;\n stdair::ClassAvailabilityMapHolder_T::const_iterator itCAM =\n lClassAvailabilityMapHolder.begin();\n stdair::ClassList_StringList_T::const_iterator itClassList =\n lClassPath.begin();\n assert (lClassAvailabilityMapHolder.size() > 0 && lClassPath.size() > 0);\n\n for (; itCAM != lClassAvailabilityMapHolder.end() &&\n itClassList != lClassPath.end(); ++itCAM, ++itClassList) {\n const stdair::ClassList_String_T& lCurrentClassList = *itClassList;\n const stdair::ClassAvailabilityMap_T& lClassAvlMap = *itCAM;\n stdair::ClassCode_T lFirstClass;\n lFirstClass.append (lCurrentClassList, 0, 1);\n const stdair::ClassAvailabilityMap_T::const_iterator itClassAvl =\n lClassAvlMap.find (lFirstClass);\n\n \/\/ DEBUG\n if (itClassAvl == lClassAvlMap.end()) {\n std::ostringstream ostr;\n for (stdair::ClassAvailabilityMap_T::const_iterator it =\n lClassAvlMap.begin(); it != lClassAvlMap.end(); ++it) {\n ostr << it->first << \", \" << it->second << \" \";\n }\n\n STDAIR_LOG_DEBUG (\"Can not find the class: \" << lFirstClass\n << \" within the following map: \" << ostr.str());\n \n }\n assert (itClassAvl != lClassAvlMap.end()); \n \n const stdair::Availability_T& lAvl = itClassAvl->second;\n if (lAvl < lPartySize) {\n lAvlSuff = false;\n }\n }\n\n \/\/ Choose the current fare option and the current solution\n \/\/ if the current fare is lower than the current lowest fare.\n const stdair::Fare_T& lCurrentFare = lCurrentFO.getFare();\n if (lCurrentFare < lLowestFare && lCurrentFare <= lWTP) {\n lLowestFare = lCurrentFare;\n oChosenTS_ptr = &lCurrentTS;\n oChosenTS_ptr->setChosenFareOption (lCurrentFO);\n }\n }\n }\n \n return oChosenTS_ptr;\n }\n\n}\n[travelccm] Added debug messages.\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\/\/ StdAir\n#include \n#include \n#include \n#include \n#include \n\/\/ TRAVEL-CCM\n#include \n\nnamespace TRAVELCCM {\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n const stdair::TravelSolutionStruct* PriceOrientedModel::\n chooseTravelSolution (stdair::TravelSolutionList_T& ioTravelSolutionList,\n const stdair::BookingRequestStruct& iBookingRequest) {\n stdair::TravelSolutionStruct* oChosenTS_ptr = NULL;\n\n \/\/ Get the willingness-to-pay of the customer\n const stdair::WTP_T& lWTP = iBookingRequest.getWTP();\n\n stdair::Fare_T lLowestFare = std::numeric_limits::max();\n \/\/ Browse the travel solution list and choose the cheapest one.\n for (stdair::TravelSolutionList_T::iterator itTS =\n ioTravelSolutionList.begin(); itTS != ioTravelSolutionList.end();\n ++itTS) {\n stdair::TravelSolutionStruct& lCurrentTS = *itTS;\n\n const stdair::FareOptionList_T& lFareOptionList =\n lCurrentTS.getFareOptionList();\n for (stdair::FareOptionList_T::const_iterator itFO =\n lFareOptionList.begin(); itFO != lFareOptionList.end(); ++itFO) {\n const stdair::FareOptionStruct& lCurrentFO = *itFO;\n\n \/\/ Check the availability.\n const stdair::NbOfSeats_T& lPartySize = iBookingRequest.getPartySize();\n const stdair::ClassList_StringList_T& lClassPath =\n lCurrentFO.getClassPath();\n const stdair::ClassAvailabilityMapHolder_T& lClassAvailabilityMapHolder =\n lCurrentTS.getClassAvailabilityMapHolder();\n bool lAvlSuff = true;\n stdair::ClassAvailabilityMapHolder_T::const_iterator itCAMH =\n lClassAvailabilityMapHolder.begin();\n stdair::ClassList_StringList_T::const_iterator itClassList =\n lClassPath.begin();\n assert (lClassAvailabilityMapHolder.size() > 0 && lClassPath.size() > 0);\n\n for (; itCAMH != lClassAvailabilityMapHolder.end(),\n itClassList != lClassPath.end(); ++itCAMH, ++itClassList) {\n const stdair::ClassList_String_T& lCurrentClassList = *itClassList;\n const stdair::ClassAvailabilityMap_T& lClassAvlMap = *itCAMH;\n stdair::ClassCode_T lFirstClass;\n lFirstClass.append (lCurrentClassList, 0, 1);\n const stdair::ClassAvailabilityMap_T::const_iterator itClassAvl =\n lClassAvlMap.find (lFirstClass);\n\n \/\/ DEBUG\n if (itClassAvl == lClassAvlMap.end()) {\n std::ostringstream ostr;\n for (stdair::ClassAvailabilityMap_T::const_iterator it =\n lClassAvlMap.begin(); it != lClassAvlMap.end(); ++it) {\n ostr << it->first << \", \" << it->second << \" \";\n }\n\n STDAIR_LOG_DEBUG (\"Can not find the class: \" << lFirstClass\n << \" within the following map: \" << ostr.str());\n \n }\n assert (itClassAvl != lClassAvlMap.end());\n\n const stdair::Availability_T& lAvl = itClassAvl->second;\n if (lAvl < lPartySize) {\n lAvlSuff = false;\n }\n }\n\n \/\/ Choose the current fare option and the current solution\n \/\/ if the current fare is lower than the current lowest fare.\n const stdair::Fare_T& lCurrentFare = lCurrentFO.getFare();\n if (lCurrentFare < lLowestFare) {\n lLowestFare = lCurrentFare;\n oChosenTS_ptr = &lCurrentTS;\n oChosenTS_ptr->setChosenFareOption (lCurrentFO);\n }\n }\n }\n \n return oChosenTS_ptr;\n }\n\n}\n<|endoftext|>"} {"text":"#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \"soa\/types\/periodic_utils.h\"\n#include \n\nusing namespace std;\nusing namespace ML;\nusing namespace Datacratic;\n\nBOOST_AUTO_TEST_CASE(time_period_test)\n{\n TimePeriod tp(\"20s\");\n BOOST_CHECK_EQUAL(tp.interval, 20);\n BOOST_CHECK_EQUAL(tp.toString(), \"20s\");\n\n tp.parse(\"1m\");\n BOOST_CHECK_EQUAL(tp.interval, 60);\n BOOST_CHECK_EQUAL(tp.toString(), \"1m\");\n\n tp.parse(\"90s\");\n BOOST_CHECK_EQUAL(tp.interval, 90);\n BOOST_CHECK_EQUAL(tp.toString(), \"90s\");\n\n bool threw = false;\n try {\n JML_TRACE_EXCEPTIONS(false);\n tp.parse(\"1m25s\");\n }\n catch (...) {\n threw = true;\n }\n BOOST_CHECK(threw);\n\n tp.parse(\"1h\");\n BOOST_CHECK_EQUAL(tp.interval, 3600);\n BOOST_CHECK_EQUAL(tp.toString(), \"1h\");\n\n\n tp.parse(\"1d\");\n BOOST_CHECK_EQUAL(tp.interval, 3600 * 24);\n BOOST_CHECK_EQUAL(tp.toString(), \"1d\");\n}\n\n#if 1\nBOOST_AUTO_TEST_CASE(time_period_granularity_multiplier)\n{\n JML_TRACE_EXCEPTIONS(false);\n\n \/* different families *\/\n BOOST_CHECK_THROW(granularityMultiplier(YEARS, MINUTES), ML::Exception);\n\n \/* seconds cannot be translated to minutes *\/\n BOOST_CHECK_THROW(granularityMultiplier(SECONDS, MINUTES), ML::Exception);\n\n int mult = granularityMultiplier(MILLISECONDS, MILLISECONDS);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(MINUTES, MILLISECONDS);\n BOOST_CHECK_EQUAL(mult, 60000);\n\n mult = granularityMultiplier(MINUTES, MINUTES);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(WEEKS, MINUTES);\n BOOST_CHECK_EQUAL(mult, 10080);\n\n mult = granularityMultiplier(YEARS, YEARS);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(YEARS, MONTHS);\n BOOST_CHECK_EQUAL(mult, 12);\n}\n#endif\n\n#if 1\n\/* Ensure that operators + and += works well for TimePeriod *\/\nBOOST_AUTO_TEST_CASE(time_period_op_plus_equal)\n{\n \/* same unit *\/\n {\n TimePeriod period1(\"2m\");\n TimePeriod period2(\"5m\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, MINUTES);\n BOOST_CHECK_EQUAL(total.number, 7);\n BOOST_CHECK_EQUAL(total.interval, 420);\n }\n\n \/* distinct compatible units *\/\n {\n TimePeriod period1(\"1h\");\n TimePeriod period2(\"2s\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, SECONDS);\n BOOST_CHECK_EQUAL(total.number, 3602);\n BOOST_CHECK_EQUAL(total.interval, 3602);\n\n \/* operator += *\/\n period1 += period2;\n\n BOOST_CHECK_EQUAL(period1.granularity, SECONDS);\n BOOST_CHECK_EQUAL(period1.number, 3602);\n BOOST_CHECK_EQUAL(period1.interval, 3602);\n }\n\n \/* same as above, in reverse order *\/\n {\n TimePeriod period1(\"2s\");\n TimePeriod period2(\"1h\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, SECONDS);\n BOOST_CHECK_EQUAL(total.number, 3602);\n BOOST_CHECK_EQUAL(total.interval, 3602);\n\n \/* operator += *\/\n period1 += period2;\n\n BOOST_CHECK_EQUAL(period1.granularity, SECONDS);\n BOOST_CHECK_EQUAL(period1.number, 3602);\n BOOST_CHECK_EQUAL(period1.interval, 3602);\n }\n\n \/* incompatible units *\/\n {\n TimePeriod yearly;\n yearly.granularity = YEARS;\n yearly.number = 1;\n yearly.interval = -1; \/\/ years do not have a fixed set of seconds\n TimePeriod minutely(\"2m\");\n\n JML_TRACE_EXCEPTIONS(false);\n BOOST_CHECK_THROW(yearly + minutely, ML::Exception);\n }\n}\n#endif\nPLAT-766: test answers Jeremy's question#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \"soa\/types\/periodic_utils.h\"\n#include \n\nusing namespace std;\nusing namespace ML;\nusing namespace Datacratic;\n\nBOOST_AUTO_TEST_CASE(time_period_test)\n{\n TimePeriod tp(\"20s\");\n BOOST_CHECK_EQUAL(tp.interval, 20);\n BOOST_CHECK_EQUAL(tp.toString(), \"20s\");\n\n tp.parse(\"1m\");\n BOOST_CHECK_EQUAL(tp.interval, 60);\n BOOST_CHECK_EQUAL(tp.toString(), \"1m\");\n\n tp.parse(\"90s\");\n BOOST_CHECK_EQUAL(tp.interval, 90);\n BOOST_CHECK_EQUAL(tp.toString(), \"90s\");\n\n bool threw = false;\n try {\n JML_TRACE_EXCEPTIONS(false);\n tp.parse(\"1m25s\");\n }\n catch (...) {\n threw = true;\n }\n BOOST_CHECK(threw);\n\n tp.parse(\"1h\");\n BOOST_CHECK_EQUAL(tp.interval, 3600);\n BOOST_CHECK_EQUAL(tp.toString(), \"1h\");\n\n\n tp.parse(\"1d\");\n BOOST_CHECK_EQUAL(tp.interval, 3600 * 24);\n BOOST_CHECK_EQUAL(tp.toString(), \"1d\");\n}\n\n#if 1\nBOOST_AUTO_TEST_CASE(time_period_granularity_multiplier)\n{\n JML_TRACE_EXCEPTIONS(false);\n\n \/* different families *\/\n BOOST_CHECK_THROW(granularityMultiplier(YEARS, MINUTES), ML::Exception);\n\n \/* seconds cannot be translated to minutes *\/\n BOOST_CHECK_THROW(granularityMultiplier(SECONDS, MINUTES), ML::Exception);\n\n int mult = granularityMultiplier(MILLISECONDS, MILLISECONDS);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(MINUTES, MILLISECONDS);\n BOOST_CHECK_EQUAL(mult, 60000);\n\n mult = granularityMultiplier(MINUTES, MINUTES);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(WEEKS, MINUTES);\n BOOST_CHECK_EQUAL(mult, 10080);\n\n mult = granularityMultiplier(YEARS, YEARS);\n BOOST_CHECK_EQUAL(mult, 1);\n\n mult = granularityMultiplier(YEARS, MONTHS);\n BOOST_CHECK_EQUAL(mult, 12);\n}\n#endif\n\n#if 1\n\/* Ensure that operators + and += works well for TimePeriod *\/\nBOOST_AUTO_TEST_CASE(time_period_op_plus_equal)\n{\n \/* same unit *\/\n {\n TimePeriod period1(\"2m\");\n TimePeriod period2(\"5m\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, MINUTES);\n BOOST_CHECK_EQUAL(total.number, 7);\n BOOST_CHECK_EQUAL(total.interval, 420);\n }\n\n \/* distinct compatible units *\/\n {\n TimePeriod period1(\"1h\");\n TimePeriod period2(\"2s\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, SECONDS);\n BOOST_CHECK_EQUAL(total.number, 3602);\n BOOST_CHECK_EQUAL(total.interval, 3602);\n\n \/* operator += *\/\n period1 += period2;\n\n BOOST_CHECK_EQUAL(period1.granularity, SECONDS);\n BOOST_CHECK_EQUAL(period1.number, 3602);\n BOOST_CHECK_EQUAL(period1.interval, 3602);\n }\n\n \/* same as above, in reverse order *\/\n {\n TimePeriod period1(\"2s\");\n TimePeriod period2(\"1h\");\n\n TimePeriod total = period1 + period2;\n\n BOOST_CHECK_EQUAL(total.granularity, SECONDS);\n BOOST_CHECK_EQUAL(total.number, 3602);\n BOOST_CHECK_EQUAL(total.interval, 3602);\n\n \/* operator += *\/\n period1 += period2;\n\n BOOST_CHECK_EQUAL(period1.granularity, SECONDS);\n BOOST_CHECK_EQUAL(period1.number, 3602);\n BOOST_CHECK_EQUAL(period1.interval, 3602);\n }\n\n \/* incompatible units *\/\n {\n TimePeriod yearly;\n yearly.granularity = YEARS;\n yearly.number = 1;\n yearly.interval = -1; \/\/ years do not have a fixed set of seconds\n TimePeriod minutely(\"2m\");\n\n JML_TRACE_EXCEPTIONS(false);\n BOOST_CHECK_THROW(yearly + minutely, ML::Exception);\n }\n\n {\n TimePeriod t;\n\n t += \"1s\";\n BOOST_CHECK_EQUAL(t.granularity, SECONDS);\n BOOST_CHECK_EQUAL(t.number, 1);\n BOOST_CHECK_EQUAL(t.interval, 1);\n }\n}\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: tdoc_content.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2004-07-05 10:40:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Kai Sommerfeld ( kso@sun.com )\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_TDOC_CONTENT_HXX\n#define INCLUDED_TDOC_CONTENT_HXX\n\n#ifndef _UCBHELPER_CONTENTHELPER_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_TASK_DOCUMENTPASSWORDREQUEST_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_\n#include \n#endif\n\n#ifndef INCLUDED_TDOC_PROVIDER_HXX\n#include \"tdoc_provider.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace sdbc { class XRow; }\n namespace io { class XInputStream; class XOutputStream; }\n namespace beans { struct PropertyValue; }\n namespace ucb { struct OpenCommandArgument2; struct TransferInfo; }\n} } }\n\nnamespace tdoc_ucp\n{\n\n\/\/=========================================================================\n\n#define TDOC_ROOT_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsRootContent\"\n#define TDOC_DOCUMENT_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsDocumentContent\"\n#define TDOC_FOLDER_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsFolderContent\"\n#define TDOC_STREAM_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsStreamContent\"\n\n\/\/=========================================================================\n\nenum ContentType { STREAM, FOLDER, DOCUMENT, ROOT };\n\nclass ContentProperties\n{\npublic:\n ContentProperties()\n {}\n\n ContentProperties( const ContentType & rType, const rtl::OUString & rTitle )\n : m_eType( rType ),\n m_aContentType( rType == STREAM\n ? rtl::OUString::createFromAscii( TDOC_STREAM_CONTENT_TYPE )\n : rType == FOLDER\n ? rtl::OUString::createFromAscii( TDOC_FOLDER_CONTENT_TYPE )\n : rType == DOCUMENT\n ? rtl::OUString::createFromAscii( TDOC_DOCUMENT_CONTENT_TYPE )\n : rtl::OUString::createFromAscii( TDOC_ROOT_CONTENT_TYPE ) ),\n m_aTitle( rTitle )\n {}\n\n ContentType getType() const { return m_eType; }\n\n \/\/ Properties\n\n const rtl::OUString & getContentType() const { return m_aContentType; }\n\n bool getIsFolder() const { return m_eType > STREAM; }\n bool getIsDocument() const { return !getIsFolder(); }\n\n const rtl::OUString & getTitle() const { return m_aTitle; }\n void setTitle( const rtl::OUString & rTitle ) { m_aTitle = rTitle; }\n\nprivate:\n ContentType m_eType;\n rtl::OUString m_aContentType;\n rtl::OUString m_aTitle;\n};\n\n\/\/=========================================================================\n\nclass Content : public ::ucb::ContentImplHelper,\n public com::sun::star::ucb::XContentCreator\n{\n enum ContentState { TRANSIENT, \/\/ created via createNewContent,\n \/\/ but did not process \"insert\" yet\n PERSISTENT, \/\/ processed \"insert\"\n DEAD \/\/ processed \"delete\" \/ document was closed\n };\n\n ContentProperties m_aProps;\n ContentState m_eState;\n ContentProvider* m_pProvider;\n\nprivate:\n Content( const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const ContentProperties & rProps );\n Content( const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const com::sun::star::ucb::ContentInfo& Info );\n\n virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >\n getProperties( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > & xEnv );\n virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >\n getCommands( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > & xEnv );\n virtual ::rtl::OUString getParentURL();\n\n bool isContentCreator();\n\n static bool hasData( ContentProvider* pProvider, const Uri & rUri );\n bool hasData( const Uri & rUri ) { return hasData( m_pProvider, rUri ); }\n\n static bool loadData( ContentProvider* pProvider,\n const Uri & rUri,\n ContentProperties& rProps );\n bool storeData( const com::sun::star::uno::Reference<\n com::sun::star::io::XInputStream >& xData,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment >& xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n bool renameData( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& xOldId,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& xNewId );\n bool removeData();\n\n bool copyData( const Uri & rSourceUri );\n\n ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >\n makeNewIdentifier( const rtl::OUString& rTitle );\n\n typedef rtl::Reference< Content > ContentRef;\n typedef std::list< ContentRef > ContentRefList;\n void queryChildren( ContentRefList& rChildren );\n\n sal_Bool exchangeIdentity(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& xNewId );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties );\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >\n setPropertyValues(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& rValues,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n com::sun::star::uno::Any\n open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment >& xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void insert( const ::com::sun::star::uno::Reference<\n ::com::sun::star::io::XInputStream >& xData,\n sal_Int32 nNameClashResolve,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void destroy( sal_Bool bDeletePhysical,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties,\n const ContentProperties& rData,\n ContentProvider* pProvider,\n const ::rtl::OUString& rContentId );\n\n\n static bool commitStorage(\n const com::sun::star::uno::Reference<\n com::sun::star::embed::XStorage > & xStorage );\n\n static bool closeOutputStream(\n const com::sun::star::uno::Reference<\n com::sun::star::io::XOutputStream > & xOut );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >\n getInputStream( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > &\n xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >\n getTruncatedOutputStream(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >\n queryChildContent( const rtl::OUString & rRelativeChildUri );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >\n getStream( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\npublic:\n \/\/ Create existing content. Fail, if not already exists.\n static Content* create(\n const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier );\n\n \/\/ Create new content. Fail, if already exists.\n static Content* create(\n const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const com::sun::star::ucb::ContentInfo& Info );\n\n virtual ~Content();\n\n \/\/ XInterface\n XINTERFACE_DECL()\n\n \/\/ XTypeProvider\n XTYPEPROVIDER_DECL()\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL\n getImplementationName()\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XContent\n virtual rtl::OUString SAL_CALL\n getContentType()\n throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier > SAL_CALL\n getIdentifier()\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/ XCommandProcessor\n virtual com::sun::star::uno::Any SAL_CALL\n execute( const com::sun::star::ucb::Command& aCommand,\n sal_Int32 CommandId,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment >& Environment )\n throw( com::sun::star::uno::Exception,\n com::sun::star::ucb::CommandAbortedException,\n com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL\n abort( sal_Int32 CommandId )\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Additional interfaces\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ XContentCreator\n virtual com::sun::star::uno::Sequence<\n com::sun::star::ucb::ContentInfo > SAL_CALL\n queryCreatableContentsInfo()\n throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Reference<\n com::sun::star::ucb::XContent > SAL_CALL\n createNewContent( const com::sun::star::ucb::ContentInfo& Info )\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties,\n ContentProvider* pProvider,\n const ::rtl::OUString& rContentId );\n\n void notifyDocumentClosed();\n void notifyChildRemoved( const rtl::OUString & rRelativeChildUri );\n void notifyChildInserted( const rtl::OUString & rRelativeChildUri );\n\n rtl::Reference< ContentProvider > getContentProvider() const\n { return rtl::Reference< ContentProvider >( m_pProvider ); }\n};\n\n} \/\/ namespace tdoc_ucp\n\n#endif \/* !INCLUDED_TDOC_CONTENT_HXX *\/\nINTEGRATION: CWS scriptingf7 (1.3.2); FILE MERGED 2004\/07\/12 17:43:52 toconnor 1.3.2.3: RESYNC: (1.4-1.5); FILE MERGED 2004\/06\/23 08:47:19 toconnor 1.3.2.2: RESYNC: (1.3-1.4); FILE MERGED 2004\/06\/04 13:52:58 kso 1.3.2.1: #i29649# - Fixed impl and usage of Content::copyData(). Issue number: Submitted by: Reviewed by:\/*************************************************************************\n *\n * $RCSfile: tdoc_content.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2004-07-23 13:51:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Kai Sommerfeld ( kso@sun.com )\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_TDOC_CONTENT_HXX\n#define INCLUDED_TDOC_CONTENT_HXX\n\n#ifndef _UCBHELPER_CONTENTHELPER_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_TASK_DOCUMENTPASSWORDREQUEST_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_\n#include \n#endif\n\n#ifndef INCLUDED_TDOC_PROVIDER_HXX\n#include \"tdoc_provider.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace sdbc { class XRow; }\n namespace io { class XInputStream; class XOutputStream; }\n namespace beans { struct PropertyValue; }\n namespace ucb { struct OpenCommandArgument2; struct TransferInfo; }\n} } }\n\nnamespace tdoc_ucp\n{\n\n\/\/=========================================================================\n\n#define TDOC_ROOT_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsRootContent\"\n#define TDOC_DOCUMENT_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsDocumentContent\"\n#define TDOC_FOLDER_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsFolderContent\"\n#define TDOC_STREAM_CONTENT_SERVICE_NAME \\\n \"com.sun.star.ucb.TransientDocumentsStreamContent\"\n\n\/\/=========================================================================\n\nenum ContentType { STREAM, FOLDER, DOCUMENT, ROOT };\n\nclass ContentProperties\n{\npublic:\n ContentProperties()\n {}\n\n ContentProperties( const ContentType & rType, const rtl::OUString & rTitle )\n : m_eType( rType ),\n m_aContentType( rType == STREAM\n ? rtl::OUString::createFromAscii( TDOC_STREAM_CONTENT_TYPE )\n : rType == FOLDER\n ? rtl::OUString::createFromAscii( TDOC_FOLDER_CONTENT_TYPE )\n : rType == DOCUMENT\n ? rtl::OUString::createFromAscii( TDOC_DOCUMENT_CONTENT_TYPE )\n : rtl::OUString::createFromAscii( TDOC_ROOT_CONTENT_TYPE ) ),\n m_aTitle( rTitle )\n {}\n\n ContentType getType() const { return m_eType; }\n\n \/\/ Properties\n\n const rtl::OUString & getContentType() const { return m_aContentType; }\n\n bool getIsFolder() const { return m_eType > STREAM; }\n bool getIsDocument() const { return !getIsFolder(); }\n\n const rtl::OUString & getTitle() const { return m_aTitle; }\n void setTitle( const rtl::OUString & rTitle ) { m_aTitle = rTitle; }\n\nprivate:\n ContentType m_eType;\n rtl::OUString m_aContentType;\n rtl::OUString m_aTitle;\n};\n\n\/\/=========================================================================\n\nclass Content : public ::ucb::ContentImplHelper,\n public com::sun::star::ucb::XContentCreator\n{\n enum ContentState { TRANSIENT, \/\/ created via createNewContent,\n \/\/ but did not process \"insert\" yet\n PERSISTENT, \/\/ processed \"insert\"\n DEAD \/\/ processed \"delete\" \/ document was closed\n };\n\n ContentProperties m_aProps;\n ContentState m_eState;\n ContentProvider* m_pProvider;\n\nprivate:\n Content( const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const ContentProperties & rProps );\n Content( const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const com::sun::star::ucb::ContentInfo& Info );\n\n virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property >\n getProperties( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > & xEnv );\n virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo >\n getCommands( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment > & xEnv );\n virtual ::rtl::OUString getParentURL();\n\n bool isContentCreator();\n\n static bool hasData( ContentProvider* pProvider, const Uri & rUri );\n bool hasData( const Uri & rUri ) { return hasData( m_pProvider, rUri ); }\n\n static bool loadData( ContentProvider* pProvider,\n const Uri & rUri,\n ContentProperties& rProps );\n bool storeData( const com::sun::star::uno::Reference<\n com::sun::star::io::XInputStream >& xData,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment >& xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n bool renameData( const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& xOldId,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& xNewId );\n bool removeData();\n\n bool copyData( const Uri & rSourceUri, const rtl::OUString & rNewName );\n\n ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >\n makeNewIdentifier( const rtl::OUString& rTitle );\n\n typedef rtl::Reference< Content > ContentRef;\n typedef std::list< ContentRef > ContentRefList;\n void queryChildren( ContentRefList& rChildren );\n\n sal_Bool exchangeIdentity(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& xNewId );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties );\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >\n setPropertyValues(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& rValues,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n com::sun::star::uno::Any\n open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment >& xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void insert( const ::com::sun::star::uno::Reference<\n ::com::sun::star::io::XInputStream >& xData,\n sal_Int32 nNameClashResolve,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void destroy( sal_Bool bDeletePhysical,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw( ::com::sun::star::uno::Exception );\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties,\n const ContentProperties& rData,\n ContentProvider* pProvider,\n const ::rtl::OUString& rContentId );\n\n\n static bool commitStorage(\n const com::sun::star::uno::Reference<\n com::sun::star::embed::XStorage > & xStorage );\n\n static bool closeOutputStream(\n const com::sun::star::uno::Reference<\n com::sun::star::io::XOutputStream > & xOut );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >\n getInputStream( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > &\n xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >\n getTruncatedOutputStream(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >\n queryChildContent( const rtl::OUString & rRelativeChildUri );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::io::XStream >\n getStream( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XCommandEnvironment > & xEnv )\n throw ( ::com::sun::star::ucb::CommandFailedException,\n ::com::sun::star::task::DocumentPasswordRequest );\n\npublic:\n \/\/ Create existing content. Fail, if not already exists.\n static Content* create(\n const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier );\n\n \/\/ Create new content. Fail, if already exists.\n static Content* create(\n const com::sun::star::uno::Reference<\n com::sun::star::lang::XMultiServiceFactory >& rxSMgr,\n ContentProvider* pProvider,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier >& Identifier,\n const com::sun::star::ucb::ContentInfo& Info );\n\n virtual ~Content();\n\n \/\/ XInterface\n XINTERFACE_DECL()\n\n \/\/ XTypeProvider\n XTYPEPROVIDER_DECL()\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL\n getImplementationName()\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL\n getSupportedServiceNames()\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XContent\n virtual rtl::OUString SAL_CALL\n getContentType()\n throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Reference<\n com::sun::star::ucb::XContentIdentifier > SAL_CALL\n getIdentifier()\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/ XCommandProcessor\n virtual com::sun::star::uno::Any SAL_CALL\n execute( const com::sun::star::ucb::Command& aCommand,\n sal_Int32 CommandId,\n const com::sun::star::uno::Reference<\n com::sun::star::ucb::XCommandEnvironment >& Environment )\n throw( com::sun::star::uno::Exception,\n com::sun::star::ucb::CommandAbortedException,\n com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL\n abort( sal_Int32 CommandId )\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Additional interfaces\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ XContentCreator\n virtual com::sun::star::uno::Sequence<\n com::sun::star::ucb::ContentInfo > SAL_CALL\n queryCreatableContentsInfo()\n throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Reference<\n com::sun::star::ucb::XContent > SAL_CALL\n createNewContent( const com::sun::star::ucb::ContentInfo& Info )\n throw( com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow >\n getPropertyValues( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::Property >& rProperties,\n ContentProvider* pProvider,\n const ::rtl::OUString& rContentId );\n\n void notifyDocumentClosed();\n void notifyChildRemoved( const rtl::OUString & rRelativeChildUri );\n void notifyChildInserted( const rtl::OUString & rRelativeChildUri );\n\n rtl::Reference< ContentProvider > getContentProvider() const\n { return rtl::Reference< ContentProvider >( m_pProvider ); }\n};\n\n} \/\/ namespace tdoc_ucp\n\n#endif \/* !INCLUDED_TDOC_CONTENT_HXX *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: textsearch.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: fme $ $Date: 2002-08-02 09:57:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _UNOTOOLS_TEXTSEARCH_HXX\n#define _UNOTOOLS_TEXTSEARCH_HXX\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_\n#include \n#endif\n\n\/\/ Forward-Deklaration\nclass CharClass;\n\nnamespace com {\n namespace sun {\n namespace star {\n namespace util {\n struct SearchResult;\n struct SearchOptions;\n }\n }\n }\n}\n\n\/\/ ............................................................................\nnamespace utl\n{\n\/\/ ............................................................................\n\n\/\/ SS - Klasse fuers Suchen\nclass SearchParam\n{\npublic:\n enum SearchType{ SRCH_NORMAL, SRCH_REGEXP, SRCH_LEVDIST };\n\nprivate:\n String sSrchStr; \/\/ the search string\n String sReplaceStr; \/\/ the replace string\n\n SearchType eSrchType; \/\/ search normal\/regular\/LevDist\n\n int bWordOnly : 1; \/\/ used by normal search\n int bSrchInSel : 1; \/\/ search only in the selection\n int bCaseSense : 1; \/\/\n\n \/\/ values for the \"weight Levenshtein-Distance\"\n int bLEV_Relaxed : 1;\n int nLEV_OtherX;\n int nLEV_ShorterY;\n int nLEV_LongerZ;\n\n \/\/ asian flags - used for the transliteration\n long nTransliterationFlags;\n\npublic:\n SearchParam( const String &rText,\n SearchType eSrchType = SearchParam::SRCH_NORMAL,\n BOOL bCaseSens = TRUE,\n BOOL bWrdOnly = FALSE,\n BOOL bSrchInSel = FALSE );\n SearchParam( const SearchParam& );\n\n const String& GetSrchStr() const { return sSrchStr; }\n const String& GetReplaceStr() const { return sReplaceStr; }\n SearchType GetSrchType() const { return eSrchType; }\n\n int IsCaseSensitive() const { return bCaseSense; }\n int IsSrchInSelection() const { return bSrchInSel; }\n int IsSrchWordOnly() const { return bWordOnly; }\n\n\n void SetSrchStr( const String& rStr ) { sSrchStr = rStr; }\n void SetReplaceStr( const String& rStr ) { sReplaceStr = rStr; }\n void SetSrchType( SearchType eType ) { eSrchType = eType; }\n\n void SetCaseSensitive( int bFlag ) { bCaseSense = bFlag; }\n void SetSrchInSelection( int bFlag ) { bSrchInSel = bFlag; }\n void SetSrchWordOnly( int bFlag ) { bWordOnly = bFlag; }\n\n int IsSrchRelaxed() const { return bLEV_Relaxed; }\n int GetLEVOther() const { return nLEV_OtherX; }\n int GetLEVShorter() const { return nLEV_ShorterY; }\n int GetLEVLonger() const { return nLEV_LongerZ; }\n\n void SetSrchRelaxed( int bFlag ) { bLEV_Relaxed = bFlag; }\n void SetLEVOther( int nValue ) { nLEV_OtherX = nValue; }\n void SetLEVShorter( int nValue ) { nLEV_ShorterY = nValue; }\n void SetLEVLonger( int nValue ) { nLEV_LongerZ = nValue; }\n\n long GetTransliterationFlags() const { return nTransliterationFlags; }\n void SetTransliterationFlags( long nValue ) { nTransliterationFlags = nValue; }\n};\n\n\/\/ Klasse zum Suchen eines Strings in einem String.\n\/\/ Unterstuetzt werden folgende Verfahren:\n\/\/ - normalen Text (Bayer\/Moore)\n\/\/ - regulaere Ausdruecke\n\/\/ - gewichtete Levenshtein Distanz\n\/\/\n\/\/ Es kann Vorwaerts und Rueckwaerts gesucht werden!\n\nclass TextSearch\n{\n com::sun::star::uno::Reference < com::sun::star::util::XTextSearch >\n xTextSearch;\n\n void Init( const SearchParam & rParam,\n const ::com::sun::star::lang::Locale& rLocale );\n\npublic:\n \/\/ rText ist der zusuchende String\n \/\/ this first two CTORs are deprecated!\n TextSearch( const SearchParam & rPara, ULONG nLanguage );\n TextSearch( const SearchParam & rPara, const CharClass& rCClass );\n\n TextSearch( const ::com::sun::star::util::SearchOptions& rPara );\n ~TextSearch();\n\n \/* search in the (selected) text the search string:\n rScrTxt - the text, in in which we search\n pStart - start position for the saerch\n pEnde - end postion for the search\n\n RETURN values == TRUE: something is found\n - pStart start pos of the found text,\n - pStart end pos of the found text,\n - pSrchResult - the search reult with all found\n positons. Is only filled with more positions\n if the regular expression handles goups.\n\n == FALSE: nothing found, pStart,pEnde unchanged.\n\n Definitions: start pos always inclusive, end pos always exclusive!\n The position must always in the right direction!\n search forward: start <= end\n search backward: end <= start\n *\/\n int SearchFrwrd( const String &rStr,\n xub_StrLen* pStart, xub_StrLen* pEnde,\n ::com::sun::star::util::SearchResult* pSrchResult = 0 );\n int SearchBkwrd( const String &rStr,\n xub_StrLen* pStart, xub_StrLen* pEnde,\n ::com::sun::star::util::SearchResult* pSrchResult = 0 );\n\n void SetLocale( const ::com::sun::star::util::SearchOptions& rOpt,\n const ::com::sun::star::lang::Locale& rLocale );\n};\n\n\/\/ ............................................................................\n} \/\/ namespace utl\n\/\/ ............................................................................\n\n#endif\n\nINTEGRATION: CWS visibility03 (1.5.188); FILE MERGED 2005\/02\/28 04:33:54 mnicel 1.5.188.1: Issue number: 40092 Part of visibility work\/*************************************************************************\n *\n * $RCSfile: textsearch.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2005-04-13 12:28:20 $\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 INCLUDED_UNOTOOLSDLLAPI_H\n#include \"unotools\/unotoolsdllapi.h\"\n#endif\n\n#ifndef _UNOTOOLS_TEXTSEARCH_HXX\n#define _UNOTOOLS_TEXTSEARCH_HXX\n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XTEXTSEARCH_HPP_\n#include \n#endif\n\n\/\/ Forward-Deklaration\nclass CharClass;\n\nnamespace com {\n namespace sun {\n namespace star {\n namespace util {\n struct SearchResult;\n struct SearchOptions;\n }\n }\n }\n}\n\n\/\/ ............................................................................\nnamespace utl\n{\n\/\/ ............................................................................\n\n\/\/ SS - Klasse fuers Suchen\nclass UNOTOOLS_DLLPUBLIC SearchParam\n{\npublic:\n enum SearchType{ SRCH_NORMAL, SRCH_REGEXP, SRCH_LEVDIST };\n\nprivate:\n String sSrchStr; \/\/ the search string\n String sReplaceStr; \/\/ the replace string\n\n SearchType eSrchType; \/\/ search normal\/regular\/LevDist\n\n int bWordOnly : 1; \/\/ used by normal search\n int bSrchInSel : 1; \/\/ search only in the selection\n int bCaseSense : 1; \/\/\n\n \/\/ values for the \"weight Levenshtein-Distance\"\n int bLEV_Relaxed : 1;\n int nLEV_OtherX;\n int nLEV_ShorterY;\n int nLEV_LongerZ;\n\n \/\/ asian flags - used for the transliteration\n long nTransliterationFlags;\n\npublic:\n SearchParam( const String &rText,\n SearchType eSrchType = SearchParam::SRCH_NORMAL,\n BOOL bCaseSens = TRUE,\n BOOL bWrdOnly = FALSE,\n BOOL bSrchInSel = FALSE );\n SearchParam( const SearchParam& );\n\n const String& GetSrchStr() const { return sSrchStr; }\n const String& GetReplaceStr() const { return sReplaceStr; }\n SearchType GetSrchType() const { return eSrchType; }\n\n int IsCaseSensitive() const { return bCaseSense; }\n int IsSrchInSelection() const { return bSrchInSel; }\n int IsSrchWordOnly() const { return bWordOnly; }\n\n\n void SetSrchStr( const String& rStr ) { sSrchStr = rStr; }\n void SetReplaceStr( const String& rStr ) { sReplaceStr = rStr; }\n void SetSrchType( SearchType eType ) { eSrchType = eType; }\n\n void SetCaseSensitive( int bFlag ) { bCaseSense = bFlag; }\n void SetSrchInSelection( int bFlag ) { bSrchInSel = bFlag; }\n void SetSrchWordOnly( int bFlag ) { bWordOnly = bFlag; }\n\n int IsSrchRelaxed() const { return bLEV_Relaxed; }\n int GetLEVOther() const { return nLEV_OtherX; }\n int GetLEVShorter() const { return nLEV_ShorterY; }\n int GetLEVLonger() const { return nLEV_LongerZ; }\n\n void SetSrchRelaxed( int bFlag ) { bLEV_Relaxed = bFlag; }\n void SetLEVOther( int nValue ) { nLEV_OtherX = nValue; }\n void SetLEVShorter( int nValue ) { nLEV_ShorterY = nValue; }\n void SetLEVLonger( int nValue ) { nLEV_LongerZ = nValue; }\n\n long GetTransliterationFlags() const { return nTransliterationFlags; }\n void SetTransliterationFlags( long nValue ) { nTransliterationFlags = nValue; }\n};\n\n\/\/ Klasse zum Suchen eines Strings in einem String.\n\/\/ Unterstuetzt werden folgende Verfahren:\n\/\/ - normalen Text (Bayer\/Moore)\n\/\/ - regulaere Ausdruecke\n\/\/ - gewichtete Levenshtein Distanz\n\/\/\n\/\/ Es kann Vorwaerts und Rueckwaerts gesucht werden!\n\nclass UNOTOOLS_DLLPUBLIC TextSearch\n{\n com::sun::star::uno::Reference < com::sun::star::util::XTextSearch >\n xTextSearch;\n\n void Init( const SearchParam & rParam,\n const ::com::sun::star::lang::Locale& rLocale );\n\npublic:\n \/\/ rText ist der zusuchende String\n \/\/ this first two CTORs are deprecated!\n TextSearch( const SearchParam & rPara, ULONG nLanguage );\n TextSearch( const SearchParam & rPara, const CharClass& rCClass );\n\n TextSearch( const ::com::sun::star::util::SearchOptions& rPara );\n ~TextSearch();\n\n \/* search in the (selected) text the search string:\n rScrTxt - the text, in in which we search\n pStart - start position for the saerch\n pEnde - end postion for the search\n\n RETURN values == TRUE: something is found\n - pStart start pos of the found text,\n - pStart end pos of the found text,\n - pSrchResult - the search reult with all found\n positons. Is only filled with more positions\n if the regular expression handles goups.\n\n == FALSE: nothing found, pStart,pEnde unchanged.\n\n Definitions: start pos always inclusive, end pos always exclusive!\n The position must always in the right direction!\n search forward: start <= end\n search backward: end <= start\n *\/\n int SearchFrwrd( const String &rStr,\n xub_StrLen* pStart, xub_StrLen* pEnde,\n ::com::sun::star::util::SearchResult* pSrchResult = 0 );\n int SearchBkwrd( const String &rStr,\n xub_StrLen* pStart, xub_StrLen* pEnde,\n ::com::sun::star::util::SearchResult* pSrchResult = 0 );\n\n void SetLocale( const ::com::sun::star::util::SearchOptions& rOpt,\n const ::com::sun::star::lang::Locale& rLocale );\n};\n\n\/\/ ............................................................................\n} \/\/ namespace utl\n\/\/ ............................................................................\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2010 Manuel Yguel \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\nusing namespace std;\n\ntemplate\nstruct ei_increment_if_fixed_size\n{\n enum {\n ret = (Size == Dynamic) ? Dynamic : Size+1\n };\n};\n\ntemplate\nvoid realRoots_to_monicPolynomial_test(int deg)\n{\n typedef ei_increment_if_fixed_size<_Deg> Dim;\n typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;\n typedef Matrix<_Scalar,_Deg,1> EvalRootsType;\n\n PolynomialType pols(deg+1);\n EvalRootsType roots = EvalRootsType::Random(deg);\n realRoots_to_monicPolynomial( roots, pols );\n\n EvalRootsType evr( deg );\n for( int i=0; i() );\n if( !evalToZero ){\n cerr << evr.transpose() << endl; }\n VERIFY( evalToZero );\n}\n\ntemplate void realRoots_to_monicPolynomial_scalar()\n{\n CALL_SUBTEST_2( (realRoots_to_monicPolynomial_test<_Scalar,2>(2)) );\n CALL_SUBTEST_3( (realRoots_to_monicPolynomial_test<_Scalar,3>(3)) );\n CALL_SUBTEST_4( (realRoots_to_monicPolynomial_test<_Scalar,4>(4)) );\n CALL_SUBTEST_5( (realRoots_to_monicPolynomial_test<_Scalar,5>(5)) );\n CALL_SUBTEST_6( (realRoots_to_monicPolynomial_test<_Scalar,6>(6)) );\n CALL_SUBTEST_7( (realRoots_to_monicPolynomial_test<_Scalar,7>(7)) );\n CALL_SUBTEST_8( (realRoots_to_monicPolynomial_test<_Scalar,17>(17)) );\n\n int deg = ei_random(18,26);\n CALL_SUBTEST_9( (realRoots_to_monicPolynomial_test<_Scalar,Dynamic>(deg)) );\n}\n\n\n\n\ntemplate\nvoid CauchyBounds(int deg)\n{\n typedef ei_increment_if_fixed_size<_Deg> Dim;\n typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;\n typedef Matrix<_Scalar,_Deg,1> EvalRootsType;\n\n PolynomialType pols(deg+1);\n EvalRootsType roots = EvalRootsType::Random(deg);\n realRoots_to_monicPolynomial( roots, pols );\n _Scalar M = cauchy_max_bound( pols );\n _Scalar m = cauchy_min_bound( pols );\n _Scalar Max = roots.array().abs().maxCoeff();\n _Scalar min = roots.array().abs().minCoeff();\n bool eval = (M >= Max) && (m <= min);\n if( !eval )\n {\n cerr << \"Roots: \" << roots << endl;\n cerr << \"Bounds: (\" << m << \", \" << M << \")\" << endl;\n cerr << \"Min,Max: (\" << min << \", \" << Max << \")\" << endl;\n }\n VERIFY( eval );\n}\n\ntemplate void CauchyBounds_scalar()\n{\n CALL_SUBTEST_2( (CauchyBounds<_Scalar,2>(2)) );\n CALL_SUBTEST_3( (CauchyBounds<_Scalar,3>(3)) );\n CALL_SUBTEST_4( (CauchyBounds<_Scalar,4>(4)) );\n CALL_SUBTEST_5( (CauchyBounds<_Scalar,5>(5)) );\n CALL_SUBTEST_6( (CauchyBounds<_Scalar,6>(6)) );\n CALL_SUBTEST_7( (CauchyBounds<_Scalar,7>(7)) );\n CALL_SUBTEST_8( (CauchyBounds<_Scalar,17>(17)) );\n\n int deg = ei_random(18,26);\n CALL_SUBTEST_9( (CauchyBounds<_Scalar,Dynamic>(deg)) );\n}\n\nvoid test_polynomialutils()\n{\n for(int i = 0; i < g_repeat; i++)\n {\n realRoots_to_monicPolynomial_scalar();\n realRoots_to_monicPolynomial_scalar();\n CauchyBounds_scalar();\n CauchyBounds_scalar();\n }\n}\nFix wrong header and warnings in polynomialutils.cpp\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2010 Manuel Yguel \n\/\/\n\/\/ Eigen 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 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\nusing namespace std;\n\ntemplate\nstruct ei_increment_if_fixed_size\n{\n enum {\n ret = (Size == Dynamic) ? Dynamic : Size+1\n };\n};\n\ntemplate\nvoid realRoots_to_monicPolynomial_test(int deg)\n{\n typedef ei_increment_if_fixed_size<_Deg> Dim;\n typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;\n typedef Matrix<_Scalar,_Deg,1> EvalRootsType;\n\n PolynomialType pols(deg+1);\n EvalRootsType roots = EvalRootsType::Random(deg);\n roots_to_monicPolynomial( roots, pols );\n\n EvalRootsType evr( deg );\n for( int i=0; i() );\n if( !evalToZero ){\n cerr << evr.transpose() << endl; }\n VERIFY( evalToZero );\n}\n\ntemplate void realRoots_to_monicPolynomial_scalar()\n{\n CALL_SUBTEST_2( (realRoots_to_monicPolynomial_test<_Scalar,2>(2)) );\n CALL_SUBTEST_3( (realRoots_to_monicPolynomial_test<_Scalar,3>(3)) );\n CALL_SUBTEST_4( (realRoots_to_monicPolynomial_test<_Scalar,4>(4)) );\n CALL_SUBTEST_5( (realRoots_to_monicPolynomial_test<_Scalar,5>(5)) );\n CALL_SUBTEST_6( (realRoots_to_monicPolynomial_test<_Scalar,6>(6)) );\n CALL_SUBTEST_7( (realRoots_to_monicPolynomial_test<_Scalar,7>(7)) );\n CALL_SUBTEST_8( (realRoots_to_monicPolynomial_test<_Scalar,17>(17)) );\n\n CALL_SUBTEST_9( (realRoots_to_monicPolynomial_test<_Scalar,Dynamic>(\n ei_random(18,26) )) );\n}\n\n\n\n\ntemplate\nvoid CauchyBounds(int deg)\n{\n typedef ei_increment_if_fixed_size<_Deg> Dim;\n typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;\n typedef Matrix<_Scalar,_Deg,1> EvalRootsType;\n\n PolynomialType pols(deg+1);\n EvalRootsType roots = EvalRootsType::Random(deg);\n roots_to_monicPolynomial( roots, pols );\n _Scalar M = cauchy_max_bound( pols );\n _Scalar m = cauchy_min_bound( pols );\n _Scalar Max = roots.array().abs().maxCoeff();\n _Scalar min = roots.array().abs().minCoeff();\n bool eval = (M >= Max) && (m <= min);\n if( !eval )\n {\n cerr << \"Roots: \" << roots << endl;\n cerr << \"Bounds: (\" << m << \", \" << M << \")\" << endl;\n cerr << \"Min,Max: (\" << min << \", \" << Max << \")\" << endl;\n }\n VERIFY( eval );\n}\n\ntemplate void CauchyBounds_scalar()\n{\n CALL_SUBTEST_2( (CauchyBounds<_Scalar,2>(2)) );\n CALL_SUBTEST_3( (CauchyBounds<_Scalar,3>(3)) );\n CALL_SUBTEST_4( (CauchyBounds<_Scalar,4>(4)) );\n CALL_SUBTEST_5( (CauchyBounds<_Scalar,5>(5)) );\n CALL_SUBTEST_6( (CauchyBounds<_Scalar,6>(6)) );\n CALL_SUBTEST_7( (CauchyBounds<_Scalar,7>(7)) );\n CALL_SUBTEST_8( (CauchyBounds<_Scalar,17>(17)) );\n\n CALL_SUBTEST_9( (CauchyBounds<_Scalar,Dynamic>(\n ei_random(18,26) )) );\n}\n\nvoid test_polynomialutils()\n{\n for(int i = 0; i < g_repeat; i++)\n {\n realRoots_to_monicPolynomial_scalar();\n realRoots_to_monicPolynomial_scalar();\n CauchyBounds_scalar();\n CauchyBounds_scalar();\n }\n}\n<|endoftext|>"} {"text":"#include \"LaplaceRand.h\"\r\n\r\nLaplaceRand::LaplaceRand(double location, double scale)\r\n{\r\n setLocation(location);\r\n setScale(scale);\r\n}\r\n\r\nstd::string LaplaceRand::name()\r\n{\r\n return \"Laplace(\" + toStringWithPrecision(getLocation()) + \", \" + toStringWithPrecision(getScale()) + \")\";\r\n}\r\n\r\nvoid LaplaceRand::setLocation(double location)\r\n{\r\n mu = location;\r\n}\r\n\r\nvoid LaplaceRand::setScale(double scale)\r\n{\r\n b = std::max(scale, MIN_POSITIVE);\r\n bInv = 1.0 \/ b;\r\n}\r\n\r\ndouble LaplaceRand::f(double x) const\r\n{\r\n double y = -std::fabs(x - mu);\r\n y *= bInv;\r\n y = std::exp(y);\r\n y *= bInv;\r\n return .5 * y;\r\n}\r\n\r\ndouble LaplaceRand::F(double x) const\r\n{\r\n double y = x - mu;\r\n y *= bInv;\r\n if (x < mu)\r\n return .5 * std::exp(y);\r\n y = -.5 * std::exp(-y);\r\n return y + 1;\r\n}\r\n\r\ndouble LaplaceRand::variate() const\r\n{\r\n return LaplaceRand::variate(mu, b);\r\n}\r\n\r\ndouble LaplaceRand::variate(double location, double scale)\r\n{\r\n double e = scale * ExponentialRand::standardVariate();\r\n return location + (((signed)RandGenerator::variate() > 0) ? e : -e);\r\n}\r\n\r\nstd::complex LaplaceRand::CF(double t) const\r\n{\r\n double bt = b * t;\r\n double denominator = 1 + bt * bt;\r\n return std::complex(std::cos(t) \/ denominator, std::sin(t) \/ denominator);\r\n}\r\n\r\ndouble LaplaceRand::Median() const\r\n{\r\n return mu;\r\n}\r\n\r\ndouble LaplaceRand::Mode() const\r\n{\r\n return mu;\r\n}\r\n\r\ndouble LaplaceRand::Skewness() const\r\n{\r\n return 0.0;\r\n}\r\n\r\ndouble LaplaceRand::ExcessKurtosis() const\r\n{\r\n return 3.0;\r\n}\r\n \r\nbool LaplaceRand::fitToData(const QVector &sample)\r\n{\r\n if (sample.size() == 0)\r\n return false;\r\n\r\n \/\/\/ Calculate median\r\n \/\/\/ we use root-finding algorithm for median search\r\n \/\/\/ but note, that it is better to use median-for-median algorithm\r\n double median = 0.0;\r\n double min = sample[0], max = min;\r\n for (double var : sample) {\r\n min = std::min(var, min);\r\n max = std::max(var, max);\r\n }\r\n\r\n if (!RandMath::findRoot([sample] (double med)\r\n {\r\n \/\/\/ sum of sign(x) - derivative of sum of abs(x)\r\n double x = 0;\r\n for (double var : sample) {\r\n if (var > med)\r\n ++x;\r\n else if (var < med)\r\n --x;\r\n }\r\n return x;\r\n },\r\n min, max, median\r\n ))\r\n return false;\r\n\r\n\r\n \/\/\/ Calculate scale\r\n double deviation = 0.0;\r\n for (double var : sample) {\r\n deviation += std::fabs(var - median);\r\n }\r\n deviation \/= sample.size();\r\n\r\n setLocation(median);\r\n setScale(deviation);\r\n return true;\r\n}\r\n\r\nUpdate LaplaceRand.cpp#include \"LaplaceRand.h\"\r\n\r\nLaplaceRand::LaplaceRand(double location, double scale)\r\n{\r\n setLocation(location);\r\n setScale(scale);\r\n}\r\n\r\nstd::string LaplaceRand::name()\r\n{\r\n return \"Laplace(\" + toStringWithPrecision(getLocation()) + \", \" + toStringWithPrecision(getScale()) + \")\";\r\n}\r\n\r\nvoid LaplaceRand::setLocation(double location)\r\n{\r\n mu = location;\r\n}\r\n\r\nvoid LaplaceRand::setScale(double scale)\r\n{\r\n b = scale;\r\n if (b <= 0)\r\n b = MIN_POSITIVE;\r\n bInv = 1.0 \/ b;\r\n}\r\n\r\ndouble LaplaceRand::f(double x) const\r\n{\r\n double y = -std::fabs(x - mu);\r\n y *= bInv;\r\n y = std::exp(y);\r\n y *= bInv;\r\n return .5 * y;\r\n}\r\n\r\ndouble LaplaceRand::F(double x) const\r\n{\r\n double y = x - mu;\r\n y *= bInv;\r\n if (x < mu)\r\n return .5 * std::exp(y);\r\n y = -.5 * std::exp(-y);\r\n return y + 1;\r\n}\r\n\r\ndouble LaplaceRand::variate() const\r\n{\r\n return LaplaceRand::variate(mu, b);\r\n}\r\n\r\ndouble LaplaceRand::variate(double location, double scale)\r\n{\r\n double e = scale * ExponentialRand::standardVariate();\r\n return location + (((signed)RandGenerator::variate() > 0) ? e : -e);\r\n}\r\n\r\nstd::complex LaplaceRand::CF(double t) const\r\n{\r\n double bt = b * t;\r\n double denominator = 1 + bt * bt;\r\n return std::complex(std::cos(t) \/ denominator, std::sin(t) \/ denominator);\r\n}\r\n\r\ndouble LaplaceRand::Median() const\r\n{\r\n return mu;\r\n}\r\n\r\ndouble LaplaceRand::Mode() const\r\n{\r\n return mu;\r\n}\r\n\r\ndouble LaplaceRand::Skewness() const\r\n{\r\n return 0.0;\r\n}\r\n\r\ndouble LaplaceRand::ExcessKurtosis() const\r\n{\r\n return 3.0;\r\n}\r\n \r\nbool LaplaceRand::fitToData(const QVector &sample)\r\n{\r\n if (sample.size() == 0)\r\n return false;\r\n\r\n \/\/\/ Calculate median\r\n \/\/\/ we use root-finding algorithm for median search\r\n \/\/\/ but note, that it is better to use median-for-median algorithm\r\n double median = 0.0;\r\n double min = sample[0], max = min;\r\n for (double var : sample) {\r\n min = std::min(var, min);\r\n max = std::max(var, max);\r\n }\r\n\r\n if (!RandMath::findRoot([sample] (double med)\r\n {\r\n \/\/\/ sum of sign(x) - derivative of sum of abs(x)\r\n double x = 0;\r\n for (double var : sample) {\r\n if (var > med)\r\n ++x;\r\n else if (var < med)\r\n --x;\r\n }\r\n return x;\r\n },\r\n min, max, median\r\n ))\r\n return false;\r\n\r\n\r\n \/\/\/ Calculate scale\r\n double deviation = 0.0;\r\n for (double var : sample) {\r\n deviation += std::fabs(var - median);\r\n }\r\n deviation \/= sample.size();\r\n\r\n setLocation(median);\r\n setScale(deviation);\r\n return true;\r\n}\r\n\r\n<|endoftext|>"} {"text":"#ifndef VIENNAGRID_CONFIG_GENERIC_CONFIG_HPP\n#define VIENNAGRID_CONFIG_GENERIC_CONFIG_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\n#include \"viennagrid\/topology\/simplex.hpp\"\n\n\/** @file config\/simplex.hpp\n @brief Provides default configuration classes for simplex domains\n*\/\n\nnamespace viennagrid\n{\n namespace result_of\n {\n \/\/\n \/\/ Meta Functions for creating a default config\n \/\/\n \n template\n struct storage_layout_config\n {\n \n typedef typename viennameta::typemap::result_of::insert<\n typename storage_layout_config::type,\n viennameta::static_pair<\n boundary_cell_tag,\n viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::full_handling_tag >\n >\n >::type type;\n };\n \n template\n struct storage_layout_config\n {\n \/\/typedef viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag > type;\n typedef typename viennameta::make_typemap<\n viennagrid::vertex_tag,\n viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag >\n >::type type;\n };\n \n template\n struct storage_layout_config\n {\n \/\/typedef viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag > type;\n typedef viennameta::null_type type;\n };\n \n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::hidden_key_map_tag< viennagrid::storage::element_key_tag > type;\n };\n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::std_deque_tag type;\n };\n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::std_deque_tag type;\n };\n \n \n template\n struct default_element_config\n {\n typedef typename viennameta::make_typemap<\n \n viennagrid::element_id_type_tag,\n int,\n \n viennagrid::element_container_tag,\n viennagrid::storage::hooked_container_tag< \n \/\/viennagrid::storage::std_deque_tag,\n typename default_container_tag::type,\n hook_tag\n >,\n \n viennagrid::element_boundary_storage_layout_tag,\n typename storage_layout_config::type\n \n >::type type;\n };\n \n template\n struct default_config_helper\n {\n typedef typename viennameta::typemap::result_of::insert<\n typename default_config_helper::type,\n viennameta::static_pair<\n boundary_cell_tag,\n typename default_element_config::type\n >\n >::type type;\n };\n \n template\n struct default_config_helper\n {\n typedef typename viennameta::make_typemap<\n viennagrid::vertex_tag,\n typename default_element_config::type\n >::type type;\n };\n \n template\n struct default_config\n {\n typedef typename default_config_helper::type type;\n };\n }\n}\n\n\n#endif\nnew boundary handling tags#ifndef VIENNAGRID_CONFIG_GENERIC_CONFIG_HPP\n#define VIENNAGRID_CONFIG_GENERIC_CONFIG_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\n#include \"viennagrid\/topology\/simplex.hpp\"\n\n\/** @file config\/simplex.hpp\n @brief Provides default configuration classes for simplex domains\n*\/\n\nnamespace viennagrid\n{\n namespace result_of\n {\n \/\/\n \/\/ Meta Functions for creating a default config\n \/\/\n \n template\n struct storage_layout_config\n {\n \n typedef typename viennameta::typemap::result_of::insert<\n typename storage_layout_config::type,\n viennameta::static_pair<\n boundary_cell_tag,\n viennagrid::full_handling_tag\n \/\/viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::full_handling_tag >\n >\n >::type type;\n };\n \n template\n struct storage_layout_config\n {\n \/\/typedef viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag > type;\n typedef typename viennameta::make_typemap<\n viennagrid::vertex_tag,\n viennagrid::no_orientation_handling_tag\n \/\/viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag >\n >::type type;\n };\n \n template\n struct storage_layout_config\n {\n \/\/typedef viennameta::static_pair< viennagrid::full_handling_tag, viennagrid::no_handling_tag > type;\n typedef viennameta::null_type type;\n };\n \n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::hidden_key_map_tag< viennagrid::storage::element_key_tag > type;\n };\n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::std_deque_tag type;\n };\n \n template\n struct default_container_tag\n {\n typedef viennagrid::storage::std_deque_tag type;\n };\n \n \n template\n struct default_element_config\n {\n typedef typename viennameta::make_typemap<\n \n viennagrid::element_id_type_tag,\n int,\n \n viennagrid::element_container_tag,\n viennagrid::storage::hooked_container_tag< \n \/\/viennagrid::storage::std_deque_tag,\n typename default_container_tag::type,\n hook_tag\n >,\n \n viennagrid::element_boundary_storage_layout_tag,\n typename storage_layout_config::type\n \n >::type type;\n };\n \n template\n struct default_config_helper\n {\n typedef typename viennameta::typemap::result_of::insert<\n typename default_config_helper::type,\n viennameta::static_pair<\n boundary_cell_tag,\n typename default_element_config::type\n >\n >::type type;\n };\n \n template\n struct default_config_helper\n {\n typedef typename viennameta::make_typemap<\n viennagrid::vertex_tag,\n typename default_element_config::type\n >::type type;\n };\n \n template\n struct default_config\n {\n typedef typename default_config_helper::type type;\n };\n }\n}\n\n\n#endif\n<|endoftext|>"} {"text":"\/\/===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Top-level implementation for the PowerPC target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"PowerPC.h\"\n#include \"PowerPCTargetMachine.h\"\n#include \"PowerPCFrameInfo.h\"\n#include \"PPC32TargetMachine.h\"\n#include \"PPC32JITInfo.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \nusing namespace llvm;\n\nnamespace {\n const char *PPC32ID = \"PowerPC\/32bit\";\n\n static cl::opt DisablePPCDAGDAG(\"disable-ppc-dag-isel\", cl::Hidden,\n cl::desc(\"Disable DAG-to-DAG isel for PPC\"));\n \n \/\/ Register the targets\n RegisterTarget\n X(\"ppc32\", \" PowerPC 32-bit\");\n}\n\nPowerPCTargetMachine::PowerPCTargetMachine(const std::string &name,\n IntrinsicLowering *IL,\n const Module &M,\n const std::string &FS,\n const TargetData &TD,\n const PowerPCFrameInfo &TFI)\n: TargetMachine(name, IL, TD), FrameInfo(TFI), Subtarget(M, FS) {\n if (TargetDefault == PPCTarget) {\n if (Subtarget.isAIX()) PPCTarget = TargetAIX;\n if (Subtarget.isDarwin()) PPCTarget = TargetDarwin;\n }\n}\n\nunsigned PPC32TargetMachine::getJITMatchQuality() {\n#if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)\n return 10;\n#else\n return 0;\n#endif\n}\n\n\/\/\/ addPassesToEmitFile - Add passes to the specified pass manager to implement\n\/\/\/ a static compiler for this target.\n\/\/\/\nbool PowerPCTargetMachine::addPassesToEmitFile(PassManager &PM,\n std::ostream &Out,\n CodeGenFileType FileType) {\n if (FileType != TargetMachine::AssemblyFile) return true;\n\n \/\/ Run loop strength reduction before anything else.\n PM.add(createLoopStrengthReducePass());\n PM.add(createCFGSimplificationPass());\n\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n\n \/\/ FIXME: Implement the switch instruction in the instruction selector!\n PM.add(createLowerSwitchPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n \/\/ Install an instruction selector.\n if (!DisablePPCDAGDAG)\n PM.add(createPPC32ISelDag(*this));\n else\n PM.add(createPPC32ISelPattern(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n PM.add(createRegisterAllocator());\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n PM.add(createPrologEpilogCodeInserter());\n\n \/\/ Must run branch selection immediately preceding the asm printer\n PM.add(createPPCBranchSelectionPass());\n\n \/\/ Decide which asm printer to use. If the user has not specified one on\n \/\/ the command line, choose whichever one matches the default (current host).\n switch (PPCTarget) {\n case TargetAIX:\n PM.add(createAIXAsmPrinter(Out, *this));\n break;\n case TargetDefault:\n case TargetDarwin:\n PM.add(createDarwinAsmPrinter(Out, *this));\n break;\n }\n\n PM.add(createMachineCodeDeleter());\n return false;\n}\n\nvoid PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n \/\/ The JIT does not support or need PIC.\n PICEnabled = false;\n\n \/\/ Run loop strength reduction before anything else.\n PM.add(createLoopStrengthReducePass());\n PM.add(createCFGSimplificationPass());\n\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n\n \/\/ FIXME: Implement the switch instruction in the instruction selector!\n PM.add(createLowerSwitchPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n \/\/ Install an instruction selector.\n PM.add(createPPC32ISelPattern(TM));\n\n PM.add(createRegisterAllocator());\n PM.add(createPrologEpilogCodeInserter());\n\n \/\/ Must run branch selection immediately preceding the asm printer\n PM.add(createPPCBranchSelectionPass());\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n}\n\n\/\/\/ PowerPCTargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nPPC32TargetMachine::PPC32TargetMachine(const Module &M, IntrinsicLowering *IL,\n const std::string &FS)\n : PowerPCTargetMachine(PPC32ID, IL, M, FS,\n TargetData(PPC32ID,false,4,4,4,4,4,4,2,1,1),\n PowerPCFrameInfo(*this, false)), JITInfo(*this) {}\n\nunsigned PPC32TargetMachine::getModuleMatchQuality(const Module &M) {\n \/\/ We strongly match \"powerpc-*\".\n std::string TT = M.getTargetTriple();\n if (TT.size() >= 8 && std::string(TT.begin(), TT.begin()+8) == \"powerpc-\")\n return 20;\n\n if (M.getEndianness() == Module::BigEndian &&\n M.getPointerSize() == Module::Pointer32)\n return 10; \/\/ Weak match\n else if (M.getEndianness() != Module::AnyEndianness ||\n M.getPointerSize() != Module::AnyPointerSize)\n return 0; \/\/ Match for some other target\n\n return getJITMatchQuality()\/2;\n}\nMove the post-lsr simplify cfg pass after lowereh, so it can clean up after eh lowering as well.\/\/===-- PowerPCTargetMachine.cpp - Define TargetMachine for PowerPC -------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Top-level implementation for the PowerPC target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"PowerPC.h\"\n#include \"PowerPCTargetMachine.h\"\n#include \"PowerPCFrameInfo.h\"\n#include \"PPC32TargetMachine.h\"\n#include \"PPC32JITInfo.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/CodeGen\/IntrinsicLowering.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \nusing namespace llvm;\n\nnamespace {\n const char *PPC32ID = \"PowerPC\/32bit\";\n\n static cl::opt DisablePPCDAGDAG(\"disable-ppc-dag-isel\", cl::Hidden,\n cl::desc(\"Disable DAG-to-DAG isel for PPC\"));\n \n \/\/ Register the targets\n RegisterTarget\n X(\"ppc32\", \" PowerPC 32-bit\");\n}\n\nPowerPCTargetMachine::PowerPCTargetMachine(const std::string &name,\n IntrinsicLowering *IL,\n const Module &M,\n const std::string &FS,\n const TargetData &TD,\n const PowerPCFrameInfo &TFI)\n: TargetMachine(name, IL, TD), FrameInfo(TFI), Subtarget(M, FS) {\n if (TargetDefault == PPCTarget) {\n if (Subtarget.isAIX()) PPCTarget = TargetAIX;\n if (Subtarget.isDarwin()) PPCTarget = TargetDarwin;\n }\n}\n\nunsigned PPC32TargetMachine::getJITMatchQuality() {\n#if defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)\n return 10;\n#else\n return 0;\n#endif\n}\n\n\/\/\/ addPassesToEmitFile - Add passes to the specified pass manager to implement\n\/\/\/ a static compiler for this target.\n\/\/\/\nbool PowerPCTargetMachine::addPassesToEmitFile(PassManager &PM,\n std::ostream &Out,\n CodeGenFileType FileType) {\n if (FileType != TargetMachine::AssemblyFile) return true;\n\n \/\/ Run loop strength reduction before anything else.\n PM.add(createLoopStrengthReducePass());\n\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n \n \/\/ Clean up after other passes, e.g. merging critical edges.\n PM.add(createCFGSimplificationPass());\n\n \/\/ FIXME: Implement the switch instruction in the instruction selector!\n PM.add(createLowerSwitchPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n \/\/ Install an instruction selector.\n if (!DisablePPCDAGDAG)\n PM.add(createPPC32ISelDag(*this));\n else\n PM.add(createPPC32ISelPattern(*this));\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n PM.add(createRegisterAllocator());\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n\n PM.add(createPrologEpilogCodeInserter());\n\n \/\/ Must run branch selection immediately preceding the asm printer\n PM.add(createPPCBranchSelectionPass());\n\n \/\/ Decide which asm printer to use. If the user has not specified one on\n \/\/ the command line, choose whichever one matches the default (current host).\n switch (PPCTarget) {\n case TargetAIX:\n PM.add(createAIXAsmPrinter(Out, *this));\n break;\n case TargetDefault:\n case TargetDarwin:\n PM.add(createDarwinAsmPrinter(Out, *this));\n break;\n }\n\n PM.add(createMachineCodeDeleter());\n return false;\n}\n\nvoid PowerPCJITInfo::addPassesToJITCompile(FunctionPassManager &PM) {\n \/\/ The JIT does not support or need PIC.\n PICEnabled = false;\n\n \/\/ Run loop strength reduction before anything else.\n PM.add(createLoopStrengthReducePass());\n\n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass());\n\n \/\/ Clean up after other passes, e.g. merging critical edges.\n PM.add(createCFGSimplificationPass());\n\n \/\/ FIXME: Implement the switch instruction in the instruction selector!\n PM.add(createLowerSwitchPass());\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n \/\/ Install an instruction selector.\n PM.add(createPPC32ISelPattern(TM));\n\n PM.add(createRegisterAllocator());\n PM.add(createPrologEpilogCodeInserter());\n\n \/\/ Must run branch selection immediately preceding the asm printer\n PM.add(createPPCBranchSelectionPass());\n\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(&std::cerr));\n}\n\n\/\/\/ PowerPCTargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nPPC32TargetMachine::PPC32TargetMachine(const Module &M, IntrinsicLowering *IL,\n const std::string &FS)\n : PowerPCTargetMachine(PPC32ID, IL, M, FS,\n TargetData(PPC32ID,false,4,4,4,4,4,4,2,1,1),\n PowerPCFrameInfo(*this, false)), JITInfo(*this) {}\n\nunsigned PPC32TargetMachine::getModuleMatchQuality(const Module &M) {\n \/\/ We strongly match \"powerpc-*\".\n std::string TT = M.getTargetTriple();\n if (TT.size() >= 8 && std::string(TT.begin(), TT.begin()+8) == \"powerpc-\")\n return 20;\n\n if (M.getEndianness() == Module::BigEndian &&\n M.getPointerSize() == Module::Pointer32)\n return 10; \/\/ Weak match\n else if (M.getEndianness() != Module::AnyEndianness ||\n M.getPointerSize() != Module::AnyPointerSize)\n return 0; \/\/ Match for some other target\n\n return getJITMatchQuality()\/2;\n}\n<|endoftext|>"} {"text":"\/\/===-- XCoreTargetMachine.cpp - Define TargetMachine for XCore -----------===\/\/\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\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"XCoreTargetAsmInfo.h\"\n#include \"XCoreTargetMachine.h\"\n#include \"XCore.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\nusing namespace llvm;\n\nnamespace {\n \/\/ Register the target.\n RegisterTarget X(\"xcore\", \" XCore\");\n}\n\nconst TargetAsmInfo *XCoreTargetMachine::createTargetAsmInfo() const {\n return new XCoreTargetAsmInfo(*this);\n}\n\n\/\/\/ XCoreTargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nXCoreTargetMachine::XCoreTargetMachine(const Module &M, const std::string &FS)\n : Subtarget(*this, M, FS),\n DataLayout(\"e-p:32:32:32-a0:0:32-f32:32:32-f64:32:32-i1:8:32-i8:8:32-\"\n \"i16:16:32-i32:32:32-i64:32:32\"),\n InstrInfo(),\n FrameInfo(*this),\n TLInfo(*this) {\n}\n\nunsigned XCoreTargetMachine::getModuleMatchQuality(const Module &M) {\n std::string TT = M.getTargetTriple();\n if (TT.size() >= 6 && std::string(TT.begin(), TT.begin()+6) == \"xcore-\")\n return 20;\n \n \/\/ Otherwise we don't match.\n return 0;\n}\n\nbool XCoreTargetMachine::addInstSelector(PassManagerBase &PM, bool Fast) {\n PM.add(createXCoreISelDag(*this));\n return false;\n}\n\nbool XCoreTargetMachine::addAssemblyEmitter(PassManagerBase &PM, bool Fast, \n raw_ostream &Out) {\n \/\/ Output assembly language.\n PM.add(createXCoreCodePrinterPass(Out, *this));\n return false;\n}\n[XCore] Remove whitespace in the description used when registering XCoreTargetMachine.\/\/===-- XCoreTargetMachine.cpp - Define TargetMachine for XCore -----------===\/\/\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\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"XCoreTargetAsmInfo.h\"\n#include \"XCoreTargetMachine.h\"\n#include \"XCore.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\nusing namespace llvm;\n\nnamespace {\n \/\/ Register the target.\n RegisterTarget X(\"xcore\", \"XCore\");\n}\n\nconst TargetAsmInfo *XCoreTargetMachine::createTargetAsmInfo() const {\n return new XCoreTargetAsmInfo(*this);\n}\n\n\/\/\/ XCoreTargetMachine ctor - Create an ILP32 architecture model\n\/\/\/\nXCoreTargetMachine::XCoreTargetMachine(const Module &M, const std::string &FS)\n : Subtarget(*this, M, FS),\n DataLayout(\"e-p:32:32:32-a0:0:32-f32:32:32-f64:32:32-i1:8:32-i8:8:32-\"\n \"i16:16:32-i32:32:32-i64:32:32\"),\n InstrInfo(),\n FrameInfo(*this),\n TLInfo(*this) {\n}\n\nunsigned XCoreTargetMachine::getModuleMatchQuality(const Module &M) {\n std::string TT = M.getTargetTriple();\n if (TT.size() >= 6 && std::string(TT.begin(), TT.begin()+6) == \"xcore-\")\n return 20;\n \n \/\/ Otherwise we don't match.\n return 0;\n}\n\nbool XCoreTargetMachine::addInstSelector(PassManagerBase &PM, bool Fast) {\n PM.add(createXCoreISelDag(*this));\n return false;\n}\n\nbool XCoreTargetMachine::addAssemblyEmitter(PassManagerBase &PM, bool Fast, \n raw_ostream &Out) {\n \/\/ Output assembly language.\n PM.add(createXCoreCodePrinterPass(Out, *this));\n return false;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Fuchsia 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 \"application_runner.h\"\n\n#include \n\n#include \n#include \n\n#include \"flutter\/lib\/ui\/text\/font_collection.h\"\n#include \"fuchsia_font_manager.h\"\n#include \"lib\/icu_data\/cpp\/icu_data.h\"\n#include \"third_party\/skia\/include\/core\/SkGraphics.h\"\n\nnamespace flutter {\n\nstatic void SetProcessName(const std::string& process_name) {\n zx::process::self().set_property(ZX_PROP_NAME, process_name.c_str(),\n process_name.size());\n}\n\nstatic void SetThreadName(const std::string& thread_name) {\n zx::thread::self().set_property(ZX_PROP_NAME, thread_name.c_str(),\n thread_name.size());\n}\n\nstatic void SetProcessName(const std::string& label, size_t app_count) {\n \/\/ Format: \"flutter.+\"\n \/\/ \"flutter\" in case of error.\n\n const std::string prefix = \"flutter.\";\n const std::string suffix =\n app_count == 0 ? \"\" : \"+\" + std::to_string(app_count);\n\n if ((prefix.size() + suffix.size()) > ZX_MAX_NAME_LEN) {\n SetProcessName(\"flutter\");\n return;\n }\n\n auto truncated_label =\n label.substr(0, ZX_MAX_NAME_LEN - 1 - (prefix.size() + suffix.size()));\n\n SetProcessName(prefix + truncated_label + suffix);\n}\n\nApplicationRunner::ApplicationRunner(fxl::Closure on_termination_callback)\n : on_termination_callback_(std::move(on_termination_callback)),\n host_context_(component::ApplicationContext::CreateFromStartupInfo()) {\n SkGraphics::Init();\n\n SetupICU();\n\n SetupGlobalFonts();\n\n SetProcessName(\"application_runner\", 0);\n\n SetThreadName(\"io.flutter.application_runner\");\n\n host_context_->outgoing_services()->AddService(\n std::bind(&ApplicationRunner::RegisterApplication, this,\n std::placeholders::_1));\n\n active_applications_bindings_.set_empty_set_handler(\n [this]() { FireTerminationCallbackIfNecessary(); });\n}\n\nApplicationRunner::~ApplicationRunner() {\n host_context_->outgoing_services()\n ->RemoveService();\n}\n\nvoid ApplicationRunner::RegisterApplication(\n fidl::InterfaceRequest request) {\n active_applications_bindings_.AddBinding(this, std::move(request));\n}\n\nvoid ApplicationRunner::StartApplication(\n component::ApplicationPackage package,\n component::ApplicationStartupInfo startup_info,\n fidl::InterfaceRequest controller) {\n auto thread_application_pair =\n Application::Create(*this, \/\/ delegate\n std::move(package), \/\/ application pacakge\n std::move(startup_info), \/\/ startup info\n std::move(controller) \/\/ controller request\n );\n\n \/\/ Update the process label so that \"ps\" will will list the last appication\n \/\/ started by the runner plus the count of applications hosted by this runner.\n SetProcessName(thread_application_pair.second->GetDebugLabel(),\n active_applications_.size());\n\n active_applications_[thread_application_pair.second.get()] =\n std::move(thread_application_pair);\n}\n\nvoid ApplicationRunner::OnApplicationTerminate(const Application* application) {\n active_applications_.erase(application);\n FireTerminationCallbackIfNecessary();\n}\n\nvoid ApplicationRunner::SetupICU() {\n if (!icu_data::Initialize(host_context_.get())) {\n FXL_LOG(ERROR) << \"Could not initialize ICU data.\";\n }\n}\n\nvoid ApplicationRunner::SetupGlobalFonts() {\n \/\/ Fuchsia does not have per application (shell) fonts. Instead, all fonts\n \/\/ must be obtained from the font provider.\n auto process_font_collection =\n blink::FontCollection::ForProcess().GetFontCollection();\n\n \/\/ Connect to the system font provider.\n fonts::FontProviderSyncPtr sync_font_provider;\n host_context_->ConnectToEnvironmentService(sync_font_provider.NewRequest());\n\n \/\/ Set the default font manager.\n process_font_collection->SetDefaultFontManager(\n sk_make_sp(std::move(sync_font_provider)));\n}\n\nvoid ApplicationRunner::FireTerminationCallbackIfNecessary() {\n \/\/ We have no reason to exist if:\n \/\/ 1: No previously launched applications are running.\n \/\/ 2: No bindings exist that may require launching more applications.\n if (on_termination_callback_ && active_applications_.size() == 0 &&\n active_applications_bindings_.size() == 0) {\n on_termination_callback_();\n }\n}\n\n} \/\/ namespace flutter\nMake thread names more descriptive. (#5196)\/\/ Copyright 2018 The Fuchsia 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 \"application_runner.h\"\n\n#include \n\n#include \n#include \n\n#include \"flutter\/lib\/ui\/text\/font_collection.h\"\n#include \"fuchsia_font_manager.h\"\n#include \"lib\/icu_data\/cpp\/icu_data.h\"\n#include \"third_party\/flutter\/runtime\/dart_vm.h\"\n#include \"third_party\/skia\/include\/core\/SkGraphics.h\"\n\nnamespace flutter {\n\nstatic void SetProcessName() {\n std::stringstream stream;\n stream << \"io.flutter.runner.\";\n if (blink::DartVM::IsRunningPrecompiledCode()) {\n stream << \"aot\";\n } else {\n stream << \"jit\";\n }\n const auto name = stream.str();\n zx::process::self().set_property(ZX_PROP_NAME, name.c_str(), name.size());\n}\n\nstatic void SetThreadName(const std::string& thread_name) {\n zx::thread::self().set_property(ZX_PROP_NAME, thread_name.c_str(),\n thread_name.size());\n}\n\nApplicationRunner::ApplicationRunner(fxl::Closure on_termination_callback)\n : on_termination_callback_(std::move(on_termination_callback)),\n host_context_(component::ApplicationContext::CreateFromStartupInfo()) {\n SkGraphics::Init();\n\n SetupICU();\n\n SetupGlobalFonts();\n\n SetProcessName();\n\n SetThreadName(\"io.flutter.runner.main\");\n\n host_context_->outgoing_services()->AddService(\n std::bind(&ApplicationRunner::RegisterApplication, this,\n std::placeholders::_1));\n\n active_applications_bindings_.set_empty_set_handler(\n [this]() { FireTerminationCallbackIfNecessary(); });\n}\n\nApplicationRunner::~ApplicationRunner() {\n host_context_->outgoing_services()\n ->RemoveService();\n}\n\nvoid ApplicationRunner::RegisterApplication(\n fidl::InterfaceRequest request) {\n active_applications_bindings_.AddBinding(this, std::move(request));\n}\n\nvoid ApplicationRunner::StartApplication(\n component::ApplicationPackage package,\n component::ApplicationStartupInfo startup_info,\n fidl::InterfaceRequest controller) {\n auto thread_application_pair =\n Application::Create(*this, \/\/ delegate\n std::move(package), \/\/ application pacakge\n std::move(startup_info), \/\/ startup info\n std::move(controller) \/\/ controller request\n );\n\n active_applications_[thread_application_pair.second.get()] =\n std::move(thread_application_pair);\n}\n\nvoid ApplicationRunner::OnApplicationTerminate(const Application* application) {\n active_applications_.erase(application);\n FireTerminationCallbackIfNecessary();\n}\n\nvoid ApplicationRunner::SetupICU() {\n if (!icu_data::Initialize(host_context_.get())) {\n FXL_LOG(ERROR) << \"Could not initialize ICU data.\";\n }\n}\n\nvoid ApplicationRunner::SetupGlobalFonts() {\n \/\/ Fuchsia does not have per application (shell) fonts. Instead, all fonts\n \/\/ must be obtained from the font provider.\n auto process_font_collection =\n blink::FontCollection::ForProcess().GetFontCollection();\n\n \/\/ Connect to the system font provider.\n fonts::FontProviderSyncPtr sync_font_provider;\n host_context_->ConnectToEnvironmentService(sync_font_provider.NewRequest());\n\n \/\/ Set the default font manager.\n process_font_collection->SetDefaultFontManager(\n sk_make_sp(std::move(sync_font_provider)));\n}\n\nvoid ApplicationRunner::FireTerminationCallbackIfNecessary() {\n \/\/ We have no reason to exist if:\n \/\/ 1: No previously launched applications are running.\n \/\/ 2: No bindings exist that may require launching more applications.\n if (on_termination_callback_ && active_applications_.size() == 0 &&\n active_applications_bindings_.size() == 0) {\n on_termination_callback_();\n }\n}\n\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"#line 2 \"togo\/core\/utility\/tags.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Variation\/placeholder tags.\n@ingroup lib_core_utility\n*\/\n\n#pragma once\n\n#include \n\nnamespace togo {\n\n\/**\n\t@addtogroup lib_core_utility\n\t@{\n*\/\n\n\/** @name Variation\/placeholder tags *\/ \/\/\/ @{\n\n\/\/\/ Null value tag.\nenum class null_tag {};\n\n\/\/\/ Null reference tag.\nenum class null_ref_tag {};\n\n\/\/\/ NUL-terminated string tag.\nenum class cstr_tag {};\n\n\/\/\/ Boolean value tag.\nenum class bool_tag {};\n\n\/\/\/ @}\n\n\/** @} *\/ \/\/ end of doc-group lib_core_utility\n\n} \/\/ namespace togo\nlib\/core\/utility\/tags: added no_init_tag.#line 2 \"togo\/core\/utility\/tags.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Variation\/placeholder tags.\n@ingroup lib_core_utility\n*\/\n\n#pragma once\n\n#include \n\nnamespace togo {\n\n\/**\n\t@addtogroup lib_core_utility\n\t@{\n*\/\n\n\/** @name Variation\/placeholder tags *\/ \/\/\/ @{\n\n\/\/\/ No-initialize constructor tag.\nenum class no_init_tag {};\n\n\/\/\/ Null value tag.\nenum class null_tag {};\n\n\/\/\/ Null reference tag.\nenum class null_ref_tag {};\n\n\/\/\/ NUL-terminated string tag.\nenum class cstr_tag {};\n\n\/\/\/ Boolean value tag.\nenum class bool_tag {};\n\n\/\/\/ @}\n\n\/** @} *\/ \/\/ end of doc-group lib_core_utility\n\n} \/\/ namespace togo\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \"darkfeed\/types\/symbol.hpp\"\n#include \"crc32c.h\"\n\n\nnamespace darkfeed\n{\n\n\/\/\/ @brief Computes a hash of a symbol using the XXHash32 algorithm with offset\n\/\/\/ @param s the symbol\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_sym_32(const Symbol &s)\n{\n \/\/get hash of root symbol\n std::uint32_t base_hash = XXH32(s.root, std::strlen(s.root), 0);\n \/\/stride by type and series\n base_hash += (std::uint32_t) IssueType::MAX * s.series + (std::uint32_t) s.issue_type;\n return base_hash;\n}\n\n\n\/\/\/ @brief Struct used to check for equality between symbols in a dense hash table\nstruct eqsym {\n bool operator()(const Symbol &a, const Symbol &b) const\n {\n return a == b;\n }\n};\n\n\n\/\/\/ @brief Struct used to check for equality between exchanges\nstruct eqexg {\n bool operator()(const Exchange &a, const Exchange &b) const\n {\n return a.mic == b.mic;\n }\n};\n\n\n\/\/\/ @brief Computes the hash of a std::string using the XXHash32 algorithm\n\/\/\/ @param s the string\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_str_32(const std::string &s)\n{\n const char *str = s.c_str();\n return XXH32(str, s.length(), 0);\n}\n\n\/\/\/ @brief Computes the ahsh of a C-string using the XXHash32 algorithm\n\/\/\/ @param s the string\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_c_str_32(const char *s)\n{ return XXH32(s, std::strlen(s), 0); }\n\n\n\/\/\/ @brief Struct used to check for equality between std::string objects in a dense hash table\nstruct eqstr {\n bool operator()(const std::string &a, const std::string &b) const\n {\n return b == a;\n }\n};\n\n\n\/\/\/ @brief Struct used to check for equality between C-strings in a dense hash table\nstruct eq_c_str {\n bool operator()(const char *a, const char *b) const\n { return !std::strcmp(a, b); }\n};\n\n\n\/\/\/ @brief Struct used to hash symbols for a dense hash table\nstruct XXSymHasher32 {\n inline std::uint32_t operator()(const Symbol &s) const\n { return xxhash_sym_32(s); }\n};\n\n\n\/\/\/ @brief Struct used to hash exchanges for reporting\/listing exchange keyed hash tables\nstruct XXExchangeHasher32 {\n inline std::uint32_t operator()(const Exchange &e) const\n {\n return static_cast(e.mic);\n }\n};\n\n\n\/\/\/ @brief Struct used to hash std::string objects for a dense hash table\nstruct XXStrHasher32 {\n inline std::uint32_t operator()(const std::string &s) const\n { return xxhash_str_32(s); }\n};\n\n\n\/\/\/ @brief Struct used to hash C-strings for a dense hash table\nstruct XXCStrHasher32 {\n inline std::uint32_t operator()(const char *s) const\n { return xxhash_c_str_32(s); }\n};\n\n\n\/\/\/ @brief Computes the CRC32C checksum using slicing-by-8 method or SSE 4.2 CRC32C instruction if HAS_SSE_4_2 defined at compile time\n\/\/\/ @param crc Carryover checksum\n\/\/\/ @param s The buffer to hash\n\/\/\/ @param len The length of the buffer in bytes\n\/\/\/ @return The checksum as an unsigned 32 bit integer\nstd::uint32_t crc32c(std::uint32_t crc, const void *buf, std::size_t len);\n\n\n\/\/\/ @brief Struct used to hash strings using CRC32C\nstruct CRC32CStrHasher {\n inline std::uint32_t operator()(const std::string &s)\n {\n return CRC32C_FINISH(crc32c(CRC32C_INIT, s.c_str(), s.size()));\n }\n};\n\n\n\/\/\/ @brief Struct used to hash C-strings using CRC32C\nstruct CRC32CCStrHasher {\n inline std::uint32_t operator()(const char *s)\n {\n std::size_t len = std::strlen(s);\n return CRC32C_FINISH(crc32c(CRC32C_INIT, s, len));\n }\n};\n}\n\n\n[cpp] Add test for hardware accelerated (SSE4.3) CRC32C symbol hasher#pragma once\n#include \n#include \n#include \n#include \"darkfeed\/types\/symbol.hpp\"\n#include \"crc32c.h\"\n\n\nnamespace darkfeed\n{\n\n\/\/\/ @brief Computes a hash of a symbol using the XXHash32 algorithm with offset\n\/\/\/ @param s the symbol\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_sym_32(const Symbol &s)\n{\n \/\/get hash of root symbol\n std::uint32_t base_hash = XXH32(s.root, std::strlen(s.root), 0);\n \/\/stride by type and series\n base_hash += (std::uint32_t) IssueType::MAX * s.series + (std::uint32_t) s.issue_type;\n return base_hash;\n}\n\n\n\/\/\/ @brief Struct used to check for equality between symbols in a dense hash table\nstruct eqsym {\n bool operator()(const Symbol &a, const Symbol &b) const\n {\n return a == b;\n }\n};\n\n\n\/\/\/ @brief Struct used to check for equality between exchanges\nstruct eqexg {\n bool operator()(const Exchange &a, const Exchange &b) const\n {\n return a.mic == b.mic;\n }\n};\n\n\n\/\/\/ @brief Computes the hash of a std::string using the XXHash32 algorithm\n\/\/\/ @param s the string\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_str_32(const std::string &s)\n{\n const char *str = s.c_str();\n return XXH32(str, s.length(), 0);\n}\n\n\/\/\/ @brief Computes the ahsh of a C-string using the XXHash32 algorithm\n\/\/\/ @param s the string\n\/\/\/ @return the hash as a std::uint32_t\ninline std::uint32_t xxhash_c_str_32(const char *s)\n{ return XXH32(s, std::strlen(s), 0); }\n\n\n\/\/\/ @brief Struct used to check for equality between std::string objects in a dense hash table\nstruct eqstr {\n bool operator()(const std::string &a, const std::string &b) const\n {\n return b == a;\n }\n};\n\n\n\/\/\/ @brief Struct used to check for equality between C-strings in a dense hash table\nstruct eq_c_str {\n bool operator()(const char *a, const char *b) const\n { return !std::strcmp(a, b); }\n};\n\n\n\/\/\/ @brief Struct used to hash symbols for a dense hash table\nstruct XXSymHasher32 {\n inline std::uint32_t operator()(const Symbol &s) const\n { return xxhash_sym_32(s); }\n};\n\n\n\/\/\/ @brief Struct used to hash exchanges for reporting\/listing exchange keyed hash tables\nstruct XXExchangeHasher32 {\n inline std::uint32_t operator()(const Exchange &e) const\n {\n return static_cast(e.mic);\n }\n};\n\n\n\/\/\/ @brief Struct used to hash std::string objects for a dense hash table\nstruct XXStrHasher32 {\n inline std::uint32_t operator()(const std::string &s) const\n { return xxhash_str_32(s); }\n};\n\n\n\/\/\/ @brief Struct used to hash C-strings for a dense hash table\nstruct XXCStrHasher32 {\n inline std::uint32_t operator()(const char *s) const\n { return xxhash_c_str_32(s); }\n};\n\n\n\/\/\/ @brief Computes the CRC32C checksum using slicing-by-8 method or SSE 4.2 CRC32C instruction if HAS_SSE_4_2 defined at compile time\n\/\/\/ @param crc Carryover checksum\n\/\/\/ @param s The buffer to hash\n\/\/\/ @param len The length of the buffer in bytes\n\/\/\/ @return The checksum as an unsigned 32 bit integer\nstd::uint32_t crc32c(std::uint32_t crc, const void *buf, std::size_t len);\n\n\/\/\/ @brief Struct used to hash strings using CRC32C\nstruct CRC32CStrHasher {\n inline std::uint32_t operator()(const std::string &s)\n {\n return CRC32C_FINISH(crc32c(CRC32C_INIT, s.c_str(), s.size()));\n }\n};\n\n\/\/\/ @brief Struct used to hash C-strings using CRC32C\nstruct CRC32CCStrHasher {\n inline std::uint32_t operator()(const char *s)\n {\n std::size_t len = std::strlen(s);\n return CRC32C_FINISH(crc32c(CRC32C_INIT, s, len));\n }\n};\n\n\n\/\/\/ @brief Struct used to hash Symbols using CRC32C\nstruct CRC32CSymHasher {\n inline std::uint32_t operator()(const Symbol &s)\n {\n std::size_t len = std::strlen(s.root);\n auto post_root = crc32c(CRC32C_INIT, s.root, len);\n char modifiers[3] = {s.series, (char) s.listing_exg.mic, (char) s.issue_type};\n return CRC32C_FINISH(crc32c(post_root, modifiers, 3));\n }\n};\n\n\n\/\/\/ @brief Struct used as a std::hash wrapper for identity hash\nstruct IdentityHasher {\n inline std::uint32_t operator()(const std::uint64_t x)\n {\n return (std::uint32_t) x;\n }\n};\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: factory.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2006-12-01 17:17: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#ifndef _CPPUHELPER_FACTORY_HXX_\n#define _CPPUHELPER_FACTORY_HXX_\n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n\n#ifndef _UNO_DISPATCHER_H_\n#include \n#endif\n\n#ifndef _RTL_UNLOAD_H_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/##################################################################################################\n\n#define COMPONENT_GETENV \"component_getImplementationEnvironment\"\n#define COMPONENT_GETDESCRIPTION \"component_getDescription\"\n#define COMPONENT_WRITEINFO \"component_writeInfo\"\n#define COMPONENT_GETFACTORY \"component_getFactory\"\n\ntypedef struct _uno_Environment uno_Environment;\n\n\/** Function pointer declaration.\n Function determines the environment of the component implementation, i.e. which compiler\n compiled it. If the environment is NOT session specific (needs no additional context),\n then this function should return the environment type name and leave ppEnv (to 0).\n\n @paramppEnvTypeName environment type name; string must be constant\n @param ppEnv function returns its environment if the environment is session specific,\n i.e. has special context\n*\/\ntypedef void (SAL_CALL * component_getImplementationEnvironmentFunc)(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv );\n\n\/** Function pointer declaration.\n Function retrieves a component description.\n\n @return an XML formatted string containing a short component description\n*\/\ntypedef const sal_Char * (SAL_CALL * component_getDescriptionFunc)(void);\n\n\/** Function pointer declaration.\n Function writes component registry info, at least writing the supported service names.\n\n @param pServiceManager\n a service manager (the type is an XMultiServiceFactory that can be used\n by the environment returned by component_getImplementationEnvironment)\n @param pRegistryKey a registry key\n (the type is XRegistryKey that can be used by the environment\n returned by component_getImplementationEnvironment)\n @return true if everything went fine\n*\/\ntypedef sal_Bool (SAL_CALL * component_writeInfoFunc)(\n void * pServiceManager, void * pRegistryKey );\n\n\/** Function pointer declaration.\n Retrieves a factory to create component instances.\n\n @param pImplName\n desired implementation name\n @param pServiceManager\n a service manager (the type is XMultiServiceFactory that can be used by the environment\n returned by component_getImplementationEnvironment)\n @param pRegistryKey\n a registry key (the type is XRegistryKey that can be used by the environment\n returned by component_getImplementationEnvironment)\n @return acquired component factory\n (the type is lang::XSingleComponentFactory or lang::XSingleServiceFactory to be used by the\n environment returned by component_getImplementationEnvironment)\n*\/\ntypedef void * (SAL_CALL * component_getFactoryFunc)(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey );\n\n\/\/##################################################################################################\n\nnamespace cppu\n{\n\n\/** Function pointer declaration.\n Function creates component instance passing the component context to be used.\n\n @param xContext component context to be used\n @return component instance\n*\/\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(\n SAL_CALL * ComponentFactoryFunc)(\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext )\n SAL_THROW( (::com::sun::star::uno::Exception) );\n\n\/** Creates a single component factory supporting the XSingleComponentFactory interface.\n\n @param fptr function pointer for instanciating the object\n @param rImplementationName implementation name of service\n @param rServiceNames supported services\n @param pModCount for future extension (library unloading concept).\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory >\nSAL_CALL createSingleComponentFactory(\n ComponentFactoryFunc fptr,\n ::rtl::OUString const & rImplementationName,\n ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. The type of the instanciate function used as argument of the create*Fcatory functions.\n\n @see createSingleFactory\n @see createOneInstanceFactory\n @deprecated\n*\/\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(SAL_CALL * ComponentInstantiation)(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager );\n\n\/** Deprecated. Creates a single service factory.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param ComponentInstantiation the function pointer to create an object.\n @param rServiceNames the service supported by the implementation.\n @param pModCount for future extension (library unloading concept).\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createOneInstanceFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateSingleFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rImplementationName,\n ComponentInstantiation pCreateFunction,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a factory wrapping another one.\n This means the methods of the interfaces XServiceProvider, XServiceInfo and\n XSingleServiceFactory are forwarded.\n @attention\n The XComponent interface is not supported!\n\n @param rServiceManager the service manager used by the implementation.\n @param xSingleServiceFactory the wrapped service factory.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory.\n\n @see createSingleFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateFactoryProxy(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > & rFactory )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory which holds the instance created only once.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param ComponentInstantiation the function pointer to create an object.\n @param rServiceNames the service supported by the implementation.\n @param pModCount for future extension (library unloading concept).\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createSingleFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateOneInstanceFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rComponentName,\n ComponentInstantiation pCreateFunction,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory based on a registry.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param rImplementationKey the registry key of the implementation section.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL createSingleRegistryFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rImplementationName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey > & rImplementationKey )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory which holds the instance created only once\n based on a registry.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param rImplementationKey the registry key of the implementation section.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createSingleRegistryFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL createOneInstanceRegistryFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rComponentName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey > & rImplementationKey )\n SAL_THROW( () );\n\n}\n\n#endif\nINTEGRATION: CWS bunoexttm (1.10.4); FILE MERGED 2007\/01\/30 14:16:39 kr 1.10.4.1: joined UTF2 - COMPONENT_GETENVEXT\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: factory.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: kz $ $Date: 2007-05-09 13:24:47 $\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 _CPPUHELPER_FACTORY_HXX_\n#define _CPPUHELPER_FACTORY_HXX_\n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n\n#ifndef _UNO_DISPATCHER_H_\n#include \n#endif\n\n#ifndef _RTL_UNLOAD_H_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/##################################################################################################\n\n#define COMPONENT_GETENV \"component_getImplementationEnvironment\"\n#define COMPONENT_GETENVEXT \"component_getImplementationEnvironmentExt\"\n#define COMPONENT_GETDESCRIPTION \"component_getDescription\"\n#define COMPONENT_WRITEINFO \"component_writeInfo\"\n#define COMPONENT_GETFACTORY \"component_getFactory\"\n\ntypedef struct _uno_Environment uno_Environment;\n\n\/** Function pointer declaration.\n Function determines the environment of the component implementation, i.e. which compiler\n compiled it. If the environment is NOT session specific (needs no additional context),\n then this function should return the environment type name and leave ppEnv (to 0).\n\n @paramppEnvTypeName environment type name; string must be constant\n @param ppEnv function returns its environment if the environment is session specific,\n i.e. has special context\n*\/\ntypedef void (SAL_CALL * component_getImplementationEnvironmentFunc)(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv );\n\n\/** Function pointer declaration.\n Function determines the environment of the component implementation, i.e. the compiler.\n If the environment is NOT session specific (needs no additional context),\n then this function should return the environment type name and leave ppEnv (to 0).\n\n @param ppEnvTypeName environment type name; string must be a constant\n @param ppEnv function returns an environment if the environment is session specific,\n i.e. has special context\n @param pImplName\n*\/\ntypedef void (SAL_CALL * component_getImplementationEnvironmentExtFunc)(\n sal_Char const ** ppEnvTypeName,\n uno_Environment ** ppEnv,\n sal_Char const * pImplName,\n uno_Environment * pTargetEnv\n);\n\n\/** Function pointer declaration.\n Function retrieves a component description.\n\n @return an XML formatted string containing a short component description\n*\/\ntypedef const sal_Char * (SAL_CALL * component_getDescriptionFunc)(void);\n\n\/** Function pointer declaration.\n Function writes component registry info, at least writing the supported service names.\n\n @param pServiceManager\n a service manager (the type is an XMultiServiceFactory that can be used\n by the environment returned by component_getImplementationEnvironment)\n @param pRegistryKey a registry key\n (the type is XRegistryKey that can be used by the environment\n returned by component_getImplementationEnvironment)\n @return true if everything went fine\n*\/\ntypedef sal_Bool (SAL_CALL * component_writeInfoFunc)(\n void * pServiceManager, void * pRegistryKey );\n\n\/** Function pointer declaration.\n Retrieves a factory to create component instances.\n\n @param pImplName\n desired implementation name\n @param pServiceManager\n a service manager (the type is XMultiServiceFactory that can be used by the environment\n returned by component_getImplementationEnvironment)\n @param pRegistryKey\n a registry key (the type is XRegistryKey that can be used by the environment\n returned by component_getImplementationEnvironment)\n @return acquired component factory\n (the type is lang::XSingleComponentFactory or lang::XSingleServiceFactory to be used by the\n environment returned by component_getImplementationEnvironment)\n*\/\ntypedef void * (SAL_CALL * component_getFactoryFunc)(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey );\n\n\/\/##################################################################################################\n\nnamespace cppu\n{\n\n\/** Function pointer declaration.\n Function creates component instance passing the component context to be used.\n\n @param xContext component context to be used\n @return component instance\n*\/\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(\n SAL_CALL * ComponentFactoryFunc)(\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext )\n SAL_THROW( (::com::sun::star::uno::Exception) );\n\n\/** Creates a single component factory supporting the XSingleComponentFactory interface.\n\n @param fptr function pointer for instanciating the object\n @param rImplementationName implementation name of service\n @param rServiceNames supported services\n @param pModCount for future extension (library unloading concept).\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleComponentFactory >\nSAL_CALL createSingleComponentFactory(\n ComponentFactoryFunc fptr,\n ::rtl::OUString const & rImplementationName,\n ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. The type of the instanciate function used as argument of the create*Fcatory functions.\n\n @see createSingleFactory\n @see createOneInstanceFactory\n @deprecated\n*\/\ntypedef ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(SAL_CALL * ComponentInstantiation)(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager );\n\n\/** Deprecated. Creates a single service factory.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param ComponentInstantiation the function pointer to create an object.\n @param rServiceNames the service supported by the implementation.\n @param pModCount for future extension (library unloading concept).\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createOneInstanceFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateSingleFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rImplementationName,\n ComponentInstantiation pCreateFunction,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a factory wrapping another one.\n This means the methods of the interfaces XServiceProvider, XServiceInfo and\n XSingleServiceFactory are forwarded.\n @attention\n The XComponent interface is not supported!\n\n @param rServiceManager the service manager used by the implementation.\n @param xSingleServiceFactory the wrapped service factory.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory.\n\n @see createSingleFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateFactoryProxy(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > & rFactory )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory which holds the instance created only once.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param ComponentInstantiation the function pointer to create an object.\n @param rServiceNames the service supported by the implementation.\n @param pModCount for future extension (library unloading concept).\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createSingleFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL\ncreateOneInstanceFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rComponentName,\n ComponentInstantiation pCreateFunction,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString > & rServiceNames,\n rtl_ModuleCount * pModCount = 0 )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory based on a registry.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param rImplementationKey the registry key of the implementation section.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL createSingleRegistryFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rImplementationName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey > & rImplementationKey )\n SAL_THROW( () );\n\n\/** Deprecated. Creates a single service factory which holds the instance created only once\n based on a registry.\n\n @param rServiceManager the service manager used by the implementation.\n @param rImplementationName the implementation name. An empty string is possible.\n @param rImplementationKey the registry key of the implementation section.\n @return a factory that support the interfaces XServiceProvider, XServiceInfo\n XSingleServiceFactory and XComponent.\n\n @see createSingleRegistryFactory\n @deprecated\n*\/\n::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > SAL_CALL createOneInstanceRegistryFactory(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rServiceManager,\n const ::rtl::OUString & rComponentName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey > & rImplementationKey )\n SAL_THROW( () );\n\n}\n\n#endif\n<|endoftext|>"} {"text":"Properly identify malformed (too short) chunks in mpeg4 files.<|endoftext|>"} {"text":"slots slide on node borders except for ends<|endoftext|>"} {"text":"Fixed clang unused error<|endoftext|>"} {"text":"Run integration filter from state estimator node<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XTempFile.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 09:50:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _XTEMPFILE_HXX\n#define _XTEMPFILE_HXX\n\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\nclass SvStream;\nnamespace utl { class TempFile; }\n\nclass XTempFile : public com::sun::star::lang::XTypeProvider,\n public com::sun::star::io::XInputStream,\n public com::sun::star::io::XOutputStream,\n public com::sun::star::io::XSeekable,\n public com::sun::star::io::XStream,\n public com::sun::star::io::XTruncate,\n public com::sun::star::beans::XPropertySetInfo,\n public com::sun::star::beans::XPropertySet,\n public ::com::sun::star::lang::XServiceInfo,\n public cppu::OWeakObject\n{\nprotected:\n ::utl::TempFile* mpTempFile;\n ::osl::Mutex maMutex;\n SvStream* mpStream;\n sal_Bool mbRemoveFile;\n sal_Bool mbInClosed;\n sal_Bool mbOutClosed;\n\n \/\/ intended to hold the current position in disconnected state\n sal_Int64 mnCachedPos;\n sal_Bool mbHasCachedPos;\n\n void checkError () const;\n void checkConnected ();\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > GetProps();\n\npublic:\n XTempFile ();\n virtual ~XTempFile ();\n\n \/\/ XInterface\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType )\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL acquire( )\n throw ();\n virtual void SAL_CALL release( )\n throw ();\n\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes()\n throw ( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::sal_Int8 > SAL_CALL getImplementationId()\n throw ( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XInputStream\n virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL available( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL closeInput( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n \/\/ XOutputStream\n virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL flush( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL closeOutput( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n \/\/ XSeekable\n virtual void SAL_CALL seek( sal_Int64 location )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int64 SAL_CALL getPosition( )\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int64 SAL_CALL getLength( )\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XStream\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XTruncate\n virtual void SAL_CALL truncate()\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySetInfo\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::beans::Property SAL_CALL getPropertyByName( const ::rtl::OUString& aName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL hasPropertyByName( const ::rtl::OUString& Name ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n static ::rtl::OUString getImplementationName_Static ();\n static ::com::sun::star::uno::Sequence < ::rtl::OUString > getSupportedServiceNames_Static();\n static ::com::sun::star::uno::Reference < com::sun::star::lang::XSingleServiceFactory > createServiceFactory_Static( com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > const & rServiceFactory );\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n};\n#endif\nINTEGRATION: CWS warnings01 (1.8.16); FILE MERGED 2006\/01\/27 12:39:19 sb 1.8.16.2: #i53898# Made code warning-free. 2005\/12\/21 11:32:04 fs 1.8.16.1: #i55991# warning-free code\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: XTempFile.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 14:09:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _XTEMPFILE_HXX\n#define _XTEMPFILE_HXX\n\n#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE8_HXX_\n#include \n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\nclass SvStream;\nnamespace utl { class TempFile; }\n\nclass XTempFile : public ::cppu::WeakImplHelper8< com::sun::star::io::XInputStream\n , ::com::sun::star::io::XOutputStream\n , ::com::sun::star::io::XSeekable\n , ::com::sun::star::io::XStream\n , ::com::sun::star::io::XTruncate\n , ::com::sun::star::beans::XPropertySetInfo\n , ::com::sun::star::beans::XPropertySet\n , ::com::sun::star::lang::XServiceInfo\n >\n{\nprotected:\n ::utl::TempFile* mpTempFile;\n ::osl::Mutex maMutex;\n SvStream* mpStream;\n sal_Bool mbRemoveFile;\n sal_Bool mbInClosed;\n sal_Bool mbOutClosed;\n\n \/\/ intended to hold the current position in disconnected state\n sal_Int64 mnCachedPos;\n sal_Bool mbHasCachedPos;\n\n void checkError () const;\n void checkConnected ();\n\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > GetProps();\n\npublic:\n XTempFile ();\n virtual ~XTempFile ();\n\n \/\/ XInputStream\n virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL available( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL closeInput( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n \/\/ XOutputStream\n virtual void SAL_CALL writeBytes( const ::com::sun::star::uno::Sequence< sal_Int8 >& aData )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL flush( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL closeOutput( )\n throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n \/\/ XSeekable\n virtual void SAL_CALL seek( sal_Int64 location )\n throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int64 SAL_CALL getPosition( )\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int64 SAL_CALL getLength( )\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XStream\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > SAL_CALL getOutputStream( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XTruncate\n virtual void SAL_CALL truncate()\n throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySetInfo\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL getProperties( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::beans::Property SAL_CALL getPropertyByName( const ::rtl::OUString& aName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::sal_Bool SAL_CALL hasPropertyByName( const ::rtl::OUString& Name ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener )\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n static ::rtl::OUString getImplementationName_Static ();\n static ::com::sun::star::uno::Sequence < ::rtl::OUString > getSupportedServiceNames_Static();\n static ::com::sun::star::uno::Reference < com::sun::star::lang::XSingleServiceFactory > createServiceFactory_Static( com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > const & rServiceFactory );\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n throw (::com::sun::star::uno::RuntimeException);\n\n};\n#endif\n<|endoftext|>"} {"text":"Minor fixes to tooltips.<|endoftext|>"} {"text":"#include \n#include \n\n#include \"SentenceExtractor.h\"\n\nusing namespace std;\n\nSentenceExtractor::SentenceExtractor(ExtractorOptions opts) \n{\n this->opts = opts;\n}\n\nSentenceExtractor::~SentenceExtractor() \n{\n}\n\nchar SentenceExtractor::last_written_char() \n{\n return output[output.size()-1];\n}\n\nbool SentenceExtractor::is_last_written_char(const char* chars) \n{\n if(output.empty())\n return false;\n const int n = strlen(chars);\n const char last = last_written_char();\n for(int i = 0; i < n; i++) {\n if(last == chars[i])\n return true;\n }\n return false;\n}\n\nbool SentenceExtractor::is_ws(char ch) \n{\n return ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r';\n}\n\nchar SentenceExtractor::peek() {\n return input[pos+1];\n}\n\nchar SentenceExtractor::peek(size_t n) {\n size_t i = 0;\n while(input[pos + i] != '\\0' && ++i < n);\n return i == n ? input[pos+i] : '\\0';\n}\n\nvoid SentenceExtractor::newline(int count) \n{\n if(output.size() == 0)\n return;\n\n for(int i = output.size()-1; i >= 0 && output[i] == '\\n'; i--, count--); \n\n while(count-- > 0) {\n output += '\\n';\n }\n}\n\nbool SentenceExtractor::out_ends_with(const char* suffix)\n{\n return output.find(suffix, output.size()-strlen(suffix)) != string::npos;\n}\n\nstring SentenceExtractor::extract(const char* input) \n{\n this->input = input;\n this->pos = 0;\n this->output.clear();\n \/\/ Reserve 2MB for output. Most wikipedia articles will fit without resizing.\n this->output.reserve(2*1024*1024); \n\n while(input[pos] != '\\0') {\n const char ch = input[pos];\n switch(ch) {\n case '\\n':\n if(peek() == '\\n' && opts.separateParagraphs) {\n newline(2);\n pos++;\n }\n break;\n \n case '.':\n output += ch;\n if(is_ws(peek()) &&\n !out_ends_with(\"e.g.\") &&\n !out_ends_with(\"i.e.\")) {\n if(peek(3) == '.') { \/\/ One letter \"sentence\": most likely an abbreviation\n output += input[pos+1];\n output += input[pos+2];\n output += input[pos+3];\n pos += 3;\n }\n else {\n if(peek()=='\"' || peek()=='\\'') { \n output += input[++pos];\n }\n \n newline(1);\n }\n }\n break;\n\n case '?':\n case '!':\n output += ch;\n newline(1);\n break; \n\n case ' ':\n case '\\t':\n if(pos == 0 || !is_last_written_char(\" \\t\\r\\n\"))\n output += ch;\n break;\n\n default:\n output += ch;\n break;\n }\n \n pos++;\n }\n\n \/\/ make sure we have to newlines at the end: this is so that we\n \/\/ can concatenate outputs from multiple articles and have their\n \/\/ paragraphs clearly separated.\n newline(2);\n \n return this->output;\n}\ndo not produce reduntant spaces in the sentence extractor#include \n#include \n\n#include \"SentenceExtractor.h\"\n\nusing namespace std;\n\nSentenceExtractor::SentenceExtractor(ExtractorOptions opts) \n{\n this->opts = opts;\n}\n\nSentenceExtractor::~SentenceExtractor() \n{\n}\n\nchar SentenceExtractor::last_written_char() \n{\n return output[output.size()-1];\n}\n\nbool SentenceExtractor::is_last_written_char(const char* chars) \n{\n if(output.empty())\n return false;\n const int n = strlen(chars);\n const char last = last_written_char();\n for(int i = 0; i < n; i++) {\n if(last == chars[i])\n return true;\n }\n return false;\n}\n\nbool SentenceExtractor::is_ws(char ch) \n{\n return ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r';\n}\n\nchar SentenceExtractor::peek() {\n return input[pos+1];\n}\n\nchar SentenceExtractor::peek(size_t n) {\n size_t i = 0;\n while(input[pos + i] != '\\0' && ++i < n);\n return i == n ? input[pos+i] : '\\0';\n}\n\nvoid SentenceExtractor::newline(int count) \n{\n if(output.size() == 0)\n return;\n\n for(int i = output.size()-1; i >= 0 && output[i] == '\\n'; i--, count--); \n\n while(count-- > 0) {\n output += '\\n';\n }\n}\n\nbool SentenceExtractor::out_ends_with(const char* suffix)\n{\n return output.find(suffix, output.size()-strlen(suffix)) != string::npos;\n}\n\nstring SentenceExtractor::extract(const char* input) \n{\n this->input = input;\n this->pos = 0;\n this->output.clear();\n \/\/ Reserve 2MB for output. Most wikipedia articles will fit without resizing.\n this->output.reserve(2*1024*1024); \n\n while(input[pos] != '\\0') {\n const char ch = input[pos];\n switch(ch) {\n case '\\n':\n if(peek() == '\\n' && opts.separateParagraphs) {\n newline(2);\n pos++;\n }\n else if(!is_last_written_char(\" \\t\")) {\n output += ' ';\n }\n break;\n \n case '.':\n output += ch;\n if(is_ws(peek()) &&\n !out_ends_with(\"e.g.\") &&\n !out_ends_with(\"i.e.\")) {\n if(peek(3) == '.') { \/\/ One letter \"sentence\": most likely an abbreviation\n output += input[pos+1];\n output += input[pos+2];\n output += input[pos+3];\n pos += 3;\n }\n else {\n if(peek()=='\"' || peek()=='\\'') { \n output += input[++pos];\n }\n \n newline(1);\n }\n }\n break;\n\n case '?':\n case '!':\n output += ch;\n newline(1);\n break; \n\n case ' ':\n case '\\t':\n if(pos == 0 || !is_last_written_char(\" \\t\\r\\n\"))\n output += ch;\n break;\n\n default:\n output += ch;\n break;\n }\n \n pos++;\n }\n\n \/\/ make sure we have to newlines at the end: this is so that we\n \/\/ can concatenate outputs from multiple articles and have their\n \/\/ paragraphs clearly separated.\n newline(2);\n \n return this->output;\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 \"media\/tools\/player_x11\/gles_video_renderer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/pipeline.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"media\/base\/yuv_convert.h\"\n\nGlesVideoRenderer* GlesVideoRenderer::instance_ = NULL;\n\nGlesVideoRenderer::GlesVideoRenderer(Display* display, Window window)\n : display_(display),\n window_(window),\n new_frame_(false),\n egl_display_(NULL),\n egl_surface_(NULL),\n egl_context_(NULL) {\n}\n\nGlesVideoRenderer::~GlesVideoRenderer() {\n}\n\n\/\/ static\nbool GlesVideoRenderer::IsMediaFormatSupported(\n const media::MediaFormat& media_format) {\n int width = 0;\n int height = 0;\n return ParseMediaFormat(media_format, &width, &height);\n}\n\nvoid GlesVideoRenderer::OnStop() {\n \/\/ TODO(hclam): Context switching seems to be broek so the following\n \/\/ calls may fail. Need to fix them.\n eglMakeCurrent(egl_display_, EGL_NO_SURFACE,\n EGL_NO_SURFACE, EGL_NO_CONTEXT);\n eglDestroyContext(egl_display_, egl_context_);\n eglDestroySurface(egl_display_, egl_surface_);\n}\n\n\/\/ Matrix used for the YUV to RGB conversion.\nstatic const float kYUV2RGB[9] = {\n 1.f, 1.f, 1.f,\n 0.f, -.344f, 1.772f,\n 1.403f, -.714f, 0.f,\n};\n\n\/\/ Vertices for a full screen quad.\nstatic const float kVertices[8] = {\n -1.f, 1.f,\n -1.f, -1.f,\n 1.f, 1.f,\n 1.f, -1.f,\n};\n\n\/\/ Texture Coordinates mapping the entire texture.\nstatic const float kTextureCoords[8] = {\n 0, 0,\n 0, 1,\n 1, 0,\n 1, 1,\n};\n\n\/\/ Pass-through vertex shader.\nstatic const char kVertexShader[] =\n \"precision highp float; precision highp int;\\n\"\n \"varying vec2 interp_tc;\\n\"\n \"\\n\"\n \"attribute vec4 in_pos;\\n\"\n \"attribute vec2 in_tc;\\n\"\n \"\\n\"\n \"void main() {\\n\"\n \" interp_tc = in_tc;\\n\"\n \" gl_Position = in_pos;\\n\"\n \"}\\n\";\n\n\/\/ YUV to RGB pixel shader. Loads a pixel from each plane and pass through the\n\/\/ matrix.\nstatic const char kFragmentShader[] =\n \"precision mediump float; precision mediump int;\\n\"\n \"varying vec2 interp_tc;\\n\"\n \"\\n\"\n \"uniform sampler2D y_tex;\\n\"\n \"uniform sampler2D u_tex;\\n\"\n \"uniform sampler2D v_tex;\\n\"\n \"uniform mat3 yuv2rgb;\\n\"\n \"\\n\"\n \"void main() {\\n\"\n \" float y = texture2D(y_tex, interp_tc).x;\\n\"\n \" float u = texture2D(u_tex, interp_tc).r - .5;\\n\"\n \" float v = texture2D(v_tex, interp_tc).r - .5;\\n\"\n \" vec3 rgb = yuv2rgb * vec3(y, u, v);\\n\"\n \" gl_FragColor = vec4(rgb, 1);\\n\"\n \"}\\n\";\n\n\/\/ Buffer size for compile errors.\nstatic const unsigned int kErrorSize = 4096;\n\nbool GlesVideoRenderer::OnInitialize(media::VideoDecoder* decoder) {\n if (!ParseMediaFormat(decoder->media_format(), &width_, &height_))\n return false;\n\n LOG(INFO) << \"Initializing GLES Renderer...\";\n\n \/\/ Save this instance.\n DCHECK(!instance_);\n instance_ = this;\n return true;\n}\n\nvoid GlesVideoRenderer::OnFrameAvailable() {\n AutoLock auto_lock(lock_);\n new_frame_ = true;\n}\n\nvoid GlesVideoRenderer::Paint() {\n \/\/ Use |new_frame_| to prevent overdraw since Paint() is called more\n \/\/ often than needed. It is OK to lock only this flag and we don't\n \/\/ want to lock the whole function because this method takes a long\n \/\/ time to complete.\n {\n AutoLock auto_lock(lock_);\n if (!new_frame_)\n return;\n new_frame_ = false;\n }\n\n \/\/ Initialize GLES here to avoid context switching. Some drivers doesn't\n \/\/ like switching context between threads.\n static bool initialized = false;\n if (!initialized && !InitializeGles()) {\n initialized = true;\n host()->SetError(media::PIPELINE_ERROR_COULD_NOT_RENDER);\n return;\n }\n initialized = true;\n\n scoped_refptr video_frame;\n GetCurrentFrame(&video_frame);\n\n if (!video_frame)\n return;\n\n \/\/ Convert YUV frame to RGB.\n media::VideoSurface frame_in;\n if (video_frame->Lock(&frame_in)) {\n DCHECK(frame_in.format == media::VideoSurface::YV12 ||\n frame_in.format == media::VideoSurface::YV16);\n DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==\n frame_in.strides[media::VideoSurface::kVPlane]);\n DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);\n\n for (unsigned int i = 0; i < media::VideoSurface::kNumYUVPlanes; ++i) {\n unsigned int width = (i == media::VideoSurface::kYPlane) ?\n frame_in.width : frame_in.width \/ 2;\n unsigned int height = (i == media::VideoSurface::kYPlane ||\n frame_in.format == media::VideoSurface::YV16) ?\n frame_in.height : frame_in.height \/ 2;\n glActiveTexture(GL_TEXTURE0 + i);\n \/\/ No GL_UNPACK_ROW_LENGTH in GLES2.\n \/\/ glPixelStorei(GL_UNPACK_ROW_LENGTH, frame_in.strides[i]);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,\n GL_LUMINANCE, GL_UNSIGNED_BYTE, frame_in.data[i]);\n }\n video_frame->Unlock();\n } else {\n NOTREACHED();\n }\n\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n eglSwapBuffers(egl_display_, egl_surface_);\n}\n\nbool GlesVideoRenderer::InitializeGles() {\n \/\/ Resize the window to fit that of the video.\n XResizeWindow(display_, window_, width_, height_);\n\n egl_display_ = eglGetDisplay(display_);\n if (eglGetError() != EGL_SUCCESS) {\n DLOG(ERROR) << \"eglGetDisplay failed.\";\n return false;\n }\n\n EGLint major;\n EGLint minor;\n if (!eglInitialize(egl_display_, &major, &minor)) {\n DLOG(ERROR) << \"eglInitialize failed.\";\n return false;\n }\n DLOG(INFO) << \"EGL vendor:\" << eglQueryString(egl_display_, EGL_VENDOR);\n DLOG(INFO) << \"EGL version:\" << eglQueryString(egl_display_, EGL_VERSION);\n DLOG(INFO) << \"EGL extensions:\"\n << eglQueryString(egl_display_, EGL_EXTENSIONS);\n DLOG(INFO) << \"EGL client apis:\"\n << eglQueryString(egl_display_, EGL_CLIENT_APIS);\n\n EGLint attribs[] = {\n EGL_RED_SIZE, 5,\n EGL_GREEN_SIZE, 6,\n EGL_BLUE_SIZE, 5,\n EGL_DEPTH_SIZE, 16,\n EGL_STENCIL_SIZE, 0,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_NONE\n };\n\n EGLint num_configs = -1;\n if (!eglGetConfigs(egl_display_, NULL, 0, &num_configs)) {\n DLOG(ERROR) << \"eglGetConfigs failed.\";\n return false;\n }\n\n EGLConfig config;\n if (!eglChooseConfig(egl_display_, attribs, &config, 1, &num_configs)) {\n DLOG(ERROR) << \"eglChooseConfig failed.\";\n return false;\n }\n\n EGLint red_size, green_size, blue_size, alpha_size, depth_size, stencil_size;\n eglGetConfigAttrib(egl_display_, config, EGL_RED_SIZE, &red_size);\n eglGetConfigAttrib(egl_display_, config, EGL_GREEN_SIZE, &green_size);\n eglGetConfigAttrib(egl_display_, config, EGL_BLUE_SIZE, &blue_size);\n eglGetConfigAttrib(egl_display_, config, EGL_ALPHA_SIZE, &alpha_size);\n eglGetConfigAttrib(egl_display_, config, EGL_DEPTH_SIZE, &depth_size);\n eglGetConfigAttrib(egl_display_, config, EGL_STENCIL_SIZE, &stencil_size);\n DLOG(INFO) << \"R,G,B,A: \" << red_size << \",\" << green_size\n << \",\" << blue_size << \",\" << alpha_size << \" bits\";\n DLOG(INFO) << \"Depth: \" << depth_size << \" bits, Stencil:\" << stencil_size\n << \"bits\";\n\n egl_surface_ = eglCreateWindowSurface(egl_display_, config, window_, NULL);\n if (!egl_surface_) {\n DLOG(ERROR) << \"eglCreateWindowSurface failed.\";\n return false;\n }\n\n egl_context_ = eglCreateContext(egl_display_, config, NULL, NULL);\n if (!egl_context_) {\n DLOG(ERROR) << \"eglCreateContext failed.\";\n eglDestroySurface(egl_display_, egl_surface_);\n return false;\n }\n\n if (eglMakeCurrent(egl_display_, egl_surface_,\n egl_surface_, egl_context_) == EGL_FALSE) {\n eglDestroyContext(egl_display_, egl_context_);\n eglDestroySurface(egl_display_, egl_surface_);\n egl_display_ = NULL;\n egl_surface_ = NULL;\n egl_context_ = NULL;\n return false;\n }\n\n EGLint width;\n EGLint height;\n eglQuerySurface(egl_display_, egl_surface_, EGL_WIDTH, &width);\n eglQuerySurface(egl_display_, egl_surface_, EGL_HEIGHT, &height);\n glViewport(0, 0, width_, height_);\n\n \/\/ Create 3 textures, one for each plane, and bind them to different\n \/\/ texture units.\n glGenTextures(media::VideoSurface::kNumYUVPlanes, textures_);\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, textures_[0]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n glActiveTexture(GL_TEXTURE1);\n glBindTexture(GL_TEXTURE_2D, textures_[1]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n glActiveTexture(GL_TEXTURE2);\n glBindTexture(GL_TEXTURE_2D, textures_[2]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n GLuint program_ = glCreateProgram();\n\n \/\/ Create our YUV->RGB shader.\n GLuint vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);\n const char* vs_source = kVertexShader;\n int vs_size = sizeof(kVertexShader);\n glShaderSource(vertex_shader_, 1, &vs_source, &vs_size);\n glCompileShader(vertex_shader_);\n int result = GL_FALSE;\n glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetShaderInfoLog(vertex_shader_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glAttachShader(program_, vertex_shader_);\n\n GLuint fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);\n const char* ps_source = kFragmentShader;\n int ps_size = sizeof(kFragmentShader);\n glShaderSource(fragment_shader_, 1, &ps_source, &ps_size);\n glCompileShader(fragment_shader_);\n result = GL_FALSE;\n glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetShaderInfoLog(fragment_shader_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glAttachShader(program_, fragment_shader_);\n\n glLinkProgram(program_);\n result = GL_FALSE;\n glGetProgramiv(program_, GL_LINK_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glUseProgram(program_);\n\n \/\/ Bind parameters.\n glUniform1i(glGetUniformLocation(program_, \"y_tex\"), 0);\n glUniform1i(glGetUniformLocation(program_, \"u_tex\"), 1);\n glUniform1i(glGetUniformLocation(program_, \"v_tex\"), 2);\n int yuv2rgb_location = glGetUniformLocation(program_, \"yuv2rgb\");\n glUniformMatrix3fv(yuv2rgb_location, 1, GL_FALSE, kYUV2RGB);\n\n int pos_location = glGetAttribLocation(program_, \"in_pos\");\n glEnableVertexAttribArray(pos_location);\n glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0, kVertices);\n\n int tc_location = glGetAttribLocation(program_, \"in_tc\");\n glEnableVertexAttribArray(tc_location);\n glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,\n kTextureCoords);\n\n \/\/ We are getting called on a thread. Release the context so that it can be\n \/\/ made current on the main thread.\n \/\/ TODO(hclam): Fix this if neccessary. Currently the following call fails\n \/\/ for some drivers.\n \/\/ eglMakeCurrent(egl_display_, EGL_NO_SURFACE,\n \/\/ EGL_NO_SURFACE, EGL_NO_CONTEXT);\n return true;\n}\ngles2: fix stride support\/\/ 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 \"media\/tools\/player_x11\/gles_video_renderer.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"media\/base\/buffers.h\"\n#include \"media\/base\/pipeline.h\"\n#include \"media\/base\/filter_host.h\"\n#include \"media\/base\/yuv_convert.h\"\n\nGlesVideoRenderer* GlesVideoRenderer::instance_ = NULL;\n\nGlesVideoRenderer::GlesVideoRenderer(Display* display, Window window)\n : display_(display),\n window_(window),\n new_frame_(false),\n egl_display_(NULL),\n egl_surface_(NULL),\n egl_context_(NULL) {\n}\n\nGlesVideoRenderer::~GlesVideoRenderer() {\n}\n\n\/\/ static\nbool GlesVideoRenderer::IsMediaFormatSupported(\n const media::MediaFormat& media_format) {\n int width = 0;\n int height = 0;\n return ParseMediaFormat(media_format, &width, &height);\n}\n\nvoid GlesVideoRenderer::OnStop() {\n \/\/ TODO(hclam): Context switching seems to be broek so the following\n \/\/ calls may fail. Need to fix them.\n eglMakeCurrent(egl_display_, EGL_NO_SURFACE,\n EGL_NO_SURFACE, EGL_NO_CONTEXT);\n eglDestroyContext(egl_display_, egl_context_);\n eglDestroySurface(egl_display_, egl_surface_);\n}\n\n\/\/ Matrix used for the YUV to RGB conversion.\nstatic const float kYUV2RGB[9] = {\n 1.f, 1.f, 1.f,\n 0.f, -.344f, 1.772f,\n 1.403f, -.714f, 0.f,\n};\n\n\/\/ Vertices for a full screen quad.\nstatic const float kVertices[8] = {\n -1.f, 1.f,\n -1.f, -1.f,\n 1.f, 1.f,\n 1.f, -1.f,\n};\n\n\/\/ Texture Coordinates mapping the entire texture.\nstatic const float kTextureCoords[8] = {\n 0, 0,\n 0, 1,\n 1, 0,\n 1, 1,\n};\n\n\/\/ Pass-through vertex shader.\nstatic const char kVertexShader[] =\n \"precision highp float; precision highp int;\\n\"\n \"varying vec2 interp_tc;\\n\"\n \"\\n\"\n \"attribute vec4 in_pos;\\n\"\n \"attribute vec2 in_tc;\\n\"\n \"\\n\"\n \"void main() {\\n\"\n \" interp_tc = in_tc;\\n\"\n \" gl_Position = in_pos;\\n\"\n \"}\\n\";\n\n\/\/ YUV to RGB pixel shader. Loads a pixel from each plane and pass through the\n\/\/ matrix.\nstatic const char kFragmentShader[] =\n \"precision mediump float; precision mediump int;\\n\"\n \"varying vec2 interp_tc;\\n\"\n \"\\n\"\n \"uniform sampler2D y_tex;\\n\"\n \"uniform sampler2D u_tex;\\n\"\n \"uniform sampler2D v_tex;\\n\"\n \"uniform mat3 yuv2rgb;\\n\"\n \"\\n\"\n \"void main() {\\n\"\n \" float y = texture2D(y_tex, interp_tc).x;\\n\"\n \" float u = texture2D(u_tex, interp_tc).r - .5;\\n\"\n \" float v = texture2D(v_tex, interp_tc).r - .5;\\n\"\n \" vec3 rgb = yuv2rgb * vec3(y, u, v);\\n\"\n \" gl_FragColor = vec4(rgb, 1);\\n\"\n \"}\\n\";\n\n\/\/ Buffer size for compile errors.\nstatic const unsigned int kErrorSize = 4096;\n\nbool GlesVideoRenderer::OnInitialize(media::VideoDecoder* decoder) {\n if (!ParseMediaFormat(decoder->media_format(), &width_, &height_))\n return false;\n\n LOG(INFO) << \"Initializing GLES Renderer...\";\n\n \/\/ Save this instance.\n DCHECK(!instance_);\n instance_ = this;\n return true;\n}\n\nvoid GlesVideoRenderer::OnFrameAvailable() {\n AutoLock auto_lock(lock_);\n new_frame_ = true;\n}\n\nvoid GlesVideoRenderer::Paint() {\n \/\/ Use |new_frame_| to prevent overdraw since Paint() is called more\n \/\/ often than needed. It is OK to lock only this flag and we don't\n \/\/ want to lock the whole function because this method takes a long\n \/\/ time to complete.\n {\n AutoLock auto_lock(lock_);\n if (!new_frame_)\n return;\n new_frame_ = false;\n }\n\n \/\/ Initialize GLES here to avoid context switching. Some drivers doesn't\n \/\/ like switching context between threads.\n static bool initialized = false;\n if (!initialized && !InitializeGles()) {\n initialized = true;\n host()->SetError(media::PIPELINE_ERROR_COULD_NOT_RENDER);\n return;\n }\n initialized = true;\n\n scoped_refptr video_frame;\n GetCurrentFrame(&video_frame);\n\n if (!video_frame)\n return;\n\n \/\/ Convert YUV frame to RGB.\n media::VideoSurface frame_in;\n if (video_frame->Lock(&frame_in)) {\n DCHECK(frame_in.format == media::VideoSurface::YV12 ||\n frame_in.format == media::VideoSurface::YV16);\n DCHECK(frame_in.strides[media::VideoSurface::kUPlane] ==\n frame_in.strides[media::VideoSurface::kVPlane]);\n DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes);\n\n for (unsigned int i = 0; i < media::VideoSurface::kNumYUVPlanes; ++i) {\n unsigned int width = (i == media::VideoSurface::kYPlane) ?\n frame_in.width : frame_in.width \/ 2;\n unsigned int height = (i == media::VideoSurface::kYPlane ||\n frame_in.format == media::VideoSurface::YV16) ?\n frame_in.height : frame_in.height \/ 2;\n glActiveTexture(GL_TEXTURE0 + i);\n \/\/ GLES2 supports a fixed set of unpack alignments that should match most\n \/\/ of the time what ffmpeg outputs.\n \/\/ TODO(piman): check if it is more efficient to prefer higher\n \/\/ alignments.\n unsigned int stride = frame_in.strides[i];\n uint8* data = frame_in.data[i];\n if (stride == width) {\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n } else if (stride == ((width + 1) & ~1)) {\n glPixelStorei(GL_UNPACK_ALIGNMENT, 2);\n } else if (stride == ((width + 3) & ~3)) {\n glPixelStorei(GL_UNPACK_ALIGNMENT, 4);\n } else if (stride == ((width + 7) & ~7)) {\n glPixelStorei(GL_UNPACK_ALIGNMENT, 8);\n } else {\n \/\/ Otherwise do it line-by-line.\n glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,\n GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);\n for (unsigned int y = 0; y < height; ++y) {\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y, width, 1,\n GL_LUMINANCE, GL_UNSIGNED_BYTE, data);\n data += stride;\n }\n continue;\n }\n glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0,\n GL_LUMINANCE, GL_UNSIGNED_BYTE, data);\n }\n video_frame->Unlock();\n } else {\n NOTREACHED();\n }\n\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);\n eglSwapBuffers(egl_display_, egl_surface_);\n}\n\nbool GlesVideoRenderer::InitializeGles() {\n \/\/ Resize the window to fit that of the video.\n XResizeWindow(display_, window_, width_, height_);\n\n egl_display_ = eglGetDisplay(display_);\n if (eglGetError() != EGL_SUCCESS) {\n DLOG(ERROR) << \"eglGetDisplay failed.\";\n return false;\n }\n\n EGLint major;\n EGLint minor;\n if (!eglInitialize(egl_display_, &major, &minor)) {\n DLOG(ERROR) << \"eglInitialize failed.\";\n return false;\n }\n DLOG(INFO) << \"EGL vendor:\" << eglQueryString(egl_display_, EGL_VENDOR);\n DLOG(INFO) << \"EGL version:\" << eglQueryString(egl_display_, EGL_VERSION);\n DLOG(INFO) << \"EGL extensions:\"\n << eglQueryString(egl_display_, EGL_EXTENSIONS);\n DLOG(INFO) << \"EGL client apis:\"\n << eglQueryString(egl_display_, EGL_CLIENT_APIS);\n\n EGLint attribs[] = {\n EGL_RED_SIZE, 5,\n EGL_GREEN_SIZE, 6,\n EGL_BLUE_SIZE, 5,\n EGL_DEPTH_SIZE, 16,\n EGL_STENCIL_SIZE, 0,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_NONE\n };\n\n EGLint num_configs = -1;\n if (!eglGetConfigs(egl_display_, NULL, 0, &num_configs)) {\n DLOG(ERROR) << \"eglGetConfigs failed.\";\n return false;\n }\n\n EGLConfig config;\n if (!eglChooseConfig(egl_display_, attribs, &config, 1, &num_configs)) {\n DLOG(ERROR) << \"eglChooseConfig failed.\";\n return false;\n }\n\n EGLint red_size, green_size, blue_size, alpha_size, depth_size, stencil_size;\n eglGetConfigAttrib(egl_display_, config, EGL_RED_SIZE, &red_size);\n eglGetConfigAttrib(egl_display_, config, EGL_GREEN_SIZE, &green_size);\n eglGetConfigAttrib(egl_display_, config, EGL_BLUE_SIZE, &blue_size);\n eglGetConfigAttrib(egl_display_, config, EGL_ALPHA_SIZE, &alpha_size);\n eglGetConfigAttrib(egl_display_, config, EGL_DEPTH_SIZE, &depth_size);\n eglGetConfigAttrib(egl_display_, config, EGL_STENCIL_SIZE, &stencil_size);\n DLOG(INFO) << \"R,G,B,A: \" << red_size << \",\" << green_size\n << \",\" << blue_size << \",\" << alpha_size << \" bits\";\n DLOG(INFO) << \"Depth: \" << depth_size << \" bits, Stencil:\" << stencil_size\n << \"bits\";\n\n egl_surface_ = eglCreateWindowSurface(egl_display_, config, window_, NULL);\n if (!egl_surface_) {\n DLOG(ERROR) << \"eglCreateWindowSurface failed.\";\n return false;\n }\n\n egl_context_ = eglCreateContext(egl_display_, config, NULL, NULL);\n if (!egl_context_) {\n DLOG(ERROR) << \"eglCreateContext failed.\";\n eglDestroySurface(egl_display_, egl_surface_);\n return false;\n }\n\n if (eglMakeCurrent(egl_display_, egl_surface_,\n egl_surface_, egl_context_) == EGL_FALSE) {\n eglDestroyContext(egl_display_, egl_context_);\n eglDestroySurface(egl_display_, egl_surface_);\n egl_display_ = NULL;\n egl_surface_ = NULL;\n egl_context_ = NULL;\n return false;\n }\n\n EGLint width;\n EGLint height;\n eglQuerySurface(egl_display_, egl_surface_, EGL_WIDTH, &width);\n eglQuerySurface(egl_display_, egl_surface_, EGL_HEIGHT, &height);\n glViewport(0, 0, width_, height_);\n\n \/\/ Create 3 textures, one for each plane, and bind them to different\n \/\/ texture units.\n glGenTextures(media::VideoSurface::kNumYUVPlanes, textures_);\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, textures_[0]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n glActiveTexture(GL_TEXTURE1);\n glBindTexture(GL_TEXTURE_2D, textures_[1]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n glActiveTexture(GL_TEXTURE2);\n glBindTexture(GL_TEXTURE_2D, textures_[2]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n glEnable(GL_TEXTURE_2D);\n\n GLuint program_ = glCreateProgram();\n\n \/\/ Create our YUV->RGB shader.\n GLuint vertex_shader_ = glCreateShader(GL_VERTEX_SHADER);\n const char* vs_source = kVertexShader;\n int vs_size = sizeof(kVertexShader);\n glShaderSource(vertex_shader_, 1, &vs_source, &vs_size);\n glCompileShader(vertex_shader_);\n int result = GL_FALSE;\n glGetShaderiv(vertex_shader_, GL_COMPILE_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetShaderInfoLog(vertex_shader_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glAttachShader(program_, vertex_shader_);\n\n GLuint fragment_shader_ = glCreateShader(GL_FRAGMENT_SHADER);\n const char* ps_source = kFragmentShader;\n int ps_size = sizeof(kFragmentShader);\n glShaderSource(fragment_shader_, 1, &ps_source, &ps_size);\n glCompileShader(fragment_shader_);\n result = GL_FALSE;\n glGetShaderiv(fragment_shader_, GL_COMPILE_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetShaderInfoLog(fragment_shader_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glAttachShader(program_, fragment_shader_);\n\n glLinkProgram(program_);\n result = GL_FALSE;\n glGetProgramiv(program_, GL_LINK_STATUS, &result);\n if (!result) {\n char log[kErrorSize];\n int len;\n glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);\n log[kErrorSize - 1] = 0;\n LOG(FATAL) << log;\n }\n glUseProgram(program_);\n\n \/\/ Bind parameters.\n glUniform1i(glGetUniformLocation(program_, \"y_tex\"), 0);\n glUniform1i(glGetUniformLocation(program_, \"u_tex\"), 1);\n glUniform1i(glGetUniformLocation(program_, \"v_tex\"), 2);\n int yuv2rgb_location = glGetUniformLocation(program_, \"yuv2rgb\");\n glUniformMatrix3fv(yuv2rgb_location, 1, GL_FALSE, kYUV2RGB);\n\n int pos_location = glGetAttribLocation(program_, \"in_pos\");\n glEnableVertexAttribArray(pos_location);\n glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0, kVertices);\n\n int tc_location = glGetAttribLocation(program_, \"in_tc\");\n glEnableVertexAttribArray(tc_location);\n glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,\n kTextureCoords);\n\n \/\/ We are getting called on a thread. Release the context so that it can be\n \/\/ made current on the main thread.\n \/\/ TODO(hclam): Fix this if neccessary. Currently the following call fails\n \/\/ for some drivers.\n \/\/ eglMakeCurrent(egl_display_, EGL_NO_SURFACE,\n \/\/ EGL_NO_SURFACE, EGL_NO_CONTEXT);\n return true;\n}\n<|endoftext|>"} {"text":"\/\/ -*- c-basic-offset: 2; related-file-name: \"\" -*-\n\/*\n * @(#)$Id$\n *\n *\n * This file is distributed under the terms in the attached LICENSE file.\n * If you do not find this file, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * Or\n * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776, \n * Berkeley, CA, 94707. Attention: P2 Group.\n * \n * DESCRIPTION: Overlog based on new planner\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"ol_lexer.h\"\n#include \"ol_context.h\"\n#include \"eca_context.h\"\n#include \"localize_context.h\"\n#include \"plmb_confgen.h\"\n#include \"tableStore.h\"\n#include \"udp.h\"\n#include \"planner.h\"\n#include \"ruleStrand.h\"\n\n#include \"dot.h\"\n\nextern int ol_parser_debug;\n\nint main(int argc, char **argv)\n{\n LoggerI::Level level = LoggerI::NONE;\n PlumberPtr plumber(new Plumber(level));\n std::cout << \"TestPlanner\\n\";\n boost::shared_ptr< OL_Context > ctxt(new OL_Context());\n bool route = false;\n bool builtin = false;\n string filename(\"\");\n\n \/\/PlumberPtr plumber(new Plumber());\n\n for( int i=1; iparse_stream(&std::cin);\n } else if (arg == \"-g\") {\n\n Plumber::DataflowPtr conf(new Plumber::Dataflow(\"overlog\"));\n filename = argv[i+1];\n std::ifstream istr(filename.c_str());\n ctxt->parse_stream(&istr);\n\n boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get())); \n tableStore->initTables(); \n \n boost::shared_ptr< Localize_Context > lctxt(new Localize_Context()); \n lctxt->rewrite(ctxt.get(), tableStore.get());\n \n boost::shared_ptr< ECA_Context > ectxt(new ECA_Context()); \n ectxt->rewrite(lctxt.get(), tableStore.get());\n\n boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, \"127.0.0.1:10000\", \"0\"));\n boost::shared_ptr< Udp > udp(new Udp(\"Udp\", 10000));\n\n std::vector\n ruleStrands = planner->generateRuleStrands(ectxt);\n\n planner->setupNetwork(udp);\n planner->registerAllRuleStrands(ruleStrands);\n\n if (plumber->install(conf) == 0) {\n std::cout << \"Correctly initialized network of reachability flows.\\n\";\n } else {\n std::cout << \"** Failed to initialize correct spec\\n\";\n }\n plumber->toDot(\"overlog.dot\");\n exit (0);\n } else { \n filename = argv[i];\n std::ifstream istr(argv[i]);\n ctxt->parse_stream(&istr);\n }\n }\n\n if (builtin) {\n std::cerr << ctxt->toString();\n std::cerr.flush();\n std::cout << \"OK\\n\";\n std::cout.flush();\n } \n\n std::cout << \"Finish parsing (functors \/ tableInfos) \" \n\t << ctxt->getRules()->size() \n\t << \" \" << ctxt->getTableInfos()->size() << \"\\n\";\n\n std::cout << ctxt->toString() << \"\\n\";\n\n if (route) {\n Plumber::DataflowPtr conf(new Plumber::Dataflow(\"overlog\"));\n boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get())); \n tableStore->initTables(); \n\n FILE* strandOutput = fopen((filename + \".strand\").c_str(), \"w\");\n FILE* ecaOutput = fopen((filename + \".eca\").c_str(), \"w\");\n FILE* localOutput = fopen((filename + \".local\").c_str(), \"w\");\n\n boost::shared_ptr< Localize_Context > lctxt(new Localize_Context()); \n lctxt->rewrite(ctxt.get(), tableStore.get());\n fprintf(localOutput, lctxt->toString().c_str());\n fclose(localOutput);\n \n boost::shared_ptr< ECA_Context > ectxt(new ECA_Context()); \n ectxt->rewrite(lctxt.get(), tableStore.get());\n fprintf(ecaOutput, lctxt->toString().c_str());\n fclose(ecaOutput);\n \n boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, \"127.0.0.1:10000\", \"0\"));\n boost::shared_ptr< Udp > udp(new Udp(\"Udp\", 10000));\n std::vector ruleStrands = planner->generateRuleStrands(ectxt);\n \n for (unsigned k = 0; k < ruleStrands.size(); k++) {\n std::cout << ruleStrands.at(k)->toString();\n fprintf(strandOutput, ruleStrands.at(k)->toString().c_str());\n }\n fclose(strandOutput);\n \n planner->setupNetwork(udp);\n planner->registerAllRuleStrands(ruleStrands);\n std::cout << planner->getNetPlanner()->toString() << \"\\n\";\n\n if (plumber->install(conf) == 0) {\n std::cout << \"Correctly initialized network of reachability flows.\\n\";\n } else {\n std::cout << \"** Failed to initialize correct spec\\n\";\n } \n std::cout << \"Done.\\n\";\n\n }\n\n return 0;\n}\noverlog with new planner\/\/ -*- c-basic-offset: 2; related-file-name: \"\" -*-\n\/*\n * @(#)$Id$\n *\n *\n * This file is distributed under the terms in the attached LICENSE file.\n * If you do not find this file, copies can be found by writing to:\n * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,\n * Berkeley, CA, 94704. Attention: Intel License Inquiry.\n * Or\n * UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776, \n * Berkeley, CA, 94707. Attention: P2 Group.\n * \n * DESCRIPTION: Overlog based on new planner\n *\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"ol_lexer.h\"\n#include \"ol_context.h\"\n#include \"eca_context.h\"\n#include \"localize_context.h\"\n#include \"plmb_confgen.h\"\n#include \"tableStore.h\"\n#include \"udp.h\"\n#include \"planner.h\"\n#include \"ruleStrand.h\"\n\n#include \"dot.h\"\n\nextern int ol_parser_debug;\n\nint main(int argc, char **argv)\n{\n LoggerI::Level level = LoggerI::NONE;\n PlumberPtr plumber(new Plumber(level));\n std::cout << \"TestPlanner\\n\";\n boost::shared_ptr< OL_Context > ctxt(new OL_Context());\n bool route = false;\n bool builtin = false;\n string filename(\"\");\n\n \/\/PlumberPtr plumber(new Plumber());\n\n for( int i=1; iparse_stream(&std::cin);\n } else if (arg == \"-g\") {\n\n Plumber::DataflowPtr conf(new Plumber::Dataflow(\"overlog\"));\n filename = argv[i+1];\n std::ifstream istr(filename.c_str());\n ctxt->parse_stream(&istr);\n\n boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get())); \n tableStore->initTables(); \n \n boost::shared_ptr< Localize_Context > lctxt(new Localize_Context()); \n lctxt->rewrite(ctxt.get(), tableStore.get());\n \n boost::shared_ptr< ECA_Context > ectxt(new ECA_Context()); \n ectxt->rewrite(lctxt.get(), tableStore.get());\n\n boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, \"127.0.0.1:10000\", \"0\"));\n boost::shared_ptr< Udp > udp(new Udp(\"Udp\", 12345));\n\n std::vector\n ruleStrands = planner->generateRuleStrands(ectxt);\n\n planner->setupNetwork(udp);\n planner->registerAllRuleStrands(ruleStrands);\n\n if (plumber->install(conf) == 0) {\n std::cout << \"Correctly initialized network of reachability flows.\\n\";\n } else {\n std::cout << \"** Failed to initialize correct spec\\n\";\n }\n plumber->toDot(\"overlog.dot\");\n exit (0);\n } else { \n filename = argv[i];\n std::ifstream istr(argv[i]);\n ctxt->parse_stream(&istr);\n }\n }\n\n if (builtin) {\n std::cerr << ctxt->toString();\n std::cerr.flush();\n std::cout << \"OK\\n\";\n std::cout.flush();\n } \n\n std::cout << \"Finish parsing (functors \/ tableInfos) \" \n\t << ctxt->getRules()->size() \n\t << \" \" << ctxt->getTableInfos()->size() << \"\\n\";\n\n std::cout << ctxt->toString() << \"\\n\";\n\n if (route) {\n Plumber::DataflowPtr conf(new Plumber::Dataflow(\"overlog\"));\n boost::shared_ptr< TableStore > tableStore(new TableStore(ctxt.get())); \n tableStore->initTables(); \n\n FILE* strandOutput = fopen((filename + \".strand\").c_str(), \"w\");\n FILE* ecaOutput = fopen((filename + \".eca\").c_str(), \"w\");\n FILE* localOutput = fopen((filename + \".local\").c_str(), \"w\");\n\n boost::shared_ptr< Localize_Context > lctxt(new Localize_Context()); \n lctxt->rewrite(ctxt.get(), tableStore.get());\n fprintf(localOutput, lctxt->toString().c_str());\n fclose(localOutput);\n \n boost::shared_ptr< ECA_Context > ectxt(new ECA_Context()); \n ectxt->rewrite(lctxt.get(), tableStore.get());\n fprintf(ecaOutput, ectxt->toString().c_str());\n fclose(ecaOutput);\n \n boost::shared_ptr< Planner > planner(new Planner(conf, tableStore.get(), false, \"127.0.0.1:10000\", \"0\"));\n boost::shared_ptr< Udp > udp(new Udp(\"Udp\", 12345));\n std::vector ruleStrands = planner->generateRuleStrands(ectxt);\n \n for (unsigned k = 0; k < ruleStrands.size(); k++) {\n std::cout << ruleStrands.at(k)->toString();\n fprintf(strandOutput, ruleStrands.at(k)->toString().c_str());\n }\n fclose(strandOutput);\n \n planner->setupNetwork(udp);\n planner->registerAllRuleStrands(ruleStrands);\n std::cout << planner->getNetPlanner()->toString() << \"\\n\";\n\n if (plumber->install(conf) == 0) {\n std::cout << \"Correctly initialized network of reachability flows.\\n\";\n } else {\n std::cout << \"** Failed to initialize correct spec\\n\";\n } \n std::cout << \"Done.\\n\";\n\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018-2019 The PIVX 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\/\/ Created by tom on 2\/11\/18.\n\/\/\n\n[Cleanup][Tests] Remove crazy useful unittest created by \"Tom\"<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kTracker\/SRawEvent.h\"\n#include \"kTracker\/SRecEvent.h\"\n\n#include \"DataStruct.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n \/\/name of the TTree\n TString treename = argv[3];\n\n \/\/ input data structure\n SRecEvent* recEvent = new SRecEvent;\n\n TFile* dataFile = new TFile(argv[1], \"READ\");\n TTree* dataTree = (TTree*)dataFile->Get(treename.Data());\n\n dataTree->SetBranchAddress(\"recEvent\", &recEvent);\n\n \/\/check if raw event exists\n bool mcdata = false;\n bool mixdata = treename.Contains(\"mix\") || treename.Contains(\"pp\") || treename.Contains(\"mm\");\n SRawEvent* rawEvent;\n SRawMCEvent* rawMCEvent;\n if(dataTree->FindBranch(\"rawEvent\") != NULL)\n {\n if(TString(dataTree->FindBranch(\"rawEvent\")->GetClassName()) == \"SRawMCEvent\")\n {\n rawMCEvent = new SRawMCEvent;\n dataTree->SetBranchAddress(\"rawEvent\", &rawMCEvent);\n mcdata = true;\n }\n else\n {\n rawEvent = new SRawEvent;\n dataTree->SetBranchAddress(\"rawEvent\", &rawEvent);\n }\n }\n\n \/\/ output data structure\n Dimuon* p_dimuon = new Dimuon; Dimuon& dimuon = *p_dimuon;\n Spill* p_spill = new Spill; Spill& spill = *p_spill;\n Event* p_event = new Event; Event& event = *p_event;\n Track* p_posTrack = new Track; Track& posTrack = *p_posTrack;\n Track* p_negTrack = new Track; Track& negTrack = *p_negTrack;\n\n TFile* saveFile = new TFile(argv[2], \"recreate\");\n TTree* saveTree = new TTree(\"save\", \"save\");\n\n saveTree->Branch(\"dimuon\", &p_dimuon, 256000, 99);\n saveTree->Branch(\"event\", &p_event, 256000, 99);\n saveTree->Branch(\"spill\", &p_spill, 256000, 99);\n saveTree->Branch(\"posTrack\", &p_posTrack, 256000, 99);\n saveTree->Branch(\"negTrack\", &p_negTrack, 256000, 99);\n\n \/\/Initialize spill information accordingly\n spill.skipflag = mcdata || mixdata;\n map spillBank;\n if(!spill.skipflag && argc > 4)\n {\n TFile* spillFile = new TFile(argv[4]);\n TTree* spillTree = (TTree*)spillFile->Get(\"save\");\n\n spillTree->SetBranchAddress(\"spill\", &p_spill);\n\n for(int i = 0; i < spillTree->GetEntries(); ++i)\n {\n spillTree->GetEntry(i);\n spillBank.insert(map::value_type(spill.spillID, spill));\n }\n }\n\n \/\/start reading data\n int nDimuons = 0;\n double x_dummy, y_dummy, z_dummy;\n bool badSpillFlag = false;\n for(int i = 0; i < dataTree->GetEntries(); ++i)\n {\n dataTree->GetEntry(i);\n if(i % 1000 == 0)\n {\n cout << \"Converting \" << i << \"\/\" << dataTree->GetEntries() << endl;\n }\n\n \/\/general event level info\n event.runID = recEvent->getRunID();\n event.spillID = recEvent->getSpillID();\n event.eventID = recEvent->getEventID();\n event.status = recEvent->getRecStatus();\n if(mcdata)\n {\n event.MATRIX1 = rawMCEvent->isEmuTriggered() ? 1 : -1;\n event.weight = rawMCEvent->weight;\n event.intensity = 1.;\n }\n else if(mixdata)\n {\n event.MATRIX1 = 1;\n event.weight = 1.;\n event.intensity = 1.;\n }\n else\n {\n event.MATRIX1 = recEvent->isTriggeredBy(SRawEvent::MATRIX1) ? 1 : -1;\n event.weight = 1.;\n event.intensity = rawEvent->getIntensity();\n }\n\n \/\/spill level information\n if(!spill.skipflag && event.spillID != spill.spillID)\n {\n badSpillFlag = false;\n if(!spillBank.empty())\n {\n if(spillBank.find(recEvent->getSpillID()) == spillBank.end())\n {\n event.log(\"spillID does not exist!\");\n badSpillFlag = true;\n }\n else\n {\n spill = spillBank[recEvent->getSpillID()];\n }\n }\n }\n else\n {\n spill.spillID = recEvent->getSpillID();\n spill.targetPos = recEvent->getTargetPos();\n spill.TARGPOS_CONTROL = recEvent->getTargetPos();\n }\n if(badSpillFlag) continue;\n\n for(int j = 0; j < recEvent->getNDimuons(); ++j)\n {\n ++nDimuons;\n SRecDimuon recDimuon = recEvent->getDimuon(j);\n\n dimuon.dimuonID = nDimuons;\n dimuon.posTrackID = recDimuon.trackID_pos;\n dimuon.negTrackID = recDimuon.trackID_neg;\n dimuon.px1 = recDimuon.p_pos.Px();\n dimuon.py1 = recDimuon.p_pos.Py();\n dimuon.pz1 = recDimuon.p_pos.Pz();\n dimuon.px2 = recDimuon.p_neg.Px();\n dimuon.py2 = recDimuon.p_neg.Py();\n dimuon.pz2 = recDimuon.p_neg.Pz();\n dimuon.dx = recDimuon.vtx.X();\n dimuon.dy = recDimuon.vtx.Y();\n dimuon.dz = recDimuon.vtx.Z();\n dimuon.dpx = dimuon.px1 + dimuon.px2;\n dimuon.dpy = dimuon.py1 + dimuon.py2;\n dimuon.dpz = dimuon.pz1 + dimuon.pz2;\n dimuon.mass = recDimuon.mass;\n dimuon.xF = recDimuon.xF;\n dimuon.x1 = recDimuon.x1;\n dimuon.x2 = recDimuon.x2;\n dimuon.pT = recDimuon.pT;\n dimuon.costh = recDimuon.costh;\n dimuon.phi = recDimuon.phi;\n dimuon.chisq_dimuon = recDimuon.chisq_kf;\n dimuon.trackSeparation = recDimuon.vtx_pos.Z() - recDimuon.vtx_neg.Z();\n\n \/\/if(!dimuon.goodDimuon()) continue;\n if(dimuon.mass < 0.5 || dimuon.mass > 10. || dimuon.chisq_dimuon > 25. || dimuon.x1 < 0. || dimuon.x1 > 1.\n || dimuon.x2 < 0. || dimuon.x2 > 1. || dimuon.xF < -1. || dimuon.xF > 1. || fabs(dimuon.dx) > 2.\n || fabs(dimuon.dy) > 2. || dimuon.dz < -300. || dimuon.dz > 300. || fabs(dimuon.dpx) > 3.\n || fabs(dimuon.dpy) > 3. || dimuon.dpz < 30. || dimuon.dpz > 120. || fabs(dimuon.trackSeparation) > 300.) continue;\n\n SRecTrack recPosTrack = recEvent->getTrack(dimuon.posTrackID);\n posTrack.trackID = recDimuon.trackID_pos;\n posTrack.charge = 1;\n posTrack.nHits = recPosTrack.getNHits();\n posTrack.nHitsSt1 = recPosTrack.getNHitsInStation(1);\n posTrack.nHitsSt2 = recPosTrack.getNHitsInStation(2);\n posTrack.nHitsSt3 = recPosTrack.getNHitsInStation(3);\n posTrack.nHitsSt4H = recPosTrack.getNHitsInPTY();\n posTrack.nHitsSt4V = recPosTrack.getNHitsInPTX();\n posTrack.chisq = recPosTrack.getChisq();\n posTrack.chisq_dump = recPosTrack.getChisqDump();\n posTrack.chisq_target = recPosTrack.getChisqTarget();\n posTrack.chisq_upstream = recPosTrack.getChisqUpstream();\n recPosTrack.getExpPositionFast(600., x_dummy, y_dummy);\n posTrack.x1 = x_dummy;\n posTrack.y1 = y_dummy;\n posTrack.z1 = 600.;\n recPosTrack.getExpPositionFast(1910., x_dummy, y_dummy);\n posTrack.x3 = x_dummy;\n posTrack.y3 = y_dummy;\n posTrack.z3 = 1910.;\n posTrack.x0 = recPosTrack.getVtxPar(0);\n posTrack.y0 = recPosTrack.getVtxPar(1);\n posTrack.z0 = recPosTrack.getVtxPar(2);\n posTrack.xT = recPosTrack.getTargetPos().X();\n posTrack.yT = recPosTrack.getTargetPos().Y();\n posTrack.zT = recPosTrack.getTargetPos().Z();\n posTrack.xD = recPosTrack.getDumpPos().X();\n posTrack.yD = recPosTrack.getDumpPos().Y();\n posTrack.zD = recPosTrack.getDumpPos().Z();\n recPosTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);\n posTrack.px1 = x_dummy;\n posTrack.py1 = y_dummy;\n posTrack.pz1 = z_dummy;\n recPosTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);\n posTrack.px3 = x_dummy;\n posTrack.py3 = y_dummy;\n posTrack.pz3 = z_dummy;\n recPosTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);\n posTrack.px0 = x_dummy;\n posTrack.py0 = y_dummy;\n posTrack.pz0 = z_dummy;\n posTrack.pxT = recPosTrack.getTargetMom().X();\n posTrack.pyT = recPosTrack.getTargetMom().Y();\n posTrack.pzT = recPosTrack.getTargetMom().Z();\n posTrack.pxD = recPosTrack.getDumpMom().X();\n posTrack.pyD = recPosTrack.getDumpMom().Y();\n posTrack.pzD = recPosTrack.getDumpMom().Z();\n posTrack.roadID = recPosTrack.getTriggerRoad();\n posTrack.tx_PT = recPosTrack.getPTSlopeX();\n posTrack.ty_PT = recPosTrack.getPTSlopeY();\n posTrack.thbend = atan(posTrack.px3\/posTrack.pz3) - atan(posTrack.px1\/posTrack.pz1);\n posTrack.pxv = recDimuon.p_pos.Px();\n posTrack.pyv = recDimuon.p_pos.Py();\n posTrack.pzv = recDimuon.p_pos.Pz();\n\n SRecTrack recNegTrack = recEvent->getTrack(dimuon.negTrackID);\n negTrack.trackID = recDimuon.trackID_neg;\n negTrack.charge = 1;\n negTrack.nHits = recNegTrack.getNHits();\n negTrack.nHitsSt1 = recNegTrack.getNHitsInStation(1);\n negTrack.nHitsSt2 = recNegTrack.getNHitsInStation(2);\n negTrack.nHitsSt3 = recNegTrack.getNHitsInStation(3);\n negTrack.nHitsSt4H = recNegTrack.getNHitsInPTY();\n negTrack.nHitsSt4V = recNegTrack.getNHitsInPTX();\n negTrack.chisq = recNegTrack.getChisq();\n negTrack.chisq_dump = recNegTrack.getChisqDump();\n negTrack.chisq_target = recNegTrack.getChisqTarget();\n negTrack.chisq_upstream = recNegTrack.getChisqUpstream();\n recNegTrack.getExpPositionFast(600., x_dummy, y_dummy);\n negTrack.x1 = x_dummy;\n negTrack.y1 = y_dummy;\n negTrack.z1 = 600.;\n recNegTrack.getExpPositionFast(1910., x_dummy, y_dummy);\n negTrack.x3 = x_dummy;\n negTrack.y3 = y_dummy;\n negTrack.z3 = 1910.;\n negTrack.x0 = recNegTrack.getVtxPar(0);\n negTrack.y0 = recNegTrack.getVtxPar(1);\n negTrack.z0 = recNegTrack.getVtxPar(2);\n negTrack.xT = recNegTrack.getTargetPos().X();\n negTrack.yT = recNegTrack.getTargetPos().Y();\n negTrack.zT = recNegTrack.getTargetPos().Z();\n negTrack.xD = recNegTrack.getDumpPos().X();\n negTrack.yD = recNegTrack.getDumpPos().Y();\n negTrack.zD = recNegTrack.getDumpPos().Z();\n recNegTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);\n negTrack.px1 = x_dummy;\n negTrack.py1 = y_dummy;\n negTrack.pz1 = z_dummy;\n recNegTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);\n negTrack.px3 = x_dummy;\n negTrack.py3 = y_dummy;\n negTrack.pz3 = z_dummy;\n recNegTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);\n negTrack.px0 = x_dummy;\n negTrack.py0 = y_dummy;\n negTrack.pz0 = z_dummy;\n negTrack.pxT = recNegTrack.getTargetMom().X();\n negTrack.pyT = recNegTrack.getTargetMom().Y();\n negTrack.pzT = recNegTrack.getTargetMom().Z();\n negTrack.pxD = recNegTrack.getDumpMom().X();\n negTrack.pyD = recNegTrack.getDumpMom().Y();\n negTrack.pzD = recNegTrack.getDumpMom().Z();\n negTrack.roadID = recNegTrack.getTriggerRoad();\n negTrack.tx_PT = recNegTrack.getPTSlopeX();\n negTrack.ty_PT = recNegTrack.getPTSlopeY();\n negTrack.thbend = atan(negTrack.px3\/negTrack.pz3) - atan(negTrack.px1\/negTrack.pz1);\n negTrack.pxv = recDimuon.p_neg.Px();\n negTrack.pyv = recDimuon.p_neg.Py();\n negTrack.pzv = recDimuon.p_neg.Pz();\n\n saveTree->Fill();\n }\n\n recEvent->clear();\n }\n\n saveFile->cd();\n saveTree->Write();\n saveFile->Close();\n\n return EXIT_SUCCESS;\n}\nMinor update to let kTrackerResReader also read in full QIE info#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kTracker\/SRawEvent.h\"\n#include \"kTracker\/SRecEvent.h\"\n\n#include \"DataStruct.h\"\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n \/\/name of the TTree\n TString treename = argv[3];\n\n \/\/ input data structure\n SRecEvent* recEvent = new SRecEvent;\n\n TFile* dataFile = new TFile(argv[1], \"READ\");\n TTree* dataTree = (TTree*)dataFile->Get(treename.Data());\n\n dataTree->SetBranchAddress(\"recEvent\", &recEvent);\n\n \/\/check if raw event exists\n bool mcdata = false;\n bool mixdata = treename.Contains(\"mix\") || treename.Contains(\"pp\") || treename.Contains(\"mm\");\n SRawEvent* rawEvent;\n SRawMCEvent* rawMCEvent;\n if(dataTree->FindBranch(\"rawEvent\") != NULL)\n {\n if(TString(dataTree->FindBranch(\"rawEvent\")->GetClassName()) == \"SRawMCEvent\")\n {\n rawMCEvent = new SRawMCEvent;\n dataTree->SetBranchAddress(\"rawEvent\", &rawMCEvent);\n mcdata = true;\n }\n else\n {\n rawEvent = new SRawEvent;\n dataTree->SetBranchAddress(\"rawEvent\", &rawEvent);\n }\n }\n\n \/\/ output data structure\n Dimuon* p_dimuon = new Dimuon; Dimuon& dimuon = *p_dimuon;\n Spill* p_spill = new Spill; Spill& spill = *p_spill;\n Event* p_event = new Event; Event& event = *p_event;\n Track* p_posTrack = new Track; Track& posTrack = *p_posTrack;\n Track* p_negTrack = new Track; Track& negTrack = *p_negTrack;\n\n TFile* saveFile = new TFile(argv[2], \"recreate\");\n TTree* saveTree = new TTree(\"save\", \"save\");\n\n saveTree->Branch(\"dimuon\", &p_dimuon, 256000, 99);\n saveTree->Branch(\"event\", &p_event, 256000, 99);\n saveTree->Branch(\"spill\", &p_spill, 256000, 99);\n saveTree->Branch(\"posTrack\", &p_posTrack, 256000, 99);\n saveTree->Branch(\"negTrack\", &p_negTrack, 256000, 99);\n\n \/\/Initialize spill information accordingly\n spill.skipflag = mcdata || mixdata;\n map spillBank;\n if(!spill.skipflag && argc > 4)\n {\n TFile* spillFile = new TFile(argv[4]);\n TTree* spillTree = (TTree*)spillFile->Get(\"save\");\n\n spillTree->SetBranchAddress(\"spill\", &p_spill);\n\n for(int i = 0; i < spillTree->GetEntries(); ++i)\n {\n spillTree->GetEntry(i);\n spillBank.insert(map::value_type(spill.spillID, spill));\n }\n }\n\n \/\/start reading data\n int nDimuons = 0;\n double x_dummy, y_dummy, z_dummy;\n bool badSpillFlag = false;\n for(int i = 0; i < dataTree->GetEntries(); ++i)\n {\n dataTree->GetEntry(i);\n if(i % 1000 == 0)\n {\n cout << \"Converting \" << i << \"\/\" << dataTree->GetEntries() << endl;\n }\n\n \/\/general event level info\n event.runID = recEvent->getRunID();\n event.spillID = recEvent->getSpillID();\n event.eventID = recEvent->getEventID();\n event.status = recEvent->getRecStatus();\n if(mcdata)\n {\n event.MATRIX1 = rawMCEvent->isEmuTriggered() ? 1 : -1;\n event.weight = rawMCEvent->weight;\n event.intensity[16] = 1.;\n }\n else if(mixdata)\n {\n event.MATRIX1 = 1;\n event.weight = 1.;\n event.intensity[16] = 1.;\n }\n else\n {\n event.MATRIX1 = recEvent->isTriggeredBy(SRawEvent::MATRIX1) ? 1 : -1;\n event.weight = 1.;\n for(int j = -16; j <= 16; ++j) event.intensity[i+16] = rawEvent->getIntensity(i);\n }\n\n \/\/spill level information\n if(!spill.skipflag && event.spillID != spill.spillID)\n {\n badSpillFlag = false;\n if(!spillBank.empty())\n {\n if(spillBank.find(recEvent->getSpillID()) == spillBank.end())\n {\n event.log(\"spillID does not exist!\");\n badSpillFlag = true;\n }\n else\n {\n spill = spillBank[recEvent->getSpillID()];\n }\n }\n }\n else\n {\n spill.spillID = recEvent->getSpillID();\n spill.targetPos = recEvent->getTargetPos();\n spill.TARGPOS_CONTROL = recEvent->getTargetPos();\n }\n if(badSpillFlag) continue;\n\n for(int j = 0; j < recEvent->getNDimuons(); ++j)\n {\n ++nDimuons;\n SRecDimuon recDimuon = recEvent->getDimuon(j);\n\n dimuon.dimuonID = nDimuons;\n dimuon.posTrackID = recDimuon.trackID_pos;\n dimuon.negTrackID = recDimuon.trackID_neg;\n dimuon.px1 = recDimuon.p_pos.Px();\n dimuon.py1 = recDimuon.p_pos.Py();\n dimuon.pz1 = recDimuon.p_pos.Pz();\n dimuon.px2 = recDimuon.p_neg.Px();\n dimuon.py2 = recDimuon.p_neg.Py();\n dimuon.pz2 = recDimuon.p_neg.Pz();\n dimuon.dx = recDimuon.vtx.X();\n dimuon.dy = recDimuon.vtx.Y();\n dimuon.dz = recDimuon.vtx.Z();\n dimuon.dpx = dimuon.px1 + dimuon.px2;\n dimuon.dpy = dimuon.py1 + dimuon.py2;\n dimuon.dpz = dimuon.pz1 + dimuon.pz2;\n dimuon.mass = recDimuon.mass;\n dimuon.xF = recDimuon.xF;\n dimuon.x1 = recDimuon.x1;\n dimuon.x2 = recDimuon.x2;\n dimuon.pT = recDimuon.pT;\n dimuon.costh = recDimuon.costh;\n dimuon.phi = recDimuon.phi;\n dimuon.chisq_dimuon = recDimuon.chisq_kf;\n dimuon.trackSeparation = recDimuon.vtx_pos.Z() - recDimuon.vtx_neg.Z();\n\n \/\/if(!dimuon.goodDimuon()) continue;\n if(dimuon.mass < 0.5 || dimuon.mass > 10. || dimuon.chisq_dimuon > 25. || dimuon.x1 < 0. || dimuon.x1 > 1.\n || dimuon.x2 < 0. || dimuon.x2 > 1. || dimuon.xF < -1. || dimuon.xF > 1. || fabs(dimuon.dx) > 2.\n || fabs(dimuon.dy) > 2. || dimuon.dz < -300. || dimuon.dz > 300. || fabs(dimuon.dpx) > 3.\n || fabs(dimuon.dpy) > 3. || dimuon.dpz < 30. || dimuon.dpz > 120. || fabs(dimuon.trackSeparation) > 300.) continue;\n\n SRecTrack recPosTrack = recEvent->getTrack(dimuon.posTrackID);\n posTrack.trackID = recDimuon.trackID_pos;\n posTrack.charge = 1;\n posTrack.nHits = recPosTrack.getNHits();\n posTrack.nHitsSt1 = recPosTrack.getNHitsInStation(1);\n posTrack.nHitsSt2 = recPosTrack.getNHitsInStation(2);\n posTrack.nHitsSt3 = recPosTrack.getNHitsInStation(3);\n posTrack.nHitsSt4H = recPosTrack.getNHitsInPTY();\n posTrack.nHitsSt4V = recPosTrack.getNHitsInPTX();\n posTrack.chisq = recPosTrack.getChisq();\n posTrack.chisq_dump = recPosTrack.getChisqDump();\n posTrack.chisq_target = recPosTrack.getChisqTarget();\n posTrack.chisq_upstream = recPosTrack.getChisqUpstream();\n recPosTrack.getExpPositionFast(600., x_dummy, y_dummy);\n posTrack.x1 = x_dummy;\n posTrack.y1 = y_dummy;\n posTrack.z1 = 600.;\n recPosTrack.getExpPositionFast(1910., x_dummy, y_dummy);\n posTrack.x3 = x_dummy;\n posTrack.y3 = y_dummy;\n posTrack.z3 = 1910.;\n posTrack.x0 = recPosTrack.getVtxPar(0);\n posTrack.y0 = recPosTrack.getVtxPar(1);\n posTrack.z0 = recPosTrack.getVtxPar(2);\n posTrack.xT = recPosTrack.getTargetPos().X();\n posTrack.yT = recPosTrack.getTargetPos().Y();\n posTrack.zT = recPosTrack.getTargetPos().Z();\n posTrack.xD = recPosTrack.getDumpPos().X();\n posTrack.yD = recPosTrack.getDumpPos().Y();\n posTrack.zD = recPosTrack.getDumpPos().Z();\n recPosTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);\n posTrack.px1 = x_dummy;\n posTrack.py1 = y_dummy;\n posTrack.pz1 = z_dummy;\n recPosTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);\n posTrack.px3 = x_dummy;\n posTrack.py3 = y_dummy;\n posTrack.pz3 = z_dummy;\n recPosTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);\n posTrack.px0 = x_dummy;\n posTrack.py0 = y_dummy;\n posTrack.pz0 = z_dummy;\n posTrack.pxT = recPosTrack.getTargetMom().X();\n posTrack.pyT = recPosTrack.getTargetMom().Y();\n posTrack.pzT = recPosTrack.getTargetMom().Z();\n posTrack.pxD = recPosTrack.getDumpMom().X();\n posTrack.pyD = recPosTrack.getDumpMom().Y();\n posTrack.pzD = recPosTrack.getDumpMom().Z();\n posTrack.roadID = recPosTrack.getTriggerRoad();\n posTrack.tx_PT = recPosTrack.getPTSlopeX();\n posTrack.ty_PT = recPosTrack.getPTSlopeY();\n posTrack.thbend = atan(posTrack.px3\/posTrack.pz3) - atan(posTrack.px1\/posTrack.pz1);\n posTrack.pxv = recDimuon.p_pos.Px();\n posTrack.pyv = recDimuon.p_pos.Py();\n posTrack.pzv = recDimuon.p_pos.Pz();\n\n SRecTrack recNegTrack = recEvent->getTrack(dimuon.negTrackID);\n negTrack.trackID = recDimuon.trackID_neg;\n negTrack.charge = 1;\n negTrack.nHits = recNegTrack.getNHits();\n negTrack.nHitsSt1 = recNegTrack.getNHitsInStation(1);\n negTrack.nHitsSt2 = recNegTrack.getNHitsInStation(2);\n negTrack.nHitsSt3 = recNegTrack.getNHitsInStation(3);\n negTrack.nHitsSt4H = recNegTrack.getNHitsInPTY();\n negTrack.nHitsSt4V = recNegTrack.getNHitsInPTX();\n negTrack.chisq = recNegTrack.getChisq();\n negTrack.chisq_dump = recNegTrack.getChisqDump();\n negTrack.chisq_target = recNegTrack.getChisqTarget();\n negTrack.chisq_upstream = recNegTrack.getChisqUpstream();\n recNegTrack.getExpPositionFast(600., x_dummy, y_dummy);\n negTrack.x1 = x_dummy;\n negTrack.y1 = y_dummy;\n negTrack.z1 = 600.;\n recNegTrack.getExpPositionFast(1910., x_dummy, y_dummy);\n negTrack.x3 = x_dummy;\n negTrack.y3 = y_dummy;\n negTrack.z3 = 1910.;\n negTrack.x0 = recNegTrack.getVtxPar(0);\n negTrack.y0 = recNegTrack.getVtxPar(1);\n negTrack.z0 = recNegTrack.getVtxPar(2);\n negTrack.xT = recNegTrack.getTargetPos().X();\n negTrack.yT = recNegTrack.getTargetPos().Y();\n negTrack.zT = recNegTrack.getTargetPos().Z();\n negTrack.xD = recNegTrack.getDumpPos().X();\n negTrack.yD = recNegTrack.getDumpPos().Y();\n negTrack.zD = recNegTrack.getDumpPos().Z();\n recNegTrack.getExpMomentumFast(600., x_dummy, y_dummy, z_dummy);\n negTrack.px1 = x_dummy;\n negTrack.py1 = y_dummy;\n negTrack.pz1 = z_dummy;\n recNegTrack.getExpMomentumFast(1910., x_dummy, y_dummy, z_dummy);\n negTrack.px3 = x_dummy;\n negTrack.py3 = y_dummy;\n negTrack.pz3 = z_dummy;\n recNegTrack.getMomentumVertex(x_dummy, y_dummy, z_dummy);\n negTrack.px0 = x_dummy;\n negTrack.py0 = y_dummy;\n negTrack.pz0 = z_dummy;\n negTrack.pxT = recNegTrack.getTargetMom().X();\n negTrack.pyT = recNegTrack.getTargetMom().Y();\n negTrack.pzT = recNegTrack.getTargetMom().Z();\n negTrack.pxD = recNegTrack.getDumpMom().X();\n negTrack.pyD = recNegTrack.getDumpMom().Y();\n negTrack.pzD = recNegTrack.getDumpMom().Z();\n negTrack.roadID = recNegTrack.getTriggerRoad();\n negTrack.tx_PT = recNegTrack.getPTSlopeX();\n negTrack.ty_PT = recNegTrack.getPTSlopeY();\n negTrack.thbend = atan(negTrack.px3\/negTrack.pz3) - atan(negTrack.px1\/negTrack.pz1);\n negTrack.pxv = recDimuon.p_neg.Px();\n negTrack.pyv = recDimuon.p_neg.Py();\n negTrack.pzv = recDimuon.p_neg.Pz();\n\n saveTree->Fill();\n }\n\n recEvent->clear();\n }\n\n saveFile->cd();\n saveTree->Write();\n saveFile->Close();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * fontcolour.cpp - font and colour chooser widget\n * Program: kalarm\n * (C) 2001 by David Jarvie software@astrojar.org.uk\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., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"fontcolour.h\"\n#include \"fontcolour.moc\"\n\n\nFontColourChooser::FontColourChooser(QWidget *parent, const char *name,\n\t bool onlyFixed, const QStringList &fontList,\n\t bool makeFrame, const QString& frameLabel, bool fg, int visibleListSize)\n\t: QWidget(parent, name)\n{\n\tQVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint());\n\tQWidget* page = this;\n\tif (makeFrame)\n\t{\n\t\tpage = new QGroupBox(i18n(frameLabel), this);\n\t\ttopLayout->addWidget(page);\n\t\ttopLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());\n\t\ttopLayout->addSpacing(fontMetrics().lineSpacing()\/2);\n\t}\n\n\tQGridLayout* grid = new QGridLayout(topLayout, (fg ? 3 : 2), 2);\n\tgrid->addRowSpacing(0, KDialog::marginHint());\n\tint gridRow = 1;\n\n\tQLabel* label;\n\tif (fg)\n\t{\n\t\tlabel = new QLabel(i18n(\"Default foreground color:\"), page);\n\t\tgrid->addWidget(label, gridRow, 0, AlignRight);\n\t\tlabel->setFixedSize(label->sizeHint());\n\t\tm_fgColourButton = new ColourCombo(page);\n\t\tgrid->addWidget(m_fgColourButton, gridRow, 1, AlignRight);\n\t\tconnect(m_fgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));\n\t\t++gridRow;\n\t}\n\n\tlabel = new QLabel(i18n(\"Default background color:\"), page);\n\tlabel->setMinimumSize(label->sizeHint());\n\tgrid->addWidget(label, gridRow, 0);\n\tm_bgColourButton = new ColourCombo(page);\n\tm_bgColourButton->setMinimumSize(m_bgColourButton->sizeHint());\n\tgrid->addWidget(m_bgColourButton, gridRow, 1, AlignRight);\n\tconnect(m_bgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));\n\n\tm_fontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize);\n\ttopLayout->addWidget(m_fontChooser);\n}\n\nFontColourChooser::~FontColourChooser()\n{\n}\n\nvoid FontColourChooser::setFgColour(const QColor& colour)\n{\n\tif (m_fgColourButton)\n\t{\n\t\tm_fgColourButton->setColour(colour);\n\t\tm_fontChooser->setColor(colour);\n\t}\n}\n\nvoid FontColourChooser::setBgColour(const QColor& colour)\n{\n\tm_bgColourButton->setColour(colour);\n\tm_fontChooser->setBackgroundColor(colour);\n}\n\nvoid FontColourChooser::setSampleColour()\n{\n\tQColor bg = m_bgColourButton->color();\n\tm_fontChooser->setBackgroundColor(bg);\n\tQColor fg = fgColour();\n\tm_fontChooser->setColor(fg);\n}\n\nQColor FontColourChooser::fgColour() const\n{\n\tQColor bg = m_bgColourButton->color();\n\tQPalette pal(bg, bg);\n\treturn pal.color(QPalette::Active, QColorGroup::Text);\n}\nBetter label text\/*\n * fontcolour.cpp - font and colour chooser widget\n * Program: kalarm\n * (C) 2001, 2002 by David Jarvie software@astrojar.org.uk\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., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"fontcolour.moc\"\n\n\nFontColourChooser::FontColourChooser(QWidget *parent, const char *name,\n bool onlyFixed, const QStringList &fontList,\n bool makeFrame, const QString& frameLabel, bool fg, int visibleListSize)\n : QWidget(parent, name)\n{\n QVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint());\n QWidget* page = this;\n if (makeFrame)\n {\n page = new QGroupBox(i18n(frameLabel), this);\n topLayout->addWidget(page);\n topLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint());\n topLayout->addSpacing(fontMetrics().lineSpacing()\/2);\n }\n\n QGridLayout* grid = new QGridLayout(topLayout, (fg ? 3 : 2), 2);\n grid->addRowSpacing(0, KDialog::marginHint());\n int gridRow = 1;\n\n QLabel* label;\n if (fg)\n {\n label = new QLabel(i18n(\"Foreground color:\"), page);\n grid->addWidget(label, gridRow, 0, AlignRight);\n label->setFixedSize(label->sizeHint());\n m_fgColourButton = new ColourCombo(page);\n grid->addWidget(m_fgColourButton, gridRow, 1, AlignRight);\n connect(m_fgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));\n ++gridRow;\n }\n\n label = new QLabel(i18n(\"Background color:\"), page);\n label->setMinimumSize(label->sizeHint());\n grid->addWidget(label, gridRow, 0);\n m_bgColourButton = new ColourCombo(page);\n m_bgColourButton->setMinimumSize(m_bgColourButton->sizeHint());\n grid->addWidget(m_bgColourButton, gridRow, 1, AlignRight);\n connect(m_bgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour()));\n\n m_fontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize);\n topLayout->addWidget(m_fontChooser);\n}\n\nFontColourChooser::~FontColourChooser()\n{\n}\n\nvoid FontColourChooser::setFgColour(const QColor& colour)\n{\n if (m_fgColourButton)\n {\n m_fgColourButton->setColour(colour);\n m_fontChooser->setColor(colour);\n }\n}\n\nvoid FontColourChooser::setBgColour(const QColor& colour)\n{\n m_bgColourButton->setColour(colour);\n m_fontChooser->setBackgroundColor(colour);\n}\n\nvoid FontColourChooser::setSampleColour()\n{\n QColor bg = m_bgColourButton->color();\n m_fontChooser->setBackgroundColor(bg);\n QColor fg = fgColour();\n m_fontChooser->setColor(fg);\n}\n\nQColor FontColourChooser::fgColour() const\n{\n QColor bg = m_bgColourButton->color();\n QPalette pal(bg, bg);\n return pal.color(QPalette::Active, QColorGroup::Text);\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2001 Christoph Cullmann \n Copyright (C) 2002 Joseph Wenninger \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 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#include \"kateapp.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass KateWaiter : public QObject {\n Q_OBJECT\n \n private:\n QCoreApplication *m_app;\n \n public:\n KateWaiter (QCoreApplication *app) : QObject (app), m_app (app) {\n }\n\n public Q_SLOTS:\n void exiting () {\n m_app->quit ();\n }\n};\n\nextern \"C\" KDE_EXPORT int kdemain( int argc, char **argv )\n{\n \/\/ here we go, construct the Kate version\n QByteArray kateVersion = KateApp::kateVersion().toLatin1();\n\n KAboutData aboutData (\"kate\", 0, ki18n(\"Kate\"), kateVersion,\n ki18n( \"Kate - Advanced Text Editor\" ), KAboutData::License_LGPL_V2,\n ki18n( \"(c) 2000-2005 The Kate Authors\" ), KLocalizedString(), \"http:\/\/www.kate-editor.org\");\n aboutData.setOrganizationDomain(\"kde.org\");\n aboutData.addAuthor (ki18n(\"Christoph Cullmann\"), ki18n(\"Maintainer\"), \"cullmann@kde.org\", \"http:\/\/www.babylon2k.de\");\n aboutData.addAuthor (ki18n(\"Anders Lund\"), ki18n(\"Core Developer\"), \"anders@alweb.dk\", \"http:\/\/www.alweb.dk\");\n aboutData.addAuthor (ki18n(\"Joseph Wenninger\"), ki18n(\"Core Developer\"), \"jowenn@kde.org\", \"http:\/\/stud3.tuwien.ac.at\/~e9925371\");\n aboutData.addAuthor (ki18n(\"Hamish Rodda\"), ki18n(\"Core Developer\"), \"rodda@kde.org\");\n aboutData.addAuthor (ki18n(\"Dominik Haumann\"), ki18n(\"Developer & Highlight wizard\"), \"dhdev@gmx.de\");\n aboutData.addAuthor (ki18n(\"Waldo Bastian\"), ki18n( \"The cool buffersystem\" ), \"bastian@kde.org\" );\n aboutData.addAuthor (ki18n(\"Charles Samuels\"), ki18n(\"The Editing Commands\"), \"charles@kde.org\");\n aboutData.addAuthor (ki18n(\"Matt Newell\"), ki18n(\"Testing, ...\"), \"newellm@proaxis.com\");\n aboutData.addAuthor (ki18n(\"Michael Bartl\"), ki18n(\"Former Core Developer\"), \"michael.bartl1@chello.at\");\n aboutData.addAuthor (ki18n(\"Michael McCallum\"), ki18n(\"Core Developer\"), \"gholam@xtra.co.nz\");\n aboutData.addAuthor (ki18n(\"Jochen Wilhemly\"), ki18n( \"KWrite Author\" ), \"digisnap@cs.tu-berlin.de\" );\n aboutData.addAuthor (ki18n(\"Michael Koch\"), ki18n(\"KWrite port to KParts\"), \"koch@kde.org\");\n aboutData.addAuthor (ki18n(\"Christian Gebauer\"), KLocalizedString(), \"gebauer@kde.org\" );\n aboutData.addAuthor (ki18n(\"Simon Hausmann\"), KLocalizedString(), \"hausmann@kde.org\" );\n aboutData.addAuthor (ki18n(\"Glen Parker\"), ki18n(\"KWrite Undo History, Kspell integration\"), \"glenebob@nwlink.com\");\n aboutData.addAuthor (ki18n(\"Scott Manson\"), ki18n(\"KWrite XML Syntax highlighting support\"), \"sdmanson@alltel.net\");\n aboutData.addAuthor (ki18n(\"John Firebaugh\"), ki18n(\"Patches and more\"), \"jfirebaugh@kde.org\");\n\n aboutData.addCredit (ki18n(\"Matteo Merli\"), ki18n(\"Highlighting for RPM Spec-Files, Perl, Diff and more\"), \"merlim@libero.it\");\n aboutData.addCredit (ki18n(\"Rocky Scaletta\"), ki18n(\"Highlighting for VHDL\"), \"rocky@purdue.edu\");\n aboutData.addCredit (ki18n(\"Yury Lebedev\"), ki18n(\"Highlighting for SQL\"));\n aboutData.addCredit (ki18n(\"Chris Ross\"), ki18n(\"Highlighting for Ferite\"));\n aboutData.addCredit (ki18n(\"Nick Roux\"), ki18n(\"Highlighting for ILERPG\"));\n aboutData.addCredit (ki18n(\"Carsten Niehaus\"), ki18n(\"Highlighting for LaTeX\"));\n aboutData.addCredit (ki18n(\"Per Wigren\"), ki18n(\"Highlighting for Makefiles, Python\"));\n aboutData.addCredit (ki18n(\"Jan Fritz\"), ki18n(\"Highlighting for Python\"));\n aboutData.addCredit (ki18n(\"Daniel Naber\"));\n aboutData.addCredit (ki18n(\"Roland Pabel\"), ki18n(\"Highlighting for Scheme\"));\n aboutData.addCredit (ki18n(\"Cristi Dumitrescu\"), ki18n(\"PHP Keyword\/Datatype list\"));\n aboutData.addCredit (ki18n(\"Carsten Pfeiffer\"), ki18n(\"Very nice help\"));\n aboutData.addCredit (ki18n(\"All people who have contributed and I have forgotten to mention\"));\n\n \/\/ command line args init and co\n KCmdLineArgs::init (argc, argv, &aboutData);\n\n KCmdLineOptions options;\n options.add(\"s\");\n options.add(\"start \", ki18n(\"Start Kate with a given session\"));\n options.add(\"n\");\n options.add(\"new\", ki18n(\"Force start of a new kate instance\"));\n options.add(\"b\");\n options.add(\"block\", ki18n(\"If using an already running kate instance, block until it exits\"));\n options.add(\"p\");\n options.add(\"pid \", ki18n(\"Only try to reuse kate instance with this pid\"));\n options.add(\"e\");\n options.add(\"encoding \", ki18n(\"Set encoding for the file to open\"));\n options.add(\"l\");\n options.add(\"line \", ki18n(\"Navigate to this line\"));\n options.add(\"c\");\n options.add(\"column \", ki18n(\"Navigate to this column\"));\n options.add(\"i\");\n options.add(\"stdin\", ki18n(\"Read the contents of stdin\"));\n options.add(\"u\");\n options.add(\"use\", ki18n(\"Reuse existing Kate instance, default, only for compatiblity\"));\n options.add(\"+[URL]\", ki18n(\"Document to open\"));\n KCmdLineArgs::addCmdLineOptions (options);\n KCmdLineArgs::addTempFileOption();\n\n \/\/ get our command line args ;)\n KCmdLineArgs* args = KCmdLineArgs::parsedArgs();\n\n \/\/ now, first try to contact running kate instance if needed\n if (!args->isSet(\"new\"))\n {\n \/\/ inialize the dbus stuff...\n \/\/ bus interface\n QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface ();\n \n \/\/ service name....\n QString serviceName;\n \n \/\/ two possibilities: pid given or not...\n if ( (args->isSet(\"pid\")) || (!qgetenv(\"KATE_PID\").isEmpty()))\n {\n QString usePid;\n if (args->isSet(\"pid\")) usePid = args->getOption(\"pid\");\n else usePid = QString::fromLocal8Bit(qgetenv(\"KATE_PID\"));\n \n serviceName = \"org.kde.kate-\" + usePid;\n }\n else \/\/ pid not given, try to guess it....\n {\n QDBusReply servicesReply = i->registeredServiceNames ();\n QStringList services;\n if (servicesReply.isValid())\n services = servicesReply.value ();\n \n foreach (const QString &s, services)\n {\n if (s.startsWith (\"org.kde.kate-\"))\n {\n serviceName = s;\n break;\n }\n }\n }\n \n \/\/ no already running instance found and no specific pid given, start new instance...\n bool foundRunningService = false;\n if (!serviceName.isEmpty ())\n {\n QDBusReply there = i->isServiceRegistered (serviceName);\n foundRunningService = there.isValid () && there.value();\n }\n \n if (foundRunningService)\n {\n \/\/ open given session\n if (args->isSet (\"start\"))\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"activateSession\");\n\n QList dbusargs;\n dbusargs.append(args->getOption(\"start\"));\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n QString enc = args->isSet(\"encoding\") ? args->getOption(\"encoding\") : QByteArray(\"\");\n\n bool tempfileSet = KCmdLineArgs::isTempFileSet();\n\n \/\/ open given files...\n for (int z = 0; z < args->count(); z++)\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"openUrl\");\n\n QList dbusargs;\n dbusargs.append(args->url(z).url());\n dbusargs.append(enc);\n dbusargs.append(tempfileSet);\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n \n if( args->isSet( \"stdin\" ) )\n {\n QTextStream input(stdin, QIODevice::ReadOnly);\n\n \/\/ set chosen codec\n QTextCodec *codec = args->isSet(\"encoding\") ? QTextCodec::codecForName(args->getOption(\"encoding\").toUtf8()) : 0;\n\n if (codec)\n input.setCodec (codec);\n\n QString line;\n QString text;\n\n do\n {\n line = input.readLine();\n text.append( line + '\\n' );\n }\n while( !line.isNull() );\n\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"openInput\");\n\n QList dbusargs;\n dbusargs.append(text);\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n int line = 0;\n int column = 0;\n bool nav = false;\n\n if (args->isSet (\"line\"))\n {\n line = args->getOption (\"line\").toInt() - 1;\n nav = true;\n }\n\n if (args->isSet (\"column\"))\n {\n column = args->getOption (\"column\").toInt() - 1;\n nav = true;\n }\n\n if (nav)\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"setCursor\");\n\n QList args;\n args.append(line);\n args.append(column);\n m.setArguments(args);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n \/\/ application object to have event loop\n QCoreApplication app (argc, argv);\n \n \/\/ connect dbus signal\n if (args->isSet( \"block\" )) {\n KateWaiter *waiter = new KateWaiter (&app);\n QDBusConnection::sessionBus().connect(serviceName, QString(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"exiting\", waiter, SLOT(exiting()));\n }\n \n#ifdef Q_WS_X11\n \/\/ make the world happy, we are started, kind of...\n KStartupInfo::appStarted ();\n#endif\n\n \/\/ this will wait until exiting is emited by the used instance, if wanted...\n return args->isSet( \"block\" ) ? app.exec () : 0;\n }\n }\n\n \/\/ construct the real kate app object ;)\n KateApp app (args);\n if (app.shouldExit()) return 0;\n\n \/\/ execute ourself ;)\n return app.exec();\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n\n#include \"katemain.moc\"\nsafety net for kate, exit if the main app did leave the dbus\/* This file is part of the KDE project\n Copyright (C) 2001 Christoph Cullmann \n Copyright (C) 2002 Joseph Wenninger \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 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#include \"kateapp.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass KateWaiter : public QObject {\n Q_OBJECT\n \n private:\n QCoreApplication *m_app;\n QString m_service;\n \n public:\n KateWaiter (QCoreApplication *app, const QString &service)\n : QObject (app), m_app (app), m_service (service) {\n connect ( QDBusConnection::sessionBus().interface(), SIGNAL( serviceOwnerChanged( QString, QString, QString ) )\n , this, SLOT(serviceOwnerChanged( QString, QString, QString )) ); \n }\n\n public Q_SLOTS:\n void exiting () {\n m_app->quit ();\n }\n \n void serviceOwnerChanged( const QString & name, const QString &, const QString &) {\n if (name != m_service)\n return;\n \n m_app->quit ();\n }\n};\n\nextern \"C\" KDE_EXPORT int kdemain( int argc, char **argv )\n{\n \/\/ here we go, construct the Kate version\n QByteArray kateVersion = KateApp::kateVersion().toLatin1();\n\n KAboutData aboutData (\"kate\", 0, ki18n(\"Kate\"), kateVersion,\n ki18n( \"Kate - Advanced Text Editor\" ), KAboutData::License_LGPL_V2,\n ki18n( \"(c) 2000-2005 The Kate Authors\" ), KLocalizedString(), \"http:\/\/www.kate-editor.org\");\n aboutData.setOrganizationDomain(\"kde.org\");\n aboutData.addAuthor (ki18n(\"Christoph Cullmann\"), ki18n(\"Maintainer\"), \"cullmann@kde.org\", \"http:\/\/www.babylon2k.de\");\n aboutData.addAuthor (ki18n(\"Anders Lund\"), ki18n(\"Core Developer\"), \"anders@alweb.dk\", \"http:\/\/www.alweb.dk\");\n aboutData.addAuthor (ki18n(\"Joseph Wenninger\"), ki18n(\"Core Developer\"), \"jowenn@kde.org\", \"http:\/\/stud3.tuwien.ac.at\/~e9925371\");\n aboutData.addAuthor (ki18n(\"Hamish Rodda\"), ki18n(\"Core Developer\"), \"rodda@kde.org\");\n aboutData.addAuthor (ki18n(\"Dominik Haumann\"), ki18n(\"Developer & Highlight wizard\"), \"dhdev@gmx.de\");\n aboutData.addAuthor (ki18n(\"Waldo Bastian\"), ki18n( \"The cool buffersystem\" ), \"bastian@kde.org\" );\n aboutData.addAuthor (ki18n(\"Charles Samuels\"), ki18n(\"The Editing Commands\"), \"charles@kde.org\");\n aboutData.addAuthor (ki18n(\"Matt Newell\"), ki18n(\"Testing, ...\"), \"newellm@proaxis.com\");\n aboutData.addAuthor (ki18n(\"Michael Bartl\"), ki18n(\"Former Core Developer\"), \"michael.bartl1@chello.at\");\n aboutData.addAuthor (ki18n(\"Michael McCallum\"), ki18n(\"Core Developer\"), \"gholam@xtra.co.nz\");\n aboutData.addAuthor (ki18n(\"Jochen Wilhemly\"), ki18n( \"KWrite Author\" ), \"digisnap@cs.tu-berlin.de\" );\n aboutData.addAuthor (ki18n(\"Michael Koch\"), ki18n(\"KWrite port to KParts\"), \"koch@kde.org\");\n aboutData.addAuthor (ki18n(\"Christian Gebauer\"), KLocalizedString(), \"gebauer@kde.org\" );\n aboutData.addAuthor (ki18n(\"Simon Hausmann\"), KLocalizedString(), \"hausmann@kde.org\" );\n aboutData.addAuthor (ki18n(\"Glen Parker\"), ki18n(\"KWrite Undo History, Kspell integration\"), \"glenebob@nwlink.com\");\n aboutData.addAuthor (ki18n(\"Scott Manson\"), ki18n(\"KWrite XML Syntax highlighting support\"), \"sdmanson@alltel.net\");\n aboutData.addAuthor (ki18n(\"John Firebaugh\"), ki18n(\"Patches and more\"), \"jfirebaugh@kde.org\");\n\n aboutData.addCredit (ki18n(\"Matteo Merli\"), ki18n(\"Highlighting for RPM Spec-Files, Perl, Diff and more\"), \"merlim@libero.it\");\n aboutData.addCredit (ki18n(\"Rocky Scaletta\"), ki18n(\"Highlighting for VHDL\"), \"rocky@purdue.edu\");\n aboutData.addCredit (ki18n(\"Yury Lebedev\"), ki18n(\"Highlighting for SQL\"));\n aboutData.addCredit (ki18n(\"Chris Ross\"), ki18n(\"Highlighting for Ferite\"));\n aboutData.addCredit (ki18n(\"Nick Roux\"), ki18n(\"Highlighting for ILERPG\"));\n aboutData.addCredit (ki18n(\"Carsten Niehaus\"), ki18n(\"Highlighting for LaTeX\"));\n aboutData.addCredit (ki18n(\"Per Wigren\"), ki18n(\"Highlighting for Makefiles, Python\"));\n aboutData.addCredit (ki18n(\"Jan Fritz\"), ki18n(\"Highlighting for Python\"));\n aboutData.addCredit (ki18n(\"Daniel Naber\"));\n aboutData.addCredit (ki18n(\"Roland Pabel\"), ki18n(\"Highlighting for Scheme\"));\n aboutData.addCredit (ki18n(\"Cristi Dumitrescu\"), ki18n(\"PHP Keyword\/Datatype list\"));\n aboutData.addCredit (ki18n(\"Carsten Pfeiffer\"), ki18n(\"Very nice help\"));\n aboutData.addCredit (ki18n(\"All people who have contributed and I have forgotten to mention\"));\n\n \/\/ command line args init and co\n KCmdLineArgs::init (argc, argv, &aboutData);\n\n KCmdLineOptions options;\n options.add(\"s\");\n options.add(\"start \", ki18n(\"Start Kate with a given session\"));\n options.add(\"n\");\n options.add(\"new\", ki18n(\"Force start of a new kate instance\"));\n options.add(\"b\");\n options.add(\"block\", ki18n(\"If using an already running kate instance, block until it exits\"));\n options.add(\"p\");\n options.add(\"pid \", ki18n(\"Only try to reuse kate instance with this pid\"));\n options.add(\"e\");\n options.add(\"encoding \", ki18n(\"Set encoding for the file to open\"));\n options.add(\"l\");\n options.add(\"line \", ki18n(\"Navigate to this line\"));\n options.add(\"c\");\n options.add(\"column \", ki18n(\"Navigate to this column\"));\n options.add(\"i\");\n options.add(\"stdin\", ki18n(\"Read the contents of stdin\"));\n options.add(\"u\");\n options.add(\"use\", ki18n(\"Reuse existing Kate instance, default, only for compatiblity\"));\n options.add(\"+[URL]\", ki18n(\"Document to open\"));\n KCmdLineArgs::addCmdLineOptions (options);\n KCmdLineArgs::addTempFileOption();\n\n \/\/ get our command line args ;)\n KCmdLineArgs* args = KCmdLineArgs::parsedArgs();\n\n \/\/ now, first try to contact running kate instance if needed\n if (!args->isSet(\"new\"))\n {\n \/\/ inialize the dbus stuff...\n \/\/ bus interface\n QDBusConnectionInterface *i = QDBusConnection::sessionBus().interface ();\n \n \/\/ service name....\n QString serviceName;\n \n \/\/ two possibilities: pid given or not...\n if ( (args->isSet(\"pid\")) || (!qgetenv(\"KATE_PID\").isEmpty()))\n {\n QString usePid;\n if (args->isSet(\"pid\")) usePid = args->getOption(\"pid\");\n else usePid = QString::fromLocal8Bit(qgetenv(\"KATE_PID\"));\n \n serviceName = \"org.kde.kate-\" + usePid;\n }\n else \/\/ pid not given, try to guess it....\n {\n QDBusReply servicesReply = i->registeredServiceNames ();\n QStringList services;\n if (servicesReply.isValid())\n services = servicesReply.value ();\n \n foreach (const QString &s, services)\n {\n if (s.startsWith (\"org.kde.kate-\"))\n {\n serviceName = s;\n break;\n }\n }\n }\n \n \/\/ no already running instance found and no specific pid given, start new instance...\n bool foundRunningService = false;\n if (!serviceName.isEmpty ())\n {\n QDBusReply there = i->isServiceRegistered (serviceName);\n foundRunningService = there.isValid () && there.value();\n }\n \n if (foundRunningService)\n {\n \/\/ open given session\n if (args->isSet (\"start\"))\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"activateSession\");\n\n QList dbusargs;\n dbusargs.append(args->getOption(\"start\"));\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n QString enc = args->isSet(\"encoding\") ? args->getOption(\"encoding\") : QByteArray(\"\");\n\n bool tempfileSet = KCmdLineArgs::isTempFileSet();\n\n \/\/ open given files...\n for (int z = 0; z < args->count(); z++)\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"openUrl\");\n\n QList dbusargs;\n dbusargs.append(args->url(z).url());\n dbusargs.append(enc);\n dbusargs.append(tempfileSet);\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n \n if( args->isSet( \"stdin\" ) )\n {\n QTextStream input(stdin, QIODevice::ReadOnly);\n\n \/\/ set chosen codec\n QTextCodec *codec = args->isSet(\"encoding\") ? QTextCodec::codecForName(args->getOption(\"encoding\").toUtf8()) : 0;\n\n if (codec)\n input.setCodec (codec);\n\n QString line;\n QString text;\n\n do\n {\n line = input.readLine();\n text.append( line + '\\n' );\n }\n while( !line.isNull() );\n\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"openInput\");\n\n QList dbusargs;\n dbusargs.append(text);\n m.setArguments(dbusargs);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n int line = 0;\n int column = 0;\n bool nav = false;\n\n if (args->isSet (\"line\"))\n {\n line = args->getOption (\"line\").toInt() - 1;\n nav = true;\n }\n\n if (args->isSet (\"column\"))\n {\n column = args->getOption (\"column\").toInt() - 1;\n nav = true;\n }\n\n if (nav)\n {\n QDBusMessage m = QDBusMessage::createMethodCall (serviceName,\n QLatin1String(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"setCursor\");\n\n QList args;\n args.append(line);\n args.append(column);\n m.setArguments(args);\n\n QDBusConnection::sessionBus().call (m);\n }\n\n \/\/ application object to have event loop\n QCoreApplication app (argc, argv);\n \n \/\/ connect dbus signal\n if (args->isSet( \"block\" )) {\n KateWaiter *waiter = new KateWaiter (&app, serviceName);\n QDBusConnection::sessionBus().connect(serviceName, QString(\"\/MainApplication\"), \"org.kde.Kate.Application\", \"exiting\", waiter, SLOT(exiting()));\n }\n \n#ifdef Q_WS_X11\n \/\/ make the world happy, we are started, kind of...\n KStartupInfo::appStarted ();\n#endif\n\n \/\/ this will wait until exiting is emited by the used instance, if wanted...\n return args->isSet( \"block\" ) ? app.exec () : 0;\n }\n }\n\n \/\/ construct the real kate app object ;)\n KateApp app (args);\n if (app.shouldExit()) return 0;\n\n \/\/ execute ourself ;)\n return app.exec();\n}\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n\n#include \"katemain.moc\"\n<|endoftext|>"} {"text":"\/\/\/ Game side\n#include \n#include \n#include \n#include \n\/\/ Components\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/\/ Engine side\n#include \n\/\/ Graphic\n#include \n#include \n#include \n\n\/\/ AI\n#include \n#include \n#include \n\/\/ Debug?\n#include \n\n\/\/ Timing\n#include \n\n\/\/ Physics\n\n\/\/\/ DEBUG physics TODOJB remove\n#include \n#include \n\n#include \n\n\/\/\/ Standard\n#include \n#include \n\nnamespace Doremi\n{\n namespace Core\n {\n LevelLoaderServer::LevelLoaderServer(const DoremiEngine::Core::SharedContext& p_sharedContext) : LevelLoader(p_sharedContext) {}\n\n LevelLoaderServer::~LevelLoaderServer() {}\n\n void LevelLoaderServer::LoadLevel(const std::string& p_fileName)\n {\n using namespace std;\n string fileName = m_sharedContext.GetWorkingDirectory() + p_fileName;\n ifstream ifs;\n ifs.open(fileName, ifstream::in | ofstream::binary);\n if(ifs.is_open() == true)\n {\n \/\/ testa o lsa lite\n\n \/\/ scene name\n int sceneNameSize;\n ifs.read((char*)&sceneNameSize, sizeof(int));\n char* sceneName = new char[sceneNameSize];\n ifs.read((char*)sceneName, sizeof(char) * sceneNameSize);\n\n \/\/ how much different stuff there is\n int nrMats, nrTransforms, nrMeshes, nrLights;\n ifs.read((char*)&nrMats, sizeof(int));\n ifs.read((char*)&nrTransforms, sizeof(int));\n ifs.read((char*)&nrMeshes, sizeof(int));\n ifs.read((char*)&nrLights, sizeof(int));\n\n LoadMaterial(ifs, nrMats);\n LoadTransforms(ifs, nrTransforms);\n LoadMeshes(ifs, nrMeshes);\n LoadLights(ifs, nrLights);\n BuildEntities();\n LoadTriggers();\n }\n else\n {\n \/\/ TODOXX DO something here?\n }\n }\n\n bool LevelLoaderServer::BuildComponents(int p_entityId, int p_meshCouplingID, std::vector& p_vertexBuffer)\n {\n bool r_shouldBuildPhysics = true;\n\n const ObjectCouplingInfo& meshCoupling = m_meshCoupling[p_meshCouplingID];\n \/\/ Adds transform components to the world\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::Transform);\n TransformComponent* transComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n\n transComp->position = m_transforms[meshCoupling.transformName].translation;\n transComp->rotation = m_transforms[meshCoupling.transformName].rotation;\n transComp->scale = m_transforms[meshCoupling.transformName].scale;\n\n\n DoremiEditor::Core::TransformData transformationData = m_transforms[meshCoupling.transformName];\n\n if(transformationData.attributes.isAIground)\n {\n \/\/ Should build a potential field around this mesh\n CreatePotentialfieldAroundMesh(p_vertexBuffer, transformationData);\n }\n else\n {\n \/\/ Adds potential field components to the world that is not AI ground\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::PotentialField);\n PotentialFieldComponent* potComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n potComp->ChargedActor = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(transComp->position, -1, 2, true,\n DoremiEngine::AI::AIActorType::Wall); \/\/ TODOKO hardcoded shiet\n }\n if(transformationData.attributes.isSpawner)\n {\n r_shouldBuildPhysics = false;\n\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::EntitySpawner);\n EntitySpawnComponent* entitySpawnComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n entitySpawnComp->entityBlueprint = Blueprints::EnemyEntity; \/\/(Blueprints)transformationData.attributes.typeBlueprint;\n entitySpawnComp->maxNumSpawnedEntites = transformationData.attributes.spawnMax;\n entitySpawnComp->type = SpawnerType::TimedSpawner;\n entitySpawnComp->timeBetweenSpawns = 10;\n entitySpawnComp->spawnRadius = 100;\n }\n \/\/ If spawnpoint\n if(transformationData.attributes.spawnPointID > -1)\n {\n r_shouldBuildPhysics = false;\n\n \/\/ If start point, we also set this as starting respawn\n if(transformationData.attributes.startOrEndPoint == 1)\n {\n PlayerSpawnerHandler::GetInstance()->SetCurrentSpawner(p_entityId);\n }\n \/\/ Add component\n EntityHandler::GetInstance().AddComponent(p_entityId, static_cast(ComponentType::Trigger));\n\n \/\/ Set spawn point values\n TriggerComponent* t_triggerComp = GetComponent(p_entityId);\n t_triggerComp->triggerType = TriggerType::NewSpawnPointTrigger;\n\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n \/\/ calulate aab\n CalculateAABBBoundingBox(p_vertexBuffer, transformationData, maxPoint, minPoint, centerPoint);\n\n XMFLOAT3 dimension = XMFLOAT3(abs(minPoint.x - maxPoint.x) \/ 2.0f, abs(minPoint.y - maxPoint.y) \/ 2.0f, abs(minPoint.z - maxPoint.z) \/ 2.0f);\n\n \/\/\/\/ Create material\n int materialTriggID = m_sharedContext.GetPhysicsModule().GetPhysicsMaterialManager().CreateMaterial(0.0f, 0.0f, 0.0f);\n\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(p_entityId, centerPoint, XMFLOAT4(0, 0, 0, 1), dimension, materialTriggID);\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetTrigger(p_entityId, true);\n }\n \/\/ If endpoint\n if(transformationData.attributes.startOrEndPoint == 2)\n {\n r_shouldBuildPhysics = false;\n\n \/\/ Add component\n EntityHandler::GetInstance().AddComponent(p_entityId, static_cast(ComponentType::Trigger));\n\n \/\/ Set spawn point values\n TriggerComponent* t_triggerComp = GetComponent(p_entityId);\n t_triggerComp->triggerType = TriggerType::GoalTrigger;\n\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n \/\/ calulate aab\n CalculateAABBBoundingBox(p_vertexBuffer, transformationData, maxPoint, minPoint, centerPoint);\n\n XMFLOAT3 dimension = XMFLOAT3(abs(minPoint.x - maxPoint.x) \/ 2.0f, abs(minPoint.y - maxPoint.y) \/ 2.0f, abs(minPoint.z - maxPoint.z) \/ 2.0f);\n\n \/\/\/\/ Create material\n int materialTriggID = m_sharedContext.GetPhysicsModule().GetPhysicsMaterialManager().CreateMaterial(0.0f, 0.0f, 0.0f);\n\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(p_entityId, centerPoint, XMFLOAT4(0, 0, 0, 1), dimension, materialTriggID);\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetTrigger(p_entityId, true);\n }\n\n return r_shouldBuildPhysics;\n }\n\n void LevelLoaderServer::CalculateAABBBoundingBox(const std::vector& p_vertexBuffer,\n const DoremiEditor::Core::TransformData& p_transformationData, DirectX::XMFLOAT3& o_max,\n DirectX::XMFLOAT3& o_min, DirectX::XMFLOAT3& o_center)\n {\n DirectX::XMFLOAT3 maxPosition =\n DirectX::XMFLOAT3(-100000, -100000, -100000); \/\/ Hard coded low maxpos value TODOXX dangerous if maps is outside this scope...\n DirectX::XMFLOAT3 minPosition = DirectX::XMFLOAT3(100000, 100000, 100000);\n size_t length = p_vertexBuffer.size();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ Finding max value\n if(p_vertexBuffer[i].position.x > maxPosition.x)\n {\n maxPosition.x = p_vertexBuffer[i].position.x;\n }\n if(p_vertexBuffer[i].position.y > maxPosition.y)\n {\n maxPosition.y = p_vertexBuffer[i].position.y;\n }\n if(p_vertexBuffer[i].position.z > maxPosition.z)\n {\n maxPosition.z = p_vertexBuffer[i].position.z;\n }\n\n \/\/ FInding min value\n if(p_vertexBuffer[i].position.x < minPosition.x)\n {\n minPosition.x = p_vertexBuffer[i].position.x;\n }\n if(p_vertexBuffer[i].position.y < minPosition.y)\n {\n minPosition.y = p_vertexBuffer[i].position.y;\n }\n if(p_vertexBuffer[i].position.z < minPosition.z)\n {\n minPosition.z = p_vertexBuffer[i].position.z;\n }\n }\n \/\/ Max and min are now centered around origo with no scale and no rotation...\n DirectX::XMVECTOR maxVector = XMLoadFloat3(&maxPosition);\n DirectX::XMVECTOR minVector = XMLoadFloat3(&minPosition);\n DirectX::XMMATRIX rotation = XMMatrixRotationQuaternion(XMLoadFloat4(&p_transformationData.rotation));\n DirectX::XMMATRIX translation = XMMatrixTranslationFromVector(XMLoadFloat3(&p_transformationData.translation));\n DirectX::XMMATRIX scale = XMMatrixScalingFromVector(XMLoadFloat3(&p_transformationData.scale));\n maxVector = XMVector3Transform(maxVector, scale);\n maxVector = XMVector3Transform(maxVector, translation);\n\n minVector = XMVector3Transform(minVector, scale);\n minVector = XMVector3Transform(minVector, translation);\n \/\/ minVector = XMVector3Transform(minVector, translation * rotation * scale);\n \/\/ maxVector = XMVector3Rotate(maxVector, XMLoadFloat4(&p_transformationData.rotation));\n DirectX::XMFLOAT3 centerPoint;\n XMStoreFloat3(&o_center, (maxVector + minVector) \/ 2);\n XMStoreFloat3(&o_max, maxVector);\n XMStoreFloat3(&o_min, minVector);\n }\n\n void LevelLoaderServer::CreatePotentialfieldAroundMesh(const std::vector& p_vertexBuffer,\n const DoremiEditor::Core::TransformData& p_transformationData)\n {\n using namespace DirectX;\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n CalculateAABBBoundingBox(p_vertexBuffer, p_transformationData, maxPoint, minPoint, centerPoint);\n\n centerPoint.y = maxPoint.y;\n PotentialFieldGridCreator t_gridCreator = PotentialFieldGridCreator(m_sharedContext);\n DoremiEngine::AI::PotentialField* field =\n m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(maxPoint.x - minPoint.x, maxPoint.z - minPoint.z, 1, 1, centerPoint);\n t_gridCreator.BuildGridUsingPhysicXAndGrid(field);\n }\n }\n}\nAdded elevator load code from levelloader\/\/\/ Game side\n#include \n#include \n#include \n#include \n\/\/ Components\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ Engine side\n#include \n\/\/ Graphic\n#include \n#include \n#include \n\n\/\/ AI\n#include \n#include \n#include \n\/\/ Debug?\n#include \n\n\/\/ Timing\n#include \n\n\/\/ Physics\n\n\/\/\/ DEBUG physics TODOJB remove\n#include \n#include \n\n#include \n\n\/\/\/ Standard\n#include \n#include \n\nnamespace Doremi\n{\n namespace Core\n {\n LevelLoaderServer::LevelLoaderServer(const DoremiEngine::Core::SharedContext& p_sharedContext) : LevelLoader(p_sharedContext) {}\n\n LevelLoaderServer::~LevelLoaderServer() {}\n\n void LevelLoaderServer::LoadLevel(const std::string& p_fileName)\n {\n using namespace std;\n string fileName = m_sharedContext.GetWorkingDirectory() + p_fileName;\n ifstream ifs;\n ifs.open(fileName, ifstream::in | ofstream::binary);\n if(ifs.is_open() == true)\n {\n \/\/ testa o lsa lite\n\n \/\/ scene name\n int sceneNameSize;\n ifs.read((char*)&sceneNameSize, sizeof(int));\n char* sceneName = new char[sceneNameSize];\n ifs.read((char*)sceneName, sizeof(char) * sceneNameSize);\n\n \/\/ how much different stuff there is\n int nrMats, nrTransforms, nrMeshes, nrLights;\n ifs.read((char*)&nrMats, sizeof(int));\n ifs.read((char*)&nrTransforms, sizeof(int));\n ifs.read((char*)&nrMeshes, sizeof(int));\n ifs.read((char*)&nrLights, sizeof(int));\n\n LoadMaterial(ifs, nrMats);\n LoadTransforms(ifs, nrTransforms);\n LoadMeshes(ifs, nrMeshes);\n LoadLights(ifs, nrLights);\n BuildEntities();\n LoadTriggers();\n }\n else\n {\n \/\/ TODOXX DO something here?\n }\n }\n\n bool LevelLoaderServer::BuildComponents(int p_entityId, int p_meshCouplingID, std::vector& p_vertexBuffer)\n {\n bool r_shouldBuildPhysics = true;\n\n const ObjectCouplingInfo& meshCoupling = m_meshCoupling[p_meshCouplingID];\n \/\/ Adds transform components to the world\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::Transform);\n TransformComponent* transComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n\n transComp->position = m_transforms[meshCoupling.transformName].translation;\n transComp->rotation = m_transforms[meshCoupling.transformName].rotation;\n transComp->scale = m_transforms[meshCoupling.transformName].scale;\n\n\n DoremiEditor::Core::TransformData transformationData = m_transforms[meshCoupling.transformName];\n\n if(transformationData.attributes.isAIground)\n {\n \/\/ Should build a potential field around this mesh\n CreatePotentialfieldAroundMesh(p_vertexBuffer, transformationData);\n }\n else\n {\n \/\/ Adds potential field components to the world that is not AI ground\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::PotentialField);\n PotentialFieldComponent* potComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n potComp->ChargedActor = m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(transComp->position, -1, 2, true,\n DoremiEngine::AI::AIActorType::Wall); \/\/ TODOKO hardcoded shiet\n }\n if(transformationData.attributes.isSpawner)\n {\n r_shouldBuildPhysics = false;\n\n EntityHandler::GetInstance().AddComponent(p_entityId, (int)ComponentType::EntitySpawner);\n EntitySpawnComponent* entitySpawnComp = EntityHandler::GetInstance().GetComponentFromStorage(p_entityId);\n entitySpawnComp->entityBlueprint = Blueprints::EnemyEntity; \/\/(Blueprints)transformationData.attributes.typeBlueprint;\n entitySpawnComp->maxNumSpawnedEntites = transformationData.attributes.spawnMax;\n entitySpawnComp->type = SpawnerType::TimedSpawner;\n entitySpawnComp->timeBetweenSpawns = 10;\n entitySpawnComp->spawnRadius = 100;\n }\n \/\/ If spawnpoint\n if(transformationData.attributes.spawnPointID > -1)\n {\n r_shouldBuildPhysics = false;\n\n \/\/ If start point, we also set this as starting respawn\n if(transformationData.attributes.startOrEndPoint == 1)\n {\n PlayerSpawnerHandler::GetInstance()->SetCurrentSpawner(p_entityId);\n }\n \/\/ Add component\n EntityHandler::GetInstance().AddComponent(p_entityId, static_cast(ComponentType::Trigger));\n\n \/\/ Set spawn point values\n TriggerComponent* t_triggerComp = GetComponent(p_entityId);\n t_triggerComp->triggerType = TriggerType::NewSpawnPointTrigger;\n\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n \/\/ calulate aab\n CalculateAABBBoundingBox(p_vertexBuffer, transformationData, maxPoint, minPoint, centerPoint);\n\n XMFLOAT3 dimension = XMFLOAT3(abs(minPoint.x - maxPoint.x) \/ 2.0f, abs(minPoint.y - maxPoint.y) \/ 2.0f, abs(minPoint.z - maxPoint.z) \/ 2.0f);\n\n \/\/\/\/ Create material\n int materialTriggID = m_sharedContext.GetPhysicsModule().GetPhysicsMaterialManager().CreateMaterial(0.0f, 0.0f, 0.0f);\n\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(p_entityId, centerPoint, XMFLOAT4(0, 0, 0, 1), dimension, materialTriggID);\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetTrigger(p_entityId, true);\n }\n \/\/ If endpoint\n if(transformationData.attributes.startOrEndPoint == 2)\n {\n r_shouldBuildPhysics = false;\n\n \/\/ Add component\n EntityHandler::GetInstance().AddComponent(p_entityId, static_cast(ComponentType::Trigger));\n\n \/\/ Set spawn point values\n TriggerComponent* t_triggerComp = GetComponent(p_entityId);\n t_triggerComp->triggerType = TriggerType::GoalTrigger;\n\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n \/\/ calulate aab\n CalculateAABBBoundingBox(p_vertexBuffer, transformationData, maxPoint, minPoint, centerPoint);\n\n XMFLOAT3 dimension = XMFLOAT3(abs(minPoint.x - maxPoint.x) \/ 2.0f, abs(minPoint.y - maxPoint.y) \/ 2.0f, abs(minPoint.z - maxPoint.z) \/ 2.0f);\n\n \/\/\/\/ Create material\n int materialTriggID = m_sharedContext.GetPhysicsModule().GetPhysicsMaterialManager().CreateMaterial(0.0f, 0.0f, 0.0f);\n\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(p_entityId, centerPoint, XMFLOAT4(0, 0, 0, 1), dimension, materialTriggID);\n m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetTrigger(p_entityId, true);\n }\n if(transformationData.attributes.frequencyAffected)\n {\n \/\/ Add component\n EntityHandler::GetInstance().AddComponent(p_entityId, static_cast(ComponentType::FrequencyAffected));\n\n PlatformPatrolComponent* platComp = GetComponent(p_entityId);\n platComp->startPosition = transformationData.attributes.interactableStartPos;\n platComp->endPosition = transformationData.attributes.interactableEndPos;\n }\n\n return r_shouldBuildPhysics;\n }\n\n void LevelLoaderServer::CalculateAABBBoundingBox(const std::vector& p_vertexBuffer,\n const DoremiEditor::Core::TransformData& p_transformationData, DirectX::XMFLOAT3& o_max,\n DirectX::XMFLOAT3& o_min, DirectX::XMFLOAT3& o_center)\n {\n DirectX::XMFLOAT3 maxPosition =\n DirectX::XMFLOAT3(-100000, -100000, -100000); \/\/ Hard coded low maxpos value TODOXX dangerous if maps is outside this scope...\n DirectX::XMFLOAT3 minPosition = DirectX::XMFLOAT3(100000, 100000, 100000);\n size_t length = p_vertexBuffer.size();\n for(size_t i = 0; i < length; i++)\n {\n \/\/ Finding max value\n if(p_vertexBuffer[i].position.x > maxPosition.x)\n {\n maxPosition.x = p_vertexBuffer[i].position.x;\n }\n if(p_vertexBuffer[i].position.y > maxPosition.y)\n {\n maxPosition.y = p_vertexBuffer[i].position.y;\n }\n if(p_vertexBuffer[i].position.z > maxPosition.z)\n {\n maxPosition.z = p_vertexBuffer[i].position.z;\n }\n\n \/\/ FInding min value\n if(p_vertexBuffer[i].position.x < minPosition.x)\n {\n minPosition.x = p_vertexBuffer[i].position.x;\n }\n if(p_vertexBuffer[i].position.y < minPosition.y)\n {\n minPosition.y = p_vertexBuffer[i].position.y;\n }\n if(p_vertexBuffer[i].position.z < minPosition.z)\n {\n minPosition.z = p_vertexBuffer[i].position.z;\n }\n }\n \/\/ Max and min are now centered around origo with no scale and no rotation...\n DirectX::XMVECTOR maxVector = XMLoadFloat3(&maxPosition);\n DirectX::XMVECTOR minVector = XMLoadFloat3(&minPosition);\n DirectX::XMMATRIX rotation = XMMatrixRotationQuaternion(XMLoadFloat4(&p_transformationData.rotation));\n DirectX::XMMATRIX translation = XMMatrixTranslationFromVector(XMLoadFloat3(&p_transformationData.translation));\n DirectX::XMMATRIX scale = XMMatrixScalingFromVector(XMLoadFloat3(&p_transformationData.scale));\n maxVector = XMVector3Transform(maxVector, scale);\n maxVector = XMVector3Transform(maxVector, translation);\n\n minVector = XMVector3Transform(minVector, scale);\n minVector = XMVector3Transform(minVector, translation);\n \/\/ minVector = XMVector3Transform(minVector, translation * rotation * scale);\n \/\/ maxVector = XMVector3Rotate(maxVector, XMLoadFloat4(&p_transformationData.rotation));\n DirectX::XMFLOAT3 centerPoint;\n XMStoreFloat3(&o_center, (maxVector + minVector) \/ 2);\n XMStoreFloat3(&o_max, maxVector);\n XMStoreFloat3(&o_min, minVector);\n }\n\n void LevelLoaderServer::CreatePotentialfieldAroundMesh(const std::vector& p_vertexBuffer,\n const DoremiEditor::Core::TransformData& p_transformationData)\n {\n using namespace DirectX;\n XMFLOAT3 centerPoint, minPoint, maxPoint;\n CalculateAABBBoundingBox(p_vertexBuffer, p_transformationData, maxPoint, minPoint, centerPoint);\n\n centerPoint.y = maxPoint.y;\n PotentialFieldGridCreator t_gridCreator = PotentialFieldGridCreator(m_sharedContext);\n DoremiEngine::AI::PotentialField* field =\n m_sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewField(maxPoint.x - minPoint.x, maxPoint.z - minPoint.z, 1, 1, centerPoint);\n t_gridCreator.BuildGridUsingPhysicXAndGrid(field);\n }\n }\n}\n<|endoftext|>"} {"text":"`app::delete_entity`: added `const` modifier to a variable.<|endoftext|>"} {"text":"#include \"astutil.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"type.h\"\n\n\nstatic Type* getWrapRecordBaseType(Type* type);\n\n\n\/\/\n\/\/ removes _array and _domain wrapper records\n\/\/\nvoid\nremoveWrapRecords() {\n \/\/\n \/\/ do not remove wrap records if dead code elimination is disabled\n \/\/ (or weakened because inlining or copy propagation is disabled)\n \/\/ because code associated with accesses to the removed\n \/\/ _valueType field will remain\n \/\/\n if (fNoDeadCodeElimination || fNoInline || fNoCopyPropagation)\n return;\n\n \/\/\n \/\/ replace use of _valueType field with type\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_PRIVATE_GET_CLASS)) {\n call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol));\n }\n }\n\n \/\/\n \/\/ remove defs of _valueType field\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_SET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n if (SymExpr* se = toSymExpr(call->get(2))) {\n if (!strcmp(se->var->name, \"_valueType\")) {\n se->getStmtExpr()->remove();\n }\n }\n }\n }\n\n \/\/\n \/\/ remove _valueType fields\n \/\/\n forv_Vec(ClassType, ct, gClassTypes) {\n for_fields(field, ct) {\n if (!strcmp(field->name, \"_valueType\"))\n field->defPoint->remove();\n }\n }\n\n \/\/\n \/\/ remove formals for _valueType fields in constructors\n \/\/\n compute_call_sites();\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n for_formals(formal, fn) {\n if (!strcmp(formal->name, \"_valueType\")) {\n forv_Vec(CallExpr, call, *fn->calledBy) {\n formal_to_actual(call, formal)->remove();\n }\n formal->defPoint->remove();\n } \n }\n }\n\n \/\/\n \/\/ replace accesses of _value with wrap record\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n }\n }\n } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->primitive = primitives[PRIMITIVE_SET_REF];\n call->get(2)->remove();\n }\n }\n } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->replace(se->remove());\n }\n }\n }\n }\n\n \/\/\n \/\/ scalar replace wrap records\n \/\/\n forv_Vec(VarSymbol, var, gVarSymbols) {\n if (Type* type = getWrapRecordBaseType(var->type))\n if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF)) \/\/ refs second\n var->type = type;\n }\n forv_Vec(ArgSymbol, arg, gArgSymbols) {\n if (Type* type = getWrapRecordBaseType(arg->type)) {\n arg->intent = INTENT_BLANK; \/\/ see test\/arrays\/deitz\/test_out_array\n arg->type = type;\n }\n }\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n if (Type* type = getWrapRecordBaseType(fn->retType))\n fn->retType = type;\n }\n forv_Vec(ClassType, ct, gClassTypes) {\n if (ct->symbol->hasFlag(FLAG_REF))\n if (Symbol* var = ct->getField(1))\n if (Type* type = getWrapRecordBaseType(var->type))\n var->type = type;\n }\n\n \/\/\n \/\/ fix array element type for arrays of arrays and arrays of domains\n \/\/\n forv_Vec(ClassType, ct, gClassTypes) {\n if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) {\n if (TypeSymbol* ts = toTypeSymbol(ct->substitutions.v[0].value)) {\n if (ts->hasFlag(FLAG_ARRAY) || ts->hasFlag(FLAG_DOMAIN)) {\n ct->substitutions.v[0].value = ts->type->getField(\"_value\")->type->symbol;\n }\n }\n }\n }\n}\n\n\nstatic Type*\ngetWrapRecordBaseType(Type* type) {\n if (type->symbol->hasFlag(FLAG_ARRAY) ||\n type->symbol->hasFlag(FLAG_DOMAIN)) {\n return type->getField(\"_value\")->type;\n } else if (type->symbol->hasFlag(FLAG_REF)) {\n Type* vt = type->getValueType();\n if (vt->symbol->hasFlag(FLAG_ARRAY) ||\n vt->symbol->hasFlag(FLAG_DOMAIN)) {\n return vt->getField(\"_value\")->type->refType;\n }\n }\n return NULL;\n}\nFixed a bug in removeWrapRecords in which reference types to wrap records were modified to reference the wrapped value. Since these references are never used, this wasn't a serious issue, but the variant of prune executed with --destroy-value-type-vars ran into some serious problems.#include \"astutil.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"type.h\"\n\n\nstatic Type* getWrapRecordBaseType(Type* type);\n\n\n\/\/\n\/\/ removes _array and _domain wrapper records\n\/\/\nvoid\nremoveWrapRecords() {\n \/\/\n \/\/ do not remove wrap records if dead code elimination is disabled\n \/\/ (or weakened because inlining or copy propagation is disabled)\n \/\/ because code associated with accesses to the removed\n \/\/ _valueType field will remain\n \/\/\n if (fNoDeadCodeElimination || fNoInline || fNoCopyPropagation)\n return;\n\n \/\/\n \/\/ replace use of _valueType field with type\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_PRIVATE_GET_CLASS)) {\n call->get(1)->replace(new SymExpr(call->get(1)->typeInfo()->symbol));\n }\n }\n\n \/\/\n \/\/ remove defs of _valueType field\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_SET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n if (SymExpr* se = toSymExpr(call->get(2))) {\n if (!strcmp(se->var->name, \"_valueType\")) {\n se->getStmtExpr()->remove();\n }\n }\n }\n }\n\n \/\/\n \/\/ remove _valueType fields\n \/\/\n forv_Vec(ClassType, ct, gClassTypes) {\n for_fields(field, ct) {\n if (!strcmp(field->name, \"_valueType\"))\n field->defPoint->remove();\n }\n }\n\n \/\/\n \/\/ remove formals for _valueType fields in constructors\n \/\/\n compute_call_sites();\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n for_formals(formal, fn) {\n if (!strcmp(formal->name, \"_valueType\")) {\n forv_Vec(CallExpr, call, *fn->calledBy) {\n formal_to_actual(call, formal)->remove();\n }\n formal->defPoint->remove();\n } \n }\n }\n\n \/\/\n \/\/ replace accesses of _value with wrap record\n \/\/\n forv_Vec(CallExpr, call, gCallExprs) {\n if (call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n }\n }\n } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->primitive = primitives[PRIMITIVE_SET_REF];\n call->get(2)->remove();\n }\n }\n } else if (call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n if (SymExpr* se = toSymExpr(call->get(1))) {\n if (se->var->type->symbol->hasFlag(FLAG_ARRAY) ||\n se->var->type->symbol->hasFlag(FLAG_DOMAIN)) {\n call->replace(se->remove());\n }\n }\n }\n }\n\n \/\/\n \/\/ scalar replace wrap records\n \/\/\n forv_Vec(VarSymbol, var, gVarSymbols) {\n if (Type* type = getWrapRecordBaseType(var->type))\n if (!var->defPoint->parentSymbol->hasFlag(FLAG_REF))\n var->type = type;\n }\n forv_Vec(ArgSymbol, arg, gArgSymbols) {\n if (Type* type = getWrapRecordBaseType(arg->type)) {\n arg->intent = INTENT_BLANK; \/\/ see test\/arrays\/deitz\/test_out_array\n arg->type = type;\n }\n }\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n if (Type* type = getWrapRecordBaseType(fn->retType))\n fn->retType = type;\n }\n\n \/\/\n \/\/ fix array element type for arrays of arrays and arrays of domains\n \/\/\n forv_Vec(ClassType, ct, gClassTypes) {\n if (ct->symbol->hasFlag(FLAG_DATA_CLASS)) {\n if (TypeSymbol* ts = toTypeSymbol(ct->substitutions.v[0].value)) {\n if (ts->hasFlag(FLAG_ARRAY) || ts->hasFlag(FLAG_DOMAIN)) {\n ct->substitutions.v[0].value = ts->type->getField(\"_value\")->type->symbol;\n }\n }\n }\n }\n}\n\n\nstatic Type*\ngetWrapRecordBaseType(Type* type) {\n if (type->symbol->hasFlag(FLAG_ARRAY) ||\n type->symbol->hasFlag(FLAG_DOMAIN)) {\n return type->getField(\"_value\")->type;\n } else if (type->symbol->hasFlag(FLAG_REF)) {\n Type* vt = type->getValueType();\n if (vt->symbol->hasFlag(FLAG_ARRAY) ||\n vt->symbol->hasFlag(FLAG_DOMAIN)) {\n return vt->getField(\"_value\")->type->refType;\n }\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Here we are illustrating the use of the \n\/\/ \\doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} for PAN-sharpening. \n\/\/ This example takes a PAN and the corresponding XS images as input. These\n\/\/ images are supposed to be registered.\n\/\/\n\/\/ The fusion operation is defined as\n\/\/\n\/\/ \\begin{equation}\n\/\/ \\frac{XS}{\\mathrm{Filtered}(PAN)} PAN\n\/\/ \\end{equation}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Toulouse_Ortho_PAN.tif QB_Toulouse_Ortho_XS.tif}\n\/\/ OUTPUTS: {QB_Toulouse_Ortho_PXS.tif pretty_QB_Toulouse_Ortho_PXS.png \n\/\/ pretty_QB_Toulouse_Ortho_PAN.png pretty_QB_Toulouse_Ortho_XS.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We start by including the required header and declaring the main function:\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbSimpleRcsPanSharpeningFusionImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n#include \"otbPrintableImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\/\/ Software Guide : BeginCodeSnippet\nint main( int argc, char* argv[] )\n{\n\/\/ Software Guide : EndCodeSnippet\n \n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" inputPanchromatiqueImage inputMultiSpectralImage outputImage outputImagePrinted panchroPrinted msPrinted\" << std::endl;\n return 1;\n }\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the different image type used here as well as the image reader.\n \/\/ Note that, the reader for the PAN image is templated by an \n \/\/ \\doxygen{otb}{Image} while the XS reader uses an \n \/\/ \\doxygen{otb}{VectorImage}.\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::Image ImageType;\n typedef otb::VectorImage VectorImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileReader ReaderVectorType;\n typedef otb::VectorImage VectorIntImageType;\n \n\t\t\t\t\t\n ReaderVectorType::Pointer \treaderXS=ReaderVectorType::New();\n ReaderType::Pointer \treaderPAN=ReaderType::New();\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We pass the filenames to the readers\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n readerPAN->SetFileName(argv[1]);\n readerXS->SetFileName(argv[2]);\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the fusion filter an set its inputs using the readers:\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::SimpleRcsPanSharpeningFusionImageFilter\n FusionFilterType;\n FusionFilterType::Pointer fusion = FusionFilterType::New();\n fusion->SetPanInput(readerPAN->GetOutput());\n fusion->SetXsInput(readerXS->GetOutput());\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ And finally, we declare the writer and call its \\code{Update()} method to\n \/\/ trigger the full pipeline execution.\n \/\/\n \/\/ Software Guide : EndLatex \n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::StreamingImageFileWriter WriterType;\n WriterType::Pointer\t \twriter=WriterType::New();\n writer->SetFileName(argv[3]);\n writer->SetInput(fusion->GetOutput());\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n \n \n typedef otb::PrintableImageFilter PrintableImageType;\n PrintableImageType::Pointer printable = PrintableImageType::New();\n\n \n typedef otb::VectorImage VectorCharImageType;\n typedef otb::StreamingImageFileWriter PNGWriterType;\n PNGWriterType::Pointer pngwriter = PNGWriterType::New();\n \n printable->SetInput(fusion->GetOutput());\n printable->SetChannel(3);\n printable->SetChannel(2);\n printable->SetChannel(1); \n pngwriter->SetFileName(argv[4]);\n pngwriter->SetInput(printable->GetOutput());\n pngwriter->Update();\n \n typedef otb::PrintableImageFilter PrintableImageType2;\n PrintableImageType2::Pointer printable2 = PrintableImageType2::New();\n printable2->SetInput(readerXS->GetOutput());\n printable2->SetChannel(3);\n printable2->SetChannel(2);\n printable2->SetChannel(1); \n pngwriter->SetFileName(argv[6]);\n pngwriter->SetInput(printable2->GetOutput());\n pngwriter->Update();\n \n typedef otb::Image CharImageType;\n typedef itk::RescaleIntensityImageFilter RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n typedef otb::StreamingImageFileWriter PNGWriterType2;\n PNGWriterType2::Pointer pngwriter2 = PNGWriterType2::New();\n rescaler->SetInput(readerPAN->GetOutput());\n pngwriter2->SetFileName(argv[5]);\n pngwriter2->SetInput(rescaler->GetOutput());\n pngwriter2->Update();\n \n \n\/\/ Software Guide : BeginCodeSnippet \n return EXIT_SUCCESS;\n \n}\n\/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Figure~\\ref{fig:PANSHARP_FILTER} shows the result of applying\n \/\/ this PAN sharpening filter to a Quickbird image.\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_PAN.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_XS.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_PXS.eps}\n \/\/ \\itkcaption[Pan sharpening]{Result of applying\n \/\/ the \\doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} to \n \/\/ orthorectified Quickbird\n \/\/ image. From left to right : original PAN image, original XS image and the \n \/\/ result of the PAN sharpening} \n \/\/ \\label{fig:PANSHARP_FILTER} \n \/\/ \\end{figure}\n \/\/\n \/\/ Software Guide : EndLatex\n\n\nprise en compte des OUTPUTS\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Toulouse_Ortho_PAN.tif}, {QB_Toulouse_Ortho_XS.tif}\n\/\/ OUTPUTS: {QB_Toulouse_Ortho_PXS.tif}\n\/\/ OUTPUTS: {pretty_QB_Toulouse_Ortho_PXS.png}\n\/\/ OUTPUTS: {pretty_QB_Toulouse_Ortho_PAN.png}\n\/\/ OUTPUTS: {pretty_QB_Toulouse_Ortho_XS.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Here we are illustrating the use of the \n\/\/ \\doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} for PAN-sharpening. \n\/\/ This example takes a PAN and the corresponding XS images as input. These\n\/\/ images are supposed to be registered.\n\/\/\n\/\/ The fusion operation is defined as\n\/\/\n\/\/ \\begin{equation}\n\/\/ \\frac{XS}{\\mathrm{Filtered}(PAN)} PAN\n\/\/ \\end{equation}\n\/\/\n\/\/ Software Guide : EndLatex \n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We start by including the required header and declaring the main function:\n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbSimpleRcsPanSharpeningFusionImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n#include \"otbPrintableImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\/\/ Software Guide : BeginCodeSnippet\nint main( int argc, char* argv[] )\n{\n\/\/ Software Guide : EndCodeSnippet\n \n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" inputPanchromatiqueImage inputMultiSpectralImage outputImage outputImagePrinted panchroPrinted msPrinted\" << std::endl;\n return 1;\n }\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the different image type used here as well as the image reader.\n \/\/ Note that, the reader for the PAN image is templated by an \n \/\/ \\doxygen{otb}{Image} while the XS reader uses an \n \/\/ \\doxygen{otb}{VectorImage}.\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::Image ImageType;\n typedef otb::VectorImage VectorImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileReader ReaderVectorType;\n typedef otb::VectorImage VectorIntImageType;\n \n\t\t\t\t\t\n ReaderVectorType::Pointer \treaderXS=ReaderVectorType::New();\n ReaderType::Pointer \treaderPAN=ReaderType::New();\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We pass the filenames to the readers\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n readerPAN->SetFileName(argv[1]);\n readerXS->SetFileName(argv[2]);\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We declare the fusion filter an set its inputs using the readers:\n \/\/\n \/\/ Software Guide : EndLatex\n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::SimpleRcsPanSharpeningFusionImageFilter\n FusionFilterType;\n FusionFilterType::Pointer fusion = FusionFilterType::New();\n fusion->SetPanInput(readerPAN->GetOutput());\n fusion->SetXsInput(readerXS->GetOutput());\n \/\/ Software Guide : EndCodeSnippet\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ And finally, we declare the writer and call its \\code{Update()} method to\n \/\/ trigger the full pipeline execution.\n \/\/\n \/\/ Software Guide : EndLatex \n \n \/\/ Software Guide : BeginCodeSnippet\n typedef otb::StreamingImageFileWriter WriterType;\n WriterType::Pointer\t \twriter=WriterType::New();\n writer->SetFileName(argv[3]);\n writer->SetInput(fusion->GetOutput());\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n \n \n typedef otb::PrintableImageFilter PrintableImageType;\n PrintableImageType::Pointer printable = PrintableImageType::New();\n\n \n typedef otb::VectorImage VectorCharImageType;\n typedef otb::StreamingImageFileWriter PNGWriterType;\n PNGWriterType::Pointer pngwriter = PNGWriterType::New();\n \n printable->SetInput(fusion->GetOutput());\n printable->SetChannel(3);\n printable->SetChannel(2);\n printable->SetChannel(1); \n pngwriter->SetFileName(argv[4]);\n pngwriter->SetInput(printable->GetOutput());\n pngwriter->Update();\n \n typedef otb::PrintableImageFilter PrintableImageType2;\n PrintableImageType2::Pointer printable2 = PrintableImageType2::New();\n printable2->SetInput(readerXS->GetOutput());\n printable2->SetChannel(3);\n printable2->SetChannel(2);\n printable2->SetChannel(1); \n pngwriter->SetFileName(argv[6]);\n pngwriter->SetInput(printable2->GetOutput());\n pngwriter->Update();\n \n typedef otb::Image CharImageType;\n typedef itk::RescaleIntensityImageFilter RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n typedef otb::StreamingImageFileWriter PNGWriterType2;\n PNGWriterType2::Pointer pngwriter2 = PNGWriterType2::New();\n rescaler->SetInput(readerPAN->GetOutput());\n pngwriter2->SetFileName(argv[5]);\n pngwriter2->SetInput(rescaler->GetOutput());\n pngwriter2->Update();\n \n \n\/\/ Software Guide : BeginCodeSnippet \n return EXIT_SUCCESS;\n \n\n\/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Figure~\\ref{fig:PANSHARP_FILTER} shows the result of applying\n \/\/ this PAN sharpening filter to a Quickbird image.\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_PAN.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_XS.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{pretty_QB_Toulouse_Ortho_PXS.eps}\n \/\/ \\itkcaption[Pan sharpening]{Result of applying\n \/\/ the \\doxygen{otb}{SimpleRcsPanSharpeningFusionImageFilter} to \n \/\/ orthorectified Quickbird\n \/\/ image. From left to right : original PAN image, original XS image and the \n \/\/ result of the PAN sharpening} \n \/\/ \\label{fig:PANSHARP_FILTER} \n \/\/ \\end{figure}\n \/\/\n \/\/ Software Guide : EndLatex\n\n}\n<|endoftext|>"} {"text":"Cleaning up code.<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/nacl\/loader\/nacl_sandbox_linux.h\"\n\n#include \n#include \n\n#include \"base\/callback.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"build\/build_config.h\"\n#include \"content\/public\/common\/sandbox_init.h\"\n#include \"sandbox\/linux\/seccomp-bpf\/sandbox_bpf.h\"\n#include \"sandbox\/linux\/services\/linux_syscalls.h\"\n\nusing playground2::ErrorCode;\nusing playground2::Sandbox;\n\nnamespace {\n\n\/\/ On ARM and x86_64, System V shared memory calls have each their own system\n\/\/ call, while on i386 they are multiplexed.\n#if defined(__x86_64__) || defined(__arm__)\nbool IsSystemVSharedMemory(int sysno) {\n switch (sysno) {\n case __NR_shmat:\n case __NR_shmctl:\n case __NR_shmdt:\n case __NR_shmget:\n return true;\n default:\n return false;\n }\n}\n#endif\n\n#if defined(__i386__)\n\/\/ Big system V multiplexing system call.\nbool IsSystemVIpc(int sysno) {\n switch (sysno) {\n case __NR_ipc:\n return true;\n default:\n return false;\n }\n}\n#endif\n\nErrorCode NaClBpfSandboxPolicy(\n playground2::Sandbox* sb, int sysno, void* aux) {\n const playground2::BpfSandboxPolicyCallback baseline_policy =\n content::GetBpfSandboxBaselinePolicy();\n switch (sysno) {\n \/\/ TODO(jln): NaCl's GDB debug stub uses the following socket system calls,\n \/\/ see if it can be restricted a bit.\n#if defined(__x86_64__) || defined(__arm__)\n \/\/ transport_common.cc needs this.\n case __NR_accept:\n case __NR_setsockopt:\n#elif defined(__i386__)\n case __NR_socketcall:\n#endif\n \/\/ trusted\/service_runtime\/linux\/thread_suspension.c needs sigwait() and is\n \/\/ used by NaCl's GDB debug stub.\n case __NR_rt_sigtimedwait:\n#if defined(__i386__)\n \/\/ Needed on i386 to set-up the custom segments.\n case __NR_modify_ldt:\n#endif\n \/\/ NaClAddrSpaceBeforeAlloc needs prlimit64.\n case __NR_prlimit64:\n \/\/ NaCl uses custom signal stacks.\n case __NR_sigaltstack:\n \/\/ Below is fairly similar to the policy for a Chromium renderer.\n \/\/ TODO(jln): restrict clone(), ioctl() and prctl().\n case __NR_ioctl:\n#if defined(__i386__) || defined(__x86_64__)\n case __NR_getrlimit:\n#endif\n#if defined(__i386__) || defined(__arm__)\n case __NR_ugetrlimit:\n#endif\n case __NR_pread64:\n case __NR_pwrite64:\n case __NR_sched_get_priority_max:\n case __NR_sched_get_priority_min:\n case __NR_sched_getaffinity:\n case __NR_sched_getparam:\n case __NR_sched_getscheduler:\n case __NR_sched_setscheduler:\n case __NR_setpriority:\n case __NR_sysinfo:\n \/\/ __NR_times needed as clock() is called by CommandBufferHelper, which is\n \/\/ used by NaCl applications that use Pepper's 3D interfaces.\n \/\/ See crbug.com\/264856 for details.\n case __NR_times:\n case __NR_uname:\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n case __NR_ptrace:\n return ErrorCode(EPERM);\n default:\n \/\/ TODO(jln): look into getting rid of System V shared memory:\n \/\/ platform_qualify\/linux\/sysv_shm_and_mmap.c makes it a requirement, but\n \/\/ it may not be needed in all cases. Chromium renderers don't need\n \/\/ System V shared memory on Aura.\n#if defined(__x86_64__) || defined(__arm__)\n if (IsSystemVSharedMemory(sysno))\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n#elif defined(__i386__)\n if (IsSystemVIpc(sysno))\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n#endif\n return baseline_policy.Run(sb, sysno, aux);\n }\n NOTREACHED();\n \/\/ GCC wants this.\n return ErrorCode(EPERM);\n}\n\nvoid RunSandboxSanityChecks() {\n errno = 0;\n \/\/ Make a ptrace request with an invalid PID.\n long ptrace_ret = ptrace(PTRACE_PEEKUSER, -1 \/* pid *\/, NULL, NULL);\n CHECK_EQ(-1, ptrace_ret);\n \/\/ Without the sandbox on, this ptrace call would ESRCH instead.\n CHECK_EQ(EPERM, errno);\n}\n\n} \/\/ namespace\n\nbool InitializeBpfSandbox() {\n bool sandbox_is_initialized =\n content::InitializeSandbox(NaClBpfSandboxPolicy);\n if (sandbox_is_initialized) {\n RunSandboxSanityChecks();\n \/\/ TODO(jln): Find a way to fix this.\n \/\/ The sandbox' SIGSYS handler trips NaCl, so we disable it.\n \/\/ If SIGSYS is triggered it'll now execute the default action\n \/\/ (CORE). This will make it hard to track down bugs and sandbox violations.\n CHECK(signal(SIGSYS, SIG_DFL) != SIG_ERR);\n return true;\n }\n return false;\n}\nAdd clock_getres to allowed NaCl syscalls.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"components\/nacl\/loader\/nacl_sandbox_linux.h\"\n\n#include \n#include \n\n#include \"base\/callback.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"build\/build_config.h\"\n#include \"content\/public\/common\/sandbox_init.h\"\n#include \"sandbox\/linux\/seccomp-bpf\/sandbox_bpf.h\"\n#include \"sandbox\/linux\/services\/linux_syscalls.h\"\n\nusing playground2::ErrorCode;\nusing playground2::Sandbox;\n\nnamespace {\n\n\/\/ On ARM and x86_64, System V shared memory calls have each their own system\n\/\/ call, while on i386 they are multiplexed.\n#if defined(__x86_64__) || defined(__arm__)\nbool IsSystemVSharedMemory(int sysno) {\n switch (sysno) {\n case __NR_shmat:\n case __NR_shmctl:\n case __NR_shmdt:\n case __NR_shmget:\n return true;\n default:\n return false;\n }\n}\n#endif\n\n#if defined(__i386__)\n\/\/ Big system V multiplexing system call.\nbool IsSystemVIpc(int sysno) {\n switch (sysno) {\n case __NR_ipc:\n return true;\n default:\n return false;\n }\n}\n#endif\n\nErrorCode NaClBpfSandboxPolicy(\n playground2::Sandbox* sb, int sysno, void* aux) {\n const playground2::BpfSandboxPolicyCallback baseline_policy =\n content::GetBpfSandboxBaselinePolicy();\n switch (sysno) {\n \/\/ TODO(jln): NaCl's GDB debug stub uses the following socket system calls,\n \/\/ see if it can be restricted a bit.\n#if defined(__x86_64__) || defined(__arm__)\n \/\/ transport_common.cc needs this.\n case __NR_accept:\n case __NR_setsockopt:\n#elif defined(__i386__)\n case __NR_socketcall:\n#endif\n \/\/ trusted\/service_runtime\/linux\/thread_suspension.c needs sigwait() and is\n \/\/ used by NaCl's GDB debug stub.\n case __NR_rt_sigtimedwait:\n#if defined(__i386__)\n \/\/ Needed on i386 to set-up the custom segments.\n case __NR_modify_ldt:\n#endif\n \/\/ NaClAddrSpaceBeforeAlloc needs prlimit64.\n case __NR_prlimit64:\n \/\/ NaCl uses custom signal stacks.\n case __NR_sigaltstack:\n \/\/ Below is fairly similar to the policy for a Chromium renderer.\n \/\/ TODO(jln): restrict clone(), ioctl() and prctl().\n case __NR_ioctl:\n#if defined(__i386__) || defined(__x86_64__)\n case __NR_getrlimit:\n#endif\n#if defined(__i386__) || defined(__arm__)\n case __NR_ugetrlimit:\n#endif\n \/\/ NaCl runtime exposes clock_getres to untrusted code.\n case __NR_clock_getres:\n case __NR_pread64:\n case __NR_pwrite64:\n case __NR_sched_get_priority_max:\n case __NR_sched_get_priority_min:\n case __NR_sched_getaffinity:\n case __NR_sched_getparam:\n case __NR_sched_getscheduler:\n case __NR_sched_setscheduler:\n case __NR_setpriority:\n case __NR_sysinfo:\n \/\/ __NR_times needed as clock() is called by CommandBufferHelper, which is\n \/\/ used by NaCl applications that use Pepper's 3D interfaces.\n \/\/ See crbug.com\/264856 for details.\n case __NR_times:\n case __NR_uname:\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n case __NR_ptrace:\n return ErrorCode(EPERM);\n default:\n \/\/ TODO(jln): look into getting rid of System V shared memory:\n \/\/ platform_qualify\/linux\/sysv_shm_and_mmap.c makes it a requirement, but\n \/\/ it may not be needed in all cases. Chromium renderers don't need\n \/\/ System V shared memory on Aura.\n#if defined(__x86_64__) || defined(__arm__)\n if (IsSystemVSharedMemory(sysno))\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n#elif defined(__i386__)\n if (IsSystemVIpc(sysno))\n return ErrorCode(ErrorCode::ERR_ALLOWED);\n#endif\n return baseline_policy.Run(sb, sysno, aux);\n }\n NOTREACHED();\n \/\/ GCC wants this.\n return ErrorCode(EPERM);\n}\n\nvoid RunSandboxSanityChecks() {\n errno = 0;\n \/\/ Make a ptrace request with an invalid PID.\n long ptrace_ret = ptrace(PTRACE_PEEKUSER, -1 \/* pid *\/, NULL, NULL);\n CHECK_EQ(-1, ptrace_ret);\n \/\/ Without the sandbox on, this ptrace call would ESRCH instead.\n CHECK_EQ(EPERM, errno);\n}\n\n} \/\/ namespace\n\nbool InitializeBpfSandbox() {\n bool sandbox_is_initialized =\n content::InitializeSandbox(NaClBpfSandboxPolicy);\n if (sandbox_is_initialized) {\n RunSandboxSanityChecks();\n \/\/ TODO(jln): Find a way to fix this.\n \/\/ The sandbox' SIGSYS handler trips NaCl, so we disable it.\n \/\/ If SIGSYS is triggered it'll now execute the default action\n \/\/ (CORE). This will make it hard to track down bugs and sandbox violations.\n CHECK(signal(SIGSYS, SIG_DFL) != SIG_ERR);\n return true;\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3188\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nSWDEV-2 - Change OpenCL version number from 3188 to 3189\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3189\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3294\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nSWDEV-2 - Change OpenCL version number from 3294 to 3295\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3295\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3393\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nSWDEV-2 - Change OpenCL version number from 3393 to 3394\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3394\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3165\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nSWDEV-2 - Change OpenCL version number from 3165 to 3166\/* Copyright (c) 2010-present Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3166\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\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#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkLabelImageToShapeLabelMapFilter.h\"\n#include \"itkTestingMacros.h\"\n#include \"itkMath.h\"\n\nnamespace m = itk::Math;\n\nint itkLabelImageToShapeLabelMapFilterTest2(int , char *[])\n{\n\n const unsigned int dim = 2;\n\n typedef unsigned char PixelType;\n\n typedef itk::Image< PixelType, dim > ImageType;\n\n typedef itk::ShapeLabelObject< PixelType, dim > LabelObjectType;\n typedef itk::LabelMap< LabelObjectType > LabelMapType;\n\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n size[0] = 11;\n size[1] = 13;\n ImageType::IndexType index;\n index.Fill(0);\n region.SetSize(size);\n region.SetIndex(index);\n\n LabelMapType::Pointer labelMap;\n LabelObjectType::Pointer labelObject;\n\n LabelObjectType::OrientedBoundingBoxPointType obbOrigin;\n LabelObjectType::OrientedBoundingBoxSizeType obbSize;\n\n ImageType::Pointer image = ImageType::New();\n image->SetRegions(region);\n image->Allocate();\n\n \/\/\n \/\/ Test case one pixel\n \/\/\n\n index[0] = 5;\n index[1] = 7;\n image->SetPixel(index, 1);\n\n typedef itk::LabelImageToShapeLabelMapFilter< ImageType, LabelMapType> L2SType;\n L2SType::Pointer l2s = L2SType::New();\n l2s->SetInput( image );\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], 1.0) && m::AlmostEquals(obbSize[1], 1.0));\n\n \/\/\n \/\/ Test case two diagonal pixels\n \/\/\n\n ++index[0];\n ++index[1];\n\n image->SetPixel(index, 1);\n image->Modified();\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], m::sqrt2) && m::AlmostEquals(obbSize[1], 2.0*m::sqrt2));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 4.0) && m::AlmostEquals(obbOrigin[1], 7.0));\n\n \/\/\n \/\/ Test case two diagonal pixels, with flip direction matrix\n \/\/\n ImageType::DirectionType direction;\n direction.Fill(0.0);\n direction(0,1) = 1.0;\n direction(1,0) = 1.0;\n\n image->SetDirection(direction);\n image->Modified();\n\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], m::sqrt2) && m::AlmostEquals(obbSize[1], 2.0*m::sqrt2));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 6.0) && m::AlmostEquals(obbOrigin[1], 5.0));\n\n\n \/\/\n \/\/ Test case 2x4 rectangle\n \/\/\n image->FillBuffer(0);\n direction.SetIdentity();\n image->SetDirection(direction);\n for (unsigned int i = 4; i < 6; ++i)\n {\n for (unsigned int j = 3; j < 7; ++j)\n {\n ImageType::IndexType idx;\n idx[0] = i;\n idx[1] = j;\n image->SetPixel(idx, 1);\n }\n }\n\n image->Modified();\n\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n std::cout << labelObject;\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], 2.0) && m::AlmostEquals(obbSize[1], 4.0));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 3.5) && m::AlmostEquals(obbOrigin[1], 2.5));\n\n\n \/\/ Just exercise these methods\n std::cout << \"OBB vericies: \" << labelObject->GetOrientedBoundingBoxVertices() << std::endl;\n std::cout << \"OBB direction: \" << labelObject->GetOrientedBoundingBoxDirection();\n\n return EXIT_SUCCESS;\n}\nBUG: Initialize image data to 0\/*=========================================================================\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#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkLabelImageToShapeLabelMapFilter.h\"\n#include \"itkTestingMacros.h\"\n#include \"itkMath.h\"\n\nnamespace m = itk::Math;\n\nint itkLabelImageToShapeLabelMapFilterTest2(int , char *[])\n{\n\n const unsigned int dim = 2;\n\n typedef unsigned char PixelType;\n\n typedef itk::Image< PixelType, dim > ImageType;\n\n typedef itk::ShapeLabelObject< PixelType, dim > LabelObjectType;\n typedef itk::LabelMap< LabelObjectType > LabelMapType;\n\n\n ImageType::RegionType region;\n ImageType::SizeType size;\n size[0] = 11;\n size[1] = 13;\n ImageType::IndexType index;\n index.Fill(0);\n region.SetSize(size);\n region.SetIndex(index);\n\n LabelMapType::Pointer labelMap;\n LabelObjectType::Pointer labelObject;\n\n LabelObjectType::OrientedBoundingBoxPointType obbOrigin;\n LabelObjectType::OrientedBoundingBoxSizeType obbSize;\n\n ImageType::Pointer image = ImageType::New();\n image->SetRegions(region);\n image->Allocate(true);\n\n \/\/\n \/\/ Test case one pixel\n \/\/\n\n index[0] = 5;\n index[1] = 7;\n image->SetPixel(index, 1);\n\n typedef itk::LabelImageToShapeLabelMapFilter< ImageType, LabelMapType> L2SType;\n L2SType::Pointer l2s = L2SType::New();\n l2s->SetInput( image );\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], 1.0) && m::AlmostEquals(obbSize[1], 1.0));\n\n \/\/\n \/\/ Test case two diagonal pixels\n \/\/\n\n ++index[0];\n ++index[1];\n\n image->SetPixel(index, 1);\n image->Modified();\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], m::sqrt2) && m::AlmostEquals(obbSize[1], 2.0*m::sqrt2));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 4.0) && m::AlmostEquals(obbOrigin[1], 7.0));\n\n \/\/\n \/\/ Test case two diagonal pixels, with flip direction matrix\n \/\/\n ImageType::DirectionType direction;\n direction.Fill(0.0);\n direction(0,1) = 1.0;\n direction(1,0) = 1.0;\n\n image->SetDirection(direction);\n image->Modified();\n\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], m::sqrt2) && m::AlmostEquals(obbSize[1], 2.0*m::sqrt2));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 6.0) && m::AlmostEquals(obbOrigin[1], 5.0));\n\n\n \/\/\n \/\/ Test case 2x4 rectangle\n \/\/\n image->FillBuffer(0);\n direction.SetIdentity();\n image->SetDirection(direction);\n for (unsigned int i = 4; i < 6; ++i)\n {\n for (unsigned int j = 3; j < 7; ++j)\n {\n ImageType::IndexType idx;\n idx[0] = i;\n idx[1] = j;\n image->SetPixel(idx, 1);\n }\n }\n\n image->Modified();\n\n\n TRY_EXPECT_NO_EXCEPTION( l2s->Update() );\n\n labelMap = l2s->GetOutput();\n labelObject = labelMap->GetLabelObject(1);\n\n obbSize = labelObject->GetOrientedBoundingBoxSize();\n obbOrigin = labelObject->GetOrientedBoundingBoxOrigin();\n std::cout << labelObject;\n TEST_EXPECT_TRUE( m::AlmostEquals(obbSize[0], 2.0) && m::AlmostEquals(obbSize[1], 4.0));\n TEST_EXPECT_TRUE( m::AlmostEquals(obbOrigin[0], 3.5) && m::AlmostEquals(obbOrigin[1], 2.5));\n\n\n \/\/ Just exercise these methods\n std::cout << \"OBB vertices: \" << labelObject->GetOrientedBoundingBoxVertices() << std::endl;\n std::cout << \"OBB direction: \" << labelObject->GetOrientedBoundingBoxDirection();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"{% extends 'scan.cpp' %}\n\n{% block initializer %}std::tuple_cat({{ super() }}, make_tuple({{mapping_var_name}}.second)){% endblock %}add std:: in previous commit{% extends 'scan.cpp' %}\n\n{% block initializer %}std::tuple_cat({{ super() }}, std::make_tuple({{mapping_var_name}}.second)){% endblock %}<|endoftext|>"} {"text":"\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2021 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#define WORKAROUND_ISSUE_1146 1 \/\/ check asm solver applicability for gfx90a\n\nnamespace miopen {\n\nnamespace solver {\n\nnamespace batchnorm {\n\nbool BnBwdTrainingSpatialSingle::IsApplicable(\n const ExecutionContext&, const miopen::batchnorm::ProblemDescription& problem) const\n{\n if(problem.GetDirection() != miopen::batchnorm::Direction::Backward ||\n problem.GetMode() != miopenBNSpatial)\n return false;\n\n if(problem.IsLayoutNHWC())\n return true;\n\n int n, c, h, w;\n std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());\n\n unsigned int in_cstride = h * w;\n unsigned int in_nhw = n * in_cstride;\n\n return (in_cstride > 1024 && in_nhw < (32 * 1024 * 1024)) ||\n (in_cstride > 512 && in_nhw < (32 * 1024 * 1024)) || in_cstride <= 512;\n}\n\nConvSolution\nBnBwdTrainingSpatialSingle::GetSolution(const ExecutionContext& context,\n const miopen::batchnorm::ProblemDescription& problem) const\n{\n const auto& handle = context.GetStream();\n\n bool bfpmixparm = false;\n bool bfp16parm = false;\n bool bfp32parm = true;\n\n if(problem.GetXDesc().GetType() == miopenHalf &&\n problem.GetScaleBiasDiffDesc().GetType() == miopenHalf)\n {\n bfp16parm = true;\n bfp32parm = false;\n }\n else if(problem.GetXDesc().GetType() == miopenHalf &&\n problem.GetScaleBiasDiffDesc().GetType() == miopenFloat)\n {\n bfpmixparm = true;\n bfp32parm = false;\n }\n\n int n, c, h, w;\n std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());\n\n unsigned int in_cstride = h * w;\n unsigned int in_nstride = c * in_cstride;\n unsigned int in_nhw = n * in_cstride;\n unsigned int in_nchw = n * in_nstride;\n\n auto inhw = float(1.0 \/ in_nhw);\n\n size_t xlocalsize = 1;\n size_t ylocalsize = 1;\n\n size_t xgridsize = 1;\n size_t ygridsize = 1;\n\n unsigned int ldsgcn = 0;\n unsigned int ldsnogcn = 0;\n int variant = 1;\n\n if(problem.IsLayoutNHWC())\n {\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n else\n {\n \/\/*************************************************************************************************\n \/\/ N*H*W < 32M and H*W > 1024, use batchnorm variant#1 implementation which parallelize\n \/\/ work groups over channels and loop through NHW.\n \/\/*************************************************************************************************\n if((in_nhw < (32 * 1024 * 1024) && in_cstride > 1024))\n {\n variant = 1;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n \/\/*************************************************************************************************\n \/\/ N*H*W < 32M and H*W > 512 use batchnorm variant#1 or variant#3 implementation which\n \/\/ parallelize\n \/\/ work groups over channels and loop through N.\n \/\/*************************************************************************************************\n else if(in_nhw < (32 * 1024 * 1024) && in_cstride > 512)\n {\n variant = (n >= 32) ? 1 : 3;\n xlocalsize = std::min(64 * ((in_cstride + 63) \/ 64), static_cast(1024));\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n \/\/*************************************************************************************************\n \/\/ H*W < 512 use batchnorm variant#0 or variant#3 implementation based on batch size and\n \/\/ H*W\n \/\/*************************************************************************************************\n else if(in_cstride <= 512)\n {\n if((n > 64) && (in_cstride > 160))\n {\n variant = 3;\n xlocalsize =\n std::min(64 * ((in_cstride + 63) \/ 64), static_cast(1024));\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n else\n {\n variant = 0;\n if(bfp32parm)\n {\n xlocalsize = 1024;\n xgridsize = 1024 * c;\n }\n else\n {\n xlocalsize = 256;\n xgridsize = 256 * c;\n }\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n }\n \/\/*************************************************************************************************\n \/\/ N*H*W > 32M, use batchnorm variant#2 implementation which parallelize\n \/\/ work groups over channels and data segments.\n \/\/*************************************************************************************************\n else\n {\n variant = 2;\n ylocalsize = 1024;\n auto segment = int(std::ceil(double(in_cstride) \/ double(ylocalsize)));\n xgridsize = c;\n ygridsize = segment * ylocalsize;\n ldsgcn = ylocalsize \/ 64;\n ldsnogcn = ylocalsize;\n }\n if((in_cstride < 200) && (in_cstride > 60) && bfpmixparm)\n {\n variant = 1;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ 64;\n ldsnogcn = xlocalsize;\n }\n }\n auto result = ConvSolution{miopenStatusSuccess};\n\n {\n size_t zlocalsize = 1;\n size_t zgridsize = 1;\n\n auto kernel = KernelInfo{};\n\n auto build_params = KernelBuildParameters{\n {\"MIOPEN_USE_FP16\", static_cast(bfp16parm)},\n {\"MIOPEN_USE_FP32\", static_cast(bfp32parm)},\n {\"MIOPEN_USE_FPMIX\", static_cast(bfpmixparm)},\n {\"MIO_BN_USESAVED\", static_cast(problem.UseSaved())},\n {\"MIO_BN_N\", static_cast(n)},\n {\"MIO_BN_C\", static_cast(c)},\n {\"MIO_BN_HW\", static_cast(in_cstride)},\n {\"MIO_BN_NHW\", static_cast(in_nhw)},\n {\"MIO_BN_CHW\", in_nstride},\n {\"MIO_BN_NCHW\", in_nchw},\n {\"MIO_BN_LDS_SIZE\", ldsnogcn},\n {\"MIO_BN_LDSGCN_SIZE\", ldsgcn},\n {\"MIO_BN_VARIANT\", variant},\n {\"MIO_BN_GRP0\", xlocalsize},\n {\"MIO_BN_GRP1\", ylocalsize},\n {\"MIO_BN_GRP2\", zlocalsize},\n {\"MIO_LAYOUT_NHWC\", static_cast(problem.IsLayoutNHWC())},\n };\n\n if((n > 64) && (n % 2 == 0) && (variant == 3) && (bfpmixparm) && (problem.UseSaved()) &&\n context.use_asm_kernels && context.rmv.IsV2orV3() &&\n (StartsWith(handle.GetDeviceName(), \"gfx8\") ||\n (StartsWith(handle.GetDeviceName(), \"gfx9\")\n#if WORKAROUND_ISSUE_1146\n && (handle.GetDeviceName() != \"gfx90a\")\n#endif\n )) &&\n (!handle.GetTargetProperties().Xnack() || !*handle.GetTargetProperties().Xnack()))\n {\n kernel.kernel_file = \"gcnAsmBNBwdTrainSpatial.s\";\n kernel.kernel_name = \"miopenGcnAsmBNBwdTrainSpatial\";\n\n union\n {\n unsigned u32;\n float f32 = 0;\n } NHW_value;\n\n NHW_value.f32 = static_cast(in_nhw);\n\n build_params << KernelBuildParameters{\n {\"ROCM_METADATA_VERSION\", context.rmv.UseV3() ? \"5\" : \"4\"},\n {\"MIO_BN_NHW_FLOAT\", NHW_value.u32},\n };\n\n kernel.comp_options = build_params.GenerateFor(kbp::GcnAsm{});\n }\n else\n {\n kernel.kernel_file = \"MIOpenBatchNormBwdSpatial.cl\";\n kernel.kernel_name = \"MIOpenBatchNormBwdSpatial\";\n\n build_params << KernelBuildParameters{\n {\"MIO_BN_GFX1030\", (handle.GetDeviceName() == \"gfx1030\") ? \"1\" : \"0\"},\n };\n\n kernel.comp_options = build_params.GenerateFor(kbp::OpenCL{});\n }\n\n kernel.l_wk.push_back(xlocalsize);\n kernel.l_wk.push_back(ylocalsize);\n kernel.l_wk.push_back(zlocalsize);\n\n kernel.g_wk.push_back(xgridsize);\n kernel.g_wk.push_back(ygridsize);\n kernel.g_wk.push_back(zgridsize);\n\n result.construction_params.push_back(kernel);\n }\n\n const auto dtype = problem.GetScaleBiasDiffDesc().GetType();\n const auto useSaved = problem.UseSaved();\n\n result.invoker_factory = [=](const std::vector& kernels) {\n return [=](const Handle& handle_, const AnyInvokeParams& raw_params) {\n decltype(auto) kernel = handle_.Run(kernels.front());\n decltype(auto) params = raw_params.CastTo();\n\n visit_float(dtype, [&](auto as_float) {\n if(useSaved)\n {\n kernel(params.x,\n params.dy,\n params.dx,\n params.bnScale,\n params.resultBnScaleDiff,\n params.resultBnBiasDiff,\n params.savedMean,\n params.savedInvVariance,\n as_float(inhw));\n }\n else\n {\n kernel(params.x,\n params.dy,\n params.dx,\n params.bnScale,\n params.resultBnScaleDiff,\n params.resultBnBiasDiff,\n params.epsilon,\n inhw);\n }\n });\n };\n };\n\n return result;\n}\n\n} \/\/ namespace batchnorm\n\n} \/\/ namespace solver\n\n} \/\/ namespace miopen\n[Navi21] Fixing Batchnorm backward precision issues by adjusting workgroup size (SWDEV-292187, SWDEV-319919) (#1386)\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2021 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#define WORKAROUND_ISSUE_1146 1 \/\/ check asm solver applicability for gfx90a\n\nnamespace miopen {\n\nnamespace solver {\n\nnamespace batchnorm {\n\nbool BnBwdTrainingSpatialSingle::IsApplicable(\n const ExecutionContext&, const miopen::batchnorm::ProblemDescription& problem) const\n{\n if(problem.GetDirection() != miopen::batchnorm::Direction::Backward ||\n problem.GetMode() != miopenBNSpatial)\n return false;\n\n if(problem.IsLayoutNHWC())\n return true;\n\n int n, c, h, w;\n std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());\n\n unsigned int in_cstride = h * w;\n unsigned int in_nhw = n * in_cstride;\n\n return (in_cstride > 1024 && in_nhw < (32 * 1024 * 1024)) ||\n (in_cstride > 512 && in_nhw < (32 * 1024 * 1024)) || in_cstride <= 512;\n}\n\nConvSolution\nBnBwdTrainingSpatialSingle::GetSolution(const ExecutionContext& context,\n const miopen::batchnorm::ProblemDescription& problem) const\n{\n const auto& handle = context.GetStream();\n const unsigned wavesize = (miopen::StartsWith(handle.GetDeviceName(), \"gfx10\") ? 32 : 64);\n\n bool bfpmixparm = false;\n bool bfp16parm = false;\n bool bfp32parm = true;\n\n if(problem.GetXDesc().GetType() == miopenHalf &&\n problem.GetScaleBiasDiffDesc().GetType() == miopenHalf)\n {\n bfp16parm = true;\n bfp32parm = false;\n }\n else if(problem.GetXDesc().GetType() == miopenHalf &&\n problem.GetScaleBiasDiffDesc().GetType() == miopenFloat)\n {\n bfpmixparm = true;\n bfp32parm = false;\n }\n\n int n, c, h, w;\n std::tie(n, c, h, w) = tien<4>(problem.GetXDesc().GetLengths());\n\n unsigned int in_cstride = h * w;\n unsigned int in_nstride = c * in_cstride;\n unsigned int in_nhw = n * in_cstride;\n unsigned int in_nchw = n * in_nstride;\n\n auto inhw = float(1.0 \/ in_nhw);\n\n size_t xlocalsize = 1;\n size_t ylocalsize = 1;\n\n size_t xgridsize = 1;\n size_t ygridsize = 1;\n\n unsigned int ldsgcn = 0;\n unsigned int ldsnogcn = 0;\n int variant = 1;\n\n if(problem.IsLayoutNHWC())\n {\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n else\n {\n \/\/*************************************************************************************************\n \/\/ N*H*W < 32M and H*W > 1024, use batchnorm variant#1 implementation which parallelize\n \/\/ work groups over channels and loop through NHW.\n \/\/*************************************************************************************************\n if((in_nhw < (32 * 1024 * 1024) && in_cstride > 1024))\n {\n variant = 1;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n \/\/*************************************************************************************************\n \/\/ N*H*W < 32M and H*W > 512 use batchnorm variant#1 or variant#3 implementation which\n \/\/ parallelize\n \/\/ work groups over channels and loop through N.\n \/\/*************************************************************************************************\n else if(in_nhw < (32 * 1024 * 1024) && in_cstride > 512)\n {\n variant = (n >= 32) ? 1 : 3;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n \/\/*************************************************************************************************\n \/\/ H*W < 512 use batchnorm variant#0 or variant#3 implementation based on batch size and\n \/\/ H*W\n \/\/*************************************************************************************************\n else if(in_cstride <= 512)\n {\n if((n > 64) && (in_cstride > 160))\n {\n variant = 3;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n else\n {\n variant = 0;\n xlocalsize = 1024;\n xgridsize = 1024 * c;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n }\n \/\/*************************************************************************************************\n \/\/ N*H*W > 32M, use batchnorm variant#2 implementation which parallelize\n \/\/ work groups over channels and data segments.\n \/\/*************************************************************************************************\n else\n {\n variant = 2;\n ylocalsize = 1024;\n auto segment = int(std::ceil(double(in_cstride) \/ double(ylocalsize)));\n xgridsize = c;\n ygridsize = segment * ylocalsize;\n ldsgcn = ylocalsize \/ wavesize;\n ldsnogcn = ylocalsize;\n }\n if((in_cstride < 200) && (in_cstride > 60) && bfpmixparm)\n {\n variant = 1;\n xlocalsize = 1024;\n xgridsize = c * xlocalsize;\n ldsgcn = xlocalsize \/ wavesize;\n ldsnogcn = xlocalsize;\n }\n }\n auto result = ConvSolution{miopenStatusSuccess};\n\n {\n size_t zlocalsize = 1;\n size_t zgridsize = 1;\n\n auto kernel = KernelInfo{};\n\n auto build_params = KernelBuildParameters{\n {\"MIOPEN_USE_FP16\", static_cast(bfp16parm)},\n {\"MIOPEN_USE_FP32\", static_cast(bfp32parm)},\n {\"MIOPEN_USE_FPMIX\", static_cast(bfpmixparm)},\n {\"MIO_BN_USESAVED\", static_cast(problem.UseSaved())},\n {\"MIO_BN_N\", static_cast(n)},\n {\"MIO_BN_C\", static_cast(c)},\n {\"MIO_BN_HW\", static_cast(in_cstride)},\n {\"MIO_BN_NHW\", static_cast(in_nhw)},\n {\"MIO_BN_CHW\", in_nstride},\n {\"MIO_BN_NCHW\", in_nchw},\n {\"MIO_BN_LDS_SIZE\", ldsnogcn},\n {\"MIO_BN_LDSGCN_SIZE\", ldsgcn},\n {\"MIO_BN_VARIANT\", variant},\n {\"MIO_WAVESIZE\", wavesize},\n {\"MIO_BN_GRP0\", xlocalsize},\n {\"MIO_BN_GRP1\", ylocalsize},\n {\"MIO_BN_GRP2\", zlocalsize},\n {\"MIO_LAYOUT_NHWC\", static_cast(problem.IsLayoutNHWC())},\n };\n\n if((n > 64) && (n % 2 == 0) && (variant == 3) && (bfpmixparm) && (problem.UseSaved()) &&\n context.use_asm_kernels && context.rmv.IsV2orV3() &&\n (StartsWith(handle.GetDeviceName(), \"gfx8\") ||\n (StartsWith(handle.GetDeviceName(), \"gfx9\")\n#if WORKAROUND_ISSUE_1146\n && (handle.GetDeviceName() != \"gfx90a\")\n#endif\n )) &&\n (!handle.GetTargetProperties().Xnack() || !*handle.GetTargetProperties().Xnack()))\n {\n kernel.kernel_file = \"gcnAsmBNBwdTrainSpatial.s\";\n kernel.kernel_name = \"miopenGcnAsmBNBwdTrainSpatial\";\n\n union\n {\n unsigned u32;\n float f32 = 0;\n } NHW_value;\n\n NHW_value.f32 = static_cast(in_nhw);\n\n build_params << KernelBuildParameters{\n {\"ROCM_METADATA_VERSION\", context.rmv.UseV3() ? \"5\" : \"4\"},\n {\"MIO_BN_NHW_FLOAT\", NHW_value.u32},\n };\n\n kernel.comp_options = build_params.GenerateFor(kbp::GcnAsm{});\n }\n else\n {\n kernel.kernel_file = \"MIOpenBatchNormBwdSpatial.cl\";\n kernel.kernel_name = \"MIOpenBatchNormBwdSpatial\";\n\n build_params << KernelBuildParameters{\n {\"MIO_BN_GFX1030\", (handle.GetDeviceName() == \"gfx1030\") ? \"1\" : \"0\"},\n };\n\n kernel.comp_options = build_params.GenerateFor(kbp::OpenCL{});\n }\n\n kernel.l_wk.push_back(xlocalsize);\n kernel.l_wk.push_back(ylocalsize);\n kernel.l_wk.push_back(zlocalsize);\n\n kernel.g_wk.push_back(xgridsize);\n kernel.g_wk.push_back(ygridsize);\n kernel.g_wk.push_back(zgridsize);\n\n result.construction_params.push_back(kernel);\n }\n\n const auto dtype = problem.GetScaleBiasDiffDesc().GetType();\n const auto useSaved = problem.UseSaved();\n\n result.invoker_factory = [=](const std::vector& kernels) {\n return [=](const Handle& handle_, const AnyInvokeParams& raw_params) {\n decltype(auto) kernel = handle_.Run(kernels.front());\n decltype(auto) params = raw_params.CastTo();\n\n visit_float(dtype, [&](auto as_float) {\n if(useSaved)\n {\n kernel(params.x,\n params.dy,\n params.dx,\n params.bnScale,\n params.resultBnScaleDiff,\n params.resultBnBiasDiff,\n params.savedMean,\n params.savedInvVariance,\n as_float(inhw));\n }\n else\n {\n kernel(params.x,\n params.dy,\n params.dx,\n params.bnScale,\n params.resultBnScaleDiff,\n params.resultBnBiasDiff,\n params.epsilon,\n inhw);\n }\n });\n };\n };\n\n return result;\n}\n\n} \/\/ namespace batchnorm\n\n} \/\/ namespace solver\n\n} \/\/ namespace miopen\n<|endoftext|>"} {"text":"\/***************************************************************************\n kmailcvt2.cpp - description\n -------------------\n begin : Wed Aug 2 11:23:04 CEST 2000\n copyright : (C) 2000 by Hans Dijkema\n email : kmailcvt@hum.org\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"kmailcvt.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Add filters here\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"filter_oe4.hxx\"\n#include \"filter_oe5.hxx\"\n#include \"filter_pmail.hxx\"\n#include \"filter_plain.hxx\"\n#include \"filter_pab.hxx\"\n#include \"filter_eudora_ab.hxx\"\n#include \"filter_ldif.hxx\"\n\nKmailcvt2::Kmailcvt2(QWidget *parent, const char *name)\n\t: KWizard(parent, name, true) {\n\n\t_parent = parent;\n\n\tselfilterpage = new KSelFilterPage(this);\n\taddPage( selfilterpage, i18n( \"Step 1: Select filter\" ) );\n\n\timportpage = new KImportPage(this);\n\taddPage( importpage, i18n( \"Step 2: Importing...\" ) );\n\tsetFinishEnabled(QWizard::page(2), false);\n\n\tselfilterpage->addFilter(new filter_oe5);\n\tselfilterpage->addFilter(new filter_pmail);\n\tselfilterpage->addFilter(new filter_plain);\n\tselfilterpage->addFilter(new filter_oe4);\n\tselfilterpage->addFilter(new filter_pab);\n\tselfilterpage->addFilter(new filter_ldif);\n\tselfilterpage->addFilter(new filter_eudora_ab);\n}\n\nKmailcvt2::~Kmailcvt2() {\n}\n\nvoid Kmailcvt2::next() {\n\tif(currentPage()==selfilterpage){\n\t\t\/\/ Save selected filter\n\t\tfilter *selectedFilter = selfilterpage->getSelectedFilter();\n\t\t\/\/ Goto next page\n\t\tQWizard::next();\n\t\t\/\/ Disable cancel & back\n\t\tQWizard::cancelButton()->setEnabled(false);\n\t\tsetBackEnabled(QWizard::currentPage(), false);\n\t\t\/\/ Start import\n\t\tfilterInfo *info = new filterInfo(importpage, _parent);\n\t\tinfo->clear(); \/\/ Clear info from last time\n\t\tselectedFilter->import(info);\n\t\t\/\/ Cleanup\n\t\tdelete info;\n\t\t\/\/ Enable finish button also reenable back\n\t\tsetFinishEnabled(QWizard::currentPage(), true);\n\t\tsetBackEnabled(QWizard::currentPage(), true);\n\t\treturn;\n\t}\n\tQWizard::next();\n}\n\nvoid Kmailcvt2::back() {\n\tQWizard::cancelButton()->setEnabled(true); \/\/ Re-enable cancel\n\tQWizard::back();\n}\n\nvoid Kmailcvt2::help()\n{\n\tKAboutData aboutData( \"KMailCVT\", I18N_NOOP(\"KMAILCVT\"),\n\t\tKMAILCVT_VERSION, KMAILCVT, \n\t\tKAboutData::License_GPL_V2,\n\t\t\"(c) 2000, Hans Dijkema\");\n\taboutData.addAuthor(\"Hans Dijkema\",\"Original author\", \"kmailcvt@hum.org\", \"http:\/\/www.hum.org\/kmailcvt.html\");\n\tselfilterpage->setAuthors(aboutData);\n\n\tKAboutApplication a(&aboutData, _parent);\n\ta.exec();\n}\n\n#include \"kmailcvt.moc\"\nreorder, makes more sense imho\/***************************************************************************\n kmailcvt2.cpp - description\n -------------------\n begin : Wed Aug 2 11:23:04 CEST 2000\n copyright : (C) 2000 by Hans Dijkema\n email : kmailcvt@hum.org\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"kmailcvt.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Add filters here\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"filter_oe4.hxx\"\n#include \"filter_oe5.hxx\"\n#include \"filter_pmail.hxx\"\n#include \"filter_plain.hxx\"\n#include \"filter_pab.hxx\"\n#include \"filter_eudora_ab.hxx\"\n#include \"filter_ldif.hxx\"\n\nKmailcvt2::Kmailcvt2(QWidget *parent, const char *name)\n\t: KWizard(parent, name, true) {\n\n\t_parent = parent;\n\n\tselfilterpage = new KSelFilterPage(this);\n\taddPage( selfilterpage, i18n( \"Step 1: Select filter\" ) );\n\n\timportpage = new KImportPage(this);\n\taddPage( importpage, i18n( \"Step 2: Importing...\" ) );\n\tsetFinishEnabled(QWizard::page(2), false);\n\n\tselfilterpage->addFilter(new filter_oe5);\n\tselfilterpage->addFilter(new filter_oe4);\n\tselfilterpage->addFilter(new filter_pmail);\n\tselfilterpage->addFilter(new filter_plain);\n\tselfilterpage->addFilter(new filter_pab);\n\tselfilterpage->addFilter(new filter_ldif);\n\tselfilterpage->addFilter(new filter_eudora_ab);\n}\n\nKmailcvt2::~Kmailcvt2() {\n}\n\nvoid Kmailcvt2::next() {\n\tif(currentPage()==selfilterpage){\n\t\t\/\/ Save selected filter\n\t\tfilter *selectedFilter = selfilterpage->getSelectedFilter();\n\t\t\/\/ Goto next page\n\t\tQWizard::next();\n\t\t\/\/ Disable cancel & back\n\t\tQWizard::cancelButton()->setEnabled(false);\n\t\tsetBackEnabled(QWizard::currentPage(), false);\n\t\t\/\/ Start import\n\t\tfilterInfo *info = new filterInfo(importpage, _parent);\n\t\tinfo->clear(); \/\/ Clear info from last time\n\t\tselectedFilter->import(info);\n\t\t\/\/ Cleanup\n\t\tdelete info;\n\t\t\/\/ Enable finish button also reenable back\n\t\tsetFinishEnabled(QWizard::currentPage(), true);\n\t\tsetBackEnabled(QWizard::currentPage(), true);\n\t\treturn;\n\t}\n\tQWizard::next();\n}\n\nvoid Kmailcvt2::back() {\n\tQWizard::cancelButton()->setEnabled(true); \/\/ Re-enable cancel\n\tQWizard::back();\n}\n\nvoid Kmailcvt2::help()\n{\n\tKAboutData aboutData( \"KMailCVT\", I18N_NOOP(\"KMAILCVT\"),\n\t\tKMAILCVT_VERSION, KMAILCVT, \n\t\tKAboutData::License_GPL_V2,\n\t\t\"(c) 2000, Hans Dijkema\");\n\taboutData.addAuthor(\"Hans Dijkema\",\"Original author\", \"kmailcvt@hum.org\", \"http:\/\/www.hum.org\/kmailcvt.html\");\n\tselfilterpage->setAuthors(aboutData);\n\n\tKAboutApplication a(&aboutData, _parent);\n\ta.exec();\n}\n\n#include \"kmailcvt.moc\"\n<|endoftext|>"} {"text":"#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n\n#include \n#include \n\n#include \n\nnamespace Dune {\nnamespace Detailed {\nnamespace Discretizations {\n\n\ntemplate< class Traits >\nclass SpaceInterface\n{\npublic:\n typedef typename Traits::derived_type derived_type;\n\n typedef typename Traits::GridPartType GridPartType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridPartType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRangeRows = Traits::dimRangeRows;\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::Container::SparsityPatternDefault PatternType;\n\n const GridPartType& gridPart() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart());\n return asImp().gridPart();\n }\n\n const BackendType& backend() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().backend());\n return asImp().backend();\n }\n\n bool continuous() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous());\n return asImp().continuous();\n }\n\n const MapperType& mapper() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper());\n return asImp().mapper();\n }\n\n BaseFunctionSetType baseFunctionSet(const EntityType& entity) const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity));\n return asImp().baseFunctionSet(entity);\n }\n\n PatternType* computePattern() const\n {\n return computePattern(*this);\n }\n\n template< class OtherSpaceType >\n PatternType* computePattern(const OtherSpaceType& other) const\n {\n \/\/ check type of the other space\n return computePattern(gridPart(), other);\n }\n\n \/**\n * \\brief computes a sparsity pattern, where this space is the test space (rows\/outer) and the other space is the\n * ansatz space (cols\/inner)\n *\/\n template< class LocalGridPartType, class O >\n PatternType* computePattern(const LocalGridPartType& localGridPart,\n const SpaceInterface< O >& otherSpace) const\n {\n typedef typename PatternType::size_type size_type;\n PatternType* ret = new PatternType(mapper().size());\n PatternType& pattern = *ret;\n \/\/ walk the grid part\n for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >();\n entityIt != localGridPart.template end< 0 >();\n ++entityIt) {\n const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt;\n \/\/ get basefunctionsets\n const auto testBase = baseFunctionSet(entity);\n const auto ansatzBase = otherSpace.baseFunctionSet(entity);\n Dune::DynamicVector< size_t > globalRows(testBase.size(), 0);\n mapper().globalIndices(entity, globalRows);\n Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0);\n otherSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < testBase.size(); ++ii) {\n auto& columns = pattern.inner(globalRows[ii]);\n for (size_t jj = 0; jj < ansatzBase.size(); ++jj) {\n columns.insert(globalCols[jj]);\n }\n }\n } \/\/ walk the grid part\n return ret;\n } \/\/ ... computePattern(...)\n\n derived_type& asImp()\n {\n return static_cast< derived_type& >(*this);\n }\n\n const derived_type& asImp() const\n {\n return static_cast< const derived_type& >(*this);\n }\n}; \/\/ class SpaceInterface\n\n\n} \/\/ namespace Discretizations\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n[spaceinterface] added localConstraints()#ifndef DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n\n#include \n#include \n\n#include \n\n#include \"constraints.hh\"\n\nnamespace Dune {\nnamespace Detailed {\nnamespace Discretizations {\n\n\ntemplate< class Traits >\nclass SpaceInterface\n{\npublic:\n typedef typename Traits::derived_type derived_type;\n\n typedef typename Traits::GridPartType GridPartType;\n static const int polOrder = Traits::polOrder;\n typedef typename GridPartType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridPartType::dimension;\n typedef typename Traits::RangeFieldType RangeFieldType;\n static const unsigned int dimRangeRows = Traits::dimRangeRows;\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::Container::SparsityPatternDefault PatternType;\n\n const GridPartType& gridPart() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().gridPart());\n return asImp().gridPart();\n }\n\n const BackendType& backend() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().backend());\n return asImp().backend();\n }\n\n bool continuous() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().continuous());\n return asImp().continuous();\n }\n\n const MapperType& mapper() const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().mapper());\n return asImp().mapper();\n }\n\n BaseFunctionSetType baseFunctionSet(const EntityType& entity) const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().baseFunctionSet(entity));\n return asImp().baseFunctionSet(entity);\n }\n\n template< class ConstraintsType >\n void localConstraints(const EntityType& entity, ConstraintsType& ret) const\n {\n CHECK_INTERFACE_IMPLEMENTATION(asImp().localConstraints(entity, ret));\n asImp().localConstraints(entity, ret);\n }\n\n PatternType* computePattern() const\n {\n return computePattern(*this);\n }\n\n template< class OtherSpaceType >\n PatternType* computePattern(const OtherSpaceType& other) const\n {\n \/\/ check type of the other space\n return computePattern(gridPart(), other);\n }\n\n \/**\n * \\brief computes a sparsity pattern, where this space is the test space (rows\/outer) and the other space is the\n * ansatz space (cols\/inner)\n *\/\n template< class LocalGridPartType, class O >\n PatternType* computePattern(const LocalGridPartType& localGridPart,\n const SpaceInterface< O >& otherSpace) const\n {\n typedef typename PatternType::size_type size_type;\n PatternType* ret = new PatternType(mapper().size());\n PatternType& pattern = *ret;\n \/\/ walk the grid part\n for (typename LocalGridPartType::template Codim< 0 >::IteratorType entityIt = localGridPart.template begin< 0 >();\n entityIt != localGridPart.template end< 0 >();\n ++entityIt) {\n const typename LocalGridPartType::template Codim< 0 >::EntityType& entity = *entityIt;\n \/\/ get basefunctionsets\n const auto testBase = baseFunctionSet(entity);\n const auto ansatzBase = otherSpace.baseFunctionSet(entity);\n Dune::DynamicVector< size_t > globalRows(testBase.size(), 0);\n mapper().globalIndices(entity, globalRows);\n Dune::DynamicVector< size_t > globalCols(ansatzBase.size(), 0);\n otherSpace.mapper().globalIndices(entity, globalCols);\n for (size_t ii = 0; ii < testBase.size(); ++ii) {\n auto& columns = pattern.inner(globalRows[ii]);\n for (size_t jj = 0; jj < ansatzBase.size(); ++jj) {\n columns.insert(globalCols[jj]);\n }\n }\n } \/\/ walk the grid part\n return ret;\n } \/\/ ... computePattern(...)\n\n derived_type& asImp()\n {\n return static_cast< derived_type& >(*this);\n }\n\n const derived_type& asImp() const\n {\n return static_cast< const derived_type& >(*this);\n }\n}; \/\/ class SpaceInterface\n\n\n} \/\/ namespace Discretizations\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_SPACE_INTERFACE_HH\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LinearElliptic {\n\n\ntemplate \nclass ESV2007Problem : public ProblemBase\n{\n static_assert(AlwaysFalse::value, \"Not available for these dimensions!\");\n};\n\n\ntemplate \nclass ESV2007Problem\n : public ProblemBase\n{\n typedef ProblemBase BaseType;\n typedef Stuff::Functions::Constant ScalarConstantFunctionType;\n typedef Stuff::Functions::Constant MatrixConstantFunctionType;\n typedef Stuff::Functions::ESV2007::Testcase1Force ForceType;\n\n template \n struct GridHelper\n {\n static Stuff::Common::Configuration default_grid_cfg()\n {\n \/\/ currently: SGrid, add specialization for other grids, if needed\n auto cfg = Stuff::Grid::Providers::Configs::Cube_default();\n cfg[\"lower_left\"] = \"[-1 -1]\";\n cfg[\"num_elements\"] = \"[8 8]\";\n cfg[\"num_refinements\"] = \"0\";\n return cfg;\n }\n };\n\n template \n struct GridHelper, anything>\n {\n static Stuff::Common::Configuration default_grid_cfg()\n {\n auto cfg = Stuff::Grid::Providers::Configs::Cube_default();\n cfg[\"lower_left\"] = \"[-1 -1]\";\n cfg[\"num_elements\"] = \"[4 4]\";\n cfg[\"num_refinements\"] = \"2\";\n return cfg;\n }\n };\n\n template \n struct Helper\n {\n static_assert(AlwaysFalse::value, \"\");\n };\n\n template class E, bool anything>\n struct Helper, anything>\n {\n static Stuff::Common::Configuration default_grid_cfg()\n {\n return GridHelper::type>::default_grid_cfg();\n }\n };\n\npublic:\n static const size_t default_integration_order = 2;\n\n static Stuff::Common::Configuration default_grid_cfg()\n {\n return Helper::default_grid_cfg();\n }\n\n static Stuff::Common::Configuration default_boundary_info_cfg()\n {\n return Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();\n }\n\n ESV2007Problem(const size_t integration_order = default_integration_order,\n const Stuff::Common::Configuration& grd_cfg = default_grid_cfg(),\n const Stuff::Common::Configuration& bnd_cfg = default_boundary_info_cfg())\n : BaseType(new ScalarConstantFunctionType(1, \"diffusion_factor\"),\n new MatrixConstantFunctionType(Stuff::Functions::internal::unit_matrix(),\n \"diffusion_tensor\"),\n new ForceType(integration_order, \"force\"), new ScalarConstantFunctionType(0, \"dirichlet\"),\n new ScalarConstantFunctionType(0, \"neumann\"), grd_cfg, bnd_cfg)\n {\n }\n}; \/\/ class ESV2007Problem< ..., 1 >\n\n\ntemplate \nclass ESV2007TestCase\n : public Test::StationaryTestCase::Entity,\n typename G::ctype, G::dimension, R, r>>\n{\n typedef typename G::template Codim<0>::Entity E;\n typedef typename G::ctype D;\n static const size_t d = G::dimension;\n typedef Stuff::Functions::ESV2007::Testcase1ExactSolution ExactSolutionType;\n\npublic:\n typedef LinearElliptic::ESV2007Problem ProblemType;\n\nprivate:\n typedef Test::StationaryTestCase BaseType;\n\npublic:\n using typename BaseType::GridType;\n\n ESV2007TestCase(const size_t num_refs = 3)\n : BaseType(Stuff::Grid::Providers::Cube::create(ProblemType::default_grid_cfg())->grid_ptr(), num_refs)\n , problem_()\n , exact_solution_()\n {\n }\n\n virtual const ProblemType& problem() const override final\n {\n return problem_;\n }\n\n virtual void print_header(std::ostream& out = std::cout) const override final\n {\n out << \"+==================================================================+\\n\"\n << \"|+================================================================+|\\n\"\n << \"|| Testcase ESV2007: smooth data, homogeneous dirichlet ||\\n\"\n << \"|| (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007) ||\\n\"\n << \"|+----------------------------------------------------------------+|\\n\"\n << \"|| domain = [-1, 1] x [-1, 1] ||\\n\"\n << \"|| diffusion = 1 ||\\n\"\n << \"|| force = 1\/2 pi^2 cos(1\/2 pi x) cos(1\/2 pi y) ||\\n\"\n << \"|| dirichlet = 0 ||\\n\"\n << \"|| exact solution = cos(1\/2 pi x) cos(1\/2 pi y) ||\\n\"\n << \"|+================================================================+|\\n\"\n << \"+==================================================================+\" << std::endl;\n }\n\n virtual bool provides_exact_solution() const override final\n {\n return true;\n }\n\n virtual const ExactSolutionType& exact_solution() const override final\n {\n return exact_solution_;\n }\n\nprivate:\n const ProblemType problem_;\n const ExactSolutionType exact_solution_;\n}; \/\/ class ESV2007TestCase\n\n\n} \/\/ namespace LinearElliptic\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n[linearelliptic.problems.ESV2007] simplify grid cfg handling\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n#define DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n\n#if HAVE_ALUGRID\n#include \n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LinearElliptic {\n\n\ntemplate \nclass ESV2007Problem : public ProblemBase\n{\n static_assert(AlwaysFalse::value, \"Not available for these dimensions!\");\n};\n\n\ntemplate \nclass ESV2007Problem\n : public ProblemBase\n{\n typedef ProblemBase BaseType;\n typedef Stuff::Functions::Constant ScalarConstantFunctionType;\n typedef Stuff::Functions::Constant MatrixConstantFunctionType;\n typedef Stuff::Functions::ESV2007::Testcase1Force ForceType;\n\n template \n struct Helper\n {\n static_assert(AlwaysFalse::value, \"This should not happen!\");\n };\n\n template class E>\n struct Helper>\n {\n static Stuff::Common::Configuration default_grid_cfg()\n {\n auto cfg = Stuff::Grid::Providers::Configs::Cube_default();\n cfg[\"lower_left\"] = \"[-1 -1]\";\n cfg[\"num_elements\"] = \"[8 8]\";\n cfg[\"num_refinements\"] = \"0\";\n#if HAVE_ALUGRID\n if (std::is_same::type, ALU2dGrid<2, 2, (ALU2DGrid::ElementType)0u>>::value) {\n cfg[\"num_elements\"] = \"[4 4]\";\n cfg[\"num_refinements\"] = \"2\";\n }\n#endif \/\/ HAVE_ALUGRID\n return cfg;\n }\n };\n\npublic:\n static const size_t default_integration_order = 2;\n\n static Stuff::Common::Configuration default_grid_cfg()\n {\n return Helper::default_grid_cfg();\n }\n\n static Stuff::Common::Configuration default_boundary_info_cfg()\n {\n return Stuff::Grid::BoundaryInfoConfigs::AllDirichlet::default_config();\n }\n\n ESV2007Problem(const size_t integration_order = default_integration_order,\n const Stuff::Common::Configuration& grd_cfg = default_grid_cfg(),\n const Stuff::Common::Configuration& bnd_cfg = default_boundary_info_cfg())\n : BaseType(new ScalarConstantFunctionType(1, \"diffusion_factor\"),\n new MatrixConstantFunctionType(Stuff::Functions::internal::unit_matrix(),\n \"diffusion_tensor\"),\n new ForceType(integration_order, \"force\"), new ScalarConstantFunctionType(0, \"dirichlet\"),\n new ScalarConstantFunctionType(0, \"neumann\"), grd_cfg, bnd_cfg)\n {\n }\n}; \/\/ class ESV2007Problem< ..., 1 >\n\n\ntemplate \nclass ESV2007TestCase\n : public Test::StationaryTestCase::Entity,\n typename G::ctype, G::dimension, R, r>>\n{\n typedef typename G::template Codim<0>::Entity E;\n typedef typename G::ctype D;\n static const size_t d = G::dimension;\n typedef Stuff::Functions::ESV2007::Testcase1ExactSolution ExactSolutionType;\n\npublic:\n typedef LinearElliptic::ESV2007Problem ProblemType;\n\nprivate:\n typedef Test::StationaryTestCase BaseType;\n\npublic:\n using typename BaseType::GridType;\n\n ESV2007TestCase(const size_t num_refs = 3)\n : BaseType(Stuff::Grid::Providers::Cube::create(ProblemType::default_grid_cfg())->grid_ptr(), num_refs)\n , problem_()\n , exact_solution_()\n {\n }\n\n virtual const ProblemType& problem() const override final\n {\n return problem_;\n }\n\n virtual void print_header(std::ostream& out = std::cout) const override final\n {\n out << \"+==================================================================+\\n\"\n << \"|+================================================================+|\\n\"\n << \"|| Testcase ESV2007: smooth data, homogeneous dirichlet ||\\n\"\n << \"|| (see testcase 1, page 23 in Ern, Stephansen, Vohralik, 2007) ||\\n\"\n << \"|+----------------------------------------------------------------+|\\n\"\n << \"|| domain = [-1, 1] x [-1, 1] ||\\n\"\n << \"|| diffusion = 1 ||\\n\"\n << \"|| force = 1\/2 pi^2 cos(1\/2 pi x) cos(1\/2 pi y) ||\\n\"\n << \"|| dirichlet = 0 ||\\n\"\n << \"|| exact solution = cos(1\/2 pi x) cos(1\/2 pi y) ||\\n\"\n << \"|+================================================================+|\\n\"\n << \"+==================================================================+\" << std::endl;\n }\n\n virtual bool provides_exact_solution() const override final\n {\n return true;\n }\n\n virtual const ExactSolutionType& exact_solution() const override final\n {\n return exact_solution_;\n }\n\nprivate:\n const ProblemType problem_;\n const ExactSolutionType exact_solution_;\n}; \/\/ class ESV2007TestCase\n\n\n} \/\/ namespace LinearElliptic\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_TESTS_LINEARELLIPTIC_PROBLEMS_ESV2007_HH\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2011 James Molloy, Jörg Pfähler, Matthew Iselin\n*\n* Permission to use, copy, modify, and distribute this software for any\n* purpose with or without fee is hereby granted, provided that the above\n* copyright notice and this permission notice appear in all copies.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"NativeSyscallManager.h\"\n#include \n\nNativeSyscallManager::NativeSyscallManager()\n{\n}\n\nNativeSyscallManager::~NativeSyscallManager()\n{\n}\n\nvoid NativeSyscallManager::initialise()\n{\n SyscallManager::instance().registerSyscallHandler(native, this);\n}\n\nuintptr_t NativeSyscallManager::call(uintptr_t function, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5)\n{\n if (function >= serviceEnd)\n {\n ERROR(\"NativeSyscallManager: invalid function called: \" << Dec << static_cast(function));\n return 0;\n }\n return SyscallManager::instance().syscall(posix, function, p1, p2, p3, p4, p5);\n}\n\nuintptr_t NativeSyscallManager::syscall(SyscallState &state)\n{\n uintptr_t p1 = state.getSyscallParameter(0);\n uintptr_t p2 = state.getSyscallParameter(1);\n uintptr_t p3 = state.getSyscallParameter(2);\n uintptr_t p4 = state.getSyscallParameter(3);\n uintptr_t p5 = state.getSyscallParameter(4);\n\n \/\/ We're interruptible.\n Processor::setInterrupts(true);\n\n \/\/ NOTICE(\"Native syscall \" << state.getSyscallNumber() << \" (\" << p1 << \", \" << p2 << \", \" << p3 << \", \" << p4 << \", \" << p5);\n\n switch (state.getSyscallNumber())\n {\n case IPC_CREATE_STANDARD_MESSAGE:\n return createStandardMessage(reinterpret_cast(p1));\n case IPC_CREATE_SHARED_MESSAGE:\n return createSharedMessage(reinterpret_cast(p1), static_cast(p2), p3);\n case IPC_GET_SHARED_REGION:\n return reinterpret_cast(getIpcSharedRegion(reinterpret_cast(p1)));\n case IPC_DESTROY_MESSAGE:\n destroyMessage(reinterpret_cast(p1));\n break;\n\n case IPC_SEND_IPC:\n return static_cast(sendIpc(reinterpret_cast(p1),reinterpret_cast(p2), static_cast(p3)));\n case IPC_RECV_PHASE1:\n return reinterpret_cast(recvIpcPhase1(reinterpret_cast(p1), static_cast(p2)));\n case IPC_RECV_PHASE2:\n return recvIpcPhase2(reinterpret_cast(p1), reinterpret_cast(p2));\n\n case IPC_CREATE_ENDPOINT:\n createEndpoint(reinterpret_cast(p1));\n break;\n case IPC_REMOVE_ENDPOINT:\n removeEndpoint(reinterpret_cast(p1));\n break;\n case IPC_GET_ENDPOINT:\n return reinterpret_cast(getEndpoint(reinterpret_cast(p1)));\n break;\n\n default: ERROR (\"NativeSyscallManager: invalid syscall received: \" << Dec << state.getSyscallNumber()); return 0;\n }\n\n return 0;\n}\nnative: native syscall timing (alerts if ~ > 1s spent in a syscall)\/*\n* Copyright (c) 2011 James Molloy, Jörg Pfähler, Matthew Iselin\n*\n* Permission to use, copy, modify, and distribute this software for any\n* purpose with or without fee is hereby granted, provided that the above\n* copyright notice and this permission notice appear in all copies.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n\n#define MACHINE_FORWARD_DECL_ONLY\n#include \n#include \n\n#include \n#include \n\n#include \"NativeSyscallManager.h\"\n#include \n\nNativeSyscallManager::NativeSyscallManager()\n{\n}\n\nNativeSyscallManager::~NativeSyscallManager()\n{\n}\n\nvoid NativeSyscallManager::initialise()\n{\n SyscallManager::instance().registerSyscallHandler(native, this);\n}\n\nuintptr_t NativeSyscallManager::call(uintptr_t function, uintptr_t p1, uintptr_t p2, uintptr_t p3, uintptr_t p4, uintptr_t p5)\n{\n if (function >= serviceEnd)\n {\n ERROR(\"NativeSyscallManager: invalid function called: \" << Dec << static_cast(function));\n return 0;\n }\n\n uintptr_t ret = SyscallManager::instance().syscall(native, function, p1, p2, p3, p4, p5);\n return ret;\n}\n\nclass SyscallTimer\n{\n public:\n SyscallTimer(uintptr_t func) : function(func), t1(0), t2(0), p1(0), p2(0)\n {\n Timer *pTimer = Machine::instance().getTimer();\n t1 = pTimer->getUnixTimestamp();\n p1 = pTimer->getTickCount();\n }\n\n ~SyscallTimer()\n {\n Timer *pTimer = Machine::instance().getTimer();\n t2 = pTimer->getUnixTimestamp();\n p2 = pTimer->getTickCount();\n\n if(t2 - t1)\n {\n NOTICE(\"native: syscall \" << function);\n NOTICE(\" -> start=\" << t1 << \" (\" << p1 << \")\");\n NOTICE(\" -> end=\" << t2 << \" (\" << p2 << \")\");\n }\n }\n\n private:\n uintptr_t function;\n uint64_t t1, t2;\n uint64_t p1, p2;\n};\n\nuintptr_t NativeSyscallManager::syscall(SyscallState &state)\n{\n uintptr_t p1 = state.getSyscallParameter(0);\n uintptr_t p2 = state.getSyscallParameter(1);\n uintptr_t p3 = state.getSyscallParameter(2);\n uintptr_t p4 = state.getSyscallParameter(3);\n uintptr_t p5 = state.getSyscallParameter(4);\n\n \/\/ We're interruptible.\n Processor::setInterrupts(true);\n\n \/\/ NOTICE(\"Native syscall \" << state.getSyscallNumber() << \" (\" << p1 << \", \" << p2 << \", \" << p3 << \", \" << p4 << \", \" << p5);\n \n SyscallTimer timeme(state.getSyscallNumber());\n\n switch (state.getSyscallNumber())\n {\n case IPC_CREATE_STANDARD_MESSAGE:\n return createStandardMessage(reinterpret_cast(p1));\n case IPC_CREATE_SHARED_MESSAGE:\n return createSharedMessage(reinterpret_cast(p1), static_cast(p2), p3);\n case IPC_GET_SHARED_REGION:\n return reinterpret_cast(getIpcSharedRegion(reinterpret_cast(p1)));\n case IPC_DESTROY_MESSAGE:\n destroyMessage(reinterpret_cast(p1));\n break;\n\n case IPC_SEND_IPC:\n return static_cast(sendIpc(reinterpret_cast(p1),reinterpret_cast(p2), static_cast(p3)));\n case IPC_RECV_PHASE1:\n return reinterpret_cast(recvIpcPhase1(reinterpret_cast(p1), static_cast(p2)));\n case IPC_RECV_PHASE2:\n return recvIpcPhase2(reinterpret_cast(p1), reinterpret_cast(p2));\n\n case IPC_CREATE_ENDPOINT:\n createEndpoint(reinterpret_cast(p1));\n break;\n case IPC_REMOVE_ENDPOINT:\n removeEndpoint(reinterpret_cast(p1));\n break;\n case IPC_GET_ENDPOINT:\n return reinterpret_cast(getEndpoint(reinterpret_cast(p1)));\n break;\n\n default: ERROR (\"NativeSyscallManager: invalid syscall received: \" << Dec << state.getSyscallNumber()); return 0;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef ENGINE_IGNITER_RENDERER_THREAD_CALLBABLE_BY_PLATFORM_HPP\n#define ENGINE_IGNITER_RENDERER_THREAD_CALLBABLE_BY_PLATFORM_HPP\n#pragma once\n\n#include \"..\/renderer_thread.hpp\"\n\nnamespace engine\n{\n\n namespace global\n {\n\n class renderer_thread_callable_by_platform_t : public renderer_thread_t\n {\n\n public:\n\n };\n\n }\n\n}\n\n#endifFixed typo in #ifndef header#ifndef ENGINE_IGNITER_RENDERER_THREAD_CALLABLE_BY_PLATFORM_HPP\n#define ENGINE_IGNITER_RENDERER_THREAD_CALLABLE_BY_PLATFORM_HPP\n#pragma once\n\n#include \"..\/renderer_thread.hpp\"\n\nnamespace engine\n{\n\n namespace global\n {\n\n class renderer_thread_callable_by_platform_t : public renderer_thread_t\n {\n\n public:\n\n };\n\n }\n\n}\n\n#endif<|endoftext|>"} {"text":"\/* Copyright 2014 Open Source Robotics Foundation, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_\n#define RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace rclcpp\n{\nnamespace executors\n{\nnamespace single_threaded_executor\n{\n\nclass SingleThreadedExecutor : public executor::Executor\n{\npublic:\n RCLCPP_MAKE_SHARED_DEFINITIONS(SingleThreadedExecutor);\n\n SingleThreadedExecutor() {}\n\n ~SingleThreadedExecutor() {}\n\n void spin()\n {\n while (rclcpp::utilities::ok())\n {\n auto any_exec = get_next_executable();\n execute_any_executable(any_exec);\n }\n }\n\n void spin_node_some(rclcpp::node::Node &node)\n {\n reset_subscriber_handles();\n populate_subscriber_handles_with_node(node);\n \/\/ non-blocking = true\n auto any_exec = get_next_executable(true);\n while (any_exec->subscription)\n {\n execute_subscription(any_exec->subscription);\n \/\/ non-blocking = true\n any_exec = get_next_executable(true);\n }\n reset_subscriber_handles();\n }\n\nprivate:\n RCLCPP_DISABLE_COPY(SingleThreadedExecutor);\n\n std::vector> weak_nodes_;\n\n};\n\n} \/* namespace single_threaded_executor *\/\n} \/* namespace executors *\/\n} \/* namespace rclcpp *\/\n\n#endif \/* RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_ *\/\nSTE: remove vestigial overlaid storage for nodes\/* Copyright 2014 Open Source Robotics Foundation, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_\n#define RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace rclcpp\n{\nnamespace executors\n{\nnamespace single_threaded_executor\n{\n\nclass SingleThreadedExecutor : public executor::Executor\n{\npublic:\n RCLCPP_MAKE_SHARED_DEFINITIONS(SingleThreadedExecutor);\n\n SingleThreadedExecutor() {}\n\n ~SingleThreadedExecutor() {}\n\n void spin()\n {\n while (rclcpp::utilities::ok())\n {\n auto any_exec = get_next_executable();\n execute_any_executable(any_exec);\n }\n }\n\n void spin_node_some(rclcpp::node::Node &node)\n {\n reset_subscriber_handles();\n populate_subscriber_handles_with_node(node);\n \/\/ non-blocking = true\n auto any_exec = get_next_executable(true);\n while (any_exec->subscription)\n {\n execute_subscription(any_exec->subscription);\n \/\/ non-blocking = true\n any_exec = get_next_executable(true);\n }\n reset_subscriber_handles();\n }\n\nprivate:\n RCLCPP_DISABLE_COPY(SingleThreadedExecutor);\n\n};\n\n} \/* namespace single_threaded_executor *\/\n} \/* namespace executors *\/\n} \/* namespace rclcpp *\/\n\n#endif \/* RCLCPP_RCLCPP_EXECUTORS_SINGLE_THREADED_EXECUTOR_HPP_ *\/\n<|endoftext|>"} {"text":"#include \n#include \n\nusing namespace threadPool;\n\nTEST(TestThreadPool, SimpleQueue) {\n\tstd::atomic_int ct(0);\n\n\tThreadPool threadPool;\n\tthreadPool.spawnThread([&ct](int) { ++ct; sleep(1); }, 5);\n\n\tfor (int i(0); i<10; ++i) {\n\t\tthreadPool.queue(0);\n\t}\n\tthreadPool.wait();\n\n\tEXPECT_EQ(ct, 10);\n}\nTEST(TestThreadPool, SimpleQueue2) {\n\tfor (int j(0); j<100; ++j) {\n\t\tstd::atomic_int ct(0);\n\t\tThreadPool threadPool;\n\t\tthreadPool.spawnThread([&ct](int) { ++ct; }, 5);\n\n\t\tfor (int i(0); i<10; ++i) {\n\t\t\tthreadPool.queue(0);\n\t\t}\n\t\tthreadPool.wait();\n\n\t\tEXPECT_EQ(ct, 10);\n\t}\n}\n\nTEST(TestThreadPool, RecursiveQueue) {\n\tstd::atomic_int ct(0);\n\n\tThreadPool threadPool;\n\tthreadPool.spawnThread([&ct, &threadPool](int _ct) {\n\t\t++ct; sleep(1);\n\t\tif (_ct > 0)\n\t\t\tthreadPool.queue(_ct-1);\n\t}, 5);\n\n\tfor (int i(0); i<10; ++i) {\n\t\tthreadPool.queue(1);\n\t}\n\tthreadPool.wait();\n\n\tEXPECT_EQ(ct, 20);\n}\n\nTEST(TestThreadPool, RecursiveQueue2) {\n\tfor (int j(0); j<100; ++j) {\n\n\t\tstd::atomic_int ct(0);\n\t\tThreadPool threadPool;\n\t\tthreadPool.spawnThread([&ct, &threadPool](int _ct) {\n\t\t\t++ct;\n\t\t\tif (_ct > 0)\n\t\t\t\tthreadPool.queue(_ct-1);\n\t\t}, 5);\n\n\n\n\t\tfor (int i(0); i<10; ++i) {\n\t\t\tthreadPool.queue(1);\n\t\t}\n\t\tthreadPool.wait();\n\n\t\tEXPECT_EQ(ct, 20);\n\t}\n}\n\nremoving sleeps for faster unit testing#include \n#include \n\nusing namespace threadPool;\n\nTEST(TestThreadPool, SimpleQueue) {\n\tstd::atomic_int ct(0);\n\n\tThreadPool threadPool;\n\tthreadPool.spawnThread([&ct](int) { ++ct; }, 5);\n\n\tfor (int i(0); i<10; ++i) {\n\t\tthreadPool.queue(0);\n\t}\n\tthreadPool.wait();\n\n\tEXPECT_EQ(ct, 10);\n}\nTEST(TestThreadPool, SimpleQueue2) {\n\tfor (int j(0); j<100; ++j) {\n\t\tstd::atomic_int ct(0);\n\t\tThreadPool threadPool;\n\t\tthreadPool.spawnThread([&ct](int) { ++ct; }, 5);\n\n\t\tfor (int i(0); i<10; ++i) {\n\t\t\tthreadPool.queue(0);\n\t\t}\n\t\tthreadPool.wait();\n\n\t\tEXPECT_EQ(ct, 10);\n\t}\n}\n\nTEST(TestThreadPool, RecursiveQueue) {\n\tstd::atomic_int ct(0);\n\n\tThreadPool threadPool;\n\tthreadPool.spawnThread([&ct, &threadPool](int _ct) {\n\t\t++ct;\n\t\tif (_ct > 0)\n\t\t\tthreadPool.queue(_ct-1);\n\t}, 5);\n\n\tfor (int i(0); i<10; ++i) {\n\t\tthreadPool.queue(1);\n\t}\n\tthreadPool.wait();\n\n\tEXPECT_EQ(ct, 20);\n}\n\nTEST(TestThreadPool, RecursiveQueue2) {\n\tfor (int j(0); j<100; ++j) {\n\n\t\tstd::atomic_int ct(0);\n\t\tThreadPool threadPool;\n\t\tthreadPool.spawnThread([&ct, &threadPool](int _ct) {\n\t\t\t++ct;\n\t\t\tif (_ct > 0)\n\t\t\t\tthreadPool.queue(_ct-1);\n\t\t}, 5);\n\n\n\n\t\tfor (int i(0); i<10; ++i) {\n\t\t\tthreadPool.queue(1);\n\t\t}\n\t\tthreadPool.wait();\n\n\t\tEXPECT_EQ(ct, 20);\n\t}\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AIndexes.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 02:13:44 $\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#ifndef _CONNECTIVITY_ADO_INDEXES_HXX_\n#include \"ado\/AIndexes.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_INDEX_HXX_\n#include \"ado\/AIndex.hxx\"\n#endif\n#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_\n#include \"ado\/AConnection.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#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_\n#include \n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include \n#endif\n\nusing namespace ::comphelper;\n\n\nusing namespace connectivity;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::container;\n\nsdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)\n{\n return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OIndexes::impl_refresh() throw(RuntimeException)\n{\n m_aCollection.Refresh();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OIndexes::createDescriptor()\n{\n return new OAdoIndex(isCaseSensitive(),m_pConnection);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OIndexes::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )\n{\n OAdoIndex* pIndex = NULL;\n if ( !getImplementation(pIndex,descriptor) || pIndex == NULL )\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create index: invalid object descriptor.\" ),\n static_cast(this)\n );\n\n ADOIndexes* pIndexes = m_aCollection;\n if ( FAILED( pIndexes->Append( OLEVariant( _rForName ), OLEVariant( pIndex->getImpl() ) ) ) )\n {\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not append index.\" ),\n static_cast(this)\n );\n }\n\n return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OIndexes::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n m_aCollection.Delete(_sElementName);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\nINTEGRATION: CWS changefileheader (1.16.216); FILE MERGED 2008\/04\/01 15:08:36 thb 1.16.216.3: #i85898# Stripping all external header guards 2008\/04\/01 10:52:49 thb 1.16.216.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:26 rt 1.16.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: AIndexes.cxx,v $\n * $Revision: 1.17 $\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\/AIndexes.hxx\"\n#include \"ado\/AIndex.hxx\"\n#include \"ado\/AConnection.hxx\"\n#include \n#include \n#include \n#include \"TConnection.hxx\"\n#include \n#include \n\nusing namespace ::comphelper;\n\n\nusing namespace connectivity;\nusing namespace connectivity::ado;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::container;\n\nsdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)\n{\n return new OAdoIndex(isCaseSensitive(),m_pConnection,m_aCollection.GetItem(_rName));\n}\n\/\/ -------------------------------------------------------------------------\nvoid OIndexes::impl_refresh() throw(RuntimeException)\n{\n m_aCollection.Refresh();\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > OIndexes::createDescriptor()\n{\n return new OAdoIndex(isCaseSensitive(),m_pConnection);\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XAppend\nsdbcx::ObjectType OIndexes::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )\n{\n OAdoIndex* pIndex = NULL;\n if ( !getImplementation(pIndex,descriptor) || pIndex == NULL )\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not create index: invalid object descriptor.\" ),\n static_cast(this)\n );\n\n ADOIndexes* pIndexes = m_aCollection;\n if ( FAILED( pIndexes->Append( OLEVariant( _rForName ), OLEVariant( pIndex->getImpl() ) ) ) )\n {\n ADOS::ThrowException(*m_pConnection->getConnection(),static_cast(this));\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii( \"Could not append index.\" ),\n static_cast(this)\n );\n }\n\n return new OAdoIndex(isCaseSensitive(),m_pConnection,pIndex->getImpl());\n}\n\/\/ -------------------------------------------------------------------------\n\/\/ XDrop\nvoid OIndexes::dropObject(sal_Int32 \/*_nPos*\/,const ::rtl::OUString _sElementName)\n{\n m_aCollection.Delete(_sElementName);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ These declarations should remain global because we have to refer to\n\/\/ them in utility functions that are living outside of `main()`.\nusing DataType = double;\nusing VertexType = unsigned short;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\n\nSimplicialComplex makeFiltration( const SimplicialComplex& K, bool upper = false )\n{\n std::vector simplices;\n simplices.reserve( K.size() );\n\n std::transform( K.begin(), K.end(), std::back_inserter( simplices ),\n [&upper] ( const Simplex& s )\n {\n if( ( upper && s.data() > DataType() ) || ( !upper && s.data() < DataType() ) )\n return s;\n\n \/\/ Copy the simplex but set its weight to be zero because it does\n \/\/ not correspond to any structure that we want to learn.\n else\n {\n std::vector vertices( s.begin(), s.end() );\n return Simplex( s.begin(), s.end(), DataType() );\n }\n }\n );\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\nSimplicialComplex makeLowerFiltration( const SimplicialComplex& K )\n{\n auto L = makeFiltration( K );\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n\n return L;\n}\n\nSimplicialComplex makeUpperFiltration( const SimplicialComplex& K )\n{\n auto L = makeFiltration( K, true );\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n\n return makeFiltration( K, true );\n}\n\nusing PersistenceDiagram = aleph::PersistenceDiagram;\nusing Point = typename PersistenceDiagram::Point;\n\nPersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )\n{\n PersistenceDiagram F;\n\n if( D.dimension() != F.dimension() )\n throw std::runtime_error( \"Persistence diagram dimensions have to agree\" );\n\n for( auto&& diagram : { D, E } )\n for( auto&& p : diagram )\n F.add( p.x(), p.y() );\n\n return F;\n}\n\nint main( int argc, char** argv )\n{\n bool absolute = false;\n bool cycles = false;\n bool minimum = false;\n bool normalize = false;\n bool calculateDiagrams = false;\n bool calculateTrajectories = false;\n\n {\n static option commandLineOptions[] =\n {\n { \"absolute\" , no_argument, nullptr, 'a' },\n { \"cycles\" , no_argument, nullptr, 'c' },\n { \"minimum\" , no_argument, nullptr, 'm' },\n { \"normalize\" , no_argument, nullptr, 'n' },\n { \"persistence-diagrams\", no_argument, nullptr, 'p' },\n { \"trajectories\" , no_argument, nullptr, 't' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"acmnpt\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'a':\n absolute = true;\n break;\n case 'c':\n cycles = true;\n break;\n case 'm':\n minimum = true;\n break;\n case 'n':\n normalize = true;\n break;\n case 'p':\n calculateDiagrams = true;\n break;\n case 't':\n calculateTrajectories = true;\n break;\n default:\n break;\n }\n }\n }\n\n \/\/ 1. Read simplicial complexes --------------------------------------\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind - 1 ) );\n\n std::vector minData;\n std::vector maxData;\n\n minData.reserve( simplicialComplexes.size() );\n maxData.reserve( simplicialComplexes.size() );\n\n {\n aleph::topology::io::BipartiteAdjacencyMatrixReader reader;\n\n if( absolute )\n reader.setUseAbsoluteValues();\n\n if( minimum )\n reader.setAssignMinimumVertexWeight();\n\n for( int i = optind; i < argc; i++ )\n {\n auto filename = std::string( argv[i] );\n\n std::cerr << \"* Processing \" << filename << \"...\";\n\n SimplicialComplex K;\n reader( filename, K );\n\n std::cerr << \"finished\\n\";\n\n DataType minData_ = std::numeric_limits::max();\n DataType maxData_ = std::numeric_limits::lowest();\n\n \/\/ *Always* determine minimum and maximum weights so that we may\n \/\/ report them later on. They are only used for normalization in\n \/\/ the persistence diagram calculation step.\n for( auto&& s : K )\n {\n minData_ = std::min( minData_, s.data() );\n maxData_ = std::max( maxData_, s.data() );\n }\n\n minData.push_back( minData_ );\n maxData.push_back( maxData_ );\n\n simplicialComplexes.emplace_back( K );\n }\n }\n\n \/\/ 2. Calculate persistent homology ----------------------------------\n\n using Matrix = aleph::math::SymmetricMatrix;\n\n \/\/ Stores the distance matrix for the trajectories of persistence\n \/\/ diagrams. This will only be used if the client set the correct\n \/\/ flag.\n Matrix trajectoryDistances;\n if( calculateTrajectories )\n trajectoryDistances = Matrix( simplicialComplexes.size() );\n\n using PersistenceDiagram = aleph::PersistenceDiagram;\n using Point = typename PersistenceDiagram::Point;\n\n \/\/ Stores the zeroth persistence diagram for calculating trajectories\n \/\/ later on. This may need to be extended in order to handle diagrams\n \/\/ with higher-dimensional features.\n std::vector trajectoryDiagrams;\n if( calculateTrajectories )\n trajectoryDiagrams.reserve( simplicialComplexes.size() );\n\n for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )\n {\n bool dualize = true;\n bool includeAllUnpairedCreators = cycles;\n\n auto&& K = simplicialComplexes[i];\n auto diagrams = aleph::calculatePersistenceDiagrams(\n K,\n dualize,\n includeAllUnpairedCreators\n );\n auto&& D = diagrams.back(); \/\/ always use the last diagram; in the\n \/\/ absence of another mechanism, this\n \/\/ will always give us the features in\n \/\/ the highest dimension.\n\n D.removeDiagonal();\n if( !cycles )\n D.removeUnpaired();\n\n if( normalize )\n {\n \/\/ Ensures that points are in [-1:+1] or [0:1] if absolute values\n \/\/ have been selected by the client.\n std::transform( D.begin(), D.end(), D.begin(),\n [&absolute, &i, &minData, &maxData] ( const Point& p )\n {\n auto x = p.x();\n auto y = p.y();\n\n if( absolute )\n {\n x = (x - minData[i]) \/ (maxData[i] - minData[i]);\n y = (y - minData[i]) \/ (maxData[i] - minData[i]);\n }\n else\n {\n x = 2 * (x - minData[i]) \/ (maxData[i] - minData[i]) - 1;\n y = 2 * (y - minData[i]) \/ (maxData[i] - minData[i]) - 1;\n }\n\n return Point( x,y );\n }\n );\n }\n\n if( cycles )\n {\n std::transform( D.begin(), D.end(), D.begin(),\n [] ( const Point& p )\n {\n auto x = p.x();\n auto y = DataType();\n\n return Point( x,y );\n }\n );\n }\n\n \/\/ Determine mode of operation -------------------------------------\n \/\/\n \/\/ Several modes of operation exist for this program. They can be\n \/\/ set using the flags specified above. At present, the following\n \/\/ operations are possible:\n \/\/\n \/\/ - Calculate persistence diagrams\n \/\/ - Calculate persistence diagram trajectories\n \/\/ - Calculate 2-norm of the persistence diagrams\n\n if( calculateDiagrams )\n std::cout << D << \"\\n\\n\";\n else if( calculateTrajectories )\n trajectoryDiagrams.push_back( D );\n else\n std::cout << i << \"\\t\" << aleph::pNorm( D ) << \"\\n\";\n }\n\n \/\/ Need to calculate the trajectories afterwards because they require\n \/\/ building a database of persistence diagrams.\n if( calculateTrajectories )\n {\n for( std::size_t i = 0; i < trajectoryDiagrams.size(); i++ )\n {\n auto&& Di = trajectoryDiagrams[i];\n\n for( std::size_t j = i+1; j < trajectoryDiagrams.size(); j++ )\n {\n auto&& Dj = trajectoryDiagrams[j];\n auto dist = aleph::distances::hausdorffDistance(\n Di, Dj\n );\n\n trajectoryDistances(i,j) = dist;\n }\n }\n\n \/\/ FIXME: replace with proper layout\n std::cout << trajectoryDistances;\n }\n}\nAdded support for merged persistence diagrams#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ These declarations should remain global because we have to refer to\n\/\/ them in utility functions that are living outside of `main()`.\nusing DataType = double;\nusing VertexType = unsigned short;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\n\nSimplicialComplex makeFiltration( const SimplicialComplex& K, bool upper = false )\n{\n std::vector simplices;\n simplices.reserve( K.size() );\n\n std::transform( K.begin(), K.end(), std::back_inserter( simplices ),\n [&upper] ( const Simplex& s )\n {\n if( ( upper && s.data() > DataType() ) || ( !upper && s.data() < DataType() ) )\n return s;\n\n \/\/ Copy the simplex but set its weight to be zero because it does\n \/\/ not correspond to any structure that we want to learn.\n else\n {\n std::vector vertices( s.begin(), s.end() );\n return Simplex( s.begin(), s.end(), DataType() );\n }\n }\n );\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\nSimplicialComplex makeLowerFiltration( const SimplicialComplex& K )\n{\n auto L = makeFiltration( K );\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n\n return L;\n}\n\nSimplicialComplex makeUpperFiltration( const SimplicialComplex& K )\n{\n auto L = makeFiltration( K, true );\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n\n return makeFiltration( K, true );\n}\n\nusing PersistenceDiagram = aleph::PersistenceDiagram;\nusing Point = typename PersistenceDiagram::Point;\n\nPersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )\n{\n PersistenceDiagram F;\n\n if( D.dimension() != F.dimension() )\n throw std::runtime_error( \"Persistence diagram dimensions have to agree\" );\n\n for( auto&& diagram : { D, E } )\n for( auto&& p : diagram )\n F.add( p.x(), p.y() );\n\n return F;\n}\n\nint main( int argc, char** argv )\n{\n bool absolute = false;\n bool cycles = false;\n bool filtration = false;\n bool minimum = false;\n bool normalize = false;\n bool calculateDiagrams = false;\n bool calculateTrajectories = false;\n\n {\n static option commandLineOptions[] =\n {\n { \"absolute\" , no_argument, nullptr, 'a' },\n { \"cycles\" , no_argument, nullptr, 'c' },\n { \"filtration\" , no_argument, nullptr, 'f' },\n { \"minimum\" , no_argument, nullptr, 'm' },\n { \"normalize\" , no_argument, nullptr, 'n' },\n { \"persistence-diagrams\", no_argument, nullptr, 'p' },\n { \"trajectories\" , no_argument, nullptr, 't' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"acfmnpt\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'a':\n absolute = true;\n break;\n case 'c':\n cycles = true;\n break;\n case 'f':\n filtration = true;\n break;\n case 'm':\n minimum = true;\n break;\n case 'n':\n normalize = true;\n break;\n case 'p':\n calculateDiagrams = true;\n break;\n case 't':\n calculateTrajectories = true;\n break;\n default:\n break;\n }\n }\n }\n\n \/\/ 1. Read simplicial complexes --------------------------------------\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind - 1 ) );\n\n std::vector minData;\n std::vector maxData;\n\n minData.reserve( simplicialComplexes.size() );\n maxData.reserve( simplicialComplexes.size() );\n\n {\n aleph::topology::io::BipartiteAdjacencyMatrixReader reader;\n\n if( absolute )\n reader.setUseAbsoluteValues();\n\n if( minimum )\n reader.setAssignMinimumVertexWeight();\n\n for( int i = optind; i < argc; i++ )\n {\n auto filename = std::string( argv[i] );\n\n std::cerr << \"* Processing \" << filename << \"...\";\n\n SimplicialComplex K;\n reader( filename, K );\n\n std::cerr << \"finished\\n\";\n\n DataType minData_ = std::numeric_limits::max();\n DataType maxData_ = std::numeric_limits::lowest();\n\n \/\/ *Always* determine minimum and maximum weights so that we may\n \/\/ report them later on. They are only used for normalization in\n \/\/ the persistence diagram calculation step.\n for( auto&& s : K )\n {\n minData_ = std::min( minData_, s.data() );\n maxData_ = std::max( maxData_, s.data() );\n }\n\n minData.push_back( minData_ );\n maxData.push_back( maxData_ );\n\n simplicialComplexes.emplace_back( K );\n }\n }\n\n \/\/ 2. Calculate persistent homology ----------------------------------\n\n using Matrix = aleph::math::SymmetricMatrix;\n\n \/\/ Stores the distance matrix for the trajectories of persistence\n \/\/ diagrams. This will only be used if the client set the correct\n \/\/ flag.\n Matrix trajectoryDistances;\n if( calculateTrajectories )\n trajectoryDistances = Matrix( simplicialComplexes.size() );\n\n \/\/ Stores the zeroth persistence diagram for calculating trajectories\n \/\/ later on. This may need to be extended in order to handle diagrams\n \/\/ with higher-dimensional features.\n std::vector trajectoryDiagrams;\n if( calculateTrajectories )\n trajectoryDiagrams.reserve( simplicialComplexes.size() );\n\n for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )\n {\n \/\/ The persistence diagram that will be used in the subsequent\n \/\/ analysis. This does not necessarily have to stem from data,\n \/\/ but can be calculated from a suitable transformation.\n PersistenceDiagram D;\n\n bool dualize = true;\n bool includeAllUnpairedCreators = cycles;\n\n auto&& K = simplicialComplexes[i];\n\n if( filtration )\n {\n auto L = makeLowerFiltration( K );\n auto U = makeUpperFiltration( K );\n\n auto lowerDiagrams = aleph::calculatePersistenceDiagrams(\n L,\n dualize,\n includeAllUnpairedCreators\n );\n\n auto upperDiagrams = aleph::calculatePersistenceDiagrams(\n U,\n dualize,\n includeAllUnpairedCreators\n );\n\n D = merge( lowerDiagrams.back(), upperDiagrams.back() );\n }\n else\n {\n auto diagrams = aleph::calculatePersistenceDiagrams(\n K,\n dualize,\n includeAllUnpairedCreators\n );\n\n D = diagrams.back(); \/\/ Use the *last* diagram of the filtration so that\n \/\/ we get features in the highest dimension.\n }\n\n D.removeDiagonal();\n if( !cycles )\n D.removeUnpaired();\n\n if( normalize )\n {\n \/\/ Ensures that points are in [-1:+1] or [0:1] if absolute values\n \/\/ have been selected by the client.\n std::transform( D.begin(), D.end(), D.begin(),\n [&absolute, &i, &minData, &maxData] ( const Point& p )\n {\n auto x = p.x();\n auto y = p.y();\n\n if( absolute )\n {\n x = (x - minData[i]) \/ (maxData[i] - minData[i]);\n y = (y - minData[i]) \/ (maxData[i] - minData[i]);\n }\n else\n {\n x = 2 * (x - minData[i]) \/ (maxData[i] - minData[i]) - 1;\n y = 2 * (y - minData[i]) \/ (maxData[i] - minData[i]) - 1;\n }\n\n return Point( x,y );\n }\n );\n }\n\n if( cycles )\n {\n std::transform( D.begin(), D.end(), D.begin(),\n [] ( const Point& p )\n {\n auto x = p.x();\n auto y = DataType();\n\n return Point( x,y );\n }\n );\n }\n\n \/\/ Determine mode of operation -------------------------------------\n \/\/\n \/\/ Several modes of operation exist for this program. They can be\n \/\/ set using the flags specified above. At present, the following\n \/\/ operations are possible:\n \/\/\n \/\/ - Calculate persistence diagrams\n \/\/ - Calculate persistence diagram trajectories\n \/\/ - Calculate 2-norm of the persistence diagrams\n\n if( calculateDiagrams )\n std::cout << D << \"\\n\\n\";\n else if( calculateTrajectories )\n trajectoryDiagrams.push_back( D );\n else\n std::cout << i << \"\\t\" << aleph::pNorm( D ) << \"\\n\";\n }\n\n \/\/ Need to calculate the trajectories afterwards because they require\n \/\/ building a database of persistence diagrams.\n if( calculateTrajectories )\n {\n for( std::size_t i = 0; i < trajectoryDiagrams.size(); i++ )\n {\n auto&& Di = trajectoryDiagrams[i];\n\n for( std::size_t j = i+1; j < trajectoryDiagrams.size(); j++ )\n {\n auto&& Dj = trajectoryDiagrams[j];\n auto dist = aleph::distances::hausdorffDistance(\n Di, Dj\n );\n\n trajectoryDistances(i,j) = dist;\n }\n }\n\n \/\/ FIXME: replace with proper layout\n std::cout << trajectoryDistances;\n }\n}\n<|endoftext|>"} {"text":"#ifndef RESOLVER_DATA_TYPE_HPP\n#define RESOLVER_DATA_TYPE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nenum struct AllDirection { Same, Up, UpperRight, Right, DownerRight, Down, DownerLeft, Left, UpperLeft };\n\nstruct point_type\n{\n int x;\n int y;\n\n inline std::string const str() const\n {\n return ( boost::format(\"(%1%,%2%)\") % this->x % this->y ).str();\n }\n inline uint16_t num() const\n {\n return this->x * 16 + this->y;\n }\n\n friend inline bool operator== (point_type const& lhs, point_type const& rhs)\n {\n return lhs.x == rhs.x && lhs.y == rhs.y;\n }\n friend inline point_type const operator- (point_type const& lhs, point_type const& rhs)\n {\n return point_type{lhs.x - rhs.x, lhs.y - rhs.y};\n }\n friend inline point_type const operator+ (point_type const& lhs, point_type const& rhs)\n {\n return point_type{lhs.x + rhs.x, lhs.y + rhs.y};\n }\n\n inline int manhattan(point_type const& other) const\n {\n return std::abs(this->x - other.x) + std::abs(this->y - other.y);\n }\n template\n inline T euclid(point_type const& other) const\n {\n return std::sqrt(\n std::pow(this->x - other.x, 2) + \n std::pow(this->y - other.y, 2)\n );\n }\n\n inline point_type const up() const\n {\n return point_type{this->x, this->y - 1};\n }\n inline point_type const right() const\n {\n return point_type{this->x + 1, this->y};\n }\n inline point_type const down() const\n {\n return point_type{this->x, this->y + 1};\n }\n inline point_type const left() const\n {\n return point_type{this->x - 1, this->y};\n }\n\n inline AllDirection direction(point_type const& point)\n {\n point_type diff = *this - point;\n if (diff.x < 0) {\n if (diff.y < 0) {\n return AllDirection::DownerRight;\n } else if (diff.y > 0) {\n return AllDirection::UpperRight;\n } else {\n return AllDirection::Right;\n }\n } else if (diff.x > 0) {\n if (diff.y < 0) {\n return AllDirection::DownerLeft;\n } else if (diff.y > 0) {\n return AllDirection::UpperLeft;\n } else {\n return AllDirection::Left;\n }\n } else {\n if (diff.y < 0) {\n return AllDirection::Down;\n } else if (diff.y > 0) {\n return AllDirection::Up;\n } else {\n return AllDirection::Same;\n }\n }\n }\n\n friend std::size_t hash_value(point_type const& point)\n {\n std::size_t seed = 0;\n boost::hash_combine(seed, point.x);\n boost::hash_combine(seed, point.y);\n return seed;\n }\n};\n\ntypedef cv::Vec3b pixel_type;\ntypedef std::vector unfold_image_type;\ntypedef cv::Mat_ image_type;\n\n\/\/ [i][j]の位置に分割された画像(cv::Mat_)が入っている.\ntypedef std::vector> split_image_type;\n\nstruct question_data : private boost::noncopyable\n{\n int problem_id;\n std::string player_id;\n\n std::pair size;\n int selectable;\n int cost_select;\n int cost_change;\n std::vector> block;\n\n question_data(\n int const problem_id,\n std::string const& player_id,\n std::pair const& size,\n int const selectable,\n int const cost_select,\n int const cost_change,\n std::vector> const& block\n )\n : problem_id(problem_id), player_id(player_id), size(size), selectable(selectable), cost_select(cost_select), cost_change(cost_change), block(block)\n {\n }\n\n question_data(question_data&& other)\n {\n *this = std::move(other);\n }\n question_data& operator=(question_data&& other)\n {\n this->problem_id = other.problem_id;\n this->player_id = other.player_id;\n this->size = std::move(other.size);\n this->selectable = other.selectable;\n this->cost_select = other.cost_select;\n this->cost_change = other.cost_change;\n this->block = std::move(other.block);\n return *this;\n }\n\n question_data clone() const\n {\n return question_data{\n problem_id,\n player_id,\n size,\n selectable,\n cost_select,\n cost_change,\n block\n };\n }\n};\n\nstruct question_raw_data : private boost::noncopyable\n{\n std::pair split_num; \/\/ x * y\n int selectable_num;\n std::pair cost; \/\/ 選択コスト \/ 交換コスト\n std::pair size; \/\/ x * y\n int max_brightness; \/\/ 最大輝度\n image_type pixels;\n \n question_raw_data()\n {\n }\n question_raw_data(question_raw_data&& other)\n {\n *this = std::move(other);\n }\n question_raw_data& operator=(question_raw_data&& other)\n {\n this->split_num = std::move(other.split_num);\n this->selectable_num = other.selectable_num;\n this->cost = std::move(other.cost);\n this->size = std::move(other.size);\n this->max_brightness = other.max_brightness;\n this->pixels = std::move(other.pixels);\n return *this;\n }\n};\n\n\/\/ 斜め方向を表す列挙型\nenum struct DiagonalDirection { UpperRight, DownerRight, DownerLeft, UpperLeft };\n\n\/\/ 水平垂直方向を表す列挙型\nenum struct HVDirection { Up, Right, Down, Left };\n\n\/\/ 八方を表す列挙型\n\/\/enum struct AllDirection { Same, Up, UpperRight, Right, DownerRight, Down, DownerLeft, Left, UpperLeft };\n\ninline char direction_char(HVDirection const& d)\n{\n return \"URDL\"[static_cast(d)];\n}\n\nstruct answer_line\n{\n point_type select;\n std::vector change_list;\n};\nstruct answer_type\n{\n std::vector list;\n\n std::string const& str() const\n {\n static std::string answer_string;\n\n answer_string.erase(answer_string.begin(), answer_string.end());\n for (auto step : list) {\n answer_string += (boost::format(\"%1$02X\") % step.select.num()).str();\n answer_string.push_back('\\n');\n for (auto direction : step.change_list) {\n answer_string.push_back(direction_char(direction));\n }\n answer_string.push_back('\\n');\n }\n\n return answer_string;\n }\n};\n\nstruct step_type {\n answer_type answer;\n point_type selecting_cur;\n std::vector> matrix;\n\n friend bool operator== (step_type const& lhs, step_type const& rhs)\n {\n return lhs.matrix == rhs.matrix;\n }\n};\n\ntemplate\nstruct direction_type\n{\n \/\/ 所謂CSSなどの順番に記述\n T up;\n T right;\n T down;\n T left;\n};\n\n\/\/ ostream に吐けると便利だよね\ntemplate\nstd::basic_ostream&\noperator<< (std::basic_ostream& os, point_type const& point)\n{\n os << point.str();\n return os;\n}\n\n\/\/sort_algorithm\ntypedef std::vector>>>> compared_type;\ntypedef std::vector>> adjacent_type;\n\nnamespace std\n{\n template <>\n struct hash\n {\n std::size_t operator() (step_type const& step) const\n {\n std::size_t result;\n for (auto row : step.matrix) {\n for (auto point : row) {\n boost::hash_combine(result, point);\n }\n }\n return result;\n }\n };\n\n template <>\n struct hash\n {\n std::size_t operator() (point_type const& point) const\n {\n return hash_value(point);\n }\n };\n}\n\n#endif\n不要になった列挙型の削除#ifndef RESOLVER_DATA_TYPE_HPP\n#define RESOLVER_DATA_TYPE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nenum struct AllDirection { Same, Up, UpperRight, Right, DownerRight, Down, DownerLeft, Left, UpperLeft };\n\nstruct point_type\n{\n int x;\n int y;\n\n inline std::string const str() const\n {\n return ( boost::format(\"(%1%,%2%)\") % this->x % this->y ).str();\n }\n inline uint16_t num() const\n {\n return this->x * 16 + this->y;\n }\n\n friend inline bool operator== (point_type const& lhs, point_type const& rhs)\n {\n return lhs.x == rhs.x && lhs.y == rhs.y;\n }\n friend inline point_type const operator- (point_type const& lhs, point_type const& rhs)\n {\n return point_type{lhs.x - rhs.x, lhs.y - rhs.y};\n }\n friend inline point_type const operator+ (point_type const& lhs, point_type const& rhs)\n {\n return point_type{lhs.x + rhs.x, lhs.y + rhs.y};\n }\n\n inline int manhattan(point_type const& other) const\n {\n return std::abs(this->x - other.x) + std::abs(this->y - other.y);\n }\n template\n inline T euclid(point_type const& other) const\n {\n return std::sqrt(\n std::pow(this->x - other.x, 2) + \n std::pow(this->y - other.y, 2)\n );\n }\n\n inline point_type const up() const\n {\n return point_type{this->x, this->y - 1};\n }\n inline point_type const right() const\n {\n return point_type{this->x + 1, this->y};\n }\n inline point_type const down() const\n {\n return point_type{this->x, this->y + 1};\n }\n inline point_type const left() const\n {\n return point_type{this->x - 1, this->y};\n }\n\n inline AllDirection direction(point_type const& point)\n {\n point_type diff = *this - point;\n if (diff.x < 0) {\n if (diff.y < 0) {\n return AllDirection::DownerRight;\n } else if (diff.y > 0) {\n return AllDirection::UpperRight;\n } else {\n return AllDirection::Right;\n }\n } else if (diff.x > 0) {\n if (diff.y < 0) {\n return AllDirection::DownerLeft;\n } else if (diff.y > 0) {\n return AllDirection::UpperLeft;\n } else {\n return AllDirection::Left;\n }\n } else {\n if (diff.y < 0) {\n return AllDirection::Down;\n } else if (diff.y > 0) {\n return AllDirection::Up;\n } else {\n return AllDirection::Same;\n }\n }\n }\n\n friend std::size_t hash_value(point_type const& point)\n {\n std::size_t seed = 0;\n boost::hash_combine(seed, point.x);\n boost::hash_combine(seed, point.y);\n return seed;\n }\n};\n\ntypedef cv::Vec3b pixel_type;\ntypedef std::vector unfold_image_type;\ntypedef cv::Mat_ image_type;\n\n\/\/ [i][j]の位置に分割された画像(cv::Mat_)が入っている.\ntypedef std::vector> split_image_type;\n\nstruct question_data : private boost::noncopyable\n{\n int problem_id;\n std::string player_id;\n\n std::pair size;\n int selectable;\n int cost_select;\n int cost_change;\n std::vector> block;\n\n question_data(\n int const problem_id,\n std::string const& player_id,\n std::pair const& size,\n int const selectable,\n int const cost_select,\n int const cost_change,\n std::vector> const& block\n )\n : problem_id(problem_id), player_id(player_id), size(size), selectable(selectable), cost_select(cost_select), cost_change(cost_change), block(block)\n {\n }\n\n question_data(question_data&& other)\n {\n *this = std::move(other);\n }\n question_data& operator=(question_data&& other)\n {\n this->problem_id = other.problem_id;\n this->player_id = other.player_id;\n this->size = std::move(other.size);\n this->selectable = other.selectable;\n this->cost_select = other.cost_select;\n this->cost_change = other.cost_change;\n this->block = std::move(other.block);\n return *this;\n }\n\n question_data clone() const\n {\n return question_data{\n problem_id,\n player_id,\n size,\n selectable,\n cost_select,\n cost_change,\n block\n };\n }\n};\n\nstruct question_raw_data : private boost::noncopyable\n{\n std::pair split_num; \/\/ x * y\n int selectable_num;\n std::pair cost; \/\/ 選択コスト \/ 交換コスト\n std::pair size; \/\/ x * y\n int max_brightness; \/\/ 最大輝度\n image_type pixels;\n \n question_raw_data()\n {\n }\n question_raw_data(question_raw_data&& other)\n {\n *this = std::move(other);\n }\n question_raw_data& operator=(question_raw_data&& other)\n {\n this->split_num = std::move(other.split_num);\n this->selectable_num = other.selectable_num;\n this->cost = std::move(other.cost);\n this->size = std::move(other.size);\n this->max_brightness = other.max_brightness;\n this->pixels = std::move(other.pixels);\n return *this;\n }\n};\n\n\/\/ 水平垂直方向を表す列挙型\nenum struct HVDirection { Up, Right, Down, Left };\n\ninline char direction_char(HVDirection const& d)\n{\n return \"URDL\"[static_cast(d)];\n}\n\nstruct answer_line\n{\n point_type select;\n std::vector change_list;\n};\nstruct answer_type\n{\n std::vector list;\n\n std::string const& str() const\n {\n static std::string answer_string;\n\n answer_string.erase(answer_string.begin(), answer_string.end());\n for (auto step : list) {\n answer_string += (boost::format(\"%1$02X\") % step.select.num()).str();\n answer_string.push_back('\\n');\n for (auto direction : step.change_list) {\n answer_string.push_back(direction_char(direction));\n }\n answer_string.push_back('\\n');\n }\n\n return answer_string;\n }\n};\n\nstruct step_type {\n answer_type answer;\n point_type selecting_cur;\n std::vector> matrix;\n\n friend bool operator== (step_type const& lhs, step_type const& rhs)\n {\n return lhs.matrix == rhs.matrix;\n }\n};\n\ntemplate\nstruct direction_type\n{\n \/\/ 所謂CSSなどの順番に記述\n T up;\n T right;\n T down;\n T left;\n};\n\n\/\/ ostream に吐けると便利だよね\ntemplate\nstd::basic_ostream&\noperator<< (std::basic_ostream& os, point_type const& point)\n{\n os << point.str();\n return os;\n}\n\n\/\/sort_algorithm\ntypedef std::vector>>>> compared_type;\ntypedef std::vector>> adjacent_type;\n\nnamespace std\n{\n template <>\n struct hash\n {\n std::size_t operator() (step_type const& step) const\n {\n std::size_t result;\n for (auto row : step.matrix) {\n for (auto point : row) {\n boost::hash_combine(result, point);\n }\n }\n return result;\n }\n };\n\n template <>\n struct hash\n {\n std::size_t operator() (point_type const& point) const\n {\n return hash_value(point);\n }\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/===--- IndexerMain.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\/\/\n\/\/ clangd-indexer is a tool to gather index data (symbols, xrefs) from source.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"index\/IndexAction.h\"\n#include \"index\/Merge.h\"\n#include \"index\/Ref.h\"\n#include \"index\/Serialization.h\"\n#include \"index\/Symbol.h\"\n#include \"index\/SymbolCollector.h\"\n#include \"clang\/Tooling\/CommonOptionsParser.h\"\n#include \"clang\/Tooling\/Execution.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nnamespace clang {\nnamespace clangd {\nnamespace {\n\nstatic llvm::cl::opt\n Format(\"format\", llvm::cl::desc(\"Format of the index to be written\"),\n llvm::cl::values(clEnumValN(IndexFileFormat::YAML, \"yaml\",\n \"human-readable YAML format\"),\n clEnumValN(IndexFileFormat::RIFF, \"binary\",\n \"binary RIFF format\")),\n llvm::cl::init(IndexFileFormat::RIFF));\n\nclass IndexActionFactory : public tooling::FrontendActionFactory {\npublic:\n IndexActionFactory(IndexFileIn &Result) : Result(Result) {}\n\n clang::FrontendAction *create() override {\n SymbolCollector::Options Opts;\n return createStaticIndexingAction(\n Opts,\n [&](SymbolSlab S) {\n \/\/ Merge as we go.\n std::lock_guard Lock(SymbolsMu);\n for (const auto &Sym : S) {\n if (const auto *Existing = Symbols.find(Sym.ID))\n Symbols.insert(mergeSymbol(*Existing, Sym));\n else\n Symbols.insert(Sym);\n }\n },\n [&](RefSlab S) {\n std::lock_guard Lock(SymbolsMu);\n for (const auto &Sym : S) {\n \/\/ No need to merge as currently all Refs are from main file.\n for (const auto &Ref : Sym.second)\n Refs.insert(Sym.first, Ref);\n }\n },\n \/*IncludeGraphCallback=*\/nullptr)\n .release();\n }\n\n \/\/ Awkward: we write the result in the destructor, because the executor\n \/\/ takes ownership so it's the easiest way to get our data back out.\n ~IndexActionFactory() {\n Result.Symbols = std::move(Symbols).build();\n Result.Refs = std::move(Refs).build();\n }\n\nprivate:\n IndexFileIn &Result;\n std::mutex SymbolsMu;\n SymbolSlab::Builder Symbols;\n RefSlab::Builder Refs;\n};\n\n} \/\/ namespace\n} \/\/ namespace clangd\n} \/\/ namespace clang\n\nint main(int argc, const char **argv) {\n llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);\n\n const char *Overview = R\"(\n Creates an index of symbol information etc in a whole project.\n\n Example usage for a project using CMake compile commands:\n\n $ clangd-indexer --executor=all-TUs compile_commands.json > clangd.dex\n\n Example usage for file sequence index without flags:\n\n $ clangd-indexer File1.cpp File2.cpp ... FileN.cpp > clangd.dex\n\n Note: only symbols from header files will be indexed.\n )\";\n\n auto Executor = clang::tooling::createExecutorFromCommandLineArgs(\n argc, argv, llvm::cl::GeneralCategory, Overview);\n\n if (!Executor) {\n llvm::errs() << llvm::toString(Executor.takeError()) << \"\\n\";\n return 1;\n }\n\n \/\/ Collect symbols found in each translation unit, merging as we go.\n clang::clangd::IndexFileIn Data;\n auto Err = Executor->get()->execute(\n llvm::make_unique(Data));\n if (Err) {\n llvm::errs() << llvm::toString(std::move(Err)) << \"\\n\";\n }\n\n \/\/ Emit collected data.\n clang::clangd::IndexFileOut Out(Data);\n Out.Format = clang::clangd::Format;\n llvm::outs() << Out;\n return 0;\n}\n[clangd] Strip plugin arguments in clangd-indexer.\/\/===--- IndexerMain.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\/\/\n\/\/ clangd-indexer is a tool to gather index data (symbols, xrefs) from source.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"index\/IndexAction.h\"\n#include \"index\/Merge.h\"\n#include \"index\/Ref.h\"\n#include \"index\/Serialization.h\"\n#include \"index\/Symbol.h\"\n#include \"index\/SymbolCollector.h\"\n#include \"clang\/Tooling\/ArgumentsAdjusters.h\"\n#include \"clang\/Tooling\/CommonOptionsParser.h\"\n#include \"clang\/Tooling\/Execution.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nnamespace clang {\nnamespace clangd {\nnamespace {\n\nstatic llvm::cl::opt\n Format(\"format\", llvm::cl::desc(\"Format of the index to be written\"),\n llvm::cl::values(clEnumValN(IndexFileFormat::YAML, \"yaml\",\n \"human-readable YAML format\"),\n clEnumValN(IndexFileFormat::RIFF, \"binary\",\n \"binary RIFF format\")),\n llvm::cl::init(IndexFileFormat::RIFF));\n\nclass IndexActionFactory : public tooling::FrontendActionFactory {\npublic:\n IndexActionFactory(IndexFileIn &Result) : Result(Result) {}\n\n clang::FrontendAction *create() override {\n SymbolCollector::Options Opts;\n return createStaticIndexingAction(\n Opts,\n [&](SymbolSlab S) {\n \/\/ Merge as we go.\n std::lock_guard Lock(SymbolsMu);\n for (const auto &Sym : S) {\n if (const auto *Existing = Symbols.find(Sym.ID))\n Symbols.insert(mergeSymbol(*Existing, Sym));\n else\n Symbols.insert(Sym);\n }\n },\n [&](RefSlab S) {\n std::lock_guard Lock(SymbolsMu);\n for (const auto &Sym : S) {\n \/\/ No need to merge as currently all Refs are from main file.\n for (const auto &Ref : Sym.second)\n Refs.insert(Sym.first, Ref);\n }\n },\n \/*IncludeGraphCallback=*\/nullptr)\n .release();\n }\n\n \/\/ Awkward: we write the result in the destructor, because the executor\n \/\/ takes ownership so it's the easiest way to get our data back out.\n ~IndexActionFactory() {\n Result.Symbols = std::move(Symbols).build();\n Result.Refs = std::move(Refs).build();\n }\n\nprivate:\n IndexFileIn &Result;\n std::mutex SymbolsMu;\n SymbolSlab::Builder Symbols;\n RefSlab::Builder Refs;\n};\n\n} \/\/ namespace\n} \/\/ namespace clangd\n} \/\/ namespace clang\n\nint main(int argc, const char **argv) {\n llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);\n\n const char *Overview = R\"(\n Creates an index of symbol information etc in a whole project.\n\n Example usage for a project using CMake compile commands:\n\n $ clangd-indexer --executor=all-TUs compile_commands.json > clangd.dex\n\n Example usage for file sequence index without flags:\n\n $ clangd-indexer File1.cpp File2.cpp ... FileN.cpp > clangd.dex\n\n Note: only symbols from header files will be indexed.\n )\";\n\n auto Executor = clang::tooling::createExecutorFromCommandLineArgs(\n argc, argv, llvm::cl::GeneralCategory, Overview);\n\n if (!Executor) {\n llvm::errs() << llvm::toString(Executor.takeError()) << \"\\n\";\n return 1;\n }\n\n \/\/ Collect symbols found in each translation unit, merging as we go.\n clang::clangd::IndexFileIn Data;\n auto Err = Executor->get()->execute(\n llvm::make_unique(Data),\n clang::tooling::getStripPluginsAdjuster());\n if (Err) {\n llvm::errs() << llvm::toString(std::move(Err)) << \"\\n\";\n }\n\n \/\/ Emit collected data.\n clang::clangd::IndexFileOut Out(Data);\n Out.Format = clang::clangd::Format;\n llvm::outs() << Out;\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n\nvoid test_rtl_2_ltr(size_t idx_rtl,\n size_t idx_ltr,\n const std::vector& dims) {\n stan::json::vars_map_r vars_r;\n stan::json::vars_map_i vars_i;\n stan::json::json_data_handler handler(vars_r, vars_i);\n EXPECT_TRUE(handler.is_int_ == 0 || handler.is_int_ == 1);\n size_t idx = handler.convert_offset_rtl_2_ltr(idx_rtl,dims);\n EXPECT_EQ(idx, idx_ltr);\n}\n\nvoid test_exception(size_t idx_rtl,\n const std::string& exception_text,\n const std::vector& dims) {\n stan::json::vars_map_r vars_r;\n stan::json::vars_map_i vars_i;\n stan::json::json_data_handler handler(vars_r, vars_i);\n try {\n handler.convert_offset_rtl_2_ltr(idx_rtl,dims);\n } catch (const std::exception& e) {\n EXPECT_EQ(e.what(), exception_text);\n return;\n }\n FAIL(); \/\/ didn't throw an exception as expected.\n}\n\n\nTEST(ioJson,rtl_2_ltr_1) {\n std::vector dims(1);\n dims[0] = 7;\n test_rtl_2_ltr(0,0,dims);\n test_rtl_2_ltr(1,1,dims);\n test_rtl_2_ltr(2,2,dims);\n test_rtl_2_ltr(3,3,dims);\n test_rtl_2_ltr(4,4,dims);\n test_rtl_2_ltr(5,5,dims);\n test_rtl_2_ltr(6,6,dims);\n}\n\n\/\/ row major:\n\/\/ 11 12 13 14 21 22 23 24\n\/\/ column major:\n\/\/ 11 21 12 22 13 23 14 24\n\nTEST(ioJson,rtl_2_ltr_2) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_rtl_2_ltr(0,0,dims);\n test_rtl_2_ltr(1,2,dims);\n test_rtl_2_ltr(2,4,dims);\n test_rtl_2_ltr(3,6,dims);\n test_rtl_2_ltr(4,1,dims);\n test_rtl_2_ltr(5,3,dims);\n test_rtl_2_ltr(6,5,dims);\n test_rtl_2_ltr(7,7,dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_1) {\n std::vector dims(1);\n dims[0] = 7;\n test_exception(7,\"variable: , unexpected error\",dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_2) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_exception(8,\"variable: , unexpected error\",dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_3n) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_exception(11,\"variable: , unexpected error\",dims);\n}\nfinal testing for undefined bools, fixes #2344#include \n\n#include \n#include \n#include \n#include \n#include \n\nvoid test_rtl_2_ltr(size_t idx_rtl,\n size_t idx_ltr,\n const std::vector& dims) {\n stan::json::vars_map_r vars_r;\n stan::json::vars_map_i vars_i;\n stan::json::json_data_handler handler(vars_r, vars_i);\n\n size_t idx = handler.convert_offset_rtl_2_ltr(idx_rtl,dims);\n EXPECT_EQ(idx, idx_ltr);\n}\n\nvoid test_exception(size_t idx_rtl,\n const std::string& exception_text,\n const std::vector& dims) {\n stan::json::vars_map_r vars_r;\n stan::json::vars_map_i vars_i;\n stan::json::json_data_handler handler(vars_r, vars_i);\n try {\n handler.convert_offset_rtl_2_ltr(idx_rtl,dims);\n } catch (const std::exception& e) {\n EXPECT_EQ(e.what(), exception_text);\n return;\n }\n FAIL(); \/\/ didn't throw an exception as expected.\n}\n\n\nTEST(ioJson,rtl_2_ltr_1) {\n std::vector dims(1);\n dims[0] = 7;\n test_rtl_2_ltr(0,0,dims);\n test_rtl_2_ltr(1,1,dims);\n test_rtl_2_ltr(2,2,dims);\n test_rtl_2_ltr(3,3,dims);\n test_rtl_2_ltr(4,4,dims);\n test_rtl_2_ltr(5,5,dims);\n test_rtl_2_ltr(6,6,dims);\n}\n\n\/\/ row major:\n\/\/ 11 12 13 14 21 22 23 24\n\/\/ column major:\n\/\/ 11 21 12 22 13 23 14 24\n\nTEST(ioJson,rtl_2_ltr_2) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_rtl_2_ltr(0,0,dims);\n test_rtl_2_ltr(1,2,dims);\n test_rtl_2_ltr(2,4,dims);\n test_rtl_2_ltr(3,6,dims);\n test_rtl_2_ltr(4,1,dims);\n test_rtl_2_ltr(5,3,dims);\n test_rtl_2_ltr(6,5,dims);\n test_rtl_2_ltr(7,7,dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_1) {\n std::vector dims(1);\n dims[0] = 7;\n test_exception(7,\"variable: , unexpected error\",dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_2) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_exception(8,\"variable: , unexpected error\",dims);\n}\n\nTEST(ioJson,rtl_2_ltr_err_3n) {\n std::vector dims(2);\n dims[0] = 2;\n dims[1] = 4;\n test_exception(11,\"variable: , unexpected error\",dims);\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 8\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\nOpenCV release (3.4.8)\/\/ 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 8\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":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header:\n\n\n#include \n\n#include \n#include \n#include \n\n\nvoid Decrement(int& x) \n{ \n --x; \n}\n\nstruct UserDatabase\n{\n void AddFriend(const std::string&, const std::string&)\n {\n throw 55;\n }\n};\n\nclass User\n{\npublic:\n User(UserDatabase* db) : fCount(0), pDB_(db)\n {}\n\n std::string GetName();\n\n void AddFriend(User& newFriend);\n void AddFriendGuarded(User& newFriend);\n\n size_t countFriends();\n \n int fCount;\n\nprivate:\n typedef std::vector UserCont;\n UserCont friends_;\n UserDatabase* pDB_;\n};\n\nstd::string User::GetName()\n{\n return \"A name\";\n}\n\nsize_t User::countFriends()\n{\n return friends_.size();\n}\n\nvoid User::AddFriend(User& newFriend)\n{\n friends_.push_back(&newFriend);\n fCount++;\n pDB_->AddFriend(GetName(), newFriend.GetName());\n}\n\nvoid User::AddFriendGuarded(User& newFriend)\n{\n friends_.push_back(&newFriend);\n Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);\n \n fCount++;\n Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));\n\n pDB_->AddFriend(GetName(), newFriend.GetName());\n guard.Dismiss();\n guardRef.Dismiss();\n}\n\n\nint main()\n{\n UserDatabase db;\n\n User u1(&db);\n User u2(&db);\n\n try{ u1.AddFriend(u2); }\n catch (...){}\n std::cout << \"u1 countFriends: \" << u1.countFriends() << \"\\n\";\n std::cout << \"u1 fCount : \" << u1.fCount << \"\\n\";\n\n try{ u2.AddFriendGuarded(u1); }\n catch (...){}\n std::cout << \"u2 countFriends: \" << u2.countFriends() << \"\\n\";\n std::cout << \"u2 fCount : \" << u2.fCount << \"\\n\";\n\n#if defined(__BORLANDC__) || defined(_MSC_VER)\n system(\"PAUSE\");\n#endif\n\n}\nFixed syntax for CVS keyword.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ The Loki Library\n\/\/ Copyright (c) 2006 Peter Kmmel\n\/\/ Permission to use, copy, modify, distribute and sell this software for any \n\/\/ purpose is hereby granted without fee, provided that the above copyright \n\/\/ notice appear in all copies and that both that copyright notice and this \n\/\/ permission notice appear in supporting documentation.\n\/\/ The author makes no representations about the \n\/\/ suitability of this software for any purpose. It is provided \"as is\" \n\/\/ without express or implied warranty.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header$\n\n\n#include \n\n#include \n#include \n#include \n\n\nvoid Decrement(int& x) \n{ \n --x; \n}\n\nstruct UserDatabase\n{\n void AddFriend(const std::string&, const std::string&)\n {\n throw 55;\n }\n};\n\nclass User\n{\npublic:\n User(UserDatabase* db) : fCount(0), pDB_(db)\n {}\n\n std::string GetName();\n\n void AddFriend(User& newFriend);\n void AddFriendGuarded(User& newFriend);\n\n size_t countFriends();\n \n int fCount;\n\nprivate:\n typedef std::vector UserCont;\n UserCont friends_;\n UserDatabase* pDB_;\n};\n\nstd::string User::GetName()\n{\n return \"A name\";\n}\n\nsize_t User::countFriends()\n{\n return friends_.size();\n}\n\nvoid User::AddFriend(User& newFriend)\n{\n friends_.push_back(&newFriend);\n fCount++;\n pDB_->AddFriend(GetName(), newFriend.GetName());\n}\n\nvoid User::AddFriendGuarded(User& newFriend)\n{\n friends_.push_back(&newFriend);\n Loki::ScopeGuard guard = Loki::MakeObjGuard(friends_, &UserCont::pop_back);\n \n fCount++;\n Loki::ScopeGuard guardRef = Loki::MakeGuard(Decrement, Loki::ByRef(fCount));\n\n pDB_->AddFriend(GetName(), newFriend.GetName());\n guard.Dismiss();\n guardRef.Dismiss();\n}\n\n\nint main()\n{\n UserDatabase db;\n\n User u1(&db);\n User u2(&db);\n\n try{ u1.AddFriend(u2); }\n catch (...){}\n std::cout << \"u1 countFriends: \" << u1.countFriends() << \"\\n\";\n std::cout << \"u1 fCount : \" << u1.fCount << \"\\n\";\n\n try{ u2.AddFriendGuarded(u1); }\n catch (...){}\n std::cout << \"u2 countFriends: \" << u2.countFriends() << \"\\n\";\n std::cout << \"u2 fCount : \" << u2.fCount << \"\\n\";\n\n#if defined(__BORLANDC__) || defined(_MSC_VER)\n system(\"PAUSE\");\n#endif\n\n}\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#define SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL 0\n\n#include \"Support\/StringSplit.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace support;\nusing namespace support::strings;\n\ntemplate \nclass RangeConverter\n{\n Range const& R;\n\npublic:\n RangeConverter(Range const& R)\n : R(R)\n {\n }\n\n template \n operator Container() const\n {\n return Container(R.begin(), R.end());\n }\n};\n\ntemplate \nRangeConverter convert(Range const& R)\n{\n return RangeConverter(R);\n}\n\n\/\/TEST(StringSplitTest, EmptyString1)\n\/\/{\n\/\/ std::vector vec{ split({}, \",\") };\n\/\/\n\/\/ ASSERT_EQ(vec.size(), 1);\n\/\/ EXPECT_EQ(vec[0], \"\");\n\/\/}\n\/\/\n\/\/TEST(StringSplitTest, EmptyString2)\n\/\/{\n\/\/ std::vector vec{ split(\"\", \",\") };\n\/\/\n\/\/ ASSERT_EQ(vec.size(), 1);\n\/\/ EXPECT_EQ(vec[0], \"\");\n\/\/}\n\nTEST(StringSplitTest, EmptyString3)\n{\n std::vector vec{ split({}, any_of(\",\")) };\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, EmptyString4)\n{\n std::vector vec{ split(\"\", any_of(\",\")) };\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, X1)\n{\n std::vector vec{ split(\",\", \",\") };\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"\");\n}\n\nTEST(StringSplitTest, X2)\n{\n std::vector vec{ split(\", \", \",\") };\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \" \");\n}\n\nTEST(StringSplitTest, Z1)\n{\n std::vector vec{ split(\"a\", \",\") };\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"a\");\n}\n\nTEST(StringSplitTest, Z2)\n{\n std::vector vec{ split(\"a,\", \",\") };\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"\");\n}\n\nTEST(StringSplitTest, Z3)\n{\n std::vector vec{ split(\"a,b\", \",\") };\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n}\n\nTEST(StringSplitTest, Test6)\n{\n std::vector vec{ split(\"a.b-c,. d, e .f-\", any_of(\".,-\")) };\n\n ASSERT_EQ(vec.size(), 8);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"\");\n EXPECT_EQ(vec[4], \" d\");\n EXPECT_EQ(vec[5], \" e \");\n EXPECT_EQ(vec[6], \"f\");\n EXPECT_EQ(vec[7], \"\");\n}\n\nTEST(StringSplitTest, Test6_1)\n{\n std::vector vec{ split(\"-a-b-c-\", \"-\") };\n\n ASSERT_EQ(vec.size(), 5);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"a\");\n EXPECT_EQ(vec[2], \"b\");\n EXPECT_EQ(vec[3], \"c\");\n EXPECT_EQ(vec[4], \"\");\n}\n\nTEST(StringSplitTest, Test7)\n{\n std::vector vec{ split(\"-a-b-c----d\", \"--\") };\n\n ASSERT_EQ(vec.size(), 3);\n EXPECT_EQ(vec[0], \"-a-b-c\");\n EXPECT_EQ(vec[1], \"\");\n EXPECT_EQ(vec[2], \"d\");\n}\n\nTEST(StringSplitTest, Test7_1)\n{\n std::vector vec{ split(\"-a-b-c----d\", \"-\") };\n\n ASSERT_EQ(vec.size(), 8);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"a\");\n EXPECT_EQ(vec[2], \"b\");\n EXPECT_EQ(vec[3], \"c\");\n EXPECT_EQ(vec[4], \"\");\n EXPECT_EQ(vec[5], \"\");\n EXPECT_EQ(vec[6], \"\");\n EXPECT_EQ(vec[7], \"d\");\n}\n\nTEST(StringSplitTest, Test8)\n{\n std::vector vec{ split(\"a-b-c-d-e\", \"-\", 2) };\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n}\n\nTEST(StringSplitTest, EmptySepLiteral)\n{\n std::vector vec{ split(\"abc\", \"\") };\n\n#if !defined(SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL) || (SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL == 0)\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"abc\");\n#else\n ASSERT_EQ(vec.size(), 3);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n#endif\n}\n\nTEST(StringSplitTest, EmptySepAnyOf)\n{\n std::vector vec{ split(\"abc\", any_of(\"\")) };\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"abc\");\n}\n\nTEST(StringSplitTest, Iterator)\n{\n auto I = split(\"a,b,c,d\", \",\");\n auto E = I.end();\n\n std::vector vec;\n\n for (; I != E; ++I)\n {\n vec.push_back(*I);\n }\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"d\");\n}\n\n\n#if 1\n\n#include \n#include \n#include \n\nTEST(StringSplitTest, AdaptorsTransformed)\n{\n using namespace boost::adaptors;\n\n struct AppendX\n {\n std::string operator ()(StringRef Str) const {\n return Str + \"+x\";\n }\n };\n\n std::vector vec\n = convert(split(\"a,b,c,d\", \",\") | transformed(AppendX()));\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a+x\");\n EXPECT_EQ(vec[1], \"b+x\");\n EXPECT_EQ(vec[2], \"c+x\");\n EXPECT_EQ(vec[3], \"d+x\");\n}\n\nTEST(StringSplitTest, AdaptorsFiltered)\n{\n using namespace boost::adaptors;\n\n struct SkipEmpty\n {\n bool operator ()(StringRef Str) const {\n return !Str.empty();\n }\n };\n\n std::vector vec\n = convert(split(\"a,,,b,,,c,,,d,,,\", \",\") | filtered(SkipEmpty()));\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"d\");\n}\n\n#endif\nCompile with VC12\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#define SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL 0\n\n#include \"Support\/StringSplit.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace support;\nusing namespace support::strings;\n\ntemplate \nclass RangeConverter\n{\n Range const& R;\n\npublic:\n RangeConverter(Range const& R)\n : R(R)\n {\n }\n\n template \n operator Container() const\n {\n return Container(R.begin(), R.end());\n }\n};\n\ntemplate \nRangeConverter convert(Range const& R)\n{\n return RangeConverter(R);\n}\n\nTEST(StringSplitTest, EmptyString1)\n{\n auto vec = std::vector(split({}, \",\"));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, EmptyString2)\n{\n auto vec = std::vector(split(\"\", \",\"));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, EmptyString3)\n{\n auto vec = std::vector(split({}, any_of(\",\")));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, EmptyString4)\n{\n auto vec = std::vector(split(\"\", any_of(\",\")));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"\");\n}\n\nTEST(StringSplitTest, X1)\n{\n auto vec = std::vector(split(\",\", \",\"));\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"\");\n}\n\nTEST(StringSplitTest, X2)\n{\n auto vec = std::vector(split(\", \", \",\"));\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \" \");\n}\n\nTEST(StringSplitTest, Z1)\n{\n auto vec = std::vector(split(\"a\", \",\"));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"a\");\n}\n\nTEST(StringSplitTest, Z2)\n{\n auto vec = std::vector(split(\"a,\", \",\"));\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"\");\n}\n\nTEST(StringSplitTest, Z3)\n{\n auto vec = std::vector(split(\"a,b\", \",\"));\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n}\n\nTEST(StringSplitTest, Test6)\n{\n auto vec = std::vector(split(\"a.b-c,. d, e .f-\", any_of(\".,-\")));\n\n ASSERT_EQ(vec.size(), 8);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"\");\n EXPECT_EQ(vec[4], \" d\");\n EXPECT_EQ(vec[5], \" e \");\n EXPECT_EQ(vec[6], \"f\");\n EXPECT_EQ(vec[7], \"\");\n}\n\nTEST(StringSplitTest, Test6_1)\n{\n auto vec = std::vector(split(\"-a-b-c-\", \"-\"));\n\n ASSERT_EQ(vec.size(), 5);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"a\");\n EXPECT_EQ(vec[2], \"b\");\n EXPECT_EQ(vec[3], \"c\");\n EXPECT_EQ(vec[4], \"\");\n}\n\nTEST(StringSplitTest, Test7)\n{\n auto vec = std::vector(split(\"-a-b-c----d\", \"--\"));\n\n ASSERT_EQ(vec.size(), 3);\n EXPECT_EQ(vec[0], \"-a-b-c\");\n EXPECT_EQ(vec[1], \"\");\n EXPECT_EQ(vec[2], \"d\");\n}\n\nTEST(StringSplitTest, Test7_1)\n{\n auto vec = std::vector(split(\"-a-b-c----d\", \"-\"));\n\n ASSERT_EQ(vec.size(), 8);\n EXPECT_EQ(vec[0], \"\");\n EXPECT_EQ(vec[1], \"a\");\n EXPECT_EQ(vec[2], \"b\");\n EXPECT_EQ(vec[3], \"c\");\n EXPECT_EQ(vec[4], \"\");\n EXPECT_EQ(vec[5], \"\");\n EXPECT_EQ(vec[6], \"\");\n EXPECT_EQ(vec[7], \"d\");\n}\n\nTEST(StringSplitTest, Test8)\n{\n auto vec = std::vector(split(\"a-b-c-d-e\", \"-\", 2));\n\n ASSERT_EQ(vec.size(), 2);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n}\n\nTEST(StringSplitTest, EmptySepLiteral)\n{\n auto vec = std::vector(split(\"abc\", \"\"));\n\n#if !defined(SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL) || (SUPPORT_STRINGSPLIT_EMPTY_LITERAL_IS_SPECIAL == 0)\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"abc\");\n#else\n ASSERT_EQ(vec.size(), 3);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n#endif\n}\n\nTEST(StringSplitTest, EmptySepAnyOf)\n{\n auto vec = std::vector(split(\"abc\", any_of(\"\")));\n\n ASSERT_EQ(vec.size(), 1);\n EXPECT_EQ(vec[0], \"abc\");\n}\n\nTEST(StringSplitTest, Iterator)\n{\n auto I = split(\"a,b,c,d\", \",\");\n auto E = I.end();\n\n std::vector vec;\n\n for (; I != E; ++I)\n {\n vec.push_back(*I);\n }\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"d\");\n}\n\n\n#if 0\n\n#include \n#include \n#include \n\nTEST(StringSplitTest, AdaptorsTransformed)\n{\n using namespace boost::adaptors;\n\n struct AppendX\n {\n std::string operator ()(StringRef Str) const {\n return Str + \"+x\";\n }\n };\n\n std::vector vec\n = convert(split(\"a,b,c,d\", \",\") | transformed(AppendX()));\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a+x\");\n EXPECT_EQ(vec[1], \"b+x\");\n EXPECT_EQ(vec[2], \"c+x\");\n EXPECT_EQ(vec[3], \"d+x\");\n}\n\nTEST(StringSplitTest, AdaptorsFiltered)\n{\n using namespace boost::adaptors;\n\n struct SkipEmpty\n {\n bool operator ()(StringRef Str) const {\n return !Str.empty();\n }\n };\n\n std::vector vec\n = convert(split(\"a,,,b,,,c,,,d,,,\", \",\") | filtered(SkipEmpty()));\n\n ASSERT_EQ(vec.size(), 4);\n EXPECT_EQ(vec[0], \"a\");\n EXPECT_EQ(vec[1], \"b\");\n EXPECT_EQ(vec[2], \"c\");\n EXPECT_EQ(vec[3], \"d\");\n}\n\n#endif\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 \"NavigationController.hpp\"\n#include \"NavigationMeshContainer.hpp\"\n\n#include \"Mathematics\/Ray.hpp\"\n#include \"Mathematics\/LineSegment.hpp\"\n#include \"Mathematics\/Intersection.hpp\"\n\n#include \"SceneGraph\/Node.hpp\"\n\n#include \"Visitors\/Apply.hpp\"\n\nusing namespace crimild;\nusing namespace crimild::navigation;\n\nNavigationController::NavigationController( void )\n{\n\t\n}\n\nNavigationController::NavigationController( NavigationMeshPtr const &mesh )\n\t: _navigationMesh( mesh )\n{\n\n}\n\nNavigationController::~NavigationController( void )\n{\n\n}\n\nvoid NavigationController::start( void )\n{\n\tif ( _navigationMesh == nullptr ) {\n\t\t\/\/ No navigation mesh assigned. Find the first one in the scene\n\t\tgetNode()->getRootParent()->perform( Apply( [this]( Node *node ) {\n\t\t\tauto nav = node->getComponent< NavigationMeshContainer >();\n\t\t\tif ( nav != nullptr ) {\n\t\t\t\t_navigationMesh = crimild::retain( nav->getNavigationMesh() );\n\t\t\t}\n\t\t}));\n\t}\n}\n\nVector3f NavigationController::move( const Vector3f &from, const Vector3f &to )\n{\n\tif ( _navigationMesh == nullptr ) {\n\t\tLog::warning( CRIMILD_CURRENT_CLASS_NAME, \"No navigation mesh found\" );\n\t\treturn from;\n\t}\n\n\tNavigationCell *cell = nullptr;\n\tgetNavigationMesh()->foreachCell( [&cell, to]( NavigationCellPtr const &c ) {\n\t\tif ( c->containsPoint( to ) ) {\n\t\t\tcell = crimild::get_ptr( c );\n\t\t}\n\t});\n\n\tif ( cell == nullptr ) {\n\t\treturn from;\n\t}\n\n\tauto r = Ray3f( to, -Vector3f::UNIT_Y );\n\tconst auto p = cell->getPlane();\n\n\tfloat t = Intersection::find( p, r );\n\tif ( t < 0 ) {\n\t\tr = Ray3f( to, Vector3f::UNIT_Y );\n\t\tt = Intersection::find( p, r );\n\t\tif ( t < 0 ) {\n\t\t\treturn from;\n\t\t}\n\t}\n\n\treturn r.getPointAt( t );\n}\n\nbool NavigationController::snap( void )\n{\n\t\/\/ TODO: project current position into current cell and update position\n\n\treturn true;\n}\n\nbool NavigationController::teleport( const Vector3f &target )\n{\n\tauto cell = findCellForPoint( target );\n\tif ( cell != nullptr ) {\n\t\tsetCurrentCell( cell );\n\n\t\tgetNode()->local().setTranslate( target );\n\t}\n\n\treturn cell != nullptr;\n}\n\nbool NavigationController::move( const Vector3f &target )\n{\n\t\/\/ TODO: what about local\/world conversion?\n\n\tauto currentCell = getCurrentCell();\n\tif ( currentCell == nullptr ) {\n\t\tfindCurrentCell();\n\t\tcurrentCell = getCurrentCell();\n\t}\n\n\tif ( currentCell == nullptr ) {\n\t\t\/\/ not in a cell\n\t\treturn false;\n\t}\n\n\tauto motionPath = LineSegment3f( getNode()->getLocal().getTranslate(), target );\n\n\tbool done = false;\n\n\tauto testCell = currentCell;\n\n\tNavigationCellEdge *intersectionEdge = nullptr;\n\tVector3f intersectionPoint;\n\n\t\/\/ Search for the cell containing the destination point\n\t\/\/ or update the motion path accordingly to keep it within \n\t\/\/ the nav mesh\n\twhile ( !done && ( testCell != nullptr ) && ( motionPath.getOrigin() != motionPath.getDestination() ) ) {\n\n\t\t\/\/ classify the motion path based on the test cell\n\t\tauto result = testCell->classifyPath( motionPath, intersectionPoint, &intersectionEdge );\n\n\t\tif ( result == NavigationCell::ClassificationResult::INSIDE ) {\n\t\t\t\/\/ We found the cell containing the destination point\n\t\t\t\/\/ Project that point into the cell's plane and terminate\n\t\t\tmotionPath.setDestination( testCell->getPlane().project( motionPath.getDestination() ) );\n\t\t\tdone = true;\n\t\t}\n\t\telse if ( result == NavigationCell::ClassificationResult::OUTSIDE ) {\n\t\t\t\/\/ the motion path goes outside of the test cell\n\t\t\tif ( intersectionEdge->getNeighbor() != nullptr ) {\n\t\t\t\t\/\/ Moving to an adjacent cell. Set motion path origin\n\t\t\t\t\/\/ to intersection point and continue with next cell\n\t\t\t\tmotionPath.setOrigin( intersectionPoint );\n\t\t\t\ttestCell = intersectionEdge->getNeighbor();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ We hit a wall. \n\t\t\t\t\/\/ Project the motion path on the intersection edge\n\t\t\t\t\/\/ and terminate\n\t\t\t\tmotionPath = intersectionEdge->projectPath( motionPath );\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ this may happen if, for some reason, the start point of the motion path\n\t\t\t\/\/ lies outside of the current cell (maybe due to round errors) or it\n\t\t\t\/\/ coincides with one of the vertices\n\t\t\t\/\/ Force the motion path to start within the cell boundaries and try again\n\t\t\tmotionPath.setOrigin( testCell->snapPoint( motionPath.getOrigin() ) );\n\t\t}\n\t}\n\n\tif ( testCell == nullptr ) {\n\t\treturn false;\n\t}\n\n\tsetCurrentCell( testCell );\n\n\tgetNode()->local().setTranslate( motionPath.getDestination() );\n\n\treturn true;\n}\n\nbool NavigationController::findCurrentCell( void )\n{\n\tauto cell = NavigationController::findCellForPoint( getNode()->getLocal().getTranslate() );\n\tif ( cell != nullptr ) {\n\t\tsetCurrentCell( cell );\n\t}\n\n\treturn getCurrentCell();\n}\n\nNavigationCell *NavigationController::findCellForPoint( const Vector3f &point )\n{\n\tNavigationCell *cell = nullptr;\n\tgetNavigationMesh()->foreachCell( [&cell, point]( NavigationCellPtr const &c ) {\n\t\tif ( c->containsPoint( point ) ) {\n\t\t\tcell = crimild::get_ptr( c );\n\t\t}\n\t});\n\n\treturn cell;\n}\n\nAllow navigation teleport to work even if no valid cell is found\/*\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 \"NavigationController.hpp\"\n#include \"NavigationMeshContainer.hpp\"\n\n#include \"Mathematics\/Ray.hpp\"\n#include \"Mathematics\/LineSegment.hpp\"\n#include \"Mathematics\/Intersection.hpp\"\n\n#include \"SceneGraph\/Node.hpp\"\n\n#include \"Visitors\/Apply.hpp\"\n\nusing namespace crimild;\nusing namespace crimild::navigation;\n\nNavigationController::NavigationController( void )\n{\n\t\n}\n\nNavigationController::NavigationController( NavigationMeshPtr const &mesh )\n\t: _navigationMesh( mesh )\n{\n\n}\n\nNavigationController::~NavigationController( void )\n{\n\n}\n\nvoid NavigationController::start( void )\n{\n\tif ( _navigationMesh == nullptr ) {\n\t\t\/\/ No navigation mesh assigned. Find the first one in the scene\n\t\tgetNode()->getRootParent()->perform( Apply( [this]( Node *node ) {\n\t\t\tauto nav = node->getComponent< NavigationMeshContainer >();\n\t\t\tif ( nav != nullptr ) {\n\t\t\t\t_navigationMesh = crimild::retain( nav->getNavigationMesh() );\n\t\t\t}\n\t\t}));\n\t}\n}\n\nVector3f NavigationController::move( const Vector3f &from, const Vector3f &to )\n{\n\tif ( _navigationMesh == nullptr ) {\n\t\tLog::warning( CRIMILD_CURRENT_CLASS_NAME, \"No navigation mesh found\" );\n\t\treturn from;\n\t}\n\n\tNavigationCell *cell = nullptr;\n\tgetNavigationMesh()->foreachCell( [&cell, to]( NavigationCellPtr const &c ) {\n\t\tif ( c->containsPoint( to ) ) {\n\t\t\tcell = crimild::get_ptr( c );\n\t\t}\n\t});\n\n\tif ( cell == nullptr ) {\n\t\treturn from;\n\t}\n\n\tauto r = Ray3f( to, -Vector3f::UNIT_Y );\n\tconst auto p = cell->getPlane();\n\n\tfloat t = Intersection::find( p, r );\n\tif ( t < 0 ) {\n\t\tr = Ray3f( to, Vector3f::UNIT_Y );\n\t\tt = Intersection::find( p, r );\n\t\tif ( t < 0 ) {\n\t\t\treturn from;\n\t\t}\n\t}\n\n\treturn r.getPointAt( t );\n}\n\nbool NavigationController::snap( void )\n{\n\t\/\/ TODO: project current position into current cell and update position\n\n\treturn true;\n}\n\nbool NavigationController::teleport( const Vector3f &target )\n{\n\tauto cell = findCellForPoint( target );\n\n\tsetCurrentCell( cell );\n\tgetNode()->local().setTranslate( target );\n\n\treturn cell != nullptr;\n}\n\nbool NavigationController::move( const Vector3f &target )\n{\n\t\/\/ TODO: what about local\/world conversion?\n\n\tauto currentCell = getCurrentCell();\n\tif ( currentCell == nullptr ) {\n\t\tfindCurrentCell();\n\t\tcurrentCell = getCurrentCell();\n\t}\n\n\tif ( currentCell == nullptr ) {\n\t\t\/\/ not in a cell\n\t\treturn false;\n\t}\n\n\tauto motionPath = LineSegment3f( getNode()->getLocal().getTranslate(), target );\n\n\tbool done = false;\n\n\tauto testCell = currentCell;\n\n\tNavigationCellEdge *intersectionEdge = nullptr;\n\tVector3f intersectionPoint;\n\n\t\/\/ Search for the cell containing the destination point\n\t\/\/ or update the motion path accordingly to keep it within \n\t\/\/ the nav mesh\n\twhile ( !done && ( testCell != nullptr ) && ( motionPath.getOrigin() != motionPath.getDestination() ) ) {\n\n\t\t\/\/ classify the motion path based on the test cell\n\t\tauto result = testCell->classifyPath( motionPath, intersectionPoint, &intersectionEdge );\n\n\t\tif ( result == NavigationCell::ClassificationResult::INSIDE ) {\n\t\t\t\/\/ We found the cell containing the destination point\n\t\t\t\/\/ Project that point into the cell's plane and terminate\n\t\t\tmotionPath.setDestination( testCell->getPlane().project( motionPath.getDestination() ) );\n\t\t\tdone = true;\n\t\t}\n\t\telse if ( result == NavigationCell::ClassificationResult::OUTSIDE ) {\n\t\t\t\/\/ the motion path goes outside of the test cell\n\t\t\tif ( intersectionEdge->getNeighbor() != nullptr ) {\n\t\t\t\t\/\/ Moving to an adjacent cell. Set motion path origin\n\t\t\t\t\/\/ to intersection point and continue with next cell\n\t\t\t\tmotionPath.setOrigin( intersectionPoint );\n\t\t\t\ttestCell = intersectionEdge->getNeighbor();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ We hit a wall. \n\t\t\t\t\/\/ Project the motion path on the intersection edge\n\t\t\t\t\/\/ and terminate\n\t\t\t\tmotionPath = intersectionEdge->projectPath( motionPath );\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ this may happen if, for some reason, the start point of the motion path\n\t\t\t\/\/ lies outside of the current cell (maybe due to round errors) or it\n\t\t\t\/\/ coincides with one of the vertices\n\t\t\t\/\/ Force the motion path to start within the cell boundaries and try again\n\t\t\tmotionPath.setOrigin( testCell->snapPoint( motionPath.getOrigin() ) );\n\t\t}\n\t}\n\n\tif ( testCell == nullptr ) {\n\t\treturn false;\n\t}\n\n\tsetCurrentCell( testCell );\n\n\tgetNode()->local().setTranslate( motionPath.getDestination() );\n\n\treturn true;\n}\n\nbool NavigationController::findCurrentCell( void )\n{\n\tauto cell = NavigationController::findCellForPoint( getNode()->getLocal().getTranslate() );\n\tif ( cell != nullptr ) {\n\t\tsetCurrentCell( cell );\n\t}\n\n\treturn getCurrentCell();\n}\n\nNavigationCell *NavigationController::findCellForPoint( const Vector3f &point )\n{\n\tNavigationCell *cell = nullptr;\n\tgetNavigationMesh()->foreachCell( [&cell, point]( NavigationCellPtr const &c ) {\n\t\tif ( c->containsPoint( point ) ) {\n\t\t\tcell = crimild::get_ptr( c );\n\t\t}\n\t});\n\n\treturn cell;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \n#include \n\n#include \"db\/rt\/Exception.h\"\n#include \"db\/test\/Test.h\"\n#include \"db\/test\/Tester.h\"\n#include \"db\/test\/TestRunner.h\"\n#include \"db\/config\/ConfigManager.h\"\n#include \"db\/data\/json\/JsonWriter.h\"\n\nusing namespace std;\nusing namespace db::rt;\nusing namespace db::test;\nusing namespace db::config;\n\nvoid runConfigManagerTest(TestRunner& tr)\n{\n tr.group(\"ConfigManager\");\n \n tr.test(\"init\");\n {\n DynamicObject expect;\n expect->setType(Map);\n ConfigManager cm;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"init & clear\");\n {\n DynamicObject expect;\n expect->setType(Map);\n ConfigManager cm;\n cm.clear();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"1 config\");\n {\n DynamicObject expect;\n expect->setType(Map);\n expect[\"a\"] = 0;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"clear & 1 config\");\n {\n DynamicObject expect;\n expect->setType(Map);\n expect[\"a\"] = 0;\n ConfigManager cm;\n cm.clear();\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"config change\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), a);\n cm.getConfig()[\"a\"] = 1;\n DynamicObject expect;\n expect[\"a\"] = 1;\n assert(cm.getConfig() != a);\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"add\");\n {\n DynamicObject expect;\n expect[\"a\"] = 0;\n expect[\"b\"] = 1;\n expect[\"c\"] = 2;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n DynamicObject b;\n b[\"b\"] = 1;\n DynamicObject c;\n c[\"c\"] = 2;\n assert(cm.addConfig(a));\n assertNoException();\n assert(cm.addConfig(b));\n assertNoException();\n assert(cm.addConfig(c));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"bad remove\");\n {\n ConfigManager cm;\n assert(!cm.removeConfig(0));\n assertException();\n Exception::clearLast();\n }\n tr.passIfNoException();\n\n tr.test(\"remove\");\n {\n DynamicObject expect;\n expect[\"a\"] = 0;\n expect[\"b\"] = 1;\n expect[\"c\"] = 2;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n DynamicObject b;\n b[\"b\"] = 1;\n DynamicObject c;\n c[\"c\"] = 2;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a));\n assertNoException();\n assert(cm.addConfig(b, ConfigManager::Default, &id));\n assertNoException();\n assert(cm.addConfig(c));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"a\"] = 0;\n expect2[\"c\"] = 2;\n assert(cm.removeConfig(id));\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"update\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"a\"] = 1;\n a[\"a\"] = 1;\n assert(cm.getConfig() != expect2);\n cm.update();\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"set\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a, ConfigManager::Default, &id));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"b\"] = 0;\n DynamicObject b;\n b[\"b\"] = 0;\n cm.setConfig(id, b);\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"get\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a, ConfigManager::Default, &id));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject b;\n assert(cm.getConfig(id, b));\n assertDynoCmp(b, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"map changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n a[\"b\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[\"a\"] = 1;\n DynamicObject expect;\n expect[\"a\"] = 1;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"deep map changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"][\"b\"] = 0;\n a[\"a\"][\"c\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[\"a\"][\"c\"] = 1;\n cm.getConfig()[\"d\"] = 0;\n DynamicObject expect;\n expect[\"a\"][\"c\"] = 1;\n expect[\"d\"] = 0;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"array changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n a[2] = 12;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[1] = 21;\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = 21;\n expect[2] = \"__default__\";\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"bigger array changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[2] = 22;\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = \"__default__\";\n expect[2] = 22;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"system vs user changes\");\n {\n ConfigManager cm;\n\n \/\/ system\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n assert(cm.addConfig(a, ConfigManager::Default));\n assertNoException();\n\n \/\/ user\n DynamicObject b;\n b[0] = 20;\n b[1] = 21;\n assert(cm.addConfig(b, ConfigManager::User));\n assertNoException();\n \n \/\/ custom\n cm.getConfig()[1] = 31;\n\n {\n \/\/ Changes from system configs\n DynamicObject expect;\n expect[0] = 20;\n expect[1] = 31;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n \n {\n \/\/ Changes from system+user configs\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = 31;\n DynamicObject changes;\n cm.getChanges(changes, ConfigManager::All);\n assertDynoCmp(changes, expect);\n }\n }\n tr.passIfNoException();\n\n tr.test(\"default value\");\n {\n ConfigManager cm;\n DynamicObject a;\n a = 1;\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject b;\n b = \"__default__\";\n assert(cm.addConfig(b));\n assertNoException();\n DynamicObject expect;\n expect = 1;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"default values\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n a[2][\"0\"] = 120;\n a[2][\"1\"] = 121;\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject b;\n b[0] = \"__default__\";\n b[1] = 21;\n b[2][\"0\"] = \"__default__\";\n b[2][\"1\"] = 221;\n assert(cm.addConfig(b));\n assertNoException();\n DynamicObject expect;\n expect[0] = 10;\n expect[1] = 21;\n expect[2][\"0\"] = 120;\n expect[2][\"1\"] = 221;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"schema check\");\n {\n DynamicObject schema;\n DynamicObject config;\n assert(ConfigManager::isValidConfig(config, schema));\n schema->setType(Map);\n config->setType(Map);\n assert(ConfigManager::isValidConfig(config, schema));\n schema[\"s\"] = \"\";\n schema[\"i\"] = 0;\n config[\"s\"] = \"string\";\n config[\"i\"] = 1;\n assert(ConfigManager::isValidConfig(config, schema));\n schema[\"m\"][\"s\"] = \"\";\n schema[\"m\"][\"s2\"] = \"\";\n schema[\"a\"][0] = 0;\n schema[\"a\"][1] = 1;\n config[\"m\"][\"s\"] = \"s\";\n config[\"m\"][\"s2\"] = \"s2\";\n config[\"a\"][0] = 0;\n config[\"a\"][1] = 1;\n }\n tr.passIfNoException();\n\n tr.test(\"schema check bad\");\n {\n DynamicObject schema;\n DynamicObject config;\n assert(ConfigManager::isValidConfig(config, schema));\n schema->setType(Map);\n config->setType(Array);\n assert(!ConfigManager::isValidConfig(config, schema));\n config->setType(Map);\n schema[\"s\"] = \"\";\n schema[\"i\"] = 0;\n config[\"s\"] = 1;\n config[\"i\"] = \"string\";\n assert(!ConfigManager::isValidConfig(config, schema));\n }\n tr.passIfNoException();\n\n tr.test(\"user preferences\");\n {\n ConfigManager cm;\n\n \/\/ node\n \/\/ built in or loaded defaults\n DynamicObject nodec;\n nodec[\"node\"][\"host\"] = \"localhost\";\n nodec[\"node\"][\"port\"] = 19100;\n nodec[\"node\"][\"modulePath\"] = \"\/usr\/lib\/bitmunk\/modules\";\n nodec[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules\";\n assert(cm.addConfig(nodec));\n assertNoException();\n\n \/\/ user\n \/\/ loaded defaults\n DynamicObject userc;\n userc[\"node\"][\"port\"] = 19100;\n userc[\"node\"][\"comment\"] = \"My precious...\";\n assert(cm.addConfig(userc, ConfigManager::User));\n assertNoException();\n \n \/\/ user makes changes during runtime\n DynamicObject c = cm.getConfig();\n c[\"node\"][\"port\"] = 19200;\n c[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules:~\/.bitmunk\/modules-dev\";\n c[\"node\"][ConfigManager::TMP][\"not in changes\"] = true;\n\n \/\/ get the changes from defaults to current config\n \/\/ serialize this to disk as needed\n DynamicObject changes;\n cm.getChanges(changes);\n\n \/\/ check it's correct\n DynamicObject expect;\n expect[\"node\"][\"port\"] = 19200;\n expect[\"node\"][\"comment\"] = \"My precious...\";\n expect[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules:~\/.bitmunk\/modules-dev\";\n \/\/ NOTE: will not have TMP var\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n \n tr.test(\"versioning\");\n {\n ConfigManager cm;\n\n cm.getVersions()->clear();\n Config c;\n assert(cm.addConfig(c));\n assertNoException();\n \n cm.addVersion(\"1\");\n assert(!cm.addConfig(c));\n assertException();\n Exception::clearLast();\n \n c[ConfigManager::VERSION] = \"2\";\n assert(!cm.addConfig(c));\n assertException();\n Exception::clearLast();\n \n c[ConfigManager::VERSION] = \"1\";\n assert(cm.addConfig(c));\n assertNoException();\n \n c[ConfigManager::VERSION] = \"2\";\n cm.addVersion(\"2\");\n assert(cm.addConfig(c));\n assertNoException();\n }\n tr.passIfNoException();\n \n tr.test(\"empty array & map\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0]->setType(Array);\n a[1]->setType(Map);\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject expect;\n expect[0]->setType(Array);\n expect[1]->setType(Map);\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.ungroup();\n}\n\nclass DbConfigTester : public db::test::Tester\n{\npublic:\n DbConfigTester()\n {\n setName(\"config\");\n }\n\n \/**\n * Run automatic unit tests.\n *\/\n virtual int runAutomaticTests(TestRunner& tr)\n {\n runConfigManagerTest(tr);\n return 0;\n }\n\n \/**\n * Runs interactive unit tests.\n *\/\n virtual int runInteractiveTests(TestRunner& tr)\n {\n return 0;\n }\n};\n\n#ifndef DB_TEST_NO_MAIN\nDB_TEST_MAIN(DbConfigTester)\n#endif\nClear expected exceptions.\/*\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\n *\/\n#include \n#include \n\n#include \"db\/rt\/Exception.h\"\n#include \"db\/test\/Test.h\"\n#include \"db\/test\/Tester.h\"\n#include \"db\/test\/TestRunner.h\"\n#include \"db\/config\/ConfigManager.h\"\n#include \"db\/data\/json\/JsonWriter.h\"\n\nusing namespace std;\nusing namespace db::rt;\nusing namespace db::test;\nusing namespace db::config;\n\nvoid runConfigManagerTest(TestRunner& tr)\n{\n tr.group(\"ConfigManager\");\n \n tr.test(\"init\");\n {\n DynamicObject expect;\n expect->setType(Map);\n ConfigManager cm;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"init & clear\");\n {\n DynamicObject expect;\n expect->setType(Map);\n ConfigManager cm;\n cm.clear();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"1 config\");\n {\n DynamicObject expect;\n expect->setType(Map);\n expect[\"a\"] = 0;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"clear & 1 config\");\n {\n DynamicObject expect;\n expect->setType(Map);\n expect[\"a\"] = 0;\n ConfigManager cm;\n cm.clear();\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.test(\"config change\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), a);\n cm.getConfig()[\"a\"] = 1;\n DynamicObject expect;\n expect[\"a\"] = 1;\n assert(cm.getConfig() != a);\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"add\");\n {\n DynamicObject expect;\n expect[\"a\"] = 0;\n expect[\"b\"] = 1;\n expect[\"c\"] = 2;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n DynamicObject b;\n b[\"b\"] = 1;\n DynamicObject c;\n c[\"c\"] = 2;\n assert(cm.addConfig(a));\n assertNoException();\n assert(cm.addConfig(b));\n assertNoException();\n assert(cm.addConfig(c));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"bad remove\");\n {\n ConfigManager cm;\n assert(!cm.removeConfig(0));\n assertException();\n Exception::clearLast();\n }\n tr.passIfNoException();\n\n tr.test(\"remove\");\n {\n DynamicObject expect;\n expect[\"a\"] = 0;\n expect[\"b\"] = 1;\n expect[\"c\"] = 2;\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n DynamicObject b;\n b[\"b\"] = 1;\n DynamicObject c;\n c[\"c\"] = 2;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a));\n assertNoException();\n assert(cm.addConfig(b, ConfigManager::Default, &id));\n assertNoException();\n assert(cm.addConfig(c));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"a\"] = 0;\n expect2[\"c\"] = 2;\n assert(cm.removeConfig(id));\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"update\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"a\"] = 1;\n a[\"a\"] = 1;\n assert(cm.getConfig() != expect2);\n cm.update();\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"set\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a, ConfigManager::Default, &id));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject expect2;\n expect2[\"b\"] = 0;\n DynamicObject b;\n b[\"b\"] = 0;\n cm.setConfig(id, b);\n assertDynoCmp(cm.getConfig(), expect2);\n }\n tr.passIfNoException();\n\n tr.test(\"get\");\n {\n ConfigManager cm;\n DynamicObject expect;\n expect[\"a\"] = 0;\n DynamicObject a;\n a[\"a\"] = 0;\n ConfigManager::ConfigId id;\n assert(cm.addConfig(a, ConfigManager::Default, &id));\n assertNoException();\n assertDynoCmp(cm.getConfig(), expect);\n DynamicObject b;\n assert(cm.getConfig(id, b));\n assertDynoCmp(b, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"map changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"] = 0;\n a[\"b\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[\"a\"] = 1;\n DynamicObject expect;\n expect[\"a\"] = 1;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"deep map changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[\"a\"][\"b\"] = 0;\n a[\"a\"][\"c\"] = 0;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[\"a\"][\"c\"] = 1;\n cm.getConfig()[\"d\"] = 0;\n DynamicObject expect;\n expect[\"a\"][\"c\"] = 1;\n expect[\"d\"] = 0;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"array changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n a[2] = 12;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[1] = 21;\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = 21;\n expect[2] = \"__default__\";\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"bigger array changes\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n assert(cm.addConfig(a));\n assertNoException();\n cm.getConfig()[2] = 22;\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = \"__default__\";\n expect[2] = 22;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n\n tr.test(\"system vs user changes\");\n {\n ConfigManager cm;\n\n \/\/ system\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n assert(cm.addConfig(a, ConfigManager::Default));\n assertNoException();\n\n \/\/ user\n DynamicObject b;\n b[0] = 20;\n b[1] = 21;\n assert(cm.addConfig(b, ConfigManager::User));\n assertNoException();\n \n \/\/ custom\n cm.getConfig()[1] = 31;\n\n {\n \/\/ Changes from system configs\n DynamicObject expect;\n expect[0] = 20;\n expect[1] = 31;\n DynamicObject changes;\n cm.getChanges(changes);\n assertDynoCmp(changes, expect);\n }\n \n {\n \/\/ Changes from system+user configs\n DynamicObject expect;\n expect[0] = \"__default__\";\n expect[1] = 31;\n DynamicObject changes;\n cm.getChanges(changes, ConfigManager::All);\n assertDynoCmp(changes, expect);\n }\n }\n tr.passIfNoException();\n\n tr.test(\"default value\");\n {\n ConfigManager cm;\n DynamicObject a;\n a = 1;\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject b;\n b = \"__default__\";\n assert(cm.addConfig(b));\n assertNoException();\n DynamicObject expect;\n expect = 1;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"default values\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0] = 10;\n a[1] = 11;\n a[2][\"0\"] = 120;\n a[2][\"1\"] = 121;\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject b;\n b[0] = \"__default__\";\n b[1] = 21;\n b[2][\"0\"] = \"__default__\";\n b[2][\"1\"] = 221;\n assert(cm.addConfig(b));\n assertNoException();\n DynamicObject expect;\n expect[0] = 10;\n expect[1] = 21;\n expect[2][\"0\"] = 120;\n expect[2][\"1\"] = 221;\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n\n tr.test(\"schema check\");\n {\n DynamicObject schema;\n DynamicObject config;\n assert(ConfigManager::isValidConfig(config, schema));\n schema->setType(Map);\n config->setType(Map);\n assert(ConfigManager::isValidConfig(config, schema));\n schema[\"s\"] = \"\";\n schema[\"i\"] = 0;\n config[\"s\"] = \"string\";\n config[\"i\"] = 1;\n assert(ConfigManager::isValidConfig(config, schema));\n schema[\"m\"][\"s\"] = \"\";\n schema[\"m\"][\"s2\"] = \"\";\n schema[\"a\"][0] = 0;\n schema[\"a\"][1] = 1;\n config[\"m\"][\"s\"] = \"s\";\n config[\"m\"][\"s2\"] = \"s2\";\n config[\"a\"][0] = 0;\n config[\"a\"][1] = 1;\n }\n tr.passIfNoException();\n\n tr.test(\"schema check bad\");\n {\n DynamicObject schema;\n DynamicObject config;\n assert(ConfigManager::isValidConfig(config, schema));\n schema->setType(Map);\n config->setType(Array);\n assert(!ConfigManager::isValidConfig(config, schema));\n Exception::clearLast();\n config->setType(Map);\n schema[\"s\"] = \"\";\n schema[\"i\"] = 0;\n config[\"s\"] = 1;\n config[\"i\"] = \"string\";\n assert(!ConfigManager::isValidConfig(config, schema));\n Exception::clearLast();\n }\n tr.passIfNoException();\n\n tr.test(\"user preferences\");\n {\n ConfigManager cm;\n\n \/\/ node\n \/\/ built in or loaded defaults\n DynamicObject nodec;\n nodec[\"node\"][\"host\"] = \"localhost\";\n nodec[\"node\"][\"port\"] = 19100;\n nodec[\"node\"][\"modulePath\"] = \"\/usr\/lib\/bitmunk\/modules\";\n nodec[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules\";\n assert(cm.addConfig(nodec));\n assertNoException();\n\n \/\/ user\n \/\/ loaded defaults\n DynamicObject userc;\n userc[\"node\"][\"port\"] = 19100;\n userc[\"node\"][\"comment\"] = \"My precious...\";\n assert(cm.addConfig(userc, ConfigManager::User));\n assertNoException();\n \n \/\/ user makes changes during runtime\n DynamicObject c = cm.getConfig();\n c[\"node\"][\"port\"] = 19200;\n c[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules:~\/.bitmunk\/modules-dev\";\n c[\"node\"][ConfigManager::TMP][\"not in changes\"] = true;\n\n \/\/ get the changes from defaults to current config\n \/\/ serialize this to disk as needed\n DynamicObject changes;\n cm.getChanges(changes);\n\n \/\/ check it's correct\n DynamicObject expect;\n expect[\"node\"][\"port\"] = 19200;\n expect[\"node\"][\"comment\"] = \"My precious...\";\n expect[\"node\"][\"userModulePath\"] = \"~\/.bitmunk\/modules:~\/.bitmunk\/modules-dev\";\n \/\/ NOTE: will not have TMP var\n assertDynoCmp(changes, expect);\n }\n tr.passIfNoException();\n \n tr.test(\"versioning\");\n {\n ConfigManager cm;\n\n cm.getVersions()->clear();\n Config c;\n assert(cm.addConfig(c));\n assertNoException();\n \n cm.addVersion(\"1\");\n assert(!cm.addConfig(c));\n assertException();\n Exception::clearLast();\n \n c[ConfigManager::VERSION] = \"2\";\n assert(!cm.addConfig(c));\n assertException();\n Exception::clearLast();\n \n c[ConfigManager::VERSION] = \"1\";\n assert(cm.addConfig(c));\n assertNoException();\n \n c[ConfigManager::VERSION] = \"2\";\n cm.addVersion(\"2\");\n assert(cm.addConfig(c));\n assertNoException();\n }\n tr.passIfNoException();\n \n tr.test(\"empty array & map\");\n {\n ConfigManager cm;\n DynamicObject a;\n a[0]->setType(Array);\n a[1]->setType(Map);\n assert(cm.addConfig(a));\n assertNoException();\n DynamicObject expect;\n expect[0]->setType(Array);\n expect[1]->setType(Map);\n assertDynoCmp(cm.getConfig(), expect);\n }\n tr.passIfNoException();\n \n tr.ungroup();\n}\n\nclass DbConfigTester : public db::test::Tester\n{\npublic:\n DbConfigTester()\n {\n setName(\"config\");\n }\n\n \/**\n * Run automatic unit tests.\n *\/\n virtual int runAutomaticTests(TestRunner& tr)\n {\n runConfigManagerTest(tr);\n return 0;\n }\n\n \/**\n * Runs interactive unit tests.\n *\/\n virtual int runInteractiveTests(TestRunner& tr)\n {\n return 0;\n }\n};\n\n#ifndef DB_TEST_NO_MAIN\nDB_TEST_MAIN(DbConfigTester)\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: regcomplazy.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 09:37:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n\n#include \"sal\/main.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n\n#define OUSTR(x) ::rtl::OUString::createFromAscii( x )\n#define OSToOUS(x) ::rtl::OStringToOUString(x, osl_getThreadTextEncoding())\n#define OUSToOS(x) ::rtl::OUStringToOString(x, osl_getThreadTextEncoding())\nusing namespace ::rtl;\n\ntypedef ::std::vector< ::rtl::OString > OSVector;\n\ntypedef ::std::pair< ::rtl::OString, OSVector > DataPair;\n\ntypedef ::std::vector< DataPair > DataVector;\n\nstruct CompDescriptor {\n OString sImplementationName;\n OString sComponentName;\n OString sLoaderName;\n OSVector vSupportedServices;\n DataVector vData;\n};\n\ntypedef ::std::vector< CompDescriptor > CDescrVector;\n\nstatic void print_options() SAL_THROW( () )\n{\n printf(\n \"\\nusage: regcomplazy [-v]registry_file cmp_descr_file ...\\n\\n\"\n \"Register a cmponent using a comp description file.\\n\"\n \"Option -v prints verbose output on stdout.\\n\" );\n}\n\nstatic bool checkImplValue(RegistryValueList* pValueList, OString sImplName) {\n int i = 0;\n for (i=0; i < pValueList->getLength(); i++) {\n if (sImplName.equals(pValueList->getElement(i)))\n return true;\n }\n\n return false;\n}\n\n\/\/==================================================================================================\nSAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)\n{\n if (argc < 3)\n {\n print_options();\n return 1;\n }\n\n bool bVerbose = false;\n int nPos = 1;\n if ('-' == argv[ nPos ][ 0 ] && 'v' == argv[ nPos ][ 1 ])\n {\n if ('\\0' != argv[ nPos ][ 2 ])\n {\n print_options();\n return 1;\n }\n bVerbose = true;\n ++nPos;\n }\n\n OUString sys_path( OUSTR( argv[ nPos ] ) );\n OUString reg_url;\n oslFileError rc = osl_getFileURLFromSystemPath( sys_path.pData, ®_url.pData );\n if (osl_File_E_None != rc)\n {\n if (bVerbose)\n fprintf( stderr, \"\\nERROR: cannot make file url out of %s\\n\", argv[nPos]);\n return 1;\n }\n\n FILE* fDescr = fopen(argv[ ++nPos ], \"r\");\n OStringBuffer sBuffer(512);\n\n if ( fDescr) {\n size_t totalSize = 0;\n size_t readSize = 0;\n char pBuffer[513];\n\n while ( !feof(fDescr) )\n {\n if ( (readSize = fread(pBuffer, 1, 512, fDescr)) > 0\n && !ferror(fDescr) ) {\n totalSize += readSize;\n if (totalSize >= 512)\n sBuffer.ensureCapacity(totalSize * 2);\n\n sBuffer.append(pBuffer, readSize);\n }\n }\n }\n\n OString sDescr = sBuffer.makeStringAndClear();\n sal_Int32 nTokenIndex = 0;\n sal_Int32 nIndex = 0;\n\n CDescrVector vDescr;\n CompDescriptor descr;\n bool bFirst = true;\n\n do {\n OString sTmp = sDescr.getToken(0, '\\x0A', nTokenIndex);\n OString sToken(sTmp);\n if (sTmp.pData->buffer[sTmp.getLength()-1] == '\\x0D')\n sToken = sTmp.copy(0, sTmp.getLength()-1);\n\n if (nIndex = sToken.indexOf(\"[Data]\") >= 0) {\n do {\n OString sTmp = sDescr.getToken(0, '\\x0A', nTokenIndex);\n OString sToken(sTmp);\n if (sTmp.pData->buffer[sTmp.getLength()-1] == '\\x0D')\n sToken = sTmp.copy(0, sTmp.getLength()-1);\n\n if ((sToken.getLength() > 0) && (sToken.pData->buffer[0] != '[')) {\n OString dataKey(sToken.copy(0, sToken.indexOf('=')));\n OString sValues(sToken.copy(sToken.indexOf('=')+1));\n sal_Int32 nVIndex = 0;\n OSVector vValues;\n do {\n OString sValue = sValues.getToken(0, ';', nVIndex);\n vValues.push_back(sValue);\n } while (nVIndex >= 0 );\n descr.vData.push_back(DataPair(dataKey, vValues));\n } else\n break;\n } while (nTokenIndex >= 0 );\n }\n if ( nIndex = sToken.indexOf(\"[ComponentDescriptor]\") >= 0) {\n if (bFirst)\n bFirst = false;\n else\n vDescr.push_back(descr);\n\n descr = CompDescriptor();\n }\n else if ( nIndex = sToken.indexOf(\"ImplementationName=\") >= 0) {\n descr.sImplementationName = sToken.copy(19);\n }\n else if ( nIndex = sToken.indexOf(\"ComponentName=\") >= 0) {\n descr.sComponentName = sToken.copy(14);\n }\n else if ( nIndex = sToken.indexOf(\"LoaderName=\") >= 0) {\n descr.sLoaderName = sToken.copy(11);\n }\n else if ( (nIndex = sToken.indexOf(\"[SupportedServices]\") < 0) &&\n (sToken.getLength() > 0) &&\n (sToken.pData->buffer[0] != '[') ) {\n descr.vSupportedServices.push_back(sToken);\n }\n } while (nTokenIndex >= 0 );\n \/\/ insert the last descriptor\n vDescr.push_back(descr);\n\n RegistryLoader* pLoader = new RegistryLoader();\n if (!pLoader->isLoaded())\n {\n delete pLoader;\n return 1;\n }\n\n Registry *pReg = new Registry(*pLoader);\n delete pLoader;\n\n RegistryKey rootKey, key, subKey, serviceKey;\n\n if (pReg->open(reg_url, REG_READWRITE))\n {\n if (pReg->create(reg_url))\n {\n if (bVerbose)\n fprintf(stderr, \"ERROR: open registry \\\"%s\\\" failed\\n\", argv[1]);\n return 1;\n }\n }\n if (pReg->openRootKey(rootKey)) {\n if (bVerbose)\n fprintf(stderr, \"ERROR: open root key failed\\n\");\n return 1;\n }\n\n CDescrVector::const_iterator comp_iter = vDescr.begin();\n do {\n OString sImplName = (*comp_iter).sImplementationName;\n OUStringBuffer sbImpl;\n sbImpl.appendAscii(\"\/IMPLEMENTATIONS\/\");\n sbImpl.append(OSToOUS(sImplName));\n OUString sImplKeyName = sbImpl.makeStringAndClear();\n\n if (rootKey.openKey(sImplKeyName, key) == REG_NO_ERROR) {\n if (bVerbose) {\n fprintf(stderr, \"WARNING: implementation entry for \\\"%s\\\" already exists, existing entries are overwritten\\n\", sImplName.getStr());\n }\n } else {\n if (rootKey.createKey(sImplKeyName, key)) {\n if (bVerbose) {\n fprintf(stderr, \"ERROR: can't create new implementation entry \\\"%s\\\".\\n\", sImplName.getStr());\n }\n return 1;\n }\n }\n\n OString sLoaderName = (*comp_iter).sLoaderName;\n OUString usKeyName(OUSTR(\"UNO\/ACTIVATOR\"));\n key.createKey(usKeyName, subKey);\n subKey.setValue(OUString(), RG_VALUETYPE_STRING,\n (sal_Char*)sLoaderName.getStr(), sLoaderName.getLength()+1);\n\n OString sCompName = (*comp_iter).sComponentName;\n usKeyName = OUSTR(\"UNO\/LOCATION\");\n key.createKey(usKeyName, subKey);\n subKey.setValue(OUString(), RG_VALUETYPE_STRING,\n (sal_Char*)sCompName.getStr(), sCompName.getLength()+1);\n\n if ((*comp_iter).vData.size() > 0) {\n usKeyName = OUSTR(\"DATA\");\n RegistryKey dataKey, valueKey;\n key.createKey(usKeyName, dataKey);\n\n DataVector::const_iterator data_iter = ((*comp_iter).vData).begin();\n do {\n OUString sDataKey(OSToOUS((*data_iter).first));\n dataKey.createKey(sDataKey, valueKey);\n\n OSVector::const_iterator value_iter = ((*data_iter).second).begin();\n int vlen = (*data_iter).second.size();\n sal_Char** pValueList = (sal_Char**)rtl_allocateZeroMemory(\n vlen * sizeof(sal_Char*));\n int i = 0;\n do {\n pValueList[i] = (sal_Char*)rtl_allocateZeroMemory(\n (*value_iter).getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pValueList[i], (sal_Char*)(*value_iter).getStr(),\n (*value_iter).getLength()+1);\n i++;\n value_iter++;\n } while (value_iter != (*data_iter).second.end());\n\n valueKey.setStringListValue(OUString(), pValueList, vlen);\n\n \/\/ free memory\n for (i=0; i valueList;\n serviceKey.getStringListValue(usServiceKeyName, valueList);\n if ( checkImplValue(&valueList, sImplName) ) {\n serv_iter++;\n continue;\n }\n\n sal_Int32 nServices = valueList.getLength()+1;\n sal_Char** pImplList = (sal_Char**)rtl_allocateZeroMemory(\n nServices * sizeof(sal_Char*));\n pImplList[0] = (sal_Char*)rtl_allocateZeroMemory(\n sImplName.getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pImplList[0], (sal_Char*)sImplName.getStr(),\n sImplName.getLength()+1);\n int i = 0;\n for (i=0; i < valueList.getLength(); i++) {\n pImplList[i+1]=valueList.getElement(i);\n }\n key.setStringListValue(OUString(), pImplList, nServices);\n\n \/\/ free memory\n rtl_freeMemory(pImplList[0]);\n rtl_freeMemory(pImplList);\n\n } else {\n serviceKey.createKey(usServiceKeyName, key);\n\n sal_Char* pImplList[1];\n pImplList[0] = (sal_Char*)rtl_allocateZeroMemory(\n sImplName.getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pImplList[0], (sal_Char*)sImplName.getStr(),\n sImplName.getLength()+1);\n key.setStringListValue(OUString(), pImplList, 1);\n\n \/\/ free memory\n rtl_freeMemory(pImplList[0]);\n }\n serv_iter++;\n } while (serv_iter != (*comp_iter).vSupportedServices.end());\n\n comp_iter++;\n } while (comp_iter != vDescr.end());\n\n key.closeKey();\n subKey.closeKey();\n serviceKey.closeKey();\n rootKey.closeKey();\n pReg->close();\n\n return 0;\n}\nINTEGRATION: CWS warnings01 (1.2.12); FILE MERGED 2005\/11\/29 09:30:05 sb 1.2.12.4: #i53898# Made the code warning-free. 2005\/09\/23 02:54:54 sb 1.2.12.3: RESYNC: (1.2-1.3); FILE MERGED 2005\/09\/07 11:52:48 sb 1.2.12.2: #i53898# Made code warning-free. 2005\/09\/01 07:35:51 sb 1.2.12.1: #i53898# Made code warning-free.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: regcomplazy.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:55:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n\n#include \"sal\/main.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n\n#define OUSTR(x) ::rtl::OUString::createFromAscii( x )\n#define OSToOUS(x) ::rtl::OStringToOUString(x, osl_getThreadTextEncoding())\n#define OUSToOS(x) ::rtl::OUStringToOString(x, osl_getThreadTextEncoding())\nusing namespace ::rtl;\n\ntypedef ::std::vector< ::rtl::OString > OSVector;\n\ntypedef ::std::pair< ::rtl::OString, OSVector > DataPair;\n\ntypedef ::std::vector< DataPair > DataVector;\n\nstruct CompDescriptor {\n OString sImplementationName;\n OString sComponentName;\n OString sLoaderName;\n OSVector vSupportedServices;\n DataVector vData;\n};\n\ntypedef ::std::vector< CompDescriptor > CDescrVector;\n\nstatic void print_options() SAL_THROW( () )\n{\n printf(\n \"\\nusage: regcomplazy [-v]registry_file cmp_descr_file ...\\n\\n\"\n \"Register a cmponent using a comp description file.\\n\"\n \"Option -v prints verbose output on stdout.\\n\" );\n}\n\nstatic bool checkImplValue(RegistryValueList* pValueList, OString sImplName) {\n for (sal_uInt32 i=0; i < pValueList->getLength(); i++) {\n if (sImplName.equals(pValueList->getElement(i)))\n return true;\n }\n\n return false;\n}\n\n\/\/==================================================================================================\nSAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)\n{\n if (argc < 3)\n {\n print_options();\n return 1;\n }\n\n bool bVerbose = false;\n int nPos = 1;\n if ('-' == argv[ nPos ][ 0 ] && 'v' == argv[ nPos ][ 1 ])\n {\n if ('\\0' != argv[ nPos ][ 2 ])\n {\n print_options();\n return 1;\n }\n bVerbose = true;\n ++nPos;\n }\n\n OUString sys_path( OUSTR( argv[ nPos ] ) );\n OUString reg_url;\n oslFileError rc = osl_getFileURLFromSystemPath( sys_path.pData, ®_url.pData );\n if (osl_File_E_None != rc)\n {\n if (bVerbose)\n fprintf( stderr, \"\\nERROR: cannot make file url out of %s\\n\", argv[nPos]);\n return 1;\n }\n\n FILE* fDescr = fopen(argv[ ++nPos ], \"r\");\n OStringBuffer sBuffer(512);\n\n if ( fDescr) {\n size_t totalSize = 0;\n size_t readSize = 0;\n char pBuffer[513];\n\n while ( !feof(fDescr) )\n {\n if ( (readSize = fread(pBuffer, 1, 512, fDescr)) > 0\n && !ferror(fDescr) ) {\n totalSize += readSize;\n if (totalSize >= 512)\n sBuffer.ensureCapacity(totalSize * 2);\n\n sBuffer.append(pBuffer, readSize);\n }\n }\n }\n\n OString sDescr = sBuffer.makeStringAndClear();\n sal_Int32 nTokenIndex = 0;\n\n CDescrVector vDescr;\n CompDescriptor descr;\n bool bFirst = true;\n\n do {\n OString sTmp = sDescr.getToken(0, '\\x0A', nTokenIndex);\n OString sToken(sTmp);\n if (sTmp.pData->buffer[sTmp.getLength()-1] == '\\x0D')\n sToken = sTmp.copy(0, sTmp.getLength()-1);\n\n if (sToken.indexOf(\"[Data]\") >= 0) {\n do {\n OString sTmp2 = sDescr.getToken(0, '\\x0A', nTokenIndex);\n OString sToken2(sTmp2);\n if (sTmp2.pData->buffer[sTmp2.getLength()-1] == '\\x0D')\n sToken2 = sTmp2.copy(0, sTmp2.getLength()-1);\n\n if ((sToken2.getLength() > 0) && (sToken2.pData->buffer[0] != '[')) {\n OString dataKey(sToken2.copy(0, sToken2.indexOf('=')));\n OString sValues(sToken2.copy(sToken2.indexOf('=')+1));\n sal_Int32 nVIndex = 0;\n OSVector vValues;\n do {\n OString sValue = sValues.getToken(0, ';', nVIndex);\n vValues.push_back(sValue);\n } while (nVIndex >= 0 );\n descr.vData.push_back(DataPair(dataKey, vValues));\n } else\n break;\n } while (nTokenIndex >= 0 );\n }\n if ( sToken.indexOf(\"[ComponentDescriptor]\") >= 0) {\n if (bFirst)\n bFirst = false;\n else\n vDescr.push_back(descr);\n\n descr = CompDescriptor();\n }\n else if ( sToken.indexOf(\"ImplementationName=\") >= 0) {\n descr.sImplementationName = sToken.copy(19);\n }\n else if ( sToken.indexOf(\"ComponentName=\") >= 0) {\n descr.sComponentName = sToken.copy(14);\n }\n else if ( sToken.indexOf(\"LoaderName=\") >= 0) {\n descr.sLoaderName = sToken.copy(11);\n }\n else if ( (sToken.indexOf(\"[SupportedServices]\") < 0) &&\n (sToken.getLength() > 0) &&\n (sToken.pData->buffer[0] != '[') ) {\n descr.vSupportedServices.push_back(sToken);\n }\n } while (nTokenIndex >= 0 );\n \/\/ insert the last descriptor\n vDescr.push_back(descr);\n\n RegistryLoader* pLoader = new RegistryLoader();\n if (!pLoader->isLoaded())\n {\n delete pLoader;\n return 1;\n }\n\n Registry *pReg = new Registry(*pLoader);\n delete pLoader;\n\n RegistryKey rootKey, key, subKey, serviceKey;\n\n if (pReg->open(reg_url, REG_READWRITE))\n {\n if (pReg->create(reg_url))\n {\n if (bVerbose)\n fprintf(stderr, \"ERROR: open registry \\\"%s\\\" failed\\n\", argv[1]);\n return 1;\n }\n }\n if (pReg->openRootKey(rootKey)) {\n if (bVerbose)\n fprintf(stderr, \"ERROR: open root key failed\\n\");\n return 1;\n }\n\n CDescrVector::const_iterator comp_iter = vDescr.begin();\n do {\n OString sImplName = (*comp_iter).sImplementationName;\n OUStringBuffer sbImpl;\n sbImpl.appendAscii(\"\/IMPLEMENTATIONS\/\");\n sbImpl.append(OSToOUS(sImplName));\n OUString sImplKeyName = sbImpl.makeStringAndClear();\n\n if (rootKey.openKey(sImplKeyName, key) == REG_NO_ERROR) {\n if (bVerbose) {\n fprintf(stderr, \"WARNING: implementation entry for \\\"%s\\\" already exists, existing entries are overwritten\\n\", sImplName.getStr());\n }\n } else {\n if (rootKey.createKey(sImplKeyName, key)) {\n if (bVerbose) {\n fprintf(stderr, \"ERROR: can't create new implementation entry \\\"%s\\\".\\n\", sImplName.getStr());\n }\n return 1;\n }\n }\n\n OString sLoaderName = (*comp_iter).sLoaderName;\n OUString usKeyName(OUSTR(\"UNO\/ACTIVATOR\"));\n key.createKey(usKeyName, subKey);\n subKey.setValue(OUString(), RG_VALUETYPE_STRING,\n (sal_Char*)sLoaderName.getStr(), sLoaderName.getLength()+1);\n\n OString sCompName = (*comp_iter).sComponentName;\n usKeyName = OUSTR(\"UNO\/LOCATION\");\n key.createKey(usKeyName, subKey);\n subKey.setValue(OUString(), RG_VALUETYPE_STRING,\n (sal_Char*)sCompName.getStr(), sCompName.getLength()+1);\n\n if ((*comp_iter).vData.size() > 0) {\n usKeyName = OUSTR(\"DATA\");\n RegistryKey dataKey, valueKey;\n key.createKey(usKeyName, dataKey);\n\n DataVector::const_iterator data_iter = ((*comp_iter).vData).begin();\n do {\n OUString sDataKey(OSToOUS((*data_iter).first));\n dataKey.createKey(sDataKey, valueKey);\n\n OSVector::const_iterator value_iter = ((*data_iter).second).begin();\n int vlen = (*data_iter).second.size();\n sal_Char** pValueList = (sal_Char**)rtl_allocateZeroMemory(\n vlen * sizeof(sal_Char*));\n int i = 0;\n do {\n pValueList[i] = (sal_Char*)rtl_allocateZeroMemory(\n (*value_iter).getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pValueList[i], (sal_Char*)(*value_iter).getStr(),\n (*value_iter).getLength()+1);\n i++;\n value_iter++;\n } while (value_iter != (*data_iter).second.end());\n\n valueKey.setStringListValue(OUString(), pValueList, vlen);\n\n \/\/ free memory\n for (i=0; i valueList;\n serviceKey.getStringListValue(usServiceKeyName, valueList);\n if ( checkImplValue(&valueList, sImplName) ) {\n serv_iter++;\n continue;\n }\n\n sal_uInt32 nServices = valueList.getLength()+1;\n sal_Char** pImplList = (sal_Char**)rtl_allocateZeroMemory(\n nServices * sizeof(sal_Char*));\n pImplList[0] = (sal_Char*)rtl_allocateZeroMemory(\n sImplName.getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pImplList[0], (sal_Char*)sImplName.getStr(),\n sImplName.getLength()+1);\n for (sal_uInt32 i=0; i < valueList.getLength(); i++) {\n pImplList[i+1]=valueList.getElement(i);\n }\n key.setStringListValue(OUString(), pImplList, nServices);\n\n \/\/ free memory\n rtl_freeMemory(pImplList[0]);\n rtl_freeMemory(pImplList);\n\n } else {\n serviceKey.createKey(usServiceKeyName, key);\n\n sal_Char* pImplList[1];\n pImplList[0] = (sal_Char*)rtl_allocateZeroMemory(\n sImplName.getLength()+1 * sizeof(sal_Char));\n rtl_copyMemory(pImplList[0], (sal_Char*)sImplName.getStr(),\n sImplName.getLength()+1);\n key.setStringListValue(OUString(), pImplList, 1);\n\n \/\/ free memory\n rtl_freeMemory(pImplList[0]);\n }\n serv_iter++;\n } while (serv_iter != (*comp_iter).vSupportedServices.end());\n\n comp_iter++;\n } while (comp_iter != vDescr.end());\n\n key.closeKey();\n subKey.closeKey();\n serviceKey.closeKey();\n rootKey.closeKey();\n pReg->close();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_HPP\n#define STAN_MATH_OPENCL_KERNEL_GENERATOR_HPP\n#ifdef STAN_OPENCL\n\n\/**\n * \\ingroup opencl\n * \\defgroup opencl_kernel_generator OpenCL Kernel Generator\n *\n * The OpenCL kernel generator is used to combine multiple matrix operations\n * into a single OpenCL kernel. This is much simpler than writing\n * multi-operation kernels by hand.\n *\n * Because global GPU memory loads and stores are relativly slow compared to\n * calculations in a kernel, using one kernel for multiple operations is faster\n * than using one kernel per operation.\n *\n * The kernel generator uses lazy evaluation. Each operation is represented by\n * an object derived from `operation_cl`. Such an object holds arguments of the\n * operations as well as meta information needed to generate calculations on the\n * arguments. Arguments to operations can be other operations, scalars\n * or `matrix_cl` objects. An operation is evaluated when either an operation is\n * assigned to a `matrix_cl` or a left-hand-side operation or `.eval()` is\n * called.\n *\n * ## Defining a new kernel generator operation\n *\n * Unary functions can be added using one of the macros in\n * `unary_functions.hpp`.\n *\n * New kernel generator classes must satsify the conditions below:\n *\n * 1. The class must be derived from a class inheriting from `operation_cl`.\n * Optionally, if the operation should support being assigned to, it can be\n * derived from a class inheriting `operation_cl_lhs` instead.\n * 2. It's parent template arguments should be set to derived type, type of\n * scalar and types of any expression arguements.\n * 3. Member type `Scalar` should be defined as scalar type of the result of\n * the operation.\n * 4. Member function `generate` has the signature\n * ```cpp\n * inline kernel_parts generate(const std::string& i, const std::string& j,\n * const std::string& var_name_arg)\n * ```\n * 5. Member function `deep_copy` should make a copy of the expression.\n * Arguments that are operations should be copied by calling their `deep_copy`.\n *\n * The following functions can optionally be defined. Defaults are implemented\n * in `operation_cl`:\n * - `void modify_argument_indices(std::string& i, std::string& j)`:\n * - Modifies what indices are passed to argument's `generate()`.\n * - Default: No-op\n * - `void set_args(std::set& generated,\n * cl::Kernel& kernel, int& arg_num)`:\n * - Sets additional kernel arguments.\n * - Default: Calls `set_args()` on arguments.\n * - `int rows()`:\n * - Returns Number of rows of the result.\n * - Default: Returns maximum of the arguments' rows.\n * - `int cols()`:\n * - Returns number of columns of the result.\n * - Default: Returns maximum of the arguments' columns.\n * - `int thread_rows()`:\n * - Returns number of threads required for this operation in rows\n * direction.\n * - Default: returns `rows()`.\n * - `int thread_cols()`:\n * - Returns number of threads required for this operation in cols direction.\n * - Default: `cols()`.\n * - `std::pair extreme_diagonals()`:\n * - Returns indices of the extreme bottom and top nonzero diagonals of the result of\n * the operation. Diagonal has index 0, first superdiagonal 1, first subdiagonal\n * -1 and so on. For instance `load_` of a matrix with lower triangular view\n * would return bottom diagonal of `1-rows()` and top diagonal `0`. Returning a\n * more extreme value is also allowed and especially useful for operations that\n * are broadcast so their exact size is not known.\n * - Default: Bottom diagonal equals to min of bottom diagonals of\n * arguments. Top diagonal equals to max of top diagonals of arguments.\n *\n * If an operation should support being assigned to it should also define the\n * following:\n *\n * 1. Member function `generate_lhs` with same signature as `generate`\n * that returns generated code when the operation is assigned to.\n *\n * The below functions can be optionally defined for operations that support\n * being assigned to. Defaults are in `operation_cl_lhs`.\n * - `void set_view(int bottom_diagonal, int top_diagonal, int\n * bottom_zero_diagonal, int top_zero_diagonal)`:\n * - Sets view of the underlying `matrix_cl` depending on where the extreme\n * sub-\/super-diagonals are written.\n * - Default: Calls `set_view` on expression arguments with the same\n * arguments.\n * - `void check_assign_dimensions(int rows, int cols)`:\n * - If the operation size can be modified, it should be set to the given\n * size. Otherwise it should check that this operation's size matches given\n * size.\n * - Default: By default calls `check_assign_dimensions` on expression\n * arguments with the same arguments.\n *\n * A new operation should also have a user-facing function that accepts\n * arguments to the operation and returns the operation object. Arguments should\n * be passed trough function `as_operation_cl` so that they are wrapped in\n * operations if they are not operations themselves. If the operation defines\n * `modify_argument_indices` this function should make copies of arguments by\n * calling `deep_copy()` on them internally.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#endif\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0#ifndef STAN_MATH_OPENCL_KERNEL_GENERATOR_HPP\n#define STAN_MATH_OPENCL_KERNEL_GENERATOR_HPP\n#ifdef STAN_OPENCL\n\n\/**\n * \\ingroup opencl\n * \\defgroup opencl_kernel_generator OpenCL Kernel Generator\n *\n * The OpenCL kernel generator is used to combine multiple matrix operations\n * into a single OpenCL kernel. This is much simpler than writing\n * multi-operation kernels by hand.\n *\n * Because global GPU memory loads and stores are relativly slow compared to\n * calculations in a kernel, using one kernel for multiple operations is faster\n * than using one kernel per operation.\n *\n * The kernel generator uses lazy evaluation. Each operation is represented by\n * an object derived from `operation_cl`. Such an object holds arguments of the\n * operations as well as meta information needed to generate calculations on the\n * arguments. Arguments to operations can be other operations, scalars\n * or `matrix_cl` objects. An operation is evaluated when either an operation is\n * assigned to a `matrix_cl` or a left-hand-side operation or `.eval()` is\n * called.\n *\n * ## Defining a new kernel generator operation\n *\n * Unary functions can be added using one of the macros in\n * `unary_functions.hpp`.\n *\n * New kernel generator classes must satsify the conditions below:\n *\n * 1. The class must be derived from a class inheriting from `operation_cl`.\n * Optionally, if the operation should support being assigned to, it can be\n * derived from a class inheriting `operation_cl_lhs` instead.\n * 2. It's parent template arguments should be set to derived type, type of\n * scalar and types of any expression arguements.\n * 3. Member type `Scalar` should be defined as scalar type of the result of\n * the operation.\n * 4. Member function `generate` has the signature\n * ```cpp\n * inline kernel_parts generate(const std::string& i, const std::string& j,\n * const std::string& var_name_arg)\n * ```\n * 5. Member function `deep_copy` should make a copy of the expression.\n * Arguments that are operations should be copied by calling their `deep_copy`.\n *\n * The following functions can optionally be defined. Defaults are implemented\n * in `operation_cl`:\n * - `void modify_argument_indices(std::string& i, std::string& j)`:\n * - Modifies what indices are passed to argument's `generate()`.\n * - Default: No-op\n * - `void set_args(std::set& generated,\n * cl::Kernel& kernel, int& arg_num)`:\n * - Sets additional kernel arguments.\n * - Default: Calls `set_args()` on arguments.\n * - `int rows()`:\n * - Returns Number of rows of the result.\n * - Default: Returns maximum of the arguments' rows.\n * - `int cols()`:\n * - Returns number of columns of the result.\n * - Default: Returns maximum of the arguments' columns.\n * - `int thread_rows()`:\n * - Returns number of threads required for this operation in rows\n * direction.\n * - Default: returns `rows()`.\n * - `int thread_cols()`:\n * - Returns number of threads required for this operation in cols\n * direction.\n * - Default: `cols()`.\n * - `std::pair extreme_diagonals()`:\n * - Returns indices of the extreme bottom and top nonzero diagonals of the\n * result of the operation. Diagonal has index 0, first superdiagonal 1, first\n * subdiagonal -1 and so on. For instance `load_` of a matrix with lower\n * triangular view would return bottom diagonal of `1-rows()` and top diagonal\n * `0`. Returning a more extreme value is also allowed and especially useful for\n * operations that are broadcast so their exact size is not known.\n * - Default: Bottom diagonal equals to min of bottom diagonals of\n * arguments. Top diagonal equals to max of top diagonals of arguments.\n *\n * If an operation should support being assigned to it should also define the\n * following:\n *\n * 1. Member function `generate_lhs` with same signature as `generate`\n * that returns generated code when the operation is assigned to.\n *\n * The below functions can be optionally defined for operations that support\n * being assigned to. Defaults are in `operation_cl_lhs`.\n * - `void set_view(int bottom_diagonal, int top_diagonal, int\n * bottom_zero_diagonal, int top_zero_diagonal)`:\n * - Sets view of the underlying `matrix_cl` depending on where the extreme\n * sub-\/super-diagonals are written.\n * - Default: Calls `set_view` on expression arguments with the same\n * arguments.\n * - `void check_assign_dimensions(int rows, int cols)`:\n * - If the operation size can be modified, it should be set to the given\n * size. Otherwise it should check that this operation's size matches given\n * size.\n * - Default: By default calls `check_assign_dimensions` on expression\n * arguments with the same arguments.\n *\n * A new operation should also have a user-facing function that accepts\n * arguments to the operation and returns the operation object. Arguments should\n * be passed trough function `as_operation_cl` so that they are wrapped in\n * operations if they are not operations themselves. If the operation defines\n * `modify_argument_indices` this function should make copies of arguments by\n * calling `deep_copy()` on them internally.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#endif\n#endif\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_FUNCTOR_ODE_ADJOINT_HPP\n#define STAN_MATH_REV_FUNCTOR_ODE_ADJOINT_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the stiff backward differentiation formula\n * BDF solver or the non-stiff Adams solver from CVODES. The ODE system is\n * integrated using the adjoint sensitivity approach of CVODES.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param function_name Calling function name (for printing debugging messages)\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr,\n require_any_not_st_arithmetic* = nullptr>\nauto ode_adjoint_impl(\n const char* function_name, F&& f, const T_y0& y0, const T_t0& t0,\n const std::vector& ts, double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n using integrator_vari\n = cvodes_integrator_adjoint_vari, T_t0, T_ts,\n plain_type_t...>;\n auto integrator = new integrator_vari(\n function_name, std::forward(f), y0, t0, ts, relative_tolerance_forward,\n absolute_tolerance_forward, relative_tolerance_backward,\n absolute_tolerance_backward, relative_tolerance_quadrature,\n absolute_tolerance_quadrature, max_num_steps,\n num_steps_between_checkpoints, interpolation_polynomial, solver_forward,\n solver_backward, msgs, args...);\n return integrator->solution();\n}\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of times, { t1, t2, t3, ... } using the stiff backward differentiation formula BDF solver or the non-stiff Adams solver from CVODES. The ODE system is integrated using the adjoint sensitivity approach of CVODES. This implementation handles the case of a double return type which ensures that no resources are left on the AD stack.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param function_name Calling function name (for printing debugging messages)\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr,\n require_all_st_arithmetic* = nullptr>\nstd::vector ode_adjoint_impl(\n const char* function_name, F&& f, const T_y0& y0, const T_t0& t0,\n const std::vector& ts, double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n std::vector ode_solution;\n {\n nested_rev_autodiff nested;\n\n using integrator_vari\n = cvodes_integrator_adjoint_vari, T_t0, T_ts,\n plain_type_t...>;\n\n auto integrator = new integrator_vari(\n function_name, std::forward(f), y0, t0, ts, relative_tolerance_forward,\n absolute_tolerance_forward, relative_tolerance_backward,\n absolute_tolerance_backward, relative_tolerance_quadrature,\n absolute_tolerance_quadrature, max_num_steps,\n num_steps_between_checkpoints, interpolation_polynomial, solver_forward,\n solver_backward, msgs, args...);\n \n ode_solution = integrator->solution();\n }\n return ode_solution;\n}\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the stiff backward differentiation formula\n * BDF solver or the non-stiff Adams solver from CVODES. The ODE system is\n * integrated using the adjoint sensitivity approach of CVODES.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr>\nauto ode_adjoint_tol_ctl(\n F&& f, const T_y0& y0, const T_t0& t0, const std::vector& ts,\n double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n return ode_adjoint_impl(\n \"ode_adjoint_tol_ctl\", std::forward(f), y0, t0, ts,\n relative_tolerance_forward, absolute_tolerance_forward,\n relative_tolerance_backward, absolute_tolerance_backward,\n relative_tolerance_quadrature, absolute_tolerance_quadrature,\n max_num_steps, num_steps_between_checkpoints, interpolation_polynomial,\n solver_forward, solver_backward, msgs, args...);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef STAN_MATH_REV_FUNCTOR_ODE_ADJOINT_HPP\n#define STAN_MATH_REV_FUNCTOR_ODE_ADJOINT_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the stiff backward differentiation formula\n * BDF solver or the non-stiff Adams solver from CVODES. The ODE system is\n * integrated using the adjoint sensitivity approach of CVODES.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param function_name Calling function name (for printing debugging messages)\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr,\n require_any_not_st_arithmetic* = nullptr>\nauto ode_adjoint_impl(\n const char* function_name, F&& f, const T_y0& y0, const T_t0& t0,\n const std::vector& ts, double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n using integrator_vari\n = cvodes_integrator_adjoint_vari, T_t0, T_ts,\n plain_type_t...>;\n auto integrator = new integrator_vari(\n function_name, std::forward(f), y0, t0, ts, relative_tolerance_forward,\n absolute_tolerance_forward, relative_tolerance_backward,\n absolute_tolerance_backward, relative_tolerance_quadrature,\n absolute_tolerance_quadrature, max_num_steps,\n num_steps_between_checkpoints, interpolation_polynomial, solver_forward,\n solver_backward, msgs, args...);\n return integrator->solution();\n}\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the stiff backward differentiation formula\n * BDF solver or the non-stiff Adams solver from CVODES. The ODE system is\n * integrated using the adjoint sensitivity approach of CVODES. This\n * implementation handles the case of a double return type which ensures that no\n * resources are left on the AD stack.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param function_name Calling function name (for printing debugging messages)\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr,\n require_all_st_arithmetic* = nullptr>\nstd::vector ode_adjoint_impl(\n const char* function_name, F&& f, const T_y0& y0, const T_t0& t0,\n const std::vector& ts, double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n std::vector ode_solution;\n {\n nested_rev_autodiff nested;\n\n using integrator_vari\n = cvodes_integrator_adjoint_vari, T_t0, T_ts,\n plain_type_t...>;\n\n auto integrator = new integrator_vari(\n function_name, std::forward(f), y0, t0, ts,\n relative_tolerance_forward, absolute_tolerance_forward,\n relative_tolerance_backward, absolute_tolerance_backward,\n relative_tolerance_quadrature, absolute_tolerance_quadrature,\n max_num_steps, num_steps_between_checkpoints, interpolation_polynomial,\n solver_forward, solver_backward, msgs, args...);\n\n ode_solution = integrator->solution();\n }\n return ode_solution;\n}\n\n\/**\n * Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of\n * times, { t1, t2, t3, ... } using the stiff backward differentiation formula\n * BDF solver or the non-stiff Adams solver from CVODES. The ODE system is\n * integrated using the adjoint sensitivity approach of CVODES.\n *\n * \\p f must define an operator() with the signature as:\n * template\n * Eigen::Matrix, Eigen::Dynamic, 1>\n * operator()(const T_t& t, const Eigen::Matrix& y,\n * std::ostream* msgs, const T_Args&... args);\n *\n * t is the time, y is the state, msgs is a stream for error messages, and args\n * are optional arguments passed to the ODE solve function (which are passed\n * through to \\p f without modification).\n *\n * @tparam F Type of ODE right hand side\n * @tparam T_y0 Type of initial state\n * @tparam T_t0 Type of initial time\n * @tparam T_ts Type of output times\n * @tparam T_Args Types of pass-through parameters\n *\n * @param f Right hand side of the ODE\n * @param y0 Initial state\n * @param t0 Initial time\n * @param ts Times at which to solve the ODE at. All values must be sorted and\n * not less than t0.\n * @param relative_tolerance_forward Relative tolerance for forward problem\n * passed to CVODES\n * @param absolute_tolerance_forward Absolute tolerance per ODE state for\n * forward problem passed to CVODES\n * @param relative_tolerance_backward Relative tolerance for backward problem\n * passed to CVODES\n * @param absolute_tolerance_backward Absolute tolerance per ODE state for\n * backward problem passed to CVODES\n * @param relative_tolerance_quadrature Relative tolerance for quadrature\n * problem passed to CVODES\n * @param absolute_tolerance_quadrature Absolute tolerance for quadrature\n * problem passed to CVODES\n * @param max_num_steps Upper limit on the number of integration steps to\n * take between each output (error if exceeded)\n * @param num_steps_between_checkpoints Number of integrator steps after which a\n * checkpoint is stored for the backward pass\n * @param interpolation_polynomial type of polynomial used for interpolation\n * @param solver_forward solver used for forward pass\n * @param solver_backward solver used for backward pass\n * @param[in, out] msgs the print stream for warning messages\n * @param args Extra arguments passed unmodified through to ODE right hand side\n * @return An `std::vector` of Eigen column vectors with scalars equal to\n * the least upper bound of `T_y0`, `T_t0`, `T_ts`, and the lambda's arguments.\n * This represents the solution to ODE at times \\p ts\n *\/\ntemplate * = nullptr>\nauto ode_adjoint_tol_ctl(\n F&& f, const T_y0& y0, const T_t0& t0, const std::vector& ts,\n double relative_tolerance_forward,\n const T_abs_tol_fwd& absolute_tolerance_forward,\n double relative_tolerance_backward,\n const T_abs_tol_bwd& absolute_tolerance_backward,\n double relative_tolerance_quadrature, double absolute_tolerance_quadrature,\n long int max_num_steps, \/\/ NOLINT(runtime\/int)\n long int num_steps_between_checkpoints, \/\/ NOLINT(runtime\/int)\n int interpolation_polynomial, int solver_forward, int solver_backward,\n std::ostream* msgs, const T_Args&... args) {\n return ode_adjoint_impl(\n \"ode_adjoint_tol_ctl\", std::forward(f), y0, t0, ts,\n relative_tolerance_forward, absolute_tolerance_forward,\n relative_tolerance_backward, absolute_tolerance_backward,\n relative_tolerance_quadrature, absolute_tolerance_quadrature,\n max_num_steps, num_steps_between_checkpoints, interpolation_polynomial,\n solver_forward, solver_backward, msgs, args...);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"testdriverconfig.h\" \/\/ SRC and BIN dir definitions\n#include \"specification.h\" \/\/ parsing spec files\n#include \"zorba\/zorba_api.h\"\n\nnamespace fs = boost::filesystem;\n\nvoid\nprintFile(std::ostream& os, std::string aInFile)\n{\n std::ifstream lInFileStream(aInFile.c_str());\n assert(lInFileStream);\n\n os << lInFileStream.rdbuf() << std::endl;\n}\n\n\/\/ print parts of a file\n\/\/ starting at aStartPos with the length of aLen\nvoid\nprintPart(std::ostream& os, std::string aInFile, \n int aStartPos, int aLen)\n{\n char* buffer = new char [aLen];\n try {\n std::ifstream lIn(aInFile.c_str());\n lIn.seekg(aStartPos);\n\n int lCharsRead = lIn.readsome (buffer, aLen);\n os.write (buffer, lCharsRead);\n os.flush();\n delete buffer;\n } catch (...)\n {\n delete buffer;\n }\n return;\n}\n\n\n\/\/ check of an error that was repored was expected \n\/\/ by the given specification object\nbool\nisErrorExpected(xqp::ZorbaAlertsManager* aManager, Specification* aSpec)\n{\n for (xqp::ZorbaAlertsManager::const_iterator lIter = aManager->begin();\n lIter != aManager->end(); ++lIter)\n {\n xqp::ZorbaAlert* lAlert = *lIter;\n switch (lAlert->theKind)\n {\n case xqp::ZorbaAlert::ERROR_ALERT:\n {\n xqp::ZorbaError* lErrorAlert = dynamic_cast(lAlert);\n std::string lErrorCode = lErrorAlert->toString(lErrorAlert->theCode);\n for (std::vector::const_iterator lErrorIter = aSpec->errorsBegin();\n lErrorIter != aSpec->errorsEnd(); ++lErrorIter)\n {\n \/\/ error is expected\n if ((*lErrorIter).compare(lErrorCode) == 0)\n return true;\n }\n break;\n }\n default:\n { }\n }\n }\n return false;\n}\n\n\/\/ print all errors that were raised\nvoid\nprintErrors(xqp::ZorbaAlertsManager* aManager)\n{\n if (aManager->size() == 0) return;\n\n std::cout<< \"Errors:\" << std::endl;\n\n for (xqp::ZorbaAlertsManager::const_iterator lIter = aManager->begin();\n lIter != aManager->end(); ++lIter)\n {\n xqp::ZorbaAlert* lAlert = *lIter;\n switch (lAlert->theKind)\n {\n case xqp::ZorbaAlert::ERROR_ALERT:\n {\n xqp::ZorbaError* lErrorAlert = dynamic_cast(lAlert);\n assert(lErrorAlert);\n std::string lErrorCode = lErrorAlert->toString(lErrorAlert->theCode);\n std::cout << lErrorCode << \" \" << lErrorAlert->theDescription << std::endl;\n break;\n }\n default:\n { \n }\n }\n }\n return;\n}\n\n\/\/ set a variable in the dynamic context\n\/\/ inlineFile specifies whether the given parameter is a file and it's value should\n\/\/ be inlined or not\nvoid\nset_var (bool inlineFile, std::string name, std::string val, \n xqp::DynamicQueryContext_t dctx, xqp::XQueryExecution_t exec)\n{\n boost::replace_all(val, \"$RBKT_SRC_DIR\", xqp::RBKT_SRC_DIR);\n if (!inlineFile && dctx != NULL) {\n dctx->SetVariableAsString (name, xqp::xqp_string (val));\n } else if (inlineFile && exec != NULL) {\n std::ifstream is (val.c_str ());\n assert (is);\n exec->SetVariable (name, val.c_str(), is);\n }\n}\n\nvoid \nset_vars (Specification* aSpec, xqp::DynamicQueryContext_t dctx, xqp::XQueryExecution_t exec) \n{\n for (std::vector::const_iterator lIter = aSpec->variablesBegin();\n lIter != aSpec->variablesEnd(); ++lIter)\n {\n set_var ((*lIter).theInline, (*lIter).theVarName, (*lIter).theVarValue, dctx, exec);\n }\n}\n\n\nvoid\ntrim(std::string& str) {\n\n std::string::size_type notwhite = str.find_first_not_of(\" \\t\\n\");\n str.erase(0,notwhite);\n\n notwhite = str.find_last_not_of(\" \\t\\n\"); \n str.erase(notwhite+1); \n}\n\n\/\/ return false if the files are not equal\n\/\/ aLine contains the line number in which the first difference occurs\n\/\/ aCol contains the column number in which the first difference occurs\n\/\/ aPos is the character number off the first difference in the file\n\/\/ -1 is returned for aLine, aCol, and aPos if the files are equal\nbool\nisEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos)\n{\n std::ifstream li(aRefFile.native_file_string().c_str());\n std::ifstream ri(aResFile.native_file_string().c_str()); \n\n std::streambuf * lb = li.rdbuf();\n std::streambuf * rb = ri.rdbuf();\n\n long ls = lb->pubseekoff (0, std::ios::end, std::ios::in);\n long rs = rb->pubseekoff (0, std::ios::end, std::ios::in);\n lb->pubseekpos (0, std::ios::in);\n rb->pubseekpos (0, std::ios::in);\n\n char* lBuf = new char[ls];\n char* rBuf = new char[rs];\n\n try {\n lb->sgetn (lBuf, ls);\n rb->sgetn (rBuf, rs);\n } catch (...)\n {\n li.close(); ri.close();\n delete[] lBuf; delete[] rBuf;\n return false;\n }\n\n li.close();\n ri.close();\n\n std::string lString(lBuf, ls);\n std::string rString(rBuf, rs);\n\n delete[] lBuf; delete[] rBuf;\n\n trim(lString);\n trim(rString);\n\n aLine = 1; aCol = 0; aPos = -1;\n\n size_t aLPos = 0, aRPos = 0;\n char lc, rc;\n while (aLPos != lString.length() && aRPos != rString.length())\n {\n lc = lString.at(aLPos);\n rc = rString.at(aRPos);\n ++aPos; ++aCol;\n if (lc == '\\n') { ++aLine; aCol = 0; }\n if ( lc != rc ) return false;\n ++aLPos; ++aRPos;\n }\n aLine = aCol = aPos = -1;\n return true;\n}\n\nclass ZorbaEngineWrapper {\npublic:\n xqp::ZorbaEngine &factory;\n\n ZorbaEngineWrapper ()\n : factory (xqp::ZorbaEngine::getInstance())\n {\n factory.initThread();\n }\n ~ZorbaEngineWrapper () {\n\n factory.uninitThread();\n factory.shutdown();\n }\n};\n\nvoid \nslurp_file (const char *fname, std::string &result) {\n std::ifstream qfile(fname); assert (qfile);\n\n qfile.seekg (0, std::ios::end);\n size_t len = qfile.tellg ();\n qfile.seekg (0, std::ios::beg);\n char *str = new char [len];\n qfile.read (str, len);\n \n std::string sstr (str, len);\n result.swap (sstr);\n delete [] str;\n}\n\nint\n#ifdef _WIN32_WCE\n_tmain(int argc, _TCHAR* argv[])\n#else\nmain(int argc, char** argv)\n#endif\n{\n fs::path lQueryFile, lResultFile, lErrorFile, lRefFile, lSpecFile;\n Specification lSpec;\n\n \/\/ do initial stuff\n if ( argc == 2 )\n {\n std::string lQueryFileString = xqp::RBKT_SRC_DIR +\"\/Queries\/\" + argv[1];\n lQueryFile = fs::system_complete( fs::path( lQueryFileString, fs::native ) );\n\n std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 );\n std::cout << \"test \" << lQueryWithoutSuffix << std::endl;\n\n lResultFile = fs::system_complete(fs::path( xqp::RBKT_BINARY_DIR +\"\/QueryResults\/\" \n +lQueryWithoutSuffix + \".res\", fs::native) );\n lErrorFile = fs::system_complete(fs::path(xqp::RBKT_BINARY_DIR +\"\/\" \n +lQueryWithoutSuffix + \".err\", fs::native) );\n lRefFile = fs::system_complete(fs::path( xqp::RBKT_SRC_DIR +\"\/ExpQueryResults\/\" \n +lQueryWithoutSuffix +\".xml.res\", fs::native) );\n lSpecFile = fs::system_complete(fs::path(xqp::RBKT_SRC_DIR+ \"\/Queries\/\" \n +lQueryWithoutSuffix +\".spec\", fs::native) );\n }\n else\n {\n std::cerr << \"\\nusage: testdriver [testfile]\" << std::endl;\n return 1;\n }\n\n \/\/ does the query file exists\n if ( (! fs::exists( lQueryFile )) || fs::is_directory( lQueryFile) )\n {\n std::cerr << \"\\n query file \" << lQueryFile.native_file_string() \n << \" does not exist or is not a file\" << std::endl;\n return 2;\n }\n\n \/\/ delete previous files if they exists\n if ( fs::exists ( lResultFile ) ) { fs::remove (lResultFile); }\n if ( fs::exists ( lErrorFile ) ) { fs::remove (lErrorFile); }\n\n \/\/ create the result directory\n fs::path lBucket = fs::system_complete(fs::path( lResultFile.branch_path().string(), fs::native ));\n if ( ! fs::exists( lBucket ) )\n fs::create_directories(lBucket); \/\/ create deep directories\n\n \/\/ read the xargs and errors if the spec file exists\n if ( fs::exists( lSpecFile )) \n { \n lSpec.parseFile(lSpecFile.native_file_string()); \n }\n\n \/\/ we must either have a reference file or an expected error code\n if ( (lSpec.errorsSize() == 0) && ((! fs::exists( lRefFile )) || fs::is_directory( lRefFile)))\n {\n std::cerr << \"No reference result and no expected errors.\" << std::endl;\n return 3;\n }\n\n \/\/ print the query\n std::cout << \"Query:\" << std::endl;\n printFile(std::cout, lQueryFile.native_file_string());\n std::cout << std::endl;\n\n \/\/ initialize the zorba engine\n ZorbaEngineWrapper lEngine; \/\/ the engine is up as long as this object lives\n\n \/\/ create and compile the query\n std::string lQueryString;\n slurp_file(lQueryFile.native_file_string().c_str(), lQueryString);\n xqp::XQuery_t lQuery = lEngine.factory.createQuery(lQueryString.c_str());\n\n xqp::ZorbaAlertsManager& lAlertsManager = lEngine.factory.getAlertsManagerForCurrentThread();\n\n if (lQuery.isNull())\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) \n { \n \/\/ done, we expected an error during compile\n return 0; \n } \n else \n { \n std::cerr << \"Error compiling query\" << std::endl;\n printErrors(&lAlertsManager); return 4;\n }\n }\n\n\n \/\/ set the variables in the dynamic context\n\txqp::DynamicQueryContext_t lDynCtxt = lEngine.factory.createDynamicContext();\n set_vars(&lSpec, lDynCtxt, NULL);\n\n \/\/ execute the query\n xqp::XQueryExecution_t lQueryResult = lQuery->createExecution(lDynCtxt); \n set_vars(&lSpec, NULL, lQueryResult);\n\n if (lQueryResult.isNull()) \/\/ how can this happen?\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) { return 0; } \/\/ done, we expected this error\n else \n { \n std::cerr << \"Error executing query\" << std::endl;\n printErrors(&lAlertsManager);\n return 5;\n }\n }\n \n {\n \/\/ serialize xml\n std::ofstream lResFileStream(lResultFile.native_file_string().c_str());\n assert (lResFileStream.good());\n\n lQueryResult->serializeXML(lResFileStream);\n\n if (lQueryResult->isError())\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) { return 0; } \/\/ again done, we expected this error\n else \n { \n std::cerr << \"Error executing query\" << std::endl;\n printErrors(&lAlertsManager); \n return 6;\n }\n }\n else if ( lSpec.errorsSize() > 0 )\n {\n std::cerr << \"Expected error(s)\";\n for (std::vector::const_iterator lIter = lSpec.errorsBegin();\n lIter != lSpec.errorsEnd(); ++lIter)\n {\n std::cerr << \" \" << *lIter;\n }\n if ( fs::exists(lResultFile) && fs::file_size(lResultFile) == 0)\n std::cerr << \" but got empty result\" << std::endl;\n else\n {\n std::cerr << \" but got result:\" << std::endl;\n printFile(std::cerr, lResultFile.native_file_string());\n std::cerr<< std::endl;\n } \n return 7;\n }\n }\n std::cout << \"Result:\" << std::endl;\n printFile(std::cout, lResultFile.native_file_string());\n std::cout.flush();\n std::cout << std::endl;\n\n\n \/\/ last, we have to diff the result\n int lLine, lCol, lPos; \/\/ where do the files differ\n bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos);\n if ( !lRes ) \/\/ results differ\n {\n std::cerr << std::endl << \"Result does not match expected result\" << std::endl;\n printFile(std::cerr, lRefFile.native_file_string());\n std::cerr << std::endl;\n\n std::cerr << \"See line \" << lLine << \", col \" << lCol << \" of expected result. \" << std::endl;\n std::cerr << \"Got \"; \n printPart(std::cerr, lResultFile.native_file_string(), lPos, 15);\n std::cerr << std::endl << \"Expected \";\n printPart(std::cerr, lRefFile.native_file_string(), lPos, 15);\n std::cerr << std::endl;\n\n return 8;\n }\n\n\n return 0;\n}\nfixed: mismatched delete#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"testdriverconfig.h\" \/\/ SRC and BIN dir definitions\n#include \"specification.h\" \/\/ parsing spec files\n#include \"zorba\/zorba_api.h\"\n\nnamespace fs = boost::filesystem;\n\nvoid\nprintFile(std::ostream& os, std::string aInFile)\n{\n std::ifstream lInFileStream(aInFile.c_str());\n assert(lInFileStream);\n\n os << lInFileStream.rdbuf() << std::endl;\n}\n\n\/\/ print parts of a file\n\/\/ starting at aStartPos with the length of aLen\nvoid\nprintPart(std::ostream& os, std::string aInFile, \n int aStartPos, int aLen)\n{\n char* buffer = new char [aLen];\n try {\n std::ifstream lIn(aInFile.c_str());\n lIn.seekg(aStartPos);\n\n int lCharsRead = lIn.readsome (buffer, aLen);\n os.write (buffer, lCharsRead);\n os.flush();\n delete[] buffer;\n } catch (...)\n {\n delete[] buffer;\n }\n return;\n}\n\n\n\/\/ check of an error that was repored was expected \n\/\/ by the given specification object\nbool\nisErrorExpected(xqp::ZorbaAlertsManager* aManager, Specification* aSpec)\n{\n for (xqp::ZorbaAlertsManager::const_iterator lIter = aManager->begin();\n lIter != aManager->end(); ++lIter)\n {\n xqp::ZorbaAlert* lAlert = *lIter;\n switch (lAlert->theKind)\n {\n case xqp::ZorbaAlert::ERROR_ALERT:\n {\n xqp::ZorbaError* lErrorAlert = dynamic_cast(lAlert);\n std::string lErrorCode = lErrorAlert->toString(lErrorAlert->theCode);\n for (std::vector::const_iterator lErrorIter = aSpec->errorsBegin();\n lErrorIter != aSpec->errorsEnd(); ++lErrorIter)\n {\n \/\/ error is expected\n if ((*lErrorIter).compare(lErrorCode) == 0)\n return true;\n }\n break;\n }\n default:\n { }\n }\n }\n return false;\n}\n\n\/\/ print all errors that were raised\nvoid\nprintErrors(xqp::ZorbaAlertsManager* aManager)\n{\n if (aManager->size() == 0) return;\n\n std::cout<< \"Errors:\" << std::endl;\n\n for (xqp::ZorbaAlertsManager::const_iterator lIter = aManager->begin();\n lIter != aManager->end(); ++lIter)\n {\n xqp::ZorbaAlert* lAlert = *lIter;\n switch (lAlert->theKind)\n {\n case xqp::ZorbaAlert::ERROR_ALERT:\n {\n xqp::ZorbaError* lErrorAlert = dynamic_cast(lAlert);\n assert(lErrorAlert);\n std::string lErrorCode = lErrorAlert->toString(lErrorAlert->theCode);\n std::cout << lErrorCode << \" \" << lErrorAlert->theDescription << std::endl;\n break;\n }\n default:\n { \n }\n }\n }\n return;\n}\n\n\/\/ set a variable in the dynamic context\n\/\/ inlineFile specifies whether the given parameter is a file and it's value should\n\/\/ be inlined or not\nvoid\nset_var (bool inlineFile, std::string name, std::string val, \n xqp::DynamicQueryContext_t dctx, xqp::XQueryExecution_t exec)\n{\n boost::replace_all(val, \"$RBKT_SRC_DIR\", xqp::RBKT_SRC_DIR);\n if (!inlineFile && dctx != NULL) {\n dctx->SetVariableAsString (name, xqp::xqp_string (val));\n } else if (inlineFile && exec != NULL) {\n std::ifstream is (val.c_str ());\n assert (is);\n exec->SetVariable (name, val.c_str(), is);\n }\n}\n\nvoid \nset_vars (Specification* aSpec, xqp::DynamicQueryContext_t dctx, xqp::XQueryExecution_t exec) \n{\n for (std::vector::const_iterator lIter = aSpec->variablesBegin();\n lIter != aSpec->variablesEnd(); ++lIter)\n {\n set_var ((*lIter).theInline, (*lIter).theVarName, (*lIter).theVarValue, dctx, exec);\n }\n}\n\n\nvoid\ntrim(std::string& str) {\n\n std::string::size_type notwhite = str.find_first_not_of(\" \\t\\n\");\n str.erase(0,notwhite);\n\n notwhite = str.find_last_not_of(\" \\t\\n\"); \n str.erase(notwhite+1); \n}\n\n\/\/ return false if the files are not equal\n\/\/ aLine contains the line number in which the first difference occurs\n\/\/ aCol contains the column number in which the first difference occurs\n\/\/ aPos is the character number off the first difference in the file\n\/\/ -1 is returned for aLine, aCol, and aPos if the files are equal\nbool\nisEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos)\n{\n std::ifstream li(aRefFile.native_file_string().c_str());\n std::ifstream ri(aResFile.native_file_string().c_str()); \n\n std::streambuf * lb = li.rdbuf();\n std::streambuf * rb = ri.rdbuf();\n\n long ls = lb->pubseekoff (0, std::ios::end, std::ios::in);\n long rs = rb->pubseekoff (0, std::ios::end, std::ios::in);\n lb->pubseekpos (0, std::ios::in);\n rb->pubseekpos (0, std::ios::in);\n\n char* lBuf = new char[ls];\n char* rBuf = new char[rs];\n\n try {\n lb->sgetn (lBuf, ls);\n rb->sgetn (rBuf, rs);\n } catch (...)\n {\n li.close(); ri.close();\n delete[] lBuf; delete[] rBuf;\n return false;\n }\n\n li.close();\n ri.close();\n\n std::string lString(lBuf, ls);\n std::string rString(rBuf, rs);\n\n delete[] lBuf; delete[] rBuf;\n\n trim(lString);\n trim(rString);\n\n aLine = 1; aCol = 0; aPos = -1;\n\n size_t aLPos = 0, aRPos = 0;\n char lc, rc;\n while (aLPos != lString.length() && aRPos != rString.length())\n {\n lc = lString.at(aLPos);\n rc = rString.at(aRPos);\n ++aPos; ++aCol;\n if (lc == '\\n') { ++aLine; aCol = 0; }\n if ( lc != rc ) return false;\n ++aLPos; ++aRPos;\n }\n aLine = aCol = aPos = -1;\n return true;\n}\n\nclass ZorbaEngineWrapper {\npublic:\n xqp::ZorbaEngine &factory;\n\n ZorbaEngineWrapper ()\n : factory (xqp::ZorbaEngine::getInstance())\n {\n factory.initThread();\n }\n ~ZorbaEngineWrapper () {\n\n factory.uninitThread();\n factory.shutdown();\n }\n};\n\nvoid \nslurp_file (const char *fname, std::string &result) {\n std::ifstream qfile(fname); assert (qfile);\n\n qfile.seekg (0, std::ios::end);\n size_t len = qfile.tellg ();\n qfile.seekg (0, std::ios::beg);\n char *str = new char [len];\n qfile.read (str, len);\n \n std::string sstr (str, len);\n result.swap (sstr);\n delete [] str;\n}\n\nint\n#ifdef _WIN32_WCE\n_tmain(int argc, _TCHAR* argv[])\n#else\nmain(int argc, char** argv)\n#endif\n{\n fs::path lQueryFile, lResultFile, lErrorFile, lRefFile, lSpecFile;\n Specification lSpec;\n\n \/\/ do initial stuff\n if ( argc == 2 )\n {\n std::string lQueryFileString = xqp::RBKT_SRC_DIR +\"\/Queries\/\" + argv[1];\n lQueryFile = fs::system_complete( fs::path( lQueryFileString, fs::native ) );\n\n std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 );\n std::cout << \"test \" << lQueryWithoutSuffix << std::endl;\n\n lResultFile = fs::system_complete(fs::path( xqp::RBKT_BINARY_DIR +\"\/QueryResults\/\" \n +lQueryWithoutSuffix + \".res\", fs::native) );\n lErrorFile = fs::system_complete(fs::path(xqp::RBKT_BINARY_DIR +\"\/\" \n +lQueryWithoutSuffix + \".err\", fs::native) );\n lRefFile = fs::system_complete(fs::path( xqp::RBKT_SRC_DIR +\"\/ExpQueryResults\/\" \n +lQueryWithoutSuffix +\".xml.res\", fs::native) );\n lSpecFile = fs::system_complete(fs::path(xqp::RBKT_SRC_DIR+ \"\/Queries\/\" \n +lQueryWithoutSuffix +\".spec\", fs::native) );\n }\n else\n {\n std::cerr << \"\\nusage: testdriver [testfile]\" << std::endl;\n return 1;\n }\n\n \/\/ does the query file exists\n if ( (! fs::exists( lQueryFile )) || fs::is_directory( lQueryFile) )\n {\n std::cerr << \"\\n query file \" << lQueryFile.native_file_string() \n << \" does not exist or is not a file\" << std::endl;\n return 2;\n }\n\n \/\/ delete previous files if they exists\n if ( fs::exists ( lResultFile ) ) { fs::remove (lResultFile); }\n if ( fs::exists ( lErrorFile ) ) { fs::remove (lErrorFile); }\n\n \/\/ create the result directory\n fs::path lBucket = fs::system_complete(fs::path( lResultFile.branch_path().string(), fs::native ));\n if ( ! fs::exists( lBucket ) )\n fs::create_directories(lBucket); \/\/ create deep directories\n\n \/\/ read the xargs and errors if the spec file exists\n if ( fs::exists( lSpecFile )) \n { \n lSpec.parseFile(lSpecFile.native_file_string()); \n }\n\n \/\/ we must either have a reference file or an expected error code\n if ( (lSpec.errorsSize() == 0) && ((! fs::exists( lRefFile )) || fs::is_directory( lRefFile)))\n {\n std::cerr << \"No reference result and no expected errors.\" << std::endl;\n return 3;\n }\n\n \/\/ print the query\n std::cout << \"Query:\" << std::endl;\n printFile(std::cout, lQueryFile.native_file_string());\n std::cout << std::endl;\n\n \/\/ initialize the zorba engine\n ZorbaEngineWrapper lEngine; \/\/ the engine is up as long as this object lives\n\n \/\/ create and compile the query\n std::string lQueryString;\n slurp_file(lQueryFile.native_file_string().c_str(), lQueryString);\n xqp::XQuery_t lQuery = lEngine.factory.createQuery(lQueryString.c_str());\n\n xqp::ZorbaAlertsManager& lAlertsManager = lEngine.factory.getAlertsManagerForCurrentThread();\n\n if (lQuery.isNull())\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) \n { \n \/\/ done, we expected an error during compile\n return 0; \n } \n else \n { \n std::cerr << \"Error compiling query\" << std::endl;\n printErrors(&lAlertsManager); return 4;\n }\n }\n\n\n \/\/ set the variables in the dynamic context\n\txqp::DynamicQueryContext_t lDynCtxt = lEngine.factory.createDynamicContext();\n set_vars(&lSpec, lDynCtxt, NULL);\n\n \/\/ execute the query\n xqp::XQueryExecution_t lQueryResult = lQuery->createExecution(lDynCtxt); \n set_vars(&lSpec, NULL, lQueryResult);\n\n if (lQueryResult.isNull()) \/\/ how can this happen?\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) { return 0; } \/\/ done, we expected this error\n else \n { \n std::cerr << \"Error executing query\" << std::endl;\n printErrors(&lAlertsManager);\n return 5;\n }\n }\n \n {\n \/\/ serialize xml\n std::ofstream lResFileStream(lResultFile.native_file_string().c_str());\n assert (lResFileStream.good());\n\n lQueryResult->serializeXML(lResFileStream);\n\n if (lQueryResult->isError())\n {\n if (isErrorExpected(&lAlertsManager, &lSpec)) { return 0; } \/\/ again done, we expected this error\n else \n { \n std::cerr << \"Error executing query\" << std::endl;\n printErrors(&lAlertsManager); \n return 6;\n }\n }\n else if ( lSpec.errorsSize() > 0 )\n {\n std::cerr << \"Expected error(s)\";\n for (std::vector::const_iterator lIter = lSpec.errorsBegin();\n lIter != lSpec.errorsEnd(); ++lIter)\n {\n std::cerr << \" \" << *lIter;\n }\n if ( fs::exists(lResultFile) && fs::file_size(lResultFile) == 0)\n std::cerr << \" but got empty result\" << std::endl;\n else\n {\n std::cerr << \" but got result:\" << std::endl;\n printFile(std::cerr, lResultFile.native_file_string());\n std::cerr<< std::endl;\n } \n return 7;\n }\n }\n std::cout << \"Result:\" << std::endl;\n printFile(std::cout, lResultFile.native_file_string());\n std::cout.flush();\n std::cout << std::endl;\n\n\n \/\/ last, we have to diff the result\n int lLine, lCol, lPos; \/\/ where do the files differ\n bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos);\n if ( !lRes ) \/\/ results differ\n {\n std::cerr << std::endl << \"Result does not match expected result\" << std::endl;\n printFile(std::cerr, lRefFile.native_file_string());\n std::cerr << std::endl;\n\n std::cerr << \"See line \" << lLine << \", col \" << lCol << \" of expected result. \" << std::endl;\n std::cerr << \"Got \"; \n printPart(std::cerr, lResultFile.native_file_string(), lPos, 15);\n std::cerr << std::endl << \"Expected \";\n printPart(std::cerr, lRefFile.native_file_string(), lPos, 15);\n std::cerr << std::endl;\n\n return 8;\n }\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"testsettings.hpp\"\n#ifdef TEST_FILE_LOCKS\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"util\/thread_wrapper.hpp\"\n\nusing namespace realm::util;\nusing namespace realm::test_util;\n\n\n\/\/ Test independence and thread-safety\n\/\/ -----------------------------------\n\/\/\n\/\/ All tests must be thread safe and independent of each other. This\n\/\/ is required because it allows for both shuffling of the execution\n\/\/ order and for parallelized testing.\n\/\/\n\/\/ In particular, avoid using std::rand() since it is not guaranteed\n\/\/ to be thread safe. Instead use the API offered in\n\/\/ `test\/util\/random.hpp`.\n\/\/\n\/\/ All files created in tests must use the TEST_PATH macro (or one of\n\/\/ its friends) to obtain a suitable file system path. See\n\/\/ `test\/util\/test_path.hpp`.\n\/\/\n\/\/\n\/\/ Debugging and the ONLY() macro\n\/\/ ------------------------------\n\/\/\n\/\/ A simple way of disabling all tests except one called `Foo`, is to\n\/\/ replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the\n\/\/ test suite. Note that you can also use filtering by setting the\n\/\/ environment varible `UNITTEST_FILTER`. See `README.md` for more on\n\/\/ this.\n\/\/\n\/\/ Another way to debug a particular test, is to copy that test into\n\/\/ `experiments\/testcase.cpp` and then run `sh build.sh\n\/\/ check-testcase` (or one of its friends) from the command line.\n\n\n\/\/ The assumption is that if multiple processes try to place an\n\/\/ exclusive lock on a file in a non-blocking fashion, then at least\n\/\/ one will succeed (assuming that no one else interferes). This test\n\/\/ trys to verify that this is the case by repeatedly letting two\n\/\/ treads compete for the lock. This is by no means a \"water tight\"\n\/\/ test, but it is probably the best we can do.\nTEST(File_NoSpuriousTryLockFailures)\n{\n#if TEST_DURATION < 1\n const int num_rounds = 1000;\n#elif TEST_DURATION < 2\n const int num_rounds = 10000;\n#elif TEST_DURATION < 3\n const int num_rounds = 100000;\n#else\n const int num_rounds = 1000000;\n#endif\n\n const int num_slaves = 2;\n\n\n Mutex mutex;\n CondVar cond;\n int num_slaves_ready = 0;\n int num_good_locks = 0;\n bool slaves_run[num_slaves];\n std::map results;\n bool terminate = false;\n\n auto kill_em_all = [&] {\n LockGuard l(mutex);\n terminate = true;\n cond.notify_all();\n };\n\n auto master = [&] {\n try {\n LockGuard l(mutex);\n for (int i = 0; i != num_rounds; ++i) {\n while (num_slaves_ready != num_slaves) {\n if (terminate)\n return;\n cond.wait(l);\n }\n num_slaves_ready = 0;\n\n ++results[num_good_locks];\n num_good_locks = 0;\n\n for (int j = 0; j != num_slaves; ++j)\n slaves_run[j] = true;\n cond.notify_all();\n }\n }\n catch (...) {\n kill_em_all();\n throw;\n }\n };\n\n auto slave = [&](int ndx, std::string path) {\n try {\n File file(path, File::mode_Write);\n for (int i = 0; i != num_rounds; ++i) {\n bool good_lock = file.try_lock_exclusive();\n if (good_lock)\n file.unlock();\n {\n LockGuard l(mutex);\n if (good_lock)\n ++num_good_locks;\n ++num_slaves_ready;\n cond.notify_all();\n while (!slaves_run[ndx]) {\n if (terminate)\n return;\n cond.wait(l);\n }\n slaves_run[ndx] = false;\n }\n }\n }\n catch (...) {\n kill_em_all();\n throw;\n }\n };\n\n TEST_PATH(path);\n ThreadWrapper slaves[num_slaves];\n for (int i = 0; i != num_slaves; ++i) {\n slaves_run[i] = false;\n slaves[i].start([=] { slave(i, std::string(path)); });\n }\n master();\n for (int i = 0; i != num_slaves; ++i)\n CHECK(!slaves[i].join());\n\n\/*\n typedef std::map::const_iterator iter;\n iter end = results.end();\n for (iter i = results.begin(); i != end; ++i)\n std::cout << i->first << \" -> \" << i->second << \"\\n\";\n*\/\n\n \/\/ Check that there are no cases where no one got the lock\n CHECK_EQUAL(0, results[0]);\n}\n\n#endif \/\/ TEST_FILE_LOCKS\nFixed instance of (likely) unintentional copy of a TestPathGuard object#include \"testsettings.hpp\"\n#ifdef TEST_FILE_LOCKS\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"util\/thread_wrapper.hpp\"\n\nusing namespace realm::util;\nusing namespace realm::test_util;\n\n\n\/\/ Test independence and thread-safety\n\/\/ -----------------------------------\n\/\/\n\/\/ All tests must be thread safe and independent of each other. This\n\/\/ is required because it allows for both shuffling of the execution\n\/\/ order and for parallelized testing.\n\/\/\n\/\/ In particular, avoid using std::rand() since it is not guaranteed\n\/\/ to be thread safe. Instead use the API offered in\n\/\/ `test\/util\/random.hpp`.\n\/\/\n\/\/ All files created in tests must use the TEST_PATH macro (or one of\n\/\/ its friends) to obtain a suitable file system path. See\n\/\/ `test\/util\/test_path.hpp`.\n\/\/\n\/\/\n\/\/ Debugging and the ONLY() macro\n\/\/ ------------------------------\n\/\/\n\/\/ A simple way of disabling all tests except one called `Foo`, is to\n\/\/ replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the\n\/\/ test suite. Note that you can also use filtering by setting the\n\/\/ environment varible `UNITTEST_FILTER`. See `README.md` for more on\n\/\/ this.\n\/\/\n\/\/ Another way to debug a particular test, is to copy that test into\n\/\/ `experiments\/testcase.cpp` and then run `sh build.sh\n\/\/ check-testcase` (or one of its friends) from the command line.\n\n\n\/\/ The assumption is that if multiple processes try to place an\n\/\/ exclusive lock on a file in a non-blocking fashion, then at least\n\/\/ one will succeed (assuming that no one else interferes). This test\n\/\/ trys to verify that this is the case by repeatedly letting two\n\/\/ treads compete for the lock. This is by no means a \"water tight\"\n\/\/ test, but it is probably the best we can do.\nTEST(File_NoSpuriousTryLockFailures)\n{\n#if TEST_DURATION < 1\n const int num_rounds = 1000;\n#elif TEST_DURATION < 2\n const int num_rounds = 10000;\n#elif TEST_DURATION < 3\n const int num_rounds = 100000;\n#else\n const int num_rounds = 1000000;\n#endif\n\n const int num_slaves = 2;\n\n\n Mutex mutex;\n CondVar cond;\n int num_slaves_ready = 0;\n int num_good_locks = 0;\n bool slaves_run[num_slaves];\n std::map results;\n bool terminate = false;\n\n auto kill_em_all = [&] {\n LockGuard l(mutex);\n terminate = true;\n cond.notify_all();\n };\n\n auto master = [&] {\n try {\n LockGuard l(mutex);\n for (int i = 0; i != num_rounds; ++i) {\n while (num_slaves_ready != num_slaves) {\n if (terminate)\n return;\n cond.wait(l);\n }\n num_slaves_ready = 0;\n\n ++results[num_good_locks];\n num_good_locks = 0;\n\n for (int j = 0; j != num_slaves; ++j)\n slaves_run[j] = true;\n cond.notify_all();\n }\n }\n catch (...) {\n kill_em_all();\n throw;\n }\n };\n\n auto slave = [&](int ndx, std::string path) {\n try {\n File file(path, File::mode_Write);\n for (int i = 0; i != num_rounds; ++i) {\n bool good_lock = file.try_lock_exclusive();\n if (good_lock)\n file.unlock();\n {\n LockGuard l(mutex);\n if (good_lock)\n ++num_good_locks;\n ++num_slaves_ready;\n cond.notify_all();\n while (!slaves_run[ndx]) {\n if (terminate)\n return;\n cond.wait(l);\n }\n slaves_run[ndx] = false;\n }\n }\n }\n catch (...) {\n kill_em_all();\n throw;\n }\n };\n\n TEST_PATH(path);\n std::string str_path = path;\n ThreadWrapper slaves[num_slaves];\n for (int i = 0; i != num_slaves; ++i) {\n slaves_run[i] = false;\n slaves[i].start([=] { slave(i, str_path); });\n }\n master();\n for (int i = 0; i != num_slaves; ++i)\n CHECK(!slaves[i].join());\n\n\/*\n typedef std::map::const_iterator iter;\n iter end = results.end();\n for (iter i = results.begin(); i != end; ++i)\n std::cout << i->first << \" -> \" << i->second << \"\\n\";\n*\/\n\n \/\/ Check that there are no cases where no one got the lock\n CHECK_EQUAL(0, results[0]);\n}\n\n#endif \/\/ TEST_FILE_LOCKS\n<|endoftext|>"} {"text":"\/*\n Copyright 2011 John Selbie\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 \"commonincludes.hpp\"\n#include \"unittest.h\"\n\n#include \"polling.h\"\n\n#include \"testpolling.h\"\n\nCTestPolling::CTestPolling()\n{\n ;\n}\n\nCTestPolling::~CTestPolling()\n{\n TestUnInit();\n}\n\nHRESULT CTestPolling::Run()\n{\n HRESULT hr = S_OK;\n \n#ifdef HAS_EPOLL\n _polltype = IPOLLING_TYPE_EPOLL;\n ChkA(Test1());\n ChkA(Test2());\n#endif\n \n _polltype = IPOLLING_TYPE_POLL;\n ChkA(Test1());\n ChkA(Test2());\n ChkA(Test3());\nCleanup:\n return hr;\n}\n\nvoid CTestPolling::TestUnInit()\n{\n size_t size = _pipes.size();\n _spPolling.ReleaseAndClear();\n \n for (size_t index = 0; index < size; index++)\n {\n close(_pipes[index].readpipe);\n close(_pipes[index].writepipe);\n }\n \n _pipes.clear();\n \n}\n\nHRESULT CTestPolling::SetNonBlocking(int fd)\n{\n HRESULT hr = S_OK;\n int result;\n int flags;\n \n flags = ::fcntl(fd, F_GETFL, 0);\n \n ChkIfA(flags == -1, ERRNOHR);\n \n flags |= O_NONBLOCK;\n \n result = fcntl(fd , F_SETFL , flags);\n \n ChkIfA(result == -1, ERRNOHR);\n \nCleanup:\n return hr; \n \n}\n\nHRESULT CTestPolling::CreateAndAddPipe()\n{\n HRESULT hr = S_OK;\n PipePair pp = {};\n int ret = -1;\n int fds[2];\n ret = ::pipe(fds);\n \n ChkIfA(ret == -1, ERRNOHR);\n\n pp.readpipe = fds[0];\n pp.writepipe = fds[1];\n pp.fDataPending = false;\n\n ChkA(SetNonBlocking(pp.readpipe));\n ChkA(SetNonBlocking(pp.writepipe));\n\n _pipes.push_back(pp);\n\n ChkA(_spPolling->Add(fds[0], IPOLLING_READ)); \n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::TestInit(size_t sizePolling, size_t sizePipeArray)\n{\n HRESULT hr = S_OK;\n \n TestUnInit();\n \n ChkA(CreatePollingInstance(_polltype, sizePolling, _spPolling.GetPointerPointer()));\n \n for (size_t index = 0; index < sizePipeArray; index++)\n {\n ChkA(CreateAndAddPipe());\n }\n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::WritePipe(PipePair* pPair)\n{\n HRESULT hr = S_OK;\n char ch = 'x';\n int ret = -1;\n \n ret = write(pPair->writepipe, &ch, 1);\n ChkIfA(ret < 0, ERRNOHR);\n ChkIfA(ret == 0, E_UNEXPECTED);\n pPair->fDataPending = true;\n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::ConsumeEvent(int* pFD, int* pCount)\n{\n HRESULT hr = S_OK;\n HRESULT hrResult = S_OK;\n PollEvent event;\n char ch;\n int result;\n int count = 0;\n int fd = -1;\n int pipesindex = -1;\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkA(hrResult);\n \n ChkIfA(hrResult == S_FALSE, S_FALSE);\n \n fd = event.fd;\n \n while (true)\n {\n result = ::read(fd, &ch, 1);\n if (result <= 0)\n {\n break;\n }\n count++;\n }\n \n pipesindex = FindPipePairIndex(fd);\n ChkIfA(pipesindex == -1, E_UNEXPECTED);\n \n ChkIfA(count == 0, E_UNEXPECTED);\n \n ChkIfA(_pipes[pipesindex].fDataPending == false, E_UNEXPECTED);\n _pipes[pipesindex].fDataPending = false;\n \nCleanup:\n if (pFD) \n {\n *pFD = fd;\n }\n if (pCount)\n {\n *pCount = count;\n }\n return hr;\n}\n\nint CTestPolling::FindPipePairIndex(int fd)\n{\n size_t size = _pipes.size();\n \n for (size_t index = 0; index < size; index++)\n {\n if ((_pipes[index].readpipe == fd) || (_pipes[index].writepipe == fd))\n {\n return index;\n }\n }\n \n return -1;\n}\n\nsize_t CTestPolling::GetPendingCount()\n{\n size_t size = _pipes.size();\n size_t count = 0;\n \n for (size_t index = 0; index < size; index++)\n {\n if (_pipes[index].fDataPending)\n {\n count++;\n }\n }\n \n return count;\n}\n\nHRESULT CTestPolling::RemovePipe(int pipeindex)\n{\n HRESULT hr = S_OK;\n \n size_t size = _pipes.size();\n \n ChkIfA(pipeindex < 0, E_FAIL);\n ChkIfA(pipeindex >= (int)size, E_FAIL);\n \n ChkA(_spPolling->Remove(_pipes[pipeindex].readpipe));\n \n close(_pipes[pipeindex].readpipe);\n _pipes[pipeindex].readpipe = -1;\n \n close(_pipes[pipeindex].writepipe);\n _pipes[pipeindex].writepipe = -1;\n \n _pipes.erase(_pipes.begin()+pipeindex);\n \nCleanup:\n return hr;\n}\n\n\n\n\/\/ simplest of all tests. Just set a file descriptor and see that it's available\n\/\/ repeat many times\nHRESULT CTestPolling::Test1()\n{\n HRESULT hr = S_OK;\n HRESULT hrResult;\n size_t size;\n PollEvent event; \n int fd;\n int count = 0;\n \n srand(100);\n\n ChkA(TestInit(10, 10));\n \n size = _pipes.size();\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED); \n \n \/\/ one event at a time model\n for (int index = 0; index < 100; index++)\n {\n\n size_t item = rand() % size;\n \n ChkA(WritePipe(&_pipes[item]));\n \n ConsumeEvent(&fd, &count);\n \n ChkIfA(fd != _pipes[item].readpipe, E_UNEXPECTED);\n ChkIfA(count != 1, E_UNEXPECTED);\n }\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);\n \nCleanup:\n return hr;\n}\n\n\n\n\/\/ create a polling set\nHRESULT CTestPolling::Test2()\n{\n \/\/ simulate the following events in random order:\n \/\/ socket added (did it succeed as expected)\n \/\/ incoming data (write to a random pipe)\n \/\/ WaitForNextEvent called (did it return an expected result\/socket)\n \/\/ Remove socket last notified about\n\n HRESULT hr = S_OK;\n HRESULT hrResult;\n PollEvent event; \n const size_t c_maxSockets = 10;\n \n srand(100);\n\n ChkA(TestInit(c_maxSockets, 0));\n \n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED); \n \n \n for (size_t index = 0; index < 1000; index++)\n {\n int randresult = ::rand() % 4;\n \n switch (randresult)\n {\n case 0:\n {\n \/\/ simulate a new socket being added\n if (_pipes.size() >= c_maxSockets)\n {\n continue;\n }\n \n ChkA(CreateAndAddPipe());\n\n break;\n }\n \n case 1:\n {\n \/\/ simulate incoming data\n size_t size = _pipes.size();\n size_t itemindex;\n \n if (size == 0)\n {\n continue;\n }\n \n itemindex = rand() % size;\n ChkA(WritePipe(&_pipes[itemindex]));\n \n break;\n }\n \n case 2:\n case 3:\n {\n int fd;\n size_t pending = GetPendingCount();\n if (pending == 0)\n {\n continue;\n }\n \n ChkA(ConsumeEvent(&fd, NULL));\n \n if (randresult == 3)\n {\n \/\/ simulate removing this pipe from the set\n ChkA(RemovePipe(FindPipePairIndex(fd)));\n }\n break;\n } \/\/ case\n } \/\/ switch\n } \/\/ for\n\nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::Test3()\n{\n HRESULT hr = S_OK;\n\n const size_t c_maxSockets = 10;\n \n ChkA(TestInit(c_maxSockets, 0));\n \n ChkA(_spPolling->Add(3, IPOLLING_READ));\n ChkA(_spPolling->Remove(3));\n ChkA(_spPolling->Add(5, IPOLLING_READ));\n ChkA(_spPolling->Add(7, IPOLLING_READ));\n ChkA(_spPolling->Add(9, IPOLLING_READ));\n ChkA(_spPolling->Remove(5));\n ChkA(_spPolling->Add(11, IPOLLING_READ));\n ChkA(_spPolling->Add(13, IPOLLING_READ));\n ChkA(_spPolling->Remove(7));\n ChkA(_spPolling->Add(15, IPOLLING_READ));\n ChkA(_spPolling->Add(17, IPOLLING_READ));\n ChkA(_spPolling->Add(19, IPOLLING_READ));\n ChkA(_spPolling->Remove(11));\n ChkA(_spPolling->Add(21, IPOLLING_READ));\n ChkA(_spPolling->Add(23, IPOLLING_READ));\n ChkA(_spPolling->Add(25, IPOLLING_READ));\n ChkA(_spPolling->Add(27, IPOLLING_READ));\n ChkA(_spPolling->Remove(13));\n \nCleanup:\n return hr;\n \n}added end of line to testpolling.cpp\/*\n Copyright 2011 John Selbie\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 \"commonincludes.hpp\"\n#include \"unittest.h\"\n\n#include \"polling.h\"\n\n#include \"testpolling.h\"\n\nCTestPolling::CTestPolling()\n{\n ;\n}\n\nCTestPolling::~CTestPolling()\n{\n TestUnInit();\n}\n\nHRESULT CTestPolling::Run()\n{\n HRESULT hr = S_OK;\n \n#ifdef HAS_EPOLL\n _polltype = IPOLLING_TYPE_EPOLL;\n ChkA(Test1());\n ChkA(Test2());\n#endif\n \n _polltype = IPOLLING_TYPE_POLL;\n ChkA(Test1());\n ChkA(Test2());\n ChkA(Test3());\nCleanup:\n return hr;\n}\n\nvoid CTestPolling::TestUnInit()\n{\n size_t size = _pipes.size();\n _spPolling.ReleaseAndClear();\n \n for (size_t index = 0; index < size; index++)\n {\n close(_pipes[index].readpipe);\n close(_pipes[index].writepipe);\n }\n \n _pipes.clear();\n \n}\n\nHRESULT CTestPolling::SetNonBlocking(int fd)\n{\n HRESULT hr = S_OK;\n int result;\n int flags;\n \n flags = ::fcntl(fd, F_GETFL, 0);\n \n ChkIfA(flags == -1, ERRNOHR);\n \n flags |= O_NONBLOCK;\n \n result = fcntl(fd , F_SETFL , flags);\n \n ChkIfA(result == -1, ERRNOHR);\n \nCleanup:\n return hr; \n \n}\n\nHRESULT CTestPolling::CreateAndAddPipe()\n{\n HRESULT hr = S_OK;\n PipePair pp = {};\n int ret = -1;\n int fds[2];\n ret = ::pipe(fds);\n \n ChkIfA(ret == -1, ERRNOHR);\n\n pp.readpipe = fds[0];\n pp.writepipe = fds[1];\n pp.fDataPending = false;\n\n ChkA(SetNonBlocking(pp.readpipe));\n ChkA(SetNonBlocking(pp.writepipe));\n\n _pipes.push_back(pp);\n\n ChkA(_spPolling->Add(fds[0], IPOLLING_READ)); \n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::TestInit(size_t sizePolling, size_t sizePipeArray)\n{\n HRESULT hr = S_OK;\n \n TestUnInit();\n \n ChkA(CreatePollingInstance(_polltype, sizePolling, _spPolling.GetPointerPointer()));\n \n for (size_t index = 0; index < sizePipeArray; index++)\n {\n ChkA(CreateAndAddPipe());\n }\n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::WritePipe(PipePair* pPair)\n{\n HRESULT hr = S_OK;\n char ch = 'x';\n int ret = -1;\n \n ret = write(pPair->writepipe, &ch, 1);\n ChkIfA(ret < 0, ERRNOHR);\n ChkIfA(ret == 0, E_UNEXPECTED);\n pPair->fDataPending = true;\n \nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::ConsumeEvent(int* pFD, int* pCount)\n{\n HRESULT hr = S_OK;\n HRESULT hrResult = S_OK;\n PollEvent event;\n char ch;\n int result;\n int count = 0;\n int fd = -1;\n int pipesindex = -1;\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkA(hrResult);\n \n ChkIfA(hrResult == S_FALSE, S_FALSE);\n \n fd = event.fd;\n \n while (true)\n {\n result = ::read(fd, &ch, 1);\n if (result <= 0)\n {\n break;\n }\n count++;\n }\n \n pipesindex = FindPipePairIndex(fd);\n ChkIfA(pipesindex == -1, E_UNEXPECTED);\n \n ChkIfA(count == 0, E_UNEXPECTED);\n \n ChkIfA(_pipes[pipesindex].fDataPending == false, E_UNEXPECTED);\n _pipes[pipesindex].fDataPending = false;\n \nCleanup:\n if (pFD) \n {\n *pFD = fd;\n }\n if (pCount)\n {\n *pCount = count;\n }\n return hr;\n}\n\nint CTestPolling::FindPipePairIndex(int fd)\n{\n size_t size = _pipes.size();\n \n for (size_t index = 0; index < size; index++)\n {\n if ((_pipes[index].readpipe == fd) || (_pipes[index].writepipe == fd))\n {\n return index;\n }\n }\n \n return -1;\n}\n\nsize_t CTestPolling::GetPendingCount()\n{\n size_t size = _pipes.size();\n size_t count = 0;\n \n for (size_t index = 0; index < size; index++)\n {\n if (_pipes[index].fDataPending)\n {\n count++;\n }\n }\n \n return count;\n}\n\nHRESULT CTestPolling::RemovePipe(int pipeindex)\n{\n HRESULT hr = S_OK;\n \n size_t size = _pipes.size();\n \n ChkIfA(pipeindex < 0, E_FAIL);\n ChkIfA(pipeindex >= (int)size, E_FAIL);\n \n ChkA(_spPolling->Remove(_pipes[pipeindex].readpipe));\n \n close(_pipes[pipeindex].readpipe);\n _pipes[pipeindex].readpipe = -1;\n \n close(_pipes[pipeindex].writepipe);\n _pipes[pipeindex].writepipe = -1;\n \n _pipes.erase(_pipes.begin()+pipeindex);\n \nCleanup:\n return hr;\n}\n\n\n\n\/\/ simplest of all tests. Just set a file descriptor and see that it's available\n\/\/ repeat many times\nHRESULT CTestPolling::Test1()\n{\n HRESULT hr = S_OK;\n HRESULT hrResult;\n size_t size;\n PollEvent event; \n int fd;\n int count = 0;\n \n srand(100);\n\n ChkA(TestInit(10, 10));\n \n size = _pipes.size();\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED); \n \n \/\/ one event at a time model\n for (int index = 0; index < 100; index++)\n {\n\n size_t item = rand() % size;\n \n ChkA(WritePipe(&_pipes[item]));\n \n ConsumeEvent(&fd, &count);\n \n ChkIfA(fd != _pipes[item].readpipe, E_UNEXPECTED);\n ChkIfA(count != 1, E_UNEXPECTED);\n }\n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED);\n \nCleanup:\n return hr;\n}\n\n\n\n\/\/ create a polling set\nHRESULT CTestPolling::Test2()\n{\n \/\/ simulate the following events in random order:\n \/\/ socket added (did it succeed as expected)\n \/\/ incoming data (write to a random pipe)\n \/\/ WaitForNextEvent called (did it return an expected result\/socket)\n \/\/ Remove socket last notified about\n\n HRESULT hr = S_OK;\n HRESULT hrResult;\n PollEvent event; \n const size_t c_maxSockets = 10;\n \n srand(100);\n\n ChkA(TestInit(c_maxSockets, 0));\n \n \n hrResult = _spPolling->WaitForNextEvent(&event, 0);\n ChkIfA(hrResult != S_FALSE, E_UNEXPECTED); \n \n \n for (size_t index = 0; index < 1000; index++)\n {\n int randresult = ::rand() % 4;\n \n switch (randresult)\n {\n case 0:\n {\n \/\/ simulate a new socket being added\n if (_pipes.size() >= c_maxSockets)\n {\n continue;\n }\n \n ChkA(CreateAndAddPipe());\n\n break;\n }\n \n case 1:\n {\n \/\/ simulate incoming data\n size_t size = _pipes.size();\n size_t itemindex;\n \n if (size == 0)\n {\n continue;\n }\n \n itemindex = rand() % size;\n ChkA(WritePipe(&_pipes[itemindex]));\n \n break;\n }\n \n case 2:\n case 3:\n {\n int fd;\n size_t pending = GetPendingCount();\n if (pending == 0)\n {\n continue;\n }\n \n ChkA(ConsumeEvent(&fd, NULL));\n \n if (randresult == 3)\n {\n \/\/ simulate removing this pipe from the set\n ChkA(RemovePipe(FindPipePairIndex(fd)));\n }\n break;\n } \/\/ case\n } \/\/ switch\n } \/\/ for\n\nCleanup:\n return hr;\n}\n\nHRESULT CTestPolling::Test3()\n{\n HRESULT hr = S_OK;\n\n const size_t c_maxSockets = 10;\n \n ChkA(TestInit(c_maxSockets, 0));\n \n ChkA(_spPolling->Add(3, IPOLLING_READ));\n ChkA(_spPolling->Remove(3));\n ChkA(_spPolling->Add(5, IPOLLING_READ));\n ChkA(_spPolling->Add(7, IPOLLING_READ));\n ChkA(_spPolling->Add(9, IPOLLING_READ));\n ChkA(_spPolling->Remove(5));\n ChkA(_spPolling->Add(11, IPOLLING_READ));\n ChkA(_spPolling->Add(13, IPOLLING_READ));\n ChkA(_spPolling->Remove(7));\n ChkA(_spPolling->Add(15, IPOLLING_READ));\n ChkA(_spPolling->Add(17, IPOLLING_READ));\n ChkA(_spPolling->Add(19, IPOLLING_READ));\n ChkA(_spPolling->Remove(11));\n ChkA(_spPolling->Add(21, IPOLLING_READ));\n ChkA(_spPolling->Add(23, IPOLLING_READ));\n ChkA(_spPolling->Add(25, IPOLLING_READ));\n ChkA(_spPolling->Add(27, IPOLLING_READ));\n ChkA(_spPolling->Remove(13));\n \nCleanup:\n return hr;\n \n}\n\n\n<|endoftext|>"} {"text":"\n\/** RandomAtomGenerator.cc *\/\n\n#include \n\n#include \n#include \n#include \n\n#include \"RandomAtomGenerator.h\"\n\nnamespace opencog {\n\nRandomAtomGenerator::RandomAtomGenerator(AtomSpace* atomspace,\n unsigned long random_seed,\n float link_size_mean,\n Type default_node_type,\n float chance_of_non_default_node,\n Type default_link_type,\n float chance_of_non_default_link,\n float chance_of_default_tv)\n{\n _atomspace = atomspace;\n\n _default_node_type = default_node_type;\n _chance_of_non_default_node = chance_of_non_default_node;\n _default_link_type = default_link_type;\n _chance_of_non_default_link = chance_of_non_default_link;\n _link_size_mean = link_size_mean;\n\n _total_types = classserver().getNumberOfClasses();\n\n _counter = 0;\n _chance_of_default_tv = chance_of_default_tv;\n\n if (random_seed != USE_TIME_RANDOM_SEED)\n _random_seed = random_seed;\n else\n _random_seed = (unsigned long) time(NULL);\n\n \/\/ Create the random generator with the correct seed value.\n _random_generator = new MT19937RandGen(_random_seed);\n\n \/\/ Create the poisson distribution around the link mean.\n _poisson_distribution = new std::poisson_distribution(_link_size_mean);\n}\n\nRandomAtomGenerator::~RandomAtomGenerator()\n{\n delete _poisson_distribution;\n delete _random_generator;\n}\n\n\nType RandomAtomGenerator::random_type(Type parent_type)\n{\n OC_ASSERT(parent_type < _total_types);\n Type candidate_type;\n\n \/\/ Loop until we get a type that is a subclass of t, skipping TYPE_NODE\n \/\/ since that type can't handle randomly generated names. Also skip other\n \/\/ validated types since the validation will fail.\n do {\n candidate_type = ATOM + _random_generator->randint(_total_types - ATOM - 1);\n } while (!classserver().isA(candidate_type, parent_type) or\n classserver().isA(candidate_type, FREE_LINK) or\n classserver().isA(candidate_type, SCOPE_LINK) or\n candidate_type == VARIABLE_LIST or\n candidate_type == DEFINE_LINK or\n candidate_type == NUMBER_NODE or\n candidate_type == TYPE_NODE);\n\n return candidate_type;\n}\n\nvoid RandomAtomGenerator::set_truth_value(Handle& atom)\n{\n \/\/ Set the truth value to a non default using the chance threshold.\n if (_random_generator->randfloat() > _chance_of_default_tv) {\n float strength = _random_generator->randfloat();\n float confidence = _random_generator->randfloat();\n TruthValuePtr stv = SimpleTruthValue::createTV(strength, confidence);\n atom->setTruthValue(stv);\n }\n}\n\nType RandomAtomGenerator::get_node_type()\n{\n Type node_type;\n if (_random_generator->randfloat() < _chance_of_non_default_node)\n node_type = random_type(NODE);\n else\n node_type = _default_node_type;\n return node_type;\n}\n\nvoid RandomAtomGenerator::make_random_node()\n{\n \/\/ Get the node type (non-default based on random chance and threshold).\n Type node_type = get_node_type();\n\n \/\/ Generate the node name.\n _counter++;\n std::string node_name(\"node \"); \n node_name += std::to_string(_counter);\n\n \/\/ Add the node to the atomspace.\n Handle node = _atomspace->add_node(node_type, node_name);\n\n \/\/ Set the truth value (non-default based on random chance and threshold).\n set_truth_value(node);\n}\n\nType RandomAtomGenerator::get_link_type()\n{\n Type link_type;\n if (_random_generator->randfloat() < _chance_of_non_default_link)\n link_type = random_type(LINK);\n else\n link_type = _default_link_type;\n return link_type;\n}\n\nHandle RandomAtomGenerator::get_random_handle()\n{\n \/\/ _random_generator->randint(range);\n return Handle::UNDEFINED;\n}\n\nbool RandomAtomGenerator::sequence_contains(HandleSeq& sequence, Handle& target)\n{\n if (std::find(sequence.begin(), sequence.end(), target) != sequence.end())\n return true;\n else\n return false;\n}\n\nvoid RandomAtomGenerator::make_random_link()\n{\n Handle link = Handle::UNDEFINED;\n\n \/\/ Loop until we add a link in case we randomly create a duplicate which\n \/\/ will not create a new link and throw off our counts.\n int initial_atom_count = _atomspace->get_size();\n do {\n \/\/ Get the link type (non-default based on random chance and threshold).\n Type link_type = get_link_type();\n\n \/\/ Get the poisson-distributed outgoing arity.\n size_t arity = (*_poisson_distribution)(*_random_generator);\n if (arity == 0)\n arity = 1;\n\n \/\/ AtomSpace will throw if the context link has bad arity\n if (link_type == CONTEXT_LINK)\n arity = 2;\n\n \/\/ Generate the outgoing sequence.\n HandleSeq outgoing;\n for (size_t outgoing_count = 0; outgoing_count < arity; outgoing_count++) {\n\n \/\/ Get a new random handle.\n Handle candidate = get_random_handle();\n\n \/\/ Test to see if it is new for this outgoing sequence.\n while (sequence_contains(outgoing, candidate))\n candidate = get_random_handle();\n \n \/\/ Add this candidate to our outgoing sequence.\n outgoing.push_back(candidate);\n }\n\n \/\/ Add the link to the atomspace.\n link = _atomspace->add_link(link_type, outgoing);\n\n \/\/ Until we've actually added a link.\n } while (_atomspace->get_size() == initial_atom_count);\n\n \/\/ Set the truth value (non-default based on random chance and threshold).\n set_truth_value(link);\n}\n\nvoid RandomAtomGenerator::make_random_atoms(long total_atoms,\n float percent_links)\n{\n \/\/ Add the nodes.\n int total_nodes = total_atoms * (1.0f - percent_links);\n for (int node_count = 0; node_count < total_nodes; node_count++)\n make_random_node();\n\n \/\/ Add the links until we get to to our total.\n int total_links = total_atoms - total_nodes;\n for (int link_count = 0; link_count < total_links; link_count++)\n make_random_link();\n}\n\n} \/\/ namespace opencog\nFix compiler warning\n\/** RandomAtomGenerator.cc *\/\n\n#include \n\n#include \n#include \n#include \n\n#include \"RandomAtomGenerator.h\"\n\nnamespace opencog {\n\nRandomAtomGenerator::RandomAtomGenerator(AtomSpace* atomspace,\n unsigned long random_seed,\n float link_size_mean,\n Type default_node_type,\n float chance_of_non_default_node,\n Type default_link_type,\n float chance_of_non_default_link,\n float chance_of_default_tv)\n{\n _atomspace = atomspace;\n\n _default_node_type = default_node_type;\n _chance_of_non_default_node = chance_of_non_default_node;\n _default_link_type = default_link_type;\n _chance_of_non_default_link = chance_of_non_default_link;\n _link_size_mean = link_size_mean;\n\n _total_types = classserver().getNumberOfClasses();\n\n _counter = 0;\n _chance_of_default_tv = chance_of_default_tv;\n\n if (random_seed != USE_TIME_RANDOM_SEED)\n _random_seed = random_seed;\n else\n _random_seed = (unsigned long) time(NULL);\n\n \/\/ Create the random generator with the correct seed value.\n _random_generator = new MT19937RandGen(_random_seed);\n\n \/\/ Create the poisson distribution around the link mean.\n _poisson_distribution = new std::poisson_distribution(_link_size_mean);\n}\n\nRandomAtomGenerator::~RandomAtomGenerator()\n{\n delete _poisson_distribution;\n delete _random_generator;\n}\n\n\nType RandomAtomGenerator::random_type(Type parent_type)\n{\n OC_ASSERT(parent_type < _total_types);\n Type candidate_type;\n\n \/\/ Loop until we get a type that is a subclass of t, skipping TYPE_NODE\n \/\/ since that type can't handle randomly generated names. Also skip other\n \/\/ validated types since the validation will fail.\n do {\n candidate_type = ATOM + _random_generator->randint(_total_types - ATOM - 1);\n } while (!classserver().isA(candidate_type, parent_type) or\n classserver().isA(candidate_type, FREE_LINK) or\n classserver().isA(candidate_type, SCOPE_LINK) or\n candidate_type == VARIABLE_LIST or\n candidate_type == DEFINE_LINK or\n candidate_type == NUMBER_NODE or\n candidate_type == TYPE_NODE);\n\n return candidate_type;\n}\n\nvoid RandomAtomGenerator::set_truth_value(Handle& atom)\n{\n \/\/ Set the truth value to a non default using the chance threshold.\n if (_random_generator->randfloat() > _chance_of_default_tv) {\n float strength = _random_generator->randfloat();\n float confidence = _random_generator->randfloat();\n TruthValuePtr stv = SimpleTruthValue::createTV(strength, confidence);\n atom->setTruthValue(stv);\n }\n}\n\nType RandomAtomGenerator::get_node_type()\n{\n Type node_type;\n if (_random_generator->randfloat() < _chance_of_non_default_node)\n node_type = random_type(NODE);\n else\n node_type = _default_node_type;\n return node_type;\n}\n\nvoid RandomAtomGenerator::make_random_node()\n{\n \/\/ Get the node type (non-default based on random chance and threshold).\n Type node_type = get_node_type();\n\n \/\/ Generate the node name.\n _counter++;\n std::string node_name(\"node \"); \n node_name += std::to_string(_counter);\n\n \/\/ Add the node to the atomspace.\n Handle node = _atomspace->add_node(node_type, node_name);\n\n \/\/ Set the truth value (non-default based on random chance and threshold).\n set_truth_value(node);\n}\n\nType RandomAtomGenerator::get_link_type()\n{\n Type link_type;\n if (_random_generator->randfloat() < _chance_of_non_default_link)\n link_type = random_type(LINK);\n else\n link_type = _default_link_type;\n return link_type;\n}\n\nHandle RandomAtomGenerator::get_random_handle()\n{\n \/\/ _random_generator->randint(range);\n return Handle::UNDEFINED;\n}\n\nbool RandomAtomGenerator::sequence_contains(HandleSeq& sequence, Handle& target)\n{\n if (std::find(sequence.begin(), sequence.end(), target) != sequence.end())\n return true;\n else\n return false;\n}\n\nvoid RandomAtomGenerator::make_random_link()\n{\n Handle link = Handle::UNDEFINED;\n\n \/\/ Loop until we add a link in case we randomly create a duplicate which\n \/\/ will not create a new link and throw off our counts.\n size_t initial_atom_count = _atomspace->get_size();\n do {\n \/\/ Get the link type (non-default based on random chance and threshold).\n Type link_type = get_link_type();\n\n \/\/ Get the poisson-distributed outgoing arity.\n size_t arity = (*_poisson_distribution)(*_random_generator);\n if (arity == 0)\n arity = 1;\n\n \/\/ AtomSpace will throw if the context link has bad arity\n if (link_type == CONTEXT_LINK)\n arity = 2;\n\n \/\/ Generate the outgoing sequence.\n HandleSeq outgoing;\n for (size_t outgoing_count = 0; outgoing_count < arity; outgoing_count++) {\n\n \/\/ Get a new random handle.\n Handle candidate = get_random_handle();\n\n \/\/ Test to see if it is new for this outgoing sequence.\n while (sequence_contains(outgoing, candidate))\n candidate = get_random_handle();\n \n \/\/ Add this candidate to our outgoing sequence.\n outgoing.push_back(candidate);\n }\n\n \/\/ Add the link to the atomspace.\n link = _atomspace->add_link(link_type, outgoing);\n\n \/\/ Until we've actually added a link.\n } while (_atomspace->get_size() == initial_atom_count);\n\n \/\/ Set the truth value (non-default based on random chance and threshold).\n set_truth_value(link);\n}\n\nvoid RandomAtomGenerator::make_random_atoms(long total_atoms,\n float percent_links)\n{\n \/\/ Add the nodes.\n int total_nodes = total_atoms * (1.0f - percent_links);\n for (int node_count = 0; node_count < total_nodes; node_count++)\n make_random_node();\n\n \/\/ Add the links until we get to to our total.\n int total_links = total_atoms - total_nodes;\n for (int link_count = 0; link_count < total_links; link_count++)\n make_random_link();\n}\n\n} \/\/ namespace opencog\n<|endoftext|>"} {"text":"\/*\n* This file is part of ATLAS. It is subject to the license terms in\n* the LICENSE file found in the top-level directory of this distribution.\n* (Also avialable at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt)\n* You may not use this file except in compliance with the License.\n*\/\n#pragma once\n\n#include \"ColladaMassager.hpp\"\n#include \"ColladaMassagerRegistry.hpp\"\n#include \"..\/AssimpImporter.hpp\"\n#include \"..\/Importer.hpp\"\n#include \n#include \n#include \"..\/AiImporter\/AiSceneImporter.hpp\"\n\nnamespace AssimpWorker {\n\n\tclass ColladaRecursiveImporter :public Importer\n\t{\n\tpublic:\n\t\tColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory, ColladaMassagerRegistry& registry, float parentScale);\n\n\t\t~ColladaRecursiveImporter();\n\n\t\tvirtual void addElementsTo(ATLAS::Model::Folder& asset);\n\t\tconst float getLocalScale();\n\t\tconst std::string getColladaUpAxis();\n\t\t\n\tprivate:\n\t\tAssimpImporter* importer;\n\t\tstd::vector childImporter;\n\t\tPoco::URI pathToWorkingDirectory;\n\t\tconst Poco::URI& colladaFileURI;\n\t\tColladaMassagerRegistry& massagerRegistry;\n\t\tColladaMassager* massager;\n\t\tconst float parentScale;\n\n\t\tvoid preprocessCollada();\n\t\tconst aiScene* runAssimpImport();\n\t\tvoid convertToFolderStructure(const aiScene* scene, ATLAS::Model::Folder& root);\n\t\tvoid importChildColladas(ATLAS::Model::Folder& root);\n\n\t\tstd::string fixRelativeReference(std::string relativeURI);\n\t\tATLAS::Model::Folder& findFolderWithName(ATLAS::Model::Folder& root, std::string name);\n\t\taiNode* findaiNodeWithName(aiNode* node, const std::string& name);\n\t\tATLAS::Model::Folder& findFolderWithColladaID(ATLAS::Model::Folder& folder, std::string id);\n\t\tvoid restoreOriginalNames(aiNode* node);\n\t};\n\n} \/\/ End namespace AssimpWorker\n\n\nRemoves declaration of not implemented function\/*\n* This file is part of ATLAS. It is subject to the license terms in\n* the LICENSE file found in the top-level directory of this distribution.\n* (Also avialable at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt)\n* You may not use this file except in compliance with the License.\n*\/\n#pragma once\n\n#include \"ColladaMassager.hpp\"\n#include \"ColladaMassagerRegistry.hpp\"\n#include \"..\/AssimpImporter.hpp\"\n#include \"..\/Importer.hpp\"\n#include \n#include \n#include \"..\/AiImporter\/AiSceneImporter.hpp\"\n\nnamespace AssimpWorker {\n\n\tclass ColladaRecursiveImporter :public Importer\n\t{\n\tpublic:\n\t\tColladaRecursiveImporter(const Poco::URI& colladaFileURI, Log& log, Poco::URI pathToWorkingDirectory, ColladaMassagerRegistry& registry, float parentScale);\n\n\t\t~ColladaRecursiveImporter();\n\n\t\tvirtual void addElementsTo(ATLAS::Model::Folder& asset);\n\t\tconst float getLocalScale();\n\t\tconst std::string getColladaUpAxis();\n\t\t\n\tprivate:\n\t\tAssimpImporter* importer;\n\t\tstd::vector childImporter;\n\t\tPoco::URI pathToWorkingDirectory;\n\t\tconst Poco::URI& colladaFileURI;\n\t\tColladaMassagerRegistry& massagerRegistry;\n\t\tColladaMassager* massager;\n\t\tconst float parentScale;\n\n\t\tvoid preprocessCollada();\n\t\tconst aiScene* runAssimpImport();\n\t\tvoid convertToFolderStructure(const aiScene* scene, ATLAS::Model::Folder& root);\n\t\tvoid importChildColladas(ATLAS::Model::Folder& root);\n\n\t\tstd::string fixRelativeReference(std::string relativeURI);\n\t\tATLAS::Model::Folder& findFolderWithName(ATLAS::Model::Folder& root, std::string name);\n\t\taiNode* findaiNodeWithName(aiNode* node, const std::string& name);\n\t\tATLAS::Model::Folder& findFolderWithColladaID(ATLAS::Model::Folder& folder, std::string id);\n\t};\n\n} \/\/ End namespace AssimpWorker\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"utils\/macro.h\"\n#include \"application_manager\/mobile_message_handler.h\"\n#include \"protocol_handler\/protocol_payload.h\"\n#include \"protocol_handler\/protocol_packet.h\"\n#include \"utils\/bitstream.h\"\n#include \"utils\/logger.h\"\n\n#include \n#include \n#include \n\nnamespace {\nconst uint8_t kRequest = 0x0;\nconst uint8_t kResponse = 0x1;\nconst uint8_t kNotification = 0x2;\nconst uint8_t kUnknown = 0xF;\n}\n\nnamespace application_manager {\nusing protocol_handler::Extract;\n\nnamespace {\ntypedef std::map MessageTypeMap;\nMessageTypeMap message_types = {std::make_pair(kRequest, \"Request\"),\n std::make_pair(kResponse, \"Response\"),\n std::make_pair(kNotification, \"Notification\")};\n}\nCREATE_LOGGERPTR_GLOBAL(logger_, \"ApplicationManager\")\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocol(\n const protocol_handler::RawMessagePtr message) {\n DCHECK_OR_RETURN(message, NULL);\n application_manager::Message* out_message = NULL;\n switch (message->protocol_version()) {\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V1\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV1(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V2\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_3:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V3\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_4:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V4\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_5:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V5\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n default:\n LOG4CXX_WARN(logger_, \"Can't recognise protocol version\");\n out_message = NULL;\n break;\n }\n if (out_message == NULL) {\n LOG4CXX_WARN(logger_, \"Message is NULL\");\n return NULL;\n }\n LOG4CXX_DEBUG(logger_,\n \"Incoming RPC_INFO: \" << (out_message->connection_key() >> 16)\n << \", \"\n << message_types[out_message->type()]\n << \", \" << out_message->function_id()\n << \", \" << out_message->correlation_id()\n << \", \" << out_message->json_message());\n return out_message;\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocol(\n const MobileMessage& message) {\n LOG4CXX_DEBUG(logger_,\n \"Outgoing RPC_INFO: \" << (message->connection_key() >> 16)\n << \", \" << message_types[message->type()]\n << \", \" << message->function_id() << \", \"\n << message->correlation_id() << \", \"\n << message->json_message());\n\n if (message->protocol_version() ==\n protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1) {\n return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);\n }\n if (Message::is_sufficient_version(\n protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2,\n message->protocol_version())) {\n return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);\n }\n return NULL;\n}\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocolV1(\n const ::protocol_handler::RawMessagePtr message) {\n LOG4CXX_AUTO_TRACE(logger_);\n application_manager::Message* outgoing_message =\n new application_manager::Message(\n protocol_handler::MessagePriority::FromServiceType(\n message->service_type()));\n if (!message) {\n NOTREACHED();\n return NULL;\n }\n\n outgoing_message->set_connection_key(message->connection_key());\n outgoing_message->set_protocol_version(\n static_cast(\n message->protocol_version()));\n outgoing_message->set_json_message(std::string(\n reinterpret_cast(message->data()), message->data_size()));\n\n if (outgoing_message->json_message().empty()) {\n delete outgoing_message;\n return NULL;\n }\n\n return outgoing_message;\n}\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocolV2(\n const ::protocol_handler::RawMessagePtr message) {\n LOG4CXX_AUTO_TRACE(logger_);\n utils::BitStream message_bytestream(message->data(), message->data_size());\n protocol_handler::ProtocolPayloadV2 payload;\n protocol_handler::Extract(\n &message_bytestream, &payload, message->data_size());\n\n \/\/ Silently drop message if it wasn't parsed correctly\n if (message_bytestream.IsBad()) {\n LOG4CXX_WARN(\n logger_,\n \"Drop ill-formed message from mobile, partially parsed: \" << payload);\n return NULL;\n }\n\n std::auto_ptr outgoing_message(\n new application_manager::Message(\n protocol_handler::MessagePriority::FromServiceType(\n message->service_type())));\n\n outgoing_message->set_json_message(payload.json);\n outgoing_message->set_function_id(payload.header.rpc_function_id);\n outgoing_message->set_message_type(\n MessageTypeFromRpcType(payload.header.rpc_type));\n outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));\n outgoing_message->set_connection_key(message->connection_key());\n outgoing_message->set_protocol_version(\n static_cast(\n message->protocol_version()));\n outgoing_message->set_data_size(message->data_size());\n outgoing_message->set_payload_size(message->payload_size());\n\n if (!payload.data.empty()) {\n const BinaryData binary_payload_data(payload.data);\n outgoing_message->set_binary_data(&binary_payload_data);\n }\n return outgoing_message.release();\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocolV1(\n const MobileMessage& message) {\n LOG4CXX_AUTO_TRACE(logger_);\n std::string message_string = message->json_message();\n if (message_string.length() == 0) {\n LOG4CXX_WARN(logger_, \"Drop ill-formed message from mobile\");\n return NULL;\n }\n\n BinaryData raw_message(message_string.length() + 1);\n memcpy(&raw_message[0], message_string.c_str(), message_string.length() + 1);\n\n protocol_handler::RawMessage* result =\n new protocol_handler::RawMessage(message->connection_key(),\n 1,\n &raw_message[0],\n message_string.length() + 1);\n\n return result;\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocolV2(\n const MobileMessage& message) {\n LOG4CXX_AUTO_TRACE(logger_);\n if (message->json_message().length() == 0) {\n LOG4CXX_ERROR(logger_, \"json string is empty.\");\n }\n uint32_t json_size = message->json_message().length();\n uint32_t binary_size = 0;\n if (message->has_binary_data()) {\n binary_size = message->binary_data()->size();\n }\n\n const size_t data_for_sending_size =\n protocol_handler::PROTOCOL_HEADER_V2_SIZE + json_size + binary_size;\n BinaryData data_for_sending(data_for_sending_size);\n uint8_t offset = 0;\n\n uint8_t rpc_type_flag = 0;\n switch (message->type()) {\n case application_manager::kRequest:\n rpc_type_flag = kRequest;\n break;\n case application_manager::kResponse:\n rpc_type_flag = kResponse;\n break;\n case application_manager::kNotification:\n rpc_type_flag = kNotification;\n break;\n default:\n NOTREACHED();\n break;\n }\n\n uint32_t function_id = message->function_id();\n data_for_sending[offset++] =\n ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);\n data_for_sending[offset++] = function_id >> 16;\n data_for_sending[offset++] = function_id >> 8;\n data_for_sending[offset++] = function_id;\n\n uint32_t correlation_id = message->correlation_id();\n data_for_sending[offset++] = correlation_id >> 24;\n data_for_sending[offset++] = correlation_id >> 16;\n data_for_sending[offset++] = correlation_id >> 8;\n data_for_sending[offset++] = correlation_id;\n\n data_for_sending[offset++] = json_size >> 24;\n data_for_sending[offset++] = json_size >> 16;\n data_for_sending[offset++] = json_size >> 8;\n data_for_sending[offset++] = json_size;\n\n memcpy(&data_for_sending[offset], message->json_message().c_str(), json_size);\n\n \/\/ Default the service type to RPC Service\n uint8_t type = 0x07;\n\n if (message->has_binary_data()) {\n \/\/ Change the service type to Hybrid Service\n type = 0x0F;\n const BinaryData& binary_data = *(message->binary_data());\n BinaryData::value_type* current_pointer =\n &data_for_sending[offset + json_size];\n for (uint32_t i = 0; i < binary_size; ++i) {\n current_pointer[i] = binary_data[i];\n }\n }\n\n protocol_handler::RawMessage* msg_to_protocol_handler =\n new protocol_handler::RawMessage(message->connection_key(),\n message->protocol_version(),\n &data_for_sending[0],\n data_for_sending_size,\n type);\n\n return msg_to_protocol_handler;\n}\n} \/\/ namespace application_manager\nfix: remove memory leak warning from cppcheck\/*\n * Copyright (c) 2014, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"utils\/macro.h\"\n#include \"application_manager\/mobile_message_handler.h\"\n#include \"protocol_handler\/protocol_payload.h\"\n#include \"protocol_handler\/protocol_packet.h\"\n#include \"utils\/bitstream.h\"\n#include \"utils\/logger.h\"\n\n#include \n#include \n#include \n\nnamespace {\nconst uint8_t kRequest = 0x0;\nconst uint8_t kResponse = 0x1;\nconst uint8_t kNotification = 0x2;\nconst uint8_t kUnknown = 0xF;\n}\n\nnamespace application_manager {\nusing protocol_handler::Extract;\n\nnamespace {\ntypedef std::map MessageTypeMap;\nMessageTypeMap message_types = {std::make_pair(kRequest, \"Request\"),\n std::make_pair(kResponse, \"Response\"),\n std::make_pair(kNotification, \"Notification\")};\n}\nCREATE_LOGGERPTR_GLOBAL(logger_, \"ApplicationManager\")\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocol(\n const protocol_handler::RawMessagePtr message) {\n DCHECK_OR_RETURN(message, NULL);\n application_manager::Message* out_message = NULL;\n switch (message->protocol_version()) {\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V1\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV1(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V2\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_3:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V3\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_4:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V4\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n case protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_5:\n LOG4CXX_DEBUG(logger_, \"Protocol version - V5\");\n out_message =\n MobileMessageHandler::HandleIncomingMessageProtocolV2(message);\n break;\n default:\n LOG4CXX_WARN(logger_, \"Can't recognise protocol version\");\n out_message = NULL;\n break;\n }\n if (out_message == NULL) {\n LOG4CXX_WARN(logger_, \"Message is NULL\");\n return NULL;\n }\n LOG4CXX_DEBUG(logger_,\n \"Incoming RPC_INFO: \" << (out_message->connection_key() >> 16)\n << \", \"\n << message_types[out_message->type()]\n << \", \" << out_message->function_id()\n << \", \" << out_message->correlation_id()\n << \", \" << out_message->json_message());\n return out_message;\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocol(\n const MobileMessage& message) {\n LOG4CXX_DEBUG(logger_,\n \"Outgoing RPC_INFO: \" << (message->connection_key() >> 16)\n << \", \" << message_types[message->type()]\n << \", \" << message->function_id() << \", \"\n << message->correlation_id() << \", \"\n << message->json_message());\n\n if (message->protocol_version() ==\n protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_1) {\n return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);\n }\n if (Message::is_sufficient_version(\n protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_2,\n message->protocol_version())) {\n return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);\n }\n return NULL;\n}\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocolV1(\n const ::protocol_handler::RawMessagePtr message) {\n LOG4CXX_AUTO_TRACE(logger_);\n application_manager::Message* outgoing_message =\n new application_manager::Message(\n protocol_handler::MessagePriority::FromServiceType(\n message->service_type()));\n if (!message) {\n NOTREACHED();\n delete outgoing_message;\n return NULL;\n }\n\n outgoing_message->set_connection_key(message->connection_key());\n outgoing_message->set_protocol_version(\n static_cast(\n message->protocol_version()));\n outgoing_message->set_json_message(std::string(\n reinterpret_cast(message->data()), message->data_size()));\n\n if (outgoing_message->json_message().empty()) {\n delete outgoing_message;\n return NULL;\n }\n\n return outgoing_message;\n}\n\napplication_manager::Message*\nMobileMessageHandler::HandleIncomingMessageProtocolV2(\n const ::protocol_handler::RawMessagePtr message) {\n LOG4CXX_AUTO_TRACE(logger_);\n utils::BitStream message_bytestream(message->data(), message->data_size());\n protocol_handler::ProtocolPayloadV2 payload;\n protocol_handler::Extract(\n &message_bytestream, &payload, message->data_size());\n\n \/\/ Silently drop message if it wasn't parsed correctly\n if (message_bytestream.IsBad()) {\n LOG4CXX_WARN(\n logger_,\n \"Drop ill-formed message from mobile, partially parsed: \" << payload);\n return NULL;\n }\n\n std::auto_ptr outgoing_message(\n new application_manager::Message(\n protocol_handler::MessagePriority::FromServiceType(\n message->service_type())));\n\n outgoing_message->set_json_message(payload.json);\n outgoing_message->set_function_id(payload.header.rpc_function_id);\n outgoing_message->set_message_type(\n MessageTypeFromRpcType(payload.header.rpc_type));\n outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));\n outgoing_message->set_connection_key(message->connection_key());\n outgoing_message->set_protocol_version(\n static_cast(\n message->protocol_version()));\n outgoing_message->set_data_size(message->data_size());\n outgoing_message->set_payload_size(message->payload_size());\n\n if (!payload.data.empty()) {\n const BinaryData binary_payload_data(payload.data);\n outgoing_message->set_binary_data(&binary_payload_data);\n }\n return outgoing_message.release();\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocolV1(\n const MobileMessage& message) {\n LOG4CXX_AUTO_TRACE(logger_);\n std::string message_string = message->json_message();\n if (message_string.length() == 0) {\n LOG4CXX_WARN(logger_, \"Drop ill-formed message from mobile\");\n return NULL;\n }\n\n BinaryData raw_message(message_string.length() + 1);\n memcpy(&raw_message[0], message_string.c_str(), message_string.length() + 1);\n\n protocol_handler::RawMessage* result =\n new protocol_handler::RawMessage(message->connection_key(),\n 1,\n &raw_message[0],\n message_string.length() + 1);\n\n return result;\n}\n\nprotocol_handler::RawMessage*\nMobileMessageHandler::HandleOutgoingMessageProtocolV2(\n const MobileMessage& message) {\n LOG4CXX_AUTO_TRACE(logger_);\n if (message->json_message().length() == 0) {\n LOG4CXX_ERROR(logger_, \"json string is empty.\");\n }\n uint32_t json_size = message->json_message().length();\n uint32_t binary_size = 0;\n if (message->has_binary_data()) {\n binary_size = message->binary_data()->size();\n }\n\n const size_t data_for_sending_size =\n protocol_handler::PROTOCOL_HEADER_V2_SIZE + json_size + binary_size;\n BinaryData data_for_sending(data_for_sending_size);\n uint8_t offset = 0;\n\n uint8_t rpc_type_flag = 0;\n switch (message->type()) {\n case application_manager::kRequest:\n rpc_type_flag = kRequest;\n break;\n case application_manager::kResponse:\n rpc_type_flag = kResponse;\n break;\n case application_manager::kNotification:\n rpc_type_flag = kNotification;\n break;\n default:\n NOTREACHED();\n break;\n }\n\n uint32_t function_id = message->function_id();\n data_for_sending[offset++] =\n ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);\n data_for_sending[offset++] = function_id >> 16;\n data_for_sending[offset++] = function_id >> 8;\n data_for_sending[offset++] = function_id;\n\n uint32_t correlation_id = message->correlation_id();\n data_for_sending[offset++] = correlation_id >> 24;\n data_for_sending[offset++] = correlation_id >> 16;\n data_for_sending[offset++] = correlation_id >> 8;\n data_for_sending[offset++] = correlation_id;\n\n data_for_sending[offset++] = json_size >> 24;\n data_for_sending[offset++] = json_size >> 16;\n data_for_sending[offset++] = json_size >> 8;\n data_for_sending[offset++] = json_size;\n\n memcpy(&data_for_sending[offset], message->json_message().c_str(), json_size);\n\n \/\/ Default the service type to RPC Service\n uint8_t type = 0x07;\n\n if (message->has_binary_data()) {\n \/\/ Change the service type to Hybrid Service\n type = 0x0F;\n const BinaryData& binary_data = *(message->binary_data());\n BinaryData::value_type* current_pointer =\n &data_for_sending[offset + json_size];\n for (uint32_t i = 0; i < binary_size; ++i) {\n current_pointer[i] = binary_data[i];\n }\n }\n\n protocol_handler::RawMessage* msg_to_protocol_handler =\n new protocol_handler::RawMessage(message->connection_key(),\n message->protocol_version(),\n &data_for_sending[0],\n data_for_sending_size,\n type);\n\n return msg_to_protocol_handler;\n}\n} \/\/ namespace application_manager\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_sgpe.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/\/ *INDENT-OFF*\n\n\n\/\/\/\n\/\/\/ @file p9_pm_recovery_ffdc_sgpe.C\n\/\/\/ @brief Models SGPE platform for the FFDC collection of PM complex\n\/\/\/\n\/\/\/ *HWP HWP Owner: Greg Still \n\/\/\/ *HWP FW Owner: Prem S Jha \n\/\/\/ *HWP Team: PM\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot\n\/\/\n\/\/ *INDENT-OFF*\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n\n namespace p9_stop_recov_ffdc\n {\n PlatSgpe::PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )\n : PlatPmComplex( i_procChipTgt,\n PLAT_SGPE,\n OCC_SRAM_SGPE_HEADER_ADDR,\n OCC_SRAM_SGPE_TRACE_START,\n OCC_SRAM_SGPE_DASHBOARD_START )\n { }\n\n\/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::init ( void* i_pHomerBuf )\n {\n FAPI_DBG (\">> PlatSgpe::init\" );\n FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),\n \"Failed To init SGPE FFDC\" );\n\n fapi_try_exit:\n FAPI_DBG (\"<< PlatSgpe::init\" );\n return fapi2::current_err;\n }\n\n \/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectFfdc( void * i_pHomerBuf,\n uint8_t i_ffdcType )\n {\n FAPI_DBG(\">> PlatSgpe::collectFfdc\");\n\n fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;\n\n HomerFfdcRegion * l_pHomerFfdc =\n ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );\n\n uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_sgpeFfdcRegion);\n PpeFfdcHeader* l_pSgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;\n\n uint16_t l_ffdcValdityVect = l_pSgpeFfdcHdr->iv_sectionsValid;\n\n if ( i_ffdcType & INIT )\n { \/\/ overwrite on init\n l_ffdcValdityVect = PPE_FFDC_INVALID;\n }\n\n \/\/In case of error , invalidate FFDC in header.\n if ( i_ffdcType & PPE_HALT_STATE )\n {\n l_ffdcValdityVect |= PPE_HALT_STATE_VALID;\n l_retCode = readPpeHaltState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting SGPE Halt State\" );\n l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;\n }\n }\n\n if ( i_ffdcType & PPE_STATE )\n {\n l_ffdcValdityVect |= PPE_STATE_VALID;\n l_retCode = collectPpeState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting SGPE State\" );\n \/\/ PPE State Data is bad & continue SRAM FFDC collection\n l_ffdcValdityVect &= ~PPE_STATE_VALID;\n }\n }\n\n if ( i_ffdcType & TRACES )\n {\n l_ffdcValdityVect |= PPE_TRACE_VALID;\n l_retCode = collectTrace( l_pFfdcLoc );\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Trace \" );\n l_ffdcValdityVect &= ~PPE_TRACE_VALID;\n }\n }\n\n if ( i_ffdcType & DASH_BOARD_VAR )\n {\n l_ffdcValdityVect |= PPE_DASHBOARD_VALID;\n l_retCode = collectGlobals( l_pFfdcLoc );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Globals\" );\n l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;\n }\n }\n\n if ( i_ffdcType & IMAGE_HEADER )\n {\n l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;\n l_retCode = collectImageHeader( l_pFfdcLoc );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Image header\" );\n l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;\n }\n }\n\n FAPI_TRY( updateSgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect),\n \"Failed To Update SGPE FFDC Header for SGPE \" );\n\n if (l_ffdcValdityVect == PPE_FFDC_INVALID)\n setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID, false );\n else\n setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectFfdc: 0x%02X\", l_ffdcValdityVect);\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectTrace( uint8_t * i_pTraceBuf )\n {\n FAPI_DBG(\">> PlatSgpe::collectTrace\" );\n PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );\n\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeTraces[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n TRACES,\n FFDC_PPE_TRACES_SIZE ),\n \"Trace Collection Failed\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectTrace\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectGlobals( uint8_t * i_pSgpeGlobals )\n {\n FAPI_DBG(\">> PlatSgpe::collectGlobals\" );\n PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeGlobals );\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeGlobals[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n DASH_BOARD_VAR,\n OCC_SRAM_SGPE_DASHBOARD_SIZE ),\n \"Failed To Collect SGPE Global Variables\" );\n\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectGlobals\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectInternalReg( uint8_t * i_pSgpeIntReg )\n {\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectImageHeader( uint8_t * i_pSgpeImgHdr )\n {\n FAPI_DBG(\">> PlatSgpe::collectImageHeader\" );\n PpeFfdcLayout *l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeImgHdr );\n\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeImageHeader[0];\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n IMAGE_HEADER,\n FFDC_PPE_IMG_HDR_SIZE ),\n \"Failed To Collect SGPE Image Header\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectImageHeader\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::updateSgpeFfdcHeader( uint8_t* i_pHomerBuf,\n uint16_t i_sectionsValid )\n {\n FAPI_DBG(\">> updateSgpeFfdcHeader\" );\n\n PpeFfdcHeader * l_pSgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));\n l_pSgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_SGPE_MAGIC_NUM );\n l_pSgpeFfdcHdr->iv_ppeNumber = 0;\n PlatPmComplex::updatePpeFfdcHeader( l_pSgpeFfdcHdr, i_sectionsValid );\n\n FAPI_DBG(\"<< updateSgpeFfdcHeader\" );\n return fapi2::FAPI2_RC_SUCCESS;\n }\n \/\/-----------------------------------------------------------------------\n\nextern \"C\"\n{\n fapi2::ReturnCode p9_pm_recovery_ffdc_sgpe( const fapi2::Target& i_procChip,\n void * i_pFfdcBuf )\n {\n FAPI_IMP(\">> p9_pm_recovery_sgpe\" );\n\n PlatSgpe l_sgpeFfdc( i_procChip );\n FAPI_TRY( l_sgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),\n \"Failed To Collect SGPE FFDC\" );\n\n fapi_try_exit:\n FAPI_IMP(\"<< p9_pm_recovery_sgpe\" );\n return fapi2::current_err;\n }\n\n}\n\n\n}\/\/namespace p9_stop_recov_ffdc ends\nIdle Stop State: Adds CME and SGPE global variables to FFDC.\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_sgpe.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/\/ *INDENT-OFF*\n\n\n\/\/\/\n\/\/\/ @file p9_pm_recovery_ffdc_sgpe.C\n\/\/\/ @brief Models SGPE platform for the FFDC collection of PM complex\n\/\/\/\n\/\/\/ *HWP HWP Owner: Greg Still \n\/\/\/ *HWP FW Owner: Prem S Jha \n\/\/\/ *HWP Team: PM\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot\n\/\/\n\/\/ *INDENT-OFF*\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n\n namespace p9_stop_recov_ffdc\n {\n PlatSgpe::PlatSgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )\n : PlatPmComplex( i_procChipTgt,\n PLAT_SGPE,\n OCC_SRAM_SGPE_HEADER_ADDR,\n OCC_SRAM_SGPE_TRACE_START,\n OCC_SRAM_SGPE_DASHBOARD_START )\n { }\n\n\/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::init ( void* i_pHomerBuf )\n {\n FAPI_DBG (\">> PlatSgpe::init\" );\n FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT),\n \"Failed To init SGPE FFDC\" );\n\n fapi_try_exit:\n FAPI_DBG (\"<< PlatSgpe::init\" );\n return fapi2::current_err;\n }\n\n \/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectFfdc( void * i_pHomerBuf,\n uint8_t i_ffdcType )\n {\n FAPI_DBG(\">> PlatSgpe::collectFfdc\");\n\n fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;\n\n HomerFfdcRegion * l_pHomerFfdc =\n ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );\n\n uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_sgpeFfdcRegion);\n PpeFfdcHeader* l_pSgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc;\n\n uint16_t l_ffdcValdityVect = l_pSgpeFfdcHdr->iv_sectionsValid;\n\n if ( i_ffdcType & INIT )\n { \/\/ overwrite on init\n l_ffdcValdityVect = PPE_FFDC_INVALID;\n }\n\n \/\/In case of error , invalidate FFDC in header.\n if ( i_ffdcType & PPE_HALT_STATE )\n {\n l_ffdcValdityVect |= PPE_HALT_STATE_VALID;\n l_retCode = readPpeHaltState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting SGPE Halt State\" );\n l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID;\n }\n }\n\n if ( i_ffdcType & PPE_STATE )\n {\n l_ffdcValdityVect |= PPE_STATE_VALID;\n l_retCode = collectPpeState ( SGPE_BASE_ADDRESS, l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting SGPE State\" );\n \/\/ PPE State Data is bad & continue SRAM FFDC collection\n l_ffdcValdityVect &= ~PPE_STATE_VALID;\n }\n }\n\n if ( i_ffdcType & TRACES )\n {\n l_ffdcValdityVect |= PPE_TRACE_VALID;\n l_retCode = collectTrace( l_pFfdcLoc );\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Trace \" );\n l_ffdcValdityVect &= ~PPE_TRACE_VALID;\n }\n }\n\n if ( i_ffdcType & DASH_BOARD_VAR )\n {\n l_ffdcValdityVect |= PPE_DASHBOARD_VALID;\n l_retCode = collectGlobals( l_pFfdcLoc );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Globals\" );\n l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;\n }\n }\n\n if ( i_ffdcType & IMAGE_HEADER )\n {\n l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID;\n l_retCode = collectImageHeader( l_pFfdcLoc );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting SGPE Image header\" );\n l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;\n }\n }\n\n FAPI_TRY( updateSgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect),\n \"Failed To Update SGPE FFDC Header for SGPE \" );\n\n if (l_ffdcValdityVect == PPE_FFDC_INVALID)\n setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID, false );\n else\n setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_SGPE_VALID );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectFfdc: 0x%02X\", l_ffdcValdityVect);\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectPartialFfdc( void * i_pBuf, FfdcDataType i_dataType,\n uint32_t & o_ffdcLength )\n {\n FAPI_DBG(\">> PlatSgpe::collectPartialFfdc\");\n fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;\n uint32_t l_maxSize = o_ffdcLength;\n FAPI_DBG(\"Max buf size %d\", o_ffdcLength );\n\n switch( i_dataType )\n {\n case IMAGE_HEADER:\n o_ffdcLength = FFDC_PPE_IMG_HDR_SIZE;\n break;\n case DASH_BOARD_VAR:\n o_ffdcLength = OCC_SRAM_SGPE_DASHBOARD_SIZE;\n break;\n case TRACES:\n o_ffdcLength = FFDC_PPE_TRACES_SIZE;\n break;\n default:\n FAPI_ERR(\"Bad FFDC Data type. Skipping 0x%d\", (uint32_t)i_dataType );\n goto fapi_try_exit;\n break;\n }\n\n if( !i_pBuf )\n {\n FAPI_ERR(\"Bad Buffer Ptr\" );\n goto fapi_try_exit;\n }\n\n if( o_ffdcLength > l_maxSize )\n {\n o_ffdcLength = l_maxSize;\n }\n\n FAPI_TRY( PlatPmComplex::collectSramInfo( PlatPmComplex::getProcChip(),\n (uint8_t*)i_pBuf,\n i_dataType,\n o_ffdcLength ),\n \"Failed To Collect SGPE SRAM FFDC\" );\n\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectPartialFfdc\");\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectTrace( uint8_t * i_pTraceBuf )\n {\n FAPI_DBG(\">> PlatSgpe::collectTrace\" );\n PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );\n\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeTraces[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n TRACES,\n FFDC_PPE_TRACES_SIZE ),\n \"Trace Collection Failed\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectTrace\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectGlobals( uint8_t * i_pSgpeGlobals )\n {\n FAPI_DBG(\">> PlatSgpe::collectGlobals\" );\n\n PpeFfdcLayout * l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeGlobals );\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeGlobals[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n DASH_BOARD_VAR,\n OCC_SRAM_SGPE_DASHBOARD_SIZE ),\n \"Failed To Collect SGPE Global Variables\" );\n\n\n fapi_try_exit:\n\n FAPI_DBG(\"<< PlatSgpe::collectGlobals\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectInternalReg( uint8_t * i_pSgpeIntReg )\n {\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::collectImageHeader( uint8_t * i_pSgpeImgHdr )\n {\n FAPI_DBG(\">> PlatSgpe::collectImageHeader\" );\n PpeFfdcLayout *l_pSgpeFfdc = ( PpeFfdcLayout *) ( i_pSgpeImgHdr );\n\n uint8_t * l_pTraceLoc = &l_pSgpeFfdc->iv_ppeImageHeader[0];\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( PlatPmComplex::getProcChip(),\n l_pTraceLoc,\n IMAGE_HEADER,\n FFDC_PPE_IMG_HDR_SIZE ),\n \"Failed To Collect SGPE Image Header\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatSgpe::collectImageHeader\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatSgpe::updateSgpeFfdcHeader( uint8_t* i_pHomerBuf,\n uint16_t i_sectionsValid )\n {\n FAPI_DBG(\">> updateSgpeFfdcHeader\" );\n\n PpeFfdcHeader * l_pSgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));\n l_pSgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_SGPE_MAGIC_NUM );\n l_pSgpeFfdcHdr->iv_ppeNumber = 0;\n PlatPmComplex::updatePpeFfdcHeader( l_pSgpeFfdcHdr, i_sectionsValid );\n\n FAPI_DBG(\"<< updateSgpeFfdcHeader\" );\n return fapi2::FAPI2_RC_SUCCESS;\n }\n \/\/-----------------------------------------------------------------------\n\nextern \"C\"\n{\n fapi2::ReturnCode p9_pm_recovery_ffdc_sgpe( const fapi2::Target& i_procChip,\n void * i_pFfdcBuf )\n {\n FAPI_IMP(\">> p9_pm_recovery_sgpe\" );\n\n PlatSgpe l_sgpeFfdc( i_procChip );\n FAPI_TRY( l_sgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ),\n \"Failed To Collect SGPE FFDC\" );\n\n fapi_try_exit:\n FAPI_IMP(\"<< p9_pm_recovery_sgpe\" );\n return fapi2::current_err;\n }\n\n}\n\n\n}\/\/namespace p9_stop_recov_ffdc ends\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: ZipPackageEntry.cxx,v $\n *\n * $Revision: 1.24 $\n *\n * last change: $Author: kz $ $Date: 2003-09-11 10:17:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): 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}\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}\n\nvoid ZipPackageEntry::doSetParent ( ZipPackageFolder * pNewParent, sal_Bool bInsert )\n{\n xParent = 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 mav09 (1.24.50); FILE MERGED 2004\/08\/06 09:56:51 mav 1.24.50.1: #i29833# reimplement folders and streams life dependencies\/*************************************************************************\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}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Packet;\n\nint main(int argc, char* argv[]) {\n int framePeriod = 1000000 \/ 60;\n\n QString logFile;\n\n \/\/ Determine log file name\n if (argc == 2) {\n logFile = argv[1];\n }\n\n if (logFile.isNull()) {\n if (!QDir(\"logs\").exists()) {\n printf(\"No logs directory and no log file specified\\n\");\n return 1;\n }\n\n logFile = QString(\"logs\/\") +\n QDateTime::currentDateTime().toString(\"yyyyMMdd-hhmmss.log\");\n }\n\n \/\/ Create vision socket\n QUdpSocket visionSocket;\n if (!visionSocket.bind(SharedVisionPortDoubleNew,\n QUdpSocket::ShareAddress)) {\n printf(\"Can't bind to shared vision port\");\n return 1;\n }\n multicast_add(&visionSocket, SharedVisionAddress);\n\n \/\/ Create referee socket\n QUdpSocket refereeSocket;\n if (!refereeSocket.bind(LegacyRefereePort, QUdpSocket::ShareAddress)) {\n printf(\"Can't bind to referee port\");\n return 1;\n }\n multicast_add(&refereeSocket, RefereeAddress);\n\n \/\/ Create log file\n int fd = creat(logFile.toLatin1(), 0666);\n if (fd < 0) {\n printf(\"Can't create %s: %m\\n\", (const char*)logFile.toLatin1());\n return 1;\n }\n\n printf(\"Writing to %s\\n\", (const char*)logFile.toLatin1());\n\n \/\/ Main loop\n LogFrame logFrame;\n bool first = true;\n while (true) {\n RJ::Time startTime = RJ::timestamp();\n\n logFrame.Clear();\n logFrame.set_command_time(startTime);\n logFrame.set_timestamp(startTime);\n\n \/\/ Check for user input (to exit)\n struct pollfd pfd;\n pfd.fd = 0;\n pfd.events = POLLIN;\n if (poll(&pfd, 1, 0) > 0) {\n \/\/ Enter pressed\n break;\n }\n\n \/\/ Read vision data\n while (visionSocket.hasPendingDatagrams()) {\n string buf;\n unsigned int n = visionSocket.pendingDatagramSize();\n buf.resize(n);\n visionSocket.readDatagram(&buf[0], n);\n\n SSL_WrapperPacket* packet = logFrame.add_raw_vision();\n if (!packet->ParseFromString(buf)) {\n printf(\"Bad vision packet of %d bytes\\n\", n);\n continue;\n }\n }\n\n \/\/ Read referee data\n while (refereeSocket.hasPendingDatagrams()) {\n unsigned int n = refereeSocket.pendingDatagramSize();\n string str(6, 0);\n refereeSocket.readDatagram(&str[0], str.size());\n\n \/\/ Check the size after receiving to discard bad packets\n if (n != str.size()) {\n printf(\"Bad referee packet of %d bytes\\n\", n);\n continue;\n }\n\n logFrame.add_raw_referee(str);\n }\n\n if (first) {\n first = false;\n\n LogConfig* logConfig = logFrame.mutable_log_config();\n logConfig->set_generator(\"simple_logger\");\n logConfig->set_git_version_hash(git_version_hash);\n logConfig->set_git_version_dirty(git_version_dirty);\n }\n\n uint32_t size = logFrame.ByteSize();\n if (write(fd, &size, sizeof(size)) != sizeof(size)) {\n printf(\"Failed to write size: %m\\n\");\n break;\n } else if (!logFrame.SerializeToFileDescriptor(fd)) {\n printf(\"Failed to write frame: %m\\n\");\n break;\n }\n\n RJ::Time endTime = RJ::timestamp();\n int lastFrameTime = endTime - startTime;\n if (lastFrameTime < framePeriod) {\n usleep(framePeriod - lastFrameTime);\n } else {\n printf(\"Processor took too long: %d us\\n\", lastFrameTime);\n }\n }\n\n \/\/ Discard input on stdin\n tcflush(0, TCIFLUSH);\n\n printf(\"Done.\\n\");\n\n return 0;\n}\nshould be working, but need protobuf file from another branch#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Packet;\n\nint main(int argc, char* argv[]) {\n int framePeriod = 1000000 \/ 60;\n\n QString logFile;\n\n \/\/ Determine log file name\n if (argc == 2) {\n logFile = argv[1];\n }\n\n if (logFile.isNull()) {\n if (!QDir(\"logs\").exists()) {\n printf(\"No logs directory and no log file specified\\n\");\n return 1;\n }\n\n logFile = QString(\"logs\/\") +\n QDateTime::currentDateTime().toString(\"yyyyMMdd-hhmmss.log\");\n }\n\n \/\/ Create vision socket\n QUdpSocket visionSocket;\n if (!visionSocket.bind(SharedVisionPortDoubleNew,\n QUdpSocket::ShareAddress)) {\n printf(\"Can't bind to shared vision port\");\n return 1;\n }\n multicast_add(&visionSocket, SharedVisionAddress);\n\n \/\/ Create referee socket\n QUdpSocket refereeSocket;\n if (!refereeSocket.bind(ProtobufRefereePort, QUdpSocket::ShareAddress)) {\n throw runtime_error(\"Can't bind to shared referee port\");\n }\n\n multicast_add(&refereeSocket, RefereeAddress);\n\n \/\/ Create log file\n int fd = creat(logFile.toLatin1(), 0666);\n if (fd < 0) {\n printf(\"Can't create %s: %m\\n\", (const char*)logFile.toLatin1());\n return 1;\n }\n\n printf(\"Writing to %s\\n\", (const char*)logFile.toLatin1());\n\n \/\/ Main loop\n LogFrame logFrame;\n bool first = true;\n while (true) {\n RJ::Time startTime = RJ::timestamp();\n\n logFrame.Clear();\n logFrame.set_command_time(startTime);\n logFrame.set_timestamp(startTime);\n\n \/\/ Check for user input (to exit)\n struct pollfd pfd;\n pfd.fd = 0;\n pfd.events = POLLIN;\n if (poll(&pfd, 1, 0) > 0) {\n \/\/ Enter pressed\n break;\n }\n\n \/\/ Read vision data\n while (visionSocket.hasPendingDatagrams()) {\n string buf;\n unsigned int n = visionSocket.pendingDatagramSize();\n buf.resize(n);\n visionSocket.readDatagram(&buf[0], n);\n\n SSL_WrapperPacket* packet = logFrame.add_raw_vision();\n if (!packet->ParseFromString(buf)) {\n printf(\"Bad vision packet of %d bytes\\n\", n);\n continue;\n }\n }\n\n \/\/ Read referee data\n while (refereeSocket.hasPendingDatagrams()) {\n string buf;\n unsigned int n = refereeSocket.pendingDatagramSize();\n buf.resize(n);\n refereeSocket.readDatagram(&buf[0], n);\n\n SSL_Referee* packet = logFrame.add_raw_refbox();\n if (!packet->ParseFromString(buf)) {\n printf(\"Bad referee packet of %d bytes\\n\", n);\n continue;\n }\n }\n\n if (first) {\n first = false;\n\n LogConfig* logConfig = logFrame.mutable_log_config();\n logConfig->set_generator(\"simple_logger\");\n logConfig->set_git_version_hash(git_version_hash);\n logConfig->set_git_version_dirty(git_version_dirty);\n }\n\n uint32_t size = logFrame.ByteSize();\n if (write(fd, &size, sizeof(size)) != sizeof(size)) {\n printf(\"Failed to write size: %m\\n\");\n break;\n } else if (!logFrame.SerializeToFileDescriptor(fd)) {\n printf(\"Failed to write frame: %m\\n\");\n break;\n }\n\n RJ::Time endTime = RJ::timestamp();\n int lastFrameTime = endTime - startTime;\n if (lastFrameTime < framePeriod) {\n usleep(framePeriod - lastFrameTime);\n } else {\n printf(\"Processor took too long: %d us\\n\", lastFrameTime);\n }\n }\n\n \/\/ Discard input on stdin\n tcflush(0, TCIFLUSH);\n\n printf(\"Done.\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"Action.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nAction * selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, Action & action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\t\/\/create pointers to the possible actions as well as a pointer to hold the chosen action\n\tAction* chosen_action;\n\tAction* actions[2];\n\tactions[0]=new Action(FORWARD);\n\tactions[1]=new Action(BACKWARD);\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(actions[0],0);\n\tinitiator_queue.enqueueWithPriority(actions[1],0);\n\t\n\t\/\/create the state space\n\tStateSpace space(100,50,initiator_queue);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta=getAngle();\n\t\tcurrent_state.theta_dot=getVelocity();\n\t\tcurrent_state.robot_state=chosen_action.action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\tchosen_action.execute();\n\t}\n\t\n\tdelete actions[0];\n\tdelete actions[1];\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nAction * selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(std::vector< std::pair >::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return it->first;\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, Action * action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\nUpdate Main.cpp#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"Action.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nAction * selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, Action & action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\t\/\/create pointers to the possible actions as well as a pointer to hold the chosen action\n\tAction* chosen_action;\n\tAction* actions[2];\n\tactions[0]=new Action(FORWARD,\/*function pointer here*\/);\n\tactions[1]=new Action(BACKWARD,\/*function pointer here*\/);\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(actions[0],0);\n\tinitiator_queue.enqueueWithPriority(actions[1],0);\n\t\n\t\/\/create the state space\n\tStateSpace space(100,50,initiator_queue);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta=getAngle();\n\t\tcurrent_state.theta_dot=getVelocity();\n\t\tcurrent_state.robot_state=chosen_action.action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\tchosen_action.execute();\n\t}\n\t\n\tdelete actions[0];\n\tdelete actions[1];\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nAction * selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(std::vector< std::pair >::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return it->first;\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, Action * action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2019 Daniel Nicoletti \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"useragent.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace Cutelyst;\n\nQ_LOGGING_CATEGORY(C_USERAGENT, \"cutelyst.useragent\", QtInfoMsg)\n\nstatic thread_local QNetworkAccessManager m_instance;\n\nQNetworkAccessManager *Cutelyst::UA::networkAccessManager()\n{\n return &m_instance;\n}\n\nQNetworkReply *UA::head(const QNetworkRequest &request)\n{\n return m_instance.head(request);\n}\n\nQNetworkReply *UA::get(const QNetworkRequest &request)\n{\n return m_instance.get(request);\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, QIODevice *data)\n{\n return m_instance.post(request, data);\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, const QByteArray &data)\n{\n return m_instance.post(request, data);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, QIODevice *data)\n{\n return m_instance.put(request, data);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, const QByteArray &data)\n{\n return m_instance.put(request, data);\n}\n\nQNetworkReply *UA::deleteResource(const QNetworkRequest &request)\n{\n return m_instance.deleteResource(request);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data)\n{\n return m_instance.sendCustomRequest(request, verb, data);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, const QByteArray &data)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))\n return m_instance.sendCustomRequest(request, verb, data);\n#else\n auto buffer = new QBuffer;\n buffer->setData(data);\n QNetworkReply *reply = m_instance.sendCustomRequest(request, verb, buffer);\n buffer->setParent(reply);\n return reply;\n#endif\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, QHttpMultiPart *multiPart)\n{\n return m_instance.post(request, multiPart);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, QHttpMultiPart *multiPart)\n{\n return m_instance.post(request, multiPart);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QHttpMultiPart *multiPart)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))\n return m_instance.sendCustomRequest(request, verb, multiPart);\n#else\n return nullptr;\n#endif\n}\n\nQNetworkReply *UA::postJson(const QNetworkRequest &request, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJson(const QNetworkRequest &request, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJson(const QNetworkRequest &request, const QByteArray &verb, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::postJsonObject(const QNetworkRequest &request, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJsonObject(const QNetworkRequest &request, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJsonObject(const QNetworkRequest &request, const QByteArray &verb, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::postJsonArray(const QNetworkRequest &request, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJsonArray(const QNetworkRequest &request, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJsonArray(const QNetworkRequest &request, const QByteArray &verb, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::forwardRequest(Request *request, const QUrl &destination)\n{\n QUrl dest(request->uri());\n dest.setHost(destination.host());\n dest.setPort(destination.port());\n dest.setScheme(destination.scheme());\n\n QNetworkRequest proxyReq(dest);\n\n const Headers reqHeaders = request->headers();\n const auto headersData = reqHeaders.data();\n auto it = headersData.constBegin();\n while (it != headersData.constEnd()) {\n proxyReq.setRawHeader(Cutelyst::Engine::camelCaseHeader(it.key()).toLatin1(), it.value().toLatin1());\n ++it;\n }\n\n return m_instance.sendCustomRequest(proxyReq, request->method().toLatin1(), request->body());\n}\n\nQNetworkReply *UA::forwardRequestResponse(Context *c, const QUrl &destination)\n{\n QNetworkReply *reply = forwardRequest(c->request(), destination);\n QObject::connect(reply, &QNetworkReply::finished, reply, [=] {\n Headers &responseHeaders = c->response()->headers();\n const QList &headers = reply->rawHeaderPairs();\n for (const QNetworkReply::RawHeaderPair &pair : headers) {\n responseHeaders.setHeader(QString::fromLatin1(pair.first), QString::fromLatin1(pair.second));\n }\n c->response()->setStatus(quint16(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt()));\n c->response()->setBody(reply);\n });\n return reply;\n}\n\nvoid UA::forwardAsync(Context *c, const QUrl &destination)\n{\n QNetworkReply *reply = forwardRequest(c->request(), destination);\n QObject::connect(reply, &QNetworkReply::finished, reply, [=] {\n Headers &responseHeaders = c->response()->headers();\n const QList &headers = reply->rawHeaderPairs();\n for (const QNetworkReply::RawHeaderPair &pair : headers) {\n responseHeaders.setHeader(QString::fromLatin1(pair.first), QString::fromLatin1(pair.second));\n }\n c->response()->setStatus(quint16(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt()));\n c->response()->setBody(reply);\n c->attachAsync();\n });\n c->detachAsync();\n}\nUA: Use Context as lambda owner\/*\n * Copyright (C) 2019 Daniel Nicoletti \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n#include \"useragent.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace Cutelyst;\n\nQ_LOGGING_CATEGORY(C_USERAGENT, \"cutelyst.useragent\", QtInfoMsg)\n\nstatic thread_local QNetworkAccessManager m_instance;\n\nQNetworkAccessManager *Cutelyst::UA::networkAccessManager()\n{\n return &m_instance;\n}\n\nQNetworkReply *UA::head(const QNetworkRequest &request)\n{\n return m_instance.head(request);\n}\n\nQNetworkReply *UA::get(const QNetworkRequest &request)\n{\n return m_instance.get(request);\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, QIODevice *data)\n{\n return m_instance.post(request, data);\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, const QByteArray &data)\n{\n return m_instance.post(request, data);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, QIODevice *data)\n{\n return m_instance.put(request, data);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, const QByteArray &data)\n{\n return m_instance.put(request, data);\n}\n\nQNetworkReply *UA::deleteResource(const QNetworkRequest &request)\n{\n return m_instance.deleteResource(request);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QIODevice *data)\n{\n return m_instance.sendCustomRequest(request, verb, data);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, const QByteArray &data)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))\n return m_instance.sendCustomRequest(request, verb, data);\n#else\n auto buffer = new QBuffer;\n buffer->setData(data);\n QNetworkReply *reply = m_instance.sendCustomRequest(request, verb, buffer);\n buffer->setParent(reply);\n return reply;\n#endif\n}\n\nQNetworkReply *UA::post(const QNetworkRequest &request, QHttpMultiPart *multiPart)\n{\n return m_instance.post(request, multiPart);\n}\n\nQNetworkReply *UA::put(const QNetworkRequest &request, QHttpMultiPart *multiPart)\n{\n return m_instance.post(request, multiPart);\n}\n\nQNetworkReply *UA::sendCustomRequest(const QNetworkRequest &request, const QByteArray &verb, QHttpMultiPart *multiPart)\n{\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0))\n return m_instance.sendCustomRequest(request, verb, multiPart);\n#else\n return nullptr;\n#endif\n}\n\nQNetworkReply *UA::postJson(const QNetworkRequest &request, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJson(const QNetworkRequest &request, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJson(const QNetworkRequest &request, const QByteArray &verb, const QJsonDocument &doc)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, doc.toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::postJsonObject(const QNetworkRequest &request, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJsonObject(const QNetworkRequest &request, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJsonObject(const QNetworkRequest &request, const QByteArray &verb, const QJsonObject &obj)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, QJsonDocument(obj).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::postJsonArray(const QNetworkRequest &request, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.post(jsonRequest, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::putJsonArray(const QNetworkRequest &request, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return m_instance.put(jsonRequest, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::sendCustomRequestJsonArray(const QNetworkRequest &request, const QByteArray &verb, const QJsonArray &array)\n{\n QNetworkRequest jsonRequest(request);\n jsonRequest.setHeader(QNetworkRequest::ContentTypeHeader, QByteArrayLiteral(\"application\/json\"));\n return UA::sendCustomRequest(jsonRequest, verb, QJsonDocument(array).toJson(QJsonDocument::Compact));\n}\n\nQNetworkReply *UA::forwardRequest(Request *request, const QUrl &destination)\n{\n QUrl dest(request->uri());\n dest.setHost(destination.host());\n dest.setPort(destination.port());\n dest.setScheme(destination.scheme());\n\n QNetworkRequest proxyReq(dest);\n\n const Headers reqHeaders = request->headers();\n const auto headersData = reqHeaders.data();\n auto it = headersData.constBegin();\n while (it != headersData.constEnd()) {\n proxyReq.setRawHeader(Cutelyst::Engine::camelCaseHeader(it.key()).toLatin1(), it.value().toLatin1());\n ++it;\n }\n\n return m_instance.sendCustomRequest(proxyReq, request->method().toLatin1(), request->body());\n}\n\nQNetworkReply *UA::forwardRequestResponse(Context *c, const QUrl &destination)\n{\n QNetworkReply *reply = forwardRequest(c->request(), destination);\n QObject::connect(reply, &QNetworkReply::finished, c, [=] {\n Headers &responseHeaders = c->response()->headers();\n const QList &headers = reply->rawHeaderPairs();\n for (const QNetworkReply::RawHeaderPair &pair : headers) {\n responseHeaders.setHeader(QString::fromLatin1(pair.first), QString::fromLatin1(pair.second));\n }\n c->response()->setStatus(quint16(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt()));\n c->response()->setBody(reply);\n });\n return reply;\n}\n\nvoid UA::forwardAsync(Context *c, const QUrl &destination)\n{\n QNetworkReply *reply = forwardRequest(c->request(), destination);\n QObject::connect(reply, &QNetworkReply::finished, c, [=] {\n Headers &responseHeaders = c->response()->headers();\n const QList &headers = reply->rawHeaderPairs();\n for (const QNetworkReply::RawHeaderPair &pair : headers) {\n responseHeaders.setHeader(QString::fromLatin1(pair.first), QString::fromLatin1(pair.second));\n }\n c->response()->setStatus(quint16(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt()));\n c->response()->setBody(reply);\n c->attachAsync();\n });\n c->detachAsync();\n}\n<|endoftext|>"} {"text":"\/**\n An implementation of Markov chains for text generation using C++11 and STL\n methods.\n\n Author: Bastian Rieck \n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst std::string punctuation = \",;:.!?\";\ntypedef std::map< std::string, std::vector > database_type;\n\n\/**\n Tokenizes a given file. Any punctuation mark and any whitespace character is\n considered a token. The function returns a container of all tokens in the\n order in which they appear in the text. By concatenating subsequent entries\n with a whitespace character, the original text may be formed again.\n*\/\n\nstd::vector getTokens( const std::string& filename )\n{\n std::ifstream in( filename );\n\n std::vector rawTokens;\n\n std::copy( std::istream_iterator( in ),\n std::istream_iterator(),\n std::back_inserter( rawTokens ) );\n\n std::vector tokens;\n tokens.reserve( rawTokens.size() );\n\n for( auto&& rawToken : rawTokens )\n {\n \/\/ Only use the _last_ punctuation that may be found in the token. We do\n \/\/ not want to split a chapter number or a word.\n auto pos = rawToken.find_last_of( punctuation );\n if( pos != std::string::npos && pos + 1 == rawToken.length() )\n {\n tokens.push_back( rawToken.substr( 0, pos ) );\n tokens.push_back( rawToken.substr( pos ) );\n }\n\n \/\/ Simply copy the token\n else\n tokens.push_back( rawToken );\n }\n\n return tokens;\n}\n\n\/**\n Joins a sequence of tokens and returns a single string. If one of the tokens\n is a punctuation mark, spurious punctuation will be avoided.\n*\/\n\ntemplate std::string join( InputIterator begin, InputIterator end )\n{\n std::string result;\n\n for( auto it = begin; it != end; ++it )\n {\n \/\/ Is this punctuation? If so, do not add any whitespace.\n if( it->length() == 1 && it->find_first_of( punctuation ) != std::string::npos )\n result += *it;\n else\n {\n if( it != begin )\n result += \" \";\n\n result += *it;\n }\n }\n\n return result;\n}\n\n\/** Splits a string into its sequence of tokens. *\/\ntemplate void split( const std::string& string, OutputIterator result )\n{\n std::istringstream buffer( string );\n\n std::vector rawTokens;\n\n std::copy( std::istream_iterator( buffer ),\n std::istream_iterator(),\n std::back_inserter( rawTokens ) );\n\n for( auto&& rawToken : rawTokens )\n {\n \/\/ Only use the _last_ punctuation that may be found in the token. We do\n \/\/ not want to split a chapter number or a word.\n auto pos = rawToken.find_last_of( punctuation );\n if( rawToken.length() > 1 && pos != std::string::npos && pos + 1 == rawToken.length() )\n {\n *result++ = rawToken.substr( 0, pos );\n *result++ = rawToken.substr( pos );\n }\n\n \/\/ Simply copy the token\n else\n *result++ = rawToken;\n }\n}\n\n\/**\n Given a vector of tokens and a prefix length, traverses the vector and stores\n the appropriate suffix of the token. The model for updating the suffixes is\n very simple --- subsequent words are merely added to a list of known words.\n This makes choosing the next word easier.\n*\/\n\ndatabase_type buildDatabase( const std::vector& tokens, unsigned int prefixLength )\n{\n database_type database;\n\n std::list prefixWords( prefixLength );\n\n for( std::size_t i = 0; i < tokens.size(); i++ )\n {\n prefixWords.pop_front();\n prefixWords.push_back( tokens.at(i) );\n\n if( i + 1 < tokens.size() )\n {\n std::string prefix = join( prefixWords.begin(),\n prefixWords.end() );\n\n database[prefix].push_back( tokens.at(i+1) );\n }\n }\n\n return database;\n}\n\n\/**\n Starts creating text from the database of tokens, using a Markov chain. The\n function will choose a prefix at random from the database, then select a\n subsequent word from the word list at random, thereby creating a new prefix.\n This process will be repeated until a number of pre-defined iterations has\n been reached.\n*\/\n\nstd::string spew( const database_type& database, unsigned int numIterations )\n{\n std::random_device rd;\n std::default_random_engine engine( rd() );\n\n std::ostringstream output;\n std::string prefix;\n\n {\n std::uniform_int_distribution distribution( 0, database.size() - 1 );\n std::size_t index = distribution( engine );\n auto it = database.begin();\n\n std::advance( it, index );\n\n prefix = it->first;\n output << prefix;\n }\n\n for( unsigned int i = 1; i < numIterations; i++ )\n {\n auto&& words = database.at( prefix );\n\n std::uniform_int_distribution distribution( 0, words.size() - 1 );\n std::size_t index = distribution( engine );\n std::string word = words.at( index );\n\n \/\/ Choose a new prefix. We do this by splitting the old prefix into a list\n \/\/ of tokens, deleting the first one, and appending the current word.\n\n std::list prefixTokens;\n split( prefix,\n std::back_inserter( prefixTokens ) );\n\n prefixTokens.pop_front();\n prefixTokens.push_back( word );\n\n prefix = join( prefixTokens.begin(), prefixTokens.end() );\n\n if( !( word.length() == 1 && word.find_first_of( punctuation ) != std::string::npos ) )\n output << \" \";\n\n output << word;\n }\n\n return output.str();\n}\n\nint main( int, char** )\n{\n auto tokens = getTokens( \"..\/King_James.txt\" );\n auto database = buildDatabase( tokens, 2 );\n\n std::cout << spew( database, 100 );\n\n return 0;\n}\nAdded licence\/*\n * An implementation of Markov chains for text generation using C++11 and STL\n * methods.\n *\n * Copyright (c) 2014 Bastian Rieck\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 THE\n * SOFTWARE.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst std::string punctuation = \",;:.!?\";\ntypedef std::map< std::string, std::vector > database_type;\n\n\/**\n Tokenizes a given file. Any punctuation mark and any whitespace character is\n considered a token. The function returns a container of all tokens in the\n order in which they appear in the text. By concatenating subsequent entries\n with a whitespace character, the original text may be formed again.\n*\/\n\nstd::vector getTokens( const std::string& filename )\n{\n std::ifstream in( filename );\n\n std::vector rawTokens;\n\n std::copy( std::istream_iterator( in ),\n std::istream_iterator(),\n std::back_inserter( rawTokens ) );\n\n std::vector tokens;\n tokens.reserve( rawTokens.size() );\n\n for( auto&& rawToken : rawTokens )\n {\n \/\/ Only use the _last_ punctuation that may be found in the token. We do\n \/\/ not want to split a chapter number or a word.\n auto pos = rawToken.find_last_of( punctuation );\n if( pos != std::string::npos && pos + 1 == rawToken.length() )\n {\n tokens.push_back( rawToken.substr( 0, pos ) );\n tokens.push_back( rawToken.substr( pos ) );\n }\n\n \/\/ Simply copy the token\n else\n tokens.push_back( rawToken );\n }\n\n return tokens;\n}\n\n\/**\n Joins a sequence of tokens and returns a single string. If one of the tokens\n is a punctuation mark, spurious punctuation will be avoided.\n*\/\n\ntemplate std::string join( InputIterator begin, InputIterator end )\n{\n std::string result;\n\n for( auto it = begin; it != end; ++it )\n {\n \/\/ Is this punctuation? If so, do not add any whitespace.\n if( it->length() == 1 && it->find_first_of( punctuation ) != std::string::npos )\n result += *it;\n else\n {\n if( it != begin )\n result += \" \";\n\n result += *it;\n }\n }\n\n return result;\n}\n\n\/** Splits a string into its sequence of tokens. *\/\ntemplate void split( const std::string& string, OutputIterator result )\n{\n std::istringstream buffer( string );\n\n std::vector rawTokens;\n\n std::copy( std::istream_iterator( buffer ),\n std::istream_iterator(),\n std::back_inserter( rawTokens ) );\n\n for( auto&& rawToken : rawTokens )\n {\n \/\/ Only use the _last_ punctuation that may be found in the token. We do\n \/\/ not want to split a chapter number or a word.\n auto pos = rawToken.find_last_of( punctuation );\n if( rawToken.length() > 1 && pos != std::string::npos && pos + 1 == rawToken.length() )\n {\n *result++ = rawToken.substr( 0, pos );\n *result++ = rawToken.substr( pos );\n }\n\n \/\/ Simply copy the token\n else\n *result++ = rawToken;\n }\n}\n\n\/**\n Given a vector of tokens and a prefix length, traverses the vector and stores\n the appropriate suffix of the token. The model for updating the suffixes is\n very simple --- subsequent words are merely added to a list of known words.\n This makes choosing the next word easier.\n*\/\n\ndatabase_type buildDatabase( const std::vector& tokens, unsigned int prefixLength )\n{\n database_type database;\n\n std::list prefixWords( prefixLength );\n\n for( std::size_t i = 0; i < tokens.size(); i++ )\n {\n prefixWords.pop_front();\n prefixWords.push_back( tokens.at(i) );\n\n if( i + 1 < tokens.size() )\n {\n std::string prefix = join( prefixWords.begin(),\n prefixWords.end() );\n\n database[prefix].push_back( tokens.at(i+1) );\n }\n }\n\n return database;\n}\n\n\/**\n Starts creating text from the database of tokens, using a Markov chain. The\n function will choose a prefix at random from the database, then select a\n subsequent word from the word list at random, thereby creating a new prefix.\n This process will be repeated until a number of pre-defined iterations has\n been reached.\n*\/\n\nstd::string spew( const database_type& database, unsigned int numIterations )\n{\n std::random_device rd;\n std::default_random_engine engine( rd() );\n\n std::ostringstream output;\n std::string prefix;\n\n {\n std::uniform_int_distribution distribution( 0, database.size() - 1 );\n std::size_t index = distribution( engine );\n auto it = database.begin();\n\n std::advance( it, index );\n\n prefix = it->first;\n output << prefix;\n }\n\n for( unsigned int i = 1; i < numIterations; i++ )\n {\n auto&& words = database.at( prefix );\n\n std::uniform_int_distribution distribution( 0, words.size() - 1 );\n std::size_t index = distribution( engine );\n std::string word = words.at( index );\n\n \/\/ Choose a new prefix. We do this by splitting the old prefix into a list\n \/\/ of tokens, deleting the first one, and appending the current word.\n\n std::list prefixTokens;\n split( prefix,\n std::back_inserter( prefixTokens ) );\n\n prefixTokens.pop_front();\n prefixTokens.push_back( word );\n\n prefix = join( prefixTokens.begin(), prefixTokens.end() );\n\n if( !( word.length() == 1 && word.find_first_of( punctuation ) != std::string::npos ) )\n output << \" \";\n\n output << word;\n }\n\n return output.str();\n}\n\nint main( int, char** )\n{\n auto tokens = getTokens( \"..\/King_James.txt\" );\n auto database = buildDatabase( tokens, 2 );\n\n std::cout << spew( database, 100 );\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"main.h\"\n\n\/* example constructor, sets some options *\/\nCaesarAttack::CaesarAttack()\n{\n \/\/ declare options, keep options as uppercase\n vector temp;\n temp.push_back(\"INPUTFILE\");\n temp.push_back(\"OUTPUTFILE\");\n set_opts(temp);\n\n \/\/ set default values, option must exist or error will printed\n set_opt_value(\"OUTPUTFILE\", \"\/tmp\/caesarattackresults.txt\");\n}\n\n\/* I am overriding the default module function\n * for displaying the description text\n *\/\nvoid CaesarAttack::disp_desc()\n{\n cout << \"Module: attacks\/caesar_attack\\n\\tThis module attempts to guess the correct shift for the Caesar cipher.\\n\\tIt makes use of frequency analysis to determine a proper guess.\\n\\tMay require user interaction.\\n\\tPlease define an INPUTFILE.\" << endl;\n cout << endl;\n}\n\n\/* overrides the virtual function from Module\n * this is where the real meaty stuff happens\n *\/\nint CaesarAttack::run()\n{\n \/\/ perform error checking on options first\n if (options[\"INPUTFILE\"].empty()) {\n cout << \"[-] Please specify an input file\" << endl;\n return 1;\n }\n\n if (options[\"OUTPUTFILE\"].empty()) {\n cout << \"[-] Please specify an output file\" << endl;\n return 2;\n }\n\n ifstream in;\n ofstream out;\n string buff;\n\n cout << \"[*] Opening input file: \" << options[\"INPUTFILE\"] << endl;\n in.open(options[\"INPUTFILE\"]);\n\n cout << \"[*] Beginning attack...\" << endl;\n begin_attack(in, out);\n\n cout << \"[*] Closing files\" << endl;\n in.close();\n out.close();\n\n return 0;\n}\n\n\/* not safe helper function\n * doesn't check array out of bounds\n *\/\nfloat chisq(float *y, float *ym)\n{\n float sq = 0.0f;\n for (int i = 0; i < 26; i++)\n sq += (y[i] - ym[i])*(y[i] - ym[i]);\n return sq;\n}\n\n\/* shifts each entry to the left one *\/\nvoid left_shift_freq(float *freq)\n{\n float temp = freq[0];\n for (int i = 0; i < 25; i++)\n freq[i] = freq[i+1];\n freq[26] = temp;\n}\n\n\/* handles the main attack sequence *\/\nvoid CaesarAttack::begin_attack(ifstream &in, ofstream &out)\n{\n \/* from analyzing huckleberry finn *\/\n float english[] = {0.0834423, 0.0169666, 0.0191698, 0.0539923, 0.112034, 0.0180501, 0.0246394, 0.0602159, 0.0646833, 0.00280142, 0.0130094, 0.0398317, 0.0236778, 0.0747964, 0.0835958, 0.0138107, 0.000442449, 0.0464413, 0.057629, 0.0967157, 0.0318857, 0.00675638, 0.03031, 0.0011919, 0.0234859, 0.00042439};\n\n int freq[26] = {0}, count = 0;\n float ffreq[26] = {0.0f};\n string buff;\n\n while (getline(in, buff)) {\n for (unsigned int i = 0; i < buff.size(); i++) {\n if (isalpha(buff[i])) {\n int t = ((int) tolower(buff[i])) - 97;\n freq[t]++; count++;\n }\n }\n }\n\n for (int i = 0; i < 26; i++)\n ffreq[i] = (float)freq[i]\/(float)count;\n\n int mins[26]; float csq[26];\n for (int i = 0; i < 26; i++) {\n mins[i] = i;\n csq[i] = chisq(ffreq, english);\n left_shift_freq(ffreq);\n }\n\n \/* insertion sort *\/\n for (int i = 0; i < 26; i++) {\n int j = i;\n while (j > 0 && csq[mins[j-1]] > csq[mins[j]]) {\n int temp = mins[j-1];\n mins[j-1] = mins[j];\n mins[j] = temp;\n j--;\n }\n }\n\n \/\/ for (int i = 0; i < 26; i++)\n \/\/ cout << \"\\t\" << mins[i] << \"\\t\" << csq[mins[i]] << endl;\n\n string ans;\n cout << \"[+] Most likely shift: \" << mins[0] << endl;\n\n for (int i = 0; i < 26; i++) {\n cout << \"[*] Decrypting file with shift \" << mins[i] << \" (chi^2 = \" << csq[mins[i]] << \")...\" << endl;\n\n out.open(options[\"OUTPUTFILE\"]);\n\n \/\/ reset input\n in.clear();\n in.seekg(0);\n\n string obuff;\n int samplecount = 0;\n cout << \"[*] Sample from decryption: \" << endl;\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, mins[i], true);\n out << obuff << endl;\n if (samplecount < 5) {\n cout << obuff << endl;\n samplecount++;\n } else {\n break;\n }\n }\n\n string ans;\n cout << \"[*] Continue decryption? [Y\/n]: \";\n getline(cin, ans);\n if (ans == \"N\" || ans == \"n\")\n continue;\n\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, mins[i], true);\n out << obuff << endl;\n }\n\n \/\/ if we get here we are done\n break;\n }\n}\nadded guess based on e frequency as first resort#include \"main.h\"\n\n\/* example constructor, sets some options *\/\nCaesarAttack::CaesarAttack()\n{\n \/\/ declare options, keep options as uppercase\n vector temp;\n temp.push_back(\"INPUTFILE\");\n temp.push_back(\"OUTPUTFILE\");\n set_opts(temp);\n\n \/\/ set default values, option must exist or error will printed\n set_opt_value(\"OUTPUTFILE\", \"\/tmp\/caesarattackresults.txt\");\n}\n\n\/* I am overriding the default module function\n * for displaying the description text\n *\/\nvoid CaesarAttack::disp_desc()\n{\n cout << \"Module: attacks\/caesar_attack\\n\\tThis module attempts to guess the correct shift for the Caesar cipher.\\n\\tIt makes use of frequency analysis to determine a proper guess.\\n\\tMay require user interaction.\\n\\tPlease define an INPUTFILE.\" << endl;\n cout << endl;\n}\n\n\/* overrides the virtual function from Module\n * this is where the real meaty stuff happens\n *\/\nint CaesarAttack::run()\n{\n \/\/ perform error checking on options first\n if (options[\"INPUTFILE\"].empty()) {\n cout << \"[-] Please specify an input file\" << endl;\n return 1;\n }\n\n if (options[\"OUTPUTFILE\"].empty()) {\n cout << \"[-] Please specify an output file\" << endl;\n return 2;\n }\n\n ifstream in;\n ofstream out;\n string buff;\n\n cout << \"[*] Opening input file: \" << options[\"INPUTFILE\"] << endl;\n in.open(options[\"INPUTFILE\"]);\n\n cout << \"[*] Beginning attack...\" << endl;\n begin_attack(in, out);\n\n cout << \"[*] Closing files\" << endl;\n in.close();\n out.close();\n\n return 0;\n}\n\n\/* not safe helper function\n * doesn't check array out of bounds\n *\/\nfloat chisq(float *y, float *ym)\n{\n float sq = 0.0f;\n for (int i = 0; i < 26; i++)\n sq += (y[i] - ym[i])*(y[i] - ym[i]);\n return sq;\n}\n\n\/* shifts each entry to the left one *\/\nvoid left_shift_freq(float *freq)\n{\n float temp = freq[0];\n for (int i = 0; i < 25; i++)\n freq[i] = freq[i+1];\n freq[26] = temp;\n}\n\n\/* handles the main attack sequence *\/\nvoid CaesarAttack::begin_attack(ifstream &in, ofstream &out)\n{\n \/* from analyzing huckleberry finn *\/\n float english[] = {0.0834423, 0.0169666, 0.0191698, 0.0539923, 0.112034, 0.0180501, 0.0246394, 0.0602159, 0.0646833, 0.00280142, 0.0130094, 0.0398317, 0.0236778, 0.0747964, 0.0835958, 0.0138107, 0.000442449, 0.0464413, 0.057629, 0.0967157, 0.0318857, 0.00675638, 0.03031, 0.0011919, 0.0234859, 0.00042439};\n\n int freq[26] = {0}, count = 0;\n float ffreq[26] = {0.0f};\n string buff;\n\n while (getline(in, buff)) {\n for (unsigned int i = 0; i < buff.size(); i++) {\n if (isalpha(buff[i])) {\n int t = ((int) tolower(buff[i])) - 97;\n freq[t]++; count++;\n }\n }\n }\n\n for (int i = 0; i < 26; i++)\n ffreq[i] = (float)freq[i]\/(float)count;\n\n int max = 0;\n for (int j = 1; j < 26; j++)\n if (ffreq[j] > ffreq[max])\n max = j;\n int maxkey = (max-4 < 0) ? max-4+26 : max-4;\n cout << \"[*] Guessing based on 'e' frequency\" << endl;\n cout << \"[*] Decrypting file with shift \" << maxkey << \"...\" << endl;\n\n out.open(options[\"OUTPUTFILE\"]);\n\n \/\/ reset input\n in.clear();\n in.seekg(0);\n\n string obuff;\n int samplecount = 0;\n cout << \"[*] Sample from decryption: \" << endl;\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, maxkey, true);\n out << obuff << endl;\n if (samplecount < 5) {\n cout << obuff << endl;\n samplecount++;\n } else {\n break;\n }\n }\n\n string ans;\n cout << \"[*] Continue decryption? [Y\/n]: \";\n getline(cin, ans);\n if (ans == \"Y\" || ans == \"y\") {\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, maxkey, true);\n out << obuff << endl;\n }\n\n return;\n }\n\n out.close();\n cout << \"[*] Falling back to chi^2 analysis...\" << endl;\n\n int mins[26]; float csq[26];\n for (int i = 0; i < 26; i++) {\n mins[i] = i;\n csq[i] = chisq(ffreq, english);\n left_shift_freq(ffreq);\n }\n\n \/* insertion sort *\/\n for (int i = 0; i < 26; i++) {\n int j = i;\n while (j > 0 && csq[mins[j-1]] > csq[mins[j]]) {\n int temp = mins[j-1];\n mins[j-1] = mins[j];\n mins[j] = temp;\n j--;\n }\n }\n\n cout << \"[+] Most likely shift: \" << mins[0] << endl;\n\n for (int i = 0; i < 26; i++) {\n cout << \"[*] Decrypting file with shift \" << mins[i] << \" (chi^2 = \" << csq[mins[i]] << \")...\" << endl;\n\n out.open(options[\"OUTPUTFILE\"]);\n\n \/\/ reset input\n in.clear();\n in.seekg(0);\n\n string obuff;\n int samplecount = 0;\n cout << \"[*] Sample from decryption: \" << endl;\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, mins[i], true);\n out << obuff << endl;\n if (samplecount < 5) {\n cout << obuff << endl;\n samplecount++;\n } else {\n break;\n }\n }\n\n string ans;\n cout << \"[*] Continue decryption? [Y\/n]: \";\n getline(cin, ans);\n if (ans == \"N\" || ans == \"n\") {\n out.close();\n continue;\n }\n\n while (getline(in, buff)) {\n Caesar::encrypt(buff, obuff, mins[i], true);\n out << obuff << endl;\n }\n\n \/\/ if we get here we are done\n break;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2020, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"web\/web-service\/ot_client.hpp\"\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\n#include \"common\/code_utils.hpp\"\n#include \"common\/logging.hpp\"\n#include \"utils\/strcpy_utils.hpp\"\n\n\/\/ Temporary solution before posix platform header files are cleaned up.\n#ifndef OPENTHREAD_POSIX_APP_SOCKET_NAME\n#define OPENTHREAD_POSIX_APP_SOCKET_NAME \"\/tmp\/openthread.sock\"\n#endif\n\nnamespace otbr {\nnamespace Web {\n\nOpenThreadClient::OpenThreadClient(void)\n : mTimeout(kDefaultTimeout)\n , mSocket(-1)\n{\n}\n\nOpenThreadClient::~OpenThreadClient(void)\n{\n Disconnect();\n}\n\nvoid OpenThreadClient::Disconnect(void)\n{\n if (mSocket != -1)\n {\n close(mSocket);\n mSocket = -1;\n }\n}\n\nbool OpenThreadClient::Connect(void)\n{\n struct sockaddr_un sockname;\n int ret;\n\n mSocket = socket(AF_UNIX, SOCK_STREAM, 0);\n VerifyOrExit(mSocket != -1, perror(\"socket\"); ret = EXIT_FAILURE);\n\n memset(&sockname, 0, sizeof(struct sockaddr_un));\n sockname.sun_family = AF_UNIX;\n strcpy_safe(sockname.sun_path, sizeof(sockname.sun_path), OPENTHREAD_POSIX_APP_SOCKET_NAME);\n\n ret = connect(mSocket, reinterpret_cast(&sockname), sizeof(struct sockaddr_un));\n\n if (ret == -1)\n {\n otbrLog(OTBR_LOG_ERR, \"OpenThread daemon is not running.\");\n }\n\nexit:\n return ret == 0;\n}\n\nchar *OpenThreadClient::Execute(const char *aFormat, ...)\n{\n va_list args;\n int ret;\n char * rval = nullptr;\n ssize_t count;\n size_t rxLength = 0;\n\n va_start(args, aFormat);\n ret = vsnprintf(&mBuffer[1], sizeof(mBuffer) - 1, aFormat, args);\n va_end(args);\n\n if (ret < 0)\n {\n otbrLog(OTBR_LOG_ERR, \"Failed to generate command: %s\", strerror(errno));\n }\n\n mBuffer[0] = '\\n';\n ret++;\n\n if (ret == sizeof(mBuffer))\n {\n otbrLog(OTBR_LOG_ERR, \"Command exceeds maximum limit: %d\", kBufferSize);\n }\n\n mBuffer[ret] = '\\n';\n ret++;\n\n count = write(mSocket, mBuffer, ret);\n\n if (count < ret)\n {\n mBuffer[ret] = '\\0';\n otbrLog(OTBR_LOG_ERR, \"Failed to send command: %s\", mBuffer);\n }\n\n for (int i = 0; i < mTimeout; ++i)\n {\n fd_set readFdSet;\n timeval timeout = {0, 1000};\n char * done;\n\n FD_ZERO(&readFdSet);\n FD_SET(mSocket, &readFdSet);\n\n ret = select(mSocket + 1, &readFdSet, nullptr, nullptr, &timeout);\n VerifyOrExit(ret != -1 || errno == EINTR);\n if (ret <= 0)\n {\n continue;\n }\n\n count = read(mSocket, &mBuffer[rxLength], sizeof(mBuffer) - rxLength);\n VerifyOrExit(count > 0);\n rxLength += count;\n\n mBuffer[rxLength] = '\\0';\n done = strstr(mBuffer, \"Done\\r\\n\");\n\n if (done != nullptr)\n {\n \/\/ remove trailing \\r\\n\n if (done - rval > 2)\n {\n done[-2] = '\\0';\n }\n\n rval = mBuffer;\n break;\n }\n }\n\nexit:\n return rval;\n}\n\nint OpenThreadClient::Scan(WpanNetworkInfo *aNetworks, int aLength)\n{\n char *result;\n int rval = 0;\n\n mTimeout = 5000;\n result = Execute(\"scan\");\n VerifyOrExit(result != nullptr);\n\n for (result = strtok(result, \"\\r\\n\"); result != nullptr && rval < aLength; result = strtok(nullptr, \"\\r\\n\"))\n {\n static const char kCliPrompt[] = \"> \";\n char * cliPrompt;\n int matched;\n int joinable;\n int lqi;\n\n \/\/ remove prompt\n if ((cliPrompt = strstr(result, kCliPrompt)) != nullptr)\n {\n if (cliPrompt == result)\n {\n result += sizeof(kCliPrompt) - 1;\n }\n else\n {\n memmove(cliPrompt, cliPrompt + sizeof(kCliPrompt) - 1, strlen(cliPrompt) - sizeof(kCliPrompt) - 1);\n }\n }\n\n matched = sscanf(result,\n \"| %d | %s | %\" PRIx64\n \" | %hx | %02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx | %hu | %hhd | %d |\",\n &joinable, aNetworks[rval].mNetworkName, &aNetworks[rval].mExtPanId, &aNetworks[rval].mPanId,\n &aNetworks[rval].mHardwareAddress[0], &aNetworks[rval].mHardwareAddress[1],\n &aNetworks[rval].mHardwareAddress[2], &aNetworks[rval].mHardwareAddress[3],\n &aNetworks[rval].mHardwareAddress[4], &aNetworks[rval].mHardwareAddress[5],\n &aNetworks[rval].mHardwareAddress[6], &aNetworks[rval].mHardwareAddress[7],\n &aNetworks[rval].mChannel, &aNetworks[rval].mRssi, &lqi);\n\n \/\/ 15 is the number of output arguments of the last sscanf()\n if (matched != 15)\n {\n continue;\n }\n\n aNetworks[rval].mAllowingJoin = joinable != 0;\n ++rval;\n }\n\n mTimeout = kDefaultTimeout;\n\nexit:\n return rval;\n}\n\nbool OpenThreadClient::FactoryReset(void)\n{\n const char *result;\n bool rval = false;\n#if __APPLE__\n typedef sig_t sighandler_t;\n#endif\n sighandler_t handler;\n\n \/\/ Ignore the expected SIGPIPE signal during daemon reset.\n handler = signal(SIGPIPE, SIG_IGN);\n Execute(\"factoryreset\");\n signal(SIGPIPE, handler);\n Disconnect();\n sleep(1);\n VerifyOrExit(rval = Connect());\n\n result = Execute(\"version\");\n VerifyOrExit(result != nullptr);\n\n rval = strstr(result, \"OPENTHREAD\") != nullptr;\n\nexit:\n return rval;\n}\n\n} \/\/ namespace Web\n} \/\/ namespace otbr\n[ot-client] fix bug in stripping `Done\\r\\n` (#781)\/*\n * Copyright (c) 2020, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"web\/web-service\/ot_client.hpp\"\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\n#include \"common\/code_utils.hpp\"\n#include \"common\/logging.hpp\"\n#include \"utils\/strcpy_utils.hpp\"\n\n\/\/ Temporary solution before posix platform header files are cleaned up.\n#ifndef OPENTHREAD_POSIX_APP_SOCKET_NAME\n#define OPENTHREAD_POSIX_APP_SOCKET_NAME \"\/tmp\/openthread.sock\"\n#endif\n\nnamespace otbr {\nnamespace Web {\n\nOpenThreadClient::OpenThreadClient(void)\n : mTimeout(kDefaultTimeout)\n , mSocket(-1)\n{\n}\n\nOpenThreadClient::~OpenThreadClient(void)\n{\n Disconnect();\n}\n\nvoid OpenThreadClient::Disconnect(void)\n{\n if (mSocket != -1)\n {\n close(mSocket);\n mSocket = -1;\n }\n}\n\nbool OpenThreadClient::Connect(void)\n{\n struct sockaddr_un sockname;\n int ret;\n\n mSocket = socket(AF_UNIX, SOCK_STREAM, 0);\n VerifyOrExit(mSocket != -1, perror(\"socket\"); ret = EXIT_FAILURE);\n\n memset(&sockname, 0, sizeof(struct sockaddr_un));\n sockname.sun_family = AF_UNIX;\n strcpy_safe(sockname.sun_path, sizeof(sockname.sun_path), OPENTHREAD_POSIX_APP_SOCKET_NAME);\n\n ret = connect(mSocket, reinterpret_cast(&sockname), sizeof(struct sockaddr_un));\n\n if (ret == -1)\n {\n otbrLog(OTBR_LOG_ERR, \"OpenThread daemon is not running.\");\n }\n\nexit:\n return ret == 0;\n}\n\nchar *OpenThreadClient::Execute(const char *aFormat, ...)\n{\n va_list args;\n int ret;\n char * rval = nullptr;\n ssize_t count;\n size_t rxLength = 0;\n\n va_start(args, aFormat);\n ret = vsnprintf(&mBuffer[1], sizeof(mBuffer) - 1, aFormat, args);\n va_end(args);\n\n if (ret < 0)\n {\n otbrLog(OTBR_LOG_ERR, \"Failed to generate command: %s\", strerror(errno));\n }\n\n mBuffer[0] = '\\n';\n ret++;\n\n if (ret == sizeof(mBuffer))\n {\n otbrLog(OTBR_LOG_ERR, \"Command exceeds maximum limit: %d\", kBufferSize);\n }\n\n mBuffer[ret] = '\\n';\n ret++;\n\n count = write(mSocket, mBuffer, ret);\n\n if (count < ret)\n {\n mBuffer[ret] = '\\0';\n otbrLog(OTBR_LOG_ERR, \"Failed to send command: %s\", mBuffer);\n }\n\n for (int i = 0; i < mTimeout; ++i)\n {\n fd_set readFdSet;\n timeval timeout = {0, 1000};\n char * done;\n\n FD_ZERO(&readFdSet);\n FD_SET(mSocket, &readFdSet);\n\n ret = select(mSocket + 1, &readFdSet, nullptr, nullptr, &timeout);\n VerifyOrExit(ret != -1 || errno == EINTR);\n if (ret <= 0)\n {\n continue;\n }\n\n count = read(mSocket, &mBuffer[rxLength], sizeof(mBuffer) - rxLength);\n VerifyOrExit(count > 0);\n rxLength += count;\n\n mBuffer[rxLength] = '\\0';\n done = strstr(mBuffer, \"Done\\r\\n\");\n\n if (done != nullptr)\n {\n \/\/ remove trailing \\r\\n\n if (done - mBuffer > 2)\n {\n done[-2] = '\\0';\n }\n\n rval = mBuffer;\n break;\n }\n }\n\nexit:\n return rval;\n}\n\nint OpenThreadClient::Scan(WpanNetworkInfo *aNetworks, int aLength)\n{\n char *result;\n int rval = 0;\n\n mTimeout = 5000;\n result = Execute(\"scan\");\n VerifyOrExit(result != nullptr);\n\n for (result = strtok(result, \"\\r\\n\"); result != nullptr && rval < aLength; result = strtok(nullptr, \"\\r\\n\"))\n {\n static const char kCliPrompt[] = \"> \";\n char * cliPrompt;\n int matched;\n int joinable;\n int lqi;\n\n \/\/ remove prompt\n if ((cliPrompt = strstr(result, kCliPrompt)) != nullptr)\n {\n if (cliPrompt == result)\n {\n result += sizeof(kCliPrompt) - 1;\n }\n else\n {\n memmove(cliPrompt, cliPrompt + sizeof(kCliPrompt) - 1, strlen(cliPrompt) - sizeof(kCliPrompt) - 1);\n }\n }\n\n matched = sscanf(result,\n \"| %d | %s | %\" PRIx64\n \" | %hx | %02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx | %hu | %hhd | %d |\",\n &joinable, aNetworks[rval].mNetworkName, &aNetworks[rval].mExtPanId, &aNetworks[rval].mPanId,\n &aNetworks[rval].mHardwareAddress[0], &aNetworks[rval].mHardwareAddress[1],\n &aNetworks[rval].mHardwareAddress[2], &aNetworks[rval].mHardwareAddress[3],\n &aNetworks[rval].mHardwareAddress[4], &aNetworks[rval].mHardwareAddress[5],\n &aNetworks[rval].mHardwareAddress[6], &aNetworks[rval].mHardwareAddress[7],\n &aNetworks[rval].mChannel, &aNetworks[rval].mRssi, &lqi);\n\n \/\/ 15 is the number of output arguments of the last sscanf()\n if (matched != 15)\n {\n continue;\n }\n\n aNetworks[rval].mAllowingJoin = joinable != 0;\n ++rval;\n }\n\n mTimeout = kDefaultTimeout;\n\nexit:\n return rval;\n}\n\nbool OpenThreadClient::FactoryReset(void)\n{\n const char *result;\n bool rval = false;\n#if __APPLE__\n typedef sig_t sighandler_t;\n#endif\n sighandler_t handler;\n\n \/\/ Ignore the expected SIGPIPE signal during daemon reset.\n handler = signal(SIGPIPE, SIG_IGN);\n Execute(\"factoryreset\");\n signal(SIGPIPE, handler);\n Disconnect();\n sleep(1);\n VerifyOrExit(rval = Connect());\n\n result = Execute(\"version\");\n VerifyOrExit(result != nullptr);\n\n rval = strstr(result, \"OPENTHREAD\") != nullptr;\n\nexit:\n return rval;\n}\n\n} \/\/ namespace Web\n} \/\/ namespace otbr\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\nTEST(ZappedChannels, FileError)\n{\n AstroData::Observation observation;\n std::vector channels;\n std::string wrongFileName = \".\/zappred_channels.conf\";\n ASSERT_THROW(AstroData::readZappedChannels(observation, wrongFileName, channels), AstroData::FileError); \n}\n\nTEST(ZappedChannels, MatchingChannels)\n{\n AstroData::Observation observation;\n std::vector channels;\n std::string fileName = \".\/zapped_channels.conf\";\n observation.setFrequencyRange(1, 1024, 0.0f, 0.0f);\n channels.resize(observation.getNrChannels());\n AstroData::readZappedChannels(observation, fileName, channels);\n EXPECT_EQ(channels.at(4), 1);\n EXPECT_EQ(channels.at(39), 1);\n EXPECT_EQ(channels.at(7), 1);\n EXPECT_EQ(channels.at(19), 1);\n EXPECT_EQ(channels.at(1023), 1);\n EXPECT_EQ(channels.at(0), 1);\n EXPECT_EQ(channels.at(45), 0);\n EXPECT_EQ(channels.at(128), 0);\n}\nUpdated the test.\/\/ Copyright 2019 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\nTEST(ZappedChannels, FileError)\n{\n AstroData::Observation observation;\n std::vector channels;\n std::string wrongFileName = \".\/zappred_channels.conf\";\n ASSERT_THROW(AstroData::readZappedChannels(observation, wrongFileName, channels), AstroData::FileError); \n}\n\nTEST(ZappedChannels, MatchingChannels)\n{\n AstroData::Observation observation;\n std::vector channels;\n std::string fileName = \".\/zapped_channels.conf\";\n observation.setFrequencyRange(1, 1024, 0.0f, 0.0f);\n channels.resize(observation.getNrChannels());\n AstroData::readZappedChannels(observation, fileName, channels);\n EXPECT_EQ(channels.at(4), 1);\n EXPECT_EQ(channels.at(39), 1);\n EXPECT_EQ(channels.at(7), 1);\n EXPECT_EQ(channels.at(19), 1);\n EXPECT_EQ(channels.at(1023), 1);\n EXPECT_EQ(channels.at(0), 1);\n EXPECT_NE(channels.at(45), 1);\n EXPECT_NE(channels.at(128), 1);\n}\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing af::dim4;\n\nnamespace cpu\n{\n\nstatic inline dim_t clamp(int a, dim_t mn, dim_t mx)\n{\n return (a < (int)mn ? mn : (a > (int)mx ? mx : a));\n}\n\nstatic inline unsigned getIdx(const dim4 &strides,\n int i, int j = 0, int k = 0, int l = 0)\n{\n return (l * strides[3] +\n k * strides[2] +\n j * strides[1] +\n i * strides[0]);\n}\n\ntemplate\nArray bilateral(const Array &in, const float &s_sigma, const float &c_sigma)\n{\n const dim4 dims = in.dims();\n const dim4 istrides = in.strides();\n\n Array out = createEmptyArray(dims);\n const dim4 ostrides = out.strides();\n\n outType *outData = out.get();\n const inType * inData = in.get();\n\n \/\/ clamp spatical and chromatic sigma's\n float space_ = std::min(11.5f, std::max(s_sigma, 0.f));\n float color_ = std::max(c_sigma, 0.f);\n const dim_t radius = std::max((dim_t)(space_ * 1.5f), (dim_t)1);\n const float svar = space_*space_;\n const float cvar = color_*color_;\n\n for(dim_t b3=0; b3 bilateral(const Array &in, const float &s_sigma, const float &c_sigma);\\\ntemplate Array bilateral(const Array &in, const float &s_sigma, const float &c_sigma);\n\nINSTANTIATE(double, double)\nINSTANTIATE(float , float)\nINSTANTIATE(char , float)\nINSTANTIATE(int , float)\nINSTANTIATE(uint , float)\nINSTANTIATE(uchar , float)\n\n}\nAsync CPU Bilateral\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing af::dim4;\nusing std::ref;\n\nnamespace cpu\n{\n\nstatic inline dim_t clamp(int a, dim_t mn, dim_t mx)\n{\n return (a < (int)mn ? mn : (a > (int)mx ? mx : a));\n}\n\nstatic inline unsigned getIdx(const dim4 &strides,\n int i, int j = 0, int k = 0, int l = 0)\n{\n return (l * strides[3] +\n k * strides[2] +\n j * strides[1] +\n i * strides[0]);\n}\n\ntemplate\nvoid bilateral_(Array out, const Array &in, float s_sigma, float c_sigma)\n{\n const dim4 dims = in.dims();\n const dim4 istrides = in.strides();\n\n const dim4 ostrides = out.strides();\n\n outType *outData = out.get();\n const inType * inData = in.get();\n\n \/\/ clamp spatical and chromatic sigma's\n float space_ = std::min(11.5f, std::max(s_sigma, 0.f));\n float color_ = std::max(c_sigma, 0.f);\n const dim_t radius = std::max((dim_t)(space_ * 1.5f), (dim_t)1);\n const float svar = space_*space_;\n const float cvar = color_*color_;\n\n for(dim_t b3=0; b3\nArray bilateral(const Array &in, const float &s_sigma, const float &c_sigma)\n{\n const dim4 dims = in.dims();\n Array out = createEmptyArray(dims);\n getQueue().enqueue(bilateral_, out, ref(in), s_sigma, c_sigma);\n return out;\n}\n\n#define INSTANTIATE(inT, outT)\\\ntemplate Array bilateral(const Array &in, const float &s_sigma, const float &c_sigma);\\\ntemplate Array bilateral(const Array &in, const float &s_sigma, const float &c_sigma);\n\nINSTANTIATE(double, double)\nINSTANTIATE(float , float)\nINSTANTIATE(char , float)\nINSTANTIATE(int , float)\nINSTANTIATE(uint , float)\nINSTANTIATE(uchar , float)\n\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht \/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n#include \"template_test.hpp\"\n\n#include \"etl\/etl.hpp\"\n\nTEMPLATE_TEST_CASE_2( \"column_major\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm test_matrix(0);\n\n REQUIRE(test_matrix.size() == 6);\n\n REQUIRE(test_matrix.template dim<0>() == 2);\n REQUIRE(test_matrix.template dim<1>() == 3);\n REQUIRE(test_matrix.dim(0) == 2);\n REQUIRE(test_matrix.dim(1) == 3);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0) == 1);\n REQUIRE(test_matrix(0, 1) == 3);\n REQUIRE(test_matrix(0, 2) == 5);\n REQUIRE(test_matrix(1, 0) == 2);\n REQUIRE(test_matrix(1, 1) == 4);\n REQUIRE(test_matrix(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/2\", \"[dyn][cm]\", Z, int, long ) {\n etl::dyn_matrix_cm test_matrix(2, 3);\n\n test_matrix = 0;\n\n REQUIRE(test_matrix.size() == 6);\n\n REQUIRE(test_matrix.template dim<0>() == 2);\n REQUIRE(test_matrix.template dim<1>() == 3);\n REQUIRE(test_matrix.dim(0) == 2);\n REQUIRE(test_matrix.dim(1) == 3);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0) == 1);\n REQUIRE(test_matrix(0, 1) == 3);\n REQUIRE(test_matrix(0, 2) == 5);\n REQUIRE(test_matrix(1, 0) == 2);\n REQUIRE(test_matrix(1, 1) == 4);\n REQUIRE(test_matrix(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/3\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm test_matrix;\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0, 0) == 1);\n REQUIRE(test_matrix(0, 0, 1) == 7);\n REQUIRE(test_matrix(0, 0, 2) == 13);\n REQUIRE(test_matrix(0, 0, 3) == 19);\n REQUIRE(test_matrix(0, 1, 0) == 3);\n REQUIRE(test_matrix(0, 1, 1) == 9);\n REQUIRE(test_matrix(0, 1, 2) == 15);\n REQUIRE(test_matrix(0, 1, 3) == 21);\n REQUIRE(test_matrix(0, 2, 0) == 5);\n REQUIRE(test_matrix(0, 2, 1) == 11);\n REQUIRE(test_matrix(0, 2, 2) == 17);\n REQUIRE(test_matrix(0, 2, 3) == 23);\n REQUIRE(test_matrix(1, 0, 0) == 2);\n REQUIRE(test_matrix(1, 0, 1) == 8);\n REQUIRE(test_matrix(1, 0, 2) == 14);\n REQUIRE(test_matrix(1, 0, 3) == 20);\n REQUIRE(test_matrix(1, 1, 0) == 4);\n REQUIRE(test_matrix(1, 1, 1) == 10);\n REQUIRE(test_matrix(1, 1, 2) == 16);\n REQUIRE(test_matrix(1, 1, 3) == 22);\n REQUIRE(test_matrix(1, 2, 0) == 6);\n REQUIRE(test_matrix(1, 2, 1) == 12);\n REQUIRE(test_matrix(1, 2, 2) == 18);\n REQUIRE(test_matrix(1, 2, 3) == 24);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/4\", \"[dyn][cm]\", Z, int, long ) {\n etl::dyn_matrix_cm test_matrix(2, 3, 4);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0, 0) == 1);\n REQUIRE(test_matrix(0, 0, 1) == 7);\n REQUIRE(test_matrix(0, 0, 2) == 13);\n REQUIRE(test_matrix(0, 0, 3) == 19);\n REQUIRE(test_matrix(0, 1, 0) == 3);\n REQUIRE(test_matrix(0, 1, 1) == 9);\n REQUIRE(test_matrix(0, 1, 2) == 15);\n REQUIRE(test_matrix(0, 1, 3) == 21);\n REQUIRE(test_matrix(0, 2, 0) == 5);\n REQUIRE(test_matrix(0, 2, 1) == 11);\n REQUIRE(test_matrix(0, 2, 2) == 17);\n REQUIRE(test_matrix(0, 2, 3) == 23);\n REQUIRE(test_matrix(1, 0, 0) == 2);\n REQUIRE(test_matrix(1, 0, 1) == 8);\n REQUIRE(test_matrix(1, 0, 2) == 14);\n REQUIRE(test_matrix(1, 0, 3) == 20);\n REQUIRE(test_matrix(1, 1, 0) == 4);\n REQUIRE(test_matrix(1, 1, 1) == 10);\n REQUIRE(test_matrix(1, 1, 2) == 16);\n REQUIRE(test_matrix(1, 1, 3) == 22);\n REQUIRE(test_matrix(1, 2, 0) == 6);\n REQUIRE(test_matrix(1, 2, 1) == 12);\n REQUIRE(test_matrix(1, 2, 2) == 18);\n REQUIRE(test_matrix(1, 2, 3) == 24);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/transpose\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n\n REQUIRE(a(0, 0) == 1);\n REQUIRE(a(0, 1) == 3);\n REQUIRE(a(0, 2) == 5);\n REQUIRE(a(1, 0) == 2);\n REQUIRE(a(1, 1) == 4);\n REQUIRE(a(1, 2) == 6);\n\n etl::fast_matrix_cm b(etl::transpose(a));\n\n REQUIRE(b(0, 0) == 1);\n REQUIRE(b(1, 0) == 3);\n REQUIRE(b(2, 0) == 5);\n REQUIRE(b(0, 1) == 2);\n REQUIRE(b(1, 1) == 4);\n REQUIRE(b(2, 1) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/tranpose\/2\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n\n REQUIRE(a(0, 0) == 1);\n REQUIRE(a(0, 1) == 4);\n REQUIRE(a(1, 0) == 2);\n REQUIRE(a(1, 1) == 5);\n REQUIRE(a(2, 0) == 3);\n REQUIRE(a(2, 1) == 6);\n\n etl::fast_matrix_cm b(etl::transpose(a));\n\n REQUIRE(b(0, 0) == 1);\n REQUIRE(b(0, 1) == 2);\n REQUIRE(b(0, 2) == 3);\n REQUIRE(b(1, 0) == 4);\n REQUIRE(b(1, 1) == 5);\n REQUIRE(b(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/binary\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n etl::fast_matrix_cm b(a + a - a + a);\n\n REQUIRE(b(0, 0) == 2);\n REQUIRE(b(0, 1) == 8);\n REQUIRE(b(1, 0) == 4);\n REQUIRE(b(1, 1) == 10);\n REQUIRE(b(2, 0) == 6);\n REQUIRE(b(2, 1) == 12);\n}\nnew test\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht \/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n#include \"template_test.hpp\"\n\n#include \"etl\/etl.hpp\"\n\nTEMPLATE_TEST_CASE_2( \"column_major\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm test_matrix(0);\n\n REQUIRE(test_matrix.size() == 6);\n\n REQUIRE(test_matrix.template dim<0>() == 2);\n REQUIRE(test_matrix.template dim<1>() == 3);\n REQUIRE(test_matrix.dim(0) == 2);\n REQUIRE(test_matrix.dim(1) == 3);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0) == 1);\n REQUIRE(test_matrix(0, 1) == 3);\n REQUIRE(test_matrix(0, 2) == 5);\n REQUIRE(test_matrix(1, 0) == 2);\n REQUIRE(test_matrix(1, 1) == 4);\n REQUIRE(test_matrix(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/2\", \"[dyn][cm]\", Z, int, long ) {\n etl::dyn_matrix_cm test_matrix(2, 3);\n\n test_matrix = 0;\n\n REQUIRE(test_matrix.size() == 6);\n\n REQUIRE(test_matrix.template dim<0>() == 2);\n REQUIRE(test_matrix.template dim<1>() == 3);\n REQUIRE(test_matrix.dim(0) == 2);\n REQUIRE(test_matrix.dim(1) == 3);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0) == 1);\n REQUIRE(test_matrix(0, 1) == 3);\n REQUIRE(test_matrix(0, 2) == 5);\n REQUIRE(test_matrix(1, 0) == 2);\n REQUIRE(test_matrix(1, 1) == 4);\n REQUIRE(test_matrix(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/3\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm test_matrix;\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0, 0) == 1);\n REQUIRE(test_matrix(0, 0, 1) == 7);\n REQUIRE(test_matrix(0, 0, 2) == 13);\n REQUIRE(test_matrix(0, 0, 3) == 19);\n REQUIRE(test_matrix(0, 1, 0) == 3);\n REQUIRE(test_matrix(0, 1, 1) == 9);\n REQUIRE(test_matrix(0, 1, 2) == 15);\n REQUIRE(test_matrix(0, 1, 3) == 21);\n REQUIRE(test_matrix(0, 2, 0) == 5);\n REQUIRE(test_matrix(0, 2, 1) == 11);\n REQUIRE(test_matrix(0, 2, 2) == 17);\n REQUIRE(test_matrix(0, 2, 3) == 23);\n REQUIRE(test_matrix(1, 0, 0) == 2);\n REQUIRE(test_matrix(1, 0, 1) == 8);\n REQUIRE(test_matrix(1, 0, 2) == 14);\n REQUIRE(test_matrix(1, 0, 3) == 20);\n REQUIRE(test_matrix(1, 1, 0) == 4);\n REQUIRE(test_matrix(1, 1, 1) == 10);\n REQUIRE(test_matrix(1, 1, 2) == 16);\n REQUIRE(test_matrix(1, 1, 3) == 22);\n REQUIRE(test_matrix(1, 2, 0) == 6);\n REQUIRE(test_matrix(1, 2, 1) == 12);\n REQUIRE(test_matrix(1, 2, 2) == 18);\n REQUIRE(test_matrix(1, 2, 3) == 24);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/4\", \"[dyn][cm]\", Z, int, long ) {\n etl::dyn_matrix_cm test_matrix(2, 3, 4);\n\n for(std::size_t i = 0; i < test_matrix.size(); ++i){\n test_matrix[i] = i+1;\n }\n\n REQUIRE(test_matrix(0, 0, 0) == 1);\n REQUIRE(test_matrix(0, 0, 1) == 7);\n REQUIRE(test_matrix(0, 0, 2) == 13);\n REQUIRE(test_matrix(0, 0, 3) == 19);\n REQUIRE(test_matrix(0, 1, 0) == 3);\n REQUIRE(test_matrix(0, 1, 1) == 9);\n REQUIRE(test_matrix(0, 1, 2) == 15);\n REQUIRE(test_matrix(0, 1, 3) == 21);\n REQUIRE(test_matrix(0, 2, 0) == 5);\n REQUIRE(test_matrix(0, 2, 1) == 11);\n REQUIRE(test_matrix(0, 2, 2) == 17);\n REQUIRE(test_matrix(0, 2, 3) == 23);\n REQUIRE(test_matrix(1, 0, 0) == 2);\n REQUIRE(test_matrix(1, 0, 1) == 8);\n REQUIRE(test_matrix(1, 0, 2) == 14);\n REQUIRE(test_matrix(1, 0, 3) == 20);\n REQUIRE(test_matrix(1, 1, 0) == 4);\n REQUIRE(test_matrix(1, 1, 1) == 10);\n REQUIRE(test_matrix(1, 1, 2) == 16);\n REQUIRE(test_matrix(1, 1, 3) == 22);\n REQUIRE(test_matrix(1, 2, 0) == 6);\n REQUIRE(test_matrix(1, 2, 1) == 12);\n REQUIRE(test_matrix(1, 2, 2) == 18);\n REQUIRE(test_matrix(1, 2, 3) == 24);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/transpose\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n\n REQUIRE(a(0, 0) == 1);\n REQUIRE(a(0, 1) == 3);\n REQUIRE(a(0, 2) == 5);\n REQUIRE(a(1, 0) == 2);\n REQUIRE(a(1, 1) == 4);\n REQUIRE(a(1, 2) == 6);\n\n etl::fast_matrix_cm b(etl::transpose(a));\n\n REQUIRE(b(0, 0) == 1);\n REQUIRE(b(1, 0) == 3);\n REQUIRE(b(2, 0) == 5);\n REQUIRE(b(0, 1) == 2);\n REQUIRE(b(1, 1) == 4);\n REQUIRE(b(2, 1) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/tranpose\/2\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n\n REQUIRE(a(0, 0) == 1);\n REQUIRE(a(0, 1) == 4);\n REQUIRE(a(1, 0) == 2);\n REQUIRE(a(1, 1) == 5);\n REQUIRE(a(2, 0) == 3);\n REQUIRE(a(2, 1) == 6);\n\n etl::fast_matrix_cm b(etl::transpose(a));\n\n REQUIRE(b(0, 0) == 1);\n REQUIRE(b(0, 1) == 2);\n REQUIRE(b(0, 2) == 3);\n REQUIRE(b(1, 0) == 4);\n REQUIRE(b(1, 1) == 5);\n REQUIRE(b(1, 2) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/binary\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a(etl::sequence_generator(1));\n etl::fast_matrix_cm b(a + a - a + a);\n\n REQUIRE(a(0, 0) == 1);\n REQUIRE(a(0, 1) == 4);\n REQUIRE(a(1, 0) == 2);\n REQUIRE(a(1, 1) == 5);\n REQUIRE(a(2, 0) == 3);\n REQUIRE(a(2, 1) == 6);\n}\n\nTEMPLATE_TEST_CASE_2( \"column_major\/sub\/1\", \"[fast][cm]\", Z, int, long ) {\n etl::fast_matrix_cm a;\n etl::fast_matrix_cm b(a(1));\n\n a(0) = etl::sequence_generator(1);\n a(1) = etl::sequence_generator(7);\n a(2) = etl::sequence_generator(13);\n\n REQUIRE(a(0)(0, 0) == 1);\n REQUIRE(a(0)(0, 1) == 4);\n REQUIRE(a(0)(1, 0) == 2);\n REQUIRE(a(0)(1, 1) == 5);\n REQUIRE(a(0)(2, 0) == 3);\n REQUIRE(a(0)(2, 1) == 6);\n\n REQUIRE(b(0, 0) == 7);\n REQUIRE(b(0, 1) == 10);\n REQUIRE(b(1, 0) == 8);\n REQUIRE(b(1, 1) == 11);\n REQUIRE(b(2, 0) == 9);\n REQUIRE(b(2, 1) == 15);\n}\n<|endoftext|>"} {"text":"\n#include \n\nusing SimTK::Inertia;\nusing SimTK::Pi;\nusing SimTK::Vec3;\n\nusing OpenSim::Body;\nusing OpenSim::CoordinateSet;\nusing OpenSim::DisplayGeometry;\nusing OpenSim::Model;\nusing OpenSim::PinJoint;\n\n\/**\n * Creates an OpenSim model of a three-legged animal. The animal has only one\n * hind leg, centered mediolaterally.\n *\n * Axis orientations, in rough terms:\n * +x: direction of forward travel.\n * +y: up.\n * +z: out of the screen.\n * *\/\n\n\/** Helper functions. **\/\nvoid addCylinderDisplayGeometry(Body * body,\n const double & diam, const double & length)\n{\n DisplayGeometry * geom = new DisplayGeometry(\"cylinder.vtp\");\n SimTK::Rotation rot;\n \/\/ Rotate the cylinder's symmetry (Y) axis to align with the body's X axis:\n rot.setRotationFromAngleAboutZ(-0.5 * Pi);\n geom->setTransform(\n SimTK::Transform(rot, Vec3(0.5 * length, 0, 0)));\n\n geom->setScaleFactors(Vec3(0.5 * diam, length, 0.5 * diam));\n body->updDisplayer()->setShowAxes(true);\n body->updDisplayer()->updGeometrySet().adoptAndAppend(geom);\n};\n\nvoid addThighCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 90, 1.0E2, -90, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addShankCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 10, 1.0E2, -160, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addCoordinateActuator(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateActuator * act = new OpenSim::CoordinateActuator(coord);\n act->setName(coord + \"_actuator\");\n act->setMinControl(-1000.0);\n act->setMaxControl(1000.0);\n model.addForce(act);\n};\n\nint main(int argc, char * argv[])\n{\n \/\/ Preliminaries.\n \/\/ --------------\n Model tripod;\n tripod.setName(\"tripod\");\n\n \/\/ Properties.\n \/\/ -----------\n \/\/ Lengths, in meters.\n double torsoX = 0.5;\n double torsoY = 0.1;\n double torsoZ = 0.3;\n double thighLength = 0.1;\n double thighDiameter = 0.07;\n double shankLength = 0.1;\n double shankDiameter = 0.05;\n\n \/\/ Masses, in kilograms.\n double torsoMass = 1.0;\n double thighMass = 1.0;\n double shankMass = 1.0;\n\n \/\/ Center of mass, in meters.\n \/\/ This really just chooses the origin of our bodies.\n Vec3 torsoCOM(0, 0, 0);\n \/\/ We choose the x direction to be the axis of the leg segments, with +x\n \/\/ pointing toward the ground.\n Vec3 thighCOM(0.5 * thighLength, 0, 0);\n Vec3 shankCOM(0.5 * shankLength, 0, 0);\n\n \/\/ Moments of inertia, in kilograms-meters^2.\n \/\/ These are about the center of mass of the body, expressed in the frame\n \/\/ of the body.\n Inertia torsoInertia = Inertia::brick(\n 0.5 * torsoX, 0.5 * torsoY, 0.5 * torsoZ);\n Inertia thighInertia = Inertia::cylinderAlongX(0.5 * thighDiameter,\n thighLength);\n Inertia shankInertia = Inertia::cylinderAlongX(0.5 * shankDiameter,\n shankLength);\n\n \/\/ Bodies.\n \/\/ -------\n Body * torso = new Body(\"torso\",\n torsoMass, torsoCOM, torsoInertia);\n Body * hindThigh = new Body(\"hind_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * hindShank = new Body(\"hind_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontLeftThigh = new Body(\"front_left_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontLeftShank = new Body(\"front_left_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontRightThigh = new Body(\"front_right_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontRightShank = new Body(\"front_right_shank\",\n shankMass, shankCOM, shankInertia);\n\n \/\/ Joints.\n \/\/ -------\n Body & ground = tripod.getGroundBody();\n\n \/\/ Ground -> Torso.\n \/\/ ````````````````\n \/\/ The torso has no constraints with respect to the ground.\n \/\/ By default, the tripod's feet are on the ground.\n Vec3 locGTinG(0, thighLength + shankLength, 0);\n Vec3 orientGTinG(0, 0, 0);\n Vec3 locGTinT(0, 0, 0);\n Vec3 orientGTinT(0, 0, 0);\n OpenSim::FreeJoint * groundTorso = new OpenSim::FreeJoint(\"torso\",\n ground, locGTinG, orientGTinG, *torso, locGTinT, orientGTinT);\n\n CoordinateSet & groundTorsoCS = groundTorso->upd_CoordinateSet();\n\n \/\/ Rotation about x.\n groundTorsoCS[0].setName(\"torso_rx\"); \n double groundTorsoCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[0].setRange(groundTorsoCS0range);\n\n groundTorsoCS[1].setName(\"torso_ry\"); \n double groundTorsoCS1range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[1].setRange(groundTorsoCS1range);\n\n groundTorsoCS[2].setName(\"torso_rz\"); \n double groundTorsoCS2range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[2].setRange(groundTorsoCS2range);\n\n \/\/ Translation in x.\n groundTorsoCS[3].setName(\"torso_tx\"); \n double groundTorsoCS3range[2] = {-1.0, 10.0};\n groundTorsoCS[3].setRange(groundTorsoCS3range);\n\n groundTorsoCS[4].setName(\"torso_ty\"); \n double groundTorsoCS4range[2] = {0.0, 2.0};\n groundTorsoCS[4].setRange(groundTorsoCS4range);\n\n groundTorsoCS[5].setName(\"torso_tz\"); \n double groundTorsoCS5range[2] = {-1.0, 1.0};\n groundTorsoCS[5].setRange(groundTorsoCS5range);\n\n \/\/ Torso -> hind thigh.\n \/\/ ````````````````````\n Vec3 locTHinT(-0.5 * torsoX, 0, 0);\n \/\/ By default, the leg is extended.\n Vec3 orientTHinT(0, 0, -0.5 * Pi);\n Vec3 locTHinH(0, 0, 0);\n Vec3 orientTHinH(0, 0, 0);\n PinJoint * torsoHindThigh = new PinJoint(\"hind_thigh\",\n *torso, locTHinT, orientTHinT, *hindThigh, locTHinH, orientTHinH);\n\n CoordinateSet & torsoHindThighCS = torsoHindThigh->upd_CoordinateSet();\n torsoHindThighCS[0].setName(\"hind_thigh_flexion\");\n double torsoHindThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoHindThighCS[0].setRange(torsoHindThighCS0range);\n\n \/\/ Hind thigh -> hind shank.\n \/\/ `````````````````````````\n Vec3 locHTSinT(thighLength, 0, 0);\n Vec3 orientHTSinT(0, 0, 0);\n Vec3 locHTSinS(0, 0, 0);\n Vec3 orientHTSinS(0, 0, 0);\n PinJoint * hindThighShank = new PinJoint(\"hind_shank\",\n *hindThigh, locHTSinT, orientHTSinT,\n *hindShank, locHTSinS, orientHTSinS);\n\n CoordinateSet & hindThighShankCS = hindThighShank->upd_CoordinateSet();\n hindThighShankCS[0].setName(\"hind_knee_extension\");\n double hindThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n hindThighShankCS[0].setRange(hindThighShankCS0range);\n\n \/\/ Torso -> front left thigh.\n \/\/ ``````````````````````````\n Vec3 locTFLinT(0.5 * torsoX, 0, -0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFLinT(0, 0, -0.5 * Pi);\n Vec3 locTFLinFL(0, 0, 0);\n Vec3 orientTFLinFL(0, 0, 0);\n PinJoint * torsoFrontLeftThigh = new PinJoint(\"front_left_thigh\",\n *torso, locTFLinT, orientTFLinT,\n *frontLeftThigh, locTFLinFL, orientTFLinFL);\n\n CoordinateSet & torsoFrontLeftThighCS =\n torsoFrontLeftThigh->upd_CoordinateSet();\n torsoFrontLeftThighCS[0].setName(\"front_left_thigh_flexion\");\n double torsoFrontLeftThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontLeftThighCS[0].setRange(torsoFrontLeftThighCS0range);\n\n \/\/ Front left thigh -> front left shank.\n \/\/ `````````````````````````````````````\n Vec3 locFLTSinT(thighLength, 0, 0);\n Vec3 orientFLTSinT(0, 0, 0);\n Vec3 locFLTSinS(0, 0, 0);\n Vec3 orientFLTSinS(0, 0, 0);\n PinJoint * frontLeftThighShank = new PinJoint(\"front_left_shank\",\n *frontLeftThigh, locFLTSinT, orientFLTSinT,\n *frontLeftShank, locFLTSinS, orientFLTSinS);\n\n CoordinateSet & frontLeftThighShankCS =\n frontLeftThighShank->upd_CoordinateSet();\n frontLeftThighShankCS[0].setName(\"front_left_knee_extension\");\n double frontLeftThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontLeftThighShankCS[0].setRange(frontLeftThighShankCS0range);\n\n \/\/ Torso -> front right thigh.\n \/\/ ```````````````````````````\n Vec3 locTFRinT(0.5 * torsoX, 0, 0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFRinT(0, 0, -0.5 * Pi);\n Vec3 locTFRinFR(0, 0, 0);\n Vec3 orientTFRinFR(0, 0, 0);\n PinJoint * torsoFrontRightThigh = new PinJoint(\"front_right_thigh\",\n *torso, locTFRinT, orientTFRinT,\n *frontRightThigh, locTFRinFR, orientTFRinFR);\n\n CoordinateSet & torsoFrontRightThighCS =\n torsoFrontRightThigh->upd_CoordinateSet();\n torsoFrontRightThighCS[0].setName(\"front_right_thigh_flexion\");\n double torsoFrontRightThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontRightThighCS[0].setRange(torsoFrontRightThighCS0range);\n\n \/\/ Front right thigh -> front right shank.\n \/\/ ```````````````````````````````````````\n Vec3 locFRTSinT(thighLength, 0, 0);\n Vec3 orientFRTSinT(0, 0, 0);\n Vec3 locFRTSinS(0, 0, 0);\n Vec3 orientFRTSinS(0, 0, 0);\n PinJoint * frontRightThighShank = new PinJoint(\"front_right_shank\",\n *frontRightThigh, locFRTSinT, orientFRTSinT,\n *frontRightShank, locFRTSinS, orientFRTSinS);\n\n CoordinateSet & frontRightThighShankCS =\n frontRightThighShank->upd_CoordinateSet();\n frontRightThighShankCS[0].setName(\"front_right_knee_extension\");\n double frontRightThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontRightThighShankCS[0].setRange(frontRightThighShankCS0range);\n\n \/\/ Add bodies to the model.\n \/\/ ------------------------\n \/\/ Now that we've define the joints.\n tripod.addBody(torso);\n tripod.addBody(hindThigh);\n tripod.addBody(hindShank);\n tripod.addBody(frontLeftThigh);\n tripod.addBody(frontLeftShank);\n tripod.addBody(frontRightThigh);\n tripod.addBody(frontRightShank);\n\n \/\/ Display geometry.\n \/\/ -----------------\n\n \/\/ Torso.\n \/\/ ``````\n DisplayGeometry * torsoDisplay = new DisplayGeometry(\"box.vtp\");\n torsoDisplay->setScaleFactors(\n Vec3(torsoX, torsoY, torsoZ));\n torso->updDisplayer()->updGeometrySet().adoptAndAppend(torsoDisplay);\n torso->updDisplayer()->setShowAxes(true);\n\n \/\/ Limbs.\n \/\/ ``````\n addCylinderDisplayGeometry(hindThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(hindShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontLeftThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontLeftShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontRightThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontRightShank, shankDiameter, shankLength);\n\n \/\/ Enforce joint limits on the legs.\n \/\/ ---------------------------------\n addThighCoordinateLimitForce(tripod, \"hind_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_left_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_right_thigh_flexion\");\n addShankCoordinateLimitForce(tripod, \"hind_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_left_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_right_knee_extension\");\n\n \/\/ Actuators.\n \/\/ ----------\n addCoordinateActuator(tripod, \"hind_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_left_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_right_thigh_flexion\");\n addCoordinateActuator(tripod, \"hind_knee_extension\");\n addCoordinateActuator(tripod, \"front_left_knee_extension\");\n addCoordinateActuator(tripod, \"front_right_knee_extension\");\n\n \/\/ Contact.\n \/\/ --------\n \/\/ So the tripod does not go through the ground.\n\n \/\/ Print the model.\n tripod.print(\"tripod.osim\");\n\n return EXIT_SUCCESS;\n}\n\nAdd foot contact geometry. Note, none of the contact geometry shows up in GUI.\n#include \n\nusing SimTK::Inertia;\nusing SimTK::Pi;\nusing SimTK::Vec3;\n\nusing OpenSim::Body;\nusing OpenSim::CoordinateSet;\nusing OpenSim::DisplayGeometry;\nusing OpenSim::Model;\nusing OpenSim::PinJoint;\n\n\/**\n * Creates an OpenSim model of a three-legged animal. The animal has only one\n * hind leg, centered mediolaterally.\n *\n * Axis orientations, in rough terms:\n * +x: direction of forward travel.\n * +y: up.\n * +z: out of the screen.\n * *\/\n\n\/** Helper functions. **\/\nvoid addCylinderDisplayGeometry(Body * body,\n const double & diam, const double & length)\n{\n DisplayGeometry * geom = new DisplayGeometry(\"cylinder.vtp\");\n SimTK::Rotation rot;\n \/\/ Rotate the cylinder's symmetry (Y) axis to align with the body's X axis:\n rot.setRotationFromAngleAboutZ(-0.5 * Pi);\n geom->setTransform(\n SimTK::Transform(rot, Vec3(0.5 * length, 0, 0)));\n\n geom->setScaleFactors(Vec3(0.5 * diam, length, 0.5 * diam));\n body->updDisplayer()->setShowAxes(true);\n body->updDisplayer()->updGeometrySet().adoptAndAppend(geom);\n};\n\nvoid addThighCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 90, 1.0E2, -90, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addShankCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 10, 1.0E2, -160, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addCoordinateActuator(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateActuator * act = new OpenSim::CoordinateActuator(coord);\n act->setName(coord + \"_actuator\");\n act->setMinControl(-1000.0);\n act->setMaxControl(1000.0);\n model.addForce(act);\n};\n\nvoid addContactGeometry(Model & model, double xmeas, Body * body,\n const std::string name)\n{\n OpenSim::ContactSphere * contact = new OpenSim::ContactSphere(\n 0.05, Vec3(xmeas, 0, 0), *body, name);\n contact->setName(name);\n model.addContactGeometry(contact);\n}\n\nint main(int argc, char * argv[])\n{\n \/\/ Preliminaries.\n \/\/ --------------\n Model tripod;\n tripod.setName(\"tripod\");\n\n \/\/ Properties.\n \/\/ -----------\n \/\/ Lengths, in meters.\n double torsoX = 0.5;\n double torsoY = 0.1;\n double torsoZ = 0.3;\n double thighLength = 0.1;\n double thighDiameter = 0.07;\n double shankLength = 0.1;\n double shankDiameter = 0.05;\n\n \/\/ Masses, in kilograms.\n double torsoMass = 1.0;\n double thighMass = 1.0;\n double shankMass = 1.0;\n\n \/\/ Center of mass, in meters.\n \/\/ This really just chooses the origin of our bodies.\n Vec3 torsoCOM(0, 0, 0);\n \/\/ We choose the x direction to be the axis of the leg segments, with +x\n \/\/ pointing toward the ground.\n Vec3 thighCOM(0.5 * thighLength, 0, 0);\n Vec3 shankCOM(0.5 * shankLength, 0, 0);\n\n \/\/ Moments of inertia, in kilograms-meters^2.\n \/\/ These are about the center of mass of the body, expressed in the frame\n \/\/ of the body.\n Inertia torsoInertia = Inertia::brick(\n 0.5 * torsoX, 0.5 * torsoY, 0.5 * torsoZ);\n Inertia thighInertia = Inertia::cylinderAlongX(0.5 * thighDiameter,\n thighLength);\n Inertia shankInertia = Inertia::cylinderAlongX(0.5 * shankDiameter,\n shankLength);\n\n \/\/ Bodies.\n \/\/ -------\n Body * torso = new Body(\"torso\",\n torsoMass, torsoCOM, torsoInertia);\n Body * hindThigh = new Body(\"hind_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * hindShank = new Body(\"hind_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontLeftThigh = new Body(\"front_left_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontLeftShank = new Body(\"front_left_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontRightThigh = new Body(\"front_right_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontRightShank = new Body(\"front_right_shank\",\n shankMass, shankCOM, shankInertia);\n\n \/\/ Joints.\n \/\/ -------\n Body & ground = tripod.getGroundBody();\n\n \/\/ Ground -> Torso.\n \/\/ ````````````````\n \/\/ The torso has no constraints with respect to the ground.\n \/\/ By default, the tripod's feet are on the ground.\n Vec3 locGTinG(0, thighLength + shankLength, 0);\n Vec3 orientGTinG(0, 0, 0);\n Vec3 locGTinT(0, 0, 0);\n Vec3 orientGTinT(0, 0, 0);\n OpenSim::FreeJoint * groundTorso = new OpenSim::FreeJoint(\"torso\",\n ground, locGTinG, orientGTinG, *torso, locGTinT, orientGTinT);\n\n CoordinateSet & groundTorsoCS = groundTorso->upd_CoordinateSet();\n\n \/\/ Rotation about x.\n groundTorsoCS[0].setName(\"torso_rx\"); \n double groundTorsoCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[0].setRange(groundTorsoCS0range);\n\n groundTorsoCS[1].setName(\"torso_ry\"); \n double groundTorsoCS1range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[1].setRange(groundTorsoCS1range);\n\n groundTorsoCS[2].setName(\"torso_rz\"); \n double groundTorsoCS2range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[2].setRange(groundTorsoCS2range);\n\n \/\/ Translation in x.\n groundTorsoCS[3].setName(\"torso_tx\"); \n double groundTorsoCS3range[2] = {-1.0, 10.0};\n groundTorsoCS[3].setRange(groundTorsoCS3range);\n\n groundTorsoCS[4].setName(\"torso_ty\"); \n double groundTorsoCS4range[2] = {0.0, 2.0};\n groundTorsoCS[4].setRange(groundTorsoCS4range);\n\n groundTorsoCS[5].setName(\"torso_tz\"); \n double groundTorsoCS5range[2] = {-1.0, 1.0};\n groundTorsoCS[5].setRange(groundTorsoCS5range);\n\n \/\/ Torso -> hind thigh.\n \/\/ ````````````````````\n Vec3 locTHinT(-0.5 * torsoX, 0, 0);\n \/\/ By default, the leg is extended.\n Vec3 orientTHinT(0, 0, -0.5 * Pi);\n Vec3 locTHinH(0, 0, 0);\n Vec3 orientTHinH(0, 0, 0);\n PinJoint * torsoHindThigh = new PinJoint(\"hind_thigh\",\n *torso, locTHinT, orientTHinT, *hindThigh, locTHinH, orientTHinH);\n\n CoordinateSet & torsoHindThighCS = torsoHindThigh->upd_CoordinateSet();\n torsoHindThighCS[0].setName(\"hind_thigh_flexion\");\n double torsoHindThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoHindThighCS[0].setRange(torsoHindThighCS0range);\n\n \/\/ Hind thigh -> hind shank.\n \/\/ `````````````````````````\n Vec3 locHTSinT(thighLength, 0, 0);\n Vec3 orientHTSinT(0, 0, 0);\n Vec3 locHTSinS(0, 0, 0);\n Vec3 orientHTSinS(0, 0, 0);\n PinJoint * hindThighShank = new PinJoint(\"hind_shank\",\n *hindThigh, locHTSinT, orientHTSinT,\n *hindShank, locHTSinS, orientHTSinS);\n\n CoordinateSet & hindThighShankCS = hindThighShank->upd_CoordinateSet();\n hindThighShankCS[0].setName(\"hind_knee_extension\");\n double hindThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n hindThighShankCS[0].setRange(hindThighShankCS0range);\n\n \/\/ Torso -> front left thigh.\n \/\/ ``````````````````````````\n Vec3 locTFLinT(0.5 * torsoX, 0, -0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFLinT(0, 0, -0.5 * Pi);\n Vec3 locTFLinFL(0, 0, 0);\n Vec3 orientTFLinFL(0, 0, 0);\n PinJoint * torsoFrontLeftThigh = new PinJoint(\"front_left_thigh\",\n *torso, locTFLinT, orientTFLinT,\n *frontLeftThigh, locTFLinFL, orientTFLinFL);\n\n CoordinateSet & torsoFrontLeftThighCS =\n torsoFrontLeftThigh->upd_CoordinateSet();\n torsoFrontLeftThighCS[0].setName(\"front_left_thigh_flexion\");\n double torsoFrontLeftThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontLeftThighCS[0].setRange(torsoFrontLeftThighCS0range);\n\n \/\/ Front left thigh -> front left shank.\n \/\/ `````````````````````````````````````\n Vec3 locFLTSinT(thighLength, 0, 0);\n Vec3 orientFLTSinT(0, 0, 0);\n Vec3 locFLTSinS(0, 0, 0);\n Vec3 orientFLTSinS(0, 0, 0);\n PinJoint * frontLeftThighShank = new PinJoint(\"front_left_shank\",\n *frontLeftThigh, locFLTSinT, orientFLTSinT,\n *frontLeftShank, locFLTSinS, orientFLTSinS);\n\n CoordinateSet & frontLeftThighShankCS =\n frontLeftThighShank->upd_CoordinateSet();\n frontLeftThighShankCS[0].setName(\"front_left_knee_extension\");\n double frontLeftThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontLeftThighShankCS[0].setRange(frontLeftThighShankCS0range);\n\n \/\/ Torso -> front right thigh.\n \/\/ ```````````````````````````\n Vec3 locTFRinT(0.5 * torsoX, 0, 0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFRinT(0, 0, -0.5 * Pi);\n Vec3 locTFRinFR(0, 0, 0);\n Vec3 orientTFRinFR(0, 0, 0);\n PinJoint * torsoFrontRightThigh = new PinJoint(\"front_right_thigh\",\n *torso, locTFRinT, orientTFRinT,\n *frontRightThigh, locTFRinFR, orientTFRinFR);\n\n CoordinateSet & torsoFrontRightThighCS =\n torsoFrontRightThigh->upd_CoordinateSet();\n torsoFrontRightThighCS[0].setName(\"front_right_thigh_flexion\");\n double torsoFrontRightThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontRightThighCS[0].setRange(torsoFrontRightThighCS0range);\n\n \/\/ Front right thigh -> front right shank.\n \/\/ ```````````````````````````````````````\n Vec3 locFRTSinT(thighLength, 0, 0);\n Vec3 orientFRTSinT(0, 0, 0);\n Vec3 locFRTSinS(0, 0, 0);\n Vec3 orientFRTSinS(0, 0, 0);\n PinJoint * frontRightThighShank = new PinJoint(\"front_right_shank\",\n *frontRightThigh, locFRTSinT, orientFRTSinT,\n *frontRightShank, locFRTSinS, orientFRTSinS);\n\n CoordinateSet & frontRightThighShankCS =\n frontRightThighShank->upd_CoordinateSet();\n frontRightThighShankCS[0].setName(\"front_right_knee_extension\");\n double frontRightThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontRightThighShankCS[0].setRange(frontRightThighShankCS0range);\n\n \/\/ Add bodies to the model.\n \/\/ ------------------------\n \/\/ Now that we've define the joints.\n tripod.addBody(torso);\n tripod.addBody(hindThigh);\n tripod.addBody(hindShank);\n tripod.addBody(frontLeftThigh);\n tripod.addBody(frontLeftShank);\n tripod.addBody(frontRightThigh);\n tripod.addBody(frontRightShank);\n\n \/\/ Display geometry.\n \/\/ -----------------\n\n \/\/ Torso.\n \/\/ ``````\n DisplayGeometry * torsoDisplay = new DisplayGeometry(\"box.vtp\");\n torsoDisplay->setScaleFactors(\n Vec3(torsoX, torsoY, torsoZ));\n torso->updDisplayer()->updGeometrySet().adoptAndAppend(torsoDisplay);\n torso->updDisplayer()->setShowAxes(true);\n\n \/\/ Limbs.\n \/\/ ``````\n addCylinderDisplayGeometry(hindThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(hindShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontLeftThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontLeftShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontRightThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontRightShank, shankDiameter, shankLength);\n\n \/\/ Enforce joint limits on the legs.\n \/\/ ---------------------------------\n addThighCoordinateLimitForce(tripod, \"hind_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_left_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_right_thigh_flexion\");\n addShankCoordinateLimitForce(tripod, \"hind_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_left_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_right_knee_extension\");\n\n \/\/ Actuators.\n \/\/ ----------\n addCoordinateActuator(tripod, \"hind_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_left_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_right_thigh_flexion\");\n addCoordinateActuator(tripod, \"hind_knee_extension\");\n addCoordinateActuator(tripod, \"front_left_knee_extension\");\n addCoordinateActuator(tripod, \"front_right_knee_extension\");\n\n \/\/ Contact.\n \/\/ --------\n \/\/ So the tripod does not go through the ground.\n OpenSim::ContactHalfSpace * groundContact = new OpenSim::ContactHalfSpace(\n Vec3(0), Vec3(0.0, 0.0, -0.5 * Pi), ground);\n groundContact->setName(\"ground_contact\");\n tripod.addContactGeometry(groundContact);\n\n \/\/ Limbs.\n \/\/ ``````\n addContactGeometry(tripod, shankLength, hindShank, \"hind_foot_contact\");\n addContactGeometry(tripod, shankLength, frontLeftShank,\n \"front_left_foot_contact\");\n addContactGeometry(tripod, shankLength, frontRightShank,\n \"front_right_foot_contact\");\n\n \/\/ Print the model.\n tripod.print(\"tripod.osim\");\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"\n#include \n\nusing SimTK::Inertia;\nusing SimTK::Pi;\nusing SimTK::Vec3;\n\nusing OpenSim::Body;\nusing OpenSim::CoordinateSet;\nusing OpenSim::DisplayGeometry;\nusing OpenSim::Model;\nusing OpenSim::PinJoint;\n\n\/**\n * Creates an OpenSim model of a three-legged animal. The animal has only one\n * hind leg, centered mediolaterally.\n *\n * Axis orientations, in rough terms:\n * +x: direction of forward travel.\n * +y: up.\n * +z: out of the screen.\n * *\/\n\n\/** Helper functions. **\/\nvoid addCylinderDisplayGeometry(Body * body,\n const double & diam, const double & length)\n{\n DisplayGeometry * geom = new DisplayGeometry(\"cylinder.vtp\");\n SimTK::Rotation rot;\n \/\/ Rotate the cylinder's symmetry (Y) axis to align with the body's X axis:\n rot.setRotationFromAngleAboutZ(-0.5 * Pi);\n geom->setTransform(\n SimTK::Transform(rot, Vec3(0.5 * length, 0, 0)));\n\n geom->setScaleFactors(Vec3(0.5 * diam, length, 0.5 * diam));\n body->updDisplayer()->setShowAxes(true);\n body->updDisplayer()->updGeometrySet().adoptAndAppend(geom);\n};\n\nvoid addThighCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 90, 1.0E2, -90, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addShankCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 10, 1.0E2, -160, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nint main(int argc, char * argv[])\n{\n \/\/ Preliminaries.\n \/\/ --------------\n Model tripod;\n tripod.setName(\"tripod\");\n\n \/\/ Properties.\n \/\/ -----------\n \/\/ Lengths, in meters.\n double torsoX = 0.5;\n double torsoY = 0.1;\n double torsoZ = 0.3;\n double thighLength = 0.1;\n double thighDiameter = 0.07;\n double shankLength = 0.1;\n double shankDiameter = 0.05;\n\n \/\/ Masses, in kilograms.\n double torsoMass = 1.0;\n double thighMass = 1.0;\n double shankMass = 1.0;\n\n \/\/ Center of mass, in meters.\n \/\/ This really just chooses the origin of our bodies.\n Vec3 torsoCOM(0, 0, 0);\n \/\/ We choose the x direction to be the axis of the leg segments, with +x\n \/\/ pointing toward the ground.\n Vec3 thighCOM(0.5 * thighLength, 0, 0);\n Vec3 shankCOM(0.5 * shankLength, 0, 0);\n\n \/\/ Moments of inertia, in kilograms-meters^2.\n \/\/ These are about the center of mass of the body, expressed in the frame\n \/\/ of the body.\n Inertia torsoInertia = Inertia::brick(\n 0.5 * torsoX, 0.5 * torsoY, 0.5 * torsoZ);\n Inertia thighInertia = Inertia::cylinderAlongX(0.5 * thighDiameter,\n thighLength);\n Inertia shankInertia = Inertia::cylinderAlongX(0.5 * shankDiameter,\n shankLength);\n\n \/\/ Bodies.\n \/\/ -------\n Body * torso = new Body(\"torso\",\n torsoMass, torsoCOM, torsoInertia);\n Body * hindThigh = new Body(\"hind_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * hindShank = new Body(\"hind_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontLeftThigh = new Body(\"front_left_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontLeftShank = new Body(\"front_left_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontRightThigh = new Body(\"front_right_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontRightShank = new Body(\"front_right_shank\",\n shankMass, shankCOM, shankInertia);\n\n \/\/ Joints.\n \/\/ -------\n Body & ground = tripod.getGroundBody();\n\n \/\/ Ground -> Torso.\n \/\/ ````````````````\n \/\/ The torso has no constraints with respect to the ground.\n \/\/ By default, the tripod's feet are on the ground.\n Vec3 locGTinG(0, thighLength + shankLength, 0);\n Vec3 orientGTinG(0, 0, 0);\n Vec3 locGTinT(0, 0, 0);\n Vec3 orientGTinT(0, 0, 0);\n OpenSim::FreeJoint * groundTorso = new OpenSim::FreeJoint(\"torso\",\n ground, locGTinG, orientGTinG, *torso, locGTinT, orientGTinT);\n\n CoordinateSet & groundTorsoCS = groundTorso->upd_CoordinateSet();\n\n \/\/ Rotation about x.\n groundTorsoCS[0].setName(\"torso_rx\"); \n double groundTorsoCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[0].setRange(groundTorsoCS0range);\n\n groundTorsoCS[1].setName(\"torso_ry\"); \n double groundTorsoCS1range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[1].setRange(groundTorsoCS1range);\n\n groundTorsoCS[2].setName(\"torso_rz\"); \n double groundTorsoCS2range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[2].setRange(groundTorsoCS2range);\n\n \/\/ Translation in x.\n groundTorsoCS[3].setName(\"torso_tx\"); \n double groundTorsoCS3range[2] = {-1.0, 10.0};\n groundTorsoCS[3].setRange(groundTorsoCS3range);\n\n groundTorsoCS[4].setName(\"torso_ty\"); \n double groundTorsoCS4range[2] = {0.0, 2.0};\n groundTorsoCS[4].setRange(groundTorsoCS4range);\n\n groundTorsoCS[5].setName(\"torso_tz\"); \n double groundTorsoCS5range[2] = {-1.0, 1.0};\n groundTorsoCS[5].setRange(groundTorsoCS5range);\n\n \/\/ Torso -> hind thigh.\n \/\/ ````````````````````\n Vec3 locTHinT(-0.5 * torsoX, 0, 0);\n \/\/ By default, the leg is extended.\n Vec3 orientTHinT(0, 0, -0.5 * Pi);\n Vec3 locTHinH(0, 0, 0);\n Vec3 orientTHinH(0, 0, 0);\n PinJoint * torsoHindThigh = new PinJoint(\"hind_thigh\",\n *torso, locTHinT, orientTHinT, *hindThigh, locTHinH, orientTHinH);\n\n CoordinateSet & torsoHindThighCS = torsoHindThigh->upd_CoordinateSet();\n torsoHindThighCS[0].setName(\"hind_thigh_flexion\");\n double torsoHindThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoHindThighCS[0].setRange(torsoHindThighCS0range);\n\n \/\/ Hind thigh -> hind shank.\n \/\/ `````````````````````````\n Vec3 locHTSinT(thighLength, 0, 0);\n Vec3 orientHTSinT(0, 0, 0);\n Vec3 locHTSinS(0, 0, 0);\n Vec3 orientHTSinS(0, 0, 0);\n PinJoint * hindThighShank = new PinJoint(\"hind_shank\",\n *hindThigh, locHTSinT, orientHTSinT,\n *hindShank, locHTSinS, orientHTSinS);\n\n CoordinateSet & hindThighShankCS = hindThighShank->upd_CoordinateSet();\n hindThighShankCS[0].setName(\"hind_knee_extension\");\n double hindThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n hindThighShankCS[0].setRange(hindThighShankCS0range);\n\n \/\/ Torso -> front left thigh.\n \/\/ ``````````````````````````\n Vec3 locTFLinT(0.5 * torsoX, 0, -0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFLinT(0, 0, -0.5 * Pi);\n Vec3 locTFLinFL(0, 0, 0);\n Vec3 orientTFLinFL(0, 0, 0);\n PinJoint * torsoFrontLeftThigh = new PinJoint(\"front_left_thigh\",\n *torso, locTFLinT, orientTFLinT,\n *frontLeftThigh, locTFLinFL, orientTFLinFL);\n\n CoordinateSet & torsoFrontLeftThighCS =\n torsoFrontLeftThigh->upd_CoordinateSet();\n torsoFrontLeftThighCS[0].setName(\"front_left_thigh_flexion\");\n double torsoFrontLeftThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontLeftThighCS[0].setRange(torsoFrontLeftThighCS0range);\n\n \/\/ Front left thigh -> front left shank.\n \/\/ `````````````````````````````````````\n Vec3 locFLTSinT(thighLength, 0, 0);\n Vec3 orientFLTSinT(0, 0, 0);\n Vec3 locFLTSinS(0, 0, 0);\n Vec3 orientFLTSinS(0, 0, 0);\n PinJoint * frontLeftThighShank = new PinJoint(\"front_left_shank\",\n *frontLeftThigh, locFLTSinT, orientFLTSinT,\n *frontLeftShank, locFLTSinS, orientFLTSinS);\n\n CoordinateSet & frontLeftThighShankCS =\n frontLeftThighShank->upd_CoordinateSet();\n frontLeftThighShankCS[0].setName(\"front_left_knee_extension\");\n double frontLeftThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontLeftThighShankCS[0].setRange(frontLeftThighShankCS0range);\n\n \/\/ Torso -> front right thigh.\n \/\/ ```````````````````````````\n Vec3 locTFRinT(0.5 * torsoX, 0, 0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFRinT(0, 0, -0.5 * Pi);\n Vec3 locTFRinFR(0, 0, 0);\n Vec3 orientTFRinFR(0, 0, 0);\n PinJoint * torsoFrontRightThigh = new PinJoint(\"front_right_thigh\",\n *torso, locTFRinT, orientTFRinT,\n *frontRightThigh, locTFRinFR, orientTFRinFR);\n\n CoordinateSet & torsoFrontRightThighCS =\n torsoFrontRightThigh->upd_CoordinateSet();\n torsoFrontRightThighCS[0].setName(\"front_right_thigh_flexion\");\n double torsoFrontRightThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontRightThighCS[0].setRange(torsoFrontRightThighCS0range);\n\n \/\/ Front right thigh -> front right shank.\n \/\/ ```````````````````````````````````````\n Vec3 locFRTSinT(thighLength, 0, 0);\n Vec3 orientFRTSinT(0, 0, 0);\n Vec3 locFRTSinS(0, 0, 0);\n Vec3 orientFRTSinS(0, 0, 0);\n PinJoint * frontRightThighShank = new PinJoint(\"front_right_shank\",\n *frontRightThigh, locFRTSinT, orientFRTSinT,\n *frontRightShank, locFRTSinS, orientFRTSinS);\n\n CoordinateSet & frontRightThighShankCS =\n frontRightThighShank->upd_CoordinateSet();\n frontRightThighShankCS[0].setName(\"front_right_knee_extension\");\n double frontRightThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontRightThighShankCS[0].setRange(frontRightThighShankCS0range);\n\n \/\/ Add bodies to the model.\n \/\/ ------------------------\n \/\/ Now that we've define the joints.\n tripod.addBody(torso);\n tripod.addBody(hindThigh);\n tripod.addBody(hindShank);\n tripod.addBody(frontLeftThigh);\n tripod.addBody(frontLeftShank);\n tripod.addBody(frontRightThigh);\n tripod.addBody(frontRightShank);\n\n \/\/ Display geometry.\n \/\/ -----------------\n\n \/\/ Torso.\n \/\/ ``````\n DisplayGeometry * torsoDisplay = new DisplayGeometry(\"box.vtp\");\n torsoDisplay->setScaleFactors(\n Vec3(torsoX, torsoY, torsoZ));\n torso->updDisplayer()->updGeometrySet().adoptAndAppend(torsoDisplay);\n torso->updDisplayer()->setShowAxes(true);\n\n addCylinderDisplayGeometry(hindThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(hindShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontLeftThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontLeftShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontRightThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontRightShank, shankDiameter, shankLength);\n\n \/\/ Enforce joint limits on the legs.\n \/\/ ---------------------------------\n addThighCoordinateLimitForce(tripod, \"hind_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_left_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_right_thigh_flexion\");\n addShankCoordinateLimitForce(tripod, \"hind_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_left_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_right_knee_extension\");\n\n \/\/ Actuators.\n \/\/ ----------\n\n \/\/ Contact.\n \/\/ --------\n \/\/ So the tripod does not go through the ground.\n\n\n \/\/ Add actuators.\n \/\/ --------------\n tripod.print(\"tripod.osim\");\n\n return EXIT_SUCCESS;\n}\n\nAdd coordinate actuators.\n#include \n\nusing SimTK::Inertia;\nusing SimTK::Pi;\nusing SimTK::Vec3;\n\nusing OpenSim::Body;\nusing OpenSim::CoordinateSet;\nusing OpenSim::DisplayGeometry;\nusing OpenSim::Model;\nusing OpenSim::PinJoint;\n\n\/**\n * Creates an OpenSim model of a three-legged animal. The animal has only one\n * hind leg, centered mediolaterally.\n *\n * Axis orientations, in rough terms:\n * +x: direction of forward travel.\n * +y: up.\n * +z: out of the screen.\n * *\/\n\n\/** Helper functions. **\/\nvoid addCylinderDisplayGeometry(Body * body,\n const double & diam, const double & length)\n{\n DisplayGeometry * geom = new DisplayGeometry(\"cylinder.vtp\");\n SimTK::Rotation rot;\n \/\/ Rotate the cylinder's symmetry (Y) axis to align with the body's X axis:\n rot.setRotationFromAngleAboutZ(-0.5 * Pi);\n geom->setTransform(\n SimTK::Transform(rot, Vec3(0.5 * length, 0, 0)));\n\n geom->setScaleFactors(Vec3(0.5 * diam, length, 0.5 * diam));\n body->updDisplayer()->setShowAxes(true);\n body->updDisplayer()->updGeometrySet().adoptAndAppend(geom);\n};\n\nvoid addThighCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 90, 1.0E2, -90, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addShankCoordinateLimitForce(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateLimitForce * force = new OpenSim::CoordinateLimitForce(\n coord, 10, 1.0E2, -160, 1.0E2, 1.0E1, 2.0, false);\n\tmodel.addForce(force);\n};\n\nvoid addCoordinateActuator(Model & model, const std::string & coord)\n{\n OpenSim::CoordinateActuator * act = new OpenSim::CoordinateActuator(coord);\n act->setName(coord + \"_actuator\");\n act->setMinControl(-1000.0);\n act->setMaxControl(1000.0);\n model.addForce(act);\n};\n\nint main(int argc, char * argv[])\n{\n \/\/ Preliminaries.\n \/\/ --------------\n Model tripod;\n tripod.setName(\"tripod\");\n\n \/\/ Properties.\n \/\/ -----------\n \/\/ Lengths, in meters.\n double torsoX = 0.5;\n double torsoY = 0.1;\n double torsoZ = 0.3;\n double thighLength = 0.1;\n double thighDiameter = 0.07;\n double shankLength = 0.1;\n double shankDiameter = 0.05;\n\n \/\/ Masses, in kilograms.\n double torsoMass = 1.0;\n double thighMass = 1.0;\n double shankMass = 1.0;\n\n \/\/ Center of mass, in meters.\n \/\/ This really just chooses the origin of our bodies.\n Vec3 torsoCOM(0, 0, 0);\n \/\/ We choose the x direction to be the axis of the leg segments, with +x\n \/\/ pointing toward the ground.\n Vec3 thighCOM(0.5 * thighLength, 0, 0);\n Vec3 shankCOM(0.5 * shankLength, 0, 0);\n\n \/\/ Moments of inertia, in kilograms-meters^2.\n \/\/ These are about the center of mass of the body, expressed in the frame\n \/\/ of the body.\n Inertia torsoInertia = Inertia::brick(\n 0.5 * torsoX, 0.5 * torsoY, 0.5 * torsoZ);\n Inertia thighInertia = Inertia::cylinderAlongX(0.5 * thighDiameter,\n thighLength);\n Inertia shankInertia = Inertia::cylinderAlongX(0.5 * shankDiameter,\n shankLength);\n\n \/\/ Bodies.\n \/\/ -------\n Body * torso = new Body(\"torso\",\n torsoMass, torsoCOM, torsoInertia);\n Body * hindThigh = new Body(\"hind_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * hindShank = new Body(\"hind_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontLeftThigh = new Body(\"front_left_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontLeftShank = new Body(\"front_left_shank\",\n shankMass, shankCOM, shankInertia);\n Body * frontRightThigh = new Body(\"front_right_thigh\",\n thighMass, thighCOM, thighInertia);\n Body * frontRightShank = new Body(\"front_right_shank\",\n shankMass, shankCOM, shankInertia);\n\n \/\/ Joints.\n \/\/ -------\n Body & ground = tripod.getGroundBody();\n\n \/\/ Ground -> Torso.\n \/\/ ````````````````\n \/\/ The torso has no constraints with respect to the ground.\n \/\/ By default, the tripod's feet are on the ground.\n Vec3 locGTinG(0, thighLength + shankLength, 0);\n Vec3 orientGTinG(0, 0, 0);\n Vec3 locGTinT(0, 0, 0);\n Vec3 orientGTinT(0, 0, 0);\n OpenSim::FreeJoint * groundTorso = new OpenSim::FreeJoint(\"torso\",\n ground, locGTinG, orientGTinG, *torso, locGTinT, orientGTinT);\n\n CoordinateSet & groundTorsoCS = groundTorso->upd_CoordinateSet();\n\n \/\/ Rotation about x.\n groundTorsoCS[0].setName(\"torso_rx\"); \n double groundTorsoCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[0].setRange(groundTorsoCS0range);\n\n groundTorsoCS[1].setName(\"torso_ry\"); \n double groundTorsoCS1range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[1].setRange(groundTorsoCS1range);\n\n groundTorsoCS[2].setName(\"torso_rz\"); \n double groundTorsoCS2range[2] = {-0.5 * Pi, 0.5 * Pi};\n groundTorsoCS[2].setRange(groundTorsoCS2range);\n\n \/\/ Translation in x.\n groundTorsoCS[3].setName(\"torso_tx\"); \n double groundTorsoCS3range[2] = {-1.0, 10.0};\n groundTorsoCS[3].setRange(groundTorsoCS3range);\n\n groundTorsoCS[4].setName(\"torso_ty\"); \n double groundTorsoCS4range[2] = {0.0, 2.0};\n groundTorsoCS[4].setRange(groundTorsoCS4range);\n\n groundTorsoCS[5].setName(\"torso_tz\"); \n double groundTorsoCS5range[2] = {-1.0, 1.0};\n groundTorsoCS[5].setRange(groundTorsoCS5range);\n\n \/\/ Torso -> hind thigh.\n \/\/ ````````````````````\n Vec3 locTHinT(-0.5 * torsoX, 0, 0);\n \/\/ By default, the leg is extended.\n Vec3 orientTHinT(0, 0, -0.5 * Pi);\n Vec3 locTHinH(0, 0, 0);\n Vec3 orientTHinH(0, 0, 0);\n PinJoint * torsoHindThigh = new PinJoint(\"hind_thigh\",\n *torso, locTHinT, orientTHinT, *hindThigh, locTHinH, orientTHinH);\n\n CoordinateSet & torsoHindThighCS = torsoHindThigh->upd_CoordinateSet();\n torsoHindThighCS[0].setName(\"hind_thigh_flexion\");\n double torsoHindThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoHindThighCS[0].setRange(torsoHindThighCS0range);\n\n \/\/ Hind thigh -> hind shank.\n \/\/ `````````````````````````\n Vec3 locHTSinT(thighLength, 0, 0);\n Vec3 orientHTSinT(0, 0, 0);\n Vec3 locHTSinS(0, 0, 0);\n Vec3 orientHTSinS(0, 0, 0);\n PinJoint * hindThighShank = new PinJoint(\"hind_shank\",\n *hindThigh, locHTSinT, orientHTSinT,\n *hindShank, locHTSinS, orientHTSinS);\n\n CoordinateSet & hindThighShankCS = hindThighShank->upd_CoordinateSet();\n hindThighShankCS[0].setName(\"hind_knee_extension\");\n double hindThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n hindThighShankCS[0].setRange(hindThighShankCS0range);\n\n \/\/ Torso -> front left thigh.\n \/\/ ``````````````````````````\n Vec3 locTFLinT(0.5 * torsoX, 0, -0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFLinT(0, 0, -0.5 * Pi);\n Vec3 locTFLinFL(0, 0, 0);\n Vec3 orientTFLinFL(0, 0, 0);\n PinJoint * torsoFrontLeftThigh = new PinJoint(\"front_left_thigh\",\n *torso, locTFLinT, orientTFLinT,\n *frontLeftThigh, locTFLinFL, orientTFLinFL);\n\n CoordinateSet & torsoFrontLeftThighCS =\n torsoFrontLeftThigh->upd_CoordinateSet();\n torsoFrontLeftThighCS[0].setName(\"front_left_thigh_flexion\");\n double torsoFrontLeftThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontLeftThighCS[0].setRange(torsoFrontLeftThighCS0range);\n\n \/\/ Front left thigh -> front left shank.\n \/\/ `````````````````````````````````````\n Vec3 locFLTSinT(thighLength, 0, 0);\n Vec3 orientFLTSinT(0, 0, 0);\n Vec3 locFLTSinS(0, 0, 0);\n Vec3 orientFLTSinS(0, 0, 0);\n PinJoint * frontLeftThighShank = new PinJoint(\"front_left_shank\",\n *frontLeftThigh, locFLTSinT, orientFLTSinT,\n *frontLeftShank, locFLTSinS, orientFLTSinS);\n\n CoordinateSet & frontLeftThighShankCS =\n frontLeftThighShank->upd_CoordinateSet();\n frontLeftThighShankCS[0].setName(\"front_left_knee_extension\");\n double frontLeftThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontLeftThighShankCS[0].setRange(frontLeftThighShankCS0range);\n\n \/\/ Torso -> front right thigh.\n \/\/ ```````````````````````````\n Vec3 locTFRinT(0.5 * torsoX, 0, 0.5 * torsoZ);\n \/\/ By default, the leg is extended.\n Vec3 orientTFRinT(0, 0, -0.5 * Pi);\n Vec3 locTFRinFR(0, 0, 0);\n Vec3 orientTFRinFR(0, 0, 0);\n PinJoint * torsoFrontRightThigh = new PinJoint(\"front_right_thigh\",\n *torso, locTFRinT, orientTFRinT,\n *frontRightThigh, locTFRinFR, orientTFRinFR);\n\n CoordinateSet & torsoFrontRightThighCS =\n torsoFrontRightThigh->upd_CoordinateSet();\n torsoFrontRightThighCS[0].setName(\"front_right_thigh_flexion\");\n double torsoFrontRightThighCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n torsoFrontRightThighCS[0].setRange(torsoFrontRightThighCS0range);\n\n \/\/ Front right thigh -> front right shank.\n \/\/ ```````````````````````````````````````\n Vec3 locFRTSinT(thighLength, 0, 0);\n Vec3 orientFRTSinT(0, 0, 0);\n Vec3 locFRTSinS(0, 0, 0);\n Vec3 orientFRTSinS(0, 0, 0);\n PinJoint * frontRightThighShank = new PinJoint(\"front_right_shank\",\n *frontRightThigh, locFRTSinT, orientFRTSinT,\n *frontRightShank, locFRTSinS, orientFRTSinS);\n\n CoordinateSet & frontRightThighShankCS =\n frontRightThighShank->upd_CoordinateSet();\n frontRightThighShankCS[0].setName(\"front_right_knee_extension\");\n double frontRightThighShankCS0range[2] = {-0.5 * Pi, 0.5 * Pi};\n frontRightThighShankCS[0].setRange(frontRightThighShankCS0range);\n\n \/\/ Add bodies to the model.\n \/\/ ------------------------\n \/\/ Now that we've define the joints.\n tripod.addBody(torso);\n tripod.addBody(hindThigh);\n tripod.addBody(hindShank);\n tripod.addBody(frontLeftThigh);\n tripod.addBody(frontLeftShank);\n tripod.addBody(frontRightThigh);\n tripod.addBody(frontRightShank);\n\n \/\/ Display geometry.\n \/\/ -----------------\n\n \/\/ Torso.\n \/\/ ``````\n DisplayGeometry * torsoDisplay = new DisplayGeometry(\"box.vtp\");\n torsoDisplay->setScaleFactors(\n Vec3(torsoX, torsoY, torsoZ));\n torso->updDisplayer()->updGeometrySet().adoptAndAppend(torsoDisplay);\n torso->updDisplayer()->setShowAxes(true);\n\n addCylinderDisplayGeometry(hindThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(hindShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontLeftThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontLeftShank, shankDiameter, shankLength);\n addCylinderDisplayGeometry(frontRightThigh, thighDiameter, thighLength);\n addCylinderDisplayGeometry(frontRightShank, shankDiameter, shankLength);\n\n \/\/ Enforce joint limits on the legs.\n \/\/ ---------------------------------\n addThighCoordinateLimitForce(tripod, \"hind_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_left_thigh_flexion\");\n addThighCoordinateLimitForce(tripod, \"front_right_thigh_flexion\");\n addShankCoordinateLimitForce(tripod, \"hind_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_left_knee_extension\");\n addShankCoordinateLimitForce(tripod, \"front_right_knee_extension\");\n\n \/\/ Actuators.\n \/\/ ----------\n\n \/\/ Contact.\n \/\/ --------\n \/\/ So the tripod does not go through the ground.\n\n addCoordinateActuator(tripod, \"hind_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_left_thigh_flexion\");\n addCoordinateActuator(tripod, \"front_right_thigh_flexion\");\n addCoordinateActuator(tripod, \"hind_knee_extension\");\n addCoordinateActuator(tripod, \"front_left_knee_extension\");\n addCoordinateActuator(tripod, \"front_right_knee_extension\");\n\n \/\/ Print the model.\n tripod.print(\"tripod.osim\");\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"#define CATCH_CONFIG_MAIN\n#include \n\n#include \n\n#include \n\nclass CountAnimation: public Animation\n{\npublic:\n CountAnimation(int initialValue):\n currentValue(initialValue)\n {}\n\n virtual int nextValue(const int32_t) override\n {\n return currentValue++;\n }\n\n virtual int getCurrentValue() const override\n {\n return currentValue;\n }\n\n virtual bool isFinished() const override\n {\n return false;\n }\n\n virtual void reset(const int &initialValue) override\n {\n currentValue = initialValue;\n }\n\nprivate:\n int currentValue;\n};\n\nAnimationPtr makeCountMap(int initialValue)\n{\n return AnimationPtr(\n new Map(AnimationPtr(new CountAnimation(initialValue)),\n [](const int& x) { return x * 2; },\n [](const int& x) { return x \/ 2; }));\n}\n\nTEST_CASE(\"Map::nextValue should map the value the wrapped animation\", \"[map]\") {\n const std::array expected = { 0, 2, 4, 6, 8 };\n auto map = makeCountMap(0);\n\n for (int x: expected) {\n REQUIRE ( x == map->nextValue(10) );\n }\n\n for (size_t i = 0; i < 5; ++i) {\n REQUIRE ( 10 == map->getCurrentValue() );\n }\n}\nAdd UT for Map::isFinished() (#111)#define CATCH_CONFIG_MAIN\n#include \n\n#include \n\n#include \n\nclass CountAnimation: public Animation\n{\npublic:\n CountAnimation(int initialValue, int finalValue):\n m_finalValue(finalValue),\n m_currentValue(initialValue)\n {}\n\n virtual int nextValue(const int32_t) override\n {\n if (!isFinished()) {\n return m_currentValue++;\n } else {\n return getCurrentValue();\n }\n }\n\n virtual int getCurrentValue() const override\n {\n return m_currentValue;\n }\n\n virtual bool isFinished() const override\n {\n return m_currentValue >= m_finalValue;\n }\n\n virtual void reset(const int &initialValue) override\n {\n m_currentValue = initialValue;\n }\n\nprivate:\n const int m_finalValue;\n int m_currentValue;\n};\n\nAnimationPtr makeCountMap(int initialValue, int finalState)\n{\n return AnimationPtr(\n new Map(AnimationPtr(new CountAnimation(initialValue, finalState)),\n [](const int& x) { return x * 2; },\n [](const int& x) { return x \/ 2; }));\n}\n\nTEST_CASE(\"Map::nextValue() and Map::getCurrentValue() should map the value the wrapped animation\", \"[map]\") {\n const std::array expected = { 0, 2, 4, 6, 8 };\n auto map = makeCountMap(0, 100);\n\n for (int x: expected) {\n REQUIRE ( x == map->nextValue(10) );\n }\n\n for (size_t i = 0; i < 5; ++i) {\n REQUIRE ( 10 == map->getCurrentValue() );\n }\n}\n\nTEST_CASE(\"Map::isFinished() should be equal to isFinished() of the wrapped animation\", \"[map]\") {\n auto map = makeCountMap(0, 1);\n REQUIRE ( !map->isFinished() );\n REQUIRE ( 0 == map->nextValue(10) );\n REQUIRE ( map->isFinished() );\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"server.h\"\n#include \"stinger_net\/stinger_server_state.h\"\n\nextern \"C\" {\n#include \"stinger_core\/stinger.h\"\n#include \"stinger_core\/stinger_shared.h\"\n#include \"stinger_core\/xmalloc.h\"\n#include \"stinger_utils\/stinger_utils.h\"\n#include \"stinger_utils\/timer.h\"\n#include \"stinger_utils\/dimacs_support.h\"\n#include \"stinger_utils\/metisish_support.h\"\n#include \"stinger_utils\/json_support.h\"\n#include \"stinger_utils\/csv.h\"\n}\n\nusing namespace gt::stinger;\n\nstatic char * graph_name = NULL;\nstatic size_t graph_sz = 0;\nstatic struct stinger * S = NULL;\n\nint main(int argc, char *argv[])\n{\n StingerServerState & server_state = StingerServerState::get_server_state();\n\n \/* default global options *\/\n int port_names = 10101;\n int port_streams = port_names + 1;\n int port_algs = port_names + 2;\n int unleash_daemon = 0;\n\n graph_name = (char *) xmalloc (128*sizeof(char));\n sprintf(graph_name, \"\/stinger-default\");\n char * input_file = (char *) xmalloc (1024*sizeof(char));\n input_file[0] = '\\0';\n char * file_type = (char *) xmalloc (128*sizeof(char));\n file_type[0] = '\\0';\n int use_numerics = 0;\n\n \/* parse command line configuration *\/\n int opt = 0;\n while(-1 != (opt = getopt(argc, argv, \"a:s:p:b:n:i:t:1h?dkvc:f:\"))) {\n switch(opt) {\n case 'p': {\n\t\t port_names = atoi(optarg);\n\t\t} break;\n\n case 'a': {\n\t\t port_algs = atoi(optarg);\n\t\t} break;\n case 's': {\n\t\t port_streams = atoi(optarg);\n\t\t} break;\n\n case 'n': {\n\t\t strcpy (graph_name, optarg);\n\t\t} break;\n \n case 'k': {\n\t\t server_state.set_write_alg_data(true);\n\t\t} break;\n\n case 'v': {\n\t\t server_state.set_write_names(true);\n\t\t} break;\n\n case 'c': {\n\t\t server_state.set_history_cap(atol(optarg));\n\t\t} break;\n\n case 'f': {\n\t\t server_state.set_out_dir(optarg);\n\t\t} break;\n\n case 'i': {\n\t\t strcpy (input_file, optarg);\n\t\t} break;\n \n case 't': {\n\t\t strcpy (file_type, optarg);\n\t\t} break;\n\n case '1': {\n\t\t use_numerics = 1;\n\t\t} break;\n case 'd': {\n\t\t unleash_daemon = 1;\n\t\t} break;\n\n case '?':\n case 'h': {\n\t\t printf(\"Usage: %s\\n\"\n\t\t \" [-p port_names]\\n\"\n\t\t\t \" [-a port_algs]\\n\"\n\t\t\t \" [-s port_streams]\\n\"\n\t\t\t \" [-n graph_name]\\n\"\n\t\t\t \" [-i input_file_path]\\n\"\n\t\t\t \" [-t file_type]\\n\"\n\t\t\t \" [-1 (for numeric IDs)]\\n\"\n\t\t\t \" [-d daemon mode]\\n\"\n\t\t\t \" [-k write algorithm states to disk]\\n\"\n\t\t\t \" [-v write vertex name mapping to disk]\\n\"\n\t\t\t \" [-f output directory for vertex names, alg states]\\n\"\n\t\t\t \" [-c cap number of history files to keep per alg] \\n\", argv[0]);\n\t\t printf(\"Defaults:\\n\\tport_names: %d\\n\\tport_algs: %d\\n\\tport_streams: %d\\n\\tgraph_name: %s\\n\", port_names, port_algs, port_streams, graph_name);\n\t\t exit(0);\n\t\t} break;\n\n }\n }\n\n \/* print configuration to the terminal *\/\n printf(\"\\tName: %s\\n\", graph_name);\n\n \/* allocate the graph *\/\n struct stinger * S = stinger_shared_new(&graph_name);\n size_t graph_sz = S->length + sizeof(struct stinger);\n\n \/* load edges from disk (if applicable) *\/\n if (input_file[0] != '\\0')\n {\n printf(\"\\tReading...\");\n tic ();\n switch (file_type[0])\n {\n case 'b': {\n\t\t int64_t nv, ne;\n\t\t int64_t *off, *ind, *weight, *graphmem;\n\t\t snarf_graph (input_file, &nv, &ne, (int64_t**)&off,\n\t\t (int64_t**)&ind, (int64_t**)&weight, (int64_t**)&graphmem);\n\t\t stinger_set_initial_edges (S, nv, 0, off, ind, weight, NULL, NULL, 0);\n\t\t free(graphmem);\n\t\t} break; \/* STINGER binary *\/\n\n case 'c': {\n\t\t load_csv_graph (S, input_file, use_numerics);\n\t\t} break; \/* CSV *\/\n\n case 'd': {\n\t\t load_dimacs_graph (S, input_file);\n\t\t} break; \/* DIMACS *\/\n\n case 'm': {\n\t\t load_metisish_graph (S, input_file);\n\t\t} break;\n\n case 'g': {\n\t\t} break; \/* GML \/ GraphML \/ GEXF -- you pick *\/\n\n case 'j': {\n\t\t load_json_graph (S, input_file);\n\t\t} break; \/* JSON *\/\n\n case 'x': {\n\t\t} break; \/* XML *\/\n\n default:\t{\n\t\t printf(\"Unsupported file type.\\n\");\n\t\t exit(0);\n\t\t} break;\n }\n printf(\" (done: %lf s)\\n\", toc ());\n }\n\n\n printf(\"Graph created. Running stats...\");\n tic();\n printf(\"\\n\\tVertices: %ld\\n\\tEdges: %ld\\n\",\n stinger_num_active_vertices(S), stinger_total_edges(S));\n\n \/* consistency check *\/\n printf(\"\\tConsistency %ld\\n\", (long) stinger_consistency_check(S, S->max_nv));\n printf(\"\\tDone. %lf seconds\\n\", toc());\n\n \/* initialize the singleton members *\/\n server_state.set_stinger(S);\n server_state.set_stinger_loc(graph_name);\n server_state.set_stinger_sz(graph_sz);\n server_state.set_port(port_names, port_streams, port_algs);\n server_state.set_mon_stinger(graph_name, sizeof(stinger_t) + S->length);\n \n \/* we need a socket that can reply with the shmem name & size of the graph *\/\n pthread_t name_pid, batch_pid;\n \n \/* this thread will handle the shared memory name mapping *\/\n pthread_create (&name_pid, NULL, start_udp_graph_name_server, NULL);\n\n \/* this thread will handle the batch & alg servers *\/\n \/* TODO: bring the thread creation for the alg server to this level *\/\n pthread_create (&batch_pid, NULL, start_tcp_batch_server, NULL);\n\n if(unleash_daemon) {\n while(1) { sleep(10); }\n } else {\n printf(\"Press to shut down the server...\\n\");\n while (getchar() != 'q');\n }\n\n printf(\"Shutting down the name server...\"); fflush(stdout);\n int status;\n kill(name_pid, SIGTERM);\n waitpid(name_pid, &status, 0);\n printf(\" done.\\n\"); fflush(stdout);\n\n printf(\"Shutting down the batch server...\"); fflush(stdout);\n kill(batch_pid, SIGTERM);\n waitpid(batch_pid, &status, 0);\n printf(\" done.\\n\"); fflush(stdout);\n\n \/* clean up *\/\n stinger_shared_free(S, graph_name, graph_sz);\n shmunlink(graph_name);\n free(graph_name);\n\n \/* clean up algorithm data stores *\/\n for (size_t i = 0; i < server_state.get_num_algs(); i++) {\n StingerAlgState * alg_state = server_state.get_alg(i);\n const char * alg_data_loc = alg_state->data_loc.c_str();\n shmunlink(alg_data_loc);\n }\n\n return 0;\n}\nClean up after signals in the server.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"server.h\"\n#include \"stinger_net\/stinger_server_state.h\"\n\nextern \"C\" {\n#include \"stinger_core\/stinger.h\"\n#include \"stinger_core\/stinger_shared.h\"\n#include \"stinger_core\/xmalloc.h\"\n#include \"stinger_utils\/stinger_utils.h\"\n#include \"stinger_utils\/timer.h\"\n#include \"stinger_utils\/dimacs_support.h\"\n#include \"stinger_utils\/metisish_support.h\"\n#include \"stinger_utils\/json_support.h\"\n#include \"stinger_utils\/csv.h\"\n}\n\nusing namespace gt::stinger;\n\nstatic char * graph_name = NULL;\nstatic size_t graph_sz = 0;\nstatic struct stinger * S = NULL;\n\n\/* we need a socket that can reply with the shmem name & size of the graph *\/\nstatic pthread_t name_pid, batch_pid;\n\nstatic StingerServerState & server_state = StingerServerState::get_server_state();\n\nstatic void cleanup (void);\nextern \"C\" {\n static void sigterm_cleanup (int);\n}\n \nint main(int argc, char *argv[])\n{\n \/* default global options *\/\n int port_names = 10101;\n int port_streams = port_names + 1;\n int port_algs = port_names + 2;\n int unleash_daemon = 0;\n\n graph_name = (char *) xmalloc (128*sizeof(char));\n sprintf(graph_name, \"\/stinger-default\");\n char * input_file = (char *) xmalloc (1024*sizeof(char));\n input_file[0] = '\\0';\n char * file_type = (char *) xmalloc (128*sizeof(char));\n file_type[0] = '\\0';\n int use_numerics = 0;\n\n \/* parse command line configuration *\/\n int opt = 0;\n while(-1 != (opt = getopt(argc, argv, \"a:s:p:b:n:i:t:1h?dkvc:f:\"))) {\n switch(opt) {\n case 'p': {\n\t\t port_names = atoi(optarg);\n\t\t} break;\n\n case 'a': {\n\t\t port_algs = atoi(optarg);\n\t\t} break;\n case 's': {\n\t\t port_streams = atoi(optarg);\n\t\t} break;\n\n case 'n': {\n\t\t strcpy (graph_name, optarg);\n\t\t} break;\n \n case 'k': {\n\t\t server_state.set_write_alg_data(true);\n\t\t} break;\n\n case 'v': {\n\t\t server_state.set_write_names(true);\n\t\t} break;\n\n case 'c': {\n\t\t server_state.set_history_cap(atol(optarg));\n\t\t} break;\n\n case 'f': {\n\t\t server_state.set_out_dir(optarg);\n\t\t} break;\n\n case 'i': {\n\t\t strcpy (input_file, optarg);\n\t\t} break;\n \n case 't': {\n\t\t strcpy (file_type, optarg);\n\t\t} break;\n\n case '1': {\n\t\t use_numerics = 1;\n\t\t} break;\n case 'd': {\n\t\t unleash_daemon = 1;\n\t\t} break;\n\n case '?':\n case 'h': {\n\t\t printf(\"Usage: %s\\n\"\n\t\t \" [-p port_names]\\n\"\n\t\t\t \" [-a port_algs]\\n\"\n\t\t\t \" [-s port_streams]\\n\"\n\t\t\t \" [-n graph_name]\\n\"\n\t\t\t \" [-i input_file_path]\\n\"\n\t\t\t \" [-t file_type]\\n\"\n\t\t\t \" [-1 (for numeric IDs)]\\n\"\n\t\t\t \" [-d daemon mode]\\n\"\n\t\t\t \" [-k write algorithm states to disk]\\n\"\n\t\t\t \" [-v write vertex name mapping to disk]\\n\"\n\t\t\t \" [-f output directory for vertex names, alg states]\\n\"\n\t\t\t \" [-c cap number of history files to keep per alg] \\n\", argv[0]);\n\t\t printf(\"Defaults:\\n\\tport_names: %d\\n\\tport_algs: %d\\n\\tport_streams: %d\\n\\tgraph_name: %s\\n\", port_names, port_algs, port_streams, graph_name);\n\t\t exit(0);\n\t\t} break;\n\n }\n }\n\n \/* print configuration to the terminal *\/\n printf(\"\\tName: %s\\n\", graph_name);\n\n \/* allocate the graph *\/\n struct stinger * S = stinger_shared_new(&graph_name);\n size_t graph_sz = S->length + sizeof(struct stinger);\n\n \/* load edges from disk (if applicable) *\/\n if (input_file[0] != '\\0')\n {\n printf(\"\\tReading...\");\n tic ();\n switch (file_type[0])\n {\n case 'b': {\n\t\t int64_t nv, ne;\n\t\t int64_t *off, *ind, *weight, *graphmem;\n\t\t snarf_graph (input_file, &nv, &ne, (int64_t**)&off,\n\t\t (int64_t**)&ind, (int64_t**)&weight, (int64_t**)&graphmem);\n\t\t stinger_set_initial_edges (S, nv, 0, off, ind, weight, NULL, NULL, 0);\n\t\t free(graphmem);\n\t\t} break; \/* STINGER binary *\/\n\n case 'c': {\n\t\t load_csv_graph (S, input_file, use_numerics);\n\t\t} break; \/* CSV *\/\n\n case 'd': {\n\t\t load_dimacs_graph (S, input_file);\n\t\t} break; \/* DIMACS *\/\n\n case 'm': {\n\t\t load_metisish_graph (S, input_file);\n\t\t} break;\n\n case 'g': {\n\t\t} break; \/* GML \/ GraphML \/ GEXF -- you pick *\/\n\n case 'j': {\n\t\t load_json_graph (S, input_file);\n\t\t} break; \/* JSON *\/\n\n case 'x': {\n\t\t} break; \/* XML *\/\n\n default:\t{\n\t\t printf(\"Unsupported file type.\\n\");\n\t\t exit(0);\n\t\t} break;\n }\n printf(\" (done: %lf s)\\n\", toc ());\n }\n\n\n printf(\"Graph created. Running stats...\");\n tic();\n printf(\"\\n\\tVertices: %ld\\n\\tEdges: %ld\\n\",\n stinger_num_active_vertices(S), stinger_total_edges(S));\n\n \/* consistency check *\/\n printf(\"\\tConsistency %ld\\n\", (long) stinger_consistency_check(S, S->max_nv));\n printf(\"\\tDone. %lf seconds\\n\", toc());\n\n \/* initialize the singleton members *\/\n server_state.set_stinger(S);\n server_state.set_stinger_loc(graph_name);\n server_state.set_stinger_sz(graph_sz);\n server_state.set_port(port_names, port_streams, port_algs);\n server_state.set_mon_stinger(graph_name, sizeof(stinger_t) + S->length);\n \n \/* this thread will handle the shared memory name mapping *\/\n pthread_create (&name_pid, NULL, start_udp_graph_name_server, NULL);\n\n \/* this thread will handle the batch & alg servers *\/\n \/* TODO: bring the thread creation for the alg server to this level *\/\n pthread_create (&batch_pid, NULL, start_tcp_batch_server, NULL);\n\n {\n struct sigaction sa;\n sa.sa_flags = 0;\n sigemptyset (&sa.sa_mask);\n sa.sa_handler = sigterm_cleanup;\n \/* Ignore the old handlers. *\/\n sigaction (SIGINT, &sa, NULL);\n sigaction (SIGTERM, &sa, NULL);\n sigaction (SIGHUP, &sa, NULL);\n }\n\n if(unleash_daemon) {\n while(1) { sleep(10); }\n } else {\n printf(\"Press to shut down the server...\\n\");\n while (getchar() != 'q');\n }\n\n cleanup ();\n\n return 0;\n}\n\nvoid\ncleanup (void)\n{\n printf(\"Shutting down the name server...\"); fflush(stdout);\n int status;\n kill(name_pid, SIGTERM);\n waitpid(name_pid, &status, 0);\n printf(\" done.\\n\"); fflush(stdout);\n\n printf(\"Shutting down the batch server...\"); fflush(stdout);\n kill(batch_pid, SIGTERM);\n waitpid(batch_pid, &status, 0);\n printf(\" done.\\n\"); fflush(stdout);\n\n \/* clean up *\/\n stinger_shared_free(S, graph_name, graph_sz);\n shmunlink(graph_name);\n free(graph_name);\n\n \/* clean up algorithm data stores *\/\n for (size_t i = 0; i < server_state.get_num_algs(); i++) {\n StingerAlgState * alg_state = server_state.get_alg(i);\n const char * alg_data_loc = alg_state->data_loc.c_str();\n shmunlink(alg_data_loc);\n }\n}\n\nvoid\nsigterm_cleanup (int)\n{\n cleanup ();\n exit (EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"#include \"boost_test.h\"\n#include \"ComplexFixedPoint.h\"\n#include \n\nusing namespace std;\n\n\nBOOST_AUTO_TEST_CASE( CFxpAccessors )\n{\n\tCFxp a(1, 2, 8);\n\n\tBOOST_CHECK_EQUAL(a.real(), 1);\n\tBOOST_CHECK_EQUAL(a.imag(), 2);\n\tBOOST_CHECK_EQUAL(a.width(), 8);\n\tBOOST_CHECK_EQUAL(a.minVal(), -128);\n\tBOOST_CHECK_EQUAL(a.maxVal(), 127);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpAssignment )\n{\n\tCFxp a(1, 2, 8);\n\tCFxp b(1, 2, 10);\n\tCFxp c;\n\tCFxp d(1, 2, 8, true);\n\tCFxp e(1, 2, 8, false);\n\n\tBOOST_CHECK_THROW(a = b, SizeMismatchException);\n\tBOOST_CHECK_NO_THROW(c = a);\n\tBOOST_CHECK_EQUAL(c, a);\n\tBOOST_CHECK_NO_THROW(d = b);\n\tBOOST_CHECK_EQUAL(d, b);\n\tBOOST_CHECK_THROW(e = b, SizeMismatchException);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpEquality )\n{\n\tCFxp a(1, 2, 8);\n\tCFxp b(1, 2, 8);\n\tCFxp c(1, 2, 10);\n\tCFxp d(13, 2, 8);\n\tCFxp e(1, 13, 8);\n\tCFxp f(24, 38, 21);\n\n\t\/* same object as lhs and rhs *\/\n\tBOOST_CHECK_EQUAL(a == a, true);\n\tBOOST_CHECK_EQUAL(a != a, false);\n\n\t\/* different equal objects *\/\n\tBOOST_CHECK_EQUAL(a == b, true);\n\tBOOST_CHECK_EQUAL(a != b, false);\n\n\t\/* same value, different widths *\/\n\tBOOST_CHECK_EQUAL(a == c, false);\n\tBOOST_CHECK_EQUAL(a != c, true);\n\n\t\/* different values, same widths *\/\n\tBOOST_CHECK_EQUAL(a == d, false);\n\tBOOST_CHECK_EQUAL(a != d, true);\n\tBOOST_CHECK_EQUAL(a == e, false);\n\tBOOST_CHECK_EQUAL(a != e, true);\n\n\t\/* everything different *\/\n\tBOOST_CHECK_EQUAL(a == f, false);\n\tBOOST_CHECK_EQUAL(a != f, true);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpScalarMultiplication )\n{\n\tCFxp a(1, 2, 8);\n\tFxp b(2, 5);\n\n\t\/* multiplication by scalar is commutative *\/\n\tBOOST_CHECK_EQUAL(a * b, b * a);\n\n\t\/* width after multiplication by scalar *\/\n\tBOOST_CHECK_EQUAL((a * b).width(), 13);\n\n\t\/* result check *\/\n\tBOOST_CHECK_EQUAL(a * b, CFxp(2, 4, 13));\n}\nAdded unit tests for CFxp addition operator#include \"boost_test.h\"\n#include \"ComplexFixedPoint.h\"\n#include \n\nusing namespace std;\n\n\nBOOST_AUTO_TEST_CASE( CFxpAccessors )\n{\n\tCFxp a(1, 2, 8);\n\n\tBOOST_CHECK_EQUAL(a.real(), 1);\n\tBOOST_CHECK_EQUAL(a.imag(), 2);\n\tBOOST_CHECK_EQUAL(a.width(), 8);\n\tBOOST_CHECK_EQUAL(a.minVal(), -128);\n\tBOOST_CHECK_EQUAL(a.maxVal(), 127);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpAssignment )\n{\n\tCFxp a(1, 2, 8);\n\tCFxp b(1, 2, 10);\n\tCFxp c;\n\tCFxp d(1, 2, 8, true);\n\tCFxp e(1, 2, 8, false);\n\n\tBOOST_CHECK_THROW(a = b, SizeMismatchException);\n\tBOOST_CHECK_NO_THROW(c = a);\n\tBOOST_CHECK_EQUAL(c, a);\n\tBOOST_CHECK_NO_THROW(d = b);\n\tBOOST_CHECK_EQUAL(d, b);\n\tBOOST_CHECK_THROW(e = b, SizeMismatchException);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpEquality )\n{\n\tCFxp a(1, 2, 8);\n\tCFxp b(1, 2, 8);\n\tCFxp c(1, 2, 10);\n\tCFxp d(13, 2, 8);\n\tCFxp e(1, 13, 8);\n\tCFxp f(24, 38, 21);\n\n\t\/* same object as lhs and rhs *\/\n\tBOOST_CHECK_EQUAL(a == a, true);\n\tBOOST_CHECK_EQUAL(a != a, false);\n\n\t\/* different equal objects *\/\n\tBOOST_CHECK_EQUAL(a == b, true);\n\tBOOST_CHECK_EQUAL(a != b, false);\n\n\t\/* same value, different widths *\/\n\tBOOST_CHECK_EQUAL(a == c, false);\n\tBOOST_CHECK_EQUAL(a != c, true);\n\n\t\/* different values, same widths *\/\n\tBOOST_CHECK_EQUAL(a == d, false);\n\tBOOST_CHECK_EQUAL(a != d, true);\n\tBOOST_CHECK_EQUAL(a == e, false);\n\tBOOST_CHECK_EQUAL(a != e, true);\n\n\t\/* everything different *\/\n\tBOOST_CHECK_EQUAL(a == f, false);\n\tBOOST_CHECK_EQUAL(a != f, true);\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpScalarMultiplication )\n{\n\tCFxp a(1, 2, 8);\n\tFxp b(2, 5);\n\n\t\/* multiplication by scalar is commutative *\/\n\tBOOST_CHECK_EQUAL(a * b, b * a);\n\n\t\/* width after multiplication by scalar *\/\n\tBOOST_CHECK_EQUAL((a * b).width(), 13);\n\n\t\/* result check *\/\n\tBOOST_CHECK_EQUAL(a * b, CFxp(2, 4, 13));\n}\n\n\nBOOST_AUTO_TEST_CASE( CFxpAddition )\n{\n\tCFxp a(1, 2, 8);\n\tCFxp b(2, 5, 5);\n\n\t\/* addition is commutative *\/\n\tBOOST_CHECK_EQUAL(a + b, b + a);\n\n\t\/* width after addition *\/\n\tBOOST_CHECK_EQUAL((a + b).width(), 9);\n\n\t\/* result check *\/\n\tBOOST_CHECK_EQUAL(a + b, CFxp(3, 7, 9));\n}\n<|endoftext|>"} {"text":"\/*\n * BasicButton.cpp\n * openFrameworks\n *\n * Created by Matthias Rohrbach on 26.10.09.\n * Copyright 2009 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"BasicButton.h\"\n\n\n\nBasicButton::BasicButton() {\n\tisEnabled\t\t= true;\n\t_isSelected\t\t= false;\n\thasActiveimage\t= false;\t\n\t_isScalingImage = false;\n\t\n\ttemp\t\t\t= NULL;\n\tnormal\t\t\t= NULL;\n\tselected\t\t= NULL;\n\tdisabled\t\t= NULL;\n\tactive\t\t\t= NULL;\n\tcurrentImage\t= NULL;\n}\n\n\nvoid BasicButton::onFirstTouchDown(MultiTouchEvent& _event){\n\tif (isEnabled) {\n\t\tif(hasActiveimage){\n\t\t\tcurrentImage = active;\n\t\t}\n\t\tofNotifyEvent(pressEvent, myEventArgs, this);\n\t}\n}\n\nvoid BasicButton::onLastTouchUp(MultiTouchEvent& _event){\n\tif (isEnabled) {\n\t\tcurrentImage = temp;\n\t\tofNotifyEvent(releaseEvent, myEventArgs, this);\n\t}\n}\n\n\nvoid BasicButton::_draw(){\n\tif(normal == NULL){\n\t\tofRect(0,0,width,height);\n\t}\n\tif (currentImage != NULL) {\n\t\tif (_isScalingImage) {\n\t\t\tcurrentImage->draw(0,0,width, height);\n\t\t} else {\n\t\t\tcurrentImage->draw((width - currentImage->getWidth()) *.5,\n\t\t\t\t\t\t\t (height - currentImage->getHeight())*.5);\n\t\t}\n\n\t}\n}\n\n\nvoid BasicButton::setImage(ofImage* _normal, ofImage* _selected, ofImage* _active, ofImage* _disabled){\n\t\n\tnormal\t\t= _normal;\n\tselected\t= _selected;\n\n\tif(selected == NULL){\n\t\tselected\t= normal;\n\t}\n\t\n\tactive\t= _active;\n\t\n\thasActiveimage\t= true;\n\tif(active == NULL){\n\t\tactive\t\t\t= normal;\n\t\thasActiveimage\t= false;\n\t}\n\n\tdisabled=_disabled;\n\tif(disabled==NULL){\n\t\tdisabled\t= normal;\n\t}\n\ttemp\t\t\t= normal;\n currentImage\t= normal;\n}\n\nvoid BasicButton::toggle(){\n\tif(_isSelected){\n\t\tdeselect();\n\t}else{\n\t\tselect();\n\t}\n}\n\nbool BasicButton::isSelected(){\n\treturn _isSelected;\n}\n\nvoid BasicButton::select(){\n\tif(_isSelected || !isEnabled)return;\n\t_isSelected\t\t= true;\n\ttemp\t\t\t= selected;\n\tcurrentImage\t= selected;\n}\n\nvoid BasicButton::deselect(){\n\tif(!_isSelected || !isEnabled)return;\n\t_isSelected\t\t= false;\n\ttemp\t\t\t= normal;\n\tcurrentImage\t= normal;\n}\n\nvoid BasicButton::disable(){\n\tif (!isEnabled) return;\n\tisEnabled\t\t= false;\n\t_isSelected\t\t= false;\n\ttemp\t\t\t= disabled;\n\tcurrentImage\t= disabled;\n}\n\nvoid BasicButton::enable(){\n\tif (isEnabled) return;\n\tisEnabled\t\t= true;\n\ttemp\t\t\t= normal;\n\tcurrentImage\t= normal;\n}Todo-comments. problems with alpha-blending...\/*\n * BasicButton.cpp\n * openFrameworks\n *\n * Created by Matthias Rohrbach on 26.10.09.\n * Copyright 2009 __MyCompanyName__. All rights reserved.\n *\n *\/\n\n#include \"BasicButton.h\"\n\n\n\nBasicButton::BasicButton() {\n\tisEnabled\t\t= true;\n\t_isSelected\t\t= false;\n\thasActiveimage\t= false;\t\n\t_isScalingImage = false;\n\t\n\ttemp\t\t\t= NULL;\n\tnormal\t\t\t= NULL;\n\tselected\t\t= NULL;\n\tdisabled\t\t= NULL;\n\tactive\t\t\t= NULL;\n\tcurrentImage\t= NULL;\n}\n\n\nvoid BasicButton::onFirstTouchDown(MultiTouchEvent& _event){\n\tif (isEnabled) {\n\t\tif(hasActiveimage){\n\t\t\tcurrentImage = active;\n\t\t}\n\t\tofNotifyEvent(pressEvent, myEventArgs, this);\n\t}\n}\n\nvoid BasicButton::onLastTouchUp(MultiTouchEvent& _event){\n\tif (isEnabled) {\n\t\tcurrentImage = temp;\n\t\tofNotifyEvent(releaseEvent, myEventArgs, this);\n\t}\n}\n\n\nvoid BasicButton::_draw(){\n\tif(normal == NULL){\n\t\tofRect(0,0,width,height);\n\t}\n\t\n\tif (currentImage != NULL) {\n\t\t\/\/ofSetColor(color.r, color.g, color.b, 0);\t\/\/ TODO: strange stuff with alpha\n\t\tif (_isScalingImage) {\n\t\t\tcurrentImage->draw(0,0,width, height);\n\t\t} else {\n\t\t\tcurrentImage->draw((width - currentImage->getWidth()) *.5,\n\t\t\t\t\t\t\t (height - currentImage->getHeight())*.5);\n\t\t}\n\t}\n}\n\n\nvoid BasicButton::setImage(ofImage* _normal, ofImage* _selected, ofImage* _active, ofImage* _disabled){\n\t\n\tnormal\t\t= _normal;\n\tselected\t= _selected;\n\n\tif(selected == NULL){\n\t\tselected\t= normal;\n\t}\n\t\n\tactive\t= _active;\n\t\n\thasActiveimage\t= true;\n\tif(active == NULL){\n\t\tactive\t\t\t= normal;\n\t\thasActiveimage\t= false;\n\t}\n\n\tdisabled=_disabled;\n\tif(disabled==NULL){\n\t\tdisabled\t= normal;\n\t}\n\ttemp\t\t\t= normal;\n currentImage\t= normal;\n}\n\nvoid BasicButton::toggle(){\n\tif(_isSelected){\n\t\tdeselect();\n\t}else{\n\t\tselect();\n\t}\n}\n\nbool BasicButton::isSelected(){\n\treturn _isSelected;\n}\n\nvoid BasicButton::select(){\n\tif(_isSelected || !isEnabled)return;\n\t_isSelected\t\t= true;\n\ttemp\t\t\t= selected;\n\tcurrentImage\t= selected;\n}\n\nvoid BasicButton::deselect(){\n\tif(!_isSelected || !isEnabled)return;\n\t_isSelected\t\t= false;\n\ttemp\t\t\t= normal;\n\tcurrentImage\t= normal;\n}\n\nvoid BasicButton::disable(){\n\tif (!isEnabled) return;\n\tisEnabled\t\t= false;\n\t_isSelected\t\t= false;\n\ttemp\t\t\t= disabled;\n\tcurrentImage\t= disabled;\n}\n\nvoid BasicButton::enable(){\n\tif (isEnabled) return;\n\tisEnabled\t\t= true;\n\ttemp\t\t\t= normal;\n\tcurrentImage\t= normal;\n}<|endoftext|>"} {"text":"\/* This file is part of the KDE project.\n\nCopyright (C) 2008 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#include \"backend.h\"\n#include \"backendnode.h\"\n\n#include \"audiooutput.h\"\n#include \"effect.h\"\n#include \"mediaobject.h\"\n#include \"videowidget.h\"\n#include \"volumeeffect.h\"\n\n\/\/windows specific (DirectX Media Object)\n#include \n\n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nQ_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend);\n\nnamespace Phonon\n{\n namespace DS9\n {\n bool Backend::AudioMoniker::operator==(const AudioMoniker &other)\n {\n return other->IsEqual(*this) == S_OK;\n }\n\n\n Backend::Backend(QObject *parent, const QVariantList &)\n : QObject(parent)\n {\n\t\t\t::CoInitialize(0);\n\n \/\/registering meta types\n qRegisterMetaType(\"HRESULT\");\n qRegisterMetaType(\"Graph\");\n }\n\n Backend::~Backend()\n {\n m_audioOutputs.clear();\n m_audioEffects.clear();\n\t\t\t::CoUninitialize();\n }\n\n QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList &args)\n {\n switch (c)\n {\n case MediaObjectClass:\n return new MediaObject(parent);\n case AudioOutputClass:\n return new AudioOutput(this, parent);\n#ifndef QT_NO_PHONON_EFFECT\n case EffectClass:\n return new Effect(m_audioEffects[ args[0].toInt() ], parent);\n#endif \/\/QT_NO_PHONON_EFFECT\n#ifndef QT_NO_PHONON_VIDEO\n case VideoWidgetClass:\n return new VideoWidget(qobject_cast(parent));\n#endif \/\/QT_NO_PHONON_VIDEO\n#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT\n case VolumeFaderEffectClass:\n return new VolumeEffect(parent);\n#endif \/\/QT_NO_PHONON_VOLUMEFADEREFFECT\n default:\n return 0;\n }\n }\n\n bool Backend::supportsVideo() const\n {\n#ifndef QT_NO_PHONON_VIDEO\n return true;\n#else\n return false;\n#endif \/\/QT_NO_PHONON_VIDEO\n }\n\n QStringList Backend::availableMimeTypes() const\n {\n QStringList ret;\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\mplayer2\\\\mime types\"), QSettings::NativeFormat);\n ret += settings.childGroups();\n }\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\wmplayer\\\\mime types\"), QSettings::NativeFormat);\n ret += settings.childGroups();\n }\n\n ret.removeDuplicates();\n ret.replaceInStrings(\"\\\\\", \"\/\");\n qSort(ret);\n return ret;\n }\n\n\t\tFilter Backend::getAudioOutputFilter(int index) const\n\t\t{\n\t\t\tFilter ret;\n\t\t\tif (index >= 0 && index < m_audioOutputs.count()) {\n\t\t\t\tm_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast(&ret));\n\t\t\t} else {\n\t\t\t\t\/\/just return the default audio renderer (not directsound)\n\t\t\t\tret = Filter(CLSID_AudioRender, IID_IBaseFilter);\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\n QList Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const\n {\n QList ret;\n\n switch(type)\n {\n case Phonon::AudioOutputDeviceType:\n {\n#ifdef Q_OS_WINCE\n\t\t\t\t\tret << 0; \/\/ only one audio device with index 0\n#else\n\t\t\t\t\tComPointer devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum);\n\t\t\t\t\tif (!devEnum) {\n\t\t\t\t\t\treturn ret; \/\/it is impossible to enumerate the devices\n\t\t\t\t\t}\n ComPointer enumMon;\n HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0);\n if (FAILED(hr)) {\n break;\n }\n AudioMoniker mon;\n\n \/\/let's reorder the devices so that directshound appears first\n int nbds = 0; \/\/number of directsound devices\n\n while (S_OK == enumMon->Next(1, mon.pparam(), 0)) {\n LPOLESTR str = 0;\n mon->GetDisplayName(0,0,&str);\n const QString name = QString::fromUtf16((unsigned short*)str);\n\t\t\t\t\t\tComPointer alloc;\n\t\t\t\t\t\t::CoGetMalloc(1, alloc.pparam());\n alloc->Free(str);\n\n int insert_pos = 0;\n if (!m_audioOutputs.contains(mon)) {\n insert_pos = m_audioOutputs.count();\n m_audioOutputs.append(mon);\n } else {\n insert_pos = m_audioOutputs.indexOf(mon);\n }\n\n if (name.contains(QLatin1String(\"DirectSound\"))) {\n ret.insert(nbds++, insert_pos);\n } else {\n ret.append(insert_pos);\n }\n }\n#endif\n\t\t\t\t\tbreak;\n }\n#ifndef QT_NO_PHONON_EFFECT\n case Phonon::EffectType:\n {\n m_audioEffects.clear();\n ComPointer enumDMO;\n HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam());\n if (SUCCEEDED(hr)) {\n CLSID clsid;\n while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) {\n ret += m_audioEffects.count();\n m_audioEffects.append(clsid);\n }\n }\n break;\n }\n break;\n#endif \/\/QT_NO_PHONON_EFFECT\n default:\n break;\n }\n\t\t\treturn ret;\n }\n\n QHash Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const\n {\n QHash ret;\n switch (type)\n {\n case Phonon::AudioOutputDeviceType:\n {\n#ifdef Q_OS_WINCE\n\t\t\t\t\tret[\"name\"] = QLatin1String(\"default audio device\");\n#else\n const AudioMoniker &mon = m_audioOutputs[index];\n LPOLESTR str = 0;\n HRESULT hr = mon->GetDisplayName(0,0, &str);\n if (SUCCEEDED(hr)) {\n QString name = QString::fromUtf16((unsigned short*)str); \n\t\t\t\t\t\tComPointer alloc;\n\t\t\t\t\t\t::CoGetMalloc(1, alloc.pparam());\n alloc->Free(str);\n ret[\"name\"] = name.mid(name.indexOf('\\\\') + 1);\n\t\t\t\t\t}\n#endif\n }\n break;\n#ifndef QT_NO_PHONON_EFFECT\n case Phonon::EffectType:\n {\n WCHAR name[80]; \/\/ 80 is clearly stated in the MSDN doc\n HRESULT hr = ::DMOGetName(m_audioEffects[index], name);\n if (SUCCEEDED(hr)) {\n ret[\"name\"] = QString::fromUtf16((unsigned short*)name);\n }\n }\n break;\n#endif \/\/QT_NO_PHONON_EFFECT\n default:\n break;\n }\n\t\t\treturn ret;\n }\n\n bool Backend::endConnectionChange(QSet objects)\n {\n if (objects.isEmpty())\n return true;\n \/\/end of a transaction\n for(QSet::const_iterator it = objects.begin(); it != objects.end(); ++it) {\n if (BackendNode *node = qobject_cast(*it)) {\n MediaObject *mo = node->mediaObject();\n if (mo) {\n switch(mo->transactionState)\n {\n case Phonon::ErrorState:\n case Phonon::StoppedState:\n case Phonon::LoadingState:\n \/\/nothing to do\n break;\n case Phonon::PausedState:\n mo->pause();\n break;\n default:\n mo->play();\n break;\n }\n\n return mo->state() != Phonon::ErrorState;\n }\n }\n }\n\n return false;\n }\n\n\n bool Backend::startConnectionChange(QSet objects)\n {\n if (objects.isEmpty())\n return true;\n\n \/\/let's save the state of the graph (before we stop it)\n for(QSet::const_iterator it = objects.begin(); it != objects.end(); ++it) {\n if (BackendNode *node = qobject_cast(*it)) {\n if (MediaObject *mo = node->mediaObject()) {\n if (mo->state() != Phonon::StoppedState) {\n mo->transactionState = mo->state();\n mo->ensureStopped(); \/\/we have to stop the graph..\n }\n return true;\n }\n }\n }\n\n return false;\n }\n\n bool Backend::connectNodes(QObject *_source, QObject *_sink)\n {\n BackendNode *source = qobject_cast(_source);\n if (!source) {\n return false;\n }\n BackendNode *sink = qobject_cast(_sink);\n if (!sink) {\n return false;\n }\n\n \/\/setting the graph if needed\n if (source->mediaObject() == 0 && sink->mediaObject() == 0) {\n \/\/error: no graph selected\n return false;\n } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) {\n \/\/this' graph becomes the common one\n source->mediaObject()->grabNode(sink);\n } else if (source->mediaObject() == 0) {\n \/\/sink's graph becomes the common one\n sink->mediaObject()->grabNode(source);\n }\n\n return source->mediaObject()->connectNodes(source, sink);\n }\n\n bool Backend::disconnectNodes(QObject *_source, QObject *_sink)\n {\n BackendNode *source = qobject_cast(_source);\n if (!source) {\n return false;\n }\n BackendNode *sink = qobject_cast(_sink);\n if (!sink) {\n return false;\n }\n\n return source->mediaObject() == 0 ||\n source->mediaObject()->disconnectNodes(source, sink);\n }\n }\n}\n\nQT_END_NAMESPACE\n\n#include \"moc_backend.cpp\"\nqt4.4 compile++\/* This file is part of the KDE project.\n\nCopyright (C) 2008 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#include \"backend.h\"\n#include \"backendnode.h\"\n\n#include \"audiooutput.h\"\n#include \"effect.h\"\n#include \"mediaobject.h\"\n#include \"videowidget.h\"\n#include \"volumeeffect.h\"\n\n\/\/windows specific (DirectX Media Object)\n#include \n\n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nQ_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend);\n\nnamespace Phonon\n{\n namespace DS9\n {\n bool Backend::AudioMoniker::operator==(const AudioMoniker &other)\n {\n return other->IsEqual(*this) == S_OK;\n }\n\n\n Backend::Backend(QObject *parent, const QVariantList &)\n : QObject(parent)\n {\n\t\t\t::CoInitialize(0);\n\n \/\/registering meta types\n qRegisterMetaType(\"HRESULT\");\n qRegisterMetaType(\"Graph\");\n }\n\n Backend::~Backend()\n {\n m_audioOutputs.clear();\n m_audioEffects.clear();\n\t\t\t::CoUninitialize();\n }\n\n QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList &args)\n {\n switch (c)\n {\n case MediaObjectClass:\n return new MediaObject(parent);\n case AudioOutputClass:\n return new AudioOutput(this, parent);\n#ifndef QT_NO_PHONON_EFFECT\n case EffectClass:\n return new Effect(m_audioEffects[ args[0].toInt() ], parent);\n#endif \/\/QT_NO_PHONON_EFFECT\n#ifndef QT_NO_PHONON_VIDEO\n case VideoWidgetClass:\n return new VideoWidget(qobject_cast(parent));\n#endif \/\/QT_NO_PHONON_VIDEO\n#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT\n case VolumeFaderEffectClass:\n return new VolumeEffect(parent);\n#endif \/\/QT_NO_PHONON_VOLUMEFADEREFFECT\n default:\n return 0;\n }\n }\n\n bool Backend::supportsVideo() const\n {\n#ifndef QT_NO_PHONON_VIDEO\n return true;\n#else\n return false;\n#endif \/\/QT_NO_PHONON_VIDEO\n }\n\n QStringList Backend::availableMimeTypes() const\n {\n#if 0\n\/\/ needs Qt4.5\n QStringList ret;\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\mplayer2\\\\mime types\"), QSettings::NativeFormat);\n ret += settings.childGroups();\n }\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\wmplayer\\\\mime types\"), QSettings::NativeFormat);\n ret += settings.childGroups();\n }\n\n ret.removeDuplicates();\n#else\n QStringList ret;\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\mplayer2\\\\mime types\"), QSettings::NativeFormat);\n Q_FOREACH(const QString &s, settings.childGroups())\n if(!ret.contains(s))\n ret += s;\n }\n {\n QSettings settings(QLatin1String(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Multimedia\\\\wmplayer\\\\mime types\"), QSettings::NativeFormat);\n Q_FOREACH(const QString &s, settings.childGroups())\n if(!ret.contains(s))\n ret += s;\n }\n#endif\n ret.replaceInStrings(\"\\\\\", \"\/\");\n qSort(ret);\n return ret;\n }\n\n\t\tFilter Backend::getAudioOutputFilter(int index) const\n\t\t{\n\t\t\tFilter ret;\n\t\t\tif (index >= 0 && index < m_audioOutputs.count()) {\n\t\t\t\tm_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast(&ret));\n\t\t\t} else {\n\t\t\t\t\/\/just return the default audio renderer (not directsound)\n\t\t\t\tret = Filter(CLSID_AudioRender, IID_IBaseFilter);\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\n QList Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const\n {\n QList ret;\n\n switch(type)\n {\n case Phonon::AudioOutputDeviceType:\n {\n#ifdef Q_OS_WINCE\n\t\t\t\t\tret << 0; \/\/ only one audio device with index 0\n#else\n\t\t\t\t\tComPointer devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum);\n\t\t\t\t\tif (!devEnum) {\n\t\t\t\t\t\treturn ret; \/\/it is impossible to enumerate the devices\n\t\t\t\t\t}\n ComPointer enumMon;\n HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0);\n if (FAILED(hr)) {\n break;\n }\n AudioMoniker mon;\n\n \/\/let's reorder the devices so that directshound appears first\n int nbds = 0; \/\/number of directsound devices\n\n while (S_OK == enumMon->Next(1, mon.pparam(), 0)) {\n LPOLESTR str = 0;\n mon->GetDisplayName(0,0,&str);\n const QString name = QString::fromUtf16((unsigned short*)str);\n\t\t\t\t\t\tComPointer alloc;\n\t\t\t\t\t\t::CoGetMalloc(1, alloc.pparam());\n alloc->Free(str);\n\n int insert_pos = 0;\n if (!m_audioOutputs.contains(mon)) {\n insert_pos = m_audioOutputs.count();\n m_audioOutputs.append(mon);\n } else {\n insert_pos = m_audioOutputs.indexOf(mon);\n }\n\n if (name.contains(QLatin1String(\"DirectSound\"))) {\n ret.insert(nbds++, insert_pos);\n } else {\n ret.append(insert_pos);\n }\n }\n#endif\n\t\t\t\t\tbreak;\n }\n#ifndef QT_NO_PHONON_EFFECT\n case Phonon::EffectType:\n {\n m_audioEffects.clear();\n ComPointer enumDMO;\n HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam());\n if (SUCCEEDED(hr)) {\n CLSID clsid;\n while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) {\n ret += m_audioEffects.count();\n m_audioEffects.append(clsid);\n }\n }\n break;\n }\n break;\n#endif \/\/QT_NO_PHONON_EFFECT\n default:\n break;\n }\n\t\t\treturn ret;\n }\n\n QHash Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const\n {\n QHash ret;\n switch (type)\n {\n case Phonon::AudioOutputDeviceType:\n {\n#ifdef Q_OS_WINCE\n\t\t\t\t\tret[\"name\"] = QLatin1String(\"default audio device\");\n#else\n const AudioMoniker &mon = m_audioOutputs[index];\n LPOLESTR str = 0;\n HRESULT hr = mon->GetDisplayName(0,0, &str);\n if (SUCCEEDED(hr)) {\n QString name = QString::fromUtf16((unsigned short*)str); \n\t\t\t\t\t\tComPointer alloc;\n\t\t\t\t\t\t::CoGetMalloc(1, alloc.pparam());\n alloc->Free(str);\n ret[\"name\"] = name.mid(name.indexOf('\\\\') + 1);\n\t\t\t\t\t}\n#endif\n }\n break;\n#ifndef QT_NO_PHONON_EFFECT\n case Phonon::EffectType:\n {\n WCHAR name[80]; \/\/ 80 is clearly stated in the MSDN doc\n HRESULT hr = ::DMOGetName(m_audioEffects[index], name);\n if (SUCCEEDED(hr)) {\n ret[\"name\"] = QString::fromUtf16((unsigned short*)name);\n }\n }\n break;\n#endif \/\/QT_NO_PHONON_EFFECT\n default:\n break;\n }\n\t\t\treturn ret;\n }\n\n bool Backend::endConnectionChange(QSet objects)\n {\n if (objects.isEmpty())\n return true;\n \/\/end of a transaction\n for(QSet::const_iterator it = objects.begin(); it != objects.end(); ++it) {\n if (BackendNode *node = qobject_cast(*it)) {\n MediaObject *mo = node->mediaObject();\n if (mo) {\n switch(mo->transactionState)\n {\n case Phonon::ErrorState:\n case Phonon::StoppedState:\n case Phonon::LoadingState:\n \/\/nothing to do\n break;\n case Phonon::PausedState:\n mo->pause();\n break;\n default:\n mo->play();\n break;\n }\n\n return mo->state() != Phonon::ErrorState;\n }\n }\n }\n\n return false;\n }\n\n\n bool Backend::startConnectionChange(QSet objects)\n {\n if (objects.isEmpty())\n return true;\n\n \/\/let's save the state of the graph (before we stop it)\n for(QSet::const_iterator it = objects.begin(); it != objects.end(); ++it) {\n if (BackendNode *node = qobject_cast(*it)) {\n if (MediaObject *mo = node->mediaObject()) {\n if (mo->state() != Phonon::StoppedState) {\n mo->transactionState = mo->state();\n mo->ensureStopped(); \/\/we have to stop the graph..\n }\n return true;\n }\n }\n }\n\n return false;\n }\n\n bool Backend::connectNodes(QObject *_source, QObject *_sink)\n {\n BackendNode *source = qobject_cast(_source);\n if (!source) {\n return false;\n }\n BackendNode *sink = qobject_cast(_sink);\n if (!sink) {\n return false;\n }\n\n \/\/setting the graph if needed\n if (source->mediaObject() == 0 && sink->mediaObject() == 0) {\n \/\/error: no graph selected\n return false;\n } else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) {\n \/\/this' graph becomes the common one\n source->mediaObject()->grabNode(sink);\n } else if (source->mediaObject() == 0) {\n \/\/sink's graph becomes the common one\n sink->mediaObject()->grabNode(source);\n }\n\n return source->mediaObject()->connectNodes(source, sink);\n }\n\n bool Backend::disconnectNodes(QObject *_source, QObject *_sink)\n {\n BackendNode *source = qobject_cast(_source);\n if (!source) {\n return false;\n }\n BackendNode *sink = qobject_cast(_sink);\n if (!sink) {\n return false;\n }\n\n return source->mediaObject() == 0 ||\n source->mediaObject()->disconnectNodes(source, sink);\n }\n }\n}\n\nQT_END_NAMESPACE\n\n#include \"moc_backend.cpp\"\n<|endoftext|>"} {"text":"#ifndef __YUNI_PRIVATE_MEDIA_STREAM_HXX__\r\n# define __YUNI_PRIVATE_MEDIA_STREAM_HXX__\r\n\r\n#include \"openal.h\"\r\n#include \"..\/..\/core\/math.h\"\r\n\r\nnamespace Yuni\r\n{\r\nnamespace Private\r\n{\r\nnamespace Media\r\n{\r\n\r\n\r\n\ttemplate\r\n\tStream::Stream(File* parent, AVFormatContext* format, AVCodecContext* codecCtx, uint index):\r\n\t\tpCodec(codecCtx),\r\n\t\tpFormat(format),\r\n\t\tpIndex(index),\r\n\t\tpALFormat(0),\r\n\t\tpSize(0),\r\n\t\tpCrtPts(AV_NOPTS_VALUE),\r\n\t\tpFrame(nullptr),\r\n\t\tpParent(parent)\r\n\t{\r\n\t\tif (!pParent)\r\n\t\t{\r\n\t\t\tpCodec = nullptr;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t\/\/ Try to find the codec for the given codec ID, and open it\r\n\t\tAVCodec* codec = ::avcodec_find_decoder(pCodec->codec_id);\r\n\t\t# if LIBAVFORMAT_VERSION_MAJOR < 53\r\n\t\tif (!codec or ::avcodec_open(pCodec, codec) < 0)\r\n\t\t# else\r\n\t\tif (!codec or ::avcodec_open2(pCodec, codec, NULL) < 0)\r\n\t\t# endif \/\/ LIBAVFORMAT_VERSION_MAJOR < 53\r\n\t\t{\r\n\t\t\tpCodec = nullptr;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (IsAudio)\r\n\t\t\tpALFormat = Private::Media::OpenAL::GetFormat(16, pCodec->channels);\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tStream::~Stream()\r\n\t{\r\n\t\tif (pCodec and pCodec->codec)\r\n\t\t{\r\n\t\t\t\/\/::avcodec_close(pCodec);\r\n\t\t\tpCodec = nullptr;\r\n\t\t}\r\n\t\tif (pFrame)\r\n\t\t\t::av_free(pFrame);\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tAVPacket* Stream::nextPacket()\r\n\t{\r\n\t\t\/\/ If the queue is empty\r\n\t\tif (pPackets.empty())\r\n\t\t{\r\n\t\t\tif (!pParent)\r\n\t\t\t\treturn nullptr;\r\n\r\n\t\t\tAVPacket* pkt = pParent->getNextPacket(this);\r\n\t\t\tif (!pkt)\r\n\t\t\t\t\/\/ No more packets\r\n\t\t\t\treturn nullptr;\r\n\t\t}\r\n\r\n\t\t\/\/ Get the first packet in queue\r\n\t\tAVPacket* pkt = pPackets.front();\r\n\t\tpPackets.pop_front();\r\n\t\treturn pkt;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tuint Stream::readFrame()\r\n\t{\r\n\t\t\/\/ Frame allocation\r\n\t\tif (!pFrame)\r\n\t\t{\r\n\t\t\tif (!(pFrame = ::avcodec_alloc_frame()))\r\n\t\t\t{\r\n\t\t\t\tstd::cerr << \"Error allocating a frame for audio decoding !\" << std::endl;\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t\/\/ Should not happen, but this is a security.\r\n\t\t\t::avcodec_get_frame_defaults(pFrame);\r\n\t\t}\r\n\r\n\t\tint bytesRead = 0;\r\n\t\tint frameFinished = 0;\r\n\t\tAVPacket* packet = nullptr;\r\n\r\n\t\twhile (not frameFinished)\r\n\t\t{\r\n\t\t\t\/\/ Get next packet\r\n\t\t\tpacket = nextPacket();\r\n\t\t\tif (!packet)\r\n\t\t\t\treturn 0;\r\n\r\n\t\t\t\/\/ VIDEO\r\n\t\t\tif (IsVideo)\r\n\t\t\t{\r\n\t\t\t\tpCrtPts = 0;\r\n\t\t\t\t\/\/ Decode the packet\r\n\t\t\t\t#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,30,0)\r\n\t\t\t\tif ((bytesRead = ::avcodec_decode_video2(pCodec, pFrame, &frameFinished, packet)) < 0)\r\n\t\t\t\t#else\r\n\t\t\t\tif ((bytesRead = ::avcodec_decode_video(pCodec, pFrame, &frameFinished, packet->data, packet->size)) < 0)\r\n\t\t\t\t#endif\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::cerr << \"Error while decoding video !\" << std::endl;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\/\/ Do not do anything here, just act normally and try to recover from the error\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/ If the frame is finished (should be in one shot)\r\n\t\t\t\tif (frameFinished)\r\n\t\t\t\t{\r\n\t\t\t\t\tif ((uint64)AV_NOPTS_VALUE == (uint64)packet->dts and pFrame->opaque\r\n\t\t\t\t\t\t&& (uint64)AV_NOPTS_VALUE != *(uint64*)pFrame->opaque)\r\n\t\t\t\t\t\tpCrtPts = *(uint64*)pFrame->opaque;\r\n\t\t\t\t\telse if ((uint64)AV_NOPTS_VALUE != (uint64)packet->dts)\r\n\t\t\t\t\t\tpCrtPts = packet->dts;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tpCrtPts = 0.0;\r\n\t\t\t\t\t\/\/ pCrtPts = ::av_frame_get_best_effort_timestamp(pFrame);\r\n\t\t\t\t\tfloat timeRatio = ::av_q2d(pFormat->streams[pIndex]->time_base);\r\n\t\t\t\t\tpCrtPts *= timeRatio;\r\n\t\t\t\t\tpCrtPts -= (pFormat->streams[pIndex]->start_time * timeRatio);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\/\/ AUDIO\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t\/\/ Decode the packet\r\n\t\t\t\t#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,30,0)\r\n\t\t\t\tif ((bytesRead = ::avcodec_decode_audio4(pCodec, pFrame, &frameFinished, packet)) < 0)\r\n\t\t\t\t#else\r\n\t\t\t\tif ((bytesRead = ::avcodec_decode_audio3(pCodec, pFrame, &frameFinished, packet->data, packet->size)) < 0)\r\n\t\t\t\t#endif\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::cerr << \"Error while decoding audio !\" << std::endl;\r\n\t\t\t\t\t\/\/ Do not do anything here, just act normally and try to recover from the error\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/ If the frame is finished (should be in one shot)\r\n\t\t\t\tif (frameFinished)\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Free packet before looping\r\n\t\t\t::av_free_packet(packet);\r\n\t\t\tdelete packet;\r\n\t\t\tpacket = nullptr;\r\n\t\t}\r\n\r\n\t\t\/\/ Free packet before quitting\r\n\t\tif (packet)\r\n\t\t{\r\n\t\t\t::av_free_packet(packet);\r\n\t\t\tdelete packet;\r\n\t\t}\r\n\r\n\t\treturn bytesRead;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline Frame::Ptr Stream::nextFrame()\r\n\t{\r\n\t\t\/\/YUNI_STATIC_ASSERT(IsVideo, nextFrameNotAccessibleInAudio);\r\n\t\tif (IsVideo)\r\n\t\t{\r\n\t\t\treadFrame();\r\n\t\t}\r\n\t\telse \/\/ IsAudio\r\n\t\t{\r\n\t\t\t\/\/readAudioFrame();\r\n\t\t\treadFrame();\r\n\t\t}\r\n\r\n\t\tstatic uint i = 1u;\r\n\t\t\/\/ TODO : Give the real frame index\r\n\t\tFrame* frame = new Frame(i++, pCrtPts);\r\n\t\t\/\/ Our Frame object takes custody of the AVFrame\r\n\t\t\/\/ and will take care of its deletion\r\n\t\tframe->setData(pFrame);\r\n\t\t\/\/ Reset the current frame\r\n\t\tpFrame = nullptr;\r\n\t\treturn frame;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline void Stream::rewind()\r\n\t{\r\n\t\tif (pFrame)\r\n\t\t\t::av_free(pFrame);\r\n\t\t::av_seek_frame(pFormat, pIndex, 0, 0);\r\n\t}\r\n\r\n\ttemplate\r\n\tinline uint Stream::index() const\r\n\t{\r\n\t\treturn pIndex;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::duration() const\r\n\t{\r\n\t\tassert(pParent);\r\n\t\treturn pParent->duration();\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::width() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\r\n\t\treturn pCodec->width;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::height() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\r\n\t\treturn pCodec->height;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::depth() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\r\n\t\treturn ::av_get_bits_per_pixel(&::av_pix_fmt_descriptors[pCodec->pix_fmt]);\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline float Stream::fps() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\r\n\t\tassert(pCodec);\r\n\t\tassert(pFormat);\r\n\t\tassert(pFormat->streams[pIndex]);\r\n\r\n\t\tauto* avStream = pFormat->streams[pIndex];\r\n\r\n\t\tfloat den = avStream->avg_frame_rate.den;\r\n\t\tfloat variable = 0.0f;\r\n\t\tif (den > 0.0f) \/\/ avoid divide by 0\r\n\t\t\tvariable = ::av_q2d(avStream->avg_frame_rate);\r\n\r\n\t\tden = avStream->time_base.num;\r\n\t\tfloat constant = 0.0f;\r\n\t\tif (den > 0.0f) \/\/ avoid divide by 0\r\n\t\t\tconstant = pCodec->ticks_per_frame * avStream->time_base.den \/ den;\r\n\r\n\t\treturn Math::Max(variable, constant);\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::rate() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\r\n\t\tassert(pCodec);\r\n\t\treturn (pCodec->channels > 0) ? (pCodec->sample_rate \/ pCodec->channels) : 0;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::channels() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\r\n\t\tassert(pCodec);\r\n\t\treturn pCodec->channels;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline uint Stream::bits() const\r\n\t{\r\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\r\n\t\tassert(pCodec);\r\n\t\t\/\/ Internal FFMpeg format is always 16 bits\r\n\t\treturn 16;\r\n\t}\r\n\r\n\r\n\ttemplate\r\n\tinline StreamType Stream::type() const\r\n\t{\r\n\t\treturn TypeT;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n} \/\/ namespace Media\r\n} \/\/ namespace Private\r\n} \/\/ namespace Yuni\r\n\r\n#endif \/\/ __YUNI_PRIVATE_MEDIA_STREAM_HXX__\r\nMedia : Fixed deprecated calls in newer versions of ffmpeg.#ifndef __YUNI_PRIVATE_MEDIA_STREAM_HXX__\n# define __YUNI_PRIVATE_MEDIA_STREAM_HXX__\n\n#include \"openal.h\"\n#include \"..\/..\/core\/math.h\"\n\nnamespace Yuni\n{\nnamespace Private\n{\nnamespace Media\n{\n\n\n\ttemplate\n\tStream::Stream(File* parent, AVFormatContext* format, AVCodecContext* codecCtx, uint index):\n\t\tpCodec(codecCtx),\n\t\tpFormat(format),\n\t\tpIndex(index),\n\t\tpALFormat(0),\n\t\tpSize(0),\n\t\tpCrtPts(AV_NOPTS_VALUE),\n\t\tpFrame(nullptr),\n\t\tpParent(parent)\n\t{\n\t\tif (!pParent)\n\t\t{\n\t\t\tpCodec = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Try to find the codec for the given codec ID, and open it\n\t\tAVCodec* codec = ::avcodec_find_decoder(pCodec->codec_id);\n\t\t# if LIBAVFORMAT_VERSION_MAJOR < 53\n\t\tif (!codec or ::avcodec_open(pCodec, codec) < 0)\n\t\t# else\n\t\tif (!codec or ::avcodec_open2(pCodec, codec, NULL) < 0)\n\t\t# endif \/\/ LIBAVFORMAT_VERSION_MAJOR < 53\n\t\t{\n\t\t\tpCodec = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tif (IsAudio)\n\t\t\tpALFormat = Private::Media::OpenAL::GetFormat(16, pCodec->channels);\n\t}\n\n\n\ttemplate\n\tStream::~Stream()\n\t{\n\t\tif (pCodec and pCodec->codec)\n\t\t{\n\t\t\t\/\/::avcodec_close(pCodec);\n\t\t\tpCodec = nullptr;\n\t\t}\n\t\tif (pFrame)\n\t\t\t::av_free(pFrame);\n\t}\n\n\n\ttemplate\n\tAVPacket* Stream::nextPacket()\n\t{\n\t\t\/\/ If the queue is empty\n\t\tif (pPackets.empty())\n\t\t{\n\t\t\tif (!pParent)\n\t\t\t\treturn nullptr;\n\n\t\t\tAVPacket* pkt = pParent->getNextPacket(this);\n\t\t\tif (!pkt)\n\t\t\t\t\/\/ No more packets\n\t\t\t\treturn nullptr;\n\t\t}\n\n\t\t\/\/ Get the first packet in queue\n\t\tAVPacket* pkt = pPackets.front();\n\t\tpPackets.pop_front();\n\t\treturn pkt;\n\t}\n\n\n\ttemplate\n\tuint Stream::readFrame()\n\t{\n\t\t\/\/ Frame allocation\n\t\tif (!pFrame)\n\t\t{\n\t\t\t#if LIBAVUTIL_VERSION_INT > AV_VERSION_INT(52, 20, 100)\n\t\t\tif (!(pFrame = ::av_frame_alloc()))\n\t\t\t#else\n\t\t\tif (!(pFrame = ::avcodec_alloc_frame()))\n\t\t\t#endif\n\t\t\t{\n\t\t\t\tstd::cerr << \"Error allocating a frame for audio decoding !\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Should not happen, but this is a security.\n\t\t\t#if LIBAVUTIL_VERSION_INT > AV_VERSION_INT(52, 20, 100)\n\t\t\t::av_frame_unref(pFrame);\n\t\t\t#else\n\t\t\t::avcodec_get_frame_defaults(pFrame);\n\t\t\t#endif\n\t\t}\n\n\t\tint bytesRead = 0;\n\t\tint frameFinished = 0;\n\t\tAVPacket* packet = nullptr;\n\n\t\twhile (not frameFinished)\n\t\t{\n\t\t\t\/\/ Get next packet\n\t\t\tpacket = nextPacket();\n\t\t\tif (!packet)\n\t\t\t\treturn 0;\n\n\t\t\t\/\/ VIDEO\n\t\t\tif (IsVideo)\n\t\t\t{\n\t\t\t\tpCrtPts = 0;\n\t\t\t\t\/\/ Decode the packet\n\t\t\t\t#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,30,0)\n\t\t\t\tif ((bytesRead = ::avcodec_decode_video2(pCodec, pFrame, &frameFinished, packet)) < 0)\n\t\t\t\t#else\n\t\t\t\tif ((bytesRead = ::avcodec_decode_video(pCodec, pFrame, &frameFinished, packet->data, packet->size)) < 0)\n\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error while decoding video !\" << std::endl;\n\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/ Do not do anything here, just act normally and try to recover from the error\n\t\t\t\t}\n\n\t\t\t\t\/\/ If the frame is finished (should be in one shot)\n\t\t\t\tif (frameFinished)\n\t\t\t\t{\n\t\t\t\t\tif ((uint64)AV_NOPTS_VALUE == (uint64)packet->dts and pFrame->opaque\n\t\t\t\t\t\t&& (uint64)AV_NOPTS_VALUE != *(uint64*)pFrame->opaque)\n\t\t\t\t\t\tpCrtPts = *(uint64*)pFrame->opaque;\n\t\t\t\t\telse if ((uint64)AV_NOPTS_VALUE != (uint64)packet->dts)\n\t\t\t\t\t\tpCrtPts = packet->dts;\n\t\t\t\t\telse\n\t\t\t\t\t\tpCrtPts = 0.0;\n\t\t\t\t\t\/\/ pCrtPts = ::av_frame_get_best_effort_timestamp(pFrame);\n\t\t\t\t\tfloat timeRatio = ::av_q2d(pFormat->streams[pIndex]->time_base);\n\t\t\t\t\tpCrtPts *= timeRatio;\n\t\t\t\t\tpCrtPts -= (pFormat->streams[pIndex]->start_time * timeRatio);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ AUDIO\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Decode the packet\n\t\t\t\t#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,30,0)\n\t\t\t\tif ((bytesRead = ::avcodec_decode_audio4(pCodec, pFrame, &frameFinished, packet)) < 0)\n\t\t\t\t#else\n\t\t\t\tif ((bytesRead = ::avcodec_decode_audio3(pCodec, pFrame, &frameFinished, packet->data, packet->size)) < 0)\n\t\t\t\t#endif\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error while decoding audio !\" << std::endl;\n\t\t\t\t\t\/\/ Do not do anything here, just act normally and try to recover from the error\n\t\t\t\t}\n\n\t\t\t\t\/\/ If the frame is finished (should be in one shot)\n\t\t\t\tif (frameFinished)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Free packet before looping\n\t\t\t::av_free_packet(packet);\n\t\t\tdelete packet;\n\t\t\tpacket = nullptr;\n\t\t}\n\n\t\t\/\/ Free packet before quitting\n\t\tif (packet)\n\t\t{\n\t\t\t::av_free_packet(packet);\n\t\t\tdelete packet;\n\t\t}\n\n\t\treturn bytesRead;\n\t}\n\n\n\ttemplate\n\tinline Frame::Ptr Stream::nextFrame()\n\t{\n\t\t\/\/YUNI_STATIC_ASSERT(IsVideo, nextFrameNotAccessibleInAudio);\n\t\tif (IsVideo)\n\t\t{\n\t\t\treadFrame();\n\t\t}\n\t\telse \/\/ IsAudio\n\t\t{\n\t\t\t\/\/readAudioFrame();\n\t\t\treadFrame();\n\t\t}\n\n\t\tstatic uint i = 1u;\n\t\t\/\/ TODO : Give the real frame index\n\t\tFrame* frame = new Frame(i++, pCrtPts);\n\t\t\/\/ Our Frame object takes custody of the AVFrame\n\t\t\/\/ and will take care of its deletion\n\t\tframe->setData(pFrame);\n\t\t\/\/ Reset the current frame\n\t\tpFrame = nullptr;\n\t\treturn frame;\n\t}\n\n\n\ttemplate\n\tinline void Stream::rewind()\n\t{\n\t\tif (pFrame)\n\t\t\t::av_free(pFrame);\n\t\t::av_seek_frame(pFormat, pIndex, 0, 0);\n\t}\n\n\ttemplate\n\tinline uint Stream::index() const\n\t{\n\t\treturn pIndex;\n\t}\n\n\n\ttemplate\n\tinline uint Stream::duration() const\n\t{\n\t\tassert(pParent);\n\t\treturn pParent->duration();\n\t}\n\n\n\ttemplate\n\tinline uint Stream::width() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\n\t\treturn pCodec->width;\n\t}\n\n\n\ttemplate\n\tinline uint Stream::height() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\n\t\treturn pCodec->height;\n\t}\n\n\n\ttemplate\n\tinline uint Stream::depth() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\n\t\t#if LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52,30,0)\n\t\treturn ::av_get_bits_per_pixel(::av_pix_fmt_desc_get(pCodec->pix_fmt));\n\t\t#else\n\t\treturn ::av_get_bits_per_pixel(&::av_pix_fmt_descriptors[pCodec->pix_fmt]);\n\t\t#endif\n\t}\n\n\n\ttemplate\n\tinline float Stream::fps() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsVideo, NotAccessibleInAudio);\n\t\tassert(pCodec);\n\t\tassert(pFormat);\n\t\tassert(pFormat->streams[pIndex]);\n\n\t\tauto* avStream = pFormat->streams[pIndex];\n\n\t\tfloat den = avStream->avg_frame_rate.den;\n\t\tfloat variable = 0.0f;\n\t\tif (den > 0.0f) \/\/ avoid divide by 0\n\t\t\tvariable = ::av_q2d(avStream->avg_frame_rate);\n\n\t\tden = avStream->time_base.num;\n\t\tfloat constant = 0.0f;\n\t\tif (den > 0.0f) \/\/ avoid divide by 0\n\t\t\tconstant = pCodec->ticks_per_frame * avStream->time_base.den \/ den;\n\n\t\treturn Math::Max(variable, constant);\n\t}\n\n\n\ttemplate\n\tinline uint Stream::rate() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\n\t\tassert(pCodec);\n\t\treturn (pCodec->channels > 0) ? (pCodec->sample_rate \/ pCodec->channels) : 0;\n\t}\n\n\n\ttemplate\n\tinline uint Stream::channels() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\n\t\tassert(pCodec);\n\t\treturn pCodec->channels;\n\t}\n\n\n\ttemplate\n\tinline uint Stream::bits() const\n\t{\n\t\tYUNI_STATIC_ASSERT(IsAudio, NotAccessibleInVideo);\n\t\tassert(pCodec);\n\t\t\/\/ Internal FFMpeg format is always 16 bits\n\t\treturn 16;\n\t}\n\n\n\ttemplate\n\tinline StreamType Stream::type() const\n\t{\n\t\treturn TypeT;\n\t}\n\n\n\n\n\n} \/\/ namespace Media\n} \/\/ namespace Private\n} \/\/ namespace Yuni\n\n#endif \/\/ __YUNI_PRIVATE_MEDIA_STREAM_HXX__\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the V4VM module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\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, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \"debugging.h\"\n#include \n#include \n#include \n#include \"qv4mm.h\"\n\nnamespace QQmlJS {\nnamespace VM {\n\nDiagnosticMessage::DiagnosticMessage()\n : offset(0)\n , length(0)\n , startLine(0)\n , startColumn(0)\n , type(0)\n , next(0)\n{}\n\nDiagnosticMessage::~DiagnosticMessage()\n{\n delete next;\n}\n\nString *DiagnosticMessage::buildFullMessage(ExecutionContext *ctx) const\n{\n QString msg;\n if (!fileName.isEmpty())\n msg = fileName + QLatin1Char(':');\n msg += QString::number(startLine) + QLatin1Char(':') + QString::number(startColumn) + QLatin1String(\": \");\n if (type == QQmlJS::VM::DiagnosticMessage::Error)\n msg += QLatin1String(\"error\");\n else\n msg += QLatin1String(\"warning\");\n msg += \": \" + message;\n\n return ctx->engine->newString(msg);\n}\n\nbool ExecutionContext::hasBinding(String *name) const\n{\n if (!function)\n return false;\n\n for (unsigned int i = 0; i < function->varCount; ++i) {\n if (__qmljs_string_equal(function->varList[i], name))\n return true;\n }\n for (unsigned int i = 0; i < function->formalParameterCount; ++i) {\n if (__qmljs_string_equal(function->formalParameterList[i], name))\n return true;\n }\n if (activation)\n return activation->__hasProperty__(this, name);\n return false;\n}\n\nvoid ExecutionContext::createMutableBinding(String *name, bool deletable)\n{\n if (!activation)\n activation = engine->newActivationObject();\n\n if (activation->__hasProperty__(this, name))\n return;\n PropertyDescriptor desc;\n desc.value = Value::undefinedValue();\n desc.type = PropertyDescriptor::Data;\n desc.configurable = deletable ? PropertyDescriptor::Set : PropertyDescriptor::Unset;\n desc.writable = PropertyDescriptor::Set;\n desc.enumberable = PropertyDescriptor::Set;\n activation->__defineOwnProperty__(this, name, &desc);\n}\n\nbool ExecutionContext::setMutableBinding(ExecutionContext *scope, String *name, Value value)\n{\n \/\/ ### throw if scope->strict is true, and it would change an immutable binding\n for (unsigned int i = 0; i < variableCount(); ++i) {\n if (__qmljs_string_equal(variables()[i], name)) {\n locals[i] = value;\n return true;\n }\n }\n for (unsigned int i = 0; i < formalCount(); ++i) {\n if (__qmljs_string_equal(formals()[i], name)) {\n arguments[i] = value;\n return true;\n }\n }\n if (activation && activation->__hasProperty__(scope, name)) {\n activation->__put__(scope, name, value);\n return true;\n }\n\n return false;\n}\n\nValue ExecutionContext::getBindingValue(ExecutionContext *scope, String *name, bool strict) const\n{\n Q_UNUSED(strict);\n assert(function);\n\n for (unsigned int i = 0; i < variableCount(); ++i) {\n if (__qmljs_string_equal(variables()[i], name))\n return locals[i];\n }\n for (unsigned int i = 0; i < formalCount(); ++i) {\n if (__qmljs_string_equal(formals()[i], name))\n return arguments[i];\n }\n if (activation && activation->__hasProperty__(this, name))\n return activation->__get__(scope, name);\n assert(false);\n}\n\nbool ExecutionContext::deleteBinding(ExecutionContext *scope, String *name)\n{\n if (activation)\n activation->__delete__(scope, name);\n\n if (scope->strictMode)\n __qmljs_throw_type_error(scope);\n return false;\n}\n\nvoid ExecutionContext::pushWithObject(Object *with)\n{\n With *w = new With;\n w->next = withObject;\n w->object = with;\n withObject = w;\n}\n\nvoid ExecutionContext::popWithObject()\n{\n assert(withObject);\n\n With *w = withObject;\n withObject = w->next;\n delete w;\n}\n\nExecutionContext *ExecutionContext::outer() const\n{\n return function ? function->scope : 0;\n}\n\nString **ExecutionContext::formals() const\n{\n return function ? function->formalParameterList : 0;\n}\n\nunsigned int ExecutionContext::formalCount() const\n{\n return function ? function->formalParameterCount : 0;\n}\n\nString **ExecutionContext::variables() const\n{\n return function ? function->varList : 0;\n}\n\nunsigned int ExecutionContext::variableCount() const\n{\n return function ? function->varCount : 0;\n}\n\n\nvoid ExecutionContext::init(ExecutionEngine *eng)\n{\n engine = eng;\n parent = 0;\n thisObject = eng->globalObject;\n\n function = 0;\n arguments = 0;\n argumentCount = 0;\n locals = 0;\n strictMode = false;\n activation = 0;\n withObject = 0;\n\n eng->exception = Value::undefinedValue();\n}\n\nbool ExecutionContext::deleteProperty(String *name)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n ExecutionContext::With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(this, name))\n w->object->__delete__(this, name);\n w = w->next;\n }\n }\n if (ctx->activation) {\n if (ctx->activation->__hasProperty__(this, name))\n ctx->activation->__delete__(this, name);\n }\n }\n if (strictMode)\n throwSyntaxError(0);\n return true;\n}\n\nvoid ExecutionContext::setProperty(String *name, Value value)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name)) {\n w->object->__put__(ctx, name, value);\n return;\n }\n w = w->next;\n }\n }\n if (ctx->setMutableBinding(this, name, value))\n return;\n }\n if (strictMode)\n throwReferenceError(Value::fromString(name));\n engine->globalObject.objectValue()->__put__(this, name, value);\n}\n\nValue ExecutionContext::getProperty(String *name)\n{\n if (name == engine->id_this)\n return thisObject;\n\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name))\n return w->object->__get__(ctx, name);\n w = w->next;\n }\n }\n\n for (unsigned int i = 0; i < ctx->variableCount(); ++i)\n if (__qmljs_string_equal(ctx->variables()[i], name))\n return ctx->locals[i];\n for (unsigned int i = 0; i < ctx->formalCount(); ++i)\n if (__qmljs_string_equal(ctx->formals()[i], name))\n return ctx->arguments[i];\n if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))\n return ctx->activation->__get__(ctx, name);\n if (name->isEqualTo(ctx->engine->id_arguments)) {\n Value arguments = Value::fromObject(new (engine->memoryManager) ArgumentsObject(this));\n createMutableBinding(ctx->engine->id_arguments, false);\n setMutableBinding(this, ctx->engine->id_arguments, arguments);\n return arguments;\n }\n }\n throwReferenceError(Value::fromString(name));\n return Value::undefinedValue();\n}\n\nValue ExecutionContext::getPropertyNoThrow(String *name)\n{\n if (name == engine->id_this)\n return thisObject;\n\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name))\n return w->object->__get__(ctx, name);\n w = w->next;\n }\n }\n\n for (unsigned int i = 0; i < ctx->variableCount(); ++i)\n if (__qmljs_string_equal(ctx->variables()[i], name))\n return ctx->locals[i];\n for (unsigned int i = 0; i < ctx->formalCount(); ++i)\n if (__qmljs_string_equal(ctx->formals()[i], name))\n return ctx->arguments[i];\n if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))\n return ctx->activation->__get__(ctx, name);\n if (name->isEqualTo(ctx->engine->id_arguments)) {\n Value arguments = Value::fromObject(new (engine->memoryManager) ArgumentsObject(this));\n createMutableBinding(ctx->engine->id_arguments, false);\n setMutableBinding(this, ctx->engine->id_arguments, arguments);\n return arguments;\n }\n }\n return Value::undefinedValue();\n}\n\n\n\nvoid ExecutionContext::inplaceBitOp(Value value, String *name, BinOp op)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->activation) {\n if (ctx->activation->inplaceBinOp(value, name, op, this))\n return;\n }\n }\n throwReferenceError(Value::fromString(name));\n}\n\nvoid ExecutionContext::throwError(Value value)\n{\n __qmljs_builtin_throw(value, this);\n}\n\nvoid ExecutionContext::throwError(const QString &message)\n{\n Value v = Value::fromString(this, message);\n throwError(Value::fromObject(engine->newErrorObject(v)));\n}\n\nvoid ExecutionContext::throwSyntaxError(DiagnosticMessage *message)\n{\n throwError(Value::fromObject(engine->newSyntaxErrorObject(this, message)));\n}\n\nvoid ExecutionContext::throwTypeError()\n{\n throwError(Value::fromObject(engine->newTypeErrorObject(this, QStringLiteral(\"Type error\"))));\n}\n\nvoid ExecutionContext::throwUnimplemented(const QString &message)\n{\n Value v = Value::fromString(this, QStringLiteral(\"Unimplemented \") + message);\n throwError(Value::fromObject(engine->newErrorObject(v)));\n}\n\nvoid ExecutionContext::throwReferenceError(Value value)\n{\n String *s = value.toString(this);\n QString msg = s->toQString() + QStringLiteral(\" is not defined\");\n throwError(Value::fromObject(engine->newReferenceErrorObject(this, msg)));\n}\n\nvoid ExecutionContext::initCallContext(ExecutionContext *parent, const Value that, FunctionObject *f, Value *args, unsigned argc)\n{\n MemoryManager::GCBlocker blockGC(parent->engine->memoryManager);\n\n engine = parent->engine;\n this->parent = parent;\n\n function = f;\n strictMode = f->strictMode;\n\n thisObject = that;\n if (!strictMode && !thisObject.isObject()) {\n if (thisObject.isUndefined() || thisObject.isNull())\n thisObject = engine->globalObject;\n else\n thisObject = thisObject.toObject(this);\n }\n\n arguments = args;\n argumentCount = argc;\n if (function->needsActivation || argc < function->formalParameterCount){\n arguments = new Value[qMax(argc, function->formalParameterCount)];\n if (argc)\n std::copy(args, args + argc, arguments);\n if (argc < function->formalParameterCount)\n std::fill(arguments + argc, arguments + function->formalParameterCount, Value::undefinedValue());\n }\n locals = function->varCount ? new Value[function->varCount] : 0;\n if (function->varCount)\n std::fill(locals, locals + function->varCount, Value::undefinedValue());\n\n if (function->needsActivation)\n activation = engine->newActivationObject();\n else\n activation = 0;\n\n withObject = 0;\n\n\n if (engine->debugger)\n engine->debugger->aboutToCall(f, this);\n}\n\nvoid ExecutionContext::leaveCallContext()\n{\n \/\/ ## Should rather be handled by a the activation object having a ref to the environment\n if (activation) {\n delete[] locals;\n locals = 0;\n }\n parent = 0;\n\n if (engine->debugger)\n engine->debugger->justLeft(this);\n}\n\nvoid ExecutionContext::wireUpPrototype()\n{\n assert(thisObject.isObject());\n\n Value proto = function->__get__(this, engine->id_prototype);\n if (proto.isObject())\n thisObject.objectValue()->prototype = proto.objectValue();\n else\n thisObject.objectValue()->prototype = engine->objectPrototype;\n}\n\n} \/\/ namespace VM\n} \/\/ namespace QQmlJS\nDon't allow this as LHS operand\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the V4VM module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\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, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \"debugging.h\"\n#include \n#include \n#include \n#include \"qv4mm.h\"\n\nnamespace QQmlJS {\nnamespace VM {\n\nDiagnosticMessage::DiagnosticMessage()\n : offset(0)\n , length(0)\n , startLine(0)\n , startColumn(0)\n , type(0)\n , next(0)\n{}\n\nDiagnosticMessage::~DiagnosticMessage()\n{\n delete next;\n}\n\nString *DiagnosticMessage::buildFullMessage(ExecutionContext *ctx) const\n{\n QString msg;\n if (!fileName.isEmpty())\n msg = fileName + QLatin1Char(':');\n msg += QString::number(startLine) + QLatin1Char(':') + QString::number(startColumn) + QLatin1String(\": \");\n if (type == QQmlJS::VM::DiagnosticMessage::Error)\n msg += QLatin1String(\"error\");\n else\n msg += QLatin1String(\"warning\");\n msg += \": \" + message;\n\n return ctx->engine->newString(msg);\n}\n\nbool ExecutionContext::hasBinding(String *name) const\n{\n if (!function)\n return false;\n\n for (unsigned int i = 0; i < function->varCount; ++i) {\n if (__qmljs_string_equal(function->varList[i], name))\n return true;\n }\n for (unsigned int i = 0; i < function->formalParameterCount; ++i) {\n if (__qmljs_string_equal(function->formalParameterList[i], name))\n return true;\n }\n if (activation)\n return activation->__hasProperty__(this, name);\n return false;\n}\n\nvoid ExecutionContext::createMutableBinding(String *name, bool deletable)\n{\n if (!activation)\n activation = engine->newActivationObject();\n\n if (activation->__hasProperty__(this, name))\n return;\n PropertyDescriptor desc;\n desc.value = Value::undefinedValue();\n desc.type = PropertyDescriptor::Data;\n desc.configurable = deletable ? PropertyDescriptor::Set : PropertyDescriptor::Unset;\n desc.writable = PropertyDescriptor::Set;\n desc.enumberable = PropertyDescriptor::Set;\n activation->__defineOwnProperty__(this, name, &desc);\n}\n\nbool ExecutionContext::setMutableBinding(ExecutionContext *scope, String *name, Value value)\n{\n \/\/ ### throw if scope->strict is true, and it would change an immutable binding\n for (unsigned int i = 0; i < variableCount(); ++i) {\n if (__qmljs_string_equal(variables()[i], name)) {\n locals[i] = value;\n return true;\n }\n }\n for (unsigned int i = 0; i < formalCount(); ++i) {\n if (__qmljs_string_equal(formals()[i], name)) {\n arguments[i] = value;\n return true;\n }\n }\n if (activation && activation->__hasProperty__(scope, name)) {\n activation->__put__(scope, name, value);\n return true;\n }\n\n return false;\n}\n\nValue ExecutionContext::getBindingValue(ExecutionContext *scope, String *name, bool strict) const\n{\n Q_UNUSED(strict);\n assert(function);\n\n for (unsigned int i = 0; i < variableCount(); ++i) {\n if (__qmljs_string_equal(variables()[i], name))\n return locals[i];\n }\n for (unsigned int i = 0; i < formalCount(); ++i) {\n if (__qmljs_string_equal(formals()[i], name))\n return arguments[i];\n }\n if (activation && activation->__hasProperty__(this, name))\n return activation->__get__(scope, name);\n assert(false);\n}\n\nbool ExecutionContext::deleteBinding(ExecutionContext *scope, String *name)\n{\n if (activation)\n activation->__delete__(scope, name);\n\n if (scope->strictMode)\n __qmljs_throw_type_error(scope);\n return false;\n}\n\nvoid ExecutionContext::pushWithObject(Object *with)\n{\n With *w = new With;\n w->next = withObject;\n w->object = with;\n withObject = w;\n}\n\nvoid ExecutionContext::popWithObject()\n{\n assert(withObject);\n\n With *w = withObject;\n withObject = w->next;\n delete w;\n}\n\nExecutionContext *ExecutionContext::outer() const\n{\n return function ? function->scope : 0;\n}\n\nString **ExecutionContext::formals() const\n{\n return function ? function->formalParameterList : 0;\n}\n\nunsigned int ExecutionContext::formalCount() const\n{\n return function ? function->formalParameterCount : 0;\n}\n\nString **ExecutionContext::variables() const\n{\n return function ? function->varList : 0;\n}\n\nunsigned int ExecutionContext::variableCount() const\n{\n return function ? function->varCount : 0;\n}\n\n\nvoid ExecutionContext::init(ExecutionEngine *eng)\n{\n engine = eng;\n parent = 0;\n thisObject = eng->globalObject;\n\n function = 0;\n arguments = 0;\n argumentCount = 0;\n locals = 0;\n strictMode = false;\n activation = 0;\n withObject = 0;\n\n eng->exception = Value::undefinedValue();\n}\n\nbool ExecutionContext::deleteProperty(String *name)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n ExecutionContext::With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(this, name))\n w->object->__delete__(this, name);\n w = w->next;\n }\n }\n if (ctx->activation) {\n if (ctx->activation->__hasProperty__(this, name))\n ctx->activation->__delete__(this, name);\n }\n }\n if (strictMode)\n throwSyntaxError(0);\n return true;\n}\n\nvoid ExecutionContext::setProperty(String *name, Value value)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name)) {\n w->object->__put__(ctx, name, value);\n return;\n }\n w = w->next;\n }\n }\n if (ctx->setMutableBinding(this, name, value))\n return;\n }\n if (strictMode || name == engine->id_this)\n throwReferenceError(Value::fromString(name));\n engine->globalObject.objectValue()->__put__(this, name, value);\n}\n\nValue ExecutionContext::getProperty(String *name)\n{\n if (name == engine->id_this)\n return thisObject;\n\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name))\n return w->object->__get__(ctx, name);\n w = w->next;\n }\n }\n\n for (unsigned int i = 0; i < ctx->variableCount(); ++i)\n if (__qmljs_string_equal(ctx->variables()[i], name))\n return ctx->locals[i];\n for (unsigned int i = 0; i < ctx->formalCount(); ++i)\n if (__qmljs_string_equal(ctx->formals()[i], name))\n return ctx->arguments[i];\n if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))\n return ctx->activation->__get__(ctx, name);\n if (name->isEqualTo(ctx->engine->id_arguments)) {\n Value arguments = Value::fromObject(new (engine->memoryManager) ArgumentsObject(this));\n createMutableBinding(ctx->engine->id_arguments, false);\n setMutableBinding(this, ctx->engine->id_arguments, arguments);\n return arguments;\n }\n }\n throwReferenceError(Value::fromString(name));\n return Value::undefinedValue();\n}\n\nValue ExecutionContext::getPropertyNoThrow(String *name)\n{\n if (name == engine->id_this)\n return thisObject;\n\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->withObject) {\n With *w = ctx->withObject;\n while (w) {\n if (w->object->__hasProperty__(ctx, name))\n return w->object->__get__(ctx, name);\n w = w->next;\n }\n }\n\n for (unsigned int i = 0; i < ctx->variableCount(); ++i)\n if (__qmljs_string_equal(ctx->variables()[i], name))\n return ctx->locals[i];\n for (unsigned int i = 0; i < ctx->formalCount(); ++i)\n if (__qmljs_string_equal(ctx->formals()[i], name))\n return ctx->arguments[i];\n if (ctx->activation && ctx->activation->__hasProperty__(ctx, name))\n return ctx->activation->__get__(ctx, name);\n if (name->isEqualTo(ctx->engine->id_arguments)) {\n Value arguments = Value::fromObject(new (engine->memoryManager) ArgumentsObject(this));\n createMutableBinding(ctx->engine->id_arguments, false);\n setMutableBinding(this, ctx->engine->id_arguments, arguments);\n return arguments;\n }\n }\n return Value::undefinedValue();\n}\n\n\n\nvoid ExecutionContext::inplaceBitOp(Value value, String *name, BinOp op)\n{\n for (ExecutionContext *ctx = this; ctx; ctx = ctx->outer()) {\n if (ctx->activation) {\n if (ctx->activation->inplaceBinOp(value, name, op, this))\n return;\n }\n }\n throwReferenceError(Value::fromString(name));\n}\n\nvoid ExecutionContext::throwError(Value value)\n{\n __qmljs_builtin_throw(value, this);\n}\n\nvoid ExecutionContext::throwError(const QString &message)\n{\n Value v = Value::fromString(this, message);\n throwError(Value::fromObject(engine->newErrorObject(v)));\n}\n\nvoid ExecutionContext::throwSyntaxError(DiagnosticMessage *message)\n{\n throwError(Value::fromObject(engine->newSyntaxErrorObject(this, message)));\n}\n\nvoid ExecutionContext::throwTypeError()\n{\n throwError(Value::fromObject(engine->newTypeErrorObject(this, QStringLiteral(\"Type error\"))));\n}\n\nvoid ExecutionContext::throwUnimplemented(const QString &message)\n{\n Value v = Value::fromString(this, QStringLiteral(\"Unimplemented \") + message);\n throwError(Value::fromObject(engine->newErrorObject(v)));\n}\n\nvoid ExecutionContext::throwReferenceError(Value value)\n{\n String *s = value.toString(this);\n QString msg = s->toQString() + QStringLiteral(\" is not defined\");\n throwError(Value::fromObject(engine->newReferenceErrorObject(this, msg)));\n}\n\nvoid ExecutionContext::initCallContext(ExecutionContext *parent, const Value that, FunctionObject *f, Value *args, unsigned argc)\n{\n MemoryManager::GCBlocker blockGC(parent->engine->memoryManager);\n\n engine = parent->engine;\n this->parent = parent;\n\n function = f;\n strictMode = f->strictMode;\n\n thisObject = that;\n if (!strictMode && !thisObject.isObject()) {\n if (thisObject.isUndefined() || thisObject.isNull())\n thisObject = engine->globalObject;\n else\n thisObject = thisObject.toObject(this);\n }\n\n arguments = args;\n argumentCount = argc;\n if (function->needsActivation || argc < function->formalParameterCount){\n arguments = new Value[qMax(argc, function->formalParameterCount)];\n if (argc)\n std::copy(args, args + argc, arguments);\n if (argc < function->formalParameterCount)\n std::fill(arguments + argc, arguments + function->formalParameterCount, Value::undefinedValue());\n }\n locals = function->varCount ? new Value[function->varCount] : 0;\n if (function->varCount)\n std::fill(locals, locals + function->varCount, Value::undefinedValue());\n\n if (function->needsActivation)\n activation = engine->newActivationObject();\n else\n activation = 0;\n\n withObject = 0;\n\n\n if (engine->debugger)\n engine->debugger->aboutToCall(f, this);\n}\n\nvoid ExecutionContext::leaveCallContext()\n{\n \/\/ ## Should rather be handled by a the activation object having a ref to the environment\n if (activation) {\n delete[] locals;\n locals = 0;\n }\n parent = 0;\n\n if (engine->debugger)\n engine->debugger->justLeft(this);\n}\n\nvoid ExecutionContext::wireUpPrototype()\n{\n assert(thisObject.isObject());\n\n Value proto = function->__get__(this, engine->id_prototype);\n if (proto.isObject())\n thisObject.objectValue()->prototype = proto.objectValue();\n else\n thisObject.objectValue()->prototype = engine->objectPrototype;\n}\n\n} \/\/ namespace VM\n} \/\/ namespace QQmlJS\n<|endoftext|>"} {"text":"#include \"module.h\"\n\n#include \"resolve.h\"\n#include \"environment.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nstatic QJSValue bindMethod(const QJSValue &obj, const char *name)\n{\n auto method = obj.property(name);\n return method.property(\"bind\").callWithInstance(method, {obj});\n}\n\nModule::Module(Environment *environment, const QString &fileName, QObject *parent) :\n QObject(parent),\n mEnvironment(environment),\n mExports(environment->engine()->newObject()),\n mFileName(fileName)\n{\n}\n\nModule::~Module()\n{\n}\n\nvoid Module::setExports(const QJSValue &exports)\n{\n mExports = exports;\n}\n\nQString Module::resolveRequire(const QString &path) const\n{\n auto file = resolve::require(path, mFileName, mEnvironment->builtins().keys());\n if (file.isEmpty()) {\n \/\/ TODO: throw errors (impossible with Qt public API only?)\n qWarning() << \"cannot load module\" << path << \"from\" << mFileName;\n }\n return file;\n}\n\nQJSValue Module::require(const QString &path)\n{\n auto fileName = resolveRequire(path);\n if (fileName.isEmpty()) {\n return QJSValue();\n }\n\n auto module = mEnvironment->modules()->value(fileName, nullptr);\n\n if (!module) {\n module = new Module(mEnvironment, fileName, this);\n\n module->mParentModule = this;\n mChildModules << module;\n\n module->load();\n }\n\n return module->exports();\n}\n\nvoid Module::load()\n{\n QFile file(mFileName);\n\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qWarning() << \"cannot open file: \" << mFileName;\n return;\n }\n\n auto header = \"(function (module, exports, require, __filename, __dirname, process, Buffer) {\";\n auto content = QString::fromUtf8(file.readAll());\n auto footer = \"})\";\n\n auto scope = mEnvironment->engine()->evaluate(header + content + footer, mFileName, 0);\n\n auto module = mEnvironment->engine()->newQObject(this);\n auto require = bindMethod(module, \"require\");\n\n auto fileName = mFileName;\n auto dirName = QFileInfo(fileName).absolutePath();\n\n auto process = mEnvironment->builtins()[\"__process\"];\n auto bufferClass = mEnvironment->builtins()[\"__Buffer\"];\n\n mEnvironment->modules()->insert(mFileName, this);\n\n scope.call({module, exports(), require, fileName, dirName, process, bufferClass});\n}\nLinebreak after module header and before footer#include \"module.h\"\n\n#include \"resolve.h\"\n#include \"environment.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nstatic QJSValue bindMethod(const QJSValue &obj, const char *name)\n{\n auto method = obj.property(name);\n return method.property(\"bind\").callWithInstance(method, {obj});\n}\n\nModule::Module(Environment *environment, const QString &fileName, QObject *parent) :\n QObject(parent),\n mEnvironment(environment),\n mExports(environment->engine()->newObject()),\n mFileName(fileName)\n{\n}\n\nModule::~Module()\n{\n}\n\nvoid Module::setExports(const QJSValue &exports)\n{\n mExports = exports;\n}\n\nQString Module::resolveRequire(const QString &path) const\n{\n auto file = resolve::require(path, mFileName, mEnvironment->builtins().keys());\n if (file.isEmpty()) {\n \/\/ TODO: throw errors (impossible with Qt public API only?)\n qWarning() << \"cannot load module\" << path << \"from\" << mFileName;\n }\n return file;\n}\n\nQJSValue Module::require(const QString &path)\n{\n auto fileName = resolveRequire(path);\n if (fileName.isEmpty()) {\n return QJSValue();\n }\n\n auto module = mEnvironment->modules()->value(fileName, nullptr);\n\n if (!module) {\n module = new Module(mEnvironment, fileName, this);\n\n module->mParentModule = this;\n mChildModules << module;\n\n module->load();\n }\n\n return module->exports();\n}\n\nvoid Module::load()\n{\n QFile file(mFileName);\n\n if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n qWarning() << \"cannot open file: \" << mFileName;\n return;\n }\n\n auto header = \"(function (module, exports, require, __filename, __dirname, process, Buffer) {\\n\";\n auto content = QString::fromUtf8(file.readAll());\n auto footer = \"\\n})\";\n\n auto scope = mEnvironment->engine()->evaluate(header + content + footer, mFileName, 0);\n\n auto module = mEnvironment->engine()->newQObject(this);\n auto require = bindMethod(module, \"require\");\n\n auto fileName = mFileName;\n auto dirName = QFileInfo(fileName).absolutePath();\n\n auto process = mEnvironment->builtins()[\"__process\"];\n auto bufferClass = mEnvironment->builtins()[\"__Buffer\"];\n\n mEnvironment->modules()->insert(mFileName, this);\n\n scope.call({module, exports(), require, fileName, dirName, process, bufferClass});\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 2.0.0, packaged on July 2010.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n *****************************************************************************\/\n\n#include \"glc_cachemanager.h\"\n#include \n\n\nGLC_CacheManager::GLC_CacheManager(const QString& path)\n: m_Dir()\n, m_UseCompression(true)\n, m_CompressionLevel(-1)\n{\n\tif (! path.isEmpty())\n\t{\n\t\tQFileInfo pathInfo(path);\n\t\tif (pathInfo.isDir() && pathInfo.isReadable())\n\t\t{\n\t\t\tm_Dir.setPath(path);\n\t\t}\n\t}\n}\n\n\/\/ Copy constructor\nGLC_CacheManager::GLC_CacheManager(const GLC_CacheManager& cacheManager)\n:m_Dir(cacheManager.m_Dir)\n, m_UseCompression(cacheManager.m_UseCompression)\n, m_CompressionLevel(cacheManager.m_CompressionLevel)\n{\n\n}\n\n\/\/ Assignement operator\nGLC_CacheManager& GLC_CacheManager::operator=(const GLC_CacheManager& cacheManager)\n{\n\tm_Dir= cacheManager.m_Dir;\n\tm_UseCompression= cacheManager.m_UseCompression;\n\tm_CompressionLevel= cacheManager.m_CompressionLevel;\n\n\treturn *this;\n}\n\nGLC_CacheManager::~GLC_CacheManager()\n{\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Return true if the cache is is readable\nbool GLC_CacheManager::isReadable() const\n{\n\tbool isReadable= true;\n\tisReadable= isReadable && m_Dir.exists();\n\tQFileInfo dirInfo(m_Dir.absolutePath());\n\tisReadable= isReadable && dirInfo.isReadable();\n\n\treturn isReadable;\n\n}\n\n\/\/ Return true if the cache is writable\nbool GLC_CacheManager::isWritable() const\n{\n\tbool isWritable= true;\n\tisWritable= isWritable && m_Dir.exists();\n\tQFileInfo dirInfo(m_Dir.absolutePath());\n\tisWritable= isWritable && dirInfo.isWritable();\n\n\treturn isWritable;\n}\n\n\/\/ Return True if the specified file is cashed in the specified context\nbool GLC_CacheManager::isCashed(const QString& context, const QString& fileName) const\n{\n\tif (! isReadable()) return false;\n\n\tQFileInfo fileInfo(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName + '.' + GLC_BSRep::suffix());\n\treturn fileInfo.exists();\n}\n\n\/\/ Return True if the cached file is usable\nbool GLC_CacheManager::isUsable(const QDateTime& timeStamp, const QString& context, const QString& fileName) const\n{\n\tbool result= isCashed(context, fileName);\n\n\tif (result)\n\t{\n\t\tQFileInfo cacheFileInfo(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName+ '.' + GLC_BSRep::suffix());\n\t\t\/\/result= result && (timeStamp == cacheFileInfo.lastModified());\n\t\tresult= result && cacheFileInfo.isReadable();\n\t\tif (result)\n\t\t{\n\t\t\tGLC_BSRep binaryRep;\n\t\t\tbinaryRep.setAbsoluteFileName(cacheFileInfo.absoluteFilePath());\n\t\t\tresult= result && binaryRep.repIsUpToDate(timeStamp);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\/\/ Return the binary serialized representation of the specified file\nGLC_BSRep GLC_CacheManager::binary3DRep(const QString& context, const QString& fileName) const\n{\n\tconst QString absoluteFileName(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName + '.' + GLC_BSRep::suffix());\n\tGLC_BSRep binaryRep(absoluteFileName);\n\n\treturn binaryRep;\n}\n\n\/\/ Add the specified file in the cache\nbool GLC_CacheManager::addToCache(const QString& context, const GLC_3DRep& rep)\n{\n\tQ_ASSERT(!rep.fileName().isEmpty());\n\tbool addedToCache= isWritable();\n\tif (addedToCache)\n\t{\n\t\tQFileInfo contextCacheInfo(m_Dir.absolutePath() + QDir::separator() + context);\n\t\tif (! contextCacheInfo.exists())\n\t\t{\n\t\t\taddedToCache= m_Dir.mkdir(context);\n\t\t}\n\t\tif (addedToCache)\n\t\t{\n\t\t\tQString repFileName= rep.fileName();\n\t\t\tif (glc::isArchiveString(repFileName))\n\t\t\t{\n\t\t\t\trepFileName= glc::archiveEntryFileName(repFileName);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trepFileName= QFileInfo(repFileName).fileName();\n\t\t\t}\n\t\t\tconst QString binaryFileName= contextCacheInfo.filePath() + QDir::separator() + repFileName;\n\t\t\tGLC_BSRep binariRep(binaryFileName, m_UseCompression);\n\t\t\tbinariRep.setCompressionLevel(m_CompressionLevel);\n\t\t\taddedToCache= binariRep.save(rep);\n\t\t}\n\t}\n\n\treturn addedToCache;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Set the cache file path\nbool GLC_CacheManager::setCachePath(const QString& path)\n{\n\tQFileInfo pathInfo(path);\n\tbool result= pathInfo.isDir();\n\tresult= result && pathInfo.isReadable();\n\n\tif (result)\n\t{\n\t\tm_Dir.setPath(path);\n\t}\n\treturn result;\n}\n\nrefactoring\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 2.0.0, packaged on July 2010.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n *****************************************************************************\/\n\n#include \"glc_cachemanager.h\"\n#include \n\n\nGLC_CacheManager::GLC_CacheManager(const QString& path)\n: m_Dir()\n, m_UseCompression(true)\n, m_CompressionLevel(-1)\n{\n\tif (! path.isEmpty())\n\t{\n\t\tQFileInfo pathInfo(path);\n\t\tif (pathInfo.isDir() && pathInfo.isReadable())\n\t\t{\n\t\t\tm_Dir.setPath(path);\n\t\t}\n\t}\n}\n\n\/\/ Copy constructor\nGLC_CacheManager::GLC_CacheManager(const GLC_CacheManager& cacheManager)\n:m_Dir(cacheManager.m_Dir)\n, m_UseCompression(cacheManager.m_UseCompression)\n, m_CompressionLevel(cacheManager.m_CompressionLevel)\n{\n\n}\n\n\/\/ Assignement operator\nGLC_CacheManager& GLC_CacheManager::operator=(const GLC_CacheManager& cacheManager)\n{\n\tm_Dir= cacheManager.m_Dir;\n\tm_UseCompression= cacheManager.m_UseCompression;\n\tm_CompressionLevel= cacheManager.m_CompressionLevel;\n\n\treturn *this;\n}\n\nGLC_CacheManager::~GLC_CacheManager()\n{\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Return true if the cache is is readable\nbool GLC_CacheManager::isReadable() const\n{\n\tbool isReadable= true;\n\tisReadable= isReadable && m_Dir.exists();\n\tQFileInfo dirInfo(m_Dir.absolutePath());\n\tisReadable= isReadable && dirInfo.isReadable();\n\n\treturn isReadable;\n\n}\n\n\/\/ Return true if the cache is writable\nbool GLC_CacheManager::isWritable() const\n{\n\tbool isWritable= true;\n\tisWritable= isWritable && m_Dir.exists();\n\tQFileInfo dirInfo(m_Dir.absolutePath());\n\tisWritable= isWritable && dirInfo.isWritable();\n\n\treturn isWritable;\n}\n\n\/\/ Return True if the specified file is cashed in the specified context\nbool GLC_CacheManager::isCashed(const QString& context, const QString& fileName) const\n{\n\tif (! isReadable()) return false;\n\n\tQFileInfo fileInfo(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName + '.' + GLC_BSRep::suffix());\n\treturn fileInfo.exists();\n}\n\n\/\/ Return True if the cached file is usable\nbool GLC_CacheManager::isUsable(const QDateTime& timeStamp, const QString& context, const QString& fileName) const\n{\n\tbool result= isCashed(context, fileName);\n\n\tif (result)\n\t{\n\t\tQFileInfo cacheFileInfo(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName+ '.' + GLC_BSRep::suffix());\n\t\t\/\/result= result && (timeStamp == cacheFileInfo.lastModified());\n\t\tresult= result && cacheFileInfo.isReadable();\n\t\tif (result)\n\t\t{\n\t\t\tGLC_BSRep binaryRep;\n\t\t\tbinaryRep.setAbsoluteFileName(cacheFileInfo.absoluteFilePath());\n\t\t\tresult= result && binaryRep.isUsable(timeStamp);\n\t\t}\n\t}\n\n\treturn result;\n}\n\n\/\/ Return the binary serialized representation of the specified file\nGLC_BSRep GLC_CacheManager::binary3DRep(const QString& context, const QString& fileName) const\n{\n\tconst QString absoluteFileName(m_Dir.absolutePath() + QDir::separator() + context + QDir::separator() + fileName + '.' + GLC_BSRep::suffix());\n\tGLC_BSRep binaryRep(absoluteFileName);\n\n\treturn binaryRep;\n}\n\n\/\/ Add the specified file in the cache\nbool GLC_CacheManager::addToCache(const QString& context, const GLC_3DRep& rep)\n{\n\tQ_ASSERT(!rep.fileName().isEmpty());\n\tbool addedToCache= isWritable();\n\tif (addedToCache)\n\t{\n\t\tQFileInfo contextCacheInfo(m_Dir.absolutePath() + QDir::separator() + context);\n\t\tif (! contextCacheInfo.exists())\n\t\t{\n\t\t\taddedToCache= m_Dir.mkdir(context);\n\t\t}\n\t\tif (addedToCache)\n\t\t{\n\t\t\tQString repFileName= rep.fileName();\n\t\t\tif (glc::isArchiveString(repFileName))\n\t\t\t{\n\t\t\t\trepFileName= glc::archiveEntryFileName(repFileName);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trepFileName= QFileInfo(repFileName).fileName();\n\t\t\t}\n\t\t\tconst QString binaryFileName= contextCacheInfo.filePath() + QDir::separator() + repFileName;\n\t\t\tGLC_BSRep binariRep(binaryFileName, m_UseCompression);\n\t\t\tbinariRep.setCompressionLevel(m_CompressionLevel);\n\t\t\taddedToCache= binariRep.save(rep);\n\t\t}\n\t}\n\n\treturn addedToCache;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Set the cache file path\nbool GLC_CacheManager::setCachePath(const QString& path)\n{\n\tQFileInfo pathInfo(path);\n\tbool result= pathInfo.isDir();\n\tresult= result && pathInfo.isReadable();\n\n\tif (result)\n\t{\n\t\tm_Dir.setPath(path);\n\t}\n\treturn result;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkRRect.h\"\n#include \"SkPath.h\"\n\nclass ScaledStrokesGM : public skiagm::GM {\npublic:\n ScaledStrokesGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"scaledstrokes\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(640, 320);\n }\n\n static void draw_path(SkScalar size, SkCanvas* canvas, SkPaint paint) {\n SkScalar c = 0.551915024494f * size;\n SkPath path;\n path.moveTo(0.0f, size);\n path.cubicTo(c, size, size, c, size, 0.0f);\n path.cubicTo(size, -c, c, -size, 0.0f, -size);\n path.cubicTo(-c, -size, -size, -c, -size, 0.0f);\n path.cubicTo(-size, c, -c, size, 0.0f, size);\n canvas->drawPath(path, paint);\n }\n\n void onDraw(SkCanvas* canvas) override {\n SkPaint paint;\n SkPath path;\n paint.setStyle(SkPaint::Style::kStroke_Style);\n canvas->translate(5.0f, 5.0f);\n const SkScalar size = 60.0f;\n for (int i = 0; i < 2; i++) {\n paint.setAntiAlias(i == 1);\n canvas->save();\n for (int j = 0; j < 4; j++) {\n SkScalar scale = 4.0f - j;\n paint.setStrokeWidth(4.0f \/ scale);\n canvas->save();\n canvas->translate(size \/ 2.0f, size \/ 2.0f);\n canvas->scale(scale, scale);\n draw_path(size \/ 2.0f \/ scale, canvas, paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(size \/ 2.0f, 80.0f + size \/ 2.0f);\n canvas->scale(scale, scale);\n canvas->drawCircle(0.0f, 0.0f, size \/ 2.0f \/ scale, paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(0.0f, 160.0f);\n canvas->scale(scale, scale);\n canvas->drawRect(SkRect::MakeXYWH(0.0f, 0.0f, size \/ scale, size \/ scale), paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(0.0f, 240.0f);\n canvas->scale(scale, scale);\n canvas->drawLine(0.0f, 0.0f, size \/ scale, size \/ scale, paint);\n canvas->restore();\n\n canvas->translate(80.0f, 0.0f);\n }\n canvas->restore();\n }\n\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\nDEF_GM( return new ScaledStrokesGM; )\nFix scaledstrokes GM\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkRRect.h\"\n#include \"SkPath.h\"\n\nclass ScaledStrokesGM : public skiagm::GM {\npublic:\n ScaledStrokesGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"scaledstrokes\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(640, 320);\n }\n\n static void draw_path(SkScalar size, SkCanvas* canvas, SkPaint paint) {\n SkScalar c = 0.551915024494f * size;\n SkPath path;\n path.moveTo(0.0f, size);\n path.cubicTo(c, size, size, c, size, 0.0f);\n path.cubicTo(size, -c, c, -size, 0.0f, -size);\n path.cubicTo(-c, -size, -size, -c, -size, 0.0f);\n path.cubicTo(-size, c, -c, size, 0.0f, size);\n canvas->drawPath(path, paint);\n }\n\n void onDraw(SkCanvas* canvas) override {\n SkPaint paint;\n SkPath path;\n paint.setStyle(SkPaint::Style::kStroke_Style);\n canvas->translate(5.0f, 5.0f);\n const SkScalar size = 60.0f;\n for (int i = 0; i < 2; i++) {\n paint.setAntiAlias(i == 1);\n for (int j = 0; j < 4; j++) {\n SkScalar scale = 4.0f - j;\n paint.setStrokeWidth(4.0f \/ scale);\n canvas->save();\n canvas->translate(size \/ 2.0f, size \/ 2.0f);\n canvas->scale(scale, scale);\n draw_path(size \/ 2.0f \/ scale, canvas, paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(size \/ 2.0f, 80.0f + size \/ 2.0f);\n canvas->scale(scale, scale);\n canvas->drawCircle(0.0f, 0.0f, size \/ 2.0f \/ scale, paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(0.0f, 160.0f);\n canvas->scale(scale, scale);\n canvas->drawRect(SkRect::MakeXYWH(0.0f, 0.0f, size \/ scale, size \/ scale), paint);\n canvas->restore();\n\n canvas->save();\n canvas->translate(0.0f, 240.0f);\n canvas->scale(scale, scale);\n canvas->drawLine(0.0f, 0.0f, size \/ scale, size \/ scale, paint);\n canvas->restore();\n\n canvas->translate(80.0f, 0.0f);\n }\n }\n\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\nDEF_GM( return new ScaledStrokesGM; )\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace blackhole {\nnamespace testing {\nnamespace formatter {\n\nusing ::blackhole::formatter::json_t;\nusing ::blackhole::formatter::routing_t;\n\nTEST(json_t, FormatMessage) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n}\n\nTEST(json_t, FormatSeverity) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(4, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n\n ASSERT_TRUE(doc.HasMember(\"severity\"));\n ASSERT_TRUE(doc[\"severity\"].IsInt());\n EXPECT_EQ(4, doc[\"severity\"].GetInt());\n}\n\nTEST(json_t, FormatTimestamp) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(4, message, pack);\n record.activate();\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n\n ASSERT_TRUE(doc.HasMember(\"timestamp\"));\n ASSERT_TRUE(doc[\"timestamp\"].IsUint64());\n EXPECT_TRUE(doc[\"timestamp\"].GetUint64() > 0);\n}\n\nTEST(json_t, FormatAttribute) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"counter\", 42}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n\n ASSERT_TRUE(doc.HasMember(\"counter\"));\n ASSERT_TRUE(doc[\"counter\"].IsInt());\n EXPECT_EQ(42, doc[\"counter\"].GetInt());\n}\n\nTEST(json_t, FormatAttributeNull) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", nullptr}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"endpoint\"].IsNull());\n}\n\nTEST(json_t, FormatAttributeBool) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"available\", true}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"available\"));\n ASSERT_TRUE(doc[\"available\"].IsBool());\n EXPECT_TRUE(doc[\"available\"].GetBool());\n}\n\nTEST(json_t, FormatAttributeDouble) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"pi\", 3.1415}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"pi\"));\n ASSERT_TRUE(doc[\"pi\"].IsDouble());\n EXPECT_DOUBLE_EQ(3.1415, doc[\"pi\"].GetDouble());\n}\n\nTEST(json_t, FormatAttributeString) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n\n ASSERT_TRUE(doc.HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"endpoint\"].IsString());\n EXPECT_STREQ(\"127.0.0.1:8080\", doc[\"endpoint\"].GetString());\n}\n\nTEST(json_t, FormatMessageWithRouting) {\n json_t formatter(routing_t().spec(\"\/fields\", {\"message\"}));\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"fields\"));\n ASSERT_TRUE(doc[\"fields\"].HasMember(\"message\"));\n ASSERT_TRUE(doc[\"fields\"][\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"fields\"][\"message\"].GetString());\n}\n\nTEST(json_t, FormatAttributeStringWithRouting) {\n json_t formatter(routing_t().spec(\"\/fields\", {\"endpoint\"}));\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"fields\"));\n ASSERT_TRUE(doc[\"fields\"].HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"fields\"][\"endpoint\"].IsString());\n EXPECT_STREQ(\"127.0.0.1:8080\", doc[\"fields\"][\"endpoint\"].GetString());\n}\n\n} \/\/ namespace formatter\n} \/\/ namespace testing\n} \/\/ namespace blackhole\nchore(tests): check nested routing#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace blackhole {\nnamespace testing {\nnamespace formatter {\n\nusing ::blackhole::formatter::json_t;\nusing ::blackhole::formatter::routing_t;\n\nTEST(json_t, FormatMessage) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n}\n\nTEST(json_t, FormatSeverity) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(4, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n\n ASSERT_TRUE(doc.HasMember(\"severity\"));\n ASSERT_TRUE(doc[\"severity\"].IsInt());\n EXPECT_EQ(4, doc[\"severity\"].GetInt());\n}\n\nTEST(json_t, FormatTimestamp) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(4, message, pack);\n record.activate();\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n\n ASSERT_TRUE(doc.HasMember(\"timestamp\"));\n ASSERT_TRUE(doc[\"timestamp\"].IsUint64());\n EXPECT_TRUE(doc[\"timestamp\"].GetUint64() > 0);\n}\n\nTEST(json_t, FormatAttribute) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"counter\", 42}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n\n ASSERT_TRUE(doc.HasMember(\"counter\"));\n ASSERT_TRUE(doc[\"counter\"].IsInt());\n EXPECT_EQ(42, doc[\"counter\"].GetInt());\n}\n\nTEST(json_t, FormatAttributeNull) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", nullptr}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"endpoint\"].IsNull());\n}\n\nTEST(json_t, FormatAttributeBool) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"available\", true}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"available\"));\n ASSERT_TRUE(doc[\"available\"].IsBool());\n EXPECT_TRUE(doc[\"available\"].GetBool());\n}\n\nTEST(json_t, FormatAttributeDouble) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"pi\", 3.1415}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"pi\"));\n ASSERT_TRUE(doc[\"pi\"].IsDouble());\n EXPECT_DOUBLE_EQ(3.1415, doc[\"pi\"].GetDouble());\n}\n\nTEST(json_t, FormatAttributeString) {\n json_t formatter;\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"message\"));\n ASSERT_TRUE(doc[\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"message\"].GetString());\n\n ASSERT_TRUE(doc.HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"endpoint\"].IsString());\n EXPECT_STREQ(\"127.0.0.1:8080\", doc[\"endpoint\"].GetString());\n}\n\nTEST(json_t, FormatMessageWithRouting) {\n json_t formatter(routing_t().spec(\"\/fields\", {\"message\"}));\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"fields\"));\n ASSERT_TRUE(doc[\"fields\"].HasMember(\"message\"));\n ASSERT_TRUE(doc[\"fields\"][\"message\"].IsString());\n EXPECT_STREQ(\"value\", doc[\"fields\"][\"message\"].GetString());\n}\n\nTEST(json_t, FormatAttributeStringWithRouting) {\n json_t formatter(routing_t().spec(\"\/fields\", {\"endpoint\"}));\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"fields\"));\n ASSERT_TRUE(doc[\"fields\"].HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"fields\"][\"endpoint\"].IsString());\n EXPECT_STREQ(\"127.0.0.1:8080\", doc[\"fields\"][\"endpoint\"].GetString());\n}\n\nTEST(json_t, FormatAttributeStringWithNestedRouting) {\n json_t formatter(routing_t().spec(\"\/fields\/external\", {\"endpoint\"}));\n\n const string_view message(\"value\");\n const attribute_list attributes{{\"endpoint\", \"127.0.0.1:8080\"}};\n const attribute_pack pack{attributes};\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n rapidjson::Document doc;\n doc.Parse<0>(writer.result().to_string().c_str());\n ASSERT_TRUE(doc.HasMember(\"fields\"));\n ASSERT_TRUE(doc[\"fields\"].HasMember(\"external\"));\n ASSERT_TRUE(doc[\"fields\"][\"external\"].IsObject());\n ASSERT_TRUE(doc[\"fields\"][\"external\"].HasMember(\"endpoint\"));\n ASSERT_TRUE(doc[\"fields\"][\"external\"][\"endpoint\"].IsString());\n EXPECT_STREQ(\"127.0.0.1:8080\", doc[\"fields\"][\"external\"][\"endpoint\"].GetString());\n}\n\n} \/\/ namespace formatter\n} \/\/ namespace testing\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"\n#ifndef __BTREE_KEY_VALUE_STORE_HPP__\n#define __BTREE_KEY_VALUE_STORE_HPP__\n\n#include \"config\/alloc.hpp\"\n#include \"buffer_cache\/buffer_cache.hpp\"\n#include \"btree\/node.hpp\" \/\/ For btree_superblock_t\n#include \"btree\/fsm.hpp\"\n#include \"utils.hpp\"\n#include \"containers\/intrusive_list.hpp\"\n#include \"concurrency\/access.hpp\"\n\n\/* When the serializer starts up, it will create an initial superblock and initialize it to zero.\nThis isn't quite the behavior we want. The job of initialize_superblock_fsm is to initialize the\nsuperblock to contain NULL_BLOCK_ID rather than zero as the root node. *\/\n\nclass initialize_superblock_fsm_t :\n private block_available_callback_t,\n private transaction_begin_callback_t,\n private transaction_commit_callback_t,\n public alloc_mixin_t, initialize_superblock_fsm_t>{\n\npublic:\n initialize_superblock_fsm_t(cache_t *cache)\n : state(state_unstarted), cache(cache), sb_buf(NULL), txn(NULL)\n {}\n ~initialize_superblock_fsm_t() {\n assert(state == state_unstarted || state == state_done);\n }\n \n struct callback_t {\n virtual void on_initialize_superblock() = 0;\n };\n \n bool initialize_superblock_if_necessary(callback_t *cb) {\n assert(state == state_unstarted);\n state = state_begin_transaction;\n callback = NULL;\n if (next_initialize_superblock_step()) {\n return true;\n } else {\n callback = cb;\n return false;\n }\n }\n\nprivate:\n enum state_t {\n state_unstarted,\n state_begin_transaction,\n state_beginning_transaction,\n state_acquire_superblock,\n state_acquiring_superblock,\n state_make_change,\n state_commit_transaction,\n state_committing_transaction,\n state_finish,\n state_done\n } state;\n \n cache_t *cache;\n buf_t *sb_buf;\n transaction_t *txn;\n callback_t *callback;\n \n bool next_initialize_superblock_step() {\n \n if (state == state_begin_transaction) {\n txn = cache->begin_transaction(rwi_write, this);\n if (txn) {\n state = state_acquire_superblock;\n } else {\n state = state_beginning_transaction;\n return false;\n }\n }\n \n if (state == state_acquire_superblock) {\n sb_buf = txn->acquire(SUPERBLOCK_ID, rwi_write, this);\n if (sb_buf) {\n state = state_make_change;\n } else {\n state = state_acquiring_superblock;\n return false;\n }\n }\n \n if (state == state_make_change) {\n btree_superblock_t *sb = (btree_superblock_t*)(sb_buf->get_data_write());\n \/\/ The serializer will init the superblock to zeroes if the database is newly created.\n if (!sb->database_exists) {\n sb->database_exists = 1;\n sb->root_block = NULL_BLOCK_ID;\n }\n sb_buf->release();\n state = state_commit_transaction;\n }\n \n if (state == state_commit_transaction) {\n if (txn->commit(this)) {\n state = state_finish;\n } else {\n state = state_committing_transaction;\n return false;\n }\n }\n \n if (state == state_finish) {\n state = state_done;\n if (callback) callback->on_initialize_superblock();\n return true;\n }\n \n fail(\"Unexpected state\");\n }\n \n void on_txn_begin(transaction_t *t) {\n assert(state == state_beginning_transaction);\n txn = t;\n state = state_acquire_superblock;\n next_initialize_superblock_step();\n }\n \n void on_txn_commit(transaction_t *t) {\n assert(state == state_committing_transaction);\n state = state_finish;\n next_initialize_superblock_step();\n }\n \n void on_block_available(buf_t *buf) {\n assert(state == state_acquiring_superblock);\n sb_buf = buf;\n state = state_make_change;\n next_initialize_superblock_step();\n }\n};\n\n\/* btree_key_value_store_t is a thin wrapper around cache_t that handles initializing the buffer\ncache for the purpose of storing a btree. *\/\n\nclass btree_key_value_store_t :\n private cache_t::ready_callback_t,\n private initialize_superblock_fsm_t::callback_t,\n private cache_t::shutdown_callback_t\n{\n \npublic:\n btree_key_value_store_t(\n char *filename,\n size_t block_size,\n size_t max_size,\n bool wait_for_flush,\n unsigned int flush_timer_ms,\n unsigned int flush_threshold_percent)\n : state(state_unstarted),\n cache(filename, block_size, max_size, wait_for_flush, flush_timer_ms, flush_threshold_percent)\n { }\n\npublic:\n struct ready_callback_t {\n virtual void on_store_ready() = 0;\n };\n bool start(ready_callback_t *cb) {\n assert(state == state_unstarted);\n state = state_starting_up_start_cache;\n ready_callback = NULL;\n if (next_starting_up_step()) {\n return true;\n } else {\n ready_callback = cb;\n return false;\n }\n }\nprivate:\n bool next_starting_up_step() {\n \n if (state == state_starting_up_start_cache) {\n if (cache.start(this)) {\n state = state_starting_up_initialize_superblock;\n } else {\n state = state_starting_up_waiting_for_cache;\n return false;\n }\n }\n \n if (state == state_starting_up_initialize_superblock) {\n sb_fsm = new initialize_superblock_fsm_t(&cache);\n if (sb_fsm->initialize_superblock_if_necessary(this)) {\n state = state_starting_up_finish;\n } else {\n state = state_starting_up_waiting_for_superblock;\n return false;\n }\n }\n \n if (state == state_starting_up_finish) {\n \n delete sb_fsm;\n \n state = state_ready;\n if (ready_callback) ready_callback->on_store_ready();\n \n std::vector >::iterator it;\n for (it = fsms_waiting_for_ready.begin(); it != fsms_waiting_for_ready.end(); it ++) {\n btree_fsm_t *fsm = *it;\n bool done = (fsm->do_transition(NULL) == btree_fsm_t::transition_complete);\n if (done && fsm->on_complete) {\n fsm->on_complete(fsm);\n }\n }\n fsms_waiting_for_ready.clear();\n \n return true;\n }\n \n fail(\"Unexpected state\");\n }\n void on_cache_ready() {\n assert(state == state_starting_up_waiting_for_cache);\n state = state_starting_up_initialize_superblock;\n next_starting_up_step();\n }\n void on_initialize_superblock() {\n assert(state == state_starting_up_waiting_for_superblock);\n state = state_starting_up_finish;\n next_starting_up_step();\n }\n ready_callback_t *ready_callback;\n \n \/\/ TODO It's kind of hacky to queue requests here. Should we queue them on the worker instead or\n \/\/ perhaps refuse to accept connections until all the key-value stores are ready?\n std::vector > fsms_waiting_for_ready;\n\npublic:\n bool run_fsm(btree_fsm_t *fsm, btree_fsm_t::on_complete_t cb) {\n \n \/\/ The btree is constructed with no cache; here we must assign it its proper cache\n assert(!fsm->cache);\n fsm->cache = &cache;\n \n fsm->on_complete = cb;\n if (state == state_ready) {\n return (fsm->do_transition(NULL) == btree_fsm_t::transition_complete);\n } else {\n fsms_waiting_for_ready.push_back(fsm);\n return false;\n }\n }\n\npublic:\n struct shutdown_callback_t {\n virtual void on_store_shutdown() = 0;\n };\n bool shutdown(shutdown_callback_t *cb) {\n assert(state == state_ready);\n if (cache.shutdown(this)) {\n state = state_shut_down;\n return true;\n } else {\n state = state_shutting_down;\n shutdown_callback = cb;\n return false;\n }\n }\nprivate:\n void on_cache_shutdown() {\n state = state_shut_down;\n if (shutdown_callback) shutdown_callback->on_store_shutdown();\n }\n shutdown_callback_t *shutdown_callback;\n\nprivate:\n enum state_t {\n state_unstarted,\n \n state_starting_up_start_cache,\n state_starting_up_waiting_for_cache,\n state_starting_up_initialize_superblock,\n state_starting_up_waiting_for_superblock,\n state_starting_up_finish,\n \n state_ready,\n \n state_shutting_down,\n \n state_shut_down\n } state;\n \n initialize_superblock_fsm_t *sb_fsm;\n \n cache_t cache;\n};\n\ntypedef btree_key_value_store_t store_t;\n\n#endif \/* __BTREE_KEY_VALUE_STORE_HPP__ *\/\nFixing key value store to properly use get_data_read\/get_data_write\n#ifndef __BTREE_KEY_VALUE_STORE_HPP__\n#define __BTREE_KEY_VALUE_STORE_HPP__\n\n#include \"config\/alloc.hpp\"\n#include \"buffer_cache\/buffer_cache.hpp\"\n#include \"btree\/node.hpp\" \/\/ For btree_superblock_t\n#include \"btree\/fsm.hpp\"\n#include \"utils.hpp\"\n#include \"containers\/intrusive_list.hpp\"\n#include \"concurrency\/access.hpp\"\n\n\/* When the serializer starts up, it will create an initial superblock and initialize it to zero.\nThis isn't quite the behavior we want. The job of initialize_superblock_fsm is to initialize the\nsuperblock to contain NULL_BLOCK_ID rather than zero as the root node. *\/\n\nclass initialize_superblock_fsm_t :\n private block_available_callback_t,\n private transaction_begin_callback_t,\n private transaction_commit_callback_t,\n public alloc_mixin_t, initialize_superblock_fsm_t>{\n\npublic:\n initialize_superblock_fsm_t(cache_t *cache)\n : state(state_unstarted), cache(cache), sb_buf(NULL), txn(NULL)\n {}\n ~initialize_superblock_fsm_t() {\n assert(state == state_unstarted || state == state_done);\n }\n \n struct callback_t {\n virtual void on_initialize_superblock() = 0;\n };\n \n bool initialize_superblock_if_necessary(callback_t *cb) {\n assert(state == state_unstarted);\n state = state_begin_transaction;\n callback = NULL;\n if (next_initialize_superblock_step()) {\n return true;\n } else {\n callback = cb;\n return false;\n }\n }\n\nprivate:\n enum state_t {\n state_unstarted,\n state_begin_transaction,\n state_beginning_transaction,\n state_acquire_superblock,\n state_acquiring_superblock,\n state_make_change,\n state_commit_transaction,\n state_committing_transaction,\n state_finish,\n state_done\n } state;\n \n cache_t *cache;\n buf_t *sb_buf;\n transaction_t *txn;\n callback_t *callback;\n \n bool next_initialize_superblock_step() {\n \n if (state == state_begin_transaction) {\n txn = cache->begin_transaction(rwi_write, this);\n if (txn) {\n state = state_acquire_superblock;\n } else {\n state = state_beginning_transaction;\n return false;\n }\n }\n \n if (state == state_acquire_superblock) {\n sb_buf = txn->acquire(SUPERBLOCK_ID, rwi_write, this);\n if (sb_buf) {\n state = state_make_change;\n } else {\n state = state_acquiring_superblock;\n return false;\n }\n }\n \n if (state == state_make_change) {\n const btree_superblock_t *sb = (const btree_superblock_t*)(sb_buf->get_data_read());\n \/\/ The serializer will init the superblock to zeroes if the database is newly created.\n if (!sb->database_exists) {\n btree_superblock_t *sb = (btree_superblock_t*)(sb_buf->get_data_write());\n sb->database_exists = 1;\n sb->root_block = NULL_BLOCK_ID;\n }\n sb_buf->release();\n state = state_commit_transaction;\n }\n \n if (state == state_commit_transaction) {\n if (txn->commit(this)) {\n state = state_finish;\n } else {\n state = state_committing_transaction;\n return false;\n }\n }\n \n if (state == state_finish) {\n state = state_done;\n if (callback) callback->on_initialize_superblock();\n return true;\n }\n \n fail(\"Unexpected state\");\n }\n \n void on_txn_begin(transaction_t *t) {\n assert(state == state_beginning_transaction);\n txn = t;\n state = state_acquire_superblock;\n next_initialize_superblock_step();\n }\n \n void on_txn_commit(transaction_t *t) {\n assert(state == state_committing_transaction);\n state = state_finish;\n next_initialize_superblock_step();\n }\n \n void on_block_available(buf_t *buf) {\n assert(state == state_acquiring_superblock);\n sb_buf = buf;\n state = state_make_change;\n next_initialize_superblock_step();\n }\n};\n\n\/* btree_key_value_store_t is a thin wrapper around cache_t that handles initializing the buffer\ncache for the purpose of storing a btree. *\/\n\nclass btree_key_value_store_t :\n private cache_t::ready_callback_t,\n private initialize_superblock_fsm_t::callback_t,\n private cache_t::shutdown_callback_t\n{\n \npublic:\n btree_key_value_store_t(\n char *filename,\n size_t block_size,\n size_t max_size,\n bool wait_for_flush,\n unsigned int flush_timer_ms,\n unsigned int flush_threshold_percent)\n : state(state_unstarted),\n cache(filename, block_size, max_size, wait_for_flush, flush_timer_ms, flush_threshold_percent)\n { }\n\npublic:\n struct ready_callback_t {\n virtual void on_store_ready() = 0;\n };\n bool start(ready_callback_t *cb) {\n assert(state == state_unstarted);\n state = state_starting_up_start_cache;\n ready_callback = NULL;\n if (next_starting_up_step()) {\n return true;\n } else {\n ready_callback = cb;\n return false;\n }\n }\nprivate:\n bool next_starting_up_step() {\n \n if (state == state_starting_up_start_cache) {\n if (cache.start(this)) {\n state = state_starting_up_initialize_superblock;\n } else {\n state = state_starting_up_waiting_for_cache;\n return false;\n }\n }\n \n if (state == state_starting_up_initialize_superblock) {\n sb_fsm = new initialize_superblock_fsm_t(&cache);\n if (sb_fsm->initialize_superblock_if_necessary(this)) {\n state = state_starting_up_finish;\n } else {\n state = state_starting_up_waiting_for_superblock;\n return false;\n }\n }\n \n if (state == state_starting_up_finish) {\n \n delete sb_fsm;\n \n state = state_ready;\n if (ready_callback) ready_callback->on_store_ready();\n \n std::vector >::iterator it;\n for (it = fsms_waiting_for_ready.begin(); it != fsms_waiting_for_ready.end(); it ++) {\n btree_fsm_t *fsm = *it;\n bool done = (fsm->do_transition(NULL) == btree_fsm_t::transition_complete);\n if (done && fsm->on_complete) {\n fsm->on_complete(fsm);\n }\n }\n fsms_waiting_for_ready.clear();\n \n return true;\n }\n \n fail(\"Unexpected state\");\n }\n void on_cache_ready() {\n assert(state == state_starting_up_waiting_for_cache);\n state = state_starting_up_initialize_superblock;\n next_starting_up_step();\n }\n void on_initialize_superblock() {\n assert(state == state_starting_up_waiting_for_superblock);\n state = state_starting_up_finish;\n next_starting_up_step();\n }\n ready_callback_t *ready_callback;\n \n \/\/ TODO It's kind of hacky to queue requests here. Should we queue them on the worker instead or\n \/\/ perhaps refuse to accept connections until all the key-value stores are ready?\n std::vector > fsms_waiting_for_ready;\n\npublic:\n bool run_fsm(btree_fsm_t *fsm, btree_fsm_t::on_complete_t cb) {\n \n \/\/ The btree is constructed with no cache; here we must assign it its proper cache\n assert(!fsm->cache);\n fsm->cache = &cache;\n \n fsm->on_complete = cb;\n if (state == state_ready) {\n return (fsm->do_transition(NULL) == btree_fsm_t::transition_complete);\n } else {\n fsms_waiting_for_ready.push_back(fsm);\n return false;\n }\n }\n\npublic:\n struct shutdown_callback_t {\n virtual void on_store_shutdown() = 0;\n };\n bool shutdown(shutdown_callback_t *cb) {\n assert(state == state_ready);\n if (cache.shutdown(this)) {\n state = state_shut_down;\n return true;\n } else {\n state = state_shutting_down;\n shutdown_callback = cb;\n return false;\n }\n }\nprivate:\n void on_cache_shutdown() {\n state = state_shut_down;\n if (shutdown_callback) shutdown_callback->on_store_shutdown();\n }\n shutdown_callback_t *shutdown_callback;\n\nprivate:\n enum state_t {\n state_unstarted,\n \n state_starting_up_start_cache,\n state_starting_up_waiting_for_cache,\n state_starting_up_initialize_superblock,\n state_starting_up_waiting_for_superblock,\n state_starting_up_finish,\n \n state_ready,\n \n state_shutting_down,\n \n state_shut_down\n } state;\n \n initialize_superblock_fsm_t *sb_fsm;\n \n cache_t cache;\n};\n\ntypedef btree_key_value_store_t store_t;\n\n#endif \/* __BTREE_KEY_VALUE_STORE_HPP__ *\/\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2014-2021 AscEmu Team \nThis file is released under the MIT license. See README-MIT for more information.\n*\/\n\n#include \"MoveSplineInit.h\"\n#include \"..\/world\/Units\/Creatures\/Creature.h\"\n#include \"MoveSpline.h\"\n#include \"MovementPacketBuilder.h\"\n#include \"..\/world\/Units\/Unit.h\"\n#include \"..\/world\/Objects\/Transporter.h\"\n#include \"WorldPacket.h\"\n\nnamespace MovementNew\n{\n UnitSpeedType SelectSpeedType(uint32 moveFlags)\n {\n if (moveFlags & MOVEFLAG_FLYING)\n {\n if (moveFlags & MOVEFLAG_MOVE_BACKWARD )\n return TYPE_FLY_BACK;\n else\n return TYPE_FLY;\n }\n else if (moveFlags & MOVEFLAG_SWIMMING)\n {\n if (moveFlags & MOVEFLAG_MOVE_BACKWARD)\n return TYPE_SWIM_BACK;\n else\n return TYPE_SWIM;\n }\n else if (moveFlags & MOVEFLAG_WALK)\n {\n return TYPE_WALK;\n }\n else if (moveFlags & MOVEFLAG_MOVE_BACKWARD)\n return TYPE_RUN_BACK;\n\n \/\/ Flying creatures use MOVEFLAG_CAN_FLY or MOVEFLAG_DISABLE_GRAVITY\n \/\/ Run speed is their default flight speed.\n return TYPE_RUN;\n }\n\n int32 MoveSplineInit::Launch()\n {\n MoveSpline& move_spline = *unit->movespline;\n\n \/\/ Elevators also use MOVEFLAG_TRANSPORT but we do not keep track of their position changes\n bool transport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->GetTransport();\n Location real_position;\n \/\/ there is a big chance that current position is unknown if current state is not finalized, need compute it\n \/\/ this also allows CalculatePath spline position and update map position in much greater intervals\n \/\/ Don't compute for transport movement if the unit is in a motion between two transports\n if (!move_spline.Finalized() && move_spline.onTransport == transport)\n real_position = move_spline.ComputePosition();\n else\n {\n LocationVector const* pos;\n if (!transport)\n pos = &unit->GetPosition();\n else\n pos = &unit->movement_info.transport_position;\n\n real_position.x = pos->getPositionX();\n real_position.y = pos->getPositionY();\n real_position.z = pos->getPositionZ();\n real_position.orientation = unit->GetOrientation();\n }\n\n \/\/ should i do the things that user should do? - no.\n if (args.path.empty())\n return 0;\n\n \/\/ corrent first vertex\n args.path[0] = real_position;\n args.initialOrientation = real_position.orientation;\n args.flags.enter_cycle = args.flags.cyclic;\n move_spline.onTransport = transport;\n\n uint32 moveFlags = unit->obj_movement_info.getMovementFlags();\n\n#if VERSION_STRING <= WotLK\n moveFlags |= MOVEFLAG_SPLINE_ENABLED;\n#endif\n\n if (!args.flags.backward)\n moveFlags = (moveFlags & ~(MOVEFLAG_MOVE_BACKWARD)) | MOVEFLAG_MOVE_FORWARD;\n else\n moveFlags = (moveFlags & ~(MOVEFLAG_MOVE_FORWARD)) | MOVEFLAG_MOVE_BACKWARD;\n\n if (moveFlags & MOVEFLAG_ROOTED)\n moveFlags &= ~MOVEFLAG_MOVING_MASK;\n\n if (!args.HasVelocity)\n {\n \/\/ If spline is initialized with SetWalk method it only means we need to select\n \/\/ walk move speed for it but not add walk flag to unit\n uint32 moveFlagsForSpeed = moveFlags;\n if (args.walk)\n moveFlagsForSpeed |= MOVEFLAG_WALK;\n else\n moveFlagsForSpeed &= ~MOVEFLAG_WALK;\n\n args.velocity = unit->getSpeedRate(SelectSpeedType(moveFlagsForSpeed), true);\n if (Creature* creature = static_cast(unit))\n if (creature->GetAIInterface()->hasCalledForHelp())\n args.velocity *= 0.66f;\n }\n\n \/\/ limit the speed in the same way the client does\n args.velocity = std::min(args.velocity, args.flags.catmullrom || args.flags.flying ? 50.0f : std::max(28.0f, unit->getSpeedRate(TYPE_RUN, true) * 4.0f));\n\n if (!args.Validate(unit))\n return 0;\n\n unit->obj_movement_info.flags = moveFlags;\n move_spline.Initialize(args);\n\n WorldPacket data(SMSG_MONSTER_MOVE, 64);\n data << WoWGuid(unit->getGuid());\n if (transport)\n {\n data.SetOpcode(SMSG_MONSTER_MOVE_TRANSPORT);\n data << WoWGuid(unit->getTransGuid());\n#if VERSION_STRING >= WotLK\n data << int8(unit->GetTransSeat());\n#endif\n }\n\n PacketBuilder::WriteMonsterMove(move_spline, data);\n unit->SendMessageToSet(&data, true);\n\n return move_spline.Duration();\n }\n\n void MoveSplineInit::Stop()\n {\n MoveSpline& move_spline = *unit->movespline;\n\n \/\/ No need to stop if we are not moving\n if (move_spline.Finalized())\n return;\n\n bool transport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->getTransGuid();\n Location loc;\n if (move_spline.onTransport == transport)\n loc = move_spline.ComputePosition();\n else\n {\n LocationVector const* pos;\n if (!transport)\n pos = &unit->GetPosition();\n else\n pos = &unit->obj_movement_info.transport_position;\n\n loc.x = pos->getPositionX();\n loc.y = pos->getPositionY();\n loc.z = pos->getPositionZ();\n loc.orientation = unit->GetOrientation();\n }\n\n args.flags = MoveSplineFlag::Done;\n\n#if VERSION_STRING <= WotLK\n unit->obj_movement_info.removeMovementFlag(MOVEFLAG_SPLINE_FORWARD_ENABLED);\n#endif\n\n#if VERSION_STRING >= Cata\n unit->obj_movement_info.removeMovementFlag(MOVEFLAG_MOVE_FORWARD);\n#endif\n\n move_spline.onTransport = transport;\n move_spline.Initialize(args);\n\n WorldPacket data(SMSG_MONSTER_MOVE, 64);\n data << WoWGuid(unit->getGuid());\n if (transport)\n {\n data.SetOpcode(SMSG_MONSTER_MOVE_TRANSPORT);\n data << WoWGuid(unit->getTransGuid());\n#if VERSION_STRING >= WotLK\n data << int8(unit->GetTransSeat());\n#endif\n }\n\n PacketBuilder::WriteStopMovement(loc, args.splineId, data);\n unit->SendMessageToSet(&data, true);\n }\n\n MoveSplineInit::MoveSplineInit(Unit* m) : unit(m)\n {\n args.splineId = splineIdGen.NewId();\n \/\/ Elevators also use MOVEFLAG_TRANSPORT but we do not keep track of their position changes\n args.TransformForTransport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->getTransGuid();\n \/\/ mix existing state into new\n args.flags.canswim = unit->CanSwim();\n args.walk = unit->hasUnitMovementFlag(MOVEFLAG_WALK);\n args.flags.flying = unit->obj_movement_info.hasMovementFlag(MOVEFLAG_FLYING_MASK);\n }\n\n MoveSplineInit::~MoveSplineInit() = default;\n\n void MoveSplineInit::SetFacing(Vector3 const& spot)\n {\n TransportPathTransform transform(unit, args.TransformForTransport);\n Vector3 finalSpot = transform(spot);\n args.facing.f.x = finalSpot.x;\n args.facing.f.y = finalSpot.y;\n args.facing.f.z = finalSpot.z;\n args.flags.EnableFacingPoint();\n }\n\n void MoveSplineInit::SetFacing(Unit const* target)\n {\n args.flags.EnableFacingTarget();\n args.facing.target = target->getGuid();\n }\n\n void MoveSplineInit::SetFacing(float angle)\n {\n if (args.TransformForTransport)\n {\n if (Unit* vehicle = unit->getVehicleBase())\n angle -= vehicle->GetOrientation();\n else if (Transporter* transport = unit->GetTransport())\n angle -= transport->GetOrientation();\n }\n\n args.facing.angle = G3D::wrap(angle, 0.f, (float)G3D::twoPi());\n args.flags.EnableFacingAngle();\n }\n\n void MoveSplineInit::MovebyPath(PointsArray const& controls, int32 path_offset)\n {\n args.path_Idx_offset = path_offset;\n args.path.resize(controls.size());\n std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport));\n }\n\n void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination)\n {\n MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination);\n }\n\n void MoveSplineInit::MoveTo(Vector3 const& dest, bool generatePath, bool forceDestination)\n {\n if (generatePath)\n {\n \/\/ ToDo\n }\n\n args.path_Idx_offset = 0;\n args.path.resize(2);\n TransportPathTransform transform(unit, args.TransformForTransport);\n args.path[1] = transform(dest);\n }\n\n Vector3 TransportPathTransform::operator()(Vector3 input)\n {\n if (_transformForTransport)\n {\n if (TransportBase* transport = _owner->getCurrentVehicle())\n {\n transport->CalculatePassengerOffset(input.x, input.y, input.z);\n }\n else if (TransportBase* transport = _owner->GetTransport())\n {\n transport->CalculatePassengerOffset(input.x, input.y, input.z);\n }\n }\n return input;\n }\n}\nFix unix build\/*\nCopyright (c) 2014-2021 AscEmu Team \nThis file is released under the MIT license. See README-MIT for more information.\n*\/\n\n#include \"MoveSplineInit.h\"\n#include \"..\/world\/Units\/Creatures\/Creature.h\"\n#include \"MoveSpline.h\"\n#include \"MovementPacketBuilder.h\"\n#include \"..\/world\/Units\/Unit.h\"\n#include \"..\/world\/Objects\/Transporter.h\"\n#include \"WorldPacket.h\"\n\nnamespace MovementNew\n{\n UnitSpeedType SelectSpeedType(uint32 moveFlags)\n {\n if (moveFlags & MOVEFLAG_FLYING)\n {\n if (moveFlags & MOVEFLAG_MOVE_BACKWARD )\n return TYPE_FLY_BACK;\n else\n return TYPE_FLY;\n }\n else if (moveFlags & MOVEFLAG_SWIMMING)\n {\n if (moveFlags & MOVEFLAG_MOVE_BACKWARD)\n return TYPE_SWIM_BACK;\n else\n return TYPE_SWIM;\n }\n else if (moveFlags & MOVEFLAG_WALK)\n {\n return TYPE_WALK;\n }\n else if (moveFlags & MOVEFLAG_MOVE_BACKWARD)\n return TYPE_RUN_BACK;\n\n \/\/ Flying creatures use MOVEFLAG_CAN_FLY or MOVEFLAG_DISABLE_GRAVITY\n \/\/ Run speed is their default flight speed.\n return TYPE_RUN;\n }\n\n int32 MoveSplineInit::Launch()\n {\n MoveSpline& move_spline = *unit->movespline;\n\n \/\/ Elevators also use MOVEFLAG_TRANSPORT but we do not keep track of their position changes\n bool transport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->GetTransport();\n Location real_position;\n \/\/ there is a big chance that current position is unknown if current state is not finalized, need compute it\n \/\/ this also allows CalculatePath spline position and update map position in much greater intervals\n \/\/ Don't compute for transport movement if the unit is in a motion between two transports\n if (!move_spline.Finalized() && move_spline.onTransport == transport)\n real_position = move_spline.ComputePosition();\n else\n {\n LocationVector const pos = transport ? unit->movement_info.transport_position : unit->GetPosition();\n real_position.x = pos.getPositionX();\n real_position.y = pos.getPositionY();\n real_position.z = pos.getPositionZ();\n real_position.orientation = unit->GetOrientation();\n }\n\n \/\/ should i do the things that user should do? - no.\n if (args.path.empty())\n return 0;\n\n \/\/ corrent first vertex\n args.path[0] = real_position;\n args.initialOrientation = real_position.orientation;\n args.flags.enter_cycle = args.flags.cyclic;\n move_spline.onTransport = transport;\n\n uint32 moveFlags = unit->obj_movement_info.getMovementFlags();\n\n#if VERSION_STRING <= WotLK\n moveFlags |= MOVEFLAG_SPLINE_ENABLED;\n#endif\n\n if (!args.flags.backward)\n moveFlags = (moveFlags & ~(MOVEFLAG_MOVE_BACKWARD)) | MOVEFLAG_MOVE_FORWARD;\n else\n moveFlags = (moveFlags & ~(MOVEFLAG_MOVE_FORWARD)) | MOVEFLAG_MOVE_BACKWARD;\n\n if (moveFlags & MOVEFLAG_ROOTED)\n moveFlags &= ~MOVEFLAG_MOVING_MASK;\n\n if (!args.HasVelocity)\n {\n \/\/ If spline is initialized with SetWalk method it only means we need to select\n \/\/ walk move speed for it but not add walk flag to unit\n uint32 moveFlagsForSpeed = moveFlags;\n if (args.walk)\n moveFlagsForSpeed |= MOVEFLAG_WALK;\n else\n moveFlagsForSpeed &= ~MOVEFLAG_WALK;\n\n args.velocity = unit->getSpeedRate(SelectSpeedType(moveFlagsForSpeed), true);\n if (Creature* creature = static_cast(unit))\n if (creature->GetAIInterface()->hasCalledForHelp())\n args.velocity *= 0.66f;\n }\n\n \/\/ limit the speed in the same way the client does\n args.velocity = std::min(args.velocity, args.flags.catmullrom || args.flags.flying ? 50.0f : std::max(28.0f, unit->getSpeedRate(TYPE_RUN, true) * 4.0f));\n\n if (!args.Validate(unit))\n return 0;\n\n unit->obj_movement_info.flags = moveFlags;\n move_spline.Initialize(args);\n\n WorldPacket data(SMSG_MONSTER_MOVE, 64);\n data << WoWGuid(unit->getGuid());\n if (transport)\n {\n data.SetOpcode(SMSG_MONSTER_MOVE_TRANSPORT);\n data << WoWGuid(unit->getTransGuid());\n#if VERSION_STRING >= WotLK\n data << int8(unit->GetTransSeat());\n#endif\n }\n\n PacketBuilder::WriteMonsterMove(move_spline, data);\n unit->SendMessageToSet(&data, true);\n\n return move_spline.Duration();\n }\n\n void MoveSplineInit::Stop()\n {\n MoveSpline& move_spline = *unit->movespline;\n\n \/\/ No need to stop if we are not moving\n if (move_spline.Finalized())\n return;\n\n bool transport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->getTransGuid();\n Location loc;\n if (move_spline.onTransport == transport)\n loc = move_spline.ComputePosition();\n else\n {\n LocationVector const* pos;\n if (!transport)\n pos = &unit->GetPosition();\n else\n pos = &unit->obj_movement_info.transport_position;\n\n loc.x = pos->getPositionX();\n loc.y = pos->getPositionY();\n loc.z = pos->getPositionZ();\n loc.orientation = unit->GetOrientation();\n }\n\n args.flags = MoveSplineFlag::Done;\n\n#if VERSION_STRING <= WotLK\n unit->obj_movement_info.removeMovementFlag(MOVEFLAG_SPLINE_FORWARD_ENABLED);\n#endif\n\n#if VERSION_STRING >= Cata\n unit->obj_movement_info.removeMovementFlag(MOVEFLAG_MOVE_FORWARD);\n#endif\n\n move_spline.onTransport = transport;\n move_spline.Initialize(args);\n\n WorldPacket data(SMSG_MONSTER_MOVE, 64);\n data << WoWGuid(unit->getGuid());\n if (transport)\n {\n data.SetOpcode(SMSG_MONSTER_MOVE_TRANSPORT);\n data << WoWGuid(unit->getTransGuid());\n#if VERSION_STRING >= WotLK\n data << int8(unit->GetTransSeat());\n#endif\n }\n\n PacketBuilder::WriteStopMovement(loc, args.splineId, data);\n unit->SendMessageToSet(&data, true);\n }\n\n MoveSplineInit::MoveSplineInit(Unit* m) : unit(m)\n {\n args.splineId = splineIdGen.NewId();\n \/\/ Elevators also use MOVEFLAG_TRANSPORT but we do not keep track of their position changes\n args.TransformForTransport = unit->hasUnitMovementFlag(MOVEFLAG_TRANSPORT) && unit->getTransGuid();\n \/\/ mix existing state into new\n args.flags.canswim = unit->CanSwim();\n args.walk = unit->hasUnitMovementFlag(MOVEFLAG_WALK);\n args.flags.flying = unit->obj_movement_info.hasMovementFlag(MOVEFLAG_FLYING_MASK);\n }\n\n MoveSplineInit::~MoveSplineInit() = default;\n\n void MoveSplineInit::SetFacing(Vector3 const& spot)\n {\n TransportPathTransform transform(unit, args.TransformForTransport);\n Vector3 finalSpot = transform(spot);\n args.facing.f.x = finalSpot.x;\n args.facing.f.y = finalSpot.y;\n args.facing.f.z = finalSpot.z;\n args.flags.EnableFacingPoint();\n }\n\n void MoveSplineInit::SetFacing(Unit const* target)\n {\n args.flags.EnableFacingTarget();\n args.facing.target = target->getGuid();\n }\n\n void MoveSplineInit::SetFacing(float angle)\n {\n if (args.TransformForTransport)\n {\n if (Unit* vehicle = unit->getVehicleBase())\n angle -= vehicle->GetOrientation();\n else if (Transporter* transport = unit->GetTransport())\n angle -= transport->GetOrientation();\n }\n\n args.facing.angle = G3D::wrap(angle, 0.f, (float)G3D::twoPi());\n args.flags.EnableFacingAngle();\n }\n\n void MoveSplineInit::MovebyPath(PointsArray const& controls, int32 path_offset)\n {\n args.path_Idx_offset = path_offset;\n args.path.resize(controls.size());\n std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport));\n }\n\n void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination)\n {\n MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination);\n }\n\n void MoveSplineInit::MoveTo(Vector3 const& dest, bool generatePath, bool forceDestination)\n {\n if (generatePath)\n {\n \/\/ ToDo\n }\n\n args.path_Idx_offset = 0;\n args.path.resize(2);\n TransportPathTransform transform(unit, args.TransformForTransport);\n args.path[1] = transform(dest);\n }\n\n Vector3 TransportPathTransform::operator()(Vector3 input)\n {\n if (_transformForTransport)\n {\n if (TransportBase* transport = _owner->getCurrentVehicle())\n {\n transport->CalculatePassengerOffset(input.x, input.y, input.z);\n }\n else if (TransportBase* transport = _owner->GetTransport())\n {\n transport->CalculatePassengerOffset(input.x, input.y, input.z);\n }\n }\n return input;\n }\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n\/\/ Exposing to let me us this in tests\n\/\/ The current tests fail when the cutoff is 1e8 and pass with 1e9,\n\/\/ setting 1e10 to be safe\nconstexpr double neg_binomial_2_phi_cutoff = 1e10;\n} \/\/ namespace internal\n\n\/\/ NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0]\ntemplate \nreturn_type_t neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n using T_partials_return = partials_return_t;\n\n static const char* function = \"neg_binomial_2_lpmf\";\n\n if (size_zero(n, mu, phi)) {\n return 0.0;\n }\n\n T_partials_return logp(0.0);\n check_nonnegative(function, \"Failures variable\", n);\n check_positive_finite(function, \"Location parameter\", mu);\n check_positive_finite(function, \"Precision parameter\", phi);\n check_consistent_sizes(function, \"Failures variable\", n, \"Location parameter\",\n mu, \"Precision parameter\", phi);\n\n if (!include_summand::value) {\n return 0.0;\n }\n\n using std::log;\n\n scalar_seq_view n_vec(n);\n scalar_seq_view mu_vec(mu);\n scalar_seq_view phi_vec(phi);\n size_t size = max_size(n, mu, phi);\n\n operands_and_partials ops_partials(mu, phi);\n\n size_t len_ep = max_size(mu, phi);\n size_t len_np = max_size(n, phi);\n\n VectorBuilder mu__(length(mu));\n for (size_t i = 0, size = length(mu); i < size; ++i) {\n mu__[i] = value_of(mu_vec[i]);\n }\n\n VectorBuilder phi__(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n phi__[i] = value_of(phi_vec[i]);\n }\n\n VectorBuilder log_phi(length(phi));\n for (size_t i = 0, size = length(phi); i < size; ++i) {\n log_phi[i] = log(phi__[i]);\n }\n\n VectorBuilder\n log_mu_plus_phi(len_ep);\n for (size_t i = 0; i < len_ep; ++i) {\n log_mu_plus_phi[i] = log(mu__[i] + phi__[i]);\n }\n\n VectorBuilder n_plus_phi(len_np);\n for (size_t i = 0; i < len_np; ++i) {\n n_plus_phi[i] = n_vec[i] + phi__[i];\n }\n\n for (size_t i = 0; i < size; i++) {\n if (phi__[i] > internal::neg_binomial_2_phi_cutoff) {\n \/\/ Phi is large, deferring to Poisson.\n \/\/ Copying the code here as just calling\n \/\/ poisson_lpmf does not preserve propto logic correctly\n if (include_summand::value) {\n logp -= lgamma(n_vec[i] + 1.0);\n }\n if (include_summand::value) {\n logp += multiply_log(n_vec[i], mu__[i]) - mu__[i];\n }\n\n if (!is_constant_all::value) {\n \/\/ This is the Taylor series of the full derivative for phi -> Inf\n \/\/ Obtained in Mathematica via\n \/\/ Series[n\/mu - (n + phi)\/(mu+phi),{phi,Infinity, 1}]\n \/\/ Currently ignoring the term (mu__[i] - n_vec[i]) \/ phi__[i]\n ops_partials.edge1_.partials_[i] += n_vec[i] \/ mu__[i] - 1;\n }\n\n \/\/ The derivative wrt. phi = 0 + O(1\/neg_binomial_2_phi_cutoff^2),\n \/\/ But the quadratic term is big enough to warrant inclusion here\n \/\/ (can be around 1e-6 at cutoff).\n \/\/ Expansion obtained in Mathematica via\n \/\/ Series[1 - (n + phi) \/ (mu + phi) + Log[phi] - Log[mu + phi] -\n \/\/ PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 2}]\n if (!is_constant_all::value) {\n ops_partials.edge2_.partials_[i]\n += (mu__[i] * (-mu__[i] + 2 * n_vec[i]) + n_vec[i] * (1 - n_vec[i]))\n \/ (2 * square(phi__[i]));\n }\n\n } else {\n if (include_summand::value) {\n logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);\n }\n\n logp += phi__[i] * (log_phi[i] - log_mu_plus_phi[i])\n - (n_vec[i]) * log_mu_plus_phi[i];\n\n if (include_summand::value) {\n logp += multiply_log(n_vec[i], mu__[i]);\n }\n\n if (!is_constant_all::value) {\n ops_partials.edge1_.partials_[i]\n += n_vec[i] \/ mu__[i]\n - (n_vec[i] + phi__[i]) \/ (mu__[i] + phi__[i]);\n }\n if (!is_constant_all::value) {\n ops_partials.edge2_.partials_[i]\n += 1.0 - n_plus_phi[i] \/ (mu__[i] + phi__[i]) + log_phi[i]\n - log_mu_plus_phi[i] - digamma(phi__[i])\n + digamma(n_plus_phi[i]);\n }\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate \ninline return_type_t neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n return neg_binomial_2_lpmf(n, mu, phi);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nFixed #1531 for neg_binomial_2_lpmf#ifndef STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_NEG_BINOMIAL_2_LPMF_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\nnamespace internal {\n\/\/ Exposing to let me us this in tests\n\/\/ The current tests fail when the cutoff is 1e8 and pass with 1e9,\n\/\/ setting 1e10 to be safe\nconstexpr double neg_binomial_2_phi_cutoff = 1e10;\n} \/\/ namespace internal\n\n\/\/ NegBinomial(n|mu, phi) [mu >= 0; phi > 0; n >= 0]\ntemplate \nreturn_type_t neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n using T_partials_return = partials_return_t;\n\n static const char* function = \"neg_binomial_2_lpmf\";\n\n if (size_zero(n, mu, phi)) {\n return 0.0;\n }\n\n T_partials_return logp(0.0);\n check_nonnegative(function, \"Failures variable\", n);\n check_positive_finite(function, \"Location parameter\", mu);\n check_positive_finite(function, \"Precision parameter\", phi);\n check_consistent_sizes(function, \"Failures variable\", n, \"Location parameter\",\n mu, \"Precision parameter\", phi);\n\n if (!include_summand::value) {\n return 0.0;\n }\n\n using std::log;\n\n scalar_seq_view n_vec(n);\n scalar_seq_view mu_vec(mu);\n scalar_seq_view phi_vec(phi);\n size_t size_max = max_size(n, mu, phi);\n\n operands_and_partials ops_partials(mu, phi);\n\n size_t len_ep = max_size(mu, phi);\n size_t len_np = max_size(n, phi);\n\n size_t len_mu = length(mu);\n VectorBuilder mu__(len_mu);\n for (size_t i = 0; i < len_mu; ++i) {\n mu__[i] = value_of(mu_vec[i]);\n }\n\n size_t len_phi = length(phi);\n VectorBuilder phi__(len_phi);\n VectorBuilder log_phi(len_phi);\n for (size_t i = 0; i < len_phi; ++i) {\n phi__[i] = value_of(phi_vec[i]);\n log_phi[i] = log(phi__[i]);\n }\n\n VectorBuilder\n log_mu_plus_phi(len_ep);\n for (size_t i = 0; i < len_ep; ++i) {\n log_mu_plus_phi[i] = log(mu__[i] + phi__[i]);\n }\n\n VectorBuilder n_plus_phi(len_np);\n for (size_t i = 0; i < len_np; ++i) {\n n_plus_phi[i] = n_vec[i] + phi__[i];\n }\n\n for (size_t i = 0; i < size_max; i++) {\n if (phi__[i] > internal::neg_binomial_2_phi_cutoff) {\n \/\/ Phi is large, deferring to Poisson.\n \/\/ Copying the code here as just calling\n \/\/ poisson_lpmf does not preserve propto logic correctly\n if (include_summand::value) {\n logp -= lgamma(n_vec[i] + 1.0);\n }\n if (include_summand::value) {\n logp += multiply_log(n_vec[i], mu__[i]) - mu__[i];\n }\n\n if (!is_constant_all::value) {\n \/\/ This is the Taylor series of the full derivative for phi -> Inf\n \/\/ Obtained in Mathematica via\n \/\/ Series[n\/mu - (n + phi)\/(mu+phi),{phi,Infinity, 1}]\n \/\/ Currently ignoring the term (mu__[i] - n_vec[i]) \/ phi__[i]\n ops_partials.edge1_.partials_[i] += n_vec[i] \/ mu__[i] - 1;\n }\n\n \/\/ The derivative wrt. phi = 0 + O(1\/neg_binomial_2_phi_cutoff^2),\n \/\/ But the quadratic term is big enough to warrant inclusion here\n \/\/ (can be around 1e-6 at cutoff).\n \/\/ Expansion obtained in Mathematica via\n \/\/ Series[1 - (n + phi) \/ (mu + phi) + Log[phi] - Log[mu + phi] -\n \/\/ PolyGamma[phi] + PolyGamma[n + phi],{phi,Infinity, 2}]\n if (!is_constant_all::value) {\n ops_partials.edge2_.partials_[i]\n += (mu__[i] * (-mu__[i] + 2 * n_vec[i]) + n_vec[i] * (1 - n_vec[i]))\n \/ (2 * square(phi__[i]));\n }\n\n } else {\n if (include_summand::value) {\n logp += binomial_coefficient_log(n_plus_phi[i] - 1, n_vec[i]);\n }\n\n logp += phi__[i] * (log_phi[i] - log_mu_plus_phi[i])\n - (n_vec[i]) * log_mu_plus_phi[i];\n\n if (include_summand::value) {\n logp += multiply_log(n_vec[i], mu__[i]);\n }\n\n if (!is_constant_all::value) {\n ops_partials.edge1_.partials_[i]\n += n_vec[i] \/ mu__[i]\n - (n_vec[i] + phi__[i]) \/ (mu__[i] + phi__[i]);\n }\n if (!is_constant_all::value) {\n ops_partials.edge2_.partials_[i]\n += 1.0 - n_plus_phi[i] \/ (mu__[i] + phi__[i]) + log_phi[i]\n - log_mu_plus_phi[i] - digamma(phi__[i])\n + digamma(n_plus_phi[i]);\n }\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate \ninline return_type_t neg_binomial_2_lpmf(\n const T_n& n, const T_location& mu, const T_precision& phi) {\n return neg_binomial_2_lpmf(n, mu, phi);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"forgot to change the Invalidate to InvalidateEntry in treelistbox<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: embedtransfer.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-10-13 11:28:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _COM_SUN_STAR_EMBED_XCOMPONENTSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XVISUALOBJECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XEMBEDPERSIST_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"embedhlp.hxx\"\n\nusing namespace ::com::sun::star;\n\nSvEmbedTransferHelper::SvEmbedTransferHelper( const uno::Reference< embed::XEmbeddedObject >& xObj,\n Graphic* pGraphic,\n sal_Int64 nAspect )\n: m_xObj( xObj )\n, m_pGraphic( pGraphic ? new Graphic( *pGraphic ) : NULL )\n, m_nAspect( nAspect )\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nSvEmbedTransferHelper::~SvEmbedTransferHelper()\n{\n if ( m_pGraphic )\n {\n delete m_pGraphic;\n m_pGraphic = NULL;\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SvEmbedTransferHelper::AddSupportedFormats()\n{\n AddFormat( SOT_FORMATSTR_ID_EMBED_SOURCE );\n AddFormat( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR );\n AddFormat( FORMAT_GDIMETAFILE );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nsal_Bool SvEmbedTransferHelper::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )\n{\n sal_Bool bRet = sal_False;\n\n if( m_xObj.is() )\n {\n try\n {\n sal_uInt32 nFormat = SotExchange::GetFormat( rFlavor );\n if( HasFormat( nFormat ) )\n {\n if( nFormat == SOT_FORMATSTR_ID_OBJECTDESCRIPTOR )\n {\n TransferableObjectDescriptor aDesc;\n FillTransferableObjectDescriptor( aDesc, m_xObj, m_pGraphic, m_nAspect );\n bRet = SetTransferableObjectDescriptor( aDesc, rFlavor );\n }\n else if( nFormat == SOT_FORMATSTR_ID_EMBED_SOURCE )\n {\n try\n {\n \/\/ TODO\/LATER: Propbably the graphic should be copied here as well\n \/\/ currently it is handled by the applications\n utl::TempFile aTmp;\n aTmp.EnableKillingFile( TRUE );\n uno::Reference < embed::XEmbedPersist > xPers( m_xObj, uno::UNO_QUERY );\n if ( xPers.is() )\n {\n uno::Reference < embed::XStorage > xStg = comphelper::OStorageHelper::GetTemporaryStorage();\n ::rtl::OUString aName = ::rtl::OUString::createFromAscii(\"Dummy\");\n SvStream* pStream = NULL;\n BOOL bDeleteStream = FALSE;\n uno::Sequence < beans::PropertyValue > aEmpty;\n xPers->storeToEntry( xStg, aName, aEmpty, aEmpty );\n if ( xStg->isStreamElement( aName ) )\n {\n uno::Reference < io::XStream > xStm = xStg->cloneStreamElement( aName );\n pStream = utl::UcbStreamHelper::CreateStream( xStm );\n bDeleteStream = TRUE;\n }\n else\n {\n pStream = aTmp.GetStream( STREAM_STD_READWRITE );\n uno::Reference < embed::XStorage > xStor = comphelper::OStorageHelper::GetStorageFromStream( new utl::OStreamWrapper( *pStream ) );\n xStg->openStorageElement( aName, embed::ElementModes::READ )->copyToStorage( xStor );\n }\n\n ::com::sun::star::uno::Any aAny;\n const sal_uInt32 nLen = pStream->Seek( STREAM_SEEK_TO_END );\n ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( nLen );\n\n pStream->Seek( STREAM_SEEK_TO_BEGIN );\n pStream->Read( aSeq.getArray(), nLen );\n if ( bDeleteStream )\n delete pStream;\n\n if( ( bRet = ( aSeq.getLength() > 0 ) ) == sal_True )\n {\n aAny <<= aSeq;\n SetAny( aAny, rFlavor );\n }\n }\n else\n {\n \/\/TODO\/LATER: how to handle objects without persistance?!\n }\n }\n catch ( uno::Exception& )\n {\n }\n }\n else if ( nFormat == FORMAT_GDIMETAFILE && m_pGraphic )\n {\n SvMemoryStream aMemStm( 65535, 65535 );\n aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );\n\n const GDIMetaFile& aMetaFile = m_pGraphic->GetGDIMetaFile();\n ((GDIMetaFile*)(&aMetaFile))->Write( aMemStm );\n uno::Any aAny;\n aAny <<= uno::Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),\n aMemStm.Seek( STREAM_SEEK_TO_END ) );\n SetAny( aAny, rFlavor );\n bRet = sal_True;\n }\n else if ( m_xObj.is() && :: svt::EmbeddedObjectRef::TryRunningState( m_xObj ) )\n {\n uno::Reference< datatransfer::XTransferable > xTransferable( m_xObj->getComponent(), uno::UNO_QUERY );\n if ( xTransferable.is() )\n {\n uno::Any aAny = xTransferable->getTransferData( rFlavor );\n SetAny( aAny, rFlavor );\n bRet = sal_True;\n }\n }\n }\n }\n catch( uno::Exception& )\n {\n \/\/ Error handling?\n }\n }\n\n return bRet;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SvEmbedTransferHelper::ObjectReleased()\n{\n m_xObj = uno::Reference< embed::XEmbeddedObject >();\n}\n\nvoid SvEmbedTransferHelper::FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc,\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject >& xObj,\n Graphic* pGraphic,\n sal_Int64 nAspect )\n{\n \/\/TODO\/LATER: need TypeName to fill it into the Descriptor (will be shown in listbox)\n ::com::sun::star::datatransfer::DataFlavor aFlavor;\n SotExchange::GetFormatDataFlavor( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR, aFlavor );\n\n rDesc.maClassName = SvGlobalName( xObj->getClassID() );\n rDesc.maTypeName = aFlavor.HumanPresentableName;\n\n \/\/TODO\/LATER: the aspect size in the descriptor is wrong, unfortunately the stream\n \/\/ representation of the descriptor allows only 4 bytes for the aspect\n \/\/ so for internal transport something different should be found\n rDesc.mnViewAspect = sal::static_int_cast( nAspect );\n\n \/\/TODO\/LATER: status needs to become sal_Int64\n rDesc.mnOle2Misc = sal::static_int_cast(xObj->getStatus( rDesc.mnViewAspect ));\n\n Size aSize;\n MapMode aMapMode( MAP_100TH_MM );\n if ( nAspect == embed::Aspects::MSOLE_ICON )\n {\n if ( pGraphic )\n {\n aMapMode = pGraphic->GetPrefMapMode();\n aSize = pGraphic->GetPrefSize();\n }\n else\n aSize = Size( 2500, 2500 );\n }\n else\n {\n try\n {\n awt::Size aSz;\n aSz = xObj->getVisualAreaSize( rDesc.mnViewAspect );\n aSize = Size( aSz.Width, aSz.Height );\n }\n catch( embed::NoVisualAreaSizeException& )\n {\n OSL_ENSURE( sal_False, \"Can not get visual area size!\\n\" );\n aSize = Size( 5000, 5000 );\n }\n\n \/\/ TODO\/LEAN: getMapUnit can switch object to running state\n aMapMode = MapMode( VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( rDesc.mnViewAspect ) ) );\n }\n\n rDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapMode, MapMode( MAP_100TH_MM ) );\n rDesc.maDragStartPos = Point();\n rDesc.maDisplayName = String();\n rDesc.mbCanLink = FALSE;\n}\n\nINTEGRATION: CWS vgbugs07 (1.9.182); FILE MERGED 2007\/06\/04 13:31:43 vg 1.9.182.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: embedtransfer.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:49:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _COM_SUN_STAR_EMBED_XCOMPONENTSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XVISUALOBJECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XEMBEDPERSIST_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ASPECTS_HPP_\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"embedhlp.hxx\"\n\nusing namespace ::com::sun::star;\n\nSvEmbedTransferHelper::SvEmbedTransferHelper( const uno::Reference< embed::XEmbeddedObject >& xObj,\n Graphic* pGraphic,\n sal_Int64 nAspect )\n: m_xObj( xObj )\n, m_pGraphic( pGraphic ? new Graphic( *pGraphic ) : NULL )\n, m_nAspect( nAspect )\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nSvEmbedTransferHelper::~SvEmbedTransferHelper()\n{\n if ( m_pGraphic )\n {\n delete m_pGraphic;\n m_pGraphic = NULL;\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SvEmbedTransferHelper::AddSupportedFormats()\n{\n AddFormat( SOT_FORMATSTR_ID_EMBED_SOURCE );\n AddFormat( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR );\n AddFormat( FORMAT_GDIMETAFILE );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nsal_Bool SvEmbedTransferHelper::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )\n{\n sal_Bool bRet = sal_False;\n\n if( m_xObj.is() )\n {\n try\n {\n sal_uInt32 nFormat = SotExchange::GetFormat( rFlavor );\n if( HasFormat( nFormat ) )\n {\n if( nFormat == SOT_FORMATSTR_ID_OBJECTDESCRIPTOR )\n {\n TransferableObjectDescriptor aDesc;\n FillTransferableObjectDescriptor( aDesc, m_xObj, m_pGraphic, m_nAspect );\n bRet = SetTransferableObjectDescriptor( aDesc, rFlavor );\n }\n else if( nFormat == SOT_FORMATSTR_ID_EMBED_SOURCE )\n {\n try\n {\n \/\/ TODO\/LATER: Propbably the graphic should be copied here as well\n \/\/ currently it is handled by the applications\n utl::TempFile aTmp;\n aTmp.EnableKillingFile( TRUE );\n uno::Reference < embed::XEmbedPersist > xPers( m_xObj, uno::UNO_QUERY );\n if ( xPers.is() )\n {\n uno::Reference < embed::XStorage > xStg = comphelper::OStorageHelper::GetTemporaryStorage();\n ::rtl::OUString aName = ::rtl::OUString::createFromAscii(\"Dummy\");\n SvStream* pStream = NULL;\n BOOL bDeleteStream = FALSE;\n uno::Sequence < beans::PropertyValue > aEmpty;\n xPers->storeToEntry( xStg, aName, aEmpty, aEmpty );\n if ( xStg->isStreamElement( aName ) )\n {\n uno::Reference < io::XStream > xStm = xStg->cloneStreamElement( aName );\n pStream = utl::UcbStreamHelper::CreateStream( xStm );\n bDeleteStream = TRUE;\n }\n else\n {\n pStream = aTmp.GetStream( STREAM_STD_READWRITE );\n uno::Reference < embed::XStorage > xStor = comphelper::OStorageHelper::GetStorageFromStream( new utl::OStreamWrapper( *pStream ) );\n xStg->openStorageElement( aName, embed::ElementModes::READ )->copyToStorage( xStor );\n }\n\n ::com::sun::star::uno::Any aAny;\n const sal_uInt32 nLen = pStream->Seek( STREAM_SEEK_TO_END );\n ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( nLen );\n\n pStream->Seek( STREAM_SEEK_TO_BEGIN );\n pStream->Read( aSeq.getArray(), nLen );\n if ( bDeleteStream )\n delete pStream;\n\n if( ( bRet = ( aSeq.getLength() > 0 ) ) == sal_True )\n {\n aAny <<= aSeq;\n SetAny( aAny, rFlavor );\n }\n }\n else\n {\n \/\/TODO\/LATER: how to handle objects without persistance?!\n }\n }\n catch ( uno::Exception& )\n {\n }\n }\n else if ( nFormat == FORMAT_GDIMETAFILE && m_pGraphic )\n {\n SvMemoryStream aMemStm( 65535, 65535 );\n aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );\n\n const GDIMetaFile& aMetaFile = m_pGraphic->GetGDIMetaFile();\n ((GDIMetaFile*)(&aMetaFile))->Write( aMemStm );\n uno::Any aAny;\n aAny <<= uno::Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),\n aMemStm.Seek( STREAM_SEEK_TO_END ) );\n SetAny( aAny, rFlavor );\n bRet = sal_True;\n }\n else if ( m_xObj.is() && :: svt::EmbeddedObjectRef::TryRunningState( m_xObj ) )\n {\n uno::Reference< datatransfer::XTransferable > xTransferable( m_xObj->getComponent(), uno::UNO_QUERY );\n if ( xTransferable.is() )\n {\n uno::Any aAny = xTransferable->getTransferData( rFlavor );\n SetAny( aAny, rFlavor );\n bRet = sal_True;\n }\n }\n }\n }\n catch( uno::Exception& )\n {\n \/\/ Error handling?\n }\n }\n\n return bRet;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SvEmbedTransferHelper::ObjectReleased()\n{\n m_xObj = uno::Reference< embed::XEmbeddedObject >();\n}\n\nvoid SvEmbedTransferHelper::FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc,\n const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject >& xObj,\n Graphic* pGraphic,\n sal_Int64 nAspect )\n{\n \/\/TODO\/LATER: need TypeName to fill it into the Descriptor (will be shown in listbox)\n ::com::sun::star::datatransfer::DataFlavor aFlavor;\n SotExchange::GetFormatDataFlavor( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR, aFlavor );\n\n rDesc.maClassName = SvGlobalName( xObj->getClassID() );\n rDesc.maTypeName = aFlavor.HumanPresentableName;\n\n \/\/TODO\/LATER: the aspect size in the descriptor is wrong, unfortunately the stream\n \/\/ representation of the descriptor allows only 4 bytes for the aspect\n \/\/ so for internal transport something different should be found\n rDesc.mnViewAspect = sal::static_int_cast( nAspect );\n\n \/\/TODO\/LATER: status needs to become sal_Int64\n rDesc.mnOle2Misc = sal::static_int_cast(xObj->getStatus( rDesc.mnViewAspect ));\n\n Size aSize;\n MapMode aMapMode( MAP_100TH_MM );\n if ( nAspect == embed::Aspects::MSOLE_ICON )\n {\n if ( pGraphic )\n {\n aMapMode = pGraphic->GetPrefMapMode();\n aSize = pGraphic->GetPrefSize();\n }\n else\n aSize = Size( 2500, 2500 );\n }\n else\n {\n try\n {\n awt::Size aSz;\n aSz = xObj->getVisualAreaSize( rDesc.mnViewAspect );\n aSize = Size( aSz.Width, aSz.Height );\n }\n catch( embed::NoVisualAreaSizeException& )\n {\n OSL_ENSURE( sal_False, \"Can not get visual area size!\\n\" );\n aSize = Size( 5000, 5000 );\n }\n\n \/\/ TODO\/LEAN: getMapUnit can switch object to running state\n aMapMode = MapMode( VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( rDesc.mnViewAspect ) ) );\n }\n\n rDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapMode, MapMode( MAP_100TH_MM ) );\n rDesc.maDragStartPos = Point();\n rDesc.maDisplayName = String();\n rDesc.mbCanLink = FALSE;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \"renderer.hpp\"\n\nrenderer_t::renderer_t(QWidget * parent)\n{\n}\n\nvoid renderer_t::initializeGL()\n{\n vertex_array_obj_ = new QOpenGLVertexArrayObject();\n vertex_array_obj_->create();\n vertex_array_obj_->bind();\n\n vertex_buffer_ = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);\n vertex_buffer_->create();\n vertex_buffer_->setUsagePattern(QOpenGLBuffer::StaticDraw);\n vertex_buffer_->bind();\n\n GLfloat vertices[] = {\n \/\/Position Texcoords\n -1.f, -1.f, 0.f, 1.f, \/\/ bottom-left - 0\n 1.f, -1.f, 1.f, 1.f, \/\/ bottom-right - 1\n 1.f, 1.f, 1.f, 0.f, \/\/ top-right - 2\n -1.f, 1.f, 0.f, 0.f, \/\/ top-left - 3\n };\n\n vertex_buffer_->allocate(vertices, sizeof(vertices));\n\n index_buffer_ = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer);\n index_buffer_->create();\n index_buffer_->setUsagePattern(QOpenGLBuffer::StaticDraw);\n index_buffer_->bind();\n\n GLuint elements[] = {\n 0, 1, 2, 3\n };\n\n index_buffer_->allocate(elements, sizeof(elements));\n\n index_buffer_->bind();\n vertex_buffer_->bind();\n vertex_array_obj_->bind();\n\n vertex_shader_ = new QOpenGLShader(QOpenGLShader::Vertex);\n vertex_shader_->compileSourceCode(vertex_shader_src_.c_str());\n fragment_shader_ = new QOpenGLShader(QOpenGLShader::Fragment);\n fragment_shader_->compileSourceCode(fragment_shader_src_.c_str());\n\n program_.addShader(vertex_shader_);\n program_.addShader(fragment_shader_);\n program_.link();\n program_.bind();\n\n program_.enableAttributeArray(0);\n program_.setAttributeBuffer(0, GL_FLOAT, 0, 2, sizeof(float) * 4);\n program_.enableAttributeArray(2);\n program_.setAttributeBuffer(2, GL_FLOAT, sizeof(float) * 2, 2, sizeof(float) * 4);\n\n\/\/ parser_t parser(\"sample.tif\");\n\/\/ float ** image = parser.parse();\n\n texture_ = new QOpenGLTexture(QImage(\"Lenna.png\"));\n texture_->bind();\n}\n\nvoid renderer_t::paintGL()\n{\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n\n index_buffer_->bind();\n vertex_buffer_->bind();\n vertex_array_obj_->bind();\n program_.bind();\n texture_->bind();\n\n glDrawArrays(GL_QUADS, 0, 4);\n}\n\nvoid renderer_t::resizeGL(int width, int height)\n{\n QGLWidget::resizeGL(width, height);\n}\n\nrenderer_t::~renderer_t()\n{\n vertex_buffer_->release();\n vertex_buffer_->destroy();\n}correct image size#include \n#include \"renderer.hpp\"\n\nrenderer_t::renderer_t(QWidget * parent)\n{\n}\n\nvoid renderer_t::initializeGL()\n{\n vertex_array_obj_ = new QOpenGLVertexArrayObject();\n vertex_array_obj_->create();\n vertex_array_obj_->bind();\n\n vertex_buffer_ = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);\n vertex_buffer_->create();\n vertex_buffer_->setUsagePattern(QOpenGLBuffer::StaticDraw);\n vertex_buffer_->bind();\n\n GLfloat vertices[] = {\n \/\/Position Texcoords\n -1.f, -1.f, 0.f, 1.f, \/\/ bottom-left - 0\n 1.f, -1.f, 1.f, 1.f, \/\/ bottom-right - 1\n 1.f, 1.f, 1.f, 0.f, \/\/ top-right - 2\n -1.f, 1.f, 0.f, 0.f, \/\/ top-left - 3\n };\n\n vertex_buffer_->allocate(vertices, sizeof(vertices));\n\n index_buffer_ = new QOpenGLBuffer(QOpenGLBuffer::IndexBuffer);\n index_buffer_->create();\n index_buffer_->setUsagePattern(QOpenGLBuffer::StaticDraw);\n index_buffer_->bind();\n\n GLuint elements[] = {\n 0, 1, 2, 3\n };\n\n index_buffer_->allocate(elements, sizeof(elements));\n\n index_buffer_->bind();\n vertex_buffer_->bind();\n vertex_array_obj_->bind();\n\n vertex_shader_ = new QOpenGLShader(QOpenGLShader::Vertex);\n vertex_shader_->compileSourceCode(vertex_shader_src_.c_str());\n fragment_shader_ = new QOpenGLShader(QOpenGLShader::Fragment);\n fragment_shader_->compileSourceCode(fragment_shader_src_.c_str());\n\n program_.addShader(vertex_shader_);\n program_.addShader(fragment_shader_);\n program_.link();\n program_.bind();\n\n program_.enableAttributeArray(0);\n program_.setAttributeBuffer(0, GL_FLOAT, 0, 2, sizeof(float) * 4);\n program_.enableAttributeArray(2);\n program_.setAttributeBuffer(2, GL_FLOAT, sizeof(float) * 2, 2, sizeof(float) * 4);\n\n\/\/ parser_t parser(\"sample.tif\");\n\/\/ float ** image = parser.parse();\n\n texture_ = new QOpenGLTexture(QImage(\"Lenna.png\"));\n texture_->bind();\n}\n\nvoid renderer_t::paintGL()\n{\n glClearColor(0.0f, 0.0f, 0.0f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n\n index_buffer_->bind();\n vertex_buffer_->bind();\n vertex_array_obj_->bind();\n program_.bind();\n texture_->bind();\n\n glDrawArrays(GL_QUADS, 0, 4);\n}\n\nvoid renderer_t::resizeGL(int width, int height)\n{\n int side = qMin(width, height);\n glViewport((width - side) \/ 2, (height - side) \/ 2, side, side);\n}\n\nrenderer_t::~renderer_t()\n{\n vertex_buffer_->release();\n vertex_buffer_->destroy();\n}<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: BiasFieldEstimator.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) 2002 Insight Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even \nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \n#include \n\n#include \"imageutils.h\"\n#include \"OptionList.h\"\n#include \"itkMRIBiasFieldCorrectionFilter.h\"\n\ntypedef itk::MRIBiasFieldCorrectionFilter Corrector ;\n\nvoid print_usage()\n{\n print_line(\"MRIBiasCorrection 1.0 (21.June.2001)\");\n\n print_line(\"usage: BiasFieldEstimator --input file\" ) ;\n print_line(\" --class-mean mean(1) ... mean(i)\" ) ;\n print_line(\" --class-sigma sigma(1) ... sigma(i)\" ) ;\n print_line(\" --use-log [yes|no]\") ;\n print_line(\" [--input-mask file]\" ) ;\n print_line(\" [--degree int] [--coefficients c0,..,cn]\" ) ;\n print_line(\" [--growth double] [--shrink double] \") ;\n print_line(\" [--volume-max-iteration int] [--inter-slice-max-iteration int]\");\n print_line(\" [--init-step-size double] \");\n\n print_line(\"\");\n\n print_line(\"--input file\") ;\n print_line(\" input data set [meta image format]\" );\n print_line(\"--class-mean mean(1),...,mean(i)\" ) ;\n print_line(\" intensity means of the differen i tissue classes\") ;\n print_line(\"--class-sigma sig(1),...,sig(i)\" ) ; \n print_line(\" intensity sigmas of the different i tissue clases\") ;\n print_line(\" NOTE: The sigmas should be listed in the SAME ORDER\") ;\n print_line(\" of means\");\n print_line(\" and each value should be SEPERATED BY A SPACE)\") ;\n print_line(\"--input-mask file\" ) ;\n print_line(\" mask input with file [meta image format]\");\n print_line(\"--degree int\") ;\n print_line(\" degree of legendre polynomial used for the\") ;\n print_line(\" approximation of the bias field\" );\n print_line(\"--use-log [yes|no]\") ;\n print_line(\" if yes, assume a multiplicative bias field\") ;\n print_line(\" (use log of image, class-mean, class-sigma,\") ;\n print_line(\" and init-step-size)\" );\n print_line(\"--grow double\") ;\n print_line(\" stepsize growth factor. must be greater than 1.0\") ;\n print_line(\" [default 1.05]\" ) ;\n print_line(\"--shrink double\") ;\n print_line(\" stepsize shrink factor \") ;\n print_line(\" [default grow^(-0.25)]\" ) ; \n print_line(\"--volume-max-iteration int\") ;\n print_line(\" maximal number of iterations for 3D volume correction\") ;\n print_line(\" [default 20]\" ) ;\n print_line(\"--inter-slicemax-iteration int\") ;\n print_line(\" maximal number of iterations for each inter-slice correction\") ;\n print_line(\" [default 20]\" ) ;\n print_line(\"--init-step-size double\") ;\n print_line(\" inital step size [default 1.02]\" );\n print_line(\"--coefficients c(0),..,c(n)\") ;\n print_line(\" coefficients of the polynomial\") ;\n print_line(\" (used for generating bias field)\") ;\n\n print_line(\"\");\n\n print_line(\"example: BiasFieldEstimator --input sample.mhd\") ;\n print_line(\" --class-mean 1500 570\") ;\n print_line(\" --class-sigma 100 70 --use-log yes\");\n print_line(\" --input-mask sample.mask.mhd \") ;\n print_line(\" --degree 3 --grow 1.05 --shrink 0.9\");\n print_line(\" --max-iteration 2000 --init-step-size 1.02\") ;\n print_line(\" --coefficients 0.056789 -1.00004 0.78945 ... -0.02345\");\n}\n\n\nvoid printResult(Corrector::Pointer filter, OptionList& options)\n{\n\n options.DumpOption(\"input\") ;\n options.DumpOption(\"input-mask\") ;\n options.DumpOption(\"class-mean\") ;\n options.DumpOption(\"class-sigma\") ;\n options.DumpOption(\"use-log\") ;\n\n std::cout << \" --degree \" << filter->GetBiasFieldDegree() ;\n\n Corrector::BiasFieldType::DomainSizeType sizes = \n filter->GetBiasFieldDomainSize() ;\n std::cout << \" --size \" ;\n for (unsigned int i = 0 ; i < sizes.size() ; i++)\n {\n std::cout << sizes[i] << \" \" ;\n }\n \n std::cout << \"--grow \" << filter->GetOptimizerGrowthFactor() ;\n std::cout << \" --shrink \" << filter->GetOptimizerShrinkFactor() ;\n std::cout << \" --volume-max-iteration \" << filter->GetVolumeCorrectionMaximumIteration();\n std::cout << \" --inter-slice-max-iteration \" << filter->GetInterSliceCorrectionMaximumIteration();\n \n if (filter->IsBiasFieldMultiplicative())\n std::cout << \" --init-step-size \" \n << exp(filter->GetOptimizerInitialRadius()) ;\n else\n std::cout << \" --init-step-size \" << filter->GetOptimizerInitialRadius() ;\n\n\n std::cout << \" --coefficient-length \" << filter->GetNoOfBiasFieldCoefficients()\n << \" --coefficients \" ;\n\n Corrector::BiasFieldType::CoefficientArrayType coefficients = \n filter->GetEstimatedBiasFieldCoefficients() ;\n\n Corrector::BiasFieldType::CoefficientArrayType::iterator iter =\n coefficients.begin() ;\n\n while (iter != coefficients.end()) \n {\n std::cout << *iter << \" \" ;\n iter++ ;\n } \n std::cout << std::endl ;\n}\n \n\nint main(int argc, char* argv[])\n{\n\n if (argc <= 1)\n {\n print_usage() ;\n exit(0) ;\n }\n\n OptionList options(argc, argv) ;\n\n Corrector::Pointer filter = Corrector::New() ;\n\n std::string inputFileName ;\n std::string inputMaskFileName = \"\" ;\n bool useLog = true;\n int degree = 3;\n itk::Array coefficientVector ;\n itk::Array classMeans ;\n itk::Array classSigmas ;\n int volumeMaximumIteration = 20; \n int interSliceMaximumIteration = 20; \n double initialRadius = 1.02;\n double grow = 1.05;\n double shrink = pow(grow, -0.25);\n\n try\n {\n \/\/ get image file options\n options.GetStringOption(\"input\", &inputFileName, true) ;\n options.GetStringOption(\"input-mask\", &inputMaskFileName, false) ;\n \n \/\/ get bias field options\n useLog = options.GetBooleanOption(\"use-log\", true, true) ;\n degree = options.GetIntOption(\"degree\", 3, false) ;\n \n std::vector coefficients ;\n options.GetMultiDoubleOption(\"coefficients\", &coefficients, false) ;\n\n int length = coefficients.size() ;\n coefficientVector.resize(length) ;\n for (int i = 0 ; i < length ; i++)\n coefficientVector[i] = coefficients[i] ;\n\n \/\/ get energyfunction options\n options.GetMultiDoubleOption(\"class-mean\", &classMeans, true) ;\n options.GetMultiDoubleOption(\"class-sigma\", &classSigmas, true) ;\n\n \/\/ get optimizer options\n volumeMaximumIteration = options.GetIntOption(\"volume-max-iteration\", 20, false) ;\n interSliceMaximumIteration = options.GetIntOption(\"inter-slice-max-iteration\", 20, false) ;\n grow = options.GetDoubleOption(\"grow\", 1.05, false) ;\n shrink = pow(grow, -0.25) ;\n shrink = options.GetDoubleOption(\"shrink\", shrink, false) ;\n initialRadius = options.GetDoubleOption(\"init-step-size\", 1.02, false) ;\n }\n catch(OptionList::RequiredOptionMissing e)\n {\n std::cout << \"Error: The '\" << e.OptionTag \n << \"' option is required but missing.\" \n << std::endl ;\n }\n\n \n \/\/ load images\n ImagePointer input ;\n MaskPointer inputMask ;\n\n ImageReaderType::Pointer imageReader = ImageReaderType::New() ;\n MaskReaderType::Pointer maskReader = MaskReaderType::New() ;\n try\n {\n std::cout << \"Loading images...\" << std::endl ;\n imageReader->SetFileName(inputFileName.c_str()) ;\n imageReader->Update() ;\n input = imageReader->GetOutput() ;\n filter->SetInput(input) ;\n if (inputMaskFileName != \"\")\n {\n maskReader->SetFileName(inputMaskFileName.c_str()) ;\n maskReader->Update() ;\n inputMask = maskReader->GetOutput() ;\n filter->SetInputMask(inputMask) ;\n }\n std::cout << \"Images loaded.\" << std::endl ;\n }\n catch (itk::ExceptionObject e)\n {\n e.Print(std::cout) ;\n exit(0) ;\n }\n \n filter->IsBiasFieldMultiplicative(useLog) ;\n filter->SetInitialBiasFieldCoefficients(coefficientVector) ;\n \/\/ sets tissue classes' statistics for creating the energy function\n filter->SetTissueClassStatistics(classMeans, classSigmas) ;\n \/\/ setting standard optimizer parameters \n filter->SetOptimizerGrowthFactor(grow) ;\n filter->SetOptimizerShrinkFactor(shrink) ;\n filter->SetVolumeCorrectionMaximumIteration(volumeMaximumIteration) ;\n filter->SetInterSliceCorrectionMaximumIteration(interSliceMaximumIteration) ;\n filter->SetOptimizerInitialRadius(initialRadius) ;\n \/\/ this member function call is not necessary since the filter's internal\n \/\/ InterSliceIntensityCorrection() member sets the bias field degree to\n \/\/ zero.\n filter->SetBiasFieldDegree(degree) ;\n \/\/ turn on inter-slice intensity correction \n filter->SetUsingInterSliceIntensityCorrection(true) ;\n \/\/ disable slab identifcation\n \/\/ the filter will think the largest possible region as the only one\n \/\/ slab.\n filter->SetUsingSlabIdentification(false) ;\n \/\/ disable 3D bias correction\n filter->SetUsingBiasFieldCorrection(true) ;\n \/\/ disable output image generation\n filter->SetGeneratingOutput(false) ;\n filter->SetSlicingDirection(2) ;\n\n std::cout << \"Estimating the bias field...\" << std::endl ;\n filter->Update() ;\n\n printResult(filter, options) ;\n\n return 0 ;\n}\n\/*=========================================================================\n\nProgram: Insight Segmentation & Registration Toolkit\nModule: BiasFieldEstimator.cxx\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) 2002 Insight Consortium. All rights reserved.\nSee ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even \nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \n#include \n\n#include \"imageutils.h\"\n#include \"OptionList.h\"\n#include \"itkMRIBiasFieldCorrectionFilter.h\"\n\ntypedef itk::MRIBiasFieldCorrectionFilter Corrector ;\n\nvoid print_usage()\n{\n print_line(\"MRIBiasCorrection 1.0 (21.June.2001)\");\n\n print_line(\"usage: BiasFieldEstimator --input file\" ) ;\n print_line(\" --class-mean mean(1) ... mean(i)\" ) ;\n print_line(\" --class-sigma sigma(1) ... sigma(i)\" ) ;\n print_line(\" --use-log [yes|no]\") ;\n print_line(\" [--input-mask file]\" ) ;\n print_line(\" [--degree int] [--coefficients c0,..,cn]\" ) ;\n print_line(\" [--growth double] [--shrink double] \") ;\n print_line(\" [--volume-max-iteration int] [--inter-slice-max-iteration int]\");\n print_line(\" [--init-step-size double] \");\n\n print_line(\"\");\n\n print_line(\"--input file\") ;\n print_line(\" input data set [meta image format]\" );\n print_line(\"--class-mean mean(1),...,mean(i)\" ) ;\n print_line(\" intensity means of the differen i tissue classes\") ;\n print_line(\"--class-sigma sig(1),...,sig(i)\" ) ; \n print_line(\" intensity sigmas of the different i tissue clases\") ;\n print_line(\" NOTE: The sigmas should be listed in the SAME ORDER\") ;\n print_line(\" of means\");\n print_line(\" and each value should be SEPERATED BY A SPACE)\") ;\n print_line(\"--input-mask file\" ) ;\n print_line(\" mask input with file [meta image format]\");\n print_line(\"--degree int\") ;\n print_line(\" degree of legendre polynomial used for the\") ;\n print_line(\" approximation of the bias field\" );\n print_line(\"--use-log [yes|no]\") ;\n print_line(\" if yes, assume a multiplicative bias field\") ;\n print_line(\" (use log of image, class-mean, class-sigma,\") ;\n print_line(\" and init-step-size)\" );\n print_line(\"--grow double\") ;\n print_line(\" stepsize growth factor. must be greater than 1.0\") ;\n print_line(\" [default 1.05]\" ) ;\n print_line(\"--shrink double\") ;\n print_line(\" stepsize shrink factor \") ;\n print_line(\" [default grow^(-0.25)]\" ) ; \n print_line(\"--volume-max-iteration int\") ;\n print_line(\" maximal number of iterations for 3D volume correction\") ;\n print_line(\" [default 20]\" ) ;\n print_line(\"--inter-slicemax-iteration int\") ;\n print_line(\" maximal number of iterations for each inter-slice correction\") ;\n print_line(\" [default 20]\" ) ;\n print_line(\"--init-step-size double\") ;\n print_line(\" inital step size [default 1.02]\" );\n print_line(\"--coefficients c(0),..,c(n)\") ;\n print_line(\" coefficients of the polynomial\") ;\n print_line(\" (used for generating bias field)\") ;\n\n print_line(\"\");\n\n print_line(\"example: BiasFieldEstimator --input sample.mhd\") ;\n print_line(\" --class-mean 1500 570\") ;\n print_line(\" --class-sigma 100 70 --use-log yes\");\n print_line(\" --input-mask sample.mask.mhd \") ;\n print_line(\" --degree 3 --grow 1.05 --shrink 0.9\");\n print_line(\" --max-iteration 2000 --init-step-size 1.02\") ;\n print_line(\" --coefficients 0.056789 -1.00004 0.78945 ... -0.02345\");\n}\n\n\nvoid printResult(Corrector::Pointer filter, OptionList& options)\n{\n\n options.DumpOption(\"input\") ;\n options.DumpOption(\"input-mask\") ;\n options.DumpOption(\"class-mean\") ;\n options.DumpOption(\"class-sigma\") ;\n options.DumpOption(\"use-log\") ;\n\n std::cout << \" --degree \" << filter->GetBiasFieldDegree() ;\n\n Corrector::BiasFieldType::DomainSizeType sizes = \n filter->GetBiasFieldDomainSize() ;\n std::cout << \" --size \" ;\n for (unsigned int i = 0 ; i < sizes.size() ; i++)\n {\n std::cout << sizes[i] << \" \" ;\n }\n \n std::cout << \"--grow \" << filter->GetOptimizerGrowthFactor() ;\n std::cout << \" --shrink \" << filter->GetOptimizerShrinkFactor() ;\n std::cout << \" --volume-max-iteration \" << filter->GetVolumeCorrectionMaximumIteration();\n std::cout << \" --inter-slice-max-iteration \" << filter->GetInterSliceCorrectionMaximumIteration();\n \n if (filter->IsBiasFieldMultiplicative())\n std::cout << \" --init-step-size \" \n << exp(filter->GetOptimizerInitialRadius()) ;\n else\n std::cout << \" --init-step-size \" << filter->GetOptimizerInitialRadius() ;\n\n\n std::cout << \" --coefficient-length \" << filter->GetNoOfBiasFieldCoefficients()\n << \" --coefficients \" ;\n\n Corrector::BiasFieldType::CoefficientArrayType coefficients = \n filter->GetEstimatedBiasFieldCoefficients() ;\n\n Corrector::BiasFieldType::CoefficientArrayType::iterator iter =\n coefficients.begin() ;\n\n while (iter != coefficients.end()) \n {\n std::cout << *iter << \" \" ;\n iter++ ;\n } \n std::cout << std::endl ;\n}\n \n\nint main(int argc, char* argv[])\n{\n\n if (argc <= 1)\n {\n print_usage() ;\n exit(0) ;\n }\n\n OptionList options(argc, argv) ;\n\n Corrector::Pointer filter = Corrector::New() ;\n\n std::string inputFileName ;\n std::string inputMaskFileName = \"\" ;\n bool useLog = true;\n int degree = 3;\n itk::Array coefficientVector ;\n itk::Array classMeans ;\n itk::Array classSigmas ;\n int volumeMaximumIteration = 20; \n int interSliceMaximumIteration = 20; \n double initialRadius = 1.02;\n double grow = 1.05;\n double shrink = pow(grow, -0.25);\n\n try\n {\n \/\/ get image file options\n options.GetStringOption(\"input\", &inputFileName, true) ;\n options.GetStringOption(\"input-mask\", &inputMaskFileName, false) ;\n \n \/\/ get bias field options\n useLog = options.GetBooleanOption(\"use-log\", true, true) ;\n degree = options.GetIntOption(\"degree\", 3, false) ;\n \n std::vector coefficients ;\n options.GetMultiDoubleOption(\"coefficients\", &coefficients, false) ;\n\n int length = coefficients.size() ;\n coefficientVector.resize(length) ;\n for (int i = 0 ; i < length ; i++)\n coefficientVector[i] = coefficients[i] ;\n\n \/\/ get energyfunction options\n options.GetMultiDoubleOption(\"class-mean\", &classMeans, true) ;\n options.GetMultiDoubleOption(\"class-sigma\", &classSigmas, true) ;\n\n \/\/ get optimizer options\n volumeMaximumIteration = options.GetIntOption(\"volume-max-iteration\", 20, false) ;\n interSliceMaximumIteration = options.GetIntOption(\"inter-slice-max-iteration\", 20, false) ;\n grow = options.GetDoubleOption(\"grow\", 1.05, false) ;\n shrink = pow(grow, -0.25) ;\n shrink = options.GetDoubleOption(\"shrink\", shrink, false) ;\n initialRadius = options.GetDoubleOption(\"init-step-size\", 1.02, false) ;\n }\n catch(OptionList::RequiredOptionMissing e)\n {\n std::cout << \"Error: The '\" << e.OptionTag \n << \"' option is required but missing.\" \n << std::endl ;\n }\n\n \n \/\/ load images\n ImagePointer input ;\n MaskPointer inputMask ;\n\n ImageReaderType::Pointer imageReader = ImageReaderType::New() ;\n MaskReaderType::Pointer maskReader = MaskReaderType::New() ;\n try\n {\n std::cout << \"Loading images...\" << std::endl ;\n imageReader->SetFileName(inputFileName.c_str()) ;\n imageReader->Update() ;\n input = imageReader->GetOutput() ;\n filter->SetInput(input) ;\n if (inputMaskFileName != \"\")\n {\n maskReader->SetFileName(inputMaskFileName.c_str()) ;\n maskReader->Update() ;\n inputMask = maskReader->GetOutput() ;\n filter->SetInputMask(inputMask) ;\n }\n std::cout << \"Images loaded.\" << std::endl ;\n }\n catch (itk::ExceptionObject e)\n {\n e.Print(std::cout) ;\n exit(0) ;\n }\n \n filter->IsBiasFieldMultiplicative(useLog) ;\n filter->SetInitialBiasFieldCoefficients(coefficientVector) ;\n \/\/ sets tissue classes' statistics for creating the energy function\n filter->SetTissueClassStatistics(classMeans, classSigmas) ;\n \/\/ setting standard optimizer parameters \n filter->SetOptimizerGrowthFactor(grow) ;\n filter->SetOptimizerShrinkFactor(shrink) ;\n filter->SetVolumeCorrectionMaximumIteration(volumeMaximumIteration) ;\n filter->SetInterSliceCorrectionMaximumIteration(interSliceMaximumIteration) ;\n filter->SetOptimizerInitialRadius(initialRadius) ;\n \/\/ this member function call is not necessary since the filter's internal\n \/\/ InterSliceIntensityCorrection() member sets the bias field degree to\n \/\/ zero.\n filter->SetBiasFieldDegree(degree) ;\n \/\/ turn on inter-slice intensity correction \n filter->SetUsingInterSliceIntensityCorrection(false) ;\n \/\/ disable slab identifcation\n \/\/ the filter will think the largest possible region as the only one\n \/\/ slab.\n filter->SetUsingSlabIdentification(false) ;\n \/\/ disable 3D bias correction\n filter->SetUsingBiasFieldCorrection(true) ;\n \/\/ disable output image generation\n filter->SetGeneratingOutput(false) ;\n filter->SetSlicingDirection(2) ;\n\n std::cout << \"Estimating the bias field...\" << std::endl ;\n filter->Update() ;\n\n printResult(filter, options) ;\n\n return 0 ;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz \n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see .\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 the chemkit project nor the names of its\n** contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n******************************************************************************\/\n\n#include \"pluginmanager.h\"\n\n#include \n#include \n#include \n\n#include \n\n#include \"plugin.h\"\n#include \"foreach.h\"\n\nnamespace chemkit {\n\n\/\/ === PluginManagerPrivate ================================================ \/\/\nclass PluginManagerPrivate\n{\n public:\n std::vector plugins;\n std::string errorString;\n bool defaultPluginsLoaded;\n std::map > pluginClasses;\n};\n\n\/\/ === PluginManager ======================================================= \/\/\n\/\/\/ \\class PluginManager pluginmanager.h chemkit\/pluginmanager.h\n\/\/\/ \\ingroup chemkit\n\/\/\/ \\brief The PluginManager class manages the loading and unloading\n\/\/\/ of plugins.\n\/\/\/\n\/\/\/ \\see Plugin\n\n\/\/ --- Construction and Destruction ---------------------------------------- \/\/\nPluginManager::PluginManager()\n : d(new PluginManagerPrivate)\n{\n d->defaultPluginsLoaded = false;\n}\n\nPluginManager::~PluginManager()\n{\n foreach(Plugin *plugin, d->plugins){\n delete plugin;\n }\n\n delete d;\n}\n\n\/\/ --- Properties ---------------------------------------------------------- \/\/\n\/\/\/ Returns the plugin with \\p name. Returns \\c 0 if no plugin with\n\/\/ \\p name is loaded.\nPlugin* PluginManager::plugin(const std::string &name) const\n{\n foreach(Plugin *plugin, d->plugins){\n if(plugin->name() == name){\n return plugin;\n }\n }\n\n return 0;\n}\n\n\/\/\/ Returns a list of all the loaded plugins.\nconst std::vector& PluginManager::plugins() const\n{\n return d->plugins;\n}\n\n\/\/\/ Returns the number of loaded plugins.\nint PluginManager::pluginCount() const\n{\n return d->plugins.size();\n}\n\n\/\/ --- Plugin Loading ------------------------------------------------------ \/\/\n\/\/\/ Loads a plugin from \\p fileName. Returns \\c false if an error\n\/\/\/ occurs.\nbool PluginManager::loadPlugin(const std::string &fileName)\n{\n QPluginLoader plugin(QString::fromStdString(fileName));\n\n Plugin *instance = qobject_cast(plugin.instance());\n if(!instance){\n qDebug() << \"Failed to load plugin (\" << fileName.c_str() << \"): \" << plugin.errorString();\n return false;\n }\n\n instance->setFileName(fileName);\n\n d->plugins.push_back(instance);\n\n return true;\n}\n\n\/\/\/ Loads all plugins from \\p directory.\nvoid PluginManager::loadPlugins(const std::string &directory)\n{\n boost::filesystem::path dir(directory);\n\n if(!boost::filesystem::exists(dir)){\n return;\n }\n\n for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){\n if(QLibrary::isLibrary(iter->path().filename().c_str())){\n loadPlugin(iter->path().string());\n }\n }\n}\n\nvoid PluginManager::loadDefaultPlugins()\n{\n if(d->defaultPluginsLoaded){\n return;\n }\n\n \/\/ list of directories to load plugins from\n std::vector directories;\n\n \/\/ add default plugin directory\n#if defined(CHEMKIT_OS_LINUX)\n directories.push_back(CHEMKIT_INSTALL_PREFIX \"\/share\/chemkit\/plugins\/\");\n#elif defined(CHEMKIT_OS_WIN32)\n QSettings registry(\"HKEY_LOCAL_MACHINE\\\\Software\\\\chemkit\", QSettings::NativeFormat);\n directories.push_back(registry.value(\"PluginPath\").toString().toStdString());\n#endif\n\n \/\/ add directory from the CHEMKIT_PLUGIN_PATH environment variable\n QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();\n std::string path = environment.value(\"CHEMKIT_PLUGIN_PATH\").toStdString();\n if(!path.empty()){\n directories.push_back(path);\n }\n\n \/\/ load plugins from each directory\n foreach(const std::string &directory, directories){\n loadPlugins(directory);\n }\n\n d->defaultPluginsLoaded = true;\n}\n\n\/\/\/ Unloads the plugin.\nbool PluginManager::unloadPlugin(Plugin *plugin)\n{\n return false;\n}\n\n\/\/\/ Unloads the plugin with \\p name.\nbool PluginManager::unloadPlugin(const std::string &name)\n{\n CHEMKIT_UNUSED(name);\n\n return false;\n}\n\n\/\/ --- Error Handling ------------------------------------------------------ \/\/\nvoid PluginManager::setErrorString(const std::string &errorString)\n{\n d->errorString = errorString;\n}\n\n\/\/\/ Returns a string describing the last error that occured.\nstd::string PluginManager::errorString() const\n{\n return d->errorString;\n}\n\n\/\/ --- Static Methods ------------------------------------------------------ \/\/\n\/\/\/ Returns the instance of the plugin manager.\nPluginManager* PluginManager::instance()\n{\n static PluginManager singleton;\n\n return &singleton;\n}\n\n\/\/ --- Internal Methods ---------------------------------------------------- \/\/\n\/\/\/ Registers a new plugin function for \\p className and\n\/\/\/ \\p pluginName.\nbool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)\n{\n std::map &classPlugins = d->pluginClasses[className];\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n \/\/ prevent overwriting of previously registered plugins\n if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){\n return false;\n }\n\n \/\/ add plugin class\n classPlugins[lowerCasePluginName] = function;\n\n return true;\n}\n\n\/\/\/ Unregisters a plugin function for \\p className and \\p pluginName.\nbool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)\n{\n std::map &classPlugins = d->pluginClasses[className];\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n \/\/ remove plugin class\n return classPlugins.erase(lowerCasePluginName) > 0;\n}\n\n\/\/\/ Returns a vector of strings containing the names of registered\n\/\/\/ plugins for \\p className.\nstd::vector PluginManager::pluginClassNames(const std::string &className) const\n{\n \/\/ ensure default plugins are loaded\n const_cast(this)->loadDefaultPlugins();\n\n const std::map &classPlugins = d->pluginClasses[className];\n\n std::vector names;\n for(std::map::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){\n names.push_back(i->first);\n }\n\n return names;\n}\n\n\/\/\/ Returns the registered function for the given \\p className and \\p pluginName.\nPluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const\n{\n \/\/ ensure default plugins are loaded\n const_cast(this)->loadDefaultPlugins();\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n const std::map &classPlugins = d->pluginClasses[className];\n\n std::map::const_iterator location = classPlugins.find(lowerCasePluginName);\n if(location == classPlugins.end()){\n return 0;\n }\n\n return location->second;\n}\n\n} \/\/ end chemkit namespace\nChange PluginManager to use getenv()\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz \n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see .\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 the chemkit project nor the names of its\n** contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n******************************************************************************\/\n\n#include \"pluginmanager.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"plugin.h\"\n#include \"foreach.h\"\n\nnamespace chemkit {\n\n\/\/ === PluginManagerPrivate ================================================ \/\/\nclass PluginManagerPrivate\n{\n public:\n std::vector plugins;\n std::string errorString;\n bool defaultPluginsLoaded;\n std::map > pluginClasses;\n};\n\n\/\/ === PluginManager ======================================================= \/\/\n\/\/\/ \\class PluginManager pluginmanager.h chemkit\/pluginmanager.h\n\/\/\/ \\ingroup chemkit\n\/\/\/ \\brief The PluginManager class manages the loading and unloading\n\/\/\/ of plugins.\n\/\/\/\n\/\/\/ \\see Plugin\n\n\/\/ --- Construction and Destruction ---------------------------------------- \/\/\nPluginManager::PluginManager()\n : d(new PluginManagerPrivate)\n{\n d->defaultPluginsLoaded = false;\n}\n\nPluginManager::~PluginManager()\n{\n foreach(Plugin *plugin, d->plugins){\n delete plugin;\n }\n\n delete d;\n}\n\n\/\/ --- Properties ---------------------------------------------------------- \/\/\n\/\/\/ Returns the plugin with \\p name. Returns \\c 0 if no plugin with\n\/\/ \\p name is loaded.\nPlugin* PluginManager::plugin(const std::string &name) const\n{\n foreach(Plugin *plugin, d->plugins){\n if(plugin->name() == name){\n return plugin;\n }\n }\n\n return 0;\n}\n\n\/\/\/ Returns a list of all the loaded plugins.\nconst std::vector& PluginManager::plugins() const\n{\n return d->plugins;\n}\n\n\/\/\/ Returns the number of loaded plugins.\nint PluginManager::pluginCount() const\n{\n return d->plugins.size();\n}\n\n\/\/ --- Plugin Loading ------------------------------------------------------ \/\/\n\/\/\/ Loads a plugin from \\p fileName. Returns \\c false if an error\n\/\/\/ occurs.\nbool PluginManager::loadPlugin(const std::string &fileName)\n{\n QPluginLoader plugin(QString::fromStdString(fileName));\n\n Plugin *instance = qobject_cast(plugin.instance());\n if(!instance){\n qDebug() << \"Failed to load plugin (\" << fileName.c_str() << \"): \" << plugin.errorString();\n return false;\n }\n\n instance->setFileName(fileName);\n\n d->plugins.push_back(instance);\n\n return true;\n}\n\n\/\/\/ Loads all plugins from \\p directory.\nvoid PluginManager::loadPlugins(const std::string &directory)\n{\n boost::filesystem::path dir(directory);\n\n if(!boost::filesystem::exists(dir)){\n return;\n }\n\n for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){\n if(QLibrary::isLibrary(iter->path().filename().c_str())){\n loadPlugin(iter->path().string());\n }\n }\n}\n\nvoid PluginManager::loadDefaultPlugins()\n{\n if(d->defaultPluginsLoaded){\n return;\n }\n\n \/\/ list of directories to load plugins from\n std::vector directories;\n\n \/\/ add default plugin directory\n#if defined(CHEMKIT_OS_LINUX)\n directories.push_back(CHEMKIT_INSTALL_PREFIX \"\/share\/chemkit\/plugins\/\");\n#elif defined(CHEMKIT_OS_WIN32)\n QSettings registry(\"HKEY_LOCAL_MACHINE\\\\Software\\\\chemkit\", QSettings::NativeFormat);\n directories.push_back(registry.value(\"PluginPath\").toString().toStdString());\n#endif\n\n \/\/ add directory from the CHEMKIT_PLUGIN_PATH environment variable\n std::string path = getenv(\"CHEMKIT_PLUGIN_PATH\");\n if(!path.empty()){\n directories.push_back(path);\n }\n\n \/\/ load plugins from each directory\n foreach(const std::string &directory, directories){\n loadPlugins(directory);\n }\n\n d->defaultPluginsLoaded = true;\n}\n\n\/\/\/ Unloads the plugin.\nbool PluginManager::unloadPlugin(Plugin *plugin)\n{\n return false;\n}\n\n\/\/\/ Unloads the plugin with \\p name.\nbool PluginManager::unloadPlugin(const std::string &name)\n{\n CHEMKIT_UNUSED(name);\n\n return false;\n}\n\n\/\/ --- Error Handling ------------------------------------------------------ \/\/\nvoid PluginManager::setErrorString(const std::string &errorString)\n{\n d->errorString = errorString;\n}\n\n\/\/\/ Returns a string describing the last error that occured.\nstd::string PluginManager::errorString() const\n{\n return d->errorString;\n}\n\n\/\/ --- Static Methods ------------------------------------------------------ \/\/\n\/\/\/ Returns the instance of the plugin manager.\nPluginManager* PluginManager::instance()\n{\n static PluginManager singleton;\n\n return &singleton;\n}\n\n\/\/ --- Internal Methods ---------------------------------------------------- \/\/\n\/\/\/ Registers a new plugin function for \\p className and\n\/\/\/ \\p pluginName.\nbool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)\n{\n std::map &classPlugins = d->pluginClasses[className];\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n \/\/ prevent overwriting of previously registered plugins\n if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){\n return false;\n }\n\n \/\/ add plugin class\n classPlugins[lowerCasePluginName] = function;\n\n return true;\n}\n\n\/\/\/ Unregisters a plugin function for \\p className and \\p pluginName.\nbool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)\n{\n std::map &classPlugins = d->pluginClasses[className];\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n \/\/ remove plugin class\n return classPlugins.erase(lowerCasePluginName) > 0;\n}\n\n\/\/\/ Returns a vector of strings containing the names of registered\n\/\/\/ plugins for \\p className.\nstd::vector PluginManager::pluginClassNames(const std::string &className) const\n{\n \/\/ ensure default plugins are loaded\n const_cast(this)->loadDefaultPlugins();\n\n const std::map &classPlugins = d->pluginClasses[className];\n\n std::vector names;\n for(std::map::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){\n names.push_back(i->first);\n }\n\n return names;\n}\n\n\/\/\/ Returns the registered function for the given \\p className and \\p pluginName.\nPluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const\n{\n \/\/ ensure default plugins are loaded\n const_cast(this)->loadDefaultPlugins();\n\n \/\/ use lower case plugin name\n std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);\n\n const std::map &classPlugins = d->pluginClasses[className];\n\n std::map::const_iterator location = classPlugins.find(lowerCasePluginName);\n if(location == classPlugins.end()){\n return 0;\n }\n\n return location->second;\n}\n\n} \/\/ end chemkit namespace\n<|endoftext|>"} {"text":"\r\n\/\/\r\n\/\/ ===============================================================================\r\n\/\/ clReflect\r\n\/\/ -------------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2011 Don Williamson\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\r\n\/\/ of the Software, and to permit persons to whom the Software is furnished to do\r\n\/\/ so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/ SOFTWARE.\r\n\/\/ ===============================================================================\r\n\/\/\r\n\r\n#include \r\n#include \"DatabaseLoader.h\"\r\n\r\n\r\nnamespace\r\n{\r\n\tunsigned int GetNameHash(clcpp::Name name)\r\n\t{\r\n\t\treturn name.hash;\r\n\t}\r\n\tunsigned int GetPrimitiveHash(const clcpp::Primitive& primitive)\r\n\t{\r\n\t\treturn primitive.name.hash;\r\n\t}\r\n\tunsigned int GetPrimitivePtrHash(const clcpp::Primitive* primitive)\r\n\t{\r\n\t\treturn primitive->name.hash;\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tint BinarySearch(const clcpp::CArray& entries, unsigned int compare_hash)\r\n\t{\r\n\t\tint first = 0;\r\n\t\tint last = entries.size() - 1;\r\n\r\n\t\t\/\/ Binary search\r\n\t\twhile (first <= last)\r\n\t\t{\r\n\t\t\t\/\/ Identify the mid point\r\n\t\t\tint mid = (first + last) \/ 2;\r\n\r\n\t\t\tunsigned entry_hash = GET_HASH_FUNC(entries[mid]);\r\n\t\t\tif (compare_hash > entry_hash)\r\n\t\t\t{\r\n\t\t\t\t\/\/ Shift search to local upper half\r\n\t\t\t\tfirst = mid + 1;\r\n\t\t\t}\r\n\t\t\telse if (compare_hash < entry_hash)\r\n\t\t\t{\r\n\t\t\t\t\/\/ Shift search to local lower half\r\n\t\t\t\tlast = mid - 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t\/\/ Exact match found\r\n\t\t\t\treturn mid;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn -1;\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tclcpp::Range SearchNeighbours(const clcpp::CArray& entries, unsigned int compare_hash, int index)\r\n\t{\r\n\t\tclcpp::Range range;\r\n\t\trange.first = index;\r\n\t\trange.last = index + 1;\r\n\r\n\t\t\/\/ Search either side of the result, gathering further matches\r\n\t\twhile (range.first > 0 && GET_HASH_FUNC(entries[range.first - 1]) == compare_hash)\r\n\t\t\trange.first--;\r\n\t\twhile (range.last < entries.size() && GET_HASH_FUNC(entries[range.last]) == compare_hash)\r\n\t\t\trange.last++;\r\n\r\n\t\treturn range;\r\n\t}\r\n\r\n\r\n\r\n void RebaseFunctions(clcpp::internal::DatabaseMem& dbmem, clcpp::pointer_type base_address)\r\n\t{\r\n\t\t\/\/ Move all function addresses from their current location to their new location\r\n\t\tfor (int i = 0; i < dbmem.functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::Function& f = dbmem.functions[i];\r\n\t\t\tif (f.address)\r\n\t\t\t\tf.address = f.address - dbmem.function_base_address + base_address;\r\n\t\t}\r\n\r\n\t\t\/\/ Do the same for the GetType family of functions\r\n\t\tfor (int i = 0; i < dbmem.get_type_functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::internal::GetTypeFunctions& f = dbmem.get_type_functions[i];\r\n\t\t\tif (f.get_typename_address)\r\n\t\t\t\tf.get_typename_address = f.get_typename_address - dbmem.function_base_address + base_address;\r\n\t\t\tif (f.get_type_address)\r\n\t\t\t\tf.get_type_address = f.get_type_address - dbmem.function_base_address + base_address;\r\n\t\t}\r\n\t}\r\n\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n\r\n \/\/ GCC specific patch functions\r\n template\r\n void GccPatchFunction(clcpp::pointer_type function_address,\r\n const T& patch_value, const T& original_value)\r\n {\r\n unsigned char* function_pointer = (unsigned char*) function_address;\r\n\r\n \/\/ searches for 0x20 instruction headers at most\r\n for (int i = 0; i < 0x20; i++)\r\n {\r\n#if defined(CLCPP_USING_64_BIT)\r\n \/\/ 64 bit patch starts here\r\n if (function_pointer[i] == 0x8B) {\r\n \/\/ MOV instruction\r\n \/\/ this may be what we are looking for\r\n clcpp::uint32 target_offset = *((clcpp::uint32*) &function_pointer[i + 2]);\r\n T* target_ptr = (T*) (&function_pointer[i + 6] + target_offset);\r\n\r\n \/\/ although we get the real target address here, we still cannot\r\n \/\/ say immediately if this is our target pointer to patch. On\r\n \/\/ Mac OS X, this pointer would first point to a stub, which\r\n \/\/ then points to the real pointer, so we may have two levels\r\n \/\/ of pointers here. In this case, we would test for both cases.\r\n if (*target_ptr == original_value) {\r\n \/\/ there's no stubs, this is the pointer we are looking for\r\n *target_ptr = patch_value;\r\n return;\r\n }\r\n\r\n#if defined(CLCPP_USING_GNUC_MAC)\r\n \/\/ we test for stub pointer on mac\r\n \/\/ TODO: check if other compiler has the same behaviour\r\n T* target_stub = *((T**) target_ptr);\r\n if (*target_stub == original_value) {\r\n *target_stub = patch_value;\r\n return;\r\n }\r\n#endif \/\/ CLCPP_USING_GNUC_MAC\r\n\r\n }\r\n \/\/ 64 bit patch ends here\r\n#else\r\n \/\/ 32 bit patch starts here\r\n if (function_pointer[i] == 0xA1) {\r\n T* target_addr = *((T**) (&function_pointer[i + 1]));\r\n\r\n if (*target_addr == original_value) {\r\n *target_addr = patch_value;\r\n return;\r\n }\r\n }\r\n \/\/ 32 bit patch ends here\r\n#endif \/\/ CLCPP_USING_64_BIT\r\n }\r\n \/\/ TODO: we may want to add error raising code here since we failed to do the patch\r\n return;\r\n }\r\n\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\r\n\r\n\tvoid PatchGetTypeAddresses(clcpp::Database& db, clcpp::internal::DatabaseMem& dbmem)\r\n\t{\r\n unsigned int original_hash = CLCPP_INVALID_HASH;\r\n const clcpp::Type* original_type = (const clcpp::Type*) CLCPP_INVALID_ADDRESS;\r\n\r\n\t\tfor (int i = 0; i < dbmem.get_type_functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::internal::GetTypeFunctions& f = dbmem.get_type_functions[i];\r\n\r\n\t\t\t\/\/ Patch up the type name hash static variable\r\n\t\t\tif (f.get_typename_address)\r\n\t\t\t{\r\n unsigned int hash = db.GetName(f.type_hash).hash;\r\n\r\n#if defined(CLCPP_USING_MSVC)\r\n\t\t\t\tunsigned char* mov_instruction = (unsigned char*)f.get_typename_address;\r\n\t\t\t\tclcpp::internal::Assert(*mov_instruction == 0xA1);\r\n unsigned int* hash_address = *(unsigned int**)(mov_instruction + 1);\r\n\t\t\t\t*hash_address = hash;\r\n#endif \/\/ CLCPP_USING_MSVC\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n GccPatchFunction(f.get_typename_address,\r\n hash,\r\n original_hash);\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Patch up the type pointer static variable\r\n\t\t\tif (f.get_type_address)\r\n\t\t\t{\r\n const clcpp::Type* type = db.GetType(f.type_hash);\r\n\r\n#if defined(CLCPP_USING_MSVC)\r\n\t\t\t\tunsigned char* mov_instruction = (unsigned char*)f.get_type_address;\r\n\t\t\t\tclcpp::internal::Assert(*mov_instruction == 0xA1);\r\n\t\t\t\tconst clcpp::Type** type_address = *(const clcpp::Type***)(mov_instruction + 1);\r\n\t\t\t\t*type_address = type;\r\n#endif \/\/ CLCPP_USING_MSVC\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n GccPatchFunction(f.get_type_address,\r\n type,\r\n original_type);\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tvoid ParentPrimitivesToDatabase(clcpp::CArray& primitives, clcpp::Database* database)\r\n\t{\r\n\t\tfor (int i = 0; i < primitives.size(); i++)\r\n\t\t\tprimitives[i].database = database;\r\n\t}\r\n}\r\n\r\n\r\nconst clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray& primitives, unsigned int hash)\r\n{\r\n\tint index = BinarySearch(primitives, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn primitives[index];\r\n}\r\n\r\n\r\nclcpp::Range clcpp::internal::FindOverloadedPrimitive(const CArray& primitives, unsigned int hash)\r\n{\r\n\t\/\/ Search for the first entry\r\n\tint index = BinarySearch(primitives, hash);\r\n\tif (index == -1)\r\n\t\treturn Range();\r\n\r\n\t\/\/ Look at its neighbours to widen the primitives found\r\n\treturn SearchNeighbours(primitives, hash, index);\r\n}\r\n\r\n\r\nclcpp::Database::Database()\r\n\t: m_DatabaseMem(0)\r\n\t, m_Allocator(0)\r\n{\r\n}\r\n\r\n\r\nclcpp::Database::~Database()\r\n{\r\n\tif (m_DatabaseMem)\r\n\t\tm_Allocator->Free(m_DatabaseMem);\r\n}\r\n\r\n\r\nbool clcpp::Database::Load(IFile* file, IAllocator* allocator, clcpp::pointer_type base_address, unsigned int options)\r\n{\r\n\t\/\/ Load the database\r\n\tinternal::Assert(m_DatabaseMem == 0 && \"Database already loaded\");\r\n\tm_Allocator = allocator;\r\n\tm_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);\r\n\r\n\tif (m_DatabaseMem != 0)\r\n\t{\r\n\t\t\/\/ If no base address is provided, rebasing will not occur and it is assumed the addresses\r\n\t\t\/\/ loaded are already correct. Rebasing is usually only needed for DLLs that have been moved\r\n\t\t\/\/ by the OS due to another DLL occupying its preferred load address.\r\n\t\tif (base_address != 0)\r\n\t\t\tRebaseFunctions(*m_DatabaseMem, base_address);\r\n\r\n\t\tif ((options & OPT_DONT_PATCH_GETTYPE) == 0)\r\n\t\t\tPatchGetTypeAddresses(*this, *m_DatabaseMem);\r\n\r\n\t\t\/\/ Tell each loaded primitive that they belong to this database\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->types, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->enum_constants, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->enums, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->fields, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->functions, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->classes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->templates, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->template_types, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->namespaces, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->flag_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->int_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->float_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->primitive_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->text_attributes, this);\r\n\t}\r\n\r\n\treturn m_DatabaseMem != 0;\r\n}\r\n\r\n\r\nclcpp::Name clcpp::Database::GetName(unsigned int hash) const\r\n{\r\n\t\/\/ Lookup the name by hash\r\n\tint index = BinarySearch(m_DatabaseMem->names, hash);\r\n\tif (index == -1)\r\n\t\treturn clcpp::Name();\r\n\treturn m_DatabaseMem->names[index];\r\n}\r\n\r\n\r\nclcpp::Name clcpp::Database::GetName(const char* text) const\r\n{\r\n\t\/\/ Null pointer\r\n\tif (text == 0)\r\n\t\treturn clcpp::Name();\r\n\r\n\t\/\/ Hash and exit on no value\r\n\tunsigned int hash = internal::HashNameString(text);\r\n\tif (hash == 0)\r\n\t\treturn clcpp::Name();\r\n\r\n\treturn GetName(hash);\r\n}\r\n\r\n\r\nconst clcpp::Type* clcpp::Database::GetType(unsigned int hash) const\r\n{\r\n\treturn FindPrimitive(m_DatabaseMem->type_primitives, hash);\r\n}\r\n\r\n\r\nconst clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->namespaces, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->namespaces[index];\r\n}\r\n\r\n\r\nconst clcpp::Namespace* clcpp::Database::GetGlobalNamespace() const\r\n{\r\n\treturn &m_DatabaseMem->global_namespace;\r\n}\r\n\r\n\r\nconst clcpp::Template* clcpp::Database::GetTemplate(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->templates, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->templates[index];\r\n}\r\n\r\n\r\nconst clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->functions, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->functions[index];\r\n}\r\n\r\n\r\nclcpp::Range clcpp::Database::GetOverloadedFunction(unsigned int hash) const\r\n{\r\n\t\/\/ Quickly locate the first match\r\n\tint index = BinarySearch(m_DatabaseMem->functions, hash);\r\n\tif (index == -1)\r\n\t\treturn Range();\r\n\r\n\t\/\/ Functions can be overloaded so look at the neighbours to widen the primitives found\r\n\treturn SearchNeighbours(m_DatabaseMem->functions, hash, index);\r\n}\r\nFix windows build\r\n\/\/\r\n\/\/ ===============================================================================\r\n\/\/ clReflect\r\n\/\/ -------------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2011 Don Williamson\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\r\n\/\/ of the Software, and to permit persons to whom the Software is furnished to do\r\n\/\/ so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/ SOFTWARE.\r\n\/\/ ===============================================================================\r\n\/\/\r\n\r\n#include \r\n#include \"DatabaseLoader.h\"\r\n\r\n\r\nnamespace\r\n{\r\n\tunsigned int GetNameHash(clcpp::Name name)\r\n\t{\r\n\t\treturn name.hash;\r\n\t}\r\n\tunsigned int GetPrimitiveHash(const clcpp::Primitive& primitive)\r\n\t{\r\n\t\treturn primitive.name.hash;\r\n\t}\r\n\tunsigned int GetPrimitivePtrHash(const clcpp::Primitive* primitive)\r\n\t{\r\n\t\treturn primitive->name.hash;\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tint BinarySearch(const clcpp::CArray& entries, unsigned int compare_hash)\r\n\t{\r\n\t\tint first = 0;\r\n\t\tint last = entries.size() - 1;\r\n\r\n\t\t\/\/ Binary search\r\n\t\twhile (first <= last)\r\n\t\t{\r\n\t\t\t\/\/ Identify the mid point\r\n\t\t\tint mid = (first + last) \/ 2;\r\n\r\n\t\t\tunsigned entry_hash = GET_HASH_FUNC(entries[mid]);\r\n\t\t\tif (compare_hash > entry_hash)\r\n\t\t\t{\r\n\t\t\t\t\/\/ Shift search to local upper half\r\n\t\t\t\tfirst = mid + 1;\r\n\t\t\t}\r\n\t\t\telse if (compare_hash < entry_hash)\r\n\t\t\t{\r\n\t\t\t\t\/\/ Shift search to local lower half\r\n\t\t\t\tlast = mid - 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t\/\/ Exact match found\r\n\t\t\t\treturn mid;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn -1;\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tclcpp::Range SearchNeighbours(const clcpp::CArray& entries, unsigned int compare_hash, int index)\r\n\t{\r\n\t\tclcpp::Range range;\r\n\t\trange.first = index;\r\n\t\trange.last = index + 1;\r\n\r\n\t\t\/\/ Search either side of the result, gathering further matches\r\n\t\twhile (range.first > 0 && GET_HASH_FUNC(entries[range.first - 1]) == compare_hash)\r\n\t\t\trange.first--;\r\n\t\twhile (range.last < entries.size() && GET_HASH_FUNC(entries[range.last]) == compare_hash)\r\n\t\t\trange.last++;\r\n\r\n\t\treturn range;\r\n\t}\r\n\r\n\r\n\r\n void RebaseFunctions(clcpp::internal::DatabaseMem& dbmem, clcpp::pointer_type base_address)\r\n\t{\r\n\t\t\/\/ Move all function addresses from their current location to their new location\r\n\t\tfor (int i = 0; i < dbmem.functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::Function& f = dbmem.functions[i];\r\n\t\t\tif (f.address)\r\n\t\t\t\tf.address = f.address - dbmem.function_base_address + base_address;\r\n\t\t}\r\n\r\n\t\t\/\/ Do the same for the GetType family of functions\r\n\t\tfor (int i = 0; i < dbmem.get_type_functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::internal::GetTypeFunctions& f = dbmem.get_type_functions[i];\r\n\t\t\tif (f.get_typename_address)\r\n\t\t\t\tf.get_typename_address = f.get_typename_address - dbmem.function_base_address + base_address;\r\n\t\t\tif (f.get_type_address)\r\n\t\t\t\tf.get_type_address = f.get_type_address - dbmem.function_base_address + base_address;\r\n\t\t}\r\n\t}\r\n\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n\r\n \/\/ GCC specific patch functions\r\n template\r\n void GccPatchFunction(clcpp::pointer_type function_address,\r\n const T& patch_value, const T& original_value)\r\n {\r\n unsigned char* function_pointer = (unsigned char*) function_address;\r\n\r\n \/\/ searches for 0x20 instruction headers at most\r\n for (int i = 0; i < 0x20; i++)\r\n {\r\n#if defined(CLCPP_USING_64_BIT)\r\n \/\/ 64 bit patch starts here\r\n if (function_pointer[i] == 0x8B) {\r\n \/\/ MOV instruction\r\n \/\/ this may be what we are looking for\r\n clcpp::uint32 target_offset = *((clcpp::uint32*) &function_pointer[i + 2]);\r\n T* target_ptr = (T*) (&function_pointer[i + 6] + target_offset);\r\n\r\n \/\/ although we get the real target address here, we still cannot\r\n \/\/ say immediately if this is our target pointer to patch. On\r\n \/\/ Mac OS X, this pointer would first point to a stub, which\r\n \/\/ then points to the real pointer, so we may have two levels\r\n \/\/ of pointers here. In this case, we would test for both cases.\r\n if (*target_ptr == original_value) {\r\n \/\/ there's no stubs, this is the pointer we are looking for\r\n *target_ptr = patch_value;\r\n return;\r\n }\r\n\r\n#if defined(CLCPP_USING_GNUC_MAC)\r\n \/\/ we test for stub pointer on mac\r\n \/\/ TODO: check if other compiler has the same behaviour\r\n T* target_stub = *((T**) target_ptr);\r\n if (*target_stub == original_value) {\r\n *target_stub = patch_value;\r\n return;\r\n }\r\n#endif \/\/ CLCPP_USING_GNUC_MAC\r\n\r\n }\r\n \/\/ 64 bit patch ends here\r\n#else\r\n \/\/ 32 bit patch starts here\r\n if (function_pointer[i] == 0xA1) {\r\n T* target_addr = *((T**) (&function_pointer[i + 1]));\r\n\r\n if (*target_addr == original_value) {\r\n *target_addr = patch_value;\r\n return;\r\n }\r\n }\r\n \/\/ 32 bit patch ends here\r\n#endif \/\/ CLCPP_USING_64_BIT\r\n }\r\n \/\/ TODO: we may want to add error raising code here since we failed to do the patch\r\n return;\r\n }\r\n\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\r\n\r\n\tvoid PatchGetTypeAddresses(clcpp::Database& db, clcpp::internal::DatabaseMem& dbmem)\r\n\t{\r\n#if defined(CLCPP_USING_GNUC)\r\n unsigned int original_hash = CLCPP_INVALID_HASH;\r\n const clcpp::Type* original_type = (const clcpp::Type*) CLCPP_INVALID_ADDRESS;\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\r\n\t\tfor (int i = 0; i < dbmem.get_type_functions.size(); i++)\r\n\t\t{\r\n\t\t\tclcpp::internal::GetTypeFunctions& f = dbmem.get_type_functions[i];\r\n\r\n\t\t\t\/\/ Patch up the type name hash static variable\r\n\t\t\tif (f.get_typename_address)\r\n\t\t\t{\r\n unsigned int hash = db.GetName(f.type_hash).hash;\r\n\r\n#if defined(CLCPP_USING_MSVC)\r\n\t\t\t\tunsigned char* mov_instruction = (unsigned char*)f.get_typename_address;\r\n\t\t\t\tclcpp::internal::Assert(*mov_instruction == 0xA1);\r\n unsigned int* hash_address = *(unsigned int**)(mov_instruction + 1);\r\n\t\t\t\t*hash_address = hash;\r\n#endif \/\/ CLCPP_USING_MSVC\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n GccPatchFunction(f.get_typename_address,\r\n hash,\r\n original_hash);\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\t\t\t}\r\n\r\n\t\t\t\/\/ Patch up the type pointer static variable\r\n\t\t\tif (f.get_type_address)\r\n\t\t\t{\r\n const clcpp::Type* type = db.GetType(f.type_hash);\r\n\r\n#if defined(CLCPP_USING_MSVC)\r\n\t\t\t\tunsigned char* mov_instruction = (unsigned char*)f.get_type_address;\r\n\t\t\t\tclcpp::internal::Assert(*mov_instruction == 0xA1);\r\n\t\t\t\tconst clcpp::Type** type_address = *(const clcpp::Type***)(mov_instruction + 1);\r\n\t\t\t\t*type_address = type;\r\n#endif \/\/ CLCPP_USING_MSVC\r\n\r\n#if defined(CLCPP_USING_GNUC)\r\n GccPatchFunction(f.get_type_address,\r\n type,\r\n original_type);\r\n#endif \/\/ CLCPP_USING_GNUC\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\ttemplate \r\n\tvoid ParentPrimitivesToDatabase(clcpp::CArray& primitives, clcpp::Database* database)\r\n\t{\r\n\t\tfor (int i = 0; i < primitives.size(); i++)\r\n\t\t\tprimitives[i].database = database;\r\n\t}\r\n}\r\n\r\n\r\nconst clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray& primitives, unsigned int hash)\r\n{\r\n\tint index = BinarySearch(primitives, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn primitives[index];\r\n}\r\n\r\n\r\nclcpp::Range clcpp::internal::FindOverloadedPrimitive(const CArray& primitives, unsigned int hash)\r\n{\r\n\t\/\/ Search for the first entry\r\n\tint index = BinarySearch(primitives, hash);\r\n\tif (index == -1)\r\n\t\treturn Range();\r\n\r\n\t\/\/ Look at its neighbours to widen the primitives found\r\n\treturn SearchNeighbours(primitives, hash, index);\r\n}\r\n\r\n\r\nclcpp::Database::Database()\r\n\t: m_DatabaseMem(0)\r\n\t, m_Allocator(0)\r\n{\r\n}\r\n\r\n\r\nclcpp::Database::~Database()\r\n{\r\n\tif (m_DatabaseMem)\r\n\t\tm_Allocator->Free(m_DatabaseMem);\r\n}\r\n\r\n\r\nbool clcpp::Database::Load(IFile* file, IAllocator* allocator, clcpp::pointer_type base_address, unsigned int options)\r\n{\r\n\t\/\/ Load the database\r\n\tinternal::Assert(m_DatabaseMem == 0 && \"Database already loaded\");\r\n\tm_Allocator = allocator;\r\n\tm_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);\r\n\r\n\tif (m_DatabaseMem != 0)\r\n\t{\r\n\t\t\/\/ If no base address is provided, rebasing will not occur and it is assumed the addresses\r\n\t\t\/\/ loaded are already correct. Rebasing is usually only needed for DLLs that have been moved\r\n\t\t\/\/ by the OS due to another DLL occupying its preferred load address.\r\n\t\tif (base_address != 0)\r\n\t\t\tRebaseFunctions(*m_DatabaseMem, base_address);\r\n\r\n\t\tif ((options & OPT_DONT_PATCH_GETTYPE) == 0)\r\n\t\t\tPatchGetTypeAddresses(*this, *m_DatabaseMem);\r\n\r\n\t\t\/\/ Tell each loaded primitive that they belong to this database\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->types, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->enum_constants, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->enums, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->fields, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->functions, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->classes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->templates, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->template_types, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->namespaces, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->flag_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->int_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->float_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->primitive_attributes, this);\r\n\t\tParentPrimitivesToDatabase(m_DatabaseMem->text_attributes, this);\r\n\t}\r\n\r\n\treturn m_DatabaseMem != 0;\r\n}\r\n\r\n\r\nclcpp::Name clcpp::Database::GetName(unsigned int hash) const\r\n{\r\n\t\/\/ Lookup the name by hash\r\n\tint index = BinarySearch(m_DatabaseMem->names, hash);\r\n\tif (index == -1)\r\n\t\treturn clcpp::Name();\r\n\treturn m_DatabaseMem->names[index];\r\n}\r\n\r\n\r\nclcpp::Name clcpp::Database::GetName(const char* text) const\r\n{\r\n\t\/\/ Null pointer\r\n\tif (text == 0)\r\n\t\treturn clcpp::Name();\r\n\r\n\t\/\/ Hash and exit on no value\r\n\tunsigned int hash = internal::HashNameString(text);\r\n\tif (hash == 0)\r\n\t\treturn clcpp::Name();\r\n\r\n\treturn GetName(hash);\r\n}\r\n\r\n\r\nconst clcpp::Type* clcpp::Database::GetType(unsigned int hash) const\r\n{\r\n\treturn FindPrimitive(m_DatabaseMem->type_primitives, hash);\r\n}\r\n\r\n\r\nconst clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->namespaces, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->namespaces[index];\r\n}\r\n\r\n\r\nconst clcpp::Namespace* clcpp::Database::GetGlobalNamespace() const\r\n{\r\n\treturn &m_DatabaseMem->global_namespace;\r\n}\r\n\r\n\r\nconst clcpp::Template* clcpp::Database::GetTemplate(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->templates, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->templates[index];\r\n}\r\n\r\n\r\nconst clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const\r\n{\r\n\tint index = BinarySearch(m_DatabaseMem->functions, hash);\r\n\tif (index == -1)\r\n\t\treturn 0;\r\n\treturn &m_DatabaseMem->functions[index];\r\n}\r\n\r\n\r\nclcpp::Range clcpp::Database::GetOverloadedFunction(unsigned int hash) const\r\n{\r\n\t\/\/ Quickly locate the first match\r\n\tint index = BinarySearch(m_DatabaseMem->functions, hash);\r\n\tif (index == -1)\r\n\t\treturn Range();\r\n\r\n\t\/\/ Functions can be overloaded so look at the neighbours to widen the primitives found\r\n\treturn SearchNeighbours(m_DatabaseMem->functions, hash, index);\r\n}\r\n<|endoftext|>"} {"text":"\r\n\/\/\r\n\/\/ ===============================================================================\r\n\/\/ clReflect\r\n\/\/ -------------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2011-2012 Don Williamson & clReflect Authors (see AUTHORS file)\r\n\/\/ Released under MIT License (see LICENSE file)\r\n\/\/ ===============================================================================\r\n\/\/\r\n\r\n\/\/ TODO: Lots of stuff happening in here that needs logging\r\n\r\n#include \r\n\r\n\r\nstruct clutl::ObjectGroup::HashEntry\r\n{\r\n\tHashEntry() : hash(0), object(0) { }\r\n\tunsigned int hash;\r\n\tObject* object;\r\n};\r\n\r\n\r\n\r\n\r\nclutl::Object* clutl::CreateObject(const clcpp::Type *type, unsigned int unique_id, ObjectGroup* object_group)\r\n{\r\n\tif (type == 0)\r\n\t\treturn 0;\r\n\r\n\t\/\/ Can only create class objects\r\n\tif (type->kind != clcpp::Primitive::KIND_CLASS)\r\n\t\treturn 0;\r\n\tconst clcpp::Class* class_type = type->AsClass();\r\n\r\n\t\/\/ The object group has no registered constructor so construct manually\r\n\t\/\/ if it comes through\r\n\tObject* object = 0;\r\n\tif (type->name.hash == clcpp::GetTypeNameHash())\r\n\t{\r\n\t\tobject = new ObjectGroup();\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Need a constructor to new and a destructor to delete at a later point\r\n\t\tif (class_type->constructor == 0 || class_type->destructor == 0)\r\n\t\t\treturn 0;\r\n\r\n\t\t\/\/ Allocate and call the constructor\r\n\t\tobject = (Object*)new char[type->size];\r\n\t\ttypedef void (*CallFunc)(clutl::Object*);\r\n\t\tCallFunc call_func = (CallFunc)class_type->constructor->address;\r\n\t\tcall_func(object);\r\n\t}\r\n\r\n\t\/\/ Construct the object and add to its object group\r\n\tobject->type = type;\r\n\tobject->unique_id = unique_id;\r\n\tif (object_group)\r\n\t\tobject_group->AddObject(object);\r\n\r\n\treturn object;\r\n}\r\n\r\n\r\nvoid clutl::DestroyObject(const Object* object)\r\n{\r\n\t\/\/ These represent fatal code errors\r\n\tclcpp::internal::Assert(object != 0);\r\n\tclcpp::internal::Assert(object->type != 0);\r\n\r\n\t\/\/ Remove from any attached object group\r\n\tif (object->object_group != 0)\r\n\t\tobject->object_group->RemoveObject(object);\r\n\r\n\tif (object->type->name.hash == clcpp::GetTypeNameHash())\r\n\t{\r\n\t\t\/\/ ObjecGroup class does not have a registered destructor\r\n\t\tdelete (ObjectGroup*)object;\r\n\t}\r\n\r\n\telse\r\n\t{\r\n\t\t\/\/ Call the destructor and release the memory\r\n\t\tconst clcpp::Class* class_type = object->type->AsClass();\r\n\t\tclcpp::internal::Assert(class_type->destructor != 0);\r\n\t\ttypedef void (*CallFunc)(const clutl::Object*);\r\n\t\tCallFunc call_func = (CallFunc)class_type->destructor->address;\r\n\t\tcall_func(object);\r\n\t\tdelete [] (char*)object;\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\nclutl::ObjectGroup::ObjectGroup()\r\n\t: m_MaxNbObjects(8)\r\n\t, m_NbObjects(0)\r\n\t, m_NbOccupiedEntries(0)\r\n\t, m_NamedObjects(0)\r\n{\r\n\t\/\/ Allocate the hash table\r\n\tm_NamedObjects = new HashEntry[m_MaxNbObjects];\r\n}\r\n\r\n\r\nclutl::ObjectGroup::~ObjectGroup()\r\n{\r\n\tif (m_NamedObjects != 0)\r\n\t\tdelete [] m_NamedObjects;\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::AddObject(Object* object)\r\n{\r\n\tobject->object_group = this;\r\n\tif (object->unique_id != 0)\r\n\t\tAddHashEntry(object);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::RemoveObject(const Object* object)\r\n{\r\n\t\/\/ Remove from the hash table if it's named\r\n\tif (object->unique_id != 0)\r\n\t\tRemoveHashEntry(object->unique_id);\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObject(unsigned int unique_id) const\r\n{\r\n\t\/\/ Linear probe from the natural hash location for matching hash\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = unique_id & index_mask;\r\n\twhile (m_NamedObjects[index].hash)\r\n\t{\r\n\t\t\/\/ Ensure dummy objects are skipped\r\n\t\tif (m_NamedObjects[index].hash == unique_id &&\r\n\t\t\tm_NamedObjects[index].object != 0)\r\n\t\t\tbreak;\r\n\r\n\t\tindex = (index + 1) & index_mask;\r\n\t}\r\n\r\n\t\/\/ Get the object here\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\treturn he.object;\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObjectSearchParents(unsigned int unique_id) const\r\n{\r\n\t\/\/ Search up through the object group hierarchy\r\n\tconst ObjectGroup* group = this;\r\n\tObject* object = 0;\r\n\twhile (group != 0)\r\n\t{\r\n\t\tobject = group->FindObject(unique_id);\r\n\t\tif (object != 0)\r\n\t\t\tbreak;\r\n\r\n\t\tgroup = group->object_group;\r\n\t}\r\n\r\n\treturn object;\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObjectRelative(unsigned int* unique_ids, unsigned int nb_ids) const\r\n{\r\n\t\/\/ Locate the containing object group\r\n\tconst ObjectGroup* object_group = this;\r\n\twhile (nb_ids - 1 > 0)\r\n\t{\r\n\t\tObject* object = FindObject(*unique_ids++);\r\n\t\tif (object == 0)\r\n\t\t\treturn 0;\r\n\r\n\t\t\/\/ Ensure this is an object group\r\n\t\tif (object->type->kind != clcpp::Primitive::KIND_CLASS)\r\n\t\t\treturn 0;\r\n\t\tconst clcpp::Class* class_type = (clcpp::Class*)object->type;\r\n\t\tif (!(class_type->flag_attributes & FLAG_ATTR_IS_OBJECT_GROUP))\r\n\t\t\treturn 0;\r\n\r\n\t\tobject_group = (ObjectGroup*)object;\r\n\t\tnb_ids--;\r\n\t}\r\n\r\n\treturn object_group->FindObject(*unique_ids);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::AddHashEntry(Object* object)\r\n{\r\n\t\/\/ Linear probe from the natural hash location for a free slot, reusing any dummy slots\r\n\tunsigned int hash = object->unique_id;\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = hash & index_mask;\r\n\twhile (m_NamedObjects[index].hash && m_NamedObjects[index].object != 0)\r\n\t\tindex = (index + 1) & index_mask;\r\n\r\n\t\/\/ Add to the table\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\the.hash = hash;\r\n\the.object = object;\r\n\tm_NbObjects++;\r\n\tm_NbOccupiedEntries++;\r\n\r\n\t\/\/ Resize when load factor is greather than 2\/3\r\n\tif (m_NbObjects > (m_MaxNbObjects * 2) \/ 3)\r\n\t\tResize(true);\r\n\t\r\n\t\/\/ Or flush dummy objects so that there is always at least on empty slot\r\n\t\/\/ This is required for the FindObject loop to terminate when an object can't be find\r\n\telse if (m_NbOccupiedEntries == m_MaxNbObjects)\r\n\t\tResize(false);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::RemoveHashEntry(unsigned int hash)\r\n{\r\n\t\/\/ Linear probe from the natural hash location for matching hash\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = hash & index_mask;\r\n\twhile (m_NamedObjects[index].hash && m_NamedObjects[index].hash != hash)\r\n\t\tindex = (index + 1) & index_mask;\r\n\r\n\t\/\/ Leave the has key in-place, clearing the object pointer, marking the object as a dummy object\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\the.object = 0;\r\n\tm_NbObjects--;\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::Resize(bool increase)\r\n{\r\n\t\/\/ Backup existing table\r\n\tunsigned int old_max_nb_objects = m_MaxNbObjects;\r\n\tHashEntry* old_named_objects = m_NamedObjects;\r\n\r\n\t\/\/ Either make the table bigger or leave it the same size to flush all dummy objects\r\n\tif (increase)\r\n\t{\r\n\t\tif (m_MaxNbObjects < 8192 * 4)\r\n\t\t\tm_MaxNbObjects *= 4;\r\n\t\telse\r\n\t\t\tm_MaxNbObjects *= 2;\r\n\t}\r\n\tm_NamedObjects = new HashEntry[m_MaxNbObjects];\r\n\r\n\t\/\/ Reinsert all objects into the new hash table\r\n\tm_NbObjects = 0;\r\n\tm_NbOccupiedEntries = 0;\r\n\tfor (unsigned int i = 0; i < old_max_nb_objects; i++)\r\n\t{\r\n\t\tHashEntry& he = old_named_objects[i];\r\n\t\tif (he.object != 0)\r\n\t\t\tAddHashEntry(he.object);\r\n\t}\r\n\r\n\tdelete [] old_named_objects;\r\n}\r\n\r\n\r\nclutl::ObjectDatabase::ObjectDatabase()\r\n\t: m_RootGroup(0)\r\n{\r\n\tm_RootGroup = New();\r\n}\r\n\r\n\r\nclutl::ObjectDatabase::~ObjectDatabase()\r\n{\r\n\tDelete(m_RootGroup);\r\n}\r\n\r\n\r\nclutl::ObjectIterator::ObjectIterator(const ObjectGroup* object_group)\r\n\t: m_ObjectGroup(object_group)\r\n\t, m_Position(0)\r\n{\r\n\t\/\/ Search for the first non-empty slot\r\n\tScanForEntry();\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectIterator::GetObject() const\r\n{\r\n\tclcpp::internal::Assert(IsValid());\r\n\treturn m_ObjectGroup->m_NamedObjects[m_Position].object;\r\n}\r\n\r\n\r\nvoid clutl::ObjectIterator::MoveNext()\r\n{\r\n\tm_Position++;\r\n\tScanForEntry();\r\n}\r\n\r\n\r\nbool clutl::ObjectIterator::IsValid() const\r\n{\r\n\treturn m_Position < m_ObjectGroup->m_MaxNbObjects;\r\n}\r\n\r\n\r\nvoid clutl::ObjectIterator::ScanForEntry()\r\n{\r\n\t\/\/ Search for the next non-empty slot\r\n\twhile (m_Position < m_ObjectGroup->m_MaxNbObjects &&\r\n\t\tm_ObjectGroup->m_NamedObjects[m_Position].object == 0)\r\n\t\tm_Position++;\r\n}\r\nSupport for using the util libs without requiring generated reflection info: * Store explicitly calculated hash of clutl::ObjectGroup instead of using GetTypeNameHash. * Go back to using new for the root group allocation instead of New (should ObjectDatabase be a supported type anymore?)\r\n\/\/\r\n\/\/ ===============================================================================\r\n\/\/ clReflect\r\n\/\/ -------------------------------------------------------------------------------\r\n\/\/ Copyright (c) 2011-2012 Don Williamson & clReflect Authors (see AUTHORS file)\r\n\/\/ Released under MIT License (see LICENSE file)\r\n\/\/ ===============================================================================\r\n\/\/\r\n\r\n\/\/ TODO: Lots of stuff happening in here that needs logging\r\n\r\n#include \r\n\r\n\r\n\/\/ Store this here, rather than using GetTypeNameHash so that this library\r\n\/\/ can be used without generating an implementation of GetTypeNameHash.\r\nstatic unsigned int g_ObjectGroupHash = clcpp::internal::HashNameString(\"clutl::ObjectGroup\");\r\n\r\n\r\nstruct clutl::ObjectGroup::HashEntry\r\n{\r\n\tHashEntry() : hash(0), object(0) { }\r\n\tunsigned int hash;\r\n\tObject* object;\r\n};\r\n\r\n\r\nclutl::Object* clutl::CreateObject(const clcpp::Type *type, unsigned int unique_id, ObjectGroup* object_group)\r\n{\r\n\tif (type == 0)\r\n\t\treturn 0;\r\n\r\n\t\/\/ Can only create class objects\r\n\tif (type->kind != clcpp::Primitive::KIND_CLASS)\r\n\t\treturn 0;\r\n\tconst clcpp::Class* class_type = type->AsClass();\r\n\r\n\t\/\/ The object group has no registered constructor so construct manually\r\n\t\/\/ if it comes through\r\n\tObject* object = 0;\r\n\tif (type->name.hash == g_ObjectGroupHash)\r\n\t{\r\n\t\tobject = new ObjectGroup();\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Need a constructor to new and a destructor to delete at a later point\r\n\t\tif (class_type->constructor == 0 || class_type->destructor == 0)\r\n\t\t\treturn 0;\r\n\r\n\t\t\/\/ Allocate and call the constructor\r\n\t\tobject = (Object*)new char[type->size];\r\n\t\ttypedef void (*CallFunc)(clutl::Object*);\r\n\t\tCallFunc call_func = (CallFunc)class_type->constructor->address;\r\n\t\tcall_func(object);\r\n\t}\r\n\r\n\t\/\/ Construct the object and add to its object group\r\n\tobject->type = type;\r\n\tobject->unique_id = unique_id;\r\n\tif (object_group)\r\n\t\tobject_group->AddObject(object);\r\n\r\n\treturn object;\r\n}\r\n\r\n\r\nvoid clutl::DestroyObject(const Object* object)\r\n{\r\n\t\/\/ These represent fatal code errors\r\n\tclcpp::internal::Assert(object != 0);\r\n\tclcpp::internal::Assert(object->type != 0);\r\n\r\n\t\/\/ Remove from any attached object group\r\n\tif (object->object_group != 0)\r\n\t\tobject->object_group->RemoveObject(object);\r\n\r\n\tif (object->type->name.hash == g_ObjectGroupHash)\r\n\t{\r\n\t\t\/\/ ObjecGroup class does not have a registered destructor\r\n\t\tdelete (ObjectGroup*)object;\r\n\t}\r\n\r\n\telse\r\n\t{\r\n\t\t\/\/ Call the destructor and release the memory\r\n\t\tconst clcpp::Class* class_type = object->type->AsClass();\r\n\t\tclcpp::internal::Assert(class_type->destructor != 0);\r\n\t\ttypedef void (*CallFunc)(const clutl::Object*);\r\n\t\tCallFunc call_func = (CallFunc)class_type->destructor->address;\r\n\t\tcall_func(object);\r\n\t\tdelete [] (char*)object;\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\nclutl::ObjectGroup::ObjectGroup()\r\n\t: m_MaxNbObjects(8)\r\n\t, m_NbObjects(0)\r\n\t, m_NbOccupiedEntries(0)\r\n\t, m_NamedObjects(0)\r\n{\r\n\t\/\/ Allocate the hash table\r\n\tm_NamedObjects = new HashEntry[m_MaxNbObjects];\r\n}\r\n\r\n\r\nclutl::ObjectGroup::~ObjectGroup()\r\n{\r\n\tif (m_NamedObjects != 0)\r\n\t\tdelete [] m_NamedObjects;\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::AddObject(Object* object)\r\n{\r\n\tobject->object_group = this;\r\n\tif (object->unique_id != 0)\r\n\t\tAddHashEntry(object);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::RemoveObject(const Object* object)\r\n{\r\n\t\/\/ Remove from the hash table if it's named\r\n\tif (object->unique_id != 0)\r\n\t\tRemoveHashEntry(object->unique_id);\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObject(unsigned int unique_id) const\r\n{\r\n\t\/\/ Linear probe from the natural hash location for matching hash\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = unique_id & index_mask;\r\n\twhile (m_NamedObjects[index].hash)\r\n\t{\r\n\t\t\/\/ Ensure dummy objects are skipped\r\n\t\tif (m_NamedObjects[index].hash == unique_id &&\r\n\t\t\tm_NamedObjects[index].object != 0)\r\n\t\t\tbreak;\r\n\r\n\t\tindex = (index + 1) & index_mask;\r\n\t}\r\n\r\n\t\/\/ Get the object here\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\treturn he.object;\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObjectSearchParents(unsigned int unique_id) const\r\n{\r\n\t\/\/ Search up through the object group hierarchy\r\n\tconst ObjectGroup* group = this;\r\n\tObject* object = 0;\r\n\twhile (group != 0)\r\n\t{\r\n\t\tobject = group->FindObject(unique_id);\r\n\t\tif (object != 0)\r\n\t\t\tbreak;\r\n\r\n\t\tgroup = group->object_group;\r\n\t}\r\n\r\n\treturn object;\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectGroup::FindObjectRelative(unsigned int* unique_ids, unsigned int nb_ids) const\r\n{\r\n\t\/\/ Locate the containing object group\r\n\tconst ObjectGroup* object_group = this;\r\n\twhile (nb_ids - 1 > 0)\r\n\t{\r\n\t\tObject* object = FindObject(*unique_ids++);\r\n\t\tif (object == 0)\r\n\t\t\treturn 0;\r\n\r\n\t\t\/\/ Ensure this is an object group\r\n\t\tif (object->type->kind != clcpp::Primitive::KIND_CLASS)\r\n\t\t\treturn 0;\r\n\t\tconst clcpp::Class* class_type = (clcpp::Class*)object->type;\r\n\t\tif (!(class_type->flag_attributes & FLAG_ATTR_IS_OBJECT_GROUP))\r\n\t\t\treturn 0;\r\n\r\n\t\tobject_group = (ObjectGroup*)object;\r\n\t\tnb_ids--;\r\n\t}\r\n\r\n\treturn object_group->FindObject(*unique_ids);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::AddHashEntry(Object* object)\r\n{\r\n\t\/\/ Linear probe from the natural hash location for a free slot, reusing any dummy slots\r\n\tunsigned int hash = object->unique_id;\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = hash & index_mask;\r\n\twhile (m_NamedObjects[index].hash && m_NamedObjects[index].object != 0)\r\n\t\tindex = (index + 1) & index_mask;\r\n\r\n\t\/\/ Add to the table\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\the.hash = hash;\r\n\the.object = object;\r\n\tm_NbObjects++;\r\n\tm_NbOccupiedEntries++;\r\n\r\n\t\/\/ Resize when load factor is greather than 2\/3\r\n\tif (m_NbObjects > (m_MaxNbObjects * 2) \/ 3)\r\n\t\tResize(true);\r\n\t\r\n\t\/\/ Or flush dummy objects so that there is always at least on empty slot\r\n\t\/\/ This is required for the FindObject loop to terminate when an object can't be find\r\n\telse if (m_NbOccupiedEntries == m_MaxNbObjects)\r\n\t\tResize(false);\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::RemoveHashEntry(unsigned int hash)\r\n{\r\n\t\/\/ Linear probe from the natural hash location for matching hash\r\n\tconst unsigned int index_mask = m_MaxNbObjects - 1;\r\n\tunsigned int index = hash & index_mask;\r\n\twhile (m_NamedObjects[index].hash && m_NamedObjects[index].hash != hash)\r\n\t\tindex = (index + 1) & index_mask;\r\n\r\n\t\/\/ Leave the has key in-place, clearing the object pointer, marking the object as a dummy object\r\n\tHashEntry& he = m_NamedObjects[index];\r\n\the.object = 0;\r\n\tm_NbObjects--;\r\n}\r\n\r\n\r\nvoid clutl::ObjectGroup::Resize(bool increase)\r\n{\r\n\t\/\/ Backup existing table\r\n\tunsigned int old_max_nb_objects = m_MaxNbObjects;\r\n\tHashEntry* old_named_objects = m_NamedObjects;\r\n\r\n\t\/\/ Either make the table bigger or leave it the same size to flush all dummy objects\r\n\tif (increase)\r\n\t{\r\n\t\tif (m_MaxNbObjects < 8192 * 4)\r\n\t\t\tm_MaxNbObjects *= 4;\r\n\t\telse\r\n\t\t\tm_MaxNbObjects *= 2;\r\n\t}\r\n\tm_NamedObjects = new HashEntry[m_MaxNbObjects];\r\n\r\n\t\/\/ Reinsert all objects into the new hash table\r\n\tm_NbObjects = 0;\r\n\tm_NbOccupiedEntries = 0;\r\n\tfor (unsigned int i = 0; i < old_max_nb_objects; i++)\r\n\t{\r\n\t\tHashEntry& he = old_named_objects[i];\r\n\t\tif (he.object != 0)\r\n\t\t\tAddHashEntry(he.object);\r\n\t}\r\n\r\n\tdelete [] old_named_objects;\r\n}\r\n\r\n\r\nclutl::ObjectDatabase::ObjectDatabase()\r\n\t: m_RootGroup(0)\r\n{\r\n\tm_RootGroup = new ObjectGroup;\r\n}\r\n\r\n\r\nclutl::ObjectDatabase::~ObjectDatabase()\r\n{\r\n\tdelete m_RootGroup;\r\n}\r\n\r\n\r\nclutl::ObjectIterator::ObjectIterator(const ObjectGroup* object_group)\r\n\t: m_ObjectGroup(object_group)\r\n\t, m_Position(0)\r\n{\r\n\t\/\/ Search for the first non-empty slot\r\n\tScanForEntry();\r\n}\r\n\r\n\r\nclutl::Object* clutl::ObjectIterator::GetObject() const\r\n{\r\n\tclcpp::internal::Assert(IsValid());\r\n\treturn m_ObjectGroup->m_NamedObjects[m_Position].object;\r\n}\r\n\r\n\r\nvoid clutl::ObjectIterator::MoveNext()\r\n{\r\n\tm_Position++;\r\n\tScanForEntry();\r\n}\r\n\r\n\r\nbool clutl::ObjectIterator::IsValid() const\r\n{\r\n\treturn m_Position < m_ObjectGroup->m_MaxNbObjects;\r\n}\r\n\r\n\r\nvoid clutl::ObjectIterator::ScanForEntry()\r\n{\r\n\t\/\/ Search for the next non-empty slot\r\n\twhile (m_Position < m_ObjectGroup->m_MaxNbObjects &&\r\n\t\tm_ObjectGroup->m_NamedObjects[m_Position].object == 0)\r\n\t\tm_Position++;\r\n}\r\n<|endoftext|>"} {"text":"#pragma once\r\n\r\n#include \r\n\r\n#include \"command_base.hxx\"\r\n#include \"grammar.hxx\"\r\n#include \"positional_argument.hxx\"\r\n#include \"parser_state.hxx\"\r\n\r\nnamespace cl\r\n{\r\n\tnamespace internal\r\n\t{\r\n\t\ttemplate< typename T >\r\n\t\tstruct parser_action\r\n\t\t\t:\tpegtl::nothing\r\n\t\t{};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.names().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.names().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.values().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.is_short() = false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.is_short() = true;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif(p_state.is_short())\r\n\t\t\t\t\tp_hndlr.get(p_state.name().at(0))->read(p_state.values(), true);\r\n\t\t\t\telse p_hndlr.get(p_state.name())->read(p_state.values(), true);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\t\r\n\t\t\t\tfor (auto& t_name : p_state.names())\r\n\t\t\t\t\tp_hndlr.get(t_name.at(0))->read(p_state.values(), false);\t\t\t\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif(p_state.is_short())\r\n\t\t\t\t\tp_hndlr.get(p_state.name().at(0))->read(p_state.values(), false);\r\n\t\t\t\telse p_hndlr.get(p_state.name())->read(p_state.values(), false);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif (!p_state.values().empty())\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Try to add values to free_arguments. TODO solve without try catch\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp_hndlr.get(\"\")->read(p_state.values(), false);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (...)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ If no free_arguments was added, just ignore the values\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/ Clean up state for next match\r\n\t\t\t\tp_state.cleanup();\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n}Reworked some code to avoid using try-catch as control structure.#pragma once\r\n\r\n#include \r\n\r\n#include \"command_base.hxx\"\r\n#include \"grammar.hxx\"\r\n#include \"positional_argument.hxx\"\r\n#include \"parser_state.hxx\"\r\n\r\nnamespace cl\r\n{\r\n\tnamespace internal\r\n\t{\r\n\t\ttemplate< typename T >\r\n\t\tstruct parser_action\r\n\t\t\t:\tpegtl::nothing\r\n\t\t{};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.names().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.names().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.values().push_back(p_in.string());\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.is_short() = false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tp_state.is_short() = true;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif(p_state.is_short())\r\n\t\t\t\t\tp_hndlr.get(p_state.name().at(0))->read(p_state.values(), true);\r\n\t\t\t\telse p_hndlr.get(p_state.name())->read(p_state.values(), true);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\t\r\n\t\t\t\tfor (auto& t_name : p_state.names())\r\n\t\t\t\t\tp_hndlr.get(t_name.at(0))->read(p_state.values(), false);\t\t\t\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif(p_state.is_short())\r\n\t\t\t\t\tp_hndlr.get(p_state.name().at(0))->read(p_state.values(), false);\r\n\t\t\t\telse p_hndlr.get(p_state.name())->read(p_state.values(), false);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate< >\r\n\t\tstruct parser_action \r\n\t\t{\r\n\t\t\tstatic void apply(const pegtl::input& p_in, command_base& p_hndlr, parser_state& p_state)\r\n\t\t\t{\r\n\t\t\t\tif (!p_state.values().empty())\r\n\t\t\t\t{\r\n\t\t\t\t\t\/*\/\/ Try to add values to free_arguments. TODO solve without try catch\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp_hndlr.get(\"\")->read(p_state.values(), false);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (...)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ If no free_arguments was added, just ignore the values\r\n\t\t\t\t\t}*\/\r\n\t\t\t\t\t\/\/ The use might not have supplied a handler for free arguments\r\n\t\t\t\t\tif(p_hndlr.has(\"\"))\r\n\t\t\t\t\t\tp_hndlr.get(\"\")->read(p_state.values(), false);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/ Clean up state for next match\r\n\t\t\t\tp_state.cleanup();\r\n\t\t\t}\r\n\t\t};\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#include \"pch.h\"\n#include \"Servo.h\"\n#include \n\nnamespace winrt::servo {\n\nvoid on_load_started() { sServo->Delegate().OnServoLoadStarted(); }\n\nvoid on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }\n\nvoid on_history_changed(bool back, bool forward) {\n sServo->Delegate().OnServoHistoryChanged(back, forward);\n}\n\nvoid on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }\n\nvoid on_title_changed(const char *title) {\n sServo->Delegate().OnServoTitleChanged(char2hstring(title));\n}\n\nvoid on_url_changed(const char *url) {\n sServo->Delegate().OnServoURLChanged(char2hstring(url));\n}\n\nvoid wakeup() { sServo->Delegate().WakeUp(); }\n\nbool on_allow_navigation(const char *url) {\n return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));\n};\n\nvoid on_animating_changed(bool aAnimating) {\n sServo->Delegate().OnServoAnimatingChanged(aAnimating);\n}\n\nvoid on_panic(const char *backtrace) {\n if (sLogHandle != INVALID_HANDLE_VALUE) {\n CloseHandle(sLogHandle);\n sLogHandle = INVALID_HANDLE_VALUE;\n }\n throw hresult_error(E_FAIL, char2hstring(backtrace));\n}\n\nvoid on_ime_state_changed(bool aShow) {\n sServo->Delegate().OnServoIMEStateChanged(aShow);\n}\n\nvoid set_clipboard_contents(const char *) {\n \/\/ FIXME\n}\n\nconst char *get_clipboard_contents() {\n \/\/ FIXME\n return nullptr;\n}\n\nvoid on_media_session_metadata(const char *title, const char *album,\n const char *artist) {\n return sServo->Delegate().OnServoMediaSessionMetadata(\n char2hstring(title), char2hstring(album), char2hstring(artist));\n}\n\nvoid on_media_session_playback_state_change(\n const capi::CMediaSessionPlaybackState state) {\n return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);\n}\n\nvoid prompt_alert(const char *message, bool trusted) {\n sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);\n}\n\nvoid show_context_menu(const char *title, const char *const *items_list,\n uint32_t items_size) {\n std::optional opt_title = {};\n if (title != nullptr) {\n opt_title = char2hstring(title);\n }\n std::vector items;\n for (uint32_t i = 0; i < items_size; i++) {\n items.push_back(char2hstring(items_list[i]));\n }\n sServo->Delegate().OnServoShowContextMenu(opt_title, items);\n}\n\nvoid on_devtools_started(Servo::DevtoolsServerState result,\n const unsigned int port) {\n sServo->Delegate().OnServoDevtoolsStarted(\n result == Servo::DevtoolsServerState::Started, port);\n}\n\nvoid on_log_output(const char *buffer, uint32_t buffer_length) {\n OutputDebugStringA(buffer);\n\n if (sLogHandle == INVALID_HANDLE_VALUE) {\n return;\n }\n\n DWORD bytesWritten;\n auto writeResult =\n WriteFile(sLogHandle, buffer, buffer_length, &bytesWritten, nullptr);\n\n if (writeResult == FALSE || bytesWritten != buffer_length)\n throw std::runtime_error(\n \"Failed to write log message to the log file: error code \" +\n std::to_string(GetLastError()));\n}\n\nServo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),\n trusted);\n}\n\nServo::PromptResult prompt_yes_no(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);\n}\n\nconst char *prompt_input(const char *message, const char *default,\n bool trusted) {\n auto input = sServo->Delegate().OnServoPromptInput(\n char2hstring(message), char2hstring(default), trusted);\n if (input.has_value()) {\n return *hstring2char(*input);\n } else {\n return nullptr;\n }\n}\n\nServo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,\n EGLNativeWindowType eglNativeWindow, float dpi,\n ServoDelegate &aDelegate)\n : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {\n SetEnvironmentVariableA(\"PreviewRuntimeEnabled\", \"1\");\n\n capi::CInitOptions o;\n hstring defaultPrefs = L\" --pref dom.webxr.enabled --devtools\";\n o.args = *hstring2char(args + defaultPrefs);\n o.url = *hstring2char(url);\n o.width = mWindowWidth;\n o.height = mWindowHeight;\n o.density = dpi;\n o.enable_subpixel_text_antialiasing = false;\n o.native_widget = eglNativeWindow;\n\n \/\/ Note about logs:\n \/\/ By default: all modules are enabled. Only warn level-logs are displayed.\n \/\/ To change the log level, add \"--vslogger-level debug\" to o.args.\n \/\/ To only print logs from specific modules, add their names to pfilters.\n \/\/ For example:\n \/\/ static char *pfilters[] = {\n \/\/ \"servo\",\n \/\/ \"simpleservo\",\n \/\/ \"script::dom::bindings::error\", \/\/ Show JS errors by default.\n \/\/ \"canvas::webgl_thread\", \/\/ Show GL errors by default.\n \/\/ \"compositing\",\n \/\/ \"constellation\",\n \/\/ };\n \/\/ o.vslogger_mod_list = pfilters;\n \/\/ o.vslogger_mod_size = sizeof(pfilters) \/ sizeof(pfilters[0]);\n\n o.vslogger_mod_list = NULL;\n o.vslogger_mod_size = 0;\n\n sServo = this; \/\/ FIXME;\n\n#ifdef _DEBUG\n auto current = winrt::Windows::Storage::ApplicationData::Current();\n auto filePath = std::wstring(current.LocalFolder().Path()) + L\"\\\\stdout.txt\";\n sLogHandle =\n CreateFile2(filePath.c_str(), GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr);\n if (sLogHandle == INVALID_HANDLE_VALUE)\n throw std::runtime_error(\"Failed to open the log file: error code \" +\n std::to_string(GetLastError()));\n\n if (SetFilePointer(sLogHandle, 0, nullptr, FILE_END) ==\n INVALID_SET_FILE_POINTER)\n throw std::runtime_error(\n \"Failed to set file pointer to the end of file: error code \" +\n std::to_string(GetLastError()));\n#endif\n\n capi::CHostCallbacks c;\n c.on_load_started = &on_load_started;\n c.on_load_ended = &on_load_ended;\n c.on_title_changed = &on_title_changed;\n c.on_url_changed = &on_url_changed;\n c.on_history_changed = &on_history_changed;\n c.on_animating_changed = &on_animating_changed;\n c.on_shutdown_complete = &on_shutdown_complete;\n c.on_allow_navigation = &on_allow_navigation;\n c.on_ime_state_changed = &on_ime_state_changed;\n c.get_clipboard_contents = &get_clipboard_contents;\n c.set_clipboard_contents = &set_clipboard_contents;\n c.on_media_session_metadata = &on_media_session_metadata;\n c.on_media_session_playback_state_change =\n &on_media_session_playback_state_change;\n c.prompt_alert = &prompt_alert;\n c.prompt_ok_cancel = &prompt_ok_cancel;\n c.prompt_yes_no = &prompt_yes_no;\n c.prompt_input = &prompt_input;\n c.on_devtools_started = &on_devtools_started;\n c.show_context_menu = &show_context_menu;\n c.on_log_output = &on_log_output;\n\n capi::register_panic_handler(&on_panic);\n\n capi::init_with_egl(o, &wakeup, c);\n}\n\nServo::~Servo() {\n sServo = nullptr;\n if (sLogHandle != INVALID_HANDLE_VALUE)\n CloseHandle(sLogHandle);\n}\n\nwinrt::hstring char2hstring(const char *c_str) {\n \/\/ FIXME: any better way of doing this?\n auto str = std::string(c_str);\n int size_needed =\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);\n std::wstring str2(size_needed, 0);\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],\n size_needed);\n winrt::hstring str3{str2};\n return str3;\n}\n\nstd::unique_ptr hstring2char(hstring hstr) {\n const wchar_t *wc = hstr.c_str();\n size_t size = hstr.size() + 1;\n char *str = new char[size];\n size_t converted = 0;\n wcstombs_s(&converted, str, size, wc, hstr.size());\n return std::make_unique(str);\n}\n\n} \/\/ namespace winrt::servo\nEnable UWP logging in release builds with FirefoxRealityLogStdout env var.#include \"pch.h\"\n#include \"Servo.h\"\n#include \n\nnamespace winrt::servo {\n\nvoid on_load_started() { sServo->Delegate().OnServoLoadStarted(); }\n\nvoid on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }\n\nvoid on_history_changed(bool back, bool forward) {\n sServo->Delegate().OnServoHistoryChanged(back, forward);\n}\n\nvoid on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }\n\nvoid on_title_changed(const char *title) {\n sServo->Delegate().OnServoTitleChanged(char2hstring(title));\n}\n\nvoid on_url_changed(const char *url) {\n sServo->Delegate().OnServoURLChanged(char2hstring(url));\n}\n\nvoid wakeup() { sServo->Delegate().WakeUp(); }\n\nbool on_allow_navigation(const char *url) {\n return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));\n};\n\nvoid on_animating_changed(bool aAnimating) {\n sServo->Delegate().OnServoAnimatingChanged(aAnimating);\n}\n\nvoid on_panic(const char *backtrace) {\n if (sLogHandle != INVALID_HANDLE_VALUE) {\n CloseHandle(sLogHandle);\n sLogHandle = INVALID_HANDLE_VALUE;\n }\n throw hresult_error(E_FAIL, char2hstring(backtrace));\n}\n\nvoid on_ime_state_changed(bool aShow) {\n sServo->Delegate().OnServoIMEStateChanged(aShow);\n}\n\nvoid set_clipboard_contents(const char *) {\n \/\/ FIXME\n}\n\nconst char *get_clipboard_contents() {\n \/\/ FIXME\n return nullptr;\n}\n\nvoid on_media_session_metadata(const char *title, const char *album,\n const char *artist) {\n return sServo->Delegate().OnServoMediaSessionMetadata(\n char2hstring(title), char2hstring(album), char2hstring(artist));\n}\n\nvoid on_media_session_playback_state_change(\n const capi::CMediaSessionPlaybackState state) {\n return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);\n}\n\nvoid prompt_alert(const char *message, bool trusted) {\n sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);\n}\n\nvoid show_context_menu(const char *title, const char *const *items_list,\n uint32_t items_size) {\n std::optional opt_title = {};\n if (title != nullptr) {\n opt_title = char2hstring(title);\n }\n std::vector items;\n for (uint32_t i = 0; i < items_size; i++) {\n items.push_back(char2hstring(items_list[i]));\n }\n sServo->Delegate().OnServoShowContextMenu(opt_title, items);\n}\n\nvoid on_devtools_started(Servo::DevtoolsServerState result,\n const unsigned int port) {\n sServo->Delegate().OnServoDevtoolsStarted(\n result == Servo::DevtoolsServerState::Started, port);\n}\n\nvoid on_log_output(const char *buffer, uint32_t buffer_length) {\n OutputDebugStringA(buffer);\n\n if (sLogHandle == INVALID_HANDLE_VALUE) {\n return;\n }\n\n DWORD bytesWritten;\n auto writeResult =\n WriteFile(sLogHandle, buffer, buffer_length, &bytesWritten, nullptr);\n\n if (writeResult == FALSE || bytesWritten != buffer_length)\n throw std::runtime_error(\n \"Failed to write log message to the log file: error code \" +\n std::to_string(GetLastError()));\n}\n\nServo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),\n trusted);\n}\n\nServo::PromptResult prompt_yes_no(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);\n}\n\nconst char *prompt_input(const char *message, const char *default,\n bool trusted) {\n auto input = sServo->Delegate().OnServoPromptInput(\n char2hstring(message), char2hstring(default), trusted);\n if (input.has_value()) {\n return *hstring2char(*input);\n } else {\n return nullptr;\n }\n}\n\nServo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,\n EGLNativeWindowType eglNativeWindow, float dpi,\n ServoDelegate &aDelegate)\n : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {\n SetEnvironmentVariableA(\"PreviewRuntimeEnabled\", \"1\");\n\n capi::CInitOptions o;\n hstring defaultPrefs = L\" --pref dom.webxr.enabled --devtools\";\n o.args = *hstring2char(args + defaultPrefs);\n o.url = *hstring2char(url);\n o.width = mWindowWidth;\n o.height = mWindowHeight;\n o.density = dpi;\n o.enable_subpixel_text_antialiasing = false;\n o.native_widget = eglNativeWindow;\n\n \/\/ Note about logs:\n \/\/ By default: all modules are enabled. Only warn level-logs are displayed.\n \/\/ To change the log level, add \"--vslogger-level debug\" to o.args.\n \/\/ To only print logs from specific modules, add their names to pfilters.\n \/\/ For example:\n \/\/ static char *pfilters[] = {\n \/\/ \"servo\",\n \/\/ \"simpleservo\",\n \/\/ \"script::dom::bindings::error\", \/\/ Show JS errors by default.\n \/\/ \"canvas::webgl_thread\", \/\/ Show GL errors by default.\n \/\/ \"compositing\",\n \/\/ \"constellation\",\n \/\/ };\n \/\/ o.vslogger_mod_list = pfilters;\n \/\/ o.vslogger_mod_size = sizeof(pfilters) \/ sizeof(pfilters[0]);\n\n o.vslogger_mod_list = NULL;\n o.vslogger_mod_size = 0;\n\n sServo = this; \/\/ FIXME;\n\n#ifndef _DEBUG\n char buffer[1024];\n bool logToFile = GetEnvironmentVariableA(\"FirefoxRealityLogStdout\", buffer,\n sizeof(buffer)) != 0;\n#else\n bool logToFile = true;\n#endif\n if (logToFile) {\n auto current = winrt::Windows::Storage::ApplicationData::Current();\n auto filePath =\n std::wstring(current.LocalFolder().Path()) + L\"\\\\stdout.txt\";\n sLogHandle =\n CreateFile2(filePath.c_str(), GENERIC_WRITE, 0, CREATE_ALWAYS, nullptr);\n if (sLogHandle == INVALID_HANDLE_VALUE) {\n throw std::runtime_error(\"Failed to open the log file: error code \" +\n std::to_string(GetLastError()));\n }\n\n if (SetFilePointer(sLogHandle, 0, nullptr, FILE_END) ==\n INVALID_SET_FILE_POINTER) {\n throw std::runtime_error(\n \"Failed to set file pointer to the end of file: error code \" +\n std::to_string(GetLastError()));\n }\n }\n\n capi::CHostCallbacks c;\n c.on_load_started = &on_load_started;\n c.on_load_ended = &on_load_ended;\n c.on_title_changed = &on_title_changed;\n c.on_url_changed = &on_url_changed;\n c.on_history_changed = &on_history_changed;\n c.on_animating_changed = &on_animating_changed;\n c.on_shutdown_complete = &on_shutdown_complete;\n c.on_allow_navigation = &on_allow_navigation;\n c.on_ime_state_changed = &on_ime_state_changed;\n c.get_clipboard_contents = &get_clipboard_contents;\n c.set_clipboard_contents = &set_clipboard_contents;\n c.on_media_session_metadata = &on_media_session_metadata;\n c.on_media_session_playback_state_change =\n &on_media_session_playback_state_change;\n c.prompt_alert = &prompt_alert;\n c.prompt_ok_cancel = &prompt_ok_cancel;\n c.prompt_yes_no = &prompt_yes_no;\n c.prompt_input = &prompt_input;\n c.on_devtools_started = &on_devtools_started;\n c.show_context_menu = &show_context_menu;\n c.on_log_output = &on_log_output;\n\n capi::register_panic_handler(&on_panic);\n\n capi::init_with_egl(o, &wakeup, c);\n}\n\nServo::~Servo() {\n sServo = nullptr;\n if (sLogHandle != INVALID_HANDLE_VALUE)\n CloseHandle(sLogHandle);\n}\n\nwinrt::hstring char2hstring(const char *c_str) {\n \/\/ FIXME: any better way of doing this?\n auto str = std::string(c_str);\n int size_needed =\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);\n std::wstring str2(size_needed, 0);\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],\n size_needed);\n winrt::hstring str3{str2};\n return str3;\n}\n\nstd::unique_ptr hstring2char(hstring hstr) {\n const wchar_t *wc = hstr.c_str();\n size_t size = hstr.size() + 1;\n char *str = new char[size];\n size_t converted = 0;\n wcstombs_s(&converted, str, size, wc, hstr.size());\n return std::make_unique(str);\n}\n\n} \/\/ namespace winrt::servo\n<|endoftext|>"} {"text":"#ifndef CTRE__RETURN_TYPE__HPP\n#define CTRE__RETURN_TYPE__HPP\n\n#include \"id.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace ctre {\n\t\nstruct not_matched_tag_t { };\n\nstatic constexpr inline auto not_matched = not_matched_tag_t{};\n\t\ntemplate struct captured_content {\n\ttemplate class storage {\n\t\tIterator _begin{};\n\t\tIterator _end{};\n\t\t\n\t\tbool _matched{false};\n\tpublic:\n\t\tusing char_type = typename std::iterator_traits::value_type;\n\t\t\n\t\tusing name = Name;\n\t\n\t\tconstexpr CTRE_FORCE_INLINE storage() noexcept {}\n\t\n\t\tconstexpr CTRE_FORCE_INLINE void matched() noexcept {\n\t\t\t_matched = true;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE void unmatch() noexcept {\n\t\t\t_matched = false;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE void set_start(Iterator pos) noexcept {\n\t\t\t_begin = pos;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE storage & set_end(Iterator pos) noexcept {\n\t\t\t_end = pos;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE Iterator get_end() const noexcept {\n\t\t\treturn _end;\n\t\t}\n\t\t\n\t\n\t\tconstexpr auto begin() const noexcept {\n\t\t\treturn _begin;\n\t\t}\n\t\tconstexpr auto end() const noexcept {\n\t\t\treturn _end;\n\t\t}\n\t\n\t\tconstexpr CTRE_FORCE_INLINE operator bool() const noexcept {\n\t\t\treturn _matched;\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE const auto * data() const noexcept {\n\t\t\treturn &*_begin;\n\t\t}\n\n\t\tconstexpr CTRE_FORCE_INLINE auto size() const noexcept {\n\t\t\treturn static_cast(std::distance(_begin, _end));\n\t\t}\n\n\t\tconstexpr CTRE_FORCE_INLINE auto to_view() const noexcept {\n\t\t\treturn std::basic_string_view(&*_begin, static_cast(std::distance(_begin, _end)));\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto to_string() const noexcept {\n\t\t\treturn std::basic_string(begin(), end());\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto view() const noexcept {\n\t\t\treturn std::basic_string_view(&*_begin, static_cast(std::distance(_begin, _end)));\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto str() const noexcept {\n\t\t\treturn std::basic_string(begin(), end());\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE operator std::basic_string_view() const noexcept {\n\t\t\treturn to_view();\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE explicit operator std::basic_string() const noexcept {\n\t\t\treturn to_string();\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE static size_t get_id() noexcept {\n\t\t\treturn Id;\n\t\t}\n\t\t\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator==(const storage & lhs, std::basic_string_view rhs) noexcept {\n\t\t\treturn lhs.view() == rhs;\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(const storage & lhs, std::basic_string_view rhs) noexcept {\n\t\t\treturn lhs.view() != rhs;\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator==(std::basic_string_view lhs, const storage & rhs) noexcept {\n\t\t\treturn lhs == rhs.view();\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(std::basic_string_view lhs, const storage & rhs) noexcept {\n\t\t\treturn lhs != rhs.view();\n\t\t}\n\t};\n};\n\nstruct capture_not_exists_tag { };\n\nstatic constexpr inline auto capture_not_exists = capture_not_exists_tag{};\n\ntemplate struct captures;\n\ntemplate struct captures: captures {\n\tHead head{};\n\tconstexpr CTRE_FORCE_INLINE captures() noexcept { }\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn captures::template exists();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn captures::template exists();\n\t\t}\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#endif\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn captures::template exists();\n\t\t} else {\n\t\t\tif constexpr (Head::name::name.is_same_as(Name)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn captures::template exists();\n\t\t\t}\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#endif\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn captures::template select();\n\t\t} else {\n\t\t\tif constexpr (Head::name::name.is_same_as(Name)) {\n\t\t\t\treturn head;\n\t\t\t} else {\n\t\t\t\treturn captures::template select();\n\t\t\t}\n\t\t}\n\t}\n};\n\ntemplate <> struct captures<> {\n\tconstexpr CTRE_FORCE_INLINE captures() noexcept { }\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\treturn false;\n\t}\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\treturn false;\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#endif\n\t\treturn false;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\treturn capture_not_exists;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\treturn capture_not_exists;\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#endif\n\t\treturn capture_not_exists;\n\t}\n};\n\ntemplate class regex_results {\n\tcaptures::template storage, typename Captures::template storage...> _captures{};\npublic:\n\tusing char_type = typename std::iterator_traits::value_type;\n\t\n\tconstexpr CTRE_FORCE_INLINE regex_results() noexcept { }\n\tconstexpr CTRE_FORCE_INLINE regex_results(not_matched_tag_t) noexcept { }\n\t\n\t\/\/ special constructor for deducting\n\tconstexpr CTRE_FORCE_INLINE regex_results(Iterator, ctll::list) noexcept { }\n\t\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n\t\treturn _captures.template select();\n\t}\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n\t\treturn _captures.template select();\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n#else\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n#endif\n\t\treturn _captures.template select();\n\t}\n\tstatic constexpr size_t count() noexcept {\n\t\treturn sizeof...(Captures) + 1;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & matched() noexcept {\n\t\t_captures.template select<0>().matched();\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & unmatch() noexcept {\n\t\t_captures.template select<0>().unmatch();\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE operator bool() const noexcept {\n\t\treturn bool(_captures.template select<0>());\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE operator std::basic_string_view() const noexcept {\n\t\treturn to_view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE explicit operator std::basic_string() const noexcept {\n\t\treturn to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto to_view() const noexcept {\n\t\treturn _captures.template select<0>().to_view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto to_string() const noexcept {\n\t\treturn _captures.template select<0>().to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto view() const noexcept {\n\t\treturn _captures.template select<0>().view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto str() const noexcept {\n\t\treturn _captures.template select<0>().to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE size_t size() const noexcept {\n\t\treturn _captures.template select<0>().size();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE const auto * data() const noexcept {\n\t\treturn _captures.template select<0>().data();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE regex_results & set_start_mark(Iterator pos) noexcept {\n\t\t_captures.template select<0>().set_start(pos);\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & set_end_mark(Iterator pos) noexcept {\n\t\t_captures.template select<0>().set_end(pos);\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE Iterator get_end_position() const noexcept {\n\t\treturn _captures.template select<0>().get_end();\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr regex_results & start_capture(Iterator pos) noexcept {\n\t\t_captures.template select().set_start(pos);\n\t\treturn *this;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr regex_results & end_capture(Iterator pos) noexcept {\n\t\t_captures.template select().set_end(pos).matched();\n\t\treturn *this;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator==(const regex_results & lhs, std::basic_string_view rhs) noexcept {\n\t\treturn lhs.view() == rhs;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(const regex_results & lhs, std::basic_string_view rhs) noexcept {\n\t\treturn lhs.view() != rhs;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator==(std::basic_string_view lhs, const regex_results & rhs) noexcept {\n\t\treturn lhs == rhs.view();\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(std::basic_string_view lhs, const regex_results & rhs) noexcept {\n\t\treturn lhs != rhs.view();\n\t}\n};\n\ntemplate regex_results(Iterator, ctll::list) -> regex_results;\n\n}\n\n\/\/ support for structured bindings\n\n#ifndef __EDG__\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wmismatched-tags\"\n#endif\n\nnamespace std {\n\ttemplate struct tuple_size> : public std::integral_constant::count()> { };\n\t\n\ttemplate struct tuple_element> {\n\tpublic:\n\t\tusing type = decltype(\n\t\t\tstd::declval &>().template get()\n\t\t);\n\t};\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif\n\n#endif\nconvinience comparison shouldn't have a UB in case if the capture is empty#ifndef CTRE__RETURN_TYPE__HPP\n#define CTRE__RETURN_TYPE__HPP\n\n#include \"id.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace ctre {\n\t\nstruct not_matched_tag_t { };\n\nstatic constexpr inline auto not_matched = not_matched_tag_t{};\n\t\ntemplate struct captured_content {\n\ttemplate class storage {\n\t\tIterator _begin{};\n\t\tIterator _end{};\n\t\t\n\t\tbool _matched{false};\n\tpublic:\n\t\tusing char_type = typename std::iterator_traits::value_type;\n\t\t\n\t\tusing name = Name;\n\t\n\t\tconstexpr CTRE_FORCE_INLINE storage() noexcept {}\n\t\n\t\tconstexpr CTRE_FORCE_INLINE void matched() noexcept {\n\t\t\t_matched = true;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE void unmatch() noexcept {\n\t\t\t_matched = false;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE void set_start(Iterator pos) noexcept {\n\t\t\t_begin = pos;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE storage & set_end(Iterator pos) noexcept {\n\t\t\t_end = pos;\n\t\t\treturn *this;\n\t\t}\n\t\tconstexpr CTRE_FORCE_INLINE Iterator get_end() const noexcept {\n\t\t\treturn _end;\n\t\t}\n\t\t\n\t\n\t\tconstexpr auto begin() const noexcept {\n\t\t\treturn _begin;\n\t\t}\n\t\tconstexpr auto end() const noexcept {\n\t\t\treturn _end;\n\t\t}\n\t\n\t\tconstexpr CTRE_FORCE_INLINE operator bool() const noexcept {\n\t\t\treturn _matched;\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE const auto * data() const noexcept {\n\t\t\treturn &*_begin;\n\t\t}\n\n\t\tconstexpr CTRE_FORCE_INLINE auto size() const noexcept {\n\t\t\treturn static_cast(std::distance(_begin, _end));\n\t\t}\n\n\t\tconstexpr CTRE_FORCE_INLINE auto to_view() const noexcept {\n\t\t\treturn std::basic_string_view(&*_begin, static_cast(std::distance(_begin, _end)));\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto to_string() const noexcept {\n\t\t\treturn std::basic_string(begin(), end());\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto view() const noexcept {\n\t\t\treturn std::basic_string_view(&*_begin, static_cast(std::distance(_begin, _end)));\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE auto str() const noexcept {\n\t\t\treturn std::basic_string(begin(), end());\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE operator std::basic_string_view() const noexcept {\n\t\t\treturn to_view();\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE explicit operator std::basic_string() const noexcept {\n\t\t\treturn to_string();\n\t\t}\n\t\t\n\t\tconstexpr CTRE_FORCE_INLINE static size_t get_id() noexcept {\n\t\t\treturn Id;\n\t\t}\n\t\t\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator==(const storage & lhs, std::basic_string_view rhs) noexcept {\n\t\t\treturn bool(lhs) ? lhs.view() == rhs : false;\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(const storage & lhs, std::basic_string_view rhs) noexcept {\n\t\t\treturn bool(lhs) ? lhs.view() != rhs : false;\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator==(std::basic_string_view lhs, const storage & rhs) noexcept {\n\t\t\treturn bool(rhs) ? lhs == rhs.view() : false;\n\t\t}\n\t\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(std::basic_string_view lhs, const storage & rhs) noexcept {\n\t\t\treturn bool(rhs) ? lhs != rhs.view() : false;\n\t\t}\n\t};\n};\n\nstruct capture_not_exists_tag { };\n\nstatic constexpr inline auto capture_not_exists = capture_not_exists_tag{};\n\ntemplate struct captures;\n\ntemplate struct captures: captures {\n\tHead head{};\n\tconstexpr CTRE_FORCE_INLINE captures() noexcept { }\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn captures::template exists();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn captures::template exists();\n\t\t}\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#endif\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn captures::template exists();\n\t\t} else {\n\t\t\tif constexpr (Head::name::name.is_same_as(Name)) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn captures::template exists();\n\t\t\t}\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\tif constexpr (id == Head::get_id()) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn head;\n\t\t} else {\n\t\t\treturn captures::template select();\n\t\t}\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#endif\n\t\tif constexpr (std::is_same_v) {\n\t\t\treturn captures::template select();\n\t\t} else {\n\t\t\tif constexpr (Head::name::name.is_same_as(Name)) {\n\t\t\t\treturn head;\n\t\t\t} else {\n\t\t\t\treturn captures::template select();\n\t\t\t}\n\t\t}\n\t}\n};\n\ntemplate <> struct captures<> {\n\tconstexpr CTRE_FORCE_INLINE captures() noexcept { }\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\treturn false;\n\t}\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n\t\treturn false;\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE static constexpr bool exists() noexcept {\n#endif\n\t\treturn false;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\treturn capture_not_exists;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n\t\treturn capture_not_exists;\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#else\n\ttemplate CTRE_FORCE_INLINE constexpr auto & select() const noexcept {\n#endif\n\t\treturn capture_not_exists;\n\t}\n};\n\ntemplate class regex_results {\n\tcaptures::template storage, typename Captures::template storage...> _captures{};\npublic:\n\tusing char_type = typename std::iterator_traits::value_type;\n\t\n\tconstexpr CTRE_FORCE_INLINE regex_results() noexcept { }\n\tconstexpr CTRE_FORCE_INLINE regex_results(not_matched_tag_t) noexcept { }\n\t\n\t\/\/ special constructor for deducting\n\tconstexpr CTRE_FORCE_INLINE regex_results(Iterator, ctll::list) noexcept { }\n\t\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n\t\treturn _captures.template select();\n\t}\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n\t\treturn _captures.template select();\n\t}\n#if (__cpp_nontype_template_parameter_class || (__cpp_nontype_template_args >= 201911L))\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n#else\n\ttemplate ()>> CTRE_FORCE_INLINE constexpr auto get() const noexcept {\n#endif\n\t\treturn _captures.template select();\n\t}\n\tstatic constexpr size_t count() noexcept {\n\t\treturn sizeof...(Captures) + 1;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & matched() noexcept {\n\t\t_captures.template select<0>().matched();\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & unmatch() noexcept {\n\t\t_captures.template select<0>().unmatch();\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE operator bool() const noexcept {\n\t\treturn bool(_captures.template select<0>());\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE operator std::basic_string_view() const noexcept {\n\t\treturn to_view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE explicit operator std::basic_string() const noexcept {\n\t\treturn to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto to_view() const noexcept {\n\t\treturn _captures.template select<0>().to_view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto to_string() const noexcept {\n\t\treturn _captures.template select<0>().to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto view() const noexcept {\n\t\treturn _captures.template select<0>().view();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE auto str() const noexcept {\n\t\treturn _captures.template select<0>().to_string();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE size_t size() const noexcept {\n\t\treturn _captures.template select<0>().size();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE const auto * data() const noexcept {\n\t\treturn _captures.template select<0>().data();\n\t}\n\t\n\tconstexpr CTRE_FORCE_INLINE regex_results & set_start_mark(Iterator pos) noexcept {\n\t\t_captures.template select<0>().set_start(pos);\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE regex_results & set_end_mark(Iterator pos) noexcept {\n\t\t_captures.template select<0>().set_end(pos);\n\t\treturn *this;\n\t}\n\tconstexpr CTRE_FORCE_INLINE Iterator get_end_position() const noexcept {\n\t\treturn _captures.template select<0>().get_end();\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr regex_results & start_capture(Iterator pos) noexcept {\n\t\t_captures.template select().set_start(pos);\n\t\treturn *this;\n\t}\n\ttemplate CTRE_FORCE_INLINE constexpr regex_results & end_capture(Iterator pos) noexcept {\n\t\t_captures.template select().set_end(pos).matched();\n\t\treturn *this;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator==(const regex_results & lhs, std::basic_string_view rhs) noexcept {\n\t\treturn bool(lhs) ? lhs.view() == rhs : false;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(const regex_results & lhs, std::basic_string_view rhs) noexcept {\n\t\treturn bool(lhs) ? lhs.view() != rhs : true;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator==(std::basic_string_view lhs, const regex_results & rhs) noexcept {\n\t\treturn bool(rhs) ? lhs == rhs.view() : false;\n\t}\n\tfriend CTRE_FORCE_INLINE constexpr bool operator!=(std::basic_string_view lhs, const regex_results & rhs) noexcept {\n\t\treturn bool(rhs) ? lhs != rhs.view() : true;\n\t}\n};\n\ntemplate regex_results(Iterator, ctll::list) -> regex_results;\n\n}\n\n\/\/ support for structured bindings\n\n#ifndef __EDG__\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wmismatched-tags\"\n#endif\n\nnamespace std {\n\ttemplate struct tuple_size> : public std::integral_constant::count()> { };\n\t\n\ttemplate struct tuple_element> {\n\tpublic:\n\t\tusing type = decltype(\n\t\t\tstd::declval &>().template get()\n\t\t);\n\t};\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n#endif\n\n#endif\n<|endoftext|>"} {"text":"#include \"servercontroller.hpp\"\n#include \"serversocket.hpp\"\n#include \n\nnamespace mirrors {\n\nconst std::string boardLocatingInstructions = \"Position the camera to view the entire board.\";\n\nServerController::ServerController(QObject *parent)\n : QObject(parent),\n sock(new ServerSocket(this)),\n trackerManager(nullptr),\n detectorTimer(new QTimer(this)),\n serverState(Idle),\n currentLevel(-1)\n{\n\n connect(this, SIGNAL(markersUpdated(vector)),\n this, SLOT(broadcastPositions(vector)));\n connect(sock, SIGNAL(errorOccurred(QString)),\n this, SIGNAL(socketError(QString)));\n connect(this, SIGNAL(markersUpdated(vector)),\n sock, SLOT(processUpdates()));\n connect(sock, SIGNAL(levelChanged(int)),\n this, SLOT(changeLevel(int)));\n\n \/\/ A single-shot Timer with an interval of 0 will\n \/\/ directly fire the timeout when control goes back\n \/\/ to the event thread. We use this structure to\n \/\/ allow signals events to be processed while\n \/\/ keeping the detector active as much as possible.\n detectorTimer->setInterval(0);\n detectorTimer->setSingleShot(true);\n}\n\nServerController::~ServerController() {\n if (trackerManager != nullptr) {\n delete trackerManager;\n }\n}\n\nvoid ServerController::changeState(ServerState state) {\n this->serverState = state;\n emit stateChanged(state);\n}\n\nvoid ServerController::fatalError(const QString &message) {\n stopServer();\n emit fatalErrorOccurred(message);\n}\n\nvoid ServerController::startServer(quint16 port, int cameraDevice, cv::Size camSize, BoardDetectionApproach::Type boardDetectionApproach) {\n Q_ASSERT(serverState == Idle);\n Q_ASSERT(trackerManager == nullptr); \/\/ Otherwise we get a memory leak.\n changeState(Starting);\n\n \/\/ (Re)Initialize tracking\n trackerManager = new TrackerManager(cameraDevice, camSize, boardDetectionApproach);\n trackerManager->loadPatterns(MARKER_DIRECTORY, MARKER_COUNT);\n\n sock->setPortNumber(port);\n sock->start();\n detectorTimer->start();\n\n \/\/ Start detecting board\n connect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n}\n\nvoid ServerController::stopServer() {\n Q_ASSERT(serverState == Started || serverState == Starting);\n changeState(Stopping);\n sock->stop();\n currentLevel = -1;\n}\n\nvoid ServerController::changeLevel(int nextLevel) {\n if (nextLevel != currentLevel) {\n cv::Size2f boardSize(trackerManager->scaledBoardSize());\n sock->broadcastLevelUpdate(nextLevel, boardSize);\n currentLevel = nextLevel;\n\n std::cout << boardSize.width << \", \" << boardSize.height << std::endl;\n emit levelChanged(nextLevel);\n }\n}\n\nvoid ServerController::detectBoard() {\n Q_ASSERT(trackerManager != nullptr);\n if (state() == Stopping) {\n delete trackerManager;\n trackerManager = nullptr;\n changeState(Idle);\n\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n\n return;\n }\n Q_ASSERT(serverState == Starting);\n\n QPixmap result;\n bool boardLocated = trackerManager->locateBoard(result, true);\n\n \/\/ Show image to user\n emit imageReady(result);\n\n if (boardLocated) {\n \/\/ When the board is found, we stop trying to locate\n \/\/ the board and start detecting markers instead.\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n connect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectFrame()));\n changeState(Started);\n }\n detectorTimer->start();\n}\n\nvoid ServerController::setDebugOverlay(bool enable) {\n showDebugOverlay = enable;\n}\n\nvoid ServerController::detectFrame() {\n \/\/ detectFrame should never be called when the server is not running.\n Q_ASSERT(serverState != Idle);\n Q_ASSERT(trackerManager != nullptr);\n if (state() == Starting) {\n changeState(Started);\n }\n\n if (state() == Started) {\n QPixmap result;\n vector markers = trackerManager->getMarkerUpdates(result, showDebugOverlay);\n\n emit markersUpdated(markers);\n emit imageReady(result);\n\n detectorTimer->start();\n\n emit fpsChanged(trackerManager->getUpdateRate());\n } else {\n changeState(Idle);\n delete trackerManager;\n trackerManager = nullptr;\n\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectFrame()));\n }\n}\n\nvoid ServerController::broadcastPositions(vector markers) {\n for(MarkerUpdate marker : markers) {\n broadcastPosition(marker);\n }\n}\n\nvoid ServerController::broadcastPosition(const MarkerUpdate& marker) {\n if (marker.type == MarkerUpdateType::REMOVE) {\n sock->broadcastDelete(marker.id);\n } else {\n \/\/ Scale marker positions based on their size for Meta 1 tracking\n sock->broadcastPositionUpdate(\n marker.id,\n trackerManager->scaledMarkerCoordinate(marker.position),\n marker.rotation);\n }\n}\n\n} \/\/ namespace mirrors\n\nAdd HTTP server for board image and fix TrackerManager bug #2#include \"servercontroller.hpp\"\n#include \"serversocket.hpp\"\n#include \n#include \n\nnamespace mirrors {\n\nconst std::string boardLocatingInstructions = \"Position the camera to view the entire board.\";\n\nServerController::ServerController(QObject *parent)\n : QObject(parent),\n sock(new ServerSocket(this)),\n trackerManager(nullptr),\n detectorTimer(new QTimer(this)),\n serverState(Idle),\n currentLevel(-1),\n server(new QHttpServer)\n{\n\n connect(this, SIGNAL(markersUpdated(vector)),\n this, SLOT(broadcastPositions(vector)));\n connect(sock, SIGNAL(errorOccurred(QString)),\n this, SIGNAL(socketError(QString)));\n connect(this, SIGNAL(markersUpdated(vector)),\n sock, SLOT(processUpdates()));\n connect(sock, SIGNAL(levelChanged(int)),\n this, SLOT(changeLevel(int)));\n connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),\n this, SLOT(sendBoard(QHttpRequest*, QHttpResponse*)));\n\n \/\/ A single-shot Timer with an interval of 0 will\n \/\/ directly fire the timeout when control goes back\n \/\/ to the event thread. We use this structure to\n \/\/ allow signals events to be processed while\n \/\/ keeping the detector active as much as possible.\n detectorTimer->setInterval(0);\n detectorTimer->setSingleShot(true);\n}\n\nvoid ServerController::sendBoard(QHttpRequest* req, QHttpResponse* resp) {\n resp->setHeader(\"Content-Type\", \"image\/jpeg\");\n resp->setHeader(\"Content-Length\", QString::number(boardImageBytes.size()));\n resp->writeHead(200);\n resp->write(boardImageBytes);\n\n resp->end();\n}\n\nServerController::~ServerController() {\n if (trackerManager != nullptr) {\n delete trackerManager;\n }\n}\n\nvoid ServerController::changeState(ServerState state) {\n this->serverState = state;\n emit stateChanged(state);\n}\n\nvoid ServerController::fatalError(const QString &message) {\n stopServer();\n emit fatalErrorOccurred(message);\n}\n\nvoid ServerController::startServer(quint16 port, int cameraDevice, cv::Size camSize, BoardDetectionApproach::Type boardDetectionApproach) {\n Q_ASSERT(serverState == Idle);\n Q_ASSERT(trackerManager == nullptr); \/\/ Otherwise we get a memory leak.\n changeState(Starting);\n\n \/\/ (Re)Initialize tracking\n trackerManager = new TrackerManager(cameraDevice, camSize, boardDetectionApproach);\n trackerManager->loadPatterns(MARKER_DIRECTORY, MARKER_COUNT);\n\n sock->setPortNumber(port);\n sock->start();\n detectorTimer->start();\n\n \/\/ Start detecting board\n connect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n\n \/\/ Start server that broadcasts board image\n server->listen(port + 1);\n}\n\nvoid ServerController::stopServer() {\n Q_ASSERT(serverState == Started || serverState == Starting);\n changeState(Stopping);\n sock->stop();\n currentLevel = -1;\n}\n\nvoid ServerController::changeLevel(int nextLevel) {\n if (nextLevel != currentLevel) {\n cv::Size2f boardSize(trackerManager->scaledBoardSize());\n sock->broadcastLevelUpdate(nextLevel, boardSize);\n currentLevel = nextLevel;\n\n std::cout << boardSize.width << \", \" << boardSize.height << std::endl;\n emit levelChanged(nextLevel);\n }\n}\n\nvoid ServerController::detectBoard() {\n Q_ASSERT(trackerManager != nullptr);\n if (state() == Stopping) {\n delete trackerManager;\n trackerManager = nullptr;\n changeState(Idle);\n\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n\n return;\n }\n Q_ASSERT(serverState == Starting);\n\n QPixmap result;\n bool boardLocated = trackerManager->locateBoard(result, true);\n\n \/\/ Show image to user\n emit imageReady(result);\n\n if (boardLocated) {\n \/\/ Save an image of the board without text overlay\n QPixmap board;\n trackerManager->getMarkerUpdates(board, false);\n\n boardImageBytes.clear();\n QBuffer buffer(&boardImageBytes);\n buffer.open(QIODevice::WriteOnly);\n board.save(&buffer, \"JPG\");\n\n \/\/ When the board is found, we stop trying to locate\n \/\/ the board and start detecting markers instead.\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectBoard()));\n connect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectFrame()));\n changeState(Started);\n }\n detectorTimer->start();\n}\n\nvoid ServerController::setDebugOverlay(bool enable) {\n showDebugOverlay = enable;\n}\n\nvoid ServerController::detectFrame() {\n \/\/ detectFrame should never be called when the server is not running.\n Q_ASSERT(serverState != Idle);\n Q_ASSERT(trackerManager != nullptr);\n if (state() == Starting) {\n changeState(Started);\n }\n\n if (state() == Started) {\n QPixmap result;\n vector markers = trackerManager->getMarkerUpdates(result, showDebugOverlay);\n\n emit markersUpdated(markers);\n emit imageReady(result);\n\n detectorTimer->start();\n\n emit fpsChanged(trackerManager->getUpdateRate());\n } else {\n changeState(Idle);\n delete trackerManager;\n trackerManager = nullptr;\n\n disconnect(detectorTimer, SIGNAL(timeout()),\n this, SLOT(detectFrame()));\n }\n}\n\nvoid ServerController::broadcastPositions(vector markers) {\n for(MarkerUpdate marker : markers) {\n broadcastPosition(marker);\n }\n}\n\nvoid ServerController::broadcastPosition(const MarkerUpdate& marker) {\n if (marker.type == MarkerUpdateType::REMOVE) {\n sock->broadcastDelete(marker.id);\n } else {\n \/\/ Scale marker positions based on their size for Meta 1 tracking\n sock->broadcastPositionUpdate(\n marker.id,\n trackerManager->scaledMarkerCoordinate(marker.position),\n marker.rotation);\n }\n}\n\n} \/\/ namespace mirrors\n\n<|endoftext|>"} {"text":"#pragma once\n\/**\n\t@file\n\t@brief frequency of elements in a sequence\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace cybozu {\n\nnamespace freq_local {\n\ntemplate\nunion ci {\n\tT i;\n\tchar c[sizeof(T)];\n};\n\ntemplate void load(T& t, std::istream& is) { t.load(is); }\ntemplate void save(std::ostream& os, const T& t) { t.save(os); }\n\ntemplate\nvoid load(T *t, size_t n, std::istream& is, const char *msg)\n{\n\tconst std::streamsize size = sizeof(T) * n;\n\tif (!is.read((char*)t, size) || is.gcount() != size) {\n\t\tthrow cybozu::Exception(\"Frequency:load\") << msg;\n\t}\n}\ntemplate\nvoid save(std::ostream& os, const T *t, size_t n, const char *msg)\n{\n\tif (!os.write((const char*)t, sizeof(T) * n)) {\n\t\tthrow cybozu::Exception(\"Frequency:save\") << msg;\n\t}\n}\n\n#define CYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(type) \\\ntemplate<>void load(type& t, std::istream& is) { load(&t, 1, is, #type); } \\\ntemplate<>void save(std::ostream& os, const type& t) { save(os, &t, 1, #type); }\n\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(char)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(unsigned char)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(int)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(unsigned int)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(long)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(unsigned long)\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(wchar_t)\n#ifdef _MSC_VER\nCYBOZU_FREQUENCY_DEFINE_LOAD_SAVE(size_t)\n#endif\n\n#undef CYBOZU_FREQUENCY_DEFINE_LOAD_SAVE\n\ntemplate<>\nvoid load(std::string& t, std::istream& is)\n{\n\tsize_t size;\n\tload(size, is);\n\tt.resize(size);\n\tload(&t[0], size, is, \"string\");\n}\n\ntemplate<>\nvoid save(std::ostream& os, const std::string& t)\n{\n\tsave(os, t.size());\n\tsave(os, &t[0], t.size(), \"string\");\n}\n\ntemplate\nclass FrequencyVec {\n\tstatic const size_t N = size_t(1) << (sizeof(Element) * 8);\n\tsize_t size_;\n\tInt freqTbl_[N];\n\tuint8_t char2idx_[N];\n\tuint8_t idx2char_[N];\n\tstruct Greater {\n\t\tconst Int *p_;\n\t\texplicit Greater(const Int *p) : p_(p) {}\n\t\tbool operator()(uint8_t lhs, uint8_t rhs) const\n\t\t{\n\t\t\tInt a = p_[lhs];\n\t\t\tInt b = p_[rhs];\n\t\t\tif (a > b) return true;\n\t\t\tif (a < b) return false;\n\t\t\treturn a > b;\n\t\t}\n\t};\npublic:\n\ttypedef Element value_type;\n\ttypedef Int size_type;\n\n\tFrequencyVec() { clear(); }\n\ttemplate\n\tFrequencyVec(Iter begin, Iter end)\n\t{\n\t\tclear();\n\t\tinit(begin, end);\n\t}\n\tvoid clear()\n\t{\n\t\tsize_ = 0;\n\t\tmemset(freqTbl_, 0, sizeof(freqTbl_));\n\t}\n\ttemplate\n\tvoid init(Iter begin, Iter end)\n\t{\n\t\twhile (begin != end) {\n\t\t\tappend(*begin);\n\t\t\t++begin;\n\t\t}\n\t\tready();\n\t}\n\tvoid append(const Element e)\n\t{\n\t\tfreqTbl_[uint8_t(e)]++;\n\t}\n\tvoid ready()\n\t{\n\t\tfor (size_t i = 0; i < N; i++) idx2char_[i] = uint8_t(i);\n\t\tGreater greater(freqTbl_);\n\t\tstd::sort(idx2char_, idx2char_ + N, greater);\n\t\tsize_ = 0;\n\t\tfor (size_t i = 0; i < N; i++) {\n\t\t\tuint8_t c = idx2char_[i];\n\t\t\tchar2idx_[c] = (uint8_t)i;\n\t\t\tif (freqTbl_[c]) size_++;\n\t\t}\n\t}\n\t\/*\n\t\telement -> freq\n\t*\/\n\tInt getFrequency(Element e) const { return freqTbl_[uint8_t(e)]; }\n\t\/*\n\t\telement -> idx\n\t*\/\n\tInt getIndex(Element e) const { return char2idx_[uint8_t(e)]; }\n\t\/*\n\t\tidx -> element\n\t*\/\n\tElement getElement(size_t idx) const\n\t{\n\/\/\t\tif (idx >= N) throw cybozu::Exception(\"Frequency:getElement:bad idx\") << idx;\n\t\tassert(idx < N);\n\t\treturn Element(idx2char_[idx]);\n\t}\n\tsize_t size() const { return size_; }\n\tvoid load(std::istream& is)\n\t{\n\t\tfreq_local::load(&size_, 1u, is, \"size\");\n\t\tfreq_local::load(freqTbl_, N, is, \"freqTbl\");\n\t\tfreq_local::load(char2idx_, N, is, \"char2idx\");\n\t\tfreq_local::load(idx2char_, N, is, \"idx2char\");\n\t}\n\tvoid save(std::ostream& os) const\n\t{\n\t\tfreq_local::save(os, &size_, 1, \"size\");\n\t\tfreq_local::save(os, freqTbl_, N, \"freqTbl\");\n\t\tfreq_local::save(os, char2idx_, N, \"char2idx\");\n\t\tfreq_local::save(os, idx2char_, N, \"idx2char\");\n\t}\n\tvoid put() const\n\t{\n\t\tfor (size_t i = 0; i < size_; i++) {\n\t\t\tuint8_t c = idx2char_[i];\n\t\t\tprintf(\"%d %d %d\\n\", (int)i, c, freqTbl_[c]);\n\t\t}\n\t}\n};\n\n} \/\/ cybozu::freq_local\n\n\/*\n\tcount Element\n\tElement : type of element\n\tInt : type of counter\n*\/\ntemplate\nclass Frequency {\n\tstruct FreqIdx {\n\t\tInt freq;\n\t\tmutable Int idx;\n\t\tvoid load(std::istream& is)\n\t\t{\n\t\t\tfreq_local::load(freq, is);\n\t\t\tfreq_local::load(idx, is);\n\t\t}\n\t\tvoid save(std::ostream& os) const\n\t\t{\n\t\t\tfreq_local::save(os, freq);\n\t\t\tfreq_local::save(os, idx);\n\t\t}\n\t};\n\ttypedef CYBOZU_NAMESPACE_STD::unordered_map Map;\n\ttypedef Element value_type;\n\ttypedef Int size_type;\n\ttypedef std::vector Idx2Ref;\n\tstatic inline bool greater(typename Map::const_iterator i, typename Map::const_iterator j)\n\t{\n\t\tconst Int a = i->second.freq;\n\t\tconst Int b = j->second.freq;\n\t\tif (a > b) return true;\n\t\tif (a < b) return false;\n\t\treturn i->first > j->first;\n\t}\n\tMap m_;\n\tIdx2Ref idx2ref_;\n\tvoid initIdx2Ref()\n\t{\n\t\tidx2ref_.resize(m_.size());\n\t\tsize_t pos = 0;\n\t\tfor (typename Map::const_iterator i = m_.begin(), ie = m_.end(); i != ie; ++i) {\n\t\t\tidx2ref_[pos++] = i;\n\t\t}\n\t\tstd::sort(idx2ref_.begin(), idx2ref_.end(), greater);\n\t}\npublic:\n\tFrequency(){ clear(); }\n\ttemplate\n\tFrequency(Iter begin, Iter end)\n\t{\n\t\tclear();\n\t\tinit(begin, end);\n\t}\n\tvoid clear()\n\t{\n\t\tm_.clear();\n\t\tidx2ref_.clear();\n\t}\n\ttemplate\n\tvoid init(Iter begin, Iter end)\n\t{\n\t\twhile (begin != end) {\n\t\t\tappend(*begin);\n\t\t\t++begin;\n\t\t}\n\t\tready();\n\t}\n\tvoid append(const Element& e)\n\t{\n\t\tm_[e].freq++;\n\t}\n\tvoid ready()\n\t{\n\t\tinitIdx2Ref();\n\t\tfor (size_t i = 0, ie = idx2ref_.size(); i < ie; i++) {\n\t\t\tidx2ref_[i]->second.idx = (Int)i;\n\t\t}\n\t}\n\t\/*\n\t\telement -> freq\n\t*\/\n\tInt getFrequency(const Element& e) const\n\t{\n\t\ttypename Map::const_iterator i = m_.find(e);\n\t\treturn (i != m_.end()) ? i->second.freq : 0;\n\t}\n\t\/*\n\t\telement -> idx\n\t*\/\n\tInt getIndex(const Element& e) const\n\t{\n\t\ttypename Map::const_iterator i = m_.find(e);\n\t\tif (i == m_.end()) throw cybozu::Exception(\"Frequency:getIndex:not found\") << e;\n\t\treturn i->second.idx;\n\t}\n\t\/*\n\t\tidx -> element\n\t*\/\n\tconst Element& getElement(size_t idx) const\n\t{\n\t\tif (idx >= idx2ref_.size()) throw cybozu::Exception(\"Frequency:getElement:bad idx\") << idx;\n\t\treturn idx2ref_[idx]->first;\n\t}\n\tsize_t size() const { return idx2ref_.size(); }\n\tvoid load(std::istream& is)\n\t{\n\t\tsize_t size;\n\t\tfreq_local::load(size, is);\n\t\tfor (size_t i = 0; i < size; i++) {\n\t\t\ttypename Map::key_type k;\n\t\t\tfreq_local::load(k, is);\n\t\t\tFreqIdx freqIdx;\n\t\t\tfreq_local::load(freqIdx, is);\n\t\t\tm_.insert(typename Map::value_type(k, freqIdx));\n\t\t}\n\t\tinitIdx2Ref();\n\t}\n\tvoid save(std::ostream& os) const\n\t{\n\t\tfreq_local::save(os, m_.size());\n\t\tfor (typename Map::const_iterator i = m_.begin(), ie = m_.end(); i != ie; ++i) {\n\t\t\tfreq_local::save(os, i->first);\n\t\t\tfreq_local::save(os, i->second);\n\t\t}\n\t}\n\tvoid put() const\n\t{\n\t\tfor (size_t i = 0, n = idx2ref_.size(); i < n; i++) {\n\t\t\ttypename Map::const_iterator j = idx2ref_[i];\n\t\t\tstd::cout << i << ' ' << j->first << ' ' << j->second.freq << std::endl;\n\t\t}\n\t}\n};\n\ntemplate\nstruct Frequency : freq_local::FrequencyVec {\n\tFrequency() {}\n\ttemplate\n\tFrequency(Iterator begin, Iterator end) : freq_local::FrequencyVec(begin, end) {}\n};\ntemplate\nstruct Frequency : freq_local::FrequencyVec {\n\tFrequency() {}\n\ttemplate\n\tFrequency(Iterator begin, Iterator end) : freq_local::FrequencyVec(begin, end) {}\n};\n\n} \/\/ cybozu\nFrequency use cybozu::stream#pragma once\n\/**\n\t@file\n\t@brief frequency of elements in a sequence\n\t@author MITSUNARI Shigeo(@herumi)\n\t@license modified new BSD license\n\thttp:\/\/opensource.org\/licenses\/BSD-3-Clause\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace cybozu {\n\nnamespace freq_local {\n\ntemplate\nclass FrequencyVec {\n\tstatic const size_t N = size_t(1) << (sizeof(Element) * 8);\n\tsize_t size_;\n\tInt freqTbl_[N];\n\tuint8_t char2idx_[N];\n\tuint8_t idx2char_[N];\n\tstruct Greater {\n\t\tconst Int *p_;\n\t\texplicit Greater(const Int *p) : p_(p) {}\n\t\tbool operator()(uint8_t lhs, uint8_t rhs) const\n\t\t{\n\t\t\tInt a = p_[lhs];\n\t\t\tInt b = p_[rhs];\n\t\t\tif (a > b) return true;\n\t\t\tif (a < b) return false;\n\t\t\treturn a > b;\n\t\t}\n\t};\npublic:\n\ttypedef Element value_type;\n\ttypedef Int size_type;\n\n\tFrequencyVec() { clear(); }\n\ttemplate\n\tFrequencyVec(Iter begin, Iter end)\n\t{\n\t\tclear();\n\t\tinit(begin, end);\n\t}\n\tvoid clear()\n\t{\n\t\tsize_ = 0;\n\t\tmemset(freqTbl_, 0, sizeof(freqTbl_));\n\t}\n\ttemplate\n\tvoid init(Iter begin, Iter end)\n\t{\n\t\twhile (begin != end) {\n\t\t\tappend(*begin);\n\t\t\t++begin;\n\t\t}\n\t\tready();\n\t}\n\tvoid append(const Element e)\n\t{\n\t\tfreqTbl_[uint8_t(e)]++;\n\t}\n\tvoid ready()\n\t{\n\t\tfor (size_t i = 0; i < N; i++) idx2char_[i] = uint8_t(i);\n\t\tGreater greater(freqTbl_);\n\t\tstd::sort(idx2char_, idx2char_ + N, greater);\n\t\tsize_ = 0;\n\t\tfor (size_t i = 0; i < N; i++) {\n\t\t\tuint8_t c = idx2char_[i];\n\t\t\tchar2idx_[c] = (uint8_t)i;\n\t\t\tif (freqTbl_[c]) size_++;\n\t\t}\n\t}\n\t\/*\n\t\telement -> freq\n\t*\/\n\tInt getFrequency(Element e) const { return freqTbl_[uint8_t(e)]; }\n\t\/*\n\t\telement -> idx\n\t*\/\n\tInt getIndex(Element e) const { return char2idx_[uint8_t(e)]; }\n\t\/*\n\t\tidx -> element\n\t*\/\n\tElement getElement(size_t idx) const\n\t{\n\/\/\t\tif (idx >= N) throw cybozu::Exception(\"Frequency:getElement:bad idx\") << idx;\n\t\tassert(idx < N);\n\t\treturn Element(idx2char_[idx]);\n\t}\n\tsize_t size() const { return size_; }\n\ttemplate\n\tvoid load(InputStream& is)\n\t{\n\t\tcybozu::load(size_, is);\n\t\tcybozu::loadRange(freqTbl_, N, is);\n\t\tcybozu::loadRange(char2idx_, N, is);\n\t\tcybozu::loadRange(idx2char_, N, is);\n\t}\n\tvoid save(std::ostream& os) const\n\t{\n\t\tcybozu::save(os, size_);\n\t\tcybozu::saveRange(os, freqTbl_, N);\n\t\tcybozu::saveRange(os, char2idx_, N);\n\t\tcybozu::saveRange(os, idx2char_, N);\n\t}\n\tvoid put() const\n\t{\n\t\tfor (size_t i = 0; i < size_; i++) {\n\t\t\tuint8_t c = idx2char_[i];\n\t\t\tprintf(\"%d %d %d\\n\", (int)i, c, freqTbl_[c]);\n\t\t}\n\t}\n};\n\n} \/\/ cybozu::freq_local\n\n\/*\n\tcount Element\n\tElement : type of element\n\tInt : type of counter\n*\/\ntemplate\nclass Frequency {\n\tstruct FreqIdx {\n\t\tInt freq;\n\t\tmutable Int idx;\n\t\ttemplate\n\t\tvoid load(InputStream& is)\n\t\t{\n\t\t\tcybozu::load(freq, is);\n\t\t\tcybozu::load(idx, is);\n\t\t}\n\t\ttemplate\n\t\tvoid save(OutputStream& os) const\n\t\t{\n\t\t\tcybozu::save(os, freq);\n\t\t\tcybozu::save(os, idx);\n\t\t}\n\t};\n\ttypedef CYBOZU_NAMESPACE_STD::unordered_map Map;\n\ttypedef Element value_type;\n\ttypedef Int size_type;\n\ttypedef std::vector Idx2Ref;\n\tstatic inline bool greater(typename Map::const_iterator i, typename Map::const_iterator j)\n\t{\n\t\tconst Int a = i->second.freq;\n\t\tconst Int b = j->second.freq;\n\t\tif (a > b) return true;\n\t\tif (a < b) return false;\n\t\treturn i->first > j->first;\n\t}\n\tMap m_;\n\tIdx2Ref idx2ref_;\n\tvoid initIdx2Ref()\n\t{\n\t\tidx2ref_.resize(m_.size());\n\t\tsize_t pos = 0;\n\t\tfor (typename Map::const_iterator i = m_.begin(), ie = m_.end(); i != ie; ++i) {\n\t\t\tidx2ref_[pos++] = i;\n\t\t}\n\t\tstd::sort(idx2ref_.begin(), idx2ref_.end(), greater);\n\t}\npublic:\n\tFrequency(){ clear(); }\n\ttemplate\n\tFrequency(Iter begin, Iter end)\n\t{\n\t\tclear();\n\t\tinit(begin, end);\n\t}\n\tvoid clear()\n\t{\n\t\tm_.clear();\n\t\tidx2ref_.clear();\n\t}\n\ttemplate\n\tvoid init(Iter begin, Iter end)\n\t{\n\t\twhile (begin != end) {\n\t\t\tappend(*begin);\n\t\t\t++begin;\n\t\t}\n\t\tready();\n\t}\n\tvoid append(const Element& e)\n\t{\n\t\tm_[e].freq++;\n\t}\n\tvoid ready()\n\t{\n\t\tinitIdx2Ref();\n\t\tfor (size_t i = 0, ie = idx2ref_.size(); i < ie; i++) {\n\t\t\tidx2ref_[i]->second.idx = (Int)i;\n\t\t}\n\t}\n\t\/*\n\t\telement -> freq\n\t*\/\n\tInt getFrequency(const Element& e) const\n\t{\n\t\ttypename Map::const_iterator i = m_.find(e);\n\t\treturn (i != m_.end()) ? i->second.freq : 0;\n\t}\n\t\/*\n\t\telement -> idx\n\t*\/\n\tInt getIndex(const Element& e) const\n\t{\n\t\ttypename Map::const_iterator i = m_.find(e);\n\t\tif (i == m_.end()) throw cybozu::Exception(\"Frequency:getIndex:not found\") << e;\n\t\treturn i->second.idx;\n\t}\n\t\/*\n\t\tidx -> element\n\t*\/\n\tconst Element& getElement(size_t idx) const\n\t{\n\t\tif (idx >= idx2ref_.size()) throw cybozu::Exception(\"Frequency:getElement:bad idx\") << idx;\n\t\treturn idx2ref_[idx]->first;\n\t}\n\tsize_t size() const { return idx2ref_.size(); }\n\ttemplate\n\tvoid load(InputStream& is)\n\t{\n\t\tcybozu::load(m_, is);\n\t\tinitIdx2Ref();\n\t}\n\ttemplate\n\tvoid save(OutputStream& os) const\n\t{\n\t\tcybozu::save(os, m_);\n\t}\n\tvoid put() const\n\t{\n\t\tfor (size_t i = 0, n = idx2ref_.size(); i < n; i++) {\n\t\t\ttypename Map::const_iterator j = idx2ref_[i];\n\t\t\tstd::cout << i << ' ' << j->first << ' ' << j->second.freq << std::endl;\n\t\t}\n\t}\n};\n\ntemplate\nstruct Frequency : freq_local::FrequencyVec {\n\tFrequency() {}\n\ttemplate\n\tFrequency(Iterator begin, Iterator end) : freq_local::FrequencyVec(begin, end) {}\n};\ntemplate\nstruct Frequency : freq_local::FrequencyVec {\n\tFrequency() {}\n\ttemplate\n\tFrequency(Iterator begin, Iterator end) : freq_local::FrequencyVec(begin, end) {}\n};\n\n} \/\/ cybozu\n<|endoftext|>"} {"text":"\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \"tensorflow\/cc\/framework\/grad_op_registry.h\"\n#include \"tensorflow\/cc\/framework\/gradients.h\"\n#include \"tensorflow\/cc\/ops\/image_ops_internal.h\"\n#include \"tensorflow\/cc\/ops\/standard_ops.h\"\n\nnamespace tensorflow {\nnamespace ops {\nnamespace {\n\nStatus ResizeNearestNeighborGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n \/\/ The internal gradient implementation needs the shape of the input image.\n \/\/ x_shape = shape(x)[1:3]\n \/\/ = slice(shape(x), {1}, {3 - 1})\n auto x_shape = Slice(scope, Shape(scope, op.input(0)), {1}, {2});\n grad_outputs->push_back(internal::ResizeNearestNeighborGrad(\n scope, grad_inputs[0], x_shape,\n internal::ResizeNearestNeighborGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeNearestNeighbor\", ResizeNearestNeighborGradHelper);\n\nStatus ResizeBilinearGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n grad_outputs->push_back(internal::ResizeBilinearGrad(\n scope, grad_inputs[0], op.input(0),\n internal::ResizeBilinearGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeBilinear\", ResizeBilinearGradHelper);\n\nStatus ResizeBicubicGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n\n grad_outputs->push_back(internal::ResizeBicubicGrad(\n scope, grad_inputs[0], op.input(0),\n internal::ResizeBicubicGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeBicubic\", ResizeBicubicGradHelper);\n\nStatus ScaleAndTranslateGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n string kernel_type;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"kernel_type\", &kernel_type));\n bool antialias;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"antialias\", &antialias));\n grad_outputs->push_back(internal::ScaleAndTranslateGrad(\n scope, grad_inputs[0], op.input(0), op.input(2), op.input(3),\n internal::ScaleAndTranslateGrad::KernelType(kernel_type)\n .Antialias(antialias)));\n\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\n\nREGISTER_GRADIENT_OP(\"ScaleAndTranslate\", ScaleAndTranslateGradHelper);\n\nStatus CropAndResizeGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n DataType input_type;\n string method;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"method\", &method));\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"T\", &input_type));\n auto image_shape = Shape(scope, op.input(0));\n grad_outputs->push_back(CropAndResizeGradImage(\n scope, grad_inputs[0], op.input(1), op.input(2), image_shape, input_type,\n CropAndResizeGradImage::Method(method)));\n grad_outputs->push_back(CropAndResizeGradBoxes(\n scope, grad_inputs[0], op.input(0), op.input(1), op.input(2)));\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\n\nREGISTER_GRADIENT_OP(\"CropAndResize\", CropAndResizeGradHelper);\n} \/\/ anonymous namespace\n} \/\/ namespace ops\n} \/\/ namespace tensorflow\nMark NonMaxSuppression ops non differentiable in C++\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \"tensorflow\/cc\/framework\/grad_op_registry.h\"\n#include \"tensorflow\/cc\/framework\/gradients.h\"\n#include \"tensorflow\/cc\/ops\/image_ops_internal.h\"\n#include \"tensorflow\/cc\/ops\/standard_ops.h\"\n\nnamespace tensorflow {\nnamespace ops {\nnamespace {\n\nREGISTER_NO_GRADIENT_OP(\"NonMaxSuppression\");\nREGISTER_NO_GRADIENT_OP(\"NonMaxSuppressionV2\");\nREGISTER_NO_GRADIENT_OP(\"NonMaxSuppressionV3\");\nREGISTER_NO_GRADIENT_OP(\"NonMaxSuppressionV4\");\nREGISTER_NO_GRADIENT_OP(\"NonMaxSuppressionV5\");\n\nStatus ResizeNearestNeighborGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n \/\/ The internal gradient implementation needs the shape of the input image.\n \/\/ x_shape = shape(x)[1:3]\n \/\/ = slice(shape(x), {1}, {3 - 1})\n auto x_shape = Slice(scope, Shape(scope, op.input(0)), {1}, {2});\n grad_outputs->push_back(internal::ResizeNearestNeighborGrad(\n scope, grad_inputs[0], x_shape,\n internal::ResizeNearestNeighborGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeNearestNeighbor\", ResizeNearestNeighborGradHelper);\n\nStatus ResizeBilinearGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n grad_outputs->push_back(internal::ResizeBilinearGrad(\n scope, grad_inputs[0], op.input(0),\n internal::ResizeBilinearGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeBilinear\", ResizeBilinearGradHelper);\n\nStatus ResizeBicubicGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n bool align_corners;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"align_corners\", &align_corners));\n bool half_pixel_centers;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"half_pixel_centers\",\n &half_pixel_centers));\n\n grad_outputs->push_back(internal::ResizeBicubicGrad(\n scope, grad_inputs[0], op.input(0),\n internal::ResizeBicubicGrad::AlignCorners(align_corners)\n .HalfPixelCenters(half_pixel_centers)));\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\nREGISTER_GRADIENT_OP(\"ResizeBicubic\", ResizeBicubicGradHelper);\n\nStatus ScaleAndTranslateGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n string kernel_type;\n TF_RETURN_IF_ERROR(\n GetNodeAttr(op.node()->attrs(), \"kernel_type\", &kernel_type));\n bool antialias;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"antialias\", &antialias));\n grad_outputs->push_back(internal::ScaleAndTranslateGrad(\n scope, grad_inputs[0], op.input(0), op.input(2), op.input(3),\n internal::ScaleAndTranslateGrad::KernelType(kernel_type)\n .Antialias(antialias)));\n\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\n\nREGISTER_GRADIENT_OP(\"ScaleAndTranslate\", ScaleAndTranslateGradHelper);\n\nStatus CropAndResizeGradHelper(const Scope& scope, const Operation& op,\n const std::vector& grad_inputs,\n std::vector* grad_outputs) {\n DataType input_type;\n string method;\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"method\", &method));\n TF_RETURN_IF_ERROR(GetNodeAttr(op.node()->attrs(), \"T\", &input_type));\n auto image_shape = Shape(scope, op.input(0));\n grad_outputs->push_back(CropAndResizeGradImage(\n scope, grad_inputs[0], op.input(1), op.input(2), image_shape, input_type,\n CropAndResizeGradImage::Method(method)));\n grad_outputs->push_back(CropAndResizeGradBoxes(\n scope, grad_inputs[0], op.input(0), op.input(1), op.input(2)));\n grad_outputs->push_back(NoGradient());\n grad_outputs->push_back(NoGradient());\n return scope.status();\n}\n\nREGISTER_GRADIENT_OP(\"CropAndResize\", CropAndResizeGradHelper);\n} \/\/ anonymous namespace\n} \/\/ namespace ops\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_EXCEPTION_HPP\n#define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_EXCEPTION_HPP\n\n\/** @file\n*\n* @brief Exception Base Class.\n* @author Andreas Weis (der_ghulbus@ghulbus-inc.de)\n*\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace GHULBUS_BASE_NAMESPACE\n{\n \/** Decorator type.\n * An exception type derived from `Exception` may have an arbitrary number of decorator types attached to it\n * using `operator<<`. The data attached this way may then be retrieved from the exception object by\n * calling `getErrorInfo()`.\n *\/\n template\n class GHULBUS_BASE_API ErrorInfo {\n public:\n using ValueType = T;\n using TagType = Tag_T;\n private:\n T m_data;\n public:\n template\n ErrorInfo(Args&&... args)\n :m_data(std::forward(args)...)\n {}\n\n T const& getData() const & {\n return m_data;\n }\n\n T&& getData() && {\n return std::move(m_data);\n }\n };\n\n \/** Trait for detecting instantiations of `ErrorInfo`.\n *\/\n template\n struct IsErrorInfo : public std::false_type {};\n template\n struct IsErrorInfo> : public std::true_type {};\n\n namespace impl {\n \/** @cond\n *\/\n \/** Helper functor for converting arbitrary types to string for printing.\n * - if `T` is std::string acts as the identity function\n * - if `T` has an overload of `to_string` found through an unqualified call, uses `to_string`\n * - if `T` has an ostream inserter defined, uses `operator<<` to insert to a `std::stringstream`\n * - otherwise use `typeid(T).name()`.\n *\/\n template\n struct toStringHelper;\n\n using std::to_string;\n\n template\n struct hasToString : public std::false_type {};\n template\n struct hasToString()))>> : public std::true_type {};\n\n template\n struct hasOstreamInserter : public std::false_type {};\n template\n struct hasOstreamInserter() << std::declval())>> : public std::true_type {};\n\n template<>\n struct toStringHelper {\n std::string const& operator()(std::string const& s) {\n return s;\n }\n };\n\n template\n struct toStringHelper && hasToString::value>> {\n std::string operator()(T const& v) {\n return to_string(v);\n }\n };\n\n template\n struct toStringHelper &&\n !hasToString::value &&\n hasOstreamInserter::value>>\n {\n std::string operator()(T const& v) {\n std::stringstream sstr;\n sstr << v;\n return std::move(sstr.str());\n }\n };\n\n template\n struct toStringHelper &&\n !hasToString::value &&\n !hasOstreamInserter::value>>\n {\n std::string operator()(T const& v) {\n return typeid(T).name();\n }\n };\n \/** @endcond\n *\/\n }\n\n \/** Base class for all Ghulbus exceptions.\n * Any exception can be decorated with additional info. Instantiate an Info object from the\n * Exception_Info namespace and use `operator<<` to assign it to an exception.\n * All exceptions thrown through \\ref GHULBUS_THROW are decorated with Exception_Info::description and a\n * decorator for the location of the throw site of the exception, see `Exception_Info::Records::location`.\n * Individual decorators can be retrieved from an exception object with `getErrorInfo()`.\n * To obtain a textual representation of all the information for an exception,\n * use `getDiagnosticMessage`.\n *\n *\/\n class GHULBUS_BASE_API Exception : public virtual std::exception {\n private:\n \/** Type-erased storage for ErrorInfo (base class).\n *\/\n class ErrorInfoConcept {\n private:\n std::unique_ptr m_next;\n public:\n ErrorInfoConcept() = default;\n\n explicit ErrorInfoConcept(std::unique_ptr&& next)\n :m_next(std::move(next))\n {}\n\n virtual ~ErrorInfoConcept() noexcept = default;\n virtual std::unique_ptr clone() const = 0;\n virtual std::type_info const& getTypeInfo() const = 0;\n virtual std::string dataString() const = 0;\n\n ErrorInfoConcept const* next() const {\n return m_next.get();\n }\n\n ErrorInfoConcept* next() {\n return m_next.get();\n }\n };\n\n \/** Type-erased storage for ErrorInfo.\n *\/\n template\n class ErrorInfoModel : public ErrorInfoConcept {\n public:\n static_assert(IsErrorInfo::value,\n \"Only ErrorInfo types can be used to decorate Exception.\");\n using ValueType = typename ErrorInfo_T::ValueType;\n using TagType = typename ErrorInfo_T::TagType;\n private:\n ValueType m_data;\n public:\n ErrorInfoModel(std::unique_ptr&& next, ErrorInfo_T data)\n :ErrorInfoConcept(std::move(next)), m_data(std::move(data).getData())\n {}\n\n ~ErrorInfoModel() noexcept override = default;\n\n std::unique_ptr clone() const override {\n ErrorInfoConcept const* next_ei = next();\n return std::make_unique((next_ei == nullptr) ? nullptr : next_ei->clone(), m_data);\n }\n\n std::type_info const& getTypeInfo() const override {\n return typeid(TagType);\n }\n\n ValueType const& data() const {\n return m_data;\n }\n\n std::string dataString() const override {\n return impl::toStringHelper{}(data());\n }\n };\n\n std::unique_ptr mutable m_errorInfos;\n mutable char const* m_throwFile = nullptr;\n mutable char const* m_throwFunction = nullptr;\n mutable long m_throwLine = -1;\n mutable std::string m_message;\n protected:\n Exception() = default;\n virtual ~Exception() = default;\n\n Exception(Exception&&) noexcept = default;\n Exception& operator=(Exception&&) noexcept = default;\n\n Exception(Exception const& rhs)\n :m_errorInfos(rhs.m_errorInfos->clone()),\n m_throwFile(rhs.m_throwFile), m_throwFunction(rhs.m_throwFunction), m_throwLine(rhs.m_throwLine)\n {}\n\n Exception& operator=(Exception const& rhs) {\n if (&rhs != this) {\n m_errorInfos = rhs.m_errorInfos->clone();\n m_throwFile = rhs.m_throwFile;\n m_throwFunction = rhs.m_throwFunction;\n m_throwLine = rhs.m_throwLine;\n }\n return *this;\n }\n\n public:\n \/** Redeclare std::exception::what() as pure virtual.\n * We do this here so that Exception becomes abstract and to force inheriting classes to give\n * the noexcept guarantee.\n *\/\n virtual char const* what() const noexcept = 0;\n\n template\n std::enable_if_t>::value, void>\n addErrorInfo(ErrorInfo_T&& error_info) const {\n m_errorInfos = std::make_unique<\n ErrorInfoModel>>(std::move(m_errorInfos),\n std::forward(error_info));\n }\n\n void setExceptionLocation(char const* throw_file, char const* throw_function, long throw_line) const {\n m_throwFile = throw_file;\n m_throwFunction = throw_function;\n m_throwLine = throw_line;\n }\n\n template\n typename ErrorInfo_T::ValueType const* getErrorInfo() const {\n using TagType = typename ErrorInfo_T::TagType;\n for (ErrorInfoConcept const* it = m_errorInfos.get(); it != nullptr; it = it->next()) {\n if (it->getTypeInfo() == typeid(TagType)) {\n return &dynamic_cast const&>(*it).data();\n }\n }\n return nullptr;\n }\n\n char const* getDiagnosticMessage() const {\n \/*\n (): Throw in function \n Dynamic exception type: bla\n [] = \n ...\n [] = \n *\/\n m_message =\n std::string((m_throwFile) ? m_throwFile : \"\") +\n '(' + std::to_string(m_throwLine) + \"): Throw in function \" +\n (m_throwFunction ? m_throwFunction : \"\") +\n \"\\nDynamic exception type: \" + typeid(*this).name();\n for (ErrorInfoConcept const* it = m_errorInfos.get(); it != nullptr; it = it->next()) {\n m_message += std::string(\"\\n[\") + it->getTypeInfo().name() + \"] = \" + it->dataString();\n }\n return m_message.c_str();\n }\n };\n\n\n \/** Exception decorators.\n * Place all exception decorators in this namespace.\n * A decorator is an instance of the boost::error_info template with a unique (empty) tag type and a record type\n * that provides storage for the information.\n * For non-trivial record-types, provide a std::ostream inserter to allow for nice automatic error messages.\n *\/\n namespace Exception_Info {\n \/** Decorator Tags.\n * Tags are empty types used to uniquely identify a decoratory type.\n *\/\n namespace Tags\n {\n struct GHULBUS_BASE_API location { };\n struct GHULBUS_BASE_API description { };\n struct GHULBUS_BASE_API filename { };\n }\n \/** Decorator record types.\n *\/\n namespace Records\n {\n struct location {\n char const* file;\n char const* function;\n long line;\n\n location(char const* nfile, char const* nfunc, long nline)\n :file(nfile), function(nfunc), line(nline)\n {}\n };\n }\n\n \/** @name Decorators\n * @{\n *\/\n \/** A user-provided string describing the error.\n *\/\n using location = ErrorInfo;\n using description = ErrorInfo;\n using filename = ErrorInfo;\n \/\/\/ @}\n }\n\n \/** Decorate an exception with an ErrorInfo.\n *\/\n template\n inline std::enable_if_t>::value &&\n std::is_base_of_v, Exception_T> const&\n operator<<(Exception_T const& e, ErrorInfo_T&& error_info) {\n e.addErrorInfo(std::forward(error_info));\n return e;\n }\n\n \/** Decorate an exception with an the Exception_Info::location error info.\n *\/\n template\n inline std::enable_if_t, Exception_T> const&\n operator<<(Exception_T const& e, Exception_Info::location l) {\n Exception_Info::Records::location const loc = l.getData();\n e.setExceptionLocation(loc.file, loc.function, loc.line);\n return e;\n }\n\n \/** Attempts to retrieve the error decoration of type `ErrorInfo_T` from the exception `e`.\n * @return A pointer to the decorator record if it could be retrieved; `nullptr` otherwise.\n * Retrieval may fail if `Exception_T` is not a class derived from `Exception` or\n * if the exception does not contain a decorator of the requested type.\n *\/\n template\n inline typename ErrorInfo_T::ValueType const* getErrorInfo(Exception_T const& e) {\n if (Exception const* exc = dynamic_cast(&e); exc != nullptr) {\n return exc->getErrorInfo();\n }\n return nullptr;\n }\n\n \/** Helper function for retrieving a diagnostic information string about the exception.\n *\/\n inline char const* getDiagnosticMessage(Exception const& e) {\n return e.getDiagnosticMessage();\n }\n\n \/** Helper function applying a variadic number of decorators to an exception.\n * @param e An exception object.\n * @param args The decorators that will be applied to the exception object e.\n * @return A reference to the exception object e.\n *\/\n template\n inline auto decorate_exception(Exception_T const& e, ExceptionInfo_Ts const&... args)\n {\n return (e << ... << args);\n }\n\n \/** Concrete exception objects.\n *\/\n namespace Exceptions\n {\n namespace impl\n {\n \/** Mixin class for implementing Ghulbus::Exceptions.\n * This class provides a default implementation for what() that gives a detailed error message.\n *\/\n class GHULBUS_BASE_API ExceptionImpl : public virtual ::GHULBUS_BASE_NAMESPACE::Exception\n {\n public:\n char const* what() const noexcept override {\n return ::GHULBUS_BASE_NAMESPACE::getDiagnosticMessage(*this);\n }\n };\n }\n\n \/** Thrown by Assert::failThrow in case of a failing exception.\n *\/\n class GHULBUS_BASE_API AssertFailed : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown by interfaces that have not yet been implemented.\n *\/\n class GHULBUS_BASE_API NotImplemented : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when an I\/O operation fails.\n *\/\n class GHULBUS_BASE_API IOError : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when an invalid argument was passed to a function.\n * This is used if an argument does not violate a function's precondition but is nonetheless invalid in the\n * given context. Precondition violations are undefined behavior and may only be signaled using GHULBUS_ASSERT.\n *\/\n class GHULBUS_BASE_API InvalidArgument : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when a function call violates protocol.\n * This is used if a function call does not violate a function's precondition but is nonetheless invalid in the\n * given context. Precondition violations are undefined behavior and may only be signaled using GHULBUS_ASSERT.\n * @note Use this exception with care. Most of the time, a protocol violation is a precondition violation.\n *\/\n class GHULBUS_BASE_API ProtocolViolation : public impl::ExceptionImpl\n {\n };\n }\n}\n\n\/** @cond\n *\/\n#if defined _MSC_VER\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __FUNCSIG__\n#elif defined __clang__\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __PRETTY_FUNCTION__\n#elif defined __GNUC__\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __PRETTY_FUNCTION__\n#else\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __func__\n#endif\n\/** @endcond\n *\/\n\n\/** Throw a Ghulbus::Exception.\n * All exceptions thrown with this macro will be decorated with the supplied string description and information\n * about the source code location that triggered the throw.\n * @param exc An exception object inheriting from Ghulbus::Exception.\n * @param str A std::string or null-terminated C-string to attach to the exception as description.\n *\/\n#define GHULBUS_THROW(exc, str) \\\n throw ( (exc) << \\\n ::GHULBUS_BASE_NAMESPACE::Exception_Info::location(__FILE__, \\\n GHULBUS_INTERNAL_HELPER_FUNCTION_2, \\\n __LINE__) << \\\n ::GHULBUS_BASE_NAMESPACE::Exception_Info::description(str) )\n\n#endif\nremoved unnecessary std::move#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_EXCEPTION_HPP\n#define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_EXCEPTION_HPP\n\n\/** @file\n*\n* @brief Exception Base Class.\n* @author Andreas Weis (der_ghulbus@ghulbus-inc.de)\n*\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace GHULBUS_BASE_NAMESPACE\n{\n \/** Decorator type.\n * An exception type derived from `Exception` may have an arbitrary number of decorator types attached to it\n * using `operator<<`. The data attached this way may then be retrieved from the exception object by\n * calling `getErrorInfo()`.\n *\/\n template\n class GHULBUS_BASE_API ErrorInfo {\n public:\n using ValueType = T;\n using TagType = Tag_T;\n private:\n T m_data;\n public:\n template\n ErrorInfo(Args&&... args)\n :m_data(std::forward(args)...)\n {}\n\n T const& getData() const & {\n return m_data;\n }\n\n T&& getData() && {\n return std::move(m_data);\n }\n };\n\n \/** Trait for detecting instantiations of `ErrorInfo`.\n *\/\n template\n struct IsErrorInfo : public std::false_type {};\n template\n struct IsErrorInfo> : public std::true_type {};\n\n namespace impl {\n \/** @cond\n *\/\n \/** Helper functor for converting arbitrary types to string for printing.\n * - if `T` is std::string acts as the identity function\n * - if `T` has an overload of `to_string` found through an unqualified call, uses `to_string`\n * - if `T` has an ostream inserter defined, uses `operator<<` to insert to a `std::stringstream`\n * - otherwise use `typeid(T).name()`.\n *\/\n template\n struct toStringHelper;\n\n using std::to_string;\n\n template\n struct hasToString : public std::false_type {};\n template\n struct hasToString()))>> : public std::true_type {};\n\n template\n struct hasOstreamInserter : public std::false_type {};\n template\n struct hasOstreamInserter() << std::declval())>> : public std::true_type {};\n\n template<>\n struct toStringHelper {\n std::string const& operator()(std::string const& s) {\n return s;\n }\n };\n\n template\n struct toStringHelper && hasToString::value>> {\n std::string operator()(T const& v) {\n return to_string(v);\n }\n };\n\n template\n struct toStringHelper &&\n !hasToString::value &&\n hasOstreamInserter::value>>\n {\n std::string operator()(T const& v) {\n std::stringstream sstr;\n sstr << v;\n return sstr.str();\n }\n };\n\n template\n struct toStringHelper &&\n !hasToString::value &&\n !hasOstreamInserter::value>>\n {\n std::string operator()(T const& v) {\n return typeid(T).name();\n }\n };\n \/** @endcond\n *\/\n }\n\n \/** Base class for all Ghulbus exceptions.\n * Any exception can be decorated with additional info. Instantiate an Info object from the\n * Exception_Info namespace and use `operator<<` to assign it to an exception.\n * All exceptions thrown through \\ref GHULBUS_THROW are decorated with Exception_Info::description and a\n * decorator for the location of the throw site of the exception, see `Exception_Info::Records::location`.\n * Individual decorators can be retrieved from an exception object with `getErrorInfo()`.\n * To obtain a textual representation of all the information for an exception,\n * use `getDiagnosticMessage`.\n *\n *\/\n class GHULBUS_BASE_API Exception : public virtual std::exception {\n private:\n \/** Type-erased storage for ErrorInfo (base class).\n *\/\n class ErrorInfoConcept {\n private:\n std::unique_ptr m_next;\n public:\n ErrorInfoConcept() = default;\n\n explicit ErrorInfoConcept(std::unique_ptr&& next)\n :m_next(std::move(next))\n {}\n\n virtual ~ErrorInfoConcept() noexcept = default;\n virtual std::unique_ptr clone() const = 0;\n virtual std::type_info const& getTypeInfo() const = 0;\n virtual std::string dataString() const = 0;\n\n ErrorInfoConcept const* next() const {\n return m_next.get();\n }\n\n ErrorInfoConcept* next() {\n return m_next.get();\n }\n };\n\n \/** Type-erased storage for ErrorInfo.\n *\/\n template\n class ErrorInfoModel : public ErrorInfoConcept {\n public:\n static_assert(IsErrorInfo::value,\n \"Only ErrorInfo types can be used to decorate Exception.\");\n using ValueType = typename ErrorInfo_T::ValueType;\n using TagType = typename ErrorInfo_T::TagType;\n private:\n ValueType m_data;\n public:\n ErrorInfoModel(std::unique_ptr&& next, ErrorInfo_T data)\n :ErrorInfoConcept(std::move(next)), m_data(std::move(data).getData())\n {}\n\n ~ErrorInfoModel() noexcept override = default;\n\n std::unique_ptr clone() const override {\n ErrorInfoConcept const* next_ei = next();\n return std::make_unique((next_ei == nullptr) ? nullptr : next_ei->clone(), m_data);\n }\n\n std::type_info const& getTypeInfo() const override {\n return typeid(TagType);\n }\n\n ValueType const& data() const {\n return m_data;\n }\n\n std::string dataString() const override {\n return impl::toStringHelper{}(data());\n }\n };\n\n std::unique_ptr mutable m_errorInfos;\n mutable char const* m_throwFile = nullptr;\n mutable char const* m_throwFunction = nullptr;\n mutable long m_throwLine = -1;\n mutable std::string m_message;\n protected:\n Exception() = default;\n virtual ~Exception() = default;\n\n Exception(Exception&&) noexcept = default;\n Exception& operator=(Exception&&) noexcept = default;\n\n Exception(Exception const& rhs)\n :m_errorInfos(rhs.m_errorInfos->clone()),\n m_throwFile(rhs.m_throwFile), m_throwFunction(rhs.m_throwFunction), m_throwLine(rhs.m_throwLine)\n {}\n\n Exception& operator=(Exception const& rhs) {\n if (&rhs != this) {\n m_errorInfos = rhs.m_errorInfos->clone();\n m_throwFile = rhs.m_throwFile;\n m_throwFunction = rhs.m_throwFunction;\n m_throwLine = rhs.m_throwLine;\n }\n return *this;\n }\n\n public:\n \/** Redeclare std::exception::what() as pure virtual.\n * We do this here so that Exception becomes abstract and to force inheriting classes to give\n * the noexcept guarantee.\n *\/\n virtual char const* what() const noexcept = 0;\n\n template\n std::enable_if_t>::value, void>\n addErrorInfo(ErrorInfo_T&& error_info) const {\n m_errorInfos = std::make_unique<\n ErrorInfoModel>>(std::move(m_errorInfos),\n std::forward(error_info));\n }\n\n void setExceptionLocation(char const* throw_file, char const* throw_function, long throw_line) const {\n m_throwFile = throw_file;\n m_throwFunction = throw_function;\n m_throwLine = throw_line;\n }\n\n template\n typename ErrorInfo_T::ValueType const* getErrorInfo() const {\n using TagType = typename ErrorInfo_T::TagType;\n for (ErrorInfoConcept const* it = m_errorInfos.get(); it != nullptr; it = it->next()) {\n if (it->getTypeInfo() == typeid(TagType)) {\n return &dynamic_cast const&>(*it).data();\n }\n }\n return nullptr;\n }\n\n char const* getDiagnosticMessage() const {\n \/*\n (): Throw in function \n Dynamic exception type: bla\n [] = \n ...\n [] = \n *\/\n m_message =\n std::string((m_throwFile) ? m_throwFile : \"\") +\n '(' + std::to_string(m_throwLine) + \"): Throw in function \" +\n (m_throwFunction ? m_throwFunction : \"\") +\n \"\\nDynamic exception type: \" + typeid(*this).name();\n for (ErrorInfoConcept const* it = m_errorInfos.get(); it != nullptr; it = it->next()) {\n m_message += std::string(\"\\n[\") + it->getTypeInfo().name() + \"] = \" + it->dataString();\n }\n return m_message.c_str();\n }\n };\n\n\n \/** Exception decorators.\n * Place all exception decorators in this namespace.\n * A decorator is an instance of the boost::error_info template with a unique (empty) tag type and a record type\n * that provides storage for the information.\n * For non-trivial record-types, provide a std::ostream inserter to allow for nice automatic error messages.\n *\/\n namespace Exception_Info {\n \/** Decorator Tags.\n * Tags are empty types used to uniquely identify a decoratory type.\n *\/\n namespace Tags\n {\n struct GHULBUS_BASE_API location { };\n struct GHULBUS_BASE_API description { };\n struct GHULBUS_BASE_API filename { };\n }\n \/** Decorator record types.\n *\/\n namespace Records\n {\n struct location {\n char const* file;\n char const* function;\n long line;\n\n location(char const* nfile, char const* nfunc, long nline)\n :file(nfile), function(nfunc), line(nline)\n {}\n };\n }\n\n \/** @name Decorators\n * @{\n *\/\n \/** A user-provided string describing the error.\n *\/\n using location = ErrorInfo;\n using description = ErrorInfo;\n using filename = ErrorInfo;\n \/\/\/ @}\n }\n\n \/** Decorate an exception with an ErrorInfo.\n *\/\n template\n inline std::enable_if_t>::value &&\n std::is_base_of_v, Exception_T> const&\n operator<<(Exception_T const& e, ErrorInfo_T&& error_info) {\n e.addErrorInfo(std::forward(error_info));\n return e;\n }\n\n \/** Decorate an exception with an the Exception_Info::location error info.\n *\/\n template\n inline std::enable_if_t, Exception_T> const&\n operator<<(Exception_T const& e, Exception_Info::location l) {\n Exception_Info::Records::location const loc = l.getData();\n e.setExceptionLocation(loc.file, loc.function, loc.line);\n return e;\n }\n\n \/** Attempts to retrieve the error decoration of type `ErrorInfo_T` from the exception `e`.\n * @return A pointer to the decorator record if it could be retrieved; `nullptr` otherwise.\n * Retrieval may fail if `Exception_T` is not a class derived from `Exception` or\n * if the exception does not contain a decorator of the requested type.\n *\/\n template\n inline typename ErrorInfo_T::ValueType const* getErrorInfo(Exception_T const& e) {\n if (Exception const* exc = dynamic_cast(&e); exc != nullptr) {\n return exc->getErrorInfo();\n }\n return nullptr;\n }\n\n \/** Helper function for retrieving a diagnostic information string about the exception.\n *\/\n inline char const* getDiagnosticMessage(Exception const& e) {\n return e.getDiagnosticMessage();\n }\n\n \/** Helper function applying a variadic number of decorators to an exception.\n * @param e An exception object.\n * @param args The decorators that will be applied to the exception object e.\n * @return A reference to the exception object e.\n *\/\n template\n inline auto decorate_exception(Exception_T const& e, ExceptionInfo_Ts const&... args)\n {\n return (e << ... << args);\n }\n\n \/** Concrete exception objects.\n *\/\n namespace Exceptions\n {\n namespace impl\n {\n \/** Mixin class for implementing Ghulbus::Exceptions.\n * This class provides a default implementation for what() that gives a detailed error message.\n *\/\n class GHULBUS_BASE_API ExceptionImpl : public virtual ::GHULBUS_BASE_NAMESPACE::Exception\n {\n public:\n char const* what() const noexcept override {\n return ::GHULBUS_BASE_NAMESPACE::getDiagnosticMessage(*this);\n }\n };\n }\n\n \/** Thrown by Assert::failThrow in case of a failing exception.\n *\/\n class GHULBUS_BASE_API AssertFailed : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown by interfaces that have not yet been implemented.\n *\/\n class GHULBUS_BASE_API NotImplemented : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when an I\/O operation fails.\n *\/\n class GHULBUS_BASE_API IOError : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when an invalid argument was passed to a function.\n * This is used if an argument does not violate a function's precondition but is nonetheless invalid in the\n * given context. Precondition violations are undefined behavior and may only be signaled using GHULBUS_ASSERT.\n *\/\n class GHULBUS_BASE_API InvalidArgument : public impl::ExceptionImpl\n {\n };\n\n \/** Thrown when a function call violates protocol.\n * This is used if a function call does not violate a function's precondition but is nonetheless invalid in the\n * given context. Precondition violations are undefined behavior and may only be signaled using GHULBUS_ASSERT.\n * @note Use this exception with care. Most of the time, a protocol violation is a precondition violation.\n *\/\n class GHULBUS_BASE_API ProtocolViolation : public impl::ExceptionImpl\n {\n };\n }\n}\n\n\/** @cond\n *\/\n#if defined _MSC_VER\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __FUNCSIG__\n#elif defined __clang__\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __PRETTY_FUNCTION__\n#elif defined __GNUC__\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __PRETTY_FUNCTION__\n#else\n# define GHULBUS_INTERNAL_HELPER_FUNCTION_2 __func__\n#endif\n\/** @endcond\n *\/\n\n\/** Throw a Ghulbus::Exception.\n * All exceptions thrown with this macro will be decorated with the supplied string description and information\n * about the source code location that triggered the throw.\n * @param exc An exception object inheriting from Ghulbus::Exception.\n * @param str A std::string or null-terminated C-string to attach to the exception as description.\n *\/\n#define GHULBUS_THROW(exc, str) \\\n throw ( (exc) << \\\n ::GHULBUS_BASE_NAMESPACE::Exception_Info::location(__FILE__, \\\n GHULBUS_INTERNAL_HELPER_FUNCTION_2, \\\n __LINE__) << \\\n ::GHULBUS_BASE_NAMESPACE::Exception_Info::description(str) )\n\n#endif\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef IL_TARGET_MACHINE_H\n#define IL_TARGET_MACHINE_H\n\nnamespace eddic {\n\nstruct TargetMachine {\n int availableRegisters();\n};\n\n} \/\/end of eddic\n\n#endif\nRemove target machine<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2003, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_HPP_INCLUDED\n#define TORRENT_ALERT_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#ifndef TORRENT_MAX_ALERT_TYPES\n#define TORRENT_MAX_ALERT_TYPES 15\n#endif\n\nnamespace libtorrent {\n\n\tclass TORRENT_EXPORT alert\n\t{\n\tpublic:\n\n\t\t\/\/ only here for backwards compatibility\n\t\tenum severity_t { debug, info, warning, critical, fatal, none };\n\n\t\tenum category_t\n\t\t{\n\t\t\terror_notification = 0x1,\n\t\t\tpeer_notification = 0x2,\n\t\t\tport_mapping_notification = 0x4,\n\t\t\tstorage_notification = 0x8,\n\t\t\ttracker_notification = 0x10,\n\t\t\tdebug_notification = 0x20,\n\t\t\tstatus_notification = 0x40,\n\t\t\tprogress_notification = 0x80,\n\t\t\tip_block_notification = 0x100,\n\n\t\t\tall_categories = 0xffffffff\n\t\t};\n\n\t\talert();\n\t\tvirtual ~alert();\n\n\t\t\/\/ a timestamp is automatically created in the constructor\n\t\tptime timestamp() const;\n\n\t\tvirtual char const* what() const = 0;\n\t\tvirtual std::string message() const = 0;\n\t\tvirtual int category() const = 0;\n\n\t\tseverity_t severity() const TORRENT_DEPRECATED { return warning; }\n\n\t\tvirtual std::auto_ptr clone() const = 0;\n\n\tprivate:\n\t\tptime m_timestamp;\n\t};\n\n\tclass TORRENT_EXPORT alert_manager\n\t{\n\tpublic:\n\t\talert_manager();\n\t\t~alert_manager();\n\n\t\tvoid post_alert(const alert& alert_);\n\t\tbool pending() const;\n\t\tstd::auto_ptr get();\n\n\t\ttemplate \n\t\tbool should_post() const { return m_alert_mask & T::static_category; }\n\n\t\talert const* wait_for_alert(time_duration max_wait);\n\n\t\tvoid set_alert_mask(int m) { m_alert_mask = m; }\n\n\tprivate:\n\t\tstd::queue m_alerts;\n\t\tmutable boost::mutex m_mutex;\n\t\tboost::condition m_condition;\n\t\tint m_alert_mask;\n\t};\n\n\tstruct TORRENT_EXPORT unhandled_alert : std::exception\n\t{\n\t\tunhandled_alert() {}\n\t};\n\n\tnamespace detail {\n\n\t\tstruct void_;\n\n\t\ttemplate\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& alert_, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p))\n\t\t{\n\t\t\tif (typeid_ == typeid(T0))\n\t\t\t\thandler(*static_cast(alert_.get()));\n\t\t\telse\n\t\t\t\thandle_alert_dispatch(alert_, handler, typeid_\n\t\t\t\t\t, BOOST_PP_ENUM_SHIFTED_PARAMS(\n\t\t\t\t\tTORRENT_MAX_ALERT_TYPES, p), (void_*)0);\n\t\t}\n\n\t\ttemplate\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& alert_\n\t\t\t, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT))\n\t\t{\n\t\t\tthrow unhandled_alert();\n\t\t}\n\n\t} \/\/ namespace detail\n\n\ttemplate\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate\n\t\thandle_alert(const std::auto_ptr& alert_\n\t\t\t, const Handler& handler)\n\t\t{\n\t\t\t#define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0\n\n\t\t\tdetail::handle_alert_dispatch(alert_, handler, typeid(*alert_)\n\t\t\t\t, BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _));\n\n\t\t\t#undef ALERT_POINTER_TYPE\n\t\t}\n\t};\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_ALERT_HPP_INCLUDED\n\nfixed msvc warning\/*\n\nCopyright (c) 2003, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALERT_HPP_INCLUDED\n#define TORRENT_ALERT_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/config.hpp\"\n#include \"libtorrent\/assert.hpp\"\n\n#ifndef TORRENT_MAX_ALERT_TYPES\n#define TORRENT_MAX_ALERT_TYPES 15\n#endif\n\nnamespace libtorrent {\n\n\tclass TORRENT_EXPORT alert\n\t{\n\tpublic:\n\n\t\t\/\/ only here for backwards compatibility\n\t\tenum severity_t { debug, info, warning, critical, fatal, none };\n\n\t\tenum category_t\n\t\t{\n\t\t\terror_notification = 0x1,\n\t\t\tpeer_notification = 0x2,\n\t\t\tport_mapping_notification = 0x4,\n\t\t\tstorage_notification = 0x8,\n\t\t\ttracker_notification = 0x10,\n\t\t\tdebug_notification = 0x20,\n\t\t\tstatus_notification = 0x40,\n\t\t\tprogress_notification = 0x80,\n\t\t\tip_block_notification = 0x100,\n\n\t\t\tall_categories = 0xffffffff\n\t\t};\n\n\t\talert();\n\t\tvirtual ~alert();\n\n\t\t\/\/ a timestamp is automatically created in the constructor\n\t\tptime timestamp() const;\n\n\t\tvirtual char const* what() const = 0;\n\t\tvirtual std::string message() const = 0;\n\t\tvirtual int category() const = 0;\n\n\t\tseverity_t severity() const TORRENT_DEPRECATED { return warning; }\n\n\t\tvirtual std::auto_ptr clone() const = 0;\n\n\tprivate:\n\t\tptime m_timestamp;\n\t};\n\n\tclass TORRENT_EXPORT alert_manager\n\t{\n\tpublic:\n\t\talert_manager();\n\t\t~alert_manager();\n\n\t\tvoid post_alert(const alert& alert_);\n\t\tbool pending() const;\n\t\tstd::auto_ptr get();\n\n\t\ttemplate \n\t\tbool should_post() const { return (m_alert_mask & T::static_category) != 0; }\n\n\t\talert const* wait_for_alert(time_duration max_wait);\n\n\t\tvoid set_alert_mask(int m) { m_alert_mask = m; }\n\n\tprivate:\n\t\tstd::queue m_alerts;\n\t\tmutable boost::mutex m_mutex;\n\t\tboost::condition m_condition;\n\t\tint m_alert_mask;\n\t};\n\n\tstruct TORRENT_EXPORT unhandled_alert : std::exception\n\t{\n\t\tunhandled_alert() {}\n\t};\n\n\tnamespace detail {\n\n\t\tstruct void_;\n\n\t\ttemplate\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& alert_, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p))\n\t\t{\n\t\t\tif (typeid_ == typeid(T0))\n\t\t\t\thandler(*static_cast(alert_.get()));\n\t\t\telse\n\t\t\t\thandle_alert_dispatch(alert_, handler, typeid_\n\t\t\t\t\t, BOOST_PP_ENUM_SHIFTED_PARAMS(\n\t\t\t\t\tTORRENT_MAX_ALERT_TYPES, p), (void_*)0);\n\t\t}\n\n\t\ttemplate\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& alert_\n\t\t\t, const Handler& handler\n\t\t\t, const std::type_info& typeid_\n\t\t\t, BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT))\n\t\t{\n\t\t\tthrow unhandled_alert();\n\t\t}\n\n\t} \/\/ namespace detail\n\n\ttemplate\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate\n\t\thandle_alert(const std::auto_ptr& alert_\n\t\t\t, const Handler& handler)\n\t\t{\n\t\t\t#define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0\n\n\t\t\tdetail::handle_alert_dispatch(alert_, handler, typeid(*alert_)\n\t\t\t\t, BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _));\n\n\t\t\t#undef ALERT_POINTER_TYPE\n\t\t}\n\t};\n\n} \/\/ namespace libtorrent\n\n#endif \/\/ TORRENT_ALERT_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"\/*\n * udpmulticast.hpp\n *\n * Created on: 2015. 10. 26.\n * Author: hwang\n *\/\n\n#ifndef INCLUDE_NET_UDPMULTICAST_HPP_\n#define INCLUDE_NET_UDPMULTICAST_HPP_\n\n#include \"sock.hpp\"\n#include \n\nnamespace cossb {\nnamespace net {\n\nclass udpmulticast : public sock {\npublic:\n\tudpmulticast(netType type, const char* ipv4, int port):sock(type) {\n\t\tswitch(type)\n\t\t{\n\t\tcase netType::CLIENT: break;\n\t\tcase netType::HOST:\n\t\t{\n\t\t\tif((this->sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)\n\t\t\t\tthrow net::exception(net::excode::SOCKET_CREATE_FAIL);\n\t\t\telse {\n\t\t\t\tmemset(&_address, 0, sizeof(_address));\n\t\t\t\t_address.sin_family = AF_INET;\n\t\t\t\t_address.sin_addr.s_addr = htonl(INADDR_ANY);\n\t\t\t\t_address.sin_port = htons(port);\n\n\t\t\t\tstruct ip_mreq\t_mreq;\n\t\t\t\t_mreq.imr_multiaddr.s_addr = inet_addr(ipv4);\n\t\t\t\t_mreq.imr_interface.s_addr = htonl(INADDR_ANY);\n\n\t\t\t\t\/\/join network group\n\t\t\t\tif(::setsockopt(this->sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &_mreq, sizeof(_mreq))<0)\n\t\t\t\t\tthrow net::exception(net::excode::SOCKET_SET_ADDMEMBERSHIP_FAIL);\n\n\t\t\t\t\/\/receive timeout 3 sec\n\t\t\t\tstruct timeval timeout = {3, 0};\n\t\t\t\tif(setsockopt(this->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))<0)\n\t\t\t\t\tthrow net::exception(net::excode::SOCKET_SET_TIMEOUT_FAIL);\n\n\t\t\t\t\/\/socket reuse\n\t\t\t\tunsigned int reuse = 1;\n\t\t\t\tif(setsockopt(this->sockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)\n\t\t\t\t\tthrow net::exception(net::excode::SOCKET_SET_REUSE_FAIL);\n\n\t\t\t\tif(::bind(this->sockfd, (struct sockaddr*)&_address, sizeof(_address))<0) {\n\t\t\t\t\tthrow net::exception(net::excode::SOCKET_BIND_FAIL);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tvirtual ~udpmulticast() { }\n\n};\n\n} \/* namespace net *\/\n} \/* namespace cossb *\/\n\n\n#endif \/* INCLUDE_NET_UDPMULTICAST_HPP_ *\/\nremove udpmulticast class<|endoftext|>"} {"text":"\/\/ Copyright (c) 2021 midnightBITS\n\/\/ This code is licensed under MIT license (see LICENSE for details)\n\n#pragma once\n\n#include \n#include \n\nnamespace tangle {\n\t\/\/ Under libstdc++, std::isspace is visible as an overload set\n\t\/\/ consisting of more, than one function. This alias narrows this down\n\t\/\/ to single-function overload set available for base_parser::skip<>.\n\t\/\/\n\t\/\/ Additionally, this gives us the possibility to slap a noexcept on this\n\t\/\/ one.\n\tinline int is_space(int c) noexcept { return std::isspace(c); }\n\n\tstruct base_parser {\n\t\tstd::string_view text;\n\t\tchar const* pos = text.data();\n\t\tchar const* end = pos + text.size();\n\n\t\tbase_parser(std::string_view text) : text{text} {}\n\n\t\tbool eof() const noexcept { return pos == end; }\n\n\t\ttemplate \n\t\tvoid skip(Pred pred) noexcept(\n\t\t noexcept(pred(std::declval()))) {\n\t\t\twhile (pos < end && pred(static_cast(*pos)))\n\t\t\t\t++pos;\n\t\t}\n\n\t\ttemplate \n\t\tvoid skip_until(Pred pred) noexcept(\n\t\t noexcept(pred(std::declval()))) {\n\t\t\twhile (pos < end && !pred(static_cast(*pos)))\n\t\t\t\t++pos;\n\t\t}\n\n\t\ttemplate \n\t\tvoid look_for() noexcept {\n\t\t\tskip_until([](int c) noexcept { return ((C == c) || ...); });\n\t\t}\n\n\t\ttemplate \n\t\tstd::string_view text_until() noexcept {\n\t\t\treturn substr([](auto& self) noexcept {\n\t\t\t\tself.template look_for();\n\t\t\t});\n\t\t}\n\n\t\ttemplate \n\t\tstd::string_view substr(Oper op) noexcept(\n\t\t noexcept(op(std::declval()))) {\n\t\t\tauto start = pos;\n\t\t\top(*static_cast(this));\n\t\t\treturn {start, static_cast(pos - start)};\n\t\t}\n\n\t\tvoid skip_ws() noexcept { skip(is_space); }\n\n\t\tbool peek(char c) noexcept { return pos < end && *pos == c; }\n\t\tbool get(char c) noexcept {\n\t\t\tauto const result = peek(c);\n\t\t\tif (result) ++pos;\n\t\t\treturn result;\n\t\t}\n\t};\n} \/\/ namespace tangle\nAdd is() and index() to base_parser\/\/ Copyright (c) 2021 midnightBITS\n\/\/ This code is licensed under MIT license (see LICENSE for details)\n\n#pragma once\n\n#include \n#include \n\nnamespace tangle {\n\t\/\/ Under libstdc++, std::isspace is visible as an overload set\n\t\/\/ consisting of more, than one function. This alias narrows this down\n\t\/\/ to single-function overload set available for base_parser::skip<>.\n\t\/\/\n\t\/\/ Additionally, this gives us the possibility to slap a noexcept on this\n\t\/\/ one.\n\tinline int is_space(int c) noexcept { return std::isspace(c); }\n\n\tstruct base_parser {\n\t\tstd::string_view text;\n\t\tchar const* pos = text.data();\n\t\tchar const* end = pos + text.size();\n\n\t\tbase_parser(std::string_view text) : text{text} {}\n\n\t\tbool eof() const noexcept { return pos == end; }\n\n\t\ttemplate \n\t\tbool is(Pred pred) const\n\t\t noexcept(noexcept(pred(std::declval()))) {\n\t\t\treturn pos < end && pred(static_cast(*pos));\n\t\t}\n\n\t\ttemplate \n\t\tvoid skip(Pred pred) noexcept(\n\t\t noexcept(pred(std::declval()))) {\n\t\t\twhile (pos < end && pred(static_cast(*pos)))\n\t\t\t\t++pos;\n\t\t}\n\n\t\ttemplate \n\t\tvoid skip_until(Pred pred) noexcept(\n\t\t noexcept(pred(std::declval()))) {\n\t\t\twhile (pos < end && !pred(static_cast(*pos)))\n\t\t\t\t++pos;\n\t\t}\n\n\t\ttemplate \n\t\tvoid look_for() noexcept {\n\t\t\tskip_until([](int c) noexcept { return ((C == c) || ...); });\n\t\t}\n\n\t\ttemplate \n\t\tstd::string_view text_until() noexcept {\n\t\t\treturn substr([](auto& self) noexcept {\n\t\t\t\tself.template look_for();\n\t\t\t});\n\t\t}\n\n\t\ttemplate \n\t\tstd::string_view substr(Oper op) noexcept(\n\t\t noexcept(op(std::declval()))) {\n\t\t\tauto start = pos;\n\t\t\top(*static_cast(this));\n\t\t\treturn {start, static_cast(pos - start)};\n\t\t}\n\n\t\tvoid skip_ws() noexcept { skip(is_space); }\n\n\t\tbool peek(char c) const noexcept { return pos < end && *pos == c; }\n\t\tbool get(char c) noexcept {\n\t\t\tauto const result = peek(c);\n\t\t\tif (result) ++pos;\n\t\t\treturn result;\n\t\t}\n\n\t\tsize_t index_of(char const* ptr) const noexcept {\n\t\t\treturn static_cast(ptr - text.data());\n\t\t}\n\n\t\tsize_t index() const noexcept { return index_of(pos); }\n\t};\n} \/\/ namespace tangle\n<|endoftext|>"} {"text":"\/* Definition of the pqxx::stream_from class.\n *\n * pqxx::stream_from enables optimized batch reads from a database table.\n *\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/stream_from instead.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#ifndef PQXX_H_STREAM_FROM\n#define PQXX_H_STREAM_FROM\n\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/internal\/compiler-internal-pre.hxx\"\n\n#include \n#include \n#include \n\n#include \"pqxx\/except.hxx\"\n#include \"pqxx\/internal\/encoding_group.hxx\"\n#include \"pqxx\/internal\/stream_iterator.hxx\"\n#include \"pqxx\/internal\/transaction_focus.hxx\"\n#include \"pqxx\/separated_list.hxx\"\n#include \"pqxx\/transaction_base.hxx\"\n\n\nnamespace pqxx\n{\n\/\/\/ Pass this to a @c stream_from constructor to stream table contents.\nconstexpr from_table_t from_table;\n\/\/\/ Pass this to a @c stream_from constructor to stream query results.\nconstexpr from_query_t from_query;\n\n\n\/\/\/ Stream data from the database.\n\/** Retrieving data this way is likely to be faster than executing a query and\n * then iterating and converting the rows fields. You will also be able to\n * start processing before all of the data has come in.\n *\n * There are also downsides. If there's an error, it may leave the entire\n * connection in an unusable state, so you'll have to give the whole thing up.\n * Also, your connection to the database may break before you've received all\n * the data, so you may end up processing only part of the data. Finally,\n * opening a stream puts the connection in a special state, so you won't be\n * able to do many other things with the connection or the transaction while\n * the stream is open.\n *\n * There are two ways of starting a stream: you stream either all rows in a\n * table (in which case, use a constructor which accepts @c pqxx::from_table),\n * or the results of a query (in which case, use a concstructor which accepts\n * @c pqxx::from_query).\n *\n * Usually you'll want the @c stream convenience wrapper in transaction_base,\n * so you don't need to deal with this class directly.\n *\/\nclass PQXX_LIBEXPORT stream_from : internal::transactionfocus\n{\npublic:\n using raw_line =\n std::pair>, std::size_t>;\n\n \/\/\/ Execute query, and stream over the results.\n \/** The query can be a SELECT query or a VALUES query; or it can be an\n * UPDATE, INSERT, or DELETE with a RETURNING clause.\n *\n * The query is executed as part of a COPY statement, so there are additional\n * restrictions on what kind of query you can use here. See the PostgreSQL\n * documentation for the COPY command:\n *\n * https:\/\/www.postgresql.org\/docs\/current\/sql-copy.html\n *\/\n stream_from(transaction_base &, from_query_t, std::string_view query);\n\n \/\/\/ Stream all rows in table, all columns.\n stream_from(transaction_base &, from_table_t, std::string_view table);\n\n \/\/\/ Stream given columns from all rows in table.\n template\n stream_from(\n transaction_base &, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end);\n\n \/\/\/ Stream given columns from all rows in table.\n template\n stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Columns const &columns);\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n stream_from(transaction_base &tx, std::string_view table) :\n stream_from{tx, from_table, table}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template\n stream_from(\n transaction_base &tx, std::string_view table, Columns const &columns) :\n stream_from{tx, from_table, table, columns}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template\n stream_from(\n transaction_base &, std::string_view table, Iter columns_begin,\n Iter columns_end);\n\n ~stream_from() noexcept;\n\n [[nodiscard]] operator bool() const noexcept { return not m_finished; }\n [[nodiscard]] bool operator!() const noexcept { return m_finished; }\n\n \/\/\/ Finish this stream. Call this before continuing to use the connection.\n \/** Consumes all remaining lines, and closes the stream.\n *\n * This may take a while if you're abandoning the stream before it's done, so\n * skip it in error scenarios where you're not planning to use the connection\n * again afterwards.\n *\/\n void complete();\n\n \/\/\/ Read one row into a tuple.\n \/** Converts the row's fields into the fields making up the tuple.\n *\n * For a column which can contain nulls, be sure to give the corresponding\n * tuple field a type which can be null. For example, to read a field as\n * @c int when it may contain nulls, read it as @c std::optional.\n * Using @c std::shared_ptr or @c std::unique_ptr will also work.\n *\/\n template stream_from &operator>>(Tuple &);\n\n \/\/\/ Doing this with a @c std::variant is going to be horrifically borked.\n template\n stream_from &operator>>(std::variant &) = delete;\n\n \/\/\/ Iterate over this stream. Supports range-based \"for\" loops.\n \/** Produces an input iterator over the stream.\n *\n * Do not call this yourself. Use it like \"for (auto data : stream.iter())\".\n *\/\n template[[nodiscard]] auto iter()\n {\n return pqxx::internal::stream_input_iteration{*this};\n }\n\n \/\/\/ Read a row. Return fields as views, valid until you read the next row.\n \/** Do not access the vector, or the storage referenced by the views, after\n * closing or completing the stream, or after reading a next row.\n *\n * A @c pqxx::zview is like a @c std::string_view, but with the added\n * guarantee that if its data pointer is non-null, the string is followed by\n * a terminating zero (which falls just outside the view itself).\n *\n * If any of the views' data pointer is null, that means that the\n * corresponding SQL field is null.\n *\/\n std::vector const &read_row();\n\n \/\/\/ Read a raw line of text from the COPY command.\n \/** @warn Do not use this unless you really know what you're doing. *\/\n raw_line get_raw_line();\n\nprivate:\n stream_from(\n transaction_base &tx, std::string_view table, std::string &&columns,\n from_table_t);\n\n template\n void extract_fields(Tuple &t, std::index_sequence) const\n {\n (extract_value(t), ...);\n }\n\n static std::string compose_query(\n transaction_base const &tx, std::string_view table,\n std::string const &columns);\n\n pqxx::internal::glyph_scanner_func *m_glyph_scanner;\n\n \/\/\/ Current row's fields' text, combined into one reusable string.\n std::string m_row;\n\n \/\/\/ The current row's fields.\n std::vector m_fields;\n\n bool m_finished = false;\n\n void close();\n\n template\n void extract_value(Tuple &) const;\n\n \/\/\/ Read a line of COPY data, write @c m_row and @c m_fields.\n void parse_line();\n};\n\n\ntemplate\ninline stream_from::stream_from(\n transaction_base &tb, from_table_t, std::string_view table_name,\n Columns const &columns) :\n stream_from{\n tb, from_table, table_name, std::begin(columns), std::end(columns)}\n{}\n\n\ntemplate\ninline stream_from::stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end) :\n stream_from{\n tx, table, separated_list(\",\", columns_begin, columns_end),\n from_table}\n{}\n\n\ntemplate inline stream_from &stream_from::operator>>(Tuple &t)\n{\n if (m_finished)\n return *this;\n constexpr auto tup_size{std::tuple_size_v};\n m_fields.reserve(tup_size);\n parse_line();\n if (m_finished)\n return *this;\n\n if (m_fields.size() != tup_size)\n throw usage_error{\n \"Tried to extract \" + to_string(tup_size) +\n \" field(s) from a stream of \" + to_string(m_fields.size()) + \".\"};\n\n extract_fields(t, std::make_index_sequence{});\n return *this;\n}\n\n\ntemplate\ninline void stream_from::extract_value(Tuple &t) const\n{\n using field_type = strip_t(t))>;\n using nullity = nullness;\n assert(index < m_fields.size());\n if constexpr (nullity::always_null)\n {\n if (m_fields[index].data() != nullptr)\n throw conversion_error{\"Streaming non-null value into null field.\"};\n }\n else if (m_fields[index].data() == nullptr)\n {\n if constexpr (nullity::has_null)\n std::get(t) = nullity::null();\n else\n internal::throw_null_conversion(type_name);\n }\n else\n {\n \/\/ Don't ever try to convert a non-null value to nullptr_t!\n std::get(t) = from_string(m_fields[index]);\n }\n}\n} \/\/ namespace pqxx\n\n#include \"pqxx\/internal\/compiler-internal-post.hxx\"\n#endif\nDocument: `stream_from` tables and schemas.\/* Definition of the pqxx::stream_from class.\n *\n * pqxx::stream_from enables optimized batch reads from a database table.\n *\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/stream_from instead.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#ifndef PQXX_H_STREAM_FROM\n#define PQXX_H_STREAM_FROM\n\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/internal\/compiler-internal-pre.hxx\"\n\n#include \n#include \n#include \n\n#include \"pqxx\/except.hxx\"\n#include \"pqxx\/internal\/encoding_group.hxx\"\n#include \"pqxx\/internal\/stream_iterator.hxx\"\n#include \"pqxx\/internal\/transaction_focus.hxx\"\n#include \"pqxx\/separated_list.hxx\"\n#include \"pqxx\/transaction_base.hxx\"\n\n\nnamespace pqxx\n{\n\/\/\/ Pass this to a @c stream_from constructor to stream table contents.\nconstexpr from_table_t from_table;\n\/\/\/ Pass this to a @c stream_from constructor to stream query results.\nconstexpr from_query_t from_query;\n\n\n\/\/\/ Stream data from the database.\n\/** Retrieving data this way is likely to be faster than executing a query and\n * then iterating and converting the rows fields. You will also be able to\n * start processing before all of the data has come in.\n *\n * There are also downsides. If there's an error, it may leave the entire\n * connection in an unusable state, so you'll have to give the whole thing up.\n * Also, your connection to the database may break before you've received all\n * the data, so you may end up processing only part of the data. Finally,\n * opening a stream puts the connection in a special state, so you won't be\n * able to do many other things with the connection or the transaction while\n * the stream is open.\n *\n * There are two ways of starting a stream: you stream either all rows in a\n * table (in which case, use a constructor which accepts @c pqxx::from_table),\n * or the results of a query (in which case, use a concstructor which accepts\n * @c pqxx::from_query).\n *\n * Usually you'll want the @c stream convenience wrapper in transaction_base,\n * so you don't need to deal with this class directly.\n *\/\nclass PQXX_LIBEXPORT stream_from : internal::transactionfocus\n{\npublic:\n using raw_line =\n std::pair>, std::size_t>;\n\n \/\/\/ Execute query, and stream over the results.\n \/** The query can be a SELECT query or a VALUES query; or it can be an\n * UPDATE, INSERT, or DELETE with a RETURNING clause.\n *\n * The query is executed as part of a COPY statement, so there are additional\n * restrictions on what kind of query you can use here. See the PostgreSQL\n * documentation for the COPY command:\n *\n * https:\/\/www.postgresql.org\/docs\/current\/sql-copy.html\n *\/\n stream_from(transaction_base &, from_query_t, std::string_view query);\n\n \/\/\/ Stream all rows in table, all columns.\n \/** The table name cannot include a schema name. If you need to specify a\n * schema name, stream from a query rather than from a table.\n *\/\n stream_from(transaction_base &, from_table_t, std::string_view table);\n\n \/\/\/ Stream given columns from all rows in table.\n \/** The table name cannot include a schema name. If you need to specify a\n * schema name, stream from a query rather than from a table.\n *\/\n template\n stream_from(\n transaction_base &, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end);\n\n \/\/\/ Stream given columns from all rows in table.\n \/** The table name cannot include a schema name. If you need to specify a\n * schema name, stream from a query rather than from a table.\n *\/\n template\n stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Columns const &columns);\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n stream_from(transaction_base &tx, std::string_view table) :\n stream_from{tx, from_table, table}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template\n stream_from(\n transaction_base &tx, std::string_view table, Columns const &columns) :\n stream_from{tx, from_table, table, columns}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template\n stream_from(\n transaction_base &, std::string_view table, Iter columns_begin,\n Iter columns_end);\n\n ~stream_from() noexcept;\n\n [[nodiscard]] operator bool() const noexcept { return not m_finished; }\n [[nodiscard]] bool operator!() const noexcept { return m_finished; }\n\n \/\/\/ Finish this stream. Call this before continuing to use the connection.\n \/** Consumes all remaining lines, and closes the stream.\n *\n * This may take a while if you're abandoning the stream before it's done, so\n * skip it in error scenarios where you're not planning to use the connection\n * again afterwards.\n *\/\n void complete();\n\n \/\/\/ Read one row into a tuple.\n \/** Converts the row's fields into the fields making up the tuple.\n *\n * For a column which can contain nulls, be sure to give the corresponding\n * tuple field a type which can be null. For example, to read a field as\n * @c int when it may contain nulls, read it as @c std::optional.\n * Using @c std::shared_ptr or @c std::unique_ptr will also work.\n *\/\n template stream_from &operator>>(Tuple &);\n\n \/\/\/ Doing this with a @c std::variant is going to be horrifically borked.\n template\n stream_from &operator>>(std::variant &) = delete;\n\n \/\/\/ Iterate over this stream. Supports range-based \"for\" loops.\n \/** Produces an input iterator over the stream.\n *\n * Do not call this yourself. Use it like \"for (auto data : stream.iter())\".\n *\/\n template[[nodiscard]] auto iter()\n {\n return pqxx::internal::stream_input_iteration{*this};\n }\n\n \/\/\/ Read a row. Return fields as views, valid until you read the next row.\n \/** Do not access the vector, or the storage referenced by the views, after\n * closing or completing the stream, or after reading a next row.\n *\n * A @c pqxx::zview is like a @c std::string_view, but with the added\n * guarantee that if its data pointer is non-null, the string is followed by\n * a terminating zero (which falls just outside the view itself).\n *\n * If any of the views' data pointer is null, that means that the\n * corresponding SQL field is null.\n *\/\n std::vector const &read_row();\n\n \/\/\/ Read a raw line of text from the COPY command.\n \/** @warn Do not use this unless you really know what you're doing. *\/\n raw_line get_raw_line();\n\nprivate:\n stream_from(\n transaction_base &tx, std::string_view table, std::string &&columns,\n from_table_t);\n\n template\n void extract_fields(Tuple &t, std::index_sequence) const\n {\n (extract_value(t), ...);\n }\n\n static std::string compose_query(\n transaction_base const &tx, std::string_view table,\n std::string const &columns);\n\n pqxx::internal::glyph_scanner_func *m_glyph_scanner;\n\n \/\/\/ Current row's fields' text, combined into one reusable string.\n std::string m_row;\n\n \/\/\/ The current row's fields.\n std::vector m_fields;\n\n bool m_finished = false;\n\n void close();\n\n template\n void extract_value(Tuple &) const;\n\n \/\/\/ Read a line of COPY data, write @c m_row and @c m_fields.\n void parse_line();\n};\n\n\ntemplate\ninline stream_from::stream_from(\n transaction_base &tb, from_table_t, std::string_view table_name,\n Columns const &columns) :\n stream_from{\n tb, from_table, table_name, std::begin(columns), std::end(columns)}\n{}\n\n\ntemplate\ninline stream_from::stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end) :\n stream_from{\n tx, table, separated_list(\",\", columns_begin, columns_end),\n from_table}\n{}\n\n\ntemplate inline stream_from &stream_from::operator>>(Tuple &t)\n{\n if (m_finished)\n return *this;\n constexpr auto tup_size{std::tuple_size_v};\n m_fields.reserve(tup_size);\n parse_line();\n if (m_finished)\n return *this;\n\n if (m_fields.size() != tup_size)\n throw usage_error{\n \"Tried to extract \" + to_string(tup_size) +\n \" field(s) from a stream of \" + to_string(m_fields.size()) + \".\"};\n\n extract_fields(t, std::make_index_sequence{});\n return *this;\n}\n\n\ntemplate\ninline void stream_from::extract_value(Tuple &t) const\n{\n using field_type = strip_t(t))>;\n using nullity = nullness;\n assert(index < m_fields.size());\n if constexpr (nullity::always_null)\n {\n if (m_fields[index].data() != nullptr)\n throw conversion_error{\"Streaming non-null value into null field.\"};\n }\n else if (m_fields[index].data() == nullptr)\n {\n if constexpr (nullity::has_null)\n std::get(t) = nullity::null();\n else\n internal::throw_null_conversion(type_name);\n }\n else\n {\n \/\/ Don't ever try to convert a non-null value to nullptr_t!\n std::get(t) = from_string(m_fields[index]);\n }\n}\n} \/\/ namespace pqxx\n\n#include \"pqxx\/internal\/compiler-internal-post.hxx\"\n#endif\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007-2008, Python File Format Interface\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of the Python File Format Interface\n project nor the names of its contributors may be used to endorse\n or promote products derived from this software without specific\n prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\nFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\nANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef __EXCEPTIONS_HPP\n#define __EXCEPTIONS_HPP\n\n#include \n\nnamespace pyffi {\n\n\/\/! Thrown on name mismatch.\nclass name_error : public std::runtime_error {\npublic:\n\tname_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on type mismatch.\nclass type_error : public std::runtime_error {\npublic:\n\ttype_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on value mismatch.\nclass value_error : public std::runtime_error {\npublic:\n\tvalue_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n}; \/\/ namespace pyffi\n\n#endif\nnew exceptions\/*\n\nCopyright (c) 2007-2008, Python File Format Interface\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of the Python File Format Interface\n project nor the names of its contributors may be used to endorse\n or promote products derived from this software without specific\n prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\nFOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\nANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef __EXCEPTIONS_HPP\n#define __EXCEPTIONS_HPP\n\n#include \n\nnamespace pyffi {\n\n\/\/! Thrown on name mismatch.\nclass name_error : public std::runtime_error {\npublic:\n\tname_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on type mismatch.\nclass type_error : public std::runtime_error {\npublic:\n\ttype_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on value mismatch.\nclass value_error : public std::runtime_error {\npublic:\n\tvalue_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on attribute mismatch.\nclass attribute_error : public std::runtime_error {\npublic:\n\tattribute_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n\/\/! Thrown on key mismatch.\nclass key_error : public std::runtime_error {\npublic:\n\tkey_error(const std::string & msg)\n\t\t\t: std::runtime_error(msg) {};\n};\n\n}; \/\/ namespace pyffi\n\n#endif\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SVTOOLS_SVPARSER_HXX\n#define INCLUDED_SVTOOLS_SVPARSER_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct SvParser_Impl;\nclass SvStream;\n\nenum SvParserState\n{\n SVPAR_ACCEPTED = 0,\n SVPAR_NOTSTARTED,\n SVPAR_WORKING,\n SVPAR_PENDING,\n SVPAR_WAITFORDATA,\n SVPAR_ERROR\n};\n\nclass SVT_DLLPUBLIC SvParser : public SvRefBase\n{\n DECL_STATIC_LINK( SvParser, NewDataRead, void* );\n\nprotected:\n SvStream& rInput;\n OUString aToken; \/\/ gescanntes Token\n sal_uLong nlLineNr; \/\/ akt. Zeilen Nummer\n sal_uLong nlLinePos; \/\/ akt. Spalten Nummer\n\n SvParser_Impl *pImplData; \/\/ interne Daten\n long nTokenValue; \/\/ zusaetzlicher Wert (RTF)\n bool bTokenHasValue; \/\/ indicates whether nTokenValue is valid\n SvParserState eState; \/\/ Status auch in abgl. Klassen\n\n rtl_TextEncoding eSrcEnc; \/\/ Source encoding\n\n sal_uLong nNextChPos;\n sal_Unicode nNextCh; \/\/ Akt. Zeichen fuer die \"lex\"\n\n\n bool bDownloadingFile : 1;\/\/ sal_True: Es wird gerade ein externes\n \/\/ File geladen. d.h. alle\n \/\/ DataAvailable Links muessen\n \/\/ ignoriert werden.\n \/\/ Wenn keibes der folgenden\n \/\/ Flags gesetzt ist, wird der\n \/\/ Stream als ANSI gelesen,\n \/\/ aber als CharSet DONTKNOW\n \/\/ zurueckgegeben.\n bool bUCS2BSrcEnc : 1; \/\/ oder als big-endian UCS2\n bool bSwitchToUCS2 : 1; \/\/ Umschalten des ist erlaubt\n\n bool bRTF_InTextRead : 1; \/\/ only for RTF-Parser!!!\n\n struct TokenStackType\n {\n OUString sToken;\n long nTokenValue;\n bool bTokenHasValue;\n int nTokenId;\n\n TokenStackType()\n : nTokenValue(0)\n , bTokenHasValue(0)\n , nTokenId(0)\n {\n }\n ~TokenStackType() { }\n };\n\n \/\/ Methoden fuer Token-Stack\n int SkipToken( short nCnt = -1 ); \/\/ n Tokens zurueck \"skippen\"\n TokenStackType* GetStackPtr( short nCnt );\n inline sal_uInt8 GetStackPos() const;\n\n \/\/ scanne das naechste Token:\n \/\/ Tokenstack abarbeiten und ggfs. _GetNextToken() rufen. Diese\n \/\/ ist fuers erkennen von neuen Token verantwortlich\n int GetNextToken();\n virtual int _GetNextToken() = 0;\n\n \/\/ wird fuer jedes Token gerufen, das in CallParser erkannt wird\n virtual void NextToken( int nToken );\n\n \/\/ zu Zeiten der SvRefBase-Ableitung darf nicht jeder loeschen\n virtual ~SvParser();\n\n void ClearTxtConvContext();\n\nprivate:\n TokenStackType* pTokenStack;\n TokenStackType *pTokenStackPos;\n sal_uInt8 nTokenStackSize, nTokenStackPos;\n\npublic:\n \/\/ Konstruktor\n SvParser( SvStream& rIn, sal_uInt8 nStackSize = 3 );\n\n virtual SvParserState CallParser() = 0; \/\/ Aufruf des Parsers\n\n inline SvParserState GetStatus() const { return eState; } \/\/ StatusInfo\n\n inline sal_uLong GetLineNr() const { return nlLineNr; }\n inline sal_uLong GetLinePos() const { return nlLinePos; }\n inline sal_uLong IncLineNr() { return ++nlLineNr; }\n inline sal_uLong IncLinePos() { return ++nlLinePos; }\n inline sal_uLong SetLineNr( sal_uLong nlNum ); \/\/ inline unten\n inline sal_uLong SetLinePos( sal_uLong nlPos ); \/\/ inline unten\n\n sal_Unicode GetNextChar();\n void RereadLookahead();\n\n inline bool IsParserWorking() const { return SVPAR_WORKING == eState; }\n\n Link GetAsynchCallLink() const\n { return STATIC_LINK( this, SvParser, NewDataRead ); }\n\n long CallAsyncCallLink() { return NewDataRead( this, 0 ); }\n\n \/\/ fuers asynchrone lesen aus dem SvStream\n \/*virtual*\/ void SaveState( int nToken );\n \/*virtual*\/ void RestoreState();\n virtual void Continue( int nToken );\n\n inline void SetDownloadingFile( bool bSet ) { bDownloadingFile = bSet; }\n inline bool IsDownloadingFile() const { return bDownloadingFile; }\n\n \/\/ Set\/get source encoding. The UCS2BEncoding flag is valid if source\n \/\/ encoding is UCS2. It specifies a big endian encoding.\n void SetSrcEncoding( rtl_TextEncoding eSrcEnc );\n rtl_TextEncoding GetSrcEncoding() const { return eSrcEnc; }\n\n void SetSrcUCS2BEncoding( bool bSet ) { bUCS2BSrcEnc = bSet; }\n bool IsSrcUCS2BEncoding() const { return bUCS2BSrcEnc; }\n\n \/\/ Darf der Zeichensatz auf UCS\/2 umgeschaltet werden, wenn\n \/\/ in den ersten beiden Zeichen im Stream eine BOM steht?\n void SetSwitchToUCS2( bool bSet ) { bSwitchToUCS2 = bSet; }\n bool IsSwitchToUCS2() const { return bSwitchToUCS2; }\n\n \/\/ Aus wie vielen Bytes betseht ein Zeichen\n inline sal_uInt16 GetCharSize() const;\n\n int GetSaveToken() const;\n\n \/\/ Aufbau einer Which-Map 'rWhichMap' aus einem Array von\n \/\/ 'pWhichIds' von Which-Ids. Es hat die Lange 'nWhichIds'.\n \/\/ Die Which-Map wird nicht geloescht.\n static void BuildWhichTbl( std::vector &rWhichMap,\n sal_uInt16 *pWhichIds,\n sal_uInt16 nWhichIds );\n};\n\n\n#ifndef GOODIES_DECL_SVPARSER_DEFINED\n#define GOODIES_DECL_SVPARSER_DEFINED\ntypedef tools::SvRef SvParserRef;\n#endif\n\ninline sal_uLong SvParser::SetLineNr( sal_uLong nlNum )\n{ sal_uLong nlOld = nlLineNr; nlLineNr = nlNum; return nlOld; }\n\ninline sal_uLong SvParser::SetLinePos( sal_uLong nlPos )\n{ sal_uLong nlOld = nlLinePos; nlLinePos = nlPos; return nlOld; }\n\ninline sal_uInt8 SvParser::GetStackPos() const\n{ return nTokenStackPos; }\n\ninline sal_uInt16 SvParser::GetCharSize() const\n{\n return (RTL_TEXTENCODING_UCS2 == eSrcEnc) ? 2 : 1;\n}\n\n\n\/*========================================================================\n *\n * SvKeyValue.\n *\n *======================================================================*\/\n\nclass SvKeyValue\n{\n \/** Representation.\n *\/\n OUString m_aKey;\n OUString m_aValue;\n\npublic:\n \/** Construction.\n *\/\n SvKeyValue (void)\n {}\n\n SvKeyValue (const OUString &rKey, const OUString &rValue)\n : m_aKey (rKey), m_aValue (rValue)\n {}\n\n SvKeyValue (const SvKeyValue &rOther)\n : m_aKey (rOther.m_aKey), m_aValue (rOther.m_aValue)\n {}\n\n \/** Assignment.\n *\/\n SvKeyValue& operator= (SvKeyValue &rOther)\n {\n m_aKey = rOther.m_aKey;\n m_aValue = rOther.m_aValue;\n return *this;\n }\n\n \/** Operation.\n *\/\n const OUString& GetKey (void) const { return m_aKey; }\n const OUString& GetValue (void) const { return m_aValue; }\n\n void SetKey (const OUString &rKey ) { m_aKey = rKey; }\n void SetValue (const OUString &rValue) { m_aValue = rValue; }\n};\n\n\/*========================================================================\n *\n * SvKeyValueIterator.\n *\n *======================================================================*\/\n\ntypedef boost::ptr_vector SvKeyValueList_Impl;\n\nclass SVT_DLLPUBLIC SvKeyValueIterator : public SvRefBase,\n private boost::noncopyable\n{\n \/** Representation.\n *\/\n SvKeyValueList_Impl* m_pList;\n sal_uInt16 m_nPos;\n\npublic:\n \/** Construction\/Destruction.\n *\/\n SvKeyValueIterator (void);\n virtual ~SvKeyValueIterator (void);\n\n \/** Operation.\n *\/\n virtual bool GetFirst (SvKeyValue &rKeyVal);\n virtual bool GetNext (SvKeyValue &rKeyVal);\n virtual void Append (const SvKeyValue &rKeyVal);\n};\n\ntypedef tools::SvRef SvKeyValueIteratorRef;\n\n#endif \/\/ INCLUDED_SVTOOLS_SVPARSER_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nWaE: implicit conversion of literal of type 'int' to 'bool'\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SVTOOLS_SVPARSER_HXX\n#define INCLUDED_SVTOOLS_SVPARSER_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct SvParser_Impl;\nclass SvStream;\n\nenum SvParserState\n{\n SVPAR_ACCEPTED = 0,\n SVPAR_NOTSTARTED,\n SVPAR_WORKING,\n SVPAR_PENDING,\n SVPAR_WAITFORDATA,\n SVPAR_ERROR\n};\n\nclass SVT_DLLPUBLIC SvParser : public SvRefBase\n{\n DECL_STATIC_LINK( SvParser, NewDataRead, void* );\n\nprotected:\n SvStream& rInput;\n OUString aToken; \/\/ gescanntes Token\n sal_uLong nlLineNr; \/\/ akt. Zeilen Nummer\n sal_uLong nlLinePos; \/\/ akt. Spalten Nummer\n\n SvParser_Impl *pImplData; \/\/ interne Daten\n long nTokenValue; \/\/ zusaetzlicher Wert (RTF)\n bool bTokenHasValue; \/\/ indicates whether nTokenValue is valid\n SvParserState eState; \/\/ Status auch in abgl. Klassen\n\n rtl_TextEncoding eSrcEnc; \/\/ Source encoding\n\n sal_uLong nNextChPos;\n sal_Unicode nNextCh; \/\/ Akt. Zeichen fuer die \"lex\"\n\n\n bool bDownloadingFile : 1;\/\/ sal_True: Es wird gerade ein externes\n \/\/ File geladen. d.h. alle\n \/\/ DataAvailable Links muessen\n \/\/ ignoriert werden.\n \/\/ Wenn keibes der folgenden\n \/\/ Flags gesetzt ist, wird der\n \/\/ Stream als ANSI gelesen,\n \/\/ aber als CharSet DONTKNOW\n \/\/ zurueckgegeben.\n bool bUCS2BSrcEnc : 1; \/\/ oder als big-endian UCS2\n bool bSwitchToUCS2 : 1; \/\/ Umschalten des ist erlaubt\n\n bool bRTF_InTextRead : 1; \/\/ only for RTF-Parser!!!\n\n struct TokenStackType\n {\n OUString sToken;\n long nTokenValue;\n bool bTokenHasValue;\n int nTokenId;\n\n TokenStackType()\n : nTokenValue(0)\n , bTokenHasValue(false)\n , nTokenId(0)\n {\n }\n ~TokenStackType() { }\n };\n\n \/\/ Methoden fuer Token-Stack\n int SkipToken( short nCnt = -1 ); \/\/ n Tokens zurueck \"skippen\"\n TokenStackType* GetStackPtr( short nCnt );\n inline sal_uInt8 GetStackPos() const;\n\n \/\/ scanne das naechste Token:\n \/\/ Tokenstack abarbeiten und ggfs. _GetNextToken() rufen. Diese\n \/\/ ist fuers erkennen von neuen Token verantwortlich\n int GetNextToken();\n virtual int _GetNextToken() = 0;\n\n \/\/ wird fuer jedes Token gerufen, das in CallParser erkannt wird\n virtual void NextToken( int nToken );\n\n \/\/ zu Zeiten der SvRefBase-Ableitung darf nicht jeder loeschen\n virtual ~SvParser();\n\n void ClearTxtConvContext();\n\nprivate:\n TokenStackType* pTokenStack;\n TokenStackType *pTokenStackPos;\n sal_uInt8 nTokenStackSize, nTokenStackPos;\n\npublic:\n \/\/ Konstruktor\n SvParser( SvStream& rIn, sal_uInt8 nStackSize = 3 );\n\n virtual SvParserState CallParser() = 0; \/\/ Aufruf des Parsers\n\n inline SvParserState GetStatus() const { return eState; } \/\/ StatusInfo\n\n inline sal_uLong GetLineNr() const { return nlLineNr; }\n inline sal_uLong GetLinePos() const { return nlLinePos; }\n inline sal_uLong IncLineNr() { return ++nlLineNr; }\n inline sal_uLong IncLinePos() { return ++nlLinePos; }\n inline sal_uLong SetLineNr( sal_uLong nlNum ); \/\/ inline unten\n inline sal_uLong SetLinePos( sal_uLong nlPos ); \/\/ inline unten\n\n sal_Unicode GetNextChar();\n void RereadLookahead();\n\n inline bool IsParserWorking() const { return SVPAR_WORKING == eState; }\n\n Link GetAsynchCallLink() const\n { return STATIC_LINK( this, SvParser, NewDataRead ); }\n\n long CallAsyncCallLink() { return NewDataRead( this, 0 ); }\n\n \/\/ fuers asynchrone lesen aus dem SvStream\n \/*virtual*\/ void SaveState( int nToken );\n \/*virtual*\/ void RestoreState();\n virtual void Continue( int nToken );\n\n inline void SetDownloadingFile( bool bSet ) { bDownloadingFile = bSet; }\n inline bool IsDownloadingFile() const { return bDownloadingFile; }\n\n \/\/ Set\/get source encoding. The UCS2BEncoding flag is valid if source\n \/\/ encoding is UCS2. It specifies a big endian encoding.\n void SetSrcEncoding( rtl_TextEncoding eSrcEnc );\n rtl_TextEncoding GetSrcEncoding() const { return eSrcEnc; }\n\n void SetSrcUCS2BEncoding( bool bSet ) { bUCS2BSrcEnc = bSet; }\n bool IsSrcUCS2BEncoding() const { return bUCS2BSrcEnc; }\n\n \/\/ Darf der Zeichensatz auf UCS\/2 umgeschaltet werden, wenn\n \/\/ in den ersten beiden Zeichen im Stream eine BOM steht?\n void SetSwitchToUCS2( bool bSet ) { bSwitchToUCS2 = bSet; }\n bool IsSwitchToUCS2() const { return bSwitchToUCS2; }\n\n \/\/ Aus wie vielen Bytes betseht ein Zeichen\n inline sal_uInt16 GetCharSize() const;\n\n int GetSaveToken() const;\n\n \/\/ Aufbau einer Which-Map 'rWhichMap' aus einem Array von\n \/\/ 'pWhichIds' von Which-Ids. Es hat die Lange 'nWhichIds'.\n \/\/ Die Which-Map wird nicht geloescht.\n static void BuildWhichTbl( std::vector &rWhichMap,\n sal_uInt16 *pWhichIds,\n sal_uInt16 nWhichIds );\n};\n\n\n#ifndef GOODIES_DECL_SVPARSER_DEFINED\n#define GOODIES_DECL_SVPARSER_DEFINED\ntypedef tools::SvRef SvParserRef;\n#endif\n\ninline sal_uLong SvParser::SetLineNr( sal_uLong nlNum )\n{ sal_uLong nlOld = nlLineNr; nlLineNr = nlNum; return nlOld; }\n\ninline sal_uLong SvParser::SetLinePos( sal_uLong nlPos )\n{ sal_uLong nlOld = nlLinePos; nlLinePos = nlPos; return nlOld; }\n\ninline sal_uInt8 SvParser::GetStackPos() const\n{ return nTokenStackPos; }\n\ninline sal_uInt16 SvParser::GetCharSize() const\n{\n return (RTL_TEXTENCODING_UCS2 == eSrcEnc) ? 2 : 1;\n}\n\n\n\/*========================================================================\n *\n * SvKeyValue.\n *\n *======================================================================*\/\n\nclass SvKeyValue\n{\n \/** Representation.\n *\/\n OUString m_aKey;\n OUString m_aValue;\n\npublic:\n \/** Construction.\n *\/\n SvKeyValue (void)\n {}\n\n SvKeyValue (const OUString &rKey, const OUString &rValue)\n : m_aKey (rKey), m_aValue (rValue)\n {}\n\n SvKeyValue (const SvKeyValue &rOther)\n : m_aKey (rOther.m_aKey), m_aValue (rOther.m_aValue)\n {}\n\n \/** Assignment.\n *\/\n SvKeyValue& operator= (SvKeyValue &rOther)\n {\n m_aKey = rOther.m_aKey;\n m_aValue = rOther.m_aValue;\n return *this;\n }\n\n \/** Operation.\n *\/\n const OUString& GetKey (void) const { return m_aKey; }\n const OUString& GetValue (void) const { return m_aValue; }\n\n void SetKey (const OUString &rKey ) { m_aKey = rKey; }\n void SetValue (const OUString &rValue) { m_aValue = rValue; }\n};\n\n\/*========================================================================\n *\n * SvKeyValueIterator.\n *\n *======================================================================*\/\n\ntypedef boost::ptr_vector SvKeyValueList_Impl;\n\nclass SVT_DLLPUBLIC SvKeyValueIterator : public SvRefBase,\n private boost::noncopyable\n{\n \/** Representation.\n *\/\n SvKeyValueList_Impl* m_pList;\n sal_uInt16 m_nPos;\n\npublic:\n \/** Construction\/Destruction.\n *\/\n SvKeyValueIterator (void);\n virtual ~SvKeyValueIterator (void);\n\n \/** Operation.\n *\/\n virtual bool GetFirst (SvKeyValue &rKeyVal);\n virtual bool GetNext (SvKeyValue &rKeyVal);\n virtual void Append (const SvKeyValue &rKeyVal);\n};\n\ntypedef tools::SvRef SvKeyValueIteratorRef;\n\n#endif \/\/ INCLUDED_SVTOOLS_SVPARSER_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * (1) Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * (2) Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * (3) Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\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\n#include \n#include \n#include \n\nusing virgil::crypto::VirgilByteArray;\nusing virgil::crypto::VirgilStreamCipher;\nusing virgil::crypto::stream::VirgilStreamDataSource;\nusing virgil::crypto::stream::VirgilStreamDataSink;\n\n\n\/\/ \/**\n\/\/ * @brief Add recipients from the configuration files to the cipher.\n\/\/ * @param configFiles - array of configuration files names.\n\/\/ * @param cipher - recipients added to.\n\/\/ * @return Number of added recipients.\n\/\/ *\/\n\/\/ static size_t add_recipients_configs(const std::vector& configFiles, VirgilStreamCipher* cipher);\n\n\/\/ *\n\/\/ * @brief Add recipients from the list to the cipher.\n\/\/ * @param recipients - array of recipients , where type can be [pass|vpk_file|email|phone|domain].\n\/\/ * @param cipher - recipients added to.\n\/\/ * @return Number of added recipients.\n\n\/\/ static size_t add_recipients(const std::vector& recipientsData, VirgilStreamCipher* cipher);\n\n\/\/ \/**\n\/\/ * @brief Add recipient to the cipher.\n\/\/ * @param recipientData - , where type can be [pass|key|email|phone|domain].\n\/\/ * @param cipher - recipients added to.\n\/\/ *\/\n\/\/ static void add_recipient(const std::string recipientIdType, const std::string recipientId,\n\/\/ VirgilStreamCipher* cipher);\n\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN encrypt_main\n#endif\n\nint MAIN(int argc, char **argv) {\n try {\n std::string description = \"Encrypt data for given recipients. Recipient can be represented\"\n \" either by the password, or by the Virgil Public Key.\\n\";\n\n std::vector examples;\n examples.push_back(\n \"Encrypt data for Bob identified by email:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc email:bob@domain.com\\n\");\n\n examples.push_back(\n \"Encrypt data for Bob and Tom identified by emails:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc email:bob@domain.com email:tom@domain.com\\n\");\n\n examples.push_back(\n \"Encrypt data for user identified by password::\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc pass:strong_password\\n\");\n\n examples.push_back(\n \"Encrypt data for user's identified by configuration file:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc -r friends.txt\\n\"\n \"'friends.txt':\\n\"\n \"#friends:\\n\"\n \"email:bob@domain.com\\n\"\n \"#Tom's public-key-id\\n\"\n \"id:45979aa4-2fdb-d166-85bc-5fab3ff2b2c2\\n\"\n );\n\n std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);\n\n \/\/ Parse arguments.\n TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());\n\n TCLAP::ValueArg inArg(\"i\", \"in\", \"Data to be encrypted. If omitted stdin is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg outArg(\"o\", \"out\", \"Encrypted data. If omitted stdout is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg contentInfoArg(\"c\", \"content-info\",\n \"Content info - meta information about encrypted data. If omitted becomes a part of\"\n \" the encrypted data.\", false, \"\", \"file\");\n\n TCLAP::MultiArg recipientsConfigArg(\"r\", \"recipients\",\n \"File that contains information about recipients. Each line \"\n \"can be either empty line, or comment line, or recipient defined in format:\\n\"\n \"[pass|id|vkey|email]:\\n\"\n \"where:\\n\"\n \"\\t* if pass, then - recipient's password;\\n\"\n \"\\t* if id, then - recipient's Virgil Public Key identifier;\\n\"\n \"\\t* if vkey, then - recipient's Virgil Public Key file\\n\\t stored locally;\\n\"\n \"\\t* if email, then - recipient's email;\\n\",\n false, \"file\");\n\n TCLAP::UnlabeledMultiArg recipientsArg(\"recipient\",\n \"Contains information about one recipient. \"\n \"Same as significant line in the recipients configuration file.\",\n false, \"recipient\", false);\n\n cmd.add(recipientsArg);\n cmd.add(recipientsConfigArg);\n cmd.add(contentInfoArg);\n cmd.add(outArg);\n cmd.add(inArg);\n cmd.parse(argc, argv);\n\n\n \/\/ \/\/ Create cipher\n \/\/ VirgilStreamCipher cipher;\n\n \/\/ \/\/ Add recipients\n \/\/ size_t addedRecipientsCount = 0;\n \/\/ addedRecipientsCount += add_recipients_configs(recipientsConfigArg.getValue(), &cipher);\n \/\/ addedRecipientsCount += add_recipients(recipientsArg.getValue(), &cipher);\n \/\/ if (addedRecipientsCount == 0) {\n \/\/ throw std::invalid_argument(\"no recipients are defined\");\n \/\/ }\n\n \/\/ \/\/ Prepare input\n \/\/ std::istream* inStream;\n \/\/ std::ifstream inFile;\n \/\/ if (inArg.getValue().empty() || inArg.getValue() == \"-\") {\n \/\/ inStream = &std::cin;\n \/\/ } else {\n \/\/ inFile.open(inArg.getValue(), std::ios::in | std::ios::binary);\n \/\/ if (!inFile) {\n \/\/ throw std::invalid_argument(\"can not read file: \" + inArg.getValue());\n \/\/ }\n \/\/ inStream = &inFile;\n \/\/ }\n\n \/\/ \/\/ Prepare output\n \/\/ std::ostream* outStream;\n \/\/ std::ofstream outFile;\n \/\/ if (outArg.getValue().empty()) {\n \/\/ outStream = &std::cout;\n \/\/ } else {\n \/\/ outFile.open(outArg.getValue(), std::ios::out | std::ios::binary);\n \/\/ if (!outFile) {\n \/\/ throw std::invalid_argument(\"can not write file: \" + outArg.getValue());\n \/\/ }\n \/\/ outStream = &outFile;\n \/\/ }\n\n \/\/ VirgilStreamDataSource dataSource(*inStream);\n \/\/ VirgilStreamDataSink dataSink(*outStream);\n\n \/\/ \/\/ Define whether embed content info or not\n \/\/ bool embedContentInfo = contentInfoArg.getValue().empty();\n \/\/ cipher.encrypt(dataSource, dataSink, embedContentInfo);\n\n \/\/ \/\/ Write content info to file if it was not embedded\n \/\/ if (!embedContentInfo) {\n \/\/ std::ofstream contentInfoFile(contentInfoArg.getValue(), std::ios::out | std::ios::binary);\n \/\/ if (!contentInfoFile) {\n \/\/ throw std::invalid_argument(\"can not write file: \" + contentInfoArg.getValue());\n \/\/ }\n \/\/ VirgilByteArray contentInfo = cipher.getContentInfo();\n \/\/ std::copy(contentInfo.begin(), contentInfo.end(), std::ostreambuf_iterator(contentInfoFile));\n \/\/ }\n\n } catch (TCLAP::ArgException& exception) {\n std::cerr << \"encrypt. Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n return EXIT_FAILURE;\n } catch (std::exception& exception) {\n std::cerr << \"encrypt. Error: \" << exception.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n\/\/ size_t add_recipients_configs(const std::vector& configFiles, VirgilStreamCipher* cipher) {\n\/\/ size_t addedRecipientsCount = 0;\n\/\/ for (const auto& configFile : configFiles) {\n\/\/ std::ifstream file(configFile);\n\/\/ if (!file) {\n\/\/ throw std::invalid_argument(\"recipientsConfigArg: can not read recipient config file: \" + configFile);\n\/\/ }\n\n\/\/ \/\/ Else\n\/\/ std::string recipientData;\n\/\/ unsigned long long numberLine = 0;\n\/\/ while (file >> std::ws && std::getline(file, recipientData)) {\n\/\/ ++numberLine;\n\/\/ if (!recipientData.empty() && recipientData[0] != '#') {\n\/\/ const auto recipientPair = virgil::cli::parsePair(recipientData);\n\/\/ checkFormatRecipientArg(recipientPair);\n\/\/ const std::string recipientIdType = recipientPair.first;\n\/\/ const std::string recipientId = recipientPair.second;\n\/\/ try {\n\/\/ add_recipient(recipientIdType, recipientId, cipher);\n\/\/ } catch (std::exception& exception) {\n\/\/ throw std::runtime_error(\"can not add recipient \" + recipientIdType + \":\" + recipientId +\n\/\/ \" from line \" + std::to_string(numberLine) + \" . Details: \" + exception.what());\n\/\/ }\n\/\/ ++addedRecipientsCount;\n\/\/ }\n\/\/ }\n\/\/ }\n\n\/\/ return addedRecipientsCount;\n\/\/ }\n\n\/\/ size_t add_recipients(const std::vector& recipientsData, VirgilStreamCipher* cipher) {\n\/\/ size_t addedRecipientsCount = 0;\n\/\/ for (const auto& recipientData : recipientsData) {\n\/\/ const auto recipientPair = virgil::cli::parsePair(recipientData);\n\/\/ const std::string recipientIdType = recipientPair.first;\n\/\/ const std::string recipientId = recipientPair.second;\n\/\/ try {\n\/\/ add_recipient(recipientIdType, recipientId, cipher);\n\/\/ } catch (std::exception& exception) {\n\/\/ throw std::invalid_argument(\"can not add recipient. Error \" + recipientIdType +\n\/\/ \":\" + recipientId + \"\\n\" + exception.what());\n\/\/ }\n\/\/ ++addedRecipientsCount;\n\/\/ }\n\/\/ return addedRecipientsCount;\n\/\/ }\n\n\/\/ void add_recipient(const std::string recipientIdType, const std::string recipientId,\n\/\/ VirgilStreamCipher* cipher) {\n\/\/ if (recipientIdType == \"pass\") {\n\/\/ VirgilByteArray pwd = virgil::crypto::str2bytes(recipientId);\n\/\/ cipher->addPasswordRecipient(pwd);\n\/\/ } else {\n\/\/ \/\/ Else recipientIdType [id|vkey|email]:\n\n\/\/ \/\/cipher->addKeyRecipient(publicKeyId, publicKey.key());\n\/\/ }\n\/\/ }\nAdd base: encrypt\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * (1) Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * (2) Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * (3) Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\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\n#include \n\n#include \n#include \n#include \n\nnamespace vcrypto = virgil::crypto;\nnamespace vsdk = virgil::sdk;\nnamespace vcli = virgil::cli;\n\n\/**\n * @brief Add recipients from the list to the cipher.\n * @param recipients - array of recipients , where type can be [pass|vpk_file|email|phone|domain].\n * @param cipher - recipients added to.\n * @return Number of added recipients.\n *\/\nstatic size_t add_recipients(const std::vector& recipientsData, vcrypto::VirgilStreamCipher* cipher);\n\n\/**\n * @brief Add recipient to the cipher.\n * @param recipientData - , where type can be [pass|key|email|phone|domain].\n * @param cipher - recipients added to.\n *\/\nstatic void add_recipient(const std::string& recipientType, const std::string& recipientValue,\n vcrypto::VirgilStreamCipher* cipher);\n\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN encrypt_main\n#endif\n\nint MAIN(int argc, char **argv) {\n try {\n std::string description = \"Encrypt data for given recipients. Recipient can be represented\"\n \" either by the password, or by the Virgil Public Key.\\n\";\n\n std::vector examples;\n examples.push_back(\n \"Encrypt data for Bob identified by email:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc email:bob@domain.com\\n\");\n\n examples.push_back(\n \"Encrypt data for Bob and Tom identified by emails:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc email:bob@domain.com email:tom@domain.com\\n\");\n\n examples.push_back(\n \"Encrypt data for user identified by password::\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc pass:strong_password\\n\");\n\n examples.push_back(\n \"Encrypt data for user's identified by configuration file:\\n\"\n \"virgil encrypt -i plain.txt -o plain.txt.enc -r friends.txt\\n\"\n \"'friends.txt':\\n\"\n \"#friends:\\n\"\n \"email:bob@domain.com\\n\"\n \"#Tom's public-key-id\\n\"\n \"id:45979aa4-2fdb-d166-85bc-5fab3ff2b2c2\\n\"\n );\n\n std::string descriptionMessage = virgil::cli::getDescriptionMessage(description, examples);\n\n \/\/ Parse arguments.\n TCLAP::CmdLine cmd(descriptionMessage, ' ', virgil::cli_version());\n\n TCLAP::ValueArg inArg(\"i\", \"in\", \"Data to be encrypted. If omitted stdin is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg outArg(\"o\", \"out\", \"Encrypted data. If omitted stdout is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg contentInfoArg(\"c\", \"content-info\",\n \"Content info - meta information about encrypted data. If omitted becomes a part of\"\n \" the encrypted data.\", false, \"\", \"file\");\n\n TCLAP::UnlabeledMultiArg recipientsArg(\"recipient\",\n \"Contains information about one recipient.\\n\"\n \"Format:\\n\"\n \"[pass|id|vcard|email]:\\n\"\n \"where:\\n\"\n \"\\t* if pass, then - recipient's password;\\n\"\n \"\\t* if id, then - recipient's Virgil Card identifier;\\n\"\n \"\\t* if vcard, then - recipient's Virgil Card\/Cards file\\n\\t stored locally;\\n\"\n \"\\t* if email, then - recipient's email;\\n\",\n false, \"recipient\", false);\n\n cmd.add(recipientsArg);\n cmd.add(contentInfoArg);\n cmd.add(outArg);\n cmd.add(inArg);\n cmd.parse(argc, argv);\n\n \/\/ Create cipher\n vcrypto::VirgilStreamCipher cipher;\n\n \/\/ Add recipients\n size_t addedRecipientsCount = 0;\n addedRecipientsCount += add_recipients(recipientsArg.getValue(), &cipher);\n if (addedRecipientsCount == 0) {\n throw std::invalid_argument(\"no recipients are defined\");\n }\n\n \/\/ Prepare input\n std::istream* inStream;\n std::ifstream inFile;\n if (inArg.getValue().empty() || inArg.getValue() == \"-\") {\n inStream = &std::cin;\n } else {\n inFile.open(inArg.getValue(), std::ios::in | std::ios::binary);\n if (!inFile) {\n throw std::invalid_argument(\"can not read file: \" + inArg.getValue());\n }\n inStream = &inFile;\n }\n\n \/\/ Prepare output\n std::ostream* outStream;\n std::ofstream outFile;\n if (outArg.getValue().empty()) {\n outStream = &std::cout;\n } else {\n outFile.open(outArg.getValue(), std::ios::out | std::ios::binary);\n if (!outFile) {\n throw std::invalid_argument(\"can not write file: \" + outArg.getValue());\n }\n outStream = &outFile;\n }\n\n vcrypto::stream::VirgilStreamDataSource dataSource(*inStream);\n vcrypto::stream::VirgilStreamDataSink dataSink(*outStream);\n\n \/\/ Define whether embed content info or not\n bool embedContentInfo = contentInfoArg.getValue().empty();\n cipher.encrypt(dataSource, dataSink, embedContentInfo);\n\n \/\/ Write content info to file if it was not embedded\n if (!embedContentInfo) {\n std::ofstream contentInfoFile(contentInfoArg.getValue(), std::ios::out | std::ios::binary);\n if (!contentInfoFile) {\n throw std::invalid_argument(\"can not write file: \" + contentInfoArg.getValue());\n }\n vcrypto::VirgilByteArray contentInfo = cipher.getContentInfo();\n std::copy(contentInfo.begin(), contentInfo.end(), std::ostreambuf_iterator(contentInfoFile));\n }\n\n } catch (TCLAP::ArgException& exception) {\n std::cerr << \"encrypt. Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n return EXIT_FAILURE;\n } catch (std::exception& exception) {\n std::cerr << \"encrypt. Error: \" << exception.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n\nsize_t add_recipients(const std::vector& recipientsData, vcrypto::VirgilStreamCipher* cipher) {\n size_t addedRecipientsCount = 0;\n for (const auto& recipientData : recipientsData) {\n auto recipientPair = virgil::cli::parsePair(recipientData);\n vcli::checkFormatRecipientArg(recipientPair);\n std::string recipientType = recipientPair.first;\n std::string recipientValue = recipientPair.second;\n try {\n add_recipient(recipientType, recipientValue, cipher);\n } catch (std::exception& exception) {\n throw std::invalid_argument(\"can not add recipient. Error \" + recipientType +\n \":\" + recipientValue + \"\\n\" + exception.what());\n }\n ++addedRecipientsCount;\n }\n return addedRecipientsCount;\n}\n\nvoid add_recipient(const std::string& recipientType, const std::string& recipientValue,\n vcrypto::VirgilStreamCipher* cipher) {\n if (recipientType == \"pass\") {\n vcrypto::VirgilByteArray pwd = virgil::crypto::str2bytes(recipientValue);\n cipher->addPasswordRecipient(pwd);\n } else {\n \/\/ Else recipientType [id|vcard|email]\n std::vector recipientsCard = vcli::getRecipientCards(recipientType, recipientValue);\n for (const auto& recipientCard : recipientsCard) {\n cipher->addKeyRecipient(\n vcrypto::str2bytes(recipientCard.getId()),\n recipientCard.getPublicKey().getKey()\n );\n }\n }\n}\n<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/profiler\/utils\/xplane_builder.h\"\n\n#include \"absl\/strings\/numbers.h\"\n#include \"tensorflow\/core\/profiler\/utils\/tf_op_utils.h\"\n\nnamespace tensorflow {\nnamespace profiler {\n\nXPlaneBuilder::XPlaneBuilder(XPlane* plane) : plane_(plane) {\n for (auto& iter : *plane->mutable_event_metadata()) {\n last_event_metadata_id_ =\n std::max(last_event_metadata_id_, iter.second.id());\n event_metadata_by_name_.try_emplace(iter.second.name(), &iter.second);\n }\n for (auto& iter : *plane->mutable_stat_metadata()) {\n last_stat_metadata_id_ =\n std::max(last_stat_metadata_id_, iter.second.id());\n stat_metadata_by_name_.try_emplace(iter.second.name(), &iter.second);\n }\n for (XLine& line : *plane->mutable_lines()) {\n lines_by_id_.try_emplace(line.id(), &line);\n }\n}\n\nXEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(int64 metadata_id) {\n XEventMetadata& metadata = (*plane_->mutable_event_metadata())[metadata_id];\n metadata.set_id(metadata_id);\n return &metadata;\n}\n\n\/\/ Returns XEventMetadata for the given event name.\nXEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(\n absl::string_view name) {\n XEventMetadata*& metadata = event_metadata_by_name_[name];\n if (metadata == nullptr) {\n metadata =\n XPlaneBuilder::GetOrCreateEventMetadata(++last_event_metadata_id_);\n metadata->set_name(std::string(name));\n if (std::string event_name = TfOpEventName(name); event_name != name) {\n metadata->set_display_name(std::move(event_name));\n }\n }\n return metadata;\n}\n\nXStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(int64 metadata_id) {\n XStatMetadata& metadata = (*plane_->mutable_stat_metadata())[metadata_id];\n metadata.set_id(metadata_id);\n return &metadata;\n}\n\n\/\/ Returns XStatMetadata for the given stat name.\nXStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(absl::string_view name) {\n XStatMetadata*& metadata = stat_metadata_by_name_[name];\n if (metadata == nullptr) {\n metadata = XPlaneBuilder::GetOrCreateStatMetadata(++last_stat_metadata_id_);\n metadata->set_name(std::string(name));\n }\n return metadata;\n}\n\nXLine* XPlaneBuilder::AddLine(int64 line_id) {\n XLine*& line = lines_by_id_[line_id];\n if (line == nullptr) {\n line = RawPlane()->add_lines();\n line->set_id(line_id);\n }\n return line;\n}\n\n\/\/ Returns a builder for the line with the given id. Creates a new line if the\n\/\/ id was unused, otherwise the builder will add events to an existing line.\nXLineBuilder XPlaneBuilder::GetOrCreateLine(int64 line_id) {\n return XLineBuilder(AddLine(line_id));\n}\n\nXEventBuilder XLineBuilder::AddEvent(const XEventMetadata& metadata) {\n XEvent* event = line_->add_events();\n event->set_metadata_id(metadata.id());\n return XEventBuilder(line_, event);\n}\n\nXStat* XEventBuilder::AddStat(const XStatMetadata& metadata) {\n XStat* stat = event_->add_stats();\n stat->set_metadata_id(metadata.id());\n return stat;\n}\n\nvoid XEventBuilder::ParseAndAddStatValue(const XStatMetadata& metadata,\n absl::string_view value) {\n int64 int_value;\n uint64 uint_value;\n double double_value;\n if (absl::SimpleAtoi(value, &int_value)) {\n AddStatValue(metadata, int_value);\n } else if (absl::SimpleAtoi(value, &uint_value)) {\n AddStatValue(metadata, uint_value);\n } else if (absl::SimpleAtod(value, &double_value)) {\n AddStatValue(metadata, double_value);\n } else {\n AddStatValue(metadata, value);\n }\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\nfix ROCM build.\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/profiler\/utils\/xplane_builder.h\"\n\n#include \"absl\/strings\/numbers.h\"\n#include \"tensorflow\/core\/profiler\/utils\/tf_op_utils.h\"\n\nnamespace tensorflow {\nnamespace profiler {\n\nXPlaneBuilder::XPlaneBuilder(XPlane* plane) : plane_(plane) {\n for (auto& iter : *plane->mutable_event_metadata()) {\n last_event_metadata_id_ =\n std::max(last_event_metadata_id_, iter.second.id());\n event_metadata_by_name_.try_emplace(iter.second.name(), &iter.second);\n }\n for (auto& iter : *plane->mutable_stat_metadata()) {\n last_stat_metadata_id_ =\n std::max(last_stat_metadata_id_, iter.second.id());\n stat_metadata_by_name_.try_emplace(iter.second.name(), &iter.second);\n }\n for (XLine& line : *plane->mutable_lines()) {\n lines_by_id_.try_emplace(line.id(), &line);\n }\n}\n\nXEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(int64 metadata_id) {\n XEventMetadata& metadata = (*plane_->mutable_event_metadata())[metadata_id];\n metadata.set_id(metadata_id);\n return &metadata;\n}\n\n\/\/ Returns XEventMetadata for the given event name.\nXEventMetadata* XPlaneBuilder::GetOrCreateEventMetadata(\n absl::string_view name) {\n XEventMetadata*& metadata = event_metadata_by_name_[name];\n if (metadata == nullptr) {\n metadata =\n XPlaneBuilder::GetOrCreateEventMetadata(++last_event_metadata_id_);\n metadata->set_name(std::string(name));\n std::string event_name = TfOpEventName(name);\n if (event_name != name) {\n metadata->set_display_name(std::move(event_name));\n }\n }\n return metadata;\n}\n\nXStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(int64 metadata_id) {\n XStatMetadata& metadata = (*plane_->mutable_stat_metadata())[metadata_id];\n metadata.set_id(metadata_id);\n return &metadata;\n}\n\n\/\/ Returns XStatMetadata for the given stat name.\nXStatMetadata* XPlaneBuilder::GetOrCreateStatMetadata(absl::string_view name) {\n XStatMetadata*& metadata = stat_metadata_by_name_[name];\n if (metadata == nullptr) {\n metadata = XPlaneBuilder::GetOrCreateStatMetadata(++last_stat_metadata_id_);\n metadata->set_name(std::string(name));\n }\n return metadata;\n}\n\nXLine* XPlaneBuilder::AddLine(int64 line_id) {\n XLine*& line = lines_by_id_[line_id];\n if (line == nullptr) {\n line = RawPlane()->add_lines();\n line->set_id(line_id);\n }\n return line;\n}\n\n\/\/ Returns a builder for the line with the given id. Creates a new line if the\n\/\/ id was unused, otherwise the builder will add events to an existing line.\nXLineBuilder XPlaneBuilder::GetOrCreateLine(int64 line_id) {\n return XLineBuilder(AddLine(line_id));\n}\n\nXEventBuilder XLineBuilder::AddEvent(const XEventMetadata& metadata) {\n XEvent* event = line_->add_events();\n event->set_metadata_id(metadata.id());\n return XEventBuilder(line_, event);\n}\n\nXStat* XEventBuilder::AddStat(const XStatMetadata& metadata) {\n XStat* stat = event_->add_stats();\n stat->set_metadata_id(metadata.id());\n return stat;\n}\n\nvoid XEventBuilder::ParseAndAddStatValue(const XStatMetadata& metadata,\n absl::string_view value) {\n int64 int_value;\n uint64 uint_value;\n double double_value;\n if (absl::SimpleAtoi(value, &int_value)) {\n AddStatValue(metadata, int_value);\n } else if (absl::SimpleAtoi(value, &uint_value)) {\n AddStatValue(metadata, uint_value);\n } else if (absl::SimpleAtod(value, &double_value)) {\n AddStatValue(metadata, double_value);\n } else {\n AddStatValue(metadata, value);\n }\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\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 * @file\n * @brief IronBee — CLIPP Configuration Parser Implementation\n *\n * @author Christopher Alfeld \n *\/\n\n#include \"configuration_parser.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\n\nBOOST_FUSION_ADAPT_STRUCT(\n IronBee::CLIPP::ConfigurationParser::component_t,\n (string, name)\n (string, arg)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n IronBee::CLIPP::ConfigurationParser::chain_t,\n (IronBee::CLIPP::ConfigurationParser::component_t, base)\n (IronBee::CLIPP::ConfigurationParser::component_vec_t, modifiers)\n)\n\nnamespace IronBee {\nnamespace CLIPP {\nnamespace ConfigurationParser {\n\nnamespace {\n\nchain_vec_t parse(const std::string& input)\n{\n using namespace boost::spirit;\n\n using ascii::char_;\n using ascii::space;\n using qi::lit;\n using qi::_1;\n using qi::_val;\n using qi::lexeme;\n using qi::omit;\n using boost::phoenix::push_back;\n\n typedef string::const_iterator iterator;\n typedef qi::rule string_rule;\n typedef qi::rule component_rule;\n typedef qi::rule chain_rule;\n typedef qi::rule component_vec_rule;\n typedef qi::rule chains_rule;\n\n string_rule quoted_string = lit('\"') >> +(char_ - '\"') >> '\"';\n string_rule cfg_string = lexeme[quoted_string\n | +(char_ - '@' - space)];\n\n component_rule component = +(char_ - ':' - space) >> -(':' >> cfg_string);\n component_rule modifier = lit('@') >> component;\n component_rule base = component;\n\n component_vec_rule modifiers =\n *(omit[*space] >> modifier >> omit[*space]);\n chain_rule chain = base >> omit[*space] >> modifiers;\n\n chains_rule chains = *(omit[*space] >> chain >> omit[*space]);\n\n chain_vec_t result;\n iterator begin = input.begin();\n iterator end = input.end();\n\n bool success = qi::parse(\n begin, end,\n chains,\n result\n );\n\n cout << result.size() << endl;\n if (! success) {\n size_t pos = begin - input.begin();\n throw runtime_error(\n \"Parsing failed, next text = \" + input.substr(pos, 100)\n );\n }\n if (begin != end) {\n size_t pos = begin - input.begin();\n throw runtime_error(\n \"Parsing did not consumer all input. next text = \" +\n input.substr(pos, 100)\n );\n }\n\n return result;\n}\n\n} \/\/ Anonymous\n\nchain_vec_t parse_string(const std::string& input)\n{\n return parse(input);\n}\n\nchain_vec_t parse_file(const std::string& path)\n{\n ifstream in(path.c_str());\n if (! in) {\n throw runtime_error(\"Could not open \" + path + \" for reading.\");\n }\n string input;\n string line;\n while (in) {\n getline(in, line);\n size_t pos = line.find_first_not_of(' ');\n if (pos != string::npos && line[pos] != '#') {\n input += line;\n input += \" \";\n }\n }\n\n return parse_string(input);\n}\n\n} \/\/ ConfigurationParser\n} \/\/ CLIPP\n} \/\/ IronBee\nclipp: Remove debugging code.\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\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 * @file\n * @brief IronBee — CLIPP Configuration Parser Implementation\n *\n * @author Christopher Alfeld \n *\/\n\n#include \"configuration_parser.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\n\nBOOST_FUSION_ADAPT_STRUCT(\n IronBee::CLIPP::ConfigurationParser::component_t,\n (string, name)\n (string, arg)\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n IronBee::CLIPP::ConfigurationParser::chain_t,\n (IronBee::CLIPP::ConfigurationParser::component_t, base)\n (IronBee::CLIPP::ConfigurationParser::component_vec_t, modifiers)\n)\n\nnamespace IronBee {\nnamespace CLIPP {\nnamespace ConfigurationParser {\n\nnamespace {\n\nchain_vec_t parse(const std::string& input)\n{\n using namespace boost::spirit;\n\n using ascii::char_;\n using ascii::space;\n using qi::lit;\n using qi::_1;\n using qi::_val;\n using qi::lexeme;\n using qi::omit;\n using boost::phoenix::push_back;\n\n typedef string::const_iterator iterator;\n typedef qi::rule string_rule;\n typedef qi::rule component_rule;\n typedef qi::rule chain_rule;\n typedef qi::rule component_vec_rule;\n typedef qi::rule chains_rule;\n\n string_rule quoted_string = lit('\"') >> +(char_ - '\"') >> '\"';\n string_rule cfg_string = lexeme[quoted_string\n | +(char_ - '@' - space)];\n\n component_rule component = +(char_ - ':' - space) >> -(':' >> cfg_string);\n component_rule modifier = lit('@') >> component;\n component_rule base = component;\n\n component_vec_rule modifiers =\n *(omit[*space] >> modifier >> omit[*space]);\n chain_rule chain = base >> omit[*space] >> modifiers;\n\n chains_rule chains = *(omit[*space] >> chain >> omit[*space]);\n\n chain_vec_t result;\n iterator begin = input.begin();\n iterator end = input.end();\n\n bool success = qi::parse(\n begin, end,\n chains,\n result\n );\n\n if (! success) {\n size_t pos = begin - input.begin();\n throw runtime_error(\n \"Parsing failed, next text = \" + input.substr(pos, 100)\n );\n }\n if (begin != end) {\n size_t pos = begin - input.begin();\n throw runtime_error(\n \"Parsing did not consumer all input. next text = \" +\n input.substr(pos, 100)\n );\n }\n\n return result;\n}\n\n} \/\/ Anonymous\n\nchain_vec_t parse_string(const std::string& input)\n{\n return parse(input);\n}\n\nchain_vec_t parse_file(const std::string& path)\n{\n ifstream in(path.c_str());\n if (! in) {\n throw runtime_error(\"Could not open \" + path + \" for reading.\");\n }\n string input;\n string line;\n while (in) {\n getline(in, line);\n size_t pos = line.find_first_not_of(' ');\n if (pos != string::npos && line[pos] != '#') {\n input += line;\n input += \" \";\n }\n }\n\n return parse_string(input);\n}\n\n} \/\/ ConfigurationParser\n} \/\/ CLIPP\n} \/\/ IronBee\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 Tmplt \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"components\/downloader.hpp\"\n#include \"runes.hpp\"\n#include \"utils.hpp\"\n\nnamespace bookwyrm {\n\ndownloader::downloader(string download_dir)\n : pbar(true, true), dldir(download_dir)\n{\n curl_global_init(CURL_GLOBAL_ALL);\n curl = curl_easy_init();\n if (!curl) throw component_error(\"curl could not initialize\");\n\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n curl_easy_setopt(curl, CURLOPT_USERAGENT,\n \"Mozilla\/5.0 (X11; Linux x86_64; rv:57.0) Gecko\/20100101 Firefox\/57.0\");\n\n \/* Complete the connection phase within 30s. *\/\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);\n\n \/* Consider HTTP codes >=400 as errors. This option is NOT fail-safe. *\/\n curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);\n\n \/* Set callback function for writing data. *\/\n \/* curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloader::write_data); *\/\n\n \/* Set callback function for progress metering. *\/\n curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, downloader::progress_callback);\n curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);\n curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n\n \/*\n * Assume there is a connection error and abort transfer with CURLE_OPERATION_TIMEDOUT\n * if the download speed is under 30B\/s for 60s.\n *\/\n curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 30);\n curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 60);\n\n \/* Enable a verbose output. *\/\n \/* curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); *\/\n \/* curl_easy_setopt(curl,CURLOPT_MAX_RECV_SPEED_LARGE, 1024 * 50); *\/\n\n \/* std::cout << rune::vt100::hide_cursor; *\/\n}\n\ndownloader::~downloader()\n{\n curl_easy_cleanup(curl);\n curl_global_cleanup();\n\n \/* std::cout << rune::vt100::show_cursor; *\/\n}\n\nfs::path downloader::generate_filename(const bookwyrm::item &item)\n{\n \/\/ TODO: remove hardcodedness\n string ext = \".txt\";\n\n const fs::path base = dldir \/ fmt::format(\"{} - {} ({})\",\n utils::vector_to_string(item.nonexacts.authors),\n item.nonexacts.title, item.exacts.year);\n\n \/* If filename.ext doesn't exists, we use that. *\/\n if (auto candidate = base; !fs::exists(candidate.concat(ext)))\n return candidate;\n\n \/*\n * Otherwise, we generate a new filename on the form\n * filename.n.ext, which doesn't already exists, and where\n * n is an unsigned integer.\n *\n * That is, the filename chain generated is:\n * filename.1.ext\n * filename.2.ext\n * filename.3.ext\n * etc.\n *\/\n\n size_t i = 0;\n fs::path candidate;\n\n do {\n candidate = base;\n candidate.concat(fmt::format(\".{}{}\", ++i, ext));\n } while (fs::exists(candidate));\n\n return candidate;\n}\n\nbool downloader::sync_download(vector items)\n{\n bool any_success = false;\n\n for (const auto &item : items) {\n auto filename = generate_filename(item);\n bool success = false;\n\n for (const auto &url : item.misc.uris) {\n curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\n std::FILE *out = std::fopen(filename.c_str(), \"wb\");\n if (out == NULL) {\n \/* TODO: test this output *\/\n throw component_error(fmt::format(\"unable to create this file: {}; reason: {}\",\n filename.string(), std::strerror(errno)));\n }\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, out);\n\n if (auto res = curl_easy_perform(curl); res != CURLE_OK) {\n fmt::print(stderr, \"error: item download failed: {}\\n\", curl_easy_strerror(res));\n std::fclose(out);\n } else {\n std::fclose(out);\n any_success = success = true;\n\n \/* That source worked, so there is no need to download from the others. *\/\n break;\n }\n }\n\n if (!success) {\n fmt::print(stderr, \"error: no good sources for this item: {} - {} ({}). Sorry!\\n\",\n utils::vector_to_string(item.nonexacts.authors),\n item.nonexacts.title, item.exacts.year);\n }\n }\n\n return any_success;\n}\n\nint downloader::progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)\n{\n \/* We never upload anything. *\/\n (void)ulnow;\n (void)ultotal;\n\n \/*\n * dltotal: the size of the file being downloaded (in bytes)\n * dlnow: how much have been downloaded thus far (in bytes)\n *\/\n downloader *d = static_cast(clientp);\n\n double rate;\n if (curl_easy_getinfo(d->curl, CURLINFO_SPEED_DOWNLOAD, &rate) != CURLE_OK)\n rate = std::numeric_limits::quiet_NaN();\n\n if (d->timer.ms_since_last_update() >= 100 || dlnow == dltotal) {\n d->timer.reset();\n\n time::duration eta((dltotal - dlnow) \/ rate);\n std::stringstream eta_ss;\n if (eta.hours() > 0) {\n eta_ss << eta.hours() << \"h \"\n << std::setfill('0') << std::setw(2) << eta.minutes() << \"m \"\n << std::setfill('0') << std::setw(2) << eta.seconds() << \"s\";\n } else if (eta.minutes() > 0) {\n eta_ss << eta.minutes() << \"m \"\n << std::setfill('0') << std::setw(2) << eta.seconds() << \"s\";\n } else {\n eta_ss << eta.seconds() << \"s\";\n }\n\n \/* Download rate unit conversion. *\/\n const string rate_unit = [&rate]() {\n constexpr auto k = 1024,\n M = 1048576;\n\n if (rate > M) {\n rate \/= M;\n return \"MB\/s\";\n } else {\n rate \/= k;\n return \"kB\/s\";\n }\n }();\n\n const double fraction = static_cast(dlnow) \/ static_cast(dltotal);\n fmt::print(\"{}\\r {:.0f}% \", rune::vt100::erase_line, fraction * 100);\n\n string status_text = fmt::format(\" {dlnow:.2f}\/{dltotal:.2f}MB @ {rate:.2f}{unit} ETA: {eta}\\r\",\n fmt::arg(\"dlnow\", static_cast(dlnow)\/1024\/1024),\n fmt::arg(\"dltotal\", static_cast(dltotal)\/1024\/1024),\n fmt::arg(\"rate\", rate),\n fmt::arg(\"unit\", rate_unit),\n fmt::arg(\"eta\", eta_ss.str()));\n\n \/* Draw the progress bar. *\/\n const int term_width = []() {\n struct winsize w;\n ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);\n return w.ws_col;\n }();\n\n int bar_length = 26,\n min_bar_length = 5,\n status_text_length = status_text.length() + 6;\n\n if (status_text_length + bar_length > term_width)\n bar_length -= status_text_length + bar_length - term_width;\n\n \/* Don't draw the progress bar if length is less than min_bar_length. *\/\n if (bar_length >= min_bar_length)\n d->pbar.draw(bar_length, fraction);\n\n std::cout << status_text << std::flush;\n }\n\n return 0;\n}\n\nstring progressbar::build_bar(unsigned int length, double fraction)\n{\n std::ostringstream ss;\n\n \/* Validation *\/\n if (!std::isnormal(fraction) || fraction < 0.0)\n fraction = 0.0;\n else if (fraction > 1.0)\n fraction = 1.0;\n\n const double bar_part = fraction * length;\n\n \/* How many whole unicode characters should we print? *\/\n const unsigned int whole_bar_chars = std::floor(bar_part);\n\n \/* If the bar isn't full, which unicode character should we use? *\/\n const unsigned int partial_bar_char_idx = std::floor((bar_part - whole_bar_chars) * 8.0);\n\n using namespace rune;\n\n if (use_colour_)\n ss << vt100::bar_colour;\n\n \/* The left border *\/\n ss << (use_unicode_ ? bar::unicode::left_border : bar::left_border);\n\n \/* The filled-in part *\/\n unsigned i = 0;\n for (; i < whole_bar_chars; i++)\n ss << (use_unicode_ ? bar::unicode::fraction[8] : bar::tick);\n\n if (i < length) {\n \/* The last filled in part, if needed. *\/\n ss << (use_unicode_ ? bar::unicode::fraction[partial_bar_char_idx]\n : bar::empty_fill);\n }\n\n \/* The not-filled-in part *\/\n for (i = whole_bar_chars + 1; i < length; i++)\n ss << bar::empty_fill;\n\n \/* The bar's right border *\/\n ss << (use_unicode_ ? bar::unicode::right_border : bar::right_border);\n\n if (use_colour_)\n ss << vt100::reset_colour;\n\n return ss.str();\n}\n\n}\ndownloader: remove hardcodedness\/*\n * Copyright (C) 2017 Tmplt \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"components\/downloader.hpp\"\n#include \"runes.hpp\"\n#include \"utils.hpp\"\n\nnamespace bookwyrm {\n\ndownloader::downloader(string download_dir)\n : pbar(true, true), dldir(download_dir)\n{\n curl_global_init(CURL_GLOBAL_ALL);\n curl = curl_easy_init();\n if (!curl) throw component_error(\"curl could not initialize\");\n\n curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n curl_easy_setopt(curl, CURLOPT_USERAGENT,\n \"Mozilla\/5.0 (X11; Linux x86_64; rv:57.0) Gecko\/20100101 Firefox\/57.0\");\n\n \/* Complete the connection phase within 30s. *\/\n curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);\n\n \/* Consider HTTP codes >=400 as errors. This option is NOT fail-safe. *\/\n curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);\n\n \/* Set callback function for writing data. *\/\n \/* curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, downloader::write_data); *\/\n\n \/* Set callback function for progress metering. *\/\n curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, downloader::progress_callback);\n curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this);\n curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);\n\n \/*\n * Assume there is a connection error and abort transfer with CURLE_OPERATION_TIMEDOUT\n * if the download speed is under 30B\/s for 60s.\n *\/\n curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 30);\n curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 60);\n\n \/* Enable a verbose output. *\/\n \/* curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); *\/\n \/* curl_easy_setopt(curl,CURLOPT_MAX_RECV_SPEED_LARGE, 1024 * 50); *\/\n\n \/* std::cout << rune::vt100::hide_cursor; *\/\n}\n\ndownloader::~downloader()\n{\n curl_easy_cleanup(curl);\n curl_global_cleanup();\n\n \/* std::cout << rune::vt100::show_cursor; *\/\n}\n\nfs::path downloader::generate_filename(const bookwyrm::item &item)\n{\n const fs::path base = dldir \/ fmt::format(\"{} - {} ({}).\",\n utils::vector_to_string(item.nonexacts.authors),\n item.nonexacts.title, item.exacts.year);\n\n \/* If filename.ext doesn't exists, we use that. *\/\n if (auto candidate = base; !fs::exists(candidate.concat(item.exacts.extension)))\n return candidate;\n\n \/*\n * Otherwise, we generate a new filename on the form\n * filename.n.ext, which doesn't already exists, and where\n * n is an unsigned integer.\n *\n * That is, the filename chain generated is:\n * filename.1.ext\n * filename.2.ext\n * filename.3.ext\n * etc.\n *\/\n\n size_t i = 0;\n fs::path candidate;\n\n do {\n candidate = base;\n candidate.concat(fmt::format(\".{}.{}\", ++i, item.exacts.extension));\n } while (fs::exists(candidate));\n\n return candidate;\n}\n\nbool downloader::sync_download(vector items)\n{\n bool any_success = false;\n\n for (const auto &item : items) {\n auto filename = generate_filename(item);\n bool success = false;\n\n for (const auto &url : item.misc.uris) {\n curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\n std::FILE *out = std::fopen(filename.c_str(), \"wb\");\n if (out == NULL) {\n \/* TODO: test this output *\/\n throw component_error(fmt::format(\"unable to create this file: {}; reason: {}\",\n filename.string(), std::strerror(errno)));\n }\n curl_easy_setopt(curl, CURLOPT_WRITEDATA, out);\n\n if (auto res = curl_easy_perform(curl); res != CURLE_OK) {\n fmt::print(stderr, \"error: item download failed: {}\\n\", curl_easy_strerror(res));\n std::fclose(out);\n } else {\n std::fclose(out);\n any_success = success = true;\n\n \/* That source worked, so there is no need to download from the others. *\/\n break;\n }\n }\n\n if (!success) {\n fmt::print(stderr, \"error: no good sources for this item: {} - {} ({}). Sorry!\\n\",\n utils::vector_to_string(item.nonexacts.authors),\n item.nonexacts.title, item.exacts.year);\n }\n }\n\n return any_success;\n}\n\nint downloader::progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)\n{\n \/* We never upload anything. *\/\n (void)ulnow;\n (void)ultotal;\n\n \/*\n * dltotal: the size of the file being downloaded (in bytes)\n * dlnow: how much have been downloaded thus far (in bytes)\n *\/\n downloader *d = static_cast(clientp);\n\n double rate;\n if (curl_easy_getinfo(d->curl, CURLINFO_SPEED_DOWNLOAD, &rate) != CURLE_OK)\n rate = std::numeric_limits::quiet_NaN();\n\n if (d->timer.ms_since_last_update() >= 100 || dlnow == dltotal) {\n d->timer.reset();\n\n time::duration eta((dltotal - dlnow) \/ rate);\n std::stringstream eta_ss;\n if (eta.hours() > 0) {\n eta_ss << eta.hours() << \"h \"\n << std::setfill('0') << std::setw(2) << eta.minutes() << \"m \"\n << std::setfill('0') << std::setw(2) << eta.seconds() << \"s\";\n } else if (eta.minutes() > 0) {\n eta_ss << eta.minutes() << \"m \"\n << std::setfill('0') << std::setw(2) << eta.seconds() << \"s\";\n } else {\n eta_ss << eta.seconds() << \"s\";\n }\n\n \/* Download rate unit conversion. *\/\n const string rate_unit = [&rate]() {\n constexpr auto k = 1024,\n M = 1048576;\n\n if (rate > M) {\n rate \/= M;\n return \"MB\/s\";\n } else {\n rate \/= k;\n return \"kB\/s\";\n }\n }();\n\n const double fraction = static_cast(dlnow) \/ static_cast(dltotal);\n fmt::print(\"{}\\r {:.0f}% \", rune::vt100::erase_line, fraction * 100);\n\n string status_text = fmt::format(\" {dlnow:.2f}\/{dltotal:.2f}MB @ {rate:.2f}{unit} ETA: {eta}\\r\",\n fmt::arg(\"dlnow\", static_cast(dlnow)\/1024\/1024),\n fmt::arg(\"dltotal\", static_cast(dltotal)\/1024\/1024),\n fmt::arg(\"rate\", rate),\n fmt::arg(\"unit\", rate_unit),\n fmt::arg(\"eta\", eta_ss.str()));\n\n \/* Draw the progress bar. *\/\n const int term_width = []() {\n struct winsize w;\n ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);\n return w.ws_col;\n }();\n\n int bar_length = 26,\n min_bar_length = 5,\n status_text_length = status_text.length() + 6;\n\n if (status_text_length + bar_length > term_width)\n bar_length -= status_text_length + bar_length - term_width;\n\n \/* Don't draw the progress bar if length is less than min_bar_length. *\/\n if (bar_length >= min_bar_length)\n d->pbar.draw(bar_length, fraction);\n\n std::cout << status_text << std::flush;\n }\n\n return 0;\n}\n\nstring progressbar::build_bar(unsigned int length, double fraction)\n{\n std::ostringstream ss;\n\n \/* Validation *\/\n if (!std::isnormal(fraction) || fraction < 0.0)\n fraction = 0.0;\n else if (fraction > 1.0)\n fraction = 1.0;\n\n const double bar_part = fraction * length;\n\n \/* How many whole unicode characters should we print? *\/\n const unsigned int whole_bar_chars = std::floor(bar_part);\n\n \/* If the bar isn't full, which unicode character should we use? *\/\n const unsigned int partial_bar_char_idx = std::floor((bar_part - whole_bar_chars) * 8.0);\n\n using namespace rune;\n\n if (use_colour_)\n ss << vt100::bar_colour;\n\n \/* The left border *\/\n ss << (use_unicode_ ? bar::unicode::left_border : bar::left_border);\n\n \/* The filled-in part *\/\n unsigned i = 0;\n for (; i < whole_bar_chars; i++)\n ss << (use_unicode_ ? bar::unicode::fraction[8] : bar::tick);\n\n if (i < length) {\n \/* The last filled in part, if needed. *\/\n ss << (use_unicode_ ? bar::unicode::fraction[partial_bar_char_idx]\n : bar::empty_fill);\n }\n\n \/* The not-filled-in part *\/\n for (i = whole_bar_chars + 1; i < length; i++)\n ss << bar::empty_fill;\n\n \/* The bar's right border *\/\n ss << (use_unicode_ ? bar::unicode::right_border : bar::right_border);\n\n if (use_colour_)\n ss << vt100::reset_colour;\n\n return ss.str();\n}\n\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\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\n#ifndef _GLRETRACE_HPP_\n#define _GLRETRACE_HPP_\n\n#include \"glws.hpp\"\n#include \"retrace.hpp\"\n\n\nnamespace glretrace {\n\n\nextern bool insideList;\nextern bool insideGlBeginEnd;\n\n\nextern glws::Drawable *currentDrawable;\nextern glws::Context *currentContext;\n\nglws::Drawable *\ncreateDrawable(glws::Profile profile);\n\nglws::Drawable *\ncreateDrawable(void);\n\nglws::Context *\ncreateContext(glws::Context *shareContext, glws::Profile profile);\n\nglws::Context *\ncreateContext(glws::Context *shareContext = 0);\n\nbool\nmakeCurrent(trace::Call &call, glws::Drawable *drawable, glws::Context *context);\n\n\nvoid\ncheckGlError(trace::Call &call);\n\nextern const retrace::Entry gl_callbacks[];\nextern const retrace::Entry cgl_callbacks[];\nextern const retrace::Entry glx_callbacks[];\nextern const retrace::Entry wgl_callbacks[];\nextern const retrace::Entry egl_callbacks[];\n\nvoid frame_start();\nvoid frame_complete(trace::Call &call);\n\nvoid updateDrawable(int width, int height);\n\nvoid flushQueries();\nvoid beginProfile(trace::Call &call);\nvoid endProfile(trace::Call &call);\n\nvoid setActiveProgram(GLuint program);\n} \/* namespace glretrace *\/\n\nGLuint retrace_unmap_program(GLuint val);\n\n#endif \/* _GLRETRACE_HPP_ *\/\nRemove old unused function declaration.\/**************************************************************************\n *\n * Copyright 2011 Jose Fonseca\n * All Rights Reserved.\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\n#ifndef _GLRETRACE_HPP_\n#define _GLRETRACE_HPP_\n\n#include \"glws.hpp\"\n#include \"retrace.hpp\"\n\n\nnamespace glretrace {\n\n\nextern bool insideList;\nextern bool insideGlBeginEnd;\n\n\nextern glws::Drawable *currentDrawable;\nextern glws::Context *currentContext;\n\nglws::Drawable *\ncreateDrawable(glws::Profile profile);\n\nglws::Drawable *\ncreateDrawable(void);\n\nglws::Context *\ncreateContext(glws::Context *shareContext, glws::Profile profile);\n\nglws::Context *\ncreateContext(glws::Context *shareContext = 0);\n\nbool\nmakeCurrent(trace::Call &call, glws::Drawable *drawable, glws::Context *context);\n\n\nvoid\ncheckGlError(trace::Call &call);\n\nextern const retrace::Entry gl_callbacks[];\nextern const retrace::Entry cgl_callbacks[];\nextern const retrace::Entry glx_callbacks[];\nextern const retrace::Entry wgl_callbacks[];\nextern const retrace::Entry egl_callbacks[];\n\nvoid frame_start();\nvoid frame_complete(trace::Call &call);\n\nvoid updateDrawable(int width, int height);\n\nvoid flushQueries();\nvoid beginProfile(trace::Call &call);\nvoid endProfile(trace::Call &call);\n\nvoid setActiveProgram(GLuint program);\n} \/* namespace glretrace *\/\n\n\n#endif \/* _GLRETRACE_HPP_ *\/\n<|endoftext|>"} {"text":"#include \"aquila\/global.h\"\n#include \"aquila\/source\/generator\/SineGenerator.h\"\n#include \"aquila\/tools\/TextPlot.h\"\n#include \"UnitTest++\/UnitTest++.h\"\n#include \n#include \n\n\nSUITE(TextPlot)\n{\n auto expectedSinePlot =\n \"\\nData plot\\n\"\n \" *** *** *** *** \\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" \\n\"\n \" * * * * \\n\"\n \"* * * * \\n\"\n \" \\n\"\n \" \\n\"\n \" * * * * * * * *\\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" *** *** *** *** \\n\";\n\n TEST(DefaultTitle)\n {\n Aquila::TextPlot plot;\n CHECK_EQUAL(plot.getTitle(), \"Data plot\");\n }\n\n TEST(CustomTitle)\n {\n Aquila::TextPlot plot;\n plot.setTitle(\"My plot\");\n CHECK_EQUAL(plot.getTitle(), \"My plot\");\n }\n\n TEST(DefaultSize)\n {\n Aquila::TextPlot plot;\n CHECK_EQUAL(plot.getWidth(), 64u);\n CHECK_EQUAL(plot.getHeight(), 16u);\n }\n\n TEST(CustomSize)\n {\n Aquila::TextPlot plot;\n plot.setSize(80, 12);\n CHECK_EQUAL(plot.getWidth(), 80u);\n CHECK_EQUAL(plot.getHeight(), 12u);\n }\n\n TEST(PlotSineWave)\n {\n Aquila::SineGenerator generator(128);\n generator.setAmplitude(1).setFrequency(8).generate(64);\n std::stringstream out;\n Aquila::TextPlot plot(\"Data plot\", out);\n plot.plot(generator);\n CHECK_EQUAL(expectedSinePlot, out.str());\n }\n\n TEST(PlotSineWaveFromArray)\n {\n Aquila::SineGenerator generator(128);\n generator.setAmplitude(1).setFrequency(8).generate(64);\n std::stringstream out;\n Aquila::TextPlot plot(\"Data plot\", out);\n plot.plot(generator.toArray(), generator.length());\n CHECK_EQUAL(expectedSinePlot, out.str());\n }\n}\nAdded test for plotting a std::vector.#include \"aquila\/global.h\"\n#include \"aquila\/source\/generator\/SineGenerator.h\"\n#include \"aquila\/tools\/TextPlot.h\"\n#include \"UnitTest++\/UnitTest++.h\"\n#include \n#include \n#include \n\n\nSUITE(TextPlot)\n{\n auto expectedSinePlot =\n \"\\nData plot\\n\"\n \" *** *** *** *** \\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" \\n\"\n \" * * * * \\n\"\n \"* * * * \\n\"\n \" \\n\"\n \" \\n\"\n \" * * * * * * * *\\n\"\n \" \\n\"\n \" * * * * * * * * \\n\"\n \" \\n\"\n \" *** *** *** *** \\n\";\n\n TEST(DefaultTitle)\n {\n Aquila::TextPlot plot;\n CHECK_EQUAL(plot.getTitle(), \"Data plot\");\n }\n\n TEST(CustomTitle)\n {\n Aquila::TextPlot plot;\n plot.setTitle(\"My plot\");\n CHECK_EQUAL(plot.getTitle(), \"My plot\");\n }\n\n TEST(DefaultSize)\n {\n Aquila::TextPlot plot;\n CHECK_EQUAL(plot.getWidth(), 64u);\n CHECK_EQUAL(plot.getHeight(), 16u);\n }\n\n TEST(CustomSize)\n {\n Aquila::TextPlot plot;\n plot.setSize(80, 12);\n CHECK_EQUAL(plot.getWidth(), 80u);\n CHECK_EQUAL(plot.getHeight(), 12u);\n }\n\n TEST(PlotSineWave)\n {\n Aquila::SineGenerator generator(128);\n generator.setAmplitude(1).setFrequency(8).generate(64);\n std::stringstream out;\n Aquila::TextPlot plot(\"Data plot\", out);\n plot.plot(generator);\n CHECK_EQUAL(expectedSinePlot, out.str());\n }\n\n TEST(PlotSineWaveFromArray)\n {\n Aquila::SineGenerator generator(128);\n generator.setAmplitude(1).setFrequency(8).generate(64);\n std::stringstream out;\n Aquila::TextPlot plot(\"Data plot\", out);\n plot.plot(generator.toArray(), generator.length());\n CHECK_EQUAL(expectedSinePlot, out.str());\n }\n\n TEST(PlotSineWaveFromVector)\n {\n Aquila::SineGenerator generator(128);\n generator.setAmplitude(1).setFrequency(8).generate(64);\n auto arr = generator.toArray();\n std::vector vec(arr, arr + generator.length());\n std::stringstream out;\n Aquila::TextPlot plot(\"Data plot\", out);\n plot.plot(vec);\n CHECK_EQUAL(expectedSinePlot, out.str());\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fixedhyper.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef SVTOOLS_FIXEDHYPER_HXX\n#define SVTOOLS_FIXEDHYPER_HXX\n\n#include \"svtools\/svtdllapi.h\"\n\n#include \n\n\/\/.........................................................................\nnamespace svt\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= FixedHyperlink\n \/\/=====================================================================\n class SVT_DLLPUBLIC FixedHyperlink : public ::toolkit::FixedHyperlinkBase\n {\n private:\n long m_nTextLen;\n Pointer m_aOldPointer;\n Link m_aClickHdl;\n String m_sURL;\n\n \/** initializes the font (link color and underline).\n\n Called by the Ctors.\n *\/\n void Initialize();\n\n protected:\n \/** overwrites Window::MouseMove().\n\n Changes the pointer only over the text.\n *\/\n virtual void MouseMove( const MouseEvent& rMEvt );\n\n \/** overwrites Window::MouseButtonUp().\n\n Calls the set link if the mouse is over the text.\n *\/\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n\n \/** overwrites Window::RequestHelp().\n\n Shows tooltip only if the mouse is over the text.\n *\/\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n \/** ctors\n\n With ResId or WinBits.\n *\/\n FixedHyperlink( Window* pParent, const ResId& rId );\n FixedHyperlink( Window* pParent, WinBits nWinStyle = 0 );\n\n \/** dtor\n\n *\/\n virtual ~FixedHyperlink();\n\n \/** overwrites Window::GetFocus().\n\n Changes the color of the text and shows a focus rectangle.\n *\/\n virtual void GetFocus();\n\n \/** overwrites Window::LoseFocus().\n\n Changes the color of the text and hides the focus rectangle.\n *\/\n virtual void LoseFocus();\n\n \/** overwrites Window::KeyInput().\n\n KEY_RETURN and KEY_SPACE calls the link handler.\n *\/\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n \/** sets m_aClickHdl<\/member> with rLink<\/arg>.\n\n m_aClickHdl<\/member> is called if the text is clicked.\n *\/\n inline void SetClickHdl( const Link& rLink ) { m_aClickHdl = rLink; }\n\n \/** returns m_aClickHdl<\/member>.\n\n @return\n m_aClickHdl<\/member>\n *\/\n inline const Link& GetClickHdl() const { return m_aClickHdl; }\n\n \/\/ ::toolkit::FixedHyperbaseLink\n\n \/** sets the URL of the hyperlink and uses it as tooltip. *\/\n virtual void SetURL( const String& rNewURL );\n\n \/** returns the URL of the hyperlink.\n\n @return\n m_sURL<\/member>\n *\/\n virtual String GetURL() const;\n\n \/** sets new text and recalculates the text length. *\/\n virtual void SetDescription( const String& rNewDescription );\n };\n\n\/\/.........................................................................\n} \/\/ namespace svt\n\/\/.........................................................................\n\n#endif\n\nINTEGRATION: CWS logger2 (1.5.96); FILE MERGED 2008\/06\/30 10:56:32 pb 1.5.96.1: fix: #i90370# new class FixedHyperlinkImage\/*************************************************************************\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: fixedhyper.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef SVTOOLS_FIXEDHYPER_HXX\n#define SVTOOLS_FIXEDHYPER_HXX\n\n#include \"svtools\/svtdllapi.h\"\n\n#include \n\n\/\/.........................................................................\nnamespace svt\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= FixedHyperlink\n \/\/=====================================================================\n class SVT_DLLPUBLIC FixedHyperlink : public ::toolkit::FixedHyperlinkBase\n {\n private:\n long m_nTextLen;\n Pointer m_aOldPointer;\n Link m_aClickHdl;\n String m_sURL;\n\n \/** initializes the font (link color and underline).\n\n Called by the Ctors.\n *\/\n void Initialize();\n\n protected:\n \/** overwrites Window::MouseMove().\n\n Changes the pointer only over the text.\n *\/\n virtual void MouseMove( const MouseEvent& rMEvt );\n\n \/** overwrites Window::MouseButtonUp().\n\n Calls the set link if the mouse is over the text.\n *\/\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n\n \/** overwrites Window::RequestHelp().\n\n Shows tooltip only if the mouse is over the text.\n *\/\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n \/** ctors\n\n With ResId or WinBits.\n *\/\n FixedHyperlink( Window* pParent, const ResId& rId );\n FixedHyperlink( Window* pParent, WinBits nWinStyle = 0 );\n\n \/** dtor\n\n *\/\n virtual ~FixedHyperlink();\n\n \/** overwrites Window::GetFocus().\n\n Changes the color of the text and shows a focus rectangle.\n *\/\n virtual void GetFocus();\n\n \/** overwrites Window::LoseFocus().\n\n Changes the color of the text and hides the focus rectangle.\n *\/\n virtual void LoseFocus();\n\n \/** overwrites Window::KeyInput().\n\n KEY_RETURN and KEY_SPACE calls the link handler.\n *\/\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n \/** sets m_aClickHdl<\/member> with rLink<\/arg>.\n\n m_aClickHdl<\/member> is called if the text is clicked.\n *\/\n inline void SetClickHdl( const Link& rLink ) { m_aClickHdl = rLink; }\n\n \/** returns m_aClickHdl<\/member>.\n\n @return\n m_aClickHdl<\/member>\n *\/\n inline const Link& GetClickHdl() const { return m_aClickHdl; }\n\n \/\/ ::toolkit::FixedHyperbaseLink\n\n \/** sets the URL of the hyperlink and uses it as tooltip. *\/\n virtual void SetURL( const String& rNewURL );\n\n \/** returns the URL of the hyperlink.\n\n @return\n m_sURL<\/member>\n *\/\n virtual String GetURL() const;\n\n \/** sets new text and recalculates the text length. *\/\n virtual void SetDescription( const String& rNewDescription );\n };\n\n \/\/=====================================================================\n \/\/= FixedHyperlinkImage\n \/\/=====================================================================\n class SVT_DLLPUBLIC FixedHyperlinkImage : public FixedImage\n {\n private:\n Pointer m_aOldPointer;\n Link m_aClickHdl;\n String m_sURL;\n\n \/** initializes the font (link color and underline).\n\n Called by the Ctors.\n *\/\n void Initialize();\n\n protected:\n \/** overwrites Window::MouseMove().\n\n Changes the pointer only over the text.\n *\/\n virtual void MouseMove( const MouseEvent& rMEvt );\n\n \/** overwrites Window::MouseButtonUp().\n\n Calls the set link if the mouse is over the text.\n *\/\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n\n \/** overwrites Window::RequestHelp().\n\n Shows tooltip only if the mouse is over the text.\n *\/\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n \/** ctors\n\n With ResId or WinBits.\n *\/\n FixedHyperlinkImage( Window* pParent, const ResId& rId );\n FixedHyperlinkImage( Window* pParent, WinBits nWinStyle = 0 );\n\n \/** dtor\n\n *\/\n virtual ~FixedHyperlinkImage();\n\n \/** overwrites Window::GetFocus().\n\n Changes the color of the text and shows a focus rectangle.\n *\/\n virtual void GetFocus();\n\n \/** overwrites Window::LoseFocus().\n\n Changes the color of the text and hides the focus rectangle.\n *\/\n virtual void LoseFocus();\n\n \/** overwrites Window::KeyInput().\n\n KEY_RETURN and KEY_SPACE calls the link handler.\n *\/\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n \/** sets m_aClickHdl<\/member> with rLink<\/arg>.\n\n m_aClickHdl<\/member> is called if the text is clicked.\n *\/\n inline void SetClickHdl( const Link& rLink ) { m_aClickHdl = rLink; }\n\n \/** returns m_aClickHdl<\/member>.\n\n @return\n m_aClickHdl<\/member>\n *\/\n inline const Link& GetClickHdl() const { return m_aClickHdl; }\n\n \/\/ ::toolkit::FixedHyperbaseLink\n\n \/** sets the URL of the hyperlink and uses it as tooltip. *\/\n virtual void SetURL( const String& rNewURL );\n\n \/** returns the URL of the hyperlink.\n\n @return\n m_sURL<\/member>\n *\/\n virtual String GetURL() const;\n };\n\/\/.........................................................................\n} \/\/ namespace svt\n\/\/.........................................................................\n\n#endif\n\n<|endoftext|>"} {"text":"#ifdef _MSC_VER\n#ifdef GEOS_DEBUG_MSVC_USE_VLD\n#include \n#endif\n#endif\n\n\/\/ tut\n#include \n#include \n\/\/ geos \n#include \n\/\/ std\n#include \n#include \n#include \n\nnamespace tut\n{\n test_runner_singleton runner;\n}\n\nvoid usage()\n{\n using std::cout;\n using std::endl;\n\n const std::string module(\"geos_unit\");\n\n \/\/[list] | [ group] [test]\n cout << \"Usage: \" << module << \" [OPTION] [TARGET]\\n\"\n << endl\n << \"Targets:\\n\"\n << \" run all tests in all groups\\n\"\n << \" run all tests from given group\\n\"\n << \" run single test with given number from given group\\n\"\n << endl\n << \"Options:\\n\"\n << \" --list list all registered test groups\\n\"\n << \" --verbose run unit tests verbosely; displays non-error information\\n\"\n << \" --version print version information and exit\\n\"\n << \" --help print this message and exit\\n\"\n << endl\n << \"Examples:\\n\"\n << \" \" << module << \" -v\\n\"\n << \" \" << module << \" list\\n\"\n << \" \" << module << \" geos::geom::Envelope\\n\"\n << \" \" << module << \" geos::geom::Envelope 2\\n\"\n << endl\n << \"GEOS homepage: http:\/\/geos.refractions.net\" << endl;\n}\n\nint main(int argc, const char* argv[])\n{\n tut::reporter visi;\n\n if ( (argc == 2 && std::string(argv[1]) == \"--help\") || argc > 3 )\n {\n usage();\n return 0;\n }\n\n std::cout << \"===============================\\n\"\n << \" GEOS Test Suite Application\\n\"\n << \"===============================\\n\";\n\n tut::runner.get().set_callback(&visi);\n\n try\n {\n if ( argc == 1 )\n {\n tut::runner.get().run_tests();\n }\n else if ( argc == 2 && std::string(argv[1]) == \"--list\" )\n {\n tut::groupnames gl = tut::runner.get().list_groups();\n tut::groupnames::const_iterator b = gl.begin();\n tut::groupnames::const_iterator e = gl.end();\n\n tut::groupnames::difference_type d = std::distance(b, e);\n\n std::cout << \"Registered \" << d << \" test groups:\\n\" << std::endl;\n \n while ( b != e )\n {\n std::cout << \" \" << *b << std::endl;\n ++b;\n }\n }\n else if ( argc == 2 && std::string(argv[1]) != \"--list\" )\n {\n tut::runner.get().run_tests(argv[1]);\n }\n else if( argc == 3 )\n {\n \/\/ TODO - mloskot - check if test group with given name exists\n \/\/ TODO - mloskot - check if test case with given number exists\n std::string grpname(argv[1]);\n if (grpname.empty())\n throw std::runtime_error(\"missing test group name\");\n\n tut::test_result result;\n tut::runner.get().run_test(grpname, std::atoi(argv[2]), result);\n }\n }\n catch( const std::exception& ex )\n {\n std::cerr << \"!!! GEOS Test Suite raised exception: \" << ex.what() << std::endl;\n }\n\n \/\/ XXX - mloskot - this should be removed in future!\n geos::io::Unload::Release();\n\n return (visi.all_ok() ? EXIT_SUCCESS : EXIT_FAILURE); \n}\nMissing svn keywords\/\/ $Id$\n\/\/ \n\/\/ Test Suite Runner\n\/\/\n#ifdef _MSC_VER\n#ifdef GEOS_DEBUG_MSVC_USE_VLD\n#include \n#endif\n#endif\n\n\/\/ tut\n#include \n#include \n\/\/ geos \n#include \n\/\/ std\n#include \n#include \n#include \n\nnamespace tut\n{\n test_runner_singleton runner;\n}\n\nvoid usage()\n{\n using std::cout;\n using std::endl;\n\n const std::string module(\"geos_unit\");\n\n \/\/[list] | [ group] [test]\n cout << \"Usage: \" << module << \" [OPTION] [TARGET]\\n\"\n << endl\n << \"Targets:\\n\"\n << \" run all tests in all groups\\n\"\n << \" run all tests from given group\\n\"\n << \" run single test with given number from given group\\n\"\n << endl\n << \"Options:\\n\"\n << \" --list list all registered test groups\\n\"\n << \" --verbose run unit tests verbosely; displays non-error information\\n\"\n << \" --version print version information and exit\\n\"\n << \" --help print this message and exit\\n\"\n << endl\n << \"Examples:\\n\"\n << \" \" << module << \" -v\\n\"\n << \" \" << module << \" list\\n\"\n << \" \" << module << \" geos::geom::Envelope\\n\"\n << \" \" << module << \" geos::geom::Envelope 2\\n\"\n << endl\n << \"GEOS homepage: http:\/\/geos.refractions.net\" << endl;\n}\n\nint main(int argc, const char* argv[])\n{\n tut::reporter visi;\n\n if ( (argc == 2 && std::string(argv[1]) == \"--help\") || argc > 3 )\n {\n usage();\n return 0;\n }\n\n std::cout << \"===============================\\n\"\n << \" GEOS Test Suite Application\\n\"\n << \"===============================\\n\";\n\n tut::runner.get().set_callback(&visi);\n\n try\n {\n if ( argc == 1 )\n {\n tut::runner.get().run_tests();\n }\n else if ( argc == 2 && std::string(argv[1]) == \"--list\" )\n {\n tut::groupnames gl = tut::runner.get().list_groups();\n tut::groupnames::const_iterator b = gl.begin();\n tut::groupnames::const_iterator e = gl.end();\n\n tut::groupnames::difference_type d = std::distance(b, e);\n\n std::cout << \"Registered \" << d << \" test groups:\\n\" << std::endl;\n \n while ( b != e )\n {\n std::cout << \" \" << *b << std::endl;\n ++b;\n }\n }\n else if ( argc == 2 && std::string(argv[1]) != \"--list\" )\n {\n tut::runner.get().run_tests(argv[1]);\n }\n else if( argc == 3 )\n {\n \/\/ TODO - mloskot - check if test group with given name exists\n \/\/ TODO - mloskot - check if test case with given number exists\n std::string grpname(argv[1]);\n if (grpname.empty())\n throw std::runtime_error(\"missing test group name\");\n\n tut::test_result result;\n tut::runner.get().run_test(grpname, std::atoi(argv[2]), result);\n }\n }\n catch( const std::exception& ex )\n {\n std::cerr << \"!!! GEOS Test Suite raised exception: \" << ex.what() << std::endl;\n }\n\n \/\/ XXX - mloskot - this should be removed in future!\n geos::io::Unload::Release();\n\n return (visi.all_ok() ? EXIT_SUCCESS : EXIT_FAILURE); \n}\n<|endoftext|>"} {"text":"\/*\n * CrashHandlerProxyMain.cpp\n *\n * Copyright (C) 2019 by RStudio, Inc.\n *\n *\/\n\n#include \n#include \n#include \n\nusing namespace rstudio::core;\nusing namespace rstudio::core::system;\n\nvoid runCrashHandler(const char* argv[])\n{\n FilePath exePath;\n Error error = executablePath(nullptr, &exePath);\n if (error)\n LOG_ERROR(error);\n\n FilePath handlerPath;\n std::string crashpadHandlerPath = rstudio::core::system::getenv(kCrashpadHandlerEnvVar);\n if (!crashpadHandlerPath.empty())\n handlerPath = FilePath(crashpadHandlerPath);\n else\n handlerPath = exePath.getParent().completeChildPath(\"crashpad_handler\");\n\n std::string handlerPathStr = handlerPath.getAbsolutePath();\n const char* handlerExe = handlerPathStr.c_str();\n argv[0] = handlerExe;\n\n ::execvp(handlerExe, const_cast(argv));\n\n \/\/ if we get here, we failed to run the crash handler\n \/\/ log an error indicating why\n LOG_ERROR(systemError(errno, ERROR_LOCATION));\n}\n\nint main(int argc, const char* argv[])\n{\n \/\/ note: we log all errors and attempt to launch the crashpad handler\n \/\/ regardless, as this is a best effort proxy attempt\n log::setProgramId(\"crash-handler-proxy\");\n initializeStderrLog(\"crash-handler-proxy\", log::LogLevel::WARN);\n\n Error error = ignoreSignal(SigPipe);\n if (error)\n LOG_ERROR(error);\n\n if (realUserIsRoot() && !effectiveUserIsRoot())\n {\n error = restoreRoot();\n if (error)\n LOG_ERROR(error);\n }\n\n runCrashHandler(argv);\n\n \/\/ if we get here, we failed to run the crash handler\n return EXIT_FAILURE;\n}\nexit failure if root cannot be restored\/*\n * CrashHandlerProxyMain.cpp\n *\n * Copyright (C) 2019 by RStudio, Inc.\n *\n *\/\n\n#include \n#include \n#include \n\nusing namespace rstudio::core;\nusing namespace rstudio::core::system;\n\nvoid runCrashHandler(const char* argv[])\n{\n FilePath exePath;\n Error error = executablePath(nullptr, &exePath);\n if (error)\n LOG_ERROR(error);\n\n FilePath handlerPath;\n std::string crashpadHandlerPath = rstudio::core::system::getenv(kCrashpadHandlerEnvVar);\n if (!crashpadHandlerPath.empty())\n handlerPath = FilePath(crashpadHandlerPath);\n else\n handlerPath = exePath.getParent().completeChildPath(\"crashpad_handler\");\n\n std::string handlerPathStr = handlerPath.getAbsolutePath();\n const char* handlerExe = handlerPathStr.c_str();\n argv[0] = handlerExe;\n\n ::execvp(handlerExe, const_cast(argv));\n\n \/\/ if we get here, we failed to run the crash handler\n \/\/ log an error indicating why\n LOG_ERROR(systemError(errno, ERROR_LOCATION));\n}\n\nint main(int argc, const char* argv[])\n{\n \/\/ note: we log all errors and attempt to launch the crashpad handler\n \/\/ regardless, as this is a best effort proxy attempt\n log::setProgramId(\"crash-handler-proxy\");\n initializeStderrLog(\"crash-handler-proxy\", log::LogLevel::WARN);\n\n Error error = ignoreSignal(SigPipe);\n if (error)\n LOG_ERROR(error);\n\n if (realUserIsRoot() && !effectiveUserIsRoot())\n {\n error = restoreRoot();\n if (error)\n {\n LOG_ERROR(error);\n return EXIT_FAILURE;\n }\n }\n\n runCrashHandler(argv);\n\n \/\/ if we get here, we failed to run the crash handler\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"\/*\n * SessionPresentation.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n\/\/ TODO: transition's don't work\n\/\/ TODO: italic's don't work\n\n\/\/ TODO: more generous default width\n\/\/ TODO: align scaling with default width\n\n\/\/ TODO: stable path for view in browser\n\/\/ TODO: external css\n\/\/ TODO: presentation Depends when possible\n\n\/\/ TODO: keyword highlight only after ===\n\/\/ TODO: custom code navigator for presentations\n\/\/ TODO: run all chunks doesn't work for Rpres\n\n\n#include \"SessionPresentation.hpp\"\n\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"..\/SessionRPubs.hpp\"\n\n#include \"PresentationLog.hpp\"\n#include \"PresentationState.hpp\"\n#include \"SlideRequestHandler.hpp\"\n\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace presentation {\n\nnamespace {\n\n\nvoid showPresentation(const FilePath& filePath)\n{\n \/\/ initialize state\n presentation::state::init(filePath);\n\n \/\/ notify the client\n ClientEvent event(client_events::kShowPresentationPane,\n presentation::state::asJson());\n module_context::enqueClientEvent(event);\n}\n\nSEXP rs_showPresentation(SEXP fileSEXP)\n{\n try\n {\n \/\/ validate path\n FilePath filePath(r::sexp::asString(fileSEXP));\n if (!filePath.exists())\n throw r::exec::RErrorException(\"File path \" + filePath.absolutePath() +\n \" does not exist.\");\n\n showPresentation(filePath);\n }\n catch(const r::exec::RErrorException& e)\n {\n r::exec::error(e.message());\n }\n\n return R_NilValue;\n}\n\nSEXP rs_showPresentationHelpDoc(SEXP helpDocSEXP)\n{\n try\n {\n \/\/ verify a presentation is active\n if (!presentation::state::isActive())\n {\n throw r::exec::RErrorException(\n \"No presentation is currently active\");\n }\n\n \/\/ resolve against presentation directory\n std::string helpDoc = r::sexp::asString(helpDocSEXP);\n FilePath helpDocPath = presentation::state::directory().childPath(\n helpDoc);\n if (!helpDocPath.exists())\n {\n throw r::exec::RErrorException(\"Path \" + helpDocPath.absolutePath()\n + \" not found.\");\n }\n\n \/\/ build url and fire event\n std::string url = \"help\/presentation\/?file=\";\n std::string file = module_context::createAliasedPath(helpDocPath);\n url += http::util::urlEncode(file, true);\n\n ClientEvent event(client_events::kShowHelp, url);\n module_context::enqueClientEvent(event);\n }\n catch(const r::exec::RErrorException& e)\n {\n r::exec::error(e.message());\n }\n\n return R_NilValue;\n}\n\nError setPresentationSlideIndex(const json::JsonRpcRequest& request,\n json::JsonRpcResponse*)\n{\n int index = 0;\n Error error = json::readParam(request.params, 0, &index);\n if (error)\n return error;\n\n presentation::state::setSlideIndex(index);\n\n presentation::log().onSlideIndexChanged(index);\n\n return Success();\n}\n\nError createNewPresentation(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get file path\n std::string file;\n Error error = json::readParam(request.params, 0, &file);\n if (error)\n return error;\n FilePath filePath = module_context::resolveAliasedPath(file);\n\n \/\/ process template\n std::map vars;\n vars[\"name\"] = filePath.stem();\n core::text::TemplateFilter filter(vars);\n\n \/\/ read file with template filter\n FilePath templatePath = session::options().rResourcesPath().complete(\n \"templates\/r_presentation.Rpres\");\n std::string presContents;\n error = core::readStringFromFile(templatePath, filter, &presContents);\n if (error)\n return error;\n\n\n \/\/ write file\n return core::writeStringToFile(filePath,\n presContents,\n string_utils::LineEndingNative);\n}\n\nError showPresentationPane(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string file;\n Error error = json::readParam(request.params, 0, &file);\n if (error)\n return error;\n\n FilePath filePath = module_context::resolveAliasedPath(file);\n if (!filePath.exists())\n return core::fileNotFoundError(filePath, ERROR_LOCATION);\n\n showPresentation(filePath);\n\n return Success();\n}\n\nError closePresentationPane(const json::JsonRpcRequest&,\n json::JsonRpcResponse*)\n{\n presentation::state::clear();\n\n return Success();\n}\n\nError presentationExecuteCode(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the code\n std::string code;\n Error error = json::readParam(request.params, 0, &code);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ execute within the context of either the tutorial project directory\n \/\/ or presentation directory\n RestoreCurrentPathScope restorePathScope(\n module_context::safeCurrentPath());\n if (presentation::state::isTutorial() &&\n projects::projectContext().hasProject())\n {\n error = projects::projectContext().directory().makeCurrentPath();\n }\n else\n {\n error = presentation::state::directory().makeCurrentPath();\n }\n if (error)\n return error;\n\n\n \/\/ actually execute the code (show error in the console)\n error = r::exec::executeString(code);\n if (error)\n {\n std::string errMsg = \"Error executing code: \" + code + \"\\n\";\n errMsg += r::endUserErrorMessage(error);\n module_context::consoleWriteError(errMsg + \"\\n\");\n }\n\n return Success();\n}\n\nError setWorkingDirectory(const json::JsonRpcRequest& request,\n json::JsonRpcResponse*)\n{\n \/\/ get the path\n std::string path;\n Error error = json::readParam(request.params, 0, &path);\n if (error)\n return error;\n\n \/\/ set current path\n FilePath filePath = module_context::resolveAliasedPath(path);\n return filePath.makeCurrentPath();\n}\n\nError tutorialFeedback(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the feedback\n std::string feedback;\n Error error = json::readParam(request.params, 0, &feedback);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ record the feedback\n presentation::log().recordFeedback(feedback);\n\n return Success();\n}\n\nError tutorialQuizResponse(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the params\n int slideIndex, answer;\n bool correct;\n Error error = json::readParams(request.params,\n &slideIndex,\n &answer,\n &correct);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ record the feedback\n presentation::log().recordQuizResponse(slideIndex, answer, correct);\n\n return Success();\n}\n\n\n\nError createStandalonePresentation(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string pathParam;\n Error error = json::readParam(request.params, 0, &pathParam);\n if (error)\n return error;\n\n FilePath targetPath;\n if (!pathParam.empty())\n targetPath = module_context::resolveAliasedPath(pathParam);\n\n std::string errMsg;\n if (savePresentationAsStandalone(&targetPath, &errMsg))\n {\n pResponse->setResult(module_context::createAliasedPath(targetPath));\n }\n else\n {\n pResponse->setError(systemError(boost::system::errc::io_error,\n ERROR_LOCATION),\n json::toJsonString(errMsg));\n }\n\n return Success();\n}\n\nError createPresentationRpubsSource(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ use a stable location in the presentation directory for the Rpubs\n \/\/ source file so that update works across sessions\n std::string stem = presentation::state::filePath().stem();\n FilePath filePath = presentation::state::directory().childPath(\n stem + \"-rpubs.html\");\n\n std::string errMsg;\n if (savePresentationAsRpubsSource(filePath, &errMsg))\n {\n json::Object resultJson;\n resultJson[\"published\"] = !rpubs::previousUploadId(filePath).empty();\n resultJson[\"source_file_path\"] = module_context::createAliasedPath(\n filePath);\n pResponse->setResult(resultJson);\n }\n else\n {\n pResponse->setError(systemError(boost::system::errc::io_error,\n ERROR_LOCATION),\n json::toJsonString(errMsg));\n }\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\njson::Value presentationStateAsJson()\n{\n return presentation::state::asJson();\n}\n\nError initialize()\n{\n \/\/ register rs_showPresentation\n R_CallMethodDef methodDefShowPresentation;\n methodDefShowPresentation.name = \"rs_showPresentation\" ;\n methodDefShowPresentation.fun = (DL_FUNC) rs_showPresentation;\n methodDefShowPresentation.numArgs = 1;\n r::routines::addCallMethod(methodDefShowPresentation);\n\n \/\/ register rs_showPresentationHelpDoc\n R_CallMethodDef methodDefShowHelpDoc;\n methodDefShowHelpDoc.name = \"rs_showPresentationHelpDoc\" ;\n methodDefShowHelpDoc.fun = (DL_FUNC) rs_showPresentationHelpDoc;\n methodDefShowHelpDoc.numArgs = 1;\n r::routines::addCallMethod(methodDefShowHelpDoc);\n\n \/\/ initialize presentation log\n Error error = log().initialize();\n if (error)\n return error;\n\n using boost::bind;\n using namespace session::module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerUriHandler, \"\/presentation\", handlePresentationPaneRequest))\n (bind(registerRpcMethod, \"create_standalone_presentation\", createStandalonePresentation))\n (bind(registerRpcMethod, \"create_presentation_rpubs_source\", createPresentationRpubsSource))\n (bind(registerRpcMethod, \"set_presentation_slide_index\", setPresentationSlideIndex))\n (bind(registerRpcMethod, \"create_new_presentation\", createNewPresentation))\n (bind(registerRpcMethod, \"show_presentation_pane\", showPresentationPane))\n (bind(registerRpcMethod, \"close_presentation_pane\", closePresentationPane))\n (bind(registerRpcMethod, \"presentation_execute_code\", presentationExecuteCode))\n (bind(registerRpcMethod, \"set_working_directory\", setWorkingDirectory))\n (bind(registerRpcMethod, \"tutorial_feedback\", tutorialFeedback))\n (bind(registerRpcMethod, \"tutorial_quiz_response\", tutorialQuizResponse))\n (bind(presentation::state::initialize))\n (bind(sourceModuleRFile, \"SessionPresentation.R\"));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace presentation\n} \/\/ namespace modules\n} \/\/ namesapce session\n\nadd todos\/*\n * SessionPresentation.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n\/\/ TODO: transition's don't work\n\/\/ TODO: italic's don't work\n\n\/\/ TODO: more generous default width\n\/\/ TODO: align scaling with default width\n\n\/\/ TODO: stable path for view in browser\n\/\/ TODO: external css\n\/\/ TODO: presentation Depends when possible\n\n\/\/ TODO: keyword highlight only after ===\n\/\/ TODO: custom code navigator for presentations\n\/\/ TODO: run all chunks doesn't work for Rpres\n\n\/\/ TODO: depends should be a feature of presentations\n\/\/ TODO: auto-prompt for installation of pres packages\n\n#include \"SessionPresentation.hpp\"\n\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"..\/SessionRPubs.hpp\"\n\n#include \"PresentationLog.hpp\"\n#include \"PresentationState.hpp\"\n#include \"SlideRequestHandler.hpp\"\n\n\nusing namespace core;\n\nnamespace session {\nnamespace modules { \nnamespace presentation {\n\nnamespace {\n\n\nvoid showPresentation(const FilePath& filePath)\n{\n \/\/ initialize state\n presentation::state::init(filePath);\n\n \/\/ notify the client\n ClientEvent event(client_events::kShowPresentationPane,\n presentation::state::asJson());\n module_context::enqueClientEvent(event);\n}\n\nSEXP rs_showPresentation(SEXP fileSEXP)\n{\n try\n {\n \/\/ validate path\n FilePath filePath(r::sexp::asString(fileSEXP));\n if (!filePath.exists())\n throw r::exec::RErrorException(\"File path \" + filePath.absolutePath() +\n \" does not exist.\");\n\n showPresentation(filePath);\n }\n catch(const r::exec::RErrorException& e)\n {\n r::exec::error(e.message());\n }\n\n return R_NilValue;\n}\n\nSEXP rs_showPresentationHelpDoc(SEXP helpDocSEXP)\n{\n try\n {\n \/\/ verify a presentation is active\n if (!presentation::state::isActive())\n {\n throw r::exec::RErrorException(\n \"No presentation is currently active\");\n }\n\n \/\/ resolve against presentation directory\n std::string helpDoc = r::sexp::asString(helpDocSEXP);\n FilePath helpDocPath = presentation::state::directory().childPath(\n helpDoc);\n if (!helpDocPath.exists())\n {\n throw r::exec::RErrorException(\"Path \" + helpDocPath.absolutePath()\n + \" not found.\");\n }\n\n \/\/ build url and fire event\n std::string url = \"help\/presentation\/?file=\";\n std::string file = module_context::createAliasedPath(helpDocPath);\n url += http::util::urlEncode(file, true);\n\n ClientEvent event(client_events::kShowHelp, url);\n module_context::enqueClientEvent(event);\n }\n catch(const r::exec::RErrorException& e)\n {\n r::exec::error(e.message());\n }\n\n return R_NilValue;\n}\n\nError setPresentationSlideIndex(const json::JsonRpcRequest& request,\n json::JsonRpcResponse*)\n{\n int index = 0;\n Error error = json::readParam(request.params, 0, &index);\n if (error)\n return error;\n\n presentation::state::setSlideIndex(index);\n\n presentation::log().onSlideIndexChanged(index);\n\n return Success();\n}\n\nError createNewPresentation(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get file path\n std::string file;\n Error error = json::readParam(request.params, 0, &file);\n if (error)\n return error;\n FilePath filePath = module_context::resolveAliasedPath(file);\n\n \/\/ process template\n std::map vars;\n vars[\"name\"] = filePath.stem();\n core::text::TemplateFilter filter(vars);\n\n \/\/ read file with template filter\n FilePath templatePath = session::options().rResourcesPath().complete(\n \"templates\/r_presentation.Rpres\");\n std::string presContents;\n error = core::readStringFromFile(templatePath, filter, &presContents);\n if (error)\n return error;\n\n\n \/\/ write file\n return core::writeStringToFile(filePath,\n presContents,\n string_utils::LineEndingNative);\n}\n\nError showPresentationPane(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string file;\n Error error = json::readParam(request.params, 0, &file);\n if (error)\n return error;\n\n FilePath filePath = module_context::resolveAliasedPath(file);\n if (!filePath.exists())\n return core::fileNotFoundError(filePath, ERROR_LOCATION);\n\n showPresentation(filePath);\n\n return Success();\n}\n\nError closePresentationPane(const json::JsonRpcRequest&,\n json::JsonRpcResponse*)\n{\n presentation::state::clear();\n\n return Success();\n}\n\nError presentationExecuteCode(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the code\n std::string code;\n Error error = json::readParam(request.params, 0, &code);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ execute within the context of either the tutorial project directory\n \/\/ or presentation directory\n RestoreCurrentPathScope restorePathScope(\n module_context::safeCurrentPath());\n if (presentation::state::isTutorial() &&\n projects::projectContext().hasProject())\n {\n error = projects::projectContext().directory().makeCurrentPath();\n }\n else\n {\n error = presentation::state::directory().makeCurrentPath();\n }\n if (error)\n return error;\n\n\n \/\/ actually execute the code (show error in the console)\n error = r::exec::executeString(code);\n if (error)\n {\n std::string errMsg = \"Error executing code: \" + code + \"\\n\";\n errMsg += r::endUserErrorMessage(error);\n module_context::consoleWriteError(errMsg + \"\\n\");\n }\n\n return Success();\n}\n\nError setWorkingDirectory(const json::JsonRpcRequest& request,\n json::JsonRpcResponse*)\n{\n \/\/ get the path\n std::string path;\n Error error = json::readParam(request.params, 0, &path);\n if (error)\n return error;\n\n \/\/ set current path\n FilePath filePath = module_context::resolveAliasedPath(path);\n return filePath.makeCurrentPath();\n}\n\nError tutorialFeedback(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the feedback\n std::string feedback;\n Error error = json::readParam(request.params, 0, &feedback);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ record the feedback\n presentation::log().recordFeedback(feedback);\n\n return Success();\n}\n\nError tutorialQuizResponse(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ get the params\n int slideIndex, answer;\n bool correct;\n Error error = json::readParams(request.params,\n &slideIndex,\n &answer,\n &correct);\n if (error)\n return error;\n\n \/\/ confirm we are active\n if (!presentation::state::isActive())\n {\n pResponse->setError(json::errc::MethodUnexpected);\n return Success();\n }\n\n \/\/ record the feedback\n presentation::log().recordQuizResponse(slideIndex, answer, correct);\n\n return Success();\n}\n\n\n\nError createStandalonePresentation(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string pathParam;\n Error error = json::readParam(request.params, 0, &pathParam);\n if (error)\n return error;\n\n FilePath targetPath;\n if (!pathParam.empty())\n targetPath = module_context::resolveAliasedPath(pathParam);\n\n std::string errMsg;\n if (savePresentationAsStandalone(&targetPath, &errMsg))\n {\n pResponse->setResult(module_context::createAliasedPath(targetPath));\n }\n else\n {\n pResponse->setError(systemError(boost::system::errc::io_error,\n ERROR_LOCATION),\n json::toJsonString(errMsg));\n }\n\n return Success();\n}\n\nError createPresentationRpubsSource(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n \/\/ use a stable location in the presentation directory for the Rpubs\n \/\/ source file so that update works across sessions\n std::string stem = presentation::state::filePath().stem();\n FilePath filePath = presentation::state::directory().childPath(\n stem + \"-rpubs.html\");\n\n std::string errMsg;\n if (savePresentationAsRpubsSource(filePath, &errMsg))\n {\n json::Object resultJson;\n resultJson[\"published\"] = !rpubs::previousUploadId(filePath).empty();\n resultJson[\"source_file_path\"] = module_context::createAliasedPath(\n filePath);\n pResponse->setResult(resultJson);\n }\n else\n {\n pResponse->setError(systemError(boost::system::errc::io_error,\n ERROR_LOCATION),\n json::toJsonString(errMsg));\n }\n\n return Success();\n}\n\n} \/\/ anonymous namespace\n\n\njson::Value presentationStateAsJson()\n{\n return presentation::state::asJson();\n}\n\nError initialize()\n{\n \/\/ register rs_showPresentation\n R_CallMethodDef methodDefShowPresentation;\n methodDefShowPresentation.name = \"rs_showPresentation\" ;\n methodDefShowPresentation.fun = (DL_FUNC) rs_showPresentation;\n methodDefShowPresentation.numArgs = 1;\n r::routines::addCallMethod(methodDefShowPresentation);\n\n \/\/ register rs_showPresentationHelpDoc\n R_CallMethodDef methodDefShowHelpDoc;\n methodDefShowHelpDoc.name = \"rs_showPresentationHelpDoc\" ;\n methodDefShowHelpDoc.fun = (DL_FUNC) rs_showPresentationHelpDoc;\n methodDefShowHelpDoc.numArgs = 1;\n r::routines::addCallMethod(methodDefShowHelpDoc);\n\n \/\/ initialize presentation log\n Error error = log().initialize();\n if (error)\n return error;\n\n using boost::bind;\n using namespace session::module_context;\n ExecBlock initBlock ;\n initBlock.addFunctions()\n (bind(registerUriHandler, \"\/presentation\", handlePresentationPaneRequest))\n (bind(registerRpcMethod, \"create_standalone_presentation\", createStandalonePresentation))\n (bind(registerRpcMethod, \"create_presentation_rpubs_source\", createPresentationRpubsSource))\n (bind(registerRpcMethod, \"set_presentation_slide_index\", setPresentationSlideIndex))\n (bind(registerRpcMethod, \"create_new_presentation\", createNewPresentation))\n (bind(registerRpcMethod, \"show_presentation_pane\", showPresentationPane))\n (bind(registerRpcMethod, \"close_presentation_pane\", closePresentationPane))\n (bind(registerRpcMethod, \"presentation_execute_code\", presentationExecuteCode))\n (bind(registerRpcMethod, \"set_working_directory\", setWorkingDirectory))\n (bind(registerRpcMethod, \"tutorial_feedback\", tutorialFeedback))\n (bind(registerRpcMethod, \"tutorial_quiz_response\", tutorialQuizResponse))\n (bind(presentation::state::initialize))\n (bind(sourceModuleRFile, \"SessionPresentation.R\"));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace presentation\n} \/\/ namespace modules\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"\/\/===- lib\/MC\/MCStreamer.cpp - Streaming Machine Code Output --------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \nusing namespace llvm;\n\nMCStreamer::MCStreamer(MCContext &_Context) : Context(_Context), CurSection(0) {\n}\n\nMCStreamer::~MCStreamer() {\n}\n\nraw_ostream &MCStreamer::GetCommentOS() {\n \/\/ By default, discard comments.\n return nulls();\n}\n\n\n\/\/\/ EmitIntValue - Special case of EmitValue that avoids the client having to\n\/\/\/ pass in a MCExpr for constant integers.\nvoid MCStreamer::EmitIntValue(uint64_t Value, unsigned Size,\n unsigned AddrSpace) {\n EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);\n}\n\nvoid MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size,\n unsigned AddrSpace) {\n EmitValue(MCSymbolRefExpr::Create(Sym, getContext()), Size, AddrSpace);\n}\n\n\/\/\/ EmitFill - Emit NumBytes bytes worth of the value specified by\n\/\/\/ FillValue. This implements directives such as '.space'.\nvoid MCStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,\n unsigned AddrSpace) {\n const MCExpr *E = MCConstantExpr::Create(FillValue, getContext());\n for (uint64_t i = 0, e = NumBytes; i != e; ++i)\n EmitValue(E, 1, AddrSpace);\n}\n\n\/\/\/ EmitRawText - If this file is backed by a assembly streamer, this dumps\n\/\/\/ the specified string in the output .s file. This capability is\n\/\/\/ indicated by the hasRawTextSupport() predicate.\nvoid MCStreamer::EmitRawText(StringRef String) {\n errs() << \"EmitRawText called on an MCStreamer that doesn't support it, \"\n \" something must not be fully mc'ized\\n\";\n abort();\n}\n\nvoid MCStreamer::EmitRawText(const Twine &T) {\n SmallString<128> Str;\n T.toVector(Str);\n EmitRawText(Str.str());\n}\nGrammar fix. This is a test commit.\/\/===- lib\/MC\/MCStreamer.cpp - Streaming Machine Code Output --------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCExpr.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \nusing namespace llvm;\n\nMCStreamer::MCStreamer(MCContext &_Context) : Context(_Context), CurSection(0) {\n}\n\nMCStreamer::~MCStreamer() {\n}\n\nraw_ostream &MCStreamer::GetCommentOS() {\n \/\/ By default, discard comments.\n return nulls();\n}\n\n\n\/\/\/ EmitIntValue - Special case of EmitValue that avoids the client having to\n\/\/\/ pass in a MCExpr for constant integers.\nvoid MCStreamer::EmitIntValue(uint64_t Value, unsigned Size,\n unsigned AddrSpace) {\n EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);\n}\n\nvoid MCStreamer::EmitSymbolValue(const MCSymbol *Sym, unsigned Size,\n unsigned AddrSpace) {\n EmitValue(MCSymbolRefExpr::Create(Sym, getContext()), Size, AddrSpace);\n}\n\n\/\/\/ EmitFill - Emit NumBytes bytes worth of the value specified by\n\/\/\/ FillValue. This implements directives such as '.space'.\nvoid MCStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,\n unsigned AddrSpace) {\n const MCExpr *E = MCConstantExpr::Create(FillValue, getContext());\n for (uint64_t i = 0, e = NumBytes; i != e; ++i)\n EmitValue(E, 1, AddrSpace);\n}\n\n\/\/\/ EmitRawText - If this file is backed by an assembly streamer, this dumps\n\/\/\/ the specified string in the output .s file. This capability is\n\/\/\/ indicated by the hasRawTextSupport() predicate.\nvoid MCStreamer::EmitRawText(StringRef String) {\n errs() << \"EmitRawText called on an MCStreamer that doesn't support it, \"\n \" something must not be fully mc'ized\\n\";\n abort();\n}\n\nvoid MCStreamer::EmitRawText(const Twine &T) {\n SmallString<128> Str;\n T.toVector(Str);\n EmitRawText(Str.str());\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/isolate.h\"\n\n#include \"include\/dart_api.h\"\n\n#include \"vm\/assert.h\"\n#include \"vm\/bigint_store.h\"\n#include \"vm\/code_index_table.h\"\n#include \"vm\/compiler_stats.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/debuginfo.h\"\n#include \"vm\/heap.h\"\n#include \"vm\/message_queue.h\"\n#include \"vm\/object_store.h\"\n#include \"vm\/parser.h\"\n#include \"vm\/port.h\"\n#include \"vm\/random.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/stub_code.h\"\n#include \"vm\/thread.h\"\n#include \"vm\/timer.h\"\n#include \"vm\/visitor.h\"\n\nnamespace dart {\n\nDEFINE_FLAG(bool, report_invocation_count, false,\n \"Count function invocations and report.\");\nDECLARE_FLAG(bool, generate_gdb_symbols);\n\n\nIsolate::Isolate()\n : store_buffer_(),\n message_queue_(NULL),\n post_message_callback_(NULL),\n close_port_callback_(NULL),\n active_ports_(0),\n heap_(NULL),\n object_store_(NULL),\n top_resource_(NULL),\n top_context_(Context::null()),\n current_zone_(NULL),\n#if defined(DEBUG)\n no_gc_scope_depth_(0),\n no_handle_scope_depth_(0),\n top_handle_scope_(NULL),\n#endif\n random_seed_(Random::kDefaultRandomSeed),\n bigint_store_(NULL),\n top_exit_frame_info_(0),\n init_callback_data_(NULL),\n library_tag_handler_(NULL),\n api_state_(NULL),\n stub_code_(NULL),\n code_index_table_(NULL),\n long_jump_base_(NULL),\n timer_list_(),\n stack_limit_(0),\n stack_limit_on_overflow_exception_(0),\n ast_node_id_(AstNode::kNoId) {\n}\n\n\nIsolate::~Isolate() {\n delete message_queue_;\n delete heap_;\n delete object_store_;\n \/\/ Do not delete stack resources: top_resource_ and current_zone_.\n delete bigint_store_;\n delete api_state_;\n delete stub_code_;\n delete code_index_table_;\n}\n\n\nstatic bool StandardPostMessageCallback(Dart_Isolate dart_isolate,\n Dart_Port dest_port,\n Dart_Port reply_port,\n Dart_Message dart_message) {\n Isolate* isolate = reinterpret_cast(dart_isolate);\n ASSERT(isolate != NULL);\n PortMessage* message = new PortMessage(dest_port, reply_port, dart_message);\n isolate->message_queue()->Enqueue(message);\n return true;\n}\n\n\nstatic void StandardClosePortCallback(Dart_Isolate dart_isolate,\n Dart_Port port) {\n \/\/ Remove the pending messages for this port.\n Isolate* isolate = reinterpret_cast(dart_isolate);\n ASSERT(isolate != NULL);\n if (port == kCloseAllPorts) {\n isolate->message_queue()->FlushAll();\n } else {\n isolate->message_queue()->Flush(port);\n }\n}\n\n\nIsolate* Isolate::Init() {\n Isolate* result = new Isolate();\n ASSERT(result != NULL);\n\n \/\/ TODO(5411455): For now just set the recently created isolate as\n \/\/ the current isolate.\n SetCurrent(result);\n\n \/\/ Set up the isolate message queue.\n MessageQueue* queue = new MessageQueue();\n ASSERT(queue != NULL);\n result->set_message_queue(queue);\n result->set_post_message_callback(&StandardPostMessageCallback);\n result->set_close_port_callback(&StandardClosePortCallback);\n\n \/\/ Setup the Dart API state.\n ApiState* state = new ApiState();\n ASSERT(state != NULL);\n result->set_api_state(state);\n\n \/\/ Initialize stack top and limit in case we are running the isolate in the\n \/\/ main thread.\n \/\/ TODO(5411455): Need to figure out how to set the stack limit for the\n \/\/ main thread.\n result->SetStackLimitFromCurrentTOS(reinterpret_cast(&result));\n\n return result;\n}\n\n\n\/\/ TODO(5411455): Use flag to override default value and Validate the\n\/\/ stack size by querying OS.\nuword Isolate::GetSpecifiedStackSize() {\n uword stack_size = Isolate::kDefaultStackSize - Isolate::kStackSizeBuffer;\n return stack_size;\n}\n\n\nvoid Isolate::SetStackLimitFromCurrentTOS(uword stack_top_value) {\n SetStackLimit(stack_top_value - GetSpecifiedStackSize());\n}\n\n\nvoid Isolate::SetStackLimit(uword limit) {\n stack_limit_ = limit;\n stack_limit_on_overflow_exception_ = limit - kStackSizeBuffer;\n}\n\n\nstatic int MostCalledFunctionFirst(const Function* const* a,\n const Function* const* b) {\n if ((*a)->invocation_counter() > (*b)->invocation_counter()) {\n return -1;\n } else if ((*a)->invocation_counter() < (*b)->invocation_counter()) {\n return 1;\n } else {\n return 0;\n }\n}\n\n\nvoid Isolate::PrintInvokedFunctions() {\n Zone zone;\n HandleScope handle_scope;\n Library& library = Library::Handle();\n library = object_store()->registered_libraries();\n GrowableArray invoked_functions;\n while (!library.IsNull()) {\n Class& cls = Class::Handle();\n ClassDictionaryIterator iter(library);\n while (iter.HasNext()) {\n cls = iter.GetNextClass();\n const Array& functions = Array::Handle(cls.functions());\n for (int j = 0; j < functions.Length(); j++) {\n Function& function = Function::Handle();\n function ^= functions.At(j);\n if (function.invocation_counter() > 0) {\n invoked_functions.Add(&function);\n }\n }\n }\n library = library.next_registered();\n }\n invoked_functions.Sort(MostCalledFunctionFirst);\n for (int i = 0; i < invoked_functions.length(); i++) {\n OS::Print(\"%10d x %s\\n\",\n invoked_functions[i]->invocation_counter(),\n invoked_functions[i]->ToFullyQualifiedCString());\n }\n}\n\n\nvoid Isolate::Shutdown() {\n ASSERT(this == Isolate::Current());\n ASSERT(top_resource_ == NULL);\n ASSERT((heap_ == NULL) || heap_->Verify());\n\n \/\/ Close all the ports owned by this isolate.\n PortMap::ClosePorts();\n\n delete message_queue();\n set_message_queue(NULL);\n\n \/\/ Dump all accumalated timer data for the isolate.\n timer_list_.ReportTimers();\n if (FLAG_report_invocation_count) {\n PrintInvokedFunctions();\n }\n CompilerStats::Print();\n if (FLAG_generate_gdb_symbols) {\n DebugInfo::UnregisterAllSections();\n }\n\n \/\/ TODO(5411455): For now just make sure there are no current isolates\n \/\/ as we are shutting down the isolate.\n SetCurrent(NULL);\n}\n\n\nDart_IsolateInitCallback Isolate::init_callback_ = NULL;\n\n\nvoid Isolate::SetInitCallback(Dart_IsolateInitCallback callback) {\n init_callback_ = callback;\n}\n\n\nDart_IsolateInitCallback Isolate::InitCallback() {\n return init_callback_;\n}\n\n\nvoid Isolate::StandardRunLoop() {\n ASSERT(long_jump_base() != NULL);\n ASSERT(post_message_callback() == &StandardPostMessageCallback);\n ASSERT(close_port_callback() == &StandardClosePortCallback);\n\n while (active_ports() > 0) {\n Zone zone;\n HandleScope handle_scope;\n\n PortMessage* message = message_queue()->Dequeue(0);\n if (message != NULL) {\n Dart_HandleMessage(\n message->dest_port(), message->reply_port(), message->data());\n delete message;\n }\n }\n}\n\n\nvoid Isolate::VisitObjectPointers(ObjectPointerVisitor* visitor,\n bool validate_frames) {\n ASSERT(visitor != NULL);\n\n \/\/ Visit objects in the object store.\n object_store()->VisitObjectPointers(visitor);\n\n \/\/ Visit objects in per isolate stubs.\n StubCode::VisitObjectPointers(visitor);\n\n \/\/ Visit objects in zones.\n current_zone()->VisitObjectPointers(visitor);\n\n \/\/ Iterate over all the stack frames and visit objects on the stack.\n StackFrameIterator frames_iterator(validate_frames);\n StackFrame* frame = frames_iterator.NextFrame();\n while (frame != NULL) {\n frame->VisitObjectPointers(visitor);\n frame = frames_iterator.NextFrame();\n }\n\n \/\/ Visit the dart api state for all local and persistent handles.\n if (api_state() != NULL) {\n api_state()->VisitObjectPointers(visitor);\n }\n\n \/\/ Visit all objects in the code index table.\n if (code_index_table() != NULL) {\n code_index_table()->VisitObjectPointers(visitor);\n }\n\n \/\/ Visit the top context which is stored in the isolate.\n visitor->VisitPointer(reinterpret_cast(&top_context_));\n}\n\n} \/\/ namespace dart\nFix crash when running with --report_invocation_count. Review URL: http:\/\/codereview.chromium.org\/\/8497032\/\/ Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/isolate.h\"\n\n#include \"include\/dart_api.h\"\n\n#include \"vm\/assert.h\"\n#include \"vm\/bigint_store.h\"\n#include \"vm\/code_index_table.h\"\n#include \"vm\/compiler_stats.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/debuginfo.h\"\n#include \"vm\/heap.h\"\n#include \"vm\/message_queue.h\"\n#include \"vm\/object_store.h\"\n#include \"vm\/parser.h\"\n#include \"vm\/port.h\"\n#include \"vm\/random.h\"\n#include \"vm\/stack_frame.h\"\n#include \"vm\/stub_code.h\"\n#include \"vm\/thread.h\"\n#include \"vm\/timer.h\"\n#include \"vm\/visitor.h\"\n\nnamespace dart {\n\nDEFINE_FLAG(bool, report_invocation_count, false,\n \"Count function invocations and report.\");\nDECLARE_FLAG(bool, generate_gdb_symbols);\n\n\nIsolate::Isolate()\n : store_buffer_(),\n message_queue_(NULL),\n post_message_callback_(NULL),\n close_port_callback_(NULL),\n active_ports_(0),\n heap_(NULL),\n object_store_(NULL),\n top_resource_(NULL),\n top_context_(Context::null()),\n current_zone_(NULL),\n#if defined(DEBUG)\n no_gc_scope_depth_(0),\n no_handle_scope_depth_(0),\n top_handle_scope_(NULL),\n#endif\n random_seed_(Random::kDefaultRandomSeed),\n bigint_store_(NULL),\n top_exit_frame_info_(0),\n init_callback_data_(NULL),\n library_tag_handler_(NULL),\n api_state_(NULL),\n stub_code_(NULL),\n code_index_table_(NULL),\n long_jump_base_(NULL),\n timer_list_(),\n stack_limit_(0),\n stack_limit_on_overflow_exception_(0),\n ast_node_id_(AstNode::kNoId) {\n}\n\n\nIsolate::~Isolate() {\n delete message_queue_;\n delete heap_;\n delete object_store_;\n \/\/ Do not delete stack resources: top_resource_ and current_zone_.\n delete bigint_store_;\n delete api_state_;\n delete stub_code_;\n delete code_index_table_;\n}\n\n\nstatic bool StandardPostMessageCallback(Dart_Isolate dart_isolate,\n Dart_Port dest_port,\n Dart_Port reply_port,\n Dart_Message dart_message) {\n Isolate* isolate = reinterpret_cast(dart_isolate);\n ASSERT(isolate != NULL);\n PortMessage* message = new PortMessage(dest_port, reply_port, dart_message);\n isolate->message_queue()->Enqueue(message);\n return true;\n}\n\n\nstatic void StandardClosePortCallback(Dart_Isolate dart_isolate,\n Dart_Port port) {\n \/\/ Remove the pending messages for this port.\n Isolate* isolate = reinterpret_cast(dart_isolate);\n ASSERT(isolate != NULL);\n if (port == kCloseAllPorts) {\n isolate->message_queue()->FlushAll();\n } else {\n isolate->message_queue()->Flush(port);\n }\n}\n\n\nIsolate* Isolate::Init() {\n Isolate* result = new Isolate();\n ASSERT(result != NULL);\n\n \/\/ TODO(5411455): For now just set the recently created isolate as\n \/\/ the current isolate.\n SetCurrent(result);\n\n \/\/ Set up the isolate message queue.\n MessageQueue* queue = new MessageQueue();\n ASSERT(queue != NULL);\n result->set_message_queue(queue);\n result->set_post_message_callback(&StandardPostMessageCallback);\n result->set_close_port_callback(&StandardClosePortCallback);\n\n \/\/ Setup the Dart API state.\n ApiState* state = new ApiState();\n ASSERT(state != NULL);\n result->set_api_state(state);\n\n \/\/ Initialize stack top and limit in case we are running the isolate in the\n \/\/ main thread.\n \/\/ TODO(5411455): Need to figure out how to set the stack limit for the\n \/\/ main thread.\n result->SetStackLimitFromCurrentTOS(reinterpret_cast(&result));\n\n return result;\n}\n\n\n\/\/ TODO(5411455): Use flag to override default value and Validate the\n\/\/ stack size by querying OS.\nuword Isolate::GetSpecifiedStackSize() {\n uword stack_size = Isolate::kDefaultStackSize - Isolate::kStackSizeBuffer;\n return stack_size;\n}\n\n\nvoid Isolate::SetStackLimitFromCurrentTOS(uword stack_top_value) {\n SetStackLimit(stack_top_value - GetSpecifiedStackSize());\n}\n\n\nvoid Isolate::SetStackLimit(uword limit) {\n stack_limit_ = limit;\n stack_limit_on_overflow_exception_ = limit - kStackSizeBuffer;\n}\n\n\nstatic int MostCalledFunctionFirst(const Function* const* a,\n const Function* const* b) {\n if ((*a)->invocation_counter() > (*b)->invocation_counter()) {\n return -1;\n } else if ((*a)->invocation_counter() < (*b)->invocation_counter()) {\n return 1;\n } else {\n return 0;\n }\n}\n\n\nvoid Isolate::PrintInvokedFunctions() {\n Zone zone;\n HandleScope handle_scope;\n Library& library = Library::Handle();\n library = object_store()->registered_libraries();\n GrowableArray invoked_functions;\n while (!library.IsNull()) {\n Class& cls = Class::Handle();\n ClassDictionaryIterator iter(library);\n while (iter.HasNext()) {\n cls = iter.GetNextClass();\n const Array& functions = Array::Handle(cls.functions());\n \/\/ Class 'Dynamic' is allocated\/initialized in a special way, leaving\n \/\/ the functions field NULL instead of empty.\n const int func_len = functions.IsNull() ? 0 : functions.Length();\n for (int j = 0; j < func_len; j++) {\n Function& function = Function::Handle();\n function ^= functions.At(j);\n if (function.invocation_counter() > 0) {\n invoked_functions.Add(&function);\n }\n }\n }\n library = library.next_registered();\n }\n invoked_functions.Sort(MostCalledFunctionFirst);\n for (int i = 0; i < invoked_functions.length(); i++) {\n OS::Print(\"%10d x %s\\n\",\n invoked_functions[i]->invocation_counter(),\n invoked_functions[i]->ToFullyQualifiedCString());\n }\n}\n\n\nvoid Isolate::Shutdown() {\n ASSERT(this == Isolate::Current());\n ASSERT(top_resource_ == NULL);\n ASSERT((heap_ == NULL) || heap_->Verify());\n\n \/\/ Close all the ports owned by this isolate.\n PortMap::ClosePorts();\n\n delete message_queue();\n set_message_queue(NULL);\n\n \/\/ Dump all accumalated timer data for the isolate.\n timer_list_.ReportTimers();\n if (FLAG_report_invocation_count) {\n PrintInvokedFunctions();\n }\n CompilerStats::Print();\n if (FLAG_generate_gdb_symbols) {\n DebugInfo::UnregisterAllSections();\n }\n\n \/\/ TODO(5411455): For now just make sure there are no current isolates\n \/\/ as we are shutting down the isolate.\n SetCurrent(NULL);\n}\n\n\nDart_IsolateInitCallback Isolate::init_callback_ = NULL;\n\n\nvoid Isolate::SetInitCallback(Dart_IsolateInitCallback callback) {\n init_callback_ = callback;\n}\n\n\nDart_IsolateInitCallback Isolate::InitCallback() {\n return init_callback_;\n}\n\n\nvoid Isolate::StandardRunLoop() {\n ASSERT(long_jump_base() != NULL);\n ASSERT(post_message_callback() == &StandardPostMessageCallback);\n ASSERT(close_port_callback() == &StandardClosePortCallback);\n\n while (active_ports() > 0) {\n Zone zone;\n HandleScope handle_scope;\n\n PortMessage* message = message_queue()->Dequeue(0);\n if (message != NULL) {\n Dart_HandleMessage(\n message->dest_port(), message->reply_port(), message->data());\n delete message;\n }\n }\n}\n\n\nvoid Isolate::VisitObjectPointers(ObjectPointerVisitor* visitor,\n bool validate_frames) {\n ASSERT(visitor != NULL);\n\n \/\/ Visit objects in the object store.\n object_store()->VisitObjectPointers(visitor);\n\n \/\/ Visit objects in per isolate stubs.\n StubCode::VisitObjectPointers(visitor);\n\n \/\/ Visit objects in zones.\n current_zone()->VisitObjectPointers(visitor);\n\n \/\/ Iterate over all the stack frames and visit objects on the stack.\n StackFrameIterator frames_iterator(validate_frames);\n StackFrame* frame = frames_iterator.NextFrame();\n while (frame != NULL) {\n frame->VisitObjectPointers(visitor);\n frame = frames_iterator.NextFrame();\n }\n\n \/\/ Visit the dart api state for all local and persistent handles.\n if (api_state() != NULL) {\n api_state()->VisitObjectPointers(visitor);\n }\n\n \/\/ Visit all objects in the code index table.\n if (code_index_table() != NULL) {\n code_index_table()->VisitObjectPointers(visitor);\n }\n\n \/\/ Visit the top context which is stored in the isolate.\n visitor->VisitPointer(reinterpret_cast(&top_context_));\n}\n\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/*! \\file gather.inl\n * \\brief Inline file for gather.h.\n *\/\n\n#include \n#include \n\n#include \n\nnamespace thrust\n{\n\ntemplate\n OutputIterator gather(InputIterator map_first,\n InputIterator map_last,\n RandomAccessIterator input_first,\n OutputIterator result)\n{\n return thrust::copy(thrust::make_permutation_iterator(input_first, map_first),\n thrust::make_permutation_iterator(input_first, map_last),\n result);\n} \/\/ end gather()\n\n\ntemplate\n OutputIterator gather_if(InputIterator1 map_first,\n InputIterator1 map_last,\n InputIterator2 stencil,\n RandomAccessIterator input_first,\n OutputIterator result)\n{\n typedef typename thrust::iterator_value::type StencilType;\n return thrust::gather_if(map_first,\n map_last,\n stencil,\n input_first,\n result,\n thrust::identity());\n} \/\/ end gather_if()\n\n\ntemplate\n OutputIterator gather_if(InputIterator1 map_first,\n InputIterator1 map_last,\n InputIterator2 stencil,\n RandomAccessIterator input_first,\n OutputIterator result,\n Predicate pred)\n{\n return thrust::copy_when(thrust::make_permutation_iterator(input_first, map_first),\n thrust::make_permutation_iterator(input_first, map_last),\n stencil,\n result,\n pred);\n} \/\/ end gather_if()\n\n} \/\/ end namespace thrust\n\nImplement gather_if with transform_if + identity instead of copy_when\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/*! \\file gather.inl\n * \\brief Inline file for gather.h.\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace thrust\n{\n\ntemplate\n OutputIterator gather(InputIterator map_first,\n InputIterator map_last,\n RandomAccessIterator input_first,\n OutputIterator result)\n{\n return thrust::copy(thrust::make_permutation_iterator(input_first, map_first),\n thrust::make_permutation_iterator(input_first, map_last),\n result);\n} \/\/ end gather()\n\n\ntemplate\n OutputIterator gather_if(InputIterator1 map_first,\n InputIterator1 map_last,\n InputIterator2 stencil,\n RandomAccessIterator input_first,\n OutputIterator result)\n{\n typedef typename thrust::iterator_value::type StencilType;\n return thrust::gather_if(map_first,\n map_last,\n stencil,\n input_first,\n result,\n thrust::identity());\n} \/\/ end gather_if()\n\n\ntemplate\n OutputIterator gather_if(InputIterator1 map_first,\n InputIterator1 map_last,\n InputIterator2 stencil,\n RandomAccessIterator input_first,\n OutputIterator result,\n Predicate pred)\n{\n typedef typename thrust::iterator_value::type InputType;\n return thrust::transform_if(thrust::make_permutation_iterator(input_first, map_first),\n thrust::make_permutation_iterator(input_first, map_last),\n stencil,\n result,\n thrust::identity(),\n pred);\n} \/\/ end gather_if()\n\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace csharp {\n\nUmbrellaClassGenerator::UmbrellaClassGenerator(const FileDescriptor* file)\n : SourceGeneratorBase(file),\n file_(file) {\n namespace_ = GetFileNamespace(file);\n umbrellaClassname_ = GetUmbrellaClassUnqualifiedName(file);\n umbrellaNamespace_ = GetUmbrellaClassNestedNamespace(file);\n}\n\nUmbrellaClassGenerator::~UmbrellaClassGenerator() {\n}\n\nvoid UmbrellaClassGenerator::Generate(io::Printer* printer) {\n WriteIntroduction(printer);\n\n WriteDescriptor(printer);\n \/\/ Close the class declaration.\n printer->Outdent();\n printer->Print(\"}\\n\");\n\n \/\/ Close the namespace around the umbrella class if defined\n if (!umbrellaNamespace_.empty()) {\n printer->Outdent();\n printer->Print(\"}\\n\");\n }\n\n \/\/ write children: Enums\n if (file_->enum_type_count() > 0) {\n printer->Print(\"#region Enums\\n\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n EnumGenerator enumGenerator(file_->enum_type(i));\n enumGenerator.Generate(printer);\n }\n printer->Print(\"#endregion\\n\");\n printer->Print(\"\\n\");\n }\n\n \/\/ write children: Messages\n if (file_->message_type_count() > 0) {\n printer->Print(\"#region Messages\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n MessageGenerator messageGenerator(file_->message_type(i));\n messageGenerator.Generate(printer);\n }\n printer->Print(\"#endregion\\n\");\n printer->Print(\"\\n\");\n }\n\n \/\/ TODO(jtattermusch): add insertion point for services.\n\n if (!namespace_.empty()) {\n printer->Outdent();\n printer->Print(\"}\\n\");\n }\n printer->Print(\"\\n\");\n printer->Print(\"#endregion Designer generated code\\n\");\n}\n\nvoid UmbrellaClassGenerator::WriteIntroduction(io::Printer* printer) {\n printer->Print(\n \"\/\/ Generated by the protocol buffer compiler. DO NOT EDIT!\\n\"\n \"\/\/ source: $file_name$\\n\"\n \"#pragma warning disable 1591, 0612, 3021\\n\"\n \"#region Designer generated code\\n\"\n \"\\n\"\n \"using pb = global::Google.Protobuf;\\n\"\n \"using pbc = global::Google.Protobuf.Collections;\\n\"\n \"using pbr = global::Google.Protobuf.Reflection;\\n\"\n \"using scg = global::System.Collections.Generic;\\n\",\n \"file_name\", file_->name());\n\n if (!namespace_.empty()) {\n printer->Print(\"namespace $namespace$ {\\n\", \"namespace\", namespace_);\n printer->Indent();\n printer->Print(\"\\n\");\n }\n\n \/\/ Add the namespace around the umbrella class if defined\n if (!umbrellaNamespace_.empty()) {\n printer->Print(\"namespace $umbrella_namespace$ {\\n\",\n \"umbrella_namespace\", umbrellaNamespace_);\n printer->Indent();\n printer->Print(\"\\n\");\n }\n\n printer->Print(\n \"[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\\n\");\n WriteGeneratedCodeAttributes(printer);\n printer->Print(\n \"$access_level$ static partial class $umbrella_class_name$ {\\n\"\n \"\\n\",\n \"access_level\", class_access_level(),\n \"umbrella_class_name\", umbrellaClassname_);\n printer->Indent();\n}\n\nvoid UmbrellaClassGenerator::WriteDescriptor(io::Printer* printer) {\n printer->Print(\n \"#region Descriptor\\n\"\n \"public static pbr::FileDescriptor Descriptor {\\n\"\n \" get { return descriptor; }\\n\"\n \"}\\n\"\n \"private static pbr::FileDescriptor descriptor;\\n\"\n \"\\n\"\n \"static $umbrella_class_name$() {\\n\",\n \"umbrella_class_name\", umbrellaClassname_);\n printer->Indent();\n printer->Print(\n \"byte[] descriptorData = global::System.Convert.FromBase64String(\\n\");\n printer->Indent();\n printer->Indent();\n printer->Print(\"string.Concat(\\n\");\n printer->Indent();\n\n \/\/ TODO(jonskeet): Consider a C#-escaping format here instead of just Base64.\n std::string base64 = FileDescriptorToBase64(file_);\n while (base64.size() > 60) {\n printer->Print(\"\\\"$base64$\\\", \\n\", \"base64\", base64.substr(0, 60));\n base64 = base64.substr(60);\n }\n printer->Print(\"\\\"$base64$\\\"));\\n\", \"base64\", base64);\n printer->Outdent();\n printer->Outdent();\n printer->Outdent();\n\n \/\/ -----------------------------------------------------------------\n \/\/ Invoke InternalBuildGeneratedFileFrom() to build the file.\n printer->Print(\n \"descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,\\n\");\n printer->Print(\" new pbr::FileDescriptor[] { \");\n for (int i = 0; i < file_->dependency_count(); i++) {\n \/\/ descriptor.proto is special: we don't allow access to the generated code, but there's\n \/\/ a separately-exposed property to get at the file descriptor, specifically to allow this\n \/\/ kind of dependency.\n if (IsDescriptorProto(file_->dependency(i))) {\n printer->Print(\"pbr::FileDescriptor.DescriptorProtoFileDescriptor, \");\n } else {\n printer->Print(\n \"$full_umbrella_class_name$.Descriptor, \",\n \"full_umbrella_class_name\",\n GetUmbrellaClassName(file_->dependency(i)));\n }\n }\n printer->Print(\"},\\n\"\n \" new pbr::GeneratedCodeInfo(\");\n \/\/ Specify all the generated code information, recursively.\n if (file_->enum_type_count() > 0) {\n printer->Print(\"new[] {\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n printer->Print(\"typeof($type_name$), \", \"type_name\", GetClassName(file_->enum_type(i)));\n }\n printer->Print(\"}, \");\n }\n else {\n printer->Print(\"null, \");\n }\n if (file_->message_type_count() > 0) {\n printer->Print(\"new pbr::GeneratedCodeInfo[] {\\n\");\n printer->Indent();\n printer->Indent();\n printer->Indent();\n for (int i = 0; i < file_->message_type_count(); i++) {\n WriteGeneratedCodeInfo(file_->message_type(i), printer, i == file_->message_type_count() - 1);\n }\n printer->Outdent();\n printer->Print(\"\\n}));\\n\");\n printer->Outdent();\n printer->Outdent();\n }\n else {\n printer->Print(\"null));\\n\");\n }\n\n printer->Outdent();\n printer->Print(\"}\\n\");\n printer->Print(\"#endregion\\n\\n\");\n}\n\n\/\/ Write out the generated code for a particular message. This consists of the CLR type, property names\n\/\/ corresponding to fields, names corresponding to oneofs, nested enums, and nested types. Each array part\n\/\/ can be specified as null if it would be empty, to make the generated code somewhat simpler to read.\n\/\/ We write a line break at the end of each generated code info, so that in the final file we'll see all\n\/\/ the types, pre-ordered depth first, one per line. The indentation will be slightly unusual,\n\/\/ in that it will look like a single array when it's actually constructing a tree, but it'll be easy to\n\/\/ read even with multiple levels of nesting.\n\/\/ The \"last\" parameter indicates whether this message descriptor is the last one being printed in this immediate\n\/\/ context. It governs whether or not a trailing comma and newline is written after the constructor, effectively\n\/\/ just controlling the formatting in the generated code.\nvoid UmbrellaClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descriptor, io::Printer* printer, bool last) {\n if (IsMapEntryMessage(descriptor)) {\n printer->Print(\"null, \");\n return;\n }\n \/\/ Generated message type\n printer->Print(\"new pbr::GeneratedCodeInfo(typeof($type_name$), \", \"type_name\", GetClassName(descriptor));\n \n \/\/ Fields\n if (descriptor->field_count() > 0) {\n std::vector fields;\n for (int i = 0; i < descriptor->field_count(); i++) {\n fields.push_back(GetPropertyName(descriptor->field(i)));\n }\n printer->Print(\"new[]{ \\\"$fields$\\\" }, \", \"fields\", JoinStrings(fields, \"\\\", \\\"\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Oneofs\n if (descriptor->oneof_decl_count() > 0) {\n std::vector oneofs;\n for (int i = 0; i < descriptor->oneof_decl_count(); i++) {\n oneofs.push_back(UnderscoresToCamelCase(descriptor->oneof_decl(i)->name(), true));\n }\n printer->Print(\"new[]{ \\\"$oneofs$\\\" }, \", \"oneofs\", JoinStrings(oneofs, \"\\\", \\\"\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Nested enums\n if (descriptor->enum_type_count() > 0) {\n std::vector enums;\n for (int i = 0; i < descriptor->enum_type_count(); i++) {\n enums.push_back(GetClassName(descriptor->enum_type(i)));\n }\n printer->Print(\"new[]{ typeof($enums$) }, \", \"enums\", JoinStrings(enums, \"), typeof(\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Nested types\n if (descriptor->nested_type_count() > 0) {\n \/\/ Need to specify array type explicitly here, as all elements may be null. \n printer->Print(\"new pbr::GeneratedCodeInfo[] { \");\n for (int i = 0; i < descriptor->nested_type_count(); i++) {\n WriteGeneratedCodeInfo(descriptor->nested_type(i), printer, i == descriptor->nested_type_count() - 1);\n }\n printer->Print(\"}\");\n }\n else {\n printer->Print(\"null\");\n }\n printer->Print(last ? \")\" : \"),\\n\");\n}\n\n} \/\/ namespace csharp\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\nStop adding a space to the end of lines for descriptor binary data.\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2008 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace google {\nnamespace protobuf {\nnamespace compiler {\nnamespace csharp {\n\nUmbrellaClassGenerator::UmbrellaClassGenerator(const FileDescriptor* file)\n : SourceGeneratorBase(file),\n file_(file) {\n namespace_ = GetFileNamespace(file);\n umbrellaClassname_ = GetUmbrellaClassUnqualifiedName(file);\n umbrellaNamespace_ = GetUmbrellaClassNestedNamespace(file);\n}\n\nUmbrellaClassGenerator::~UmbrellaClassGenerator() {\n}\n\nvoid UmbrellaClassGenerator::Generate(io::Printer* printer) {\n WriteIntroduction(printer);\n\n WriteDescriptor(printer);\n \/\/ Close the class declaration.\n printer->Outdent();\n printer->Print(\"}\\n\");\n\n \/\/ Close the namespace around the umbrella class if defined\n if (!umbrellaNamespace_.empty()) {\n printer->Outdent();\n printer->Print(\"}\\n\");\n }\n\n \/\/ write children: Enums\n if (file_->enum_type_count() > 0) {\n printer->Print(\"#region Enums\\n\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n EnumGenerator enumGenerator(file_->enum_type(i));\n enumGenerator.Generate(printer);\n }\n printer->Print(\"#endregion\\n\");\n printer->Print(\"\\n\");\n }\n\n \/\/ write children: Messages\n if (file_->message_type_count() > 0) {\n printer->Print(\"#region Messages\\n\");\n for (int i = 0; i < file_->message_type_count(); i++) {\n MessageGenerator messageGenerator(file_->message_type(i));\n messageGenerator.Generate(printer);\n }\n printer->Print(\"#endregion\\n\");\n printer->Print(\"\\n\");\n }\n\n \/\/ TODO(jtattermusch): add insertion point for services.\n\n if (!namespace_.empty()) {\n printer->Outdent();\n printer->Print(\"}\\n\");\n }\n printer->Print(\"\\n\");\n printer->Print(\"#endregion Designer generated code\\n\");\n}\n\nvoid UmbrellaClassGenerator::WriteIntroduction(io::Printer* printer) {\n printer->Print(\n \"\/\/ Generated by the protocol buffer compiler. DO NOT EDIT!\\n\"\n \"\/\/ source: $file_name$\\n\"\n \"#pragma warning disable 1591, 0612, 3021\\n\"\n \"#region Designer generated code\\n\"\n \"\\n\"\n \"using pb = global::Google.Protobuf;\\n\"\n \"using pbc = global::Google.Protobuf.Collections;\\n\"\n \"using pbr = global::Google.Protobuf.Reflection;\\n\"\n \"using scg = global::System.Collections.Generic;\\n\",\n \"file_name\", file_->name());\n\n if (!namespace_.empty()) {\n printer->Print(\"namespace $namespace$ {\\n\", \"namespace\", namespace_);\n printer->Indent();\n printer->Print(\"\\n\");\n }\n\n \/\/ Add the namespace around the umbrella class if defined\n if (!umbrellaNamespace_.empty()) {\n printer->Print(\"namespace $umbrella_namespace$ {\\n\",\n \"umbrella_namespace\", umbrellaNamespace_);\n printer->Indent();\n printer->Print(\"\\n\");\n }\n\n printer->Print(\n \"[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\\n\");\n WriteGeneratedCodeAttributes(printer);\n printer->Print(\n \"$access_level$ static partial class $umbrella_class_name$ {\\n\"\n \"\\n\",\n \"access_level\", class_access_level(),\n \"umbrella_class_name\", umbrellaClassname_);\n printer->Indent();\n}\n\nvoid UmbrellaClassGenerator::WriteDescriptor(io::Printer* printer) {\n printer->Print(\n \"#region Descriptor\\n\"\n \"public static pbr::FileDescriptor Descriptor {\\n\"\n \" get { return descriptor; }\\n\"\n \"}\\n\"\n \"private static pbr::FileDescriptor descriptor;\\n\"\n \"\\n\"\n \"static $umbrella_class_name$() {\\n\",\n \"umbrella_class_name\", umbrellaClassname_);\n printer->Indent();\n printer->Print(\n \"byte[] descriptorData = global::System.Convert.FromBase64String(\\n\");\n printer->Indent();\n printer->Indent();\n printer->Print(\"string.Concat(\\n\");\n printer->Indent();\n\n \/\/ TODO(jonskeet): Consider a C#-escaping format here instead of just Base64.\n std::string base64 = FileDescriptorToBase64(file_);\n while (base64.size() > 60) {\n printer->Print(\"\\\"$base64$\\\",\\n\", \"base64\", base64.substr(0, 60));\n base64 = base64.substr(60);\n }\n printer->Print(\"\\\"$base64$\\\"));\\n\", \"base64\", base64);\n printer->Outdent();\n printer->Outdent();\n printer->Outdent();\n\n \/\/ -----------------------------------------------------------------\n \/\/ Invoke InternalBuildGeneratedFileFrom() to build the file.\n printer->Print(\n \"descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,\\n\");\n printer->Print(\" new pbr::FileDescriptor[] { \");\n for (int i = 0; i < file_->dependency_count(); i++) {\n \/\/ descriptor.proto is special: we don't allow access to the generated code, but there's\n \/\/ a separately-exposed property to get at the file descriptor, specifically to allow this\n \/\/ kind of dependency.\n if (IsDescriptorProto(file_->dependency(i))) {\n printer->Print(\"pbr::FileDescriptor.DescriptorProtoFileDescriptor, \");\n } else {\n printer->Print(\n \"$full_umbrella_class_name$.Descriptor, \",\n \"full_umbrella_class_name\",\n GetUmbrellaClassName(file_->dependency(i)));\n }\n }\n printer->Print(\"},\\n\"\n \" new pbr::GeneratedCodeInfo(\");\n \/\/ Specify all the generated code information, recursively.\n if (file_->enum_type_count() > 0) {\n printer->Print(\"new[] {\");\n for (int i = 0; i < file_->enum_type_count(); i++) {\n printer->Print(\"typeof($type_name$), \", \"type_name\", GetClassName(file_->enum_type(i)));\n }\n printer->Print(\"}, \");\n }\n else {\n printer->Print(\"null, \");\n }\n if (file_->message_type_count() > 0) {\n printer->Print(\"new pbr::GeneratedCodeInfo[] {\\n\");\n printer->Indent();\n printer->Indent();\n printer->Indent();\n for (int i = 0; i < file_->message_type_count(); i++) {\n WriteGeneratedCodeInfo(file_->message_type(i), printer, i == file_->message_type_count() - 1);\n }\n printer->Outdent();\n printer->Print(\"\\n}));\\n\");\n printer->Outdent();\n printer->Outdent();\n }\n else {\n printer->Print(\"null));\\n\");\n }\n\n printer->Outdent();\n printer->Print(\"}\\n\");\n printer->Print(\"#endregion\\n\\n\");\n}\n\n\/\/ Write out the generated code for a particular message. This consists of the CLR type, property names\n\/\/ corresponding to fields, names corresponding to oneofs, nested enums, and nested types. Each array part\n\/\/ can be specified as null if it would be empty, to make the generated code somewhat simpler to read.\n\/\/ We write a line break at the end of each generated code info, so that in the final file we'll see all\n\/\/ the types, pre-ordered depth first, one per line. The indentation will be slightly unusual,\n\/\/ in that it will look like a single array when it's actually constructing a tree, but it'll be easy to\n\/\/ read even with multiple levels of nesting.\n\/\/ The \"last\" parameter indicates whether this message descriptor is the last one being printed in this immediate\n\/\/ context. It governs whether or not a trailing comma and newline is written after the constructor, effectively\n\/\/ just controlling the formatting in the generated code.\nvoid UmbrellaClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descriptor, io::Printer* printer, bool last) {\n if (IsMapEntryMessage(descriptor)) {\n printer->Print(\"null, \");\n return;\n }\n \/\/ Generated message type\n printer->Print(\"new pbr::GeneratedCodeInfo(typeof($type_name$), \", \"type_name\", GetClassName(descriptor));\n \n \/\/ Fields\n if (descriptor->field_count() > 0) {\n std::vector fields;\n for (int i = 0; i < descriptor->field_count(); i++) {\n fields.push_back(GetPropertyName(descriptor->field(i)));\n }\n printer->Print(\"new[]{ \\\"$fields$\\\" }, \", \"fields\", JoinStrings(fields, \"\\\", \\\"\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Oneofs\n if (descriptor->oneof_decl_count() > 0) {\n std::vector oneofs;\n for (int i = 0; i < descriptor->oneof_decl_count(); i++) {\n oneofs.push_back(UnderscoresToCamelCase(descriptor->oneof_decl(i)->name(), true));\n }\n printer->Print(\"new[]{ \\\"$oneofs$\\\" }, \", \"oneofs\", JoinStrings(oneofs, \"\\\", \\\"\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Nested enums\n if (descriptor->enum_type_count() > 0) {\n std::vector enums;\n for (int i = 0; i < descriptor->enum_type_count(); i++) {\n enums.push_back(GetClassName(descriptor->enum_type(i)));\n }\n printer->Print(\"new[]{ typeof($enums$) }, \", \"enums\", JoinStrings(enums, \"), typeof(\"));\n }\n else {\n printer->Print(\"null, \");\n }\n\n \/\/ Nested types\n if (descriptor->nested_type_count() > 0) {\n \/\/ Need to specify array type explicitly here, as all elements may be null. \n printer->Print(\"new pbr::GeneratedCodeInfo[] { \");\n for (int i = 0; i < descriptor->nested_type_count(); i++) {\n WriteGeneratedCodeInfo(descriptor->nested_type(i), printer, i == descriptor->nested_type_count() - 1);\n }\n printer->Print(\"}\");\n }\n else {\n printer->Print(\"null\");\n }\n printer->Print(last ? \")\" : \"),\\n\");\n}\n\n} \/\/ namespace csharp\n} \/\/ namespace compiler\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_update_ec_state.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\/\/\/ @file p10_update_ec_state.C\n\/\/\/ @brief Update the core configured data in CCSR register and then deals with\n\/\/\/ deconfigured cores to verify the chiplet state..if it is still running then\n\/\/\/ will put the core to stop 11 state\n\/\/\/\n\/\/\/ *HWP HW Owner : Greg Still \n\/\/\/ *HWP FW Owner : Prasad Bg Ranganath \n\/\/\/ *HWP Team : PM\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB,PGPE,CME,OCC\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include \"p10_update_ec_state.H\"\n#include \n#include \"p10_hcd_common.H\"\n#include \"p10_hcd_cache_stopclocks.H\"\n#include \"p10_hcd_core_poweroff.H\"\n#include \"p10_hcd_l3_purge.H\"\n#include \"p10_hcd_l2_purge.H\"\n#include \"p10_hcd_powerbus_purge.H\"\n#include \"p10_hcd_l2_tlbie_quiesce.H\"\n#include \"p10_hcd_ncu_purge.H\"\n#include \"p10_hcd_chtm_purge.H\"\n#include \"p10_hcd_core_stopclocks.H\"\n#include \"p10_hcd_cache_poweroff.H\"\n#include \"p10_hcd_core_shadows_disable.H\"\n#include \"p10_hcd_core_stopgrid.H\"\n#include \n#include \n#include \n\n\nusing namespace scomt;\nusing namespace proc;\nusing namespace c;\nusing namespace eq;\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target& i_target);\n\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target& i_target);\n\n\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target& i_core_target,\n uint8_t i_core_unit_pos);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Constants\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ See .H for documentation\nfapi2::ReturnCode p10_update_ec_state(\n const fapi2::Target& i_target)\n{\n\n FAPI_IMP(\"> p10_update_ec_state\");\n\n FAPI_TRY(update_ec_config(i_target),\n \"Error update_core_config detected\");\n \/\/TODO Need to find the right way to get deconfigured target\n FAPI_TRY(verify_ec_hw_state(i_target));\n\nfapi_try_exit:\n FAPI_INF(\"< p10_update_ec_state\");\n\n return fapi2::current_err;\n} \/\/ END p10_update_ec_state\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target& i_target)\n{\n FAPI_INF (\">>verify_hw_state\");\n uint8_t l_core_unit_pos;\n\n std::vector >l_core_list;\n FAPI_TRY(getDeconfiguredTargets(i_target, l_core_list));\n\n for (auto l_core : l_core_list)\n {\n\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n l_core,\n l_core_unit_pos));\n FAPI_INF(\"Core present but non functional %d\",\n l_core_unit_pos);\n\n \/\/Check the clock state and power state\n FAPI_TRY(p10_check_core_l3_clock_power_state(l_core, l_core_unit_pos));\n\n }\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief Update the CCSR for cores\n\/\/\/\n\/\/\/ @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target& i_target)\n{\n FAPI_INF(\"> update_core_config...\");\n\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n fapi2::buffer l_core_config = 0;\n fapi2::buffer l_pscom_config = 0;\n\n auto l_core_present_vector =\n i_target.getChildren\n (fapi2::TARGET_STATE_PRESENT);\n\n auto l_core_functional_vector =\n i_target.getChildren\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_INF(\" Number of present cores = %d; Number of functional cores = %d\",\n l_core_present_vector.size(),\n l_core_functional_vector.size());\n\n \/\/ For each present core, set multicast groups and the CCSR\n for (auto core_present_it : l_core_present_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n FAPI_INF(\" Checking if present EC %d is functional\",\n l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_DBG(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n \/\/ Set the appropriate bit in the Core Configuration Status\n \/\/ Register buffer\n FAPI_INF(\" Setting EC %d as good in value to be written to CCSR\",\n l_present_core_unit_pos);\n l_core_config.setBit(l_present_core_unit_pos);\n\n auto l_eq = core_functional_it.getParent();\n\n l_present_core_unit_pos = l_present_core_unit_pos % 4;\n\n \/\/Update the pscom enable bit\n l_pscom_config.setBit(l_present_core_unit_pos + 5);\n\n FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));\n break;\n } \/\/ Current core\n } \/\/ Functional core loop\n } \/\/ Present core loop\n\n \/\/ Write the recalculated OCC Core Configuration Status Register\n FAPI_INF(\" Writing OCC CCSR\");\n FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));\n\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n#define CORE_START_POSITION 5\n#define CACHE_START_POSITION 9\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target& i_core_target,\n uint8_t i_core_unit_pos)\n{\n fapi2::buffer l_data = 0;\n uint64_t l_pfet_sense = 0;\n uint8_t l_core_relative_pos = i_core_unit_pos % 4;\n uint8_t l_l3_relative_pos = i_core_unit_pos % 4;\n uint8_t l_core_clock_State = 0;\n uint8_t l_l3_clock_State = 0;\n\n\n do\n {\n auto l_eq_target = i_core_target.getParent();\n \/\/Read the power state of core\/l2\n FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));\n GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);\n\n \/\/verify L3\/core clocks are on\n FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));\n l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);\n l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);\n\n \/\/Verify core is powered on\n \/\/If core is powered on\n \/\/ then if core(ECl2) clocks are on\n \/\/ then need to purge the l2 and stop the core clocks\n \/\/ if L3 clocks are on\n \/\/ then purge L3 and stop the l3 clocks\n \/\/ Power off the core and L3\n if( l_pfet_sense)\n {\n if (!l_core_clock_State)\n {\n FAPI_TRY(p10_hcd_l2_purge(i_core_target));\n FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));\n FAPI_TRY(p10_hcd_ncu_purge(i_core_target));\n FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));\n FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));\n FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_core_poweroff(i_core_target));\n\n if (!l_l3_clock_State)\n {\n FAPI_TRY(p10_hcd_chtm_purge(i_core_target));\n FAPI_TRY(p10_hcd_l3_purge(i_core_target));\n FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));\n FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));\n }\n }\n while(0);\n\nfapi_try_exit:\n FAPI_INF(\"< p10_check_core_clock_power_state...\");\n return fapi2::current_err;\n\n}\np10_update_ec_state - bypass deconfigured PFET check for now\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/pm\/p10_update_ec_state.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\/\/\/ @file p10_update_ec_state.C\n\/\/\/ @brief Update the core configured data in CCSR register and then deals with\n\/\/\/ deconfigured cores to verify the chiplet state..if it is still running then\n\/\/\/ will put the core to stop 11 state\n\/\/\/\n\/\/\/ *HWP HW Owner : Greg Still \n\/\/\/ *HWP FW Owner : Prasad Bg Ranganath \n\/\/\/ *HWP Team : PM\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB,PGPE,CME,OCC\n\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include \"p10_update_ec_state.H\"\n#include \n#include \"p10_hcd_common.H\"\n#include \"p10_hcd_cache_stopclocks.H\"\n#include \"p10_hcd_core_poweroff.H\"\n#include \"p10_hcd_l3_purge.H\"\n#include \"p10_hcd_l2_purge.H\"\n#include \"p10_hcd_powerbus_purge.H\"\n#include \"p10_hcd_l2_tlbie_quiesce.H\"\n#include \"p10_hcd_ncu_purge.H\"\n#include \"p10_hcd_chtm_purge.H\"\n#include \"p10_hcd_core_stopclocks.H\"\n#include \"p10_hcd_cache_poweroff.H\"\n#include \"p10_hcd_core_shadows_disable.H\"\n#include \"p10_hcd_core_stopgrid.H\"\n#include \n#include \n#include \n\n\nusing namespace scomt;\nusing namespace proc;\nusing namespace c;\nusing namespace eq;\n\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Function prototypes\n\/\/ -----------------------------------------------------------------------------\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target& i_target);\n\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target& i_target);\n\n\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target& i_core_target,\n uint8_t i_core_unit_pos);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Constants\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ See .H for documentation\nfapi2::ReturnCode p10_update_ec_state(\n const fapi2::Target& i_target)\n{\n\n FAPI_IMP(\"> p10_update_ec_state\");\n\n FAPI_TRY(update_ec_config(i_target),\n \"Error update_core_config detected\");\n \/\/TODO Need to find the right way to get deconfigured target\n FAPI_TRY(verify_ec_hw_state(i_target));\n\nfapi_try_exit:\n FAPI_INF(\"< p10_update_ec_state\");\n\n return fapi2::current_err;\n} \/\/ END p10_update_ec_state\n\nfapi2::ReturnCode verify_ec_hw_state(\n const fapi2::Target& i_target)\n{\n FAPI_INF (\">>verify_hw_state\");\n uint8_t l_core_unit_pos;\n\n std::vector >l_core_list;\n FAPI_TRY(getDeconfiguredTargets(i_target, l_core_list));\n\n for (auto l_core : l_core_list)\n {\n\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n l_core,\n l_core_unit_pos));\n FAPI_INF(\"Core present but non functional %d\",\n l_core_unit_pos);\n\n \/\/Check the clock state and power state\n\/\/ RTC 249759: temporarily enable deconfigured cores\/L3 to check for PFET state\n\/\/ FAPI_TRY(p10_check_core_l3_clock_power_state(l_core, l_core_unit_pos));\n\n }\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief Update the CCSR for cores\n\/\/\/\n\/\/\/ @param[in] i_target Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode update_ec_config(\n const fapi2::Target& i_target)\n{\n FAPI_INF(\"> update_core_config...\");\n\n uint8_t l_present_core_unit_pos;\n uint8_t l_functional_core_unit_pos;\n fapi2::buffer l_core_config = 0;\n fapi2::buffer l_pscom_config = 0;\n\n auto l_core_present_vector =\n i_target.getChildren\n (fapi2::TARGET_STATE_PRESENT);\n\n auto l_core_functional_vector =\n i_target.getChildren\n (fapi2::TARGET_STATE_FUNCTIONAL);\n\n FAPI_INF(\" Number of present cores = %d; Number of functional cores = %d\",\n l_core_present_vector.size(),\n l_core_functional_vector.size());\n\n \/\/ For each present core, set multicast groups and the CCSR\n for (auto core_present_it : l_core_present_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_present_it,\n l_present_core_unit_pos));\n\n FAPI_INF(\" Checking if present EC %d is functional\",\n l_present_core_unit_pos);\n\n for (auto core_functional_it : l_core_functional_vector)\n {\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n core_functional_it,\n l_functional_core_unit_pos));\n FAPI_DBG(\" Functional EC %d\",\n l_functional_core_unit_pos);\n\n if (l_functional_core_unit_pos == l_present_core_unit_pos)\n {\n \/\/ Set the appropriate bit in the Core Configuration Status\n \/\/ Register buffer\n FAPI_INF(\" Setting EC %d as good in value to be written to CCSR\",\n l_present_core_unit_pos);\n l_core_config.setBit(l_present_core_unit_pos);\n\n auto l_eq = core_functional_it.getParent();\n\n l_present_core_unit_pos = l_present_core_unit_pos % 4;\n\n \/\/Update the pscom enable bit\n l_pscom_config.setBit(l_present_core_unit_pos + 5);\n\n FAPI_TRY(fapi2::putScom(l_eq, CPLT_CTRL3_WO_OR, l_pscom_config));\n break;\n } \/\/ Current core\n } \/\/ Functional core loop\n } \/\/ Present core loop\n\n \/\/ Write the recalculated OCC Core Configuration Status Register\n FAPI_INF(\" Writing OCC CCSR\");\n FAPI_TRY(fapi2::putScom(i_target, TP_TPCHIP_OCC_OCI_OCB_CCSR_RW, l_core_config));\n\n\nfapi_try_exit:\n FAPI_INF(\"< update_core_config...\");\n return fapi2::current_err;\n\n}\n\n#define CORE_START_POSITION 5\n#define CACHE_START_POSITION 9\n\nfapi2::ReturnCode p10_check_core_l3_clock_power_state(\n const fapi2::Target& i_core_target,\n uint8_t i_core_unit_pos)\n{\n fapi2::buffer l_data = 0;\n uint64_t l_pfet_sense = 0;\n uint8_t l_core_relative_pos = i_core_unit_pos % 4;\n uint8_t l_l3_relative_pos = i_core_unit_pos % 4;\n uint8_t l_core_clock_State = 0;\n uint8_t l_l3_clock_State = 0;\n\n\n do\n {\n auto l_eq_target = i_core_target.getParent();\n \/\/Read the power state of core\/l2\n FAPI_TRY(GET_CPMS_CL2_PFETSTAT(i_core_target, l_data));\n GET_CPMS_CL2_PFETSTAT_VDD_PFETS_ENABLED_SENSE(l_data, l_pfet_sense);\n\n \/\/verify L3\/core clocks are on\n FAPI_TRY(GET_CLOCK_STAT_SL(l_eq_target, l_data));\n l_core_clock_State = l_data & BIT64(l_core_relative_pos + CORE_START_POSITION);\n l_l3_clock_State = l_data & BIT64(l_l3_relative_pos + CACHE_START_POSITION);\n\n \/\/Verify core is powered on\n \/\/If core is powered on\n \/\/ then if core(ECl2) clocks are on\n \/\/ then need to purge the l2 and stop the core clocks\n \/\/ if L3 clocks are on\n \/\/ then purge L3 and stop the l3 clocks\n \/\/ Power off the core and L3\n if( l_pfet_sense)\n {\n if (!l_core_clock_State)\n {\n FAPI_TRY(p10_hcd_l2_purge(i_core_target));\n FAPI_TRY(p10_hcd_l2_tlbie_quiesce(i_core_target));\n FAPI_TRY(p10_hcd_ncu_purge(i_core_target));\n FAPI_TRY(p10_hcd_core_shadows_disable(i_core_target));\n FAPI_TRY(p10_hcd_core_stopclocks(i_core_target));\n FAPI_TRY(p10_hcd_core_stopgrid(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_core_poweroff(i_core_target));\n\n if (!l_l3_clock_State)\n {\n FAPI_TRY(p10_hcd_chtm_purge(i_core_target));\n FAPI_TRY(p10_hcd_l3_purge(i_core_target));\n FAPI_TRY(p10_hcd_powerbus_purge(i_core_target));\n FAPI_TRY(p10_hcd_cache_stopclocks(i_core_target));\n }\n\n FAPI_TRY(p10_hcd_cache_poweroff(i_core_target));\n }\n }\n while(0);\n\nfapi_try_exit:\n FAPI_INF(\"< p10_check_core_clock_power_state...\");\n return fapi2::current_err;\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mutex.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 04:12:44 $\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 _OSL_MUTEX_HXX_\n#define _OSL_MUTEX_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n \/** A mutual exclusion synchronization object\n *\/\n class Mutex {\n\n public:\n \/** Create a thread-local mutex.\n @return 0 if the mutex could not be created, otherwise a handle to the mutex.\n @seealso ::osl_createMutex()\n *\/\n Mutex()\n {\n mutex = osl_createMutex();\n }\n\n \/** Release the OS-structures and free mutex data-structure.\n @seealso ::osl_destroyMutex()\n *\/\n ~Mutex()\n {\n osl_destroyMutex(mutex);\n }\n\n \/** Acquire the mutex, block if already acquired by another thread.\n @return sal_False if system-call fails.\n @seealso ::osl_acquireMutex()\n *\/\n sal_Bool acquire()\n {\n return osl_acquireMutex(mutex);\n }\n\n \/** Try to acquire the mutex without blocking.\n @return sal_False if it could not be acquired.\n @seealso ::osl_tryToAcquireMutex()\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireMutex(mutex);\n }\n\n \/** Release the mutex.\n @return sal_False if system-call fails.\n @seealso ::osl_releaseMutex()\n *\/\n sal_Bool release()\n {\n return osl_releaseMutex(mutex);\n }\n\n \/** Returns a global static mutex object.\n The global and static mutex object can be used to initialize other\n static objects in a thread safe manner.\n @return the global mutex object\n @seealso ::osl_getGlobalMutex()\n *\/\n static Mutex * getGlobalMutex()\n {\n return (Mutex *)osl_getGlobalMutex();\n }\n\n private:\n oslMutex mutex;\n\n \/** The underlying oslMutex has no reference count.\n\n Since the underlying oslMutex is not a reference counted object, copy\n constructed Mutex may work on an already destructed oslMutex object.\n\n *\/\n Mutex(const Mutex&);\n\n \/** The underlying oslMutex has no reference count.\n\n When destructed, the Mutex object destroys the undelying oslMutex,\n which might cause severe problems in case it's a temporary object.\n\n *\/\n Mutex(oslMutex Mutex);\n\n \/** This assignment operator is private for the same reason as\n the copy constructor.\n *\/\n Mutex& operator= (const Mutex&);\n\n \/** This assignment operator is private for the same reason as\n the constructor taking a oslMutex argument.\n *\/\n Mutex& operator= (oslMutex);\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class Guard\n {\n private:\n Guard( const Guard& );\n const Guard& operator = ( const Guard& );\n\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface. *\/\n ~Guard()\n {\n pT->release();\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class ClearableGuard\n {\n private:\n ClearableGuard( const ClearableGuard& );\n const ClearableGuard& operator = ( const ClearableGuard& );\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface if not already released by clear().\n *\/\n ~ClearableGuard()\n {\n if (pT)\n pT->release();\n }\n\n \/** Releases the mutex or interface.\n *\/\n void clear()\n {\n if(pT)\n {\n pT->release();\n pT = NULL;\n }\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template< class T >\n class ResettableGuard : public ClearableGuard< T >\n {\n private:\n ResettableGuard(ResettableGuard &); \/\/ not defined\n void operator =(ResettableGuard &); \/\/ not defined\n\n protected:\n T* pResetT;\n public:\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T* pT_ ) :\n ClearableGuard( pT_ ),\n pResetT( pT_ )\n {}\n\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T& rT ) :\n ClearableGuard( rT ),\n pResetT( &rT )\n {}\n\n \/** Re-aquires the mutex or interface.\n *\/\n void reset()\n {\n if( pResetT )\n {\n this->pT = pResetT;\n this->pT->acquire();\n }\n }\n };\n\n typedef Guard MutexGuard;\n typedef ClearableGuard ClearableMutexGuard;\n typedef ResettableGuard< Mutex > ResettableMutexGuard;\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_MUTEX_HXX_ *\/\n\nINTEGRATION: CWS changefileheader (1.13.268); FILE MERGED 2008\/03\/31 13:23:36 rt 1.13.268.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: mutex.hxx,v $\n * $Revision: 1.14 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _OSL_MUTEX_HXX_\n#define _OSL_MUTEX_HXX_\n\n#ifdef __cplusplus\n\n#include \n\n\nnamespace osl\n{\n \/** A mutual exclusion synchronization object\n *\/\n class Mutex {\n\n public:\n \/** Create a thread-local mutex.\n @return 0 if the mutex could not be created, otherwise a handle to the mutex.\n @seealso ::osl_createMutex()\n *\/\n Mutex()\n {\n mutex = osl_createMutex();\n }\n\n \/** Release the OS-structures and free mutex data-structure.\n @seealso ::osl_destroyMutex()\n *\/\n ~Mutex()\n {\n osl_destroyMutex(mutex);\n }\n\n \/** Acquire the mutex, block if already acquired by another thread.\n @return sal_False if system-call fails.\n @seealso ::osl_acquireMutex()\n *\/\n sal_Bool acquire()\n {\n return osl_acquireMutex(mutex);\n }\n\n \/** Try to acquire the mutex without blocking.\n @return sal_False if it could not be acquired.\n @seealso ::osl_tryToAcquireMutex()\n *\/\n sal_Bool tryToAcquire()\n {\n return osl_tryToAcquireMutex(mutex);\n }\n\n \/** Release the mutex.\n @return sal_False if system-call fails.\n @seealso ::osl_releaseMutex()\n *\/\n sal_Bool release()\n {\n return osl_releaseMutex(mutex);\n }\n\n \/** Returns a global static mutex object.\n The global and static mutex object can be used to initialize other\n static objects in a thread safe manner.\n @return the global mutex object\n @seealso ::osl_getGlobalMutex()\n *\/\n static Mutex * getGlobalMutex()\n {\n return (Mutex *)osl_getGlobalMutex();\n }\n\n private:\n oslMutex mutex;\n\n \/** The underlying oslMutex has no reference count.\n\n Since the underlying oslMutex is not a reference counted object, copy\n constructed Mutex may work on an already destructed oslMutex object.\n\n *\/\n Mutex(const Mutex&);\n\n \/** The underlying oslMutex has no reference count.\n\n When destructed, the Mutex object destroys the undelying oslMutex,\n which might cause severe problems in case it's a temporary object.\n\n *\/\n Mutex(oslMutex Mutex);\n\n \/** This assignment operator is private for the same reason as\n the copy constructor.\n *\/\n Mutex& operator= (const Mutex&);\n\n \/** This assignment operator is private for the same reason as\n the constructor taking a oslMutex argument.\n *\/\n Mutex& operator= (oslMutex);\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class Guard\n {\n private:\n Guard( const Guard& );\n const Guard& operator = ( const Guard& );\n\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n Guard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface. *\/\n ~Guard()\n {\n pT->release();\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template\n class ClearableGuard\n {\n private:\n ClearableGuard( const ClearableGuard& );\n const ClearableGuard& operator = ( const ClearableGuard& );\n protected:\n T * pT;\n public:\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T * pT_) : pT(pT_)\n {\n pT->acquire();\n }\n\n \/** Acquires the object specified as parameter.\n *\/\n ClearableGuard(T & t) : pT(&t)\n {\n pT->acquire();\n }\n\n \/** Releases the mutex or interface if not already released by clear().\n *\/\n ~ClearableGuard()\n {\n if (pT)\n pT->release();\n }\n\n \/** Releases the mutex or interface.\n *\/\n void clear()\n {\n if(pT)\n {\n pT->release();\n pT = NULL;\n }\n }\n };\n\n \/** A helper class for mutex objects and interfaces.\n *\/\n template< class T >\n class ResettableGuard : public ClearableGuard< T >\n {\n private:\n ResettableGuard(ResettableGuard &); \/\/ not defined\n void operator =(ResettableGuard &); \/\/ not defined\n\n protected:\n T* pResetT;\n public:\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T* pT_ ) :\n ClearableGuard( pT_ ),\n pResetT( pT_ )\n {}\n\n \/** Acquires the object specified as parameter.\n *\/\n ResettableGuard( T& rT ) :\n ClearableGuard( rT ),\n pResetT( &rT )\n {}\n\n \/** Re-aquires the mutex or interface.\n *\/\n void reset()\n {\n if( pResetT )\n {\n this->pT = pResetT;\n this->pT->acquire();\n }\n }\n };\n\n typedef Guard MutexGuard;\n typedef ClearableGuard ClearableMutexGuard;\n typedef ResettableGuard< Mutex > ResettableMutexGuard;\n}\n\n#endif \/* __cplusplus *\/\n#endif \/* _OSL_MUTEX_HXX_ *\/\n\n<|endoftext|>"} {"text":"\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n#include \n#include \n#include \/\/ memcpy\n#include \n#include \n\n#include \"tclap\/CmdLine.h\"\n#include \n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"..\/third-party\/stb_image.h\"\n\n\n#define RS_EMBED_VERSION \"0.0.0.1\"\n\nstruct float3\n{\n float x, y, z;\n};\n\nstruct short3\n{\n uint16_t x, y, z;\n};\n\nusing namespace std;\nusing namespace TCLAP;\n\nbool file_exists(const std::string& name) {\n std::ifstream f(name.c_str());\n return f.good();\n}\n\nstruct int6\n{\n int x, y, z, a, b, c;\n};\n\nbool ends_with(const std::string& s, const std::string& suffix)\n{\n auto i = s.rbegin(), j = suffix.rbegin();\n for (; i != s.rend() && j != suffix.rend() && *i == *j;\n i++, j++);\n return j == suffix.rend();\n}\n\nstd::string get_current_time()\n{\n auto t = time(nullptr);\n char buffer[20] = {};\n const tm* time = localtime(&t);\n if (nullptr != time)\n strftime(buffer, sizeof(buffer), \"%m\/%d\/%Y %H:%M:%S\", time);\n return std::string(buffer);\n}\n\nint main(int argc, char** argv) try\n{\n \/\/ Parse command line arguments\n CmdLine cmd(\"librealsense rs-embed tool\", ' ', RS_EMBED_VERSION);\n ValueArg inputFilename(\"i\", \"input\", \"Input filename\", true, \"\", \"input-file\");\n ValueArg outputFilename(\"o\", \"output\", \"Output filename\", false, \"\", \"output-file\");\n ValueArg objectName(\"n\", \"name\", \"Name\", false, \"\", \"object-name\");\n\n cmd.add(inputFilename);\n cmd.add(outputFilename);\n cmd.add(objectName);\n cmd.parse(argc, argv);\n\n auto input = inputFilename.getValue();\n auto output = outputFilename.getValue();\n auto name = objectName.getValue();\n\n if (ends_with(input, \".obj\"))\n {\n std::vector vertex_data;\n std::vector normals_raw_data;\n std::vector normals_data;\n std::vector index_raw_data;\n std::vector index_data;\n\n if (file_exists(input))\n {\n std::ifstream file(input);\n std::string str;\n while (std::getline(file, str))\n {\n if (str.size())\n {\n if (str[0] == 'v')\n {\n float a, b, c;\n if (str[1] == 'n')\n {\n sscanf(str.c_str(), \"vn %f %f %f\", &a, &b, &c);\n normals_raw_data.push_back({ a, b, c });\n }\n else\n {\n sscanf(str.c_str(), \"v %f %f %f\", &a, &b, &c);\n vertex_data.push_back({ a, b, c });\n }\n }\n if (str[0] == 'f')\n {\n int x, y, z, a, b, c; \n sscanf(str.c_str(), \"f %d\/\/%d %d\/\/%d %d\/\/%d\", &x, &a, &y, &b, &z, &c);\n index_raw_data.push_back({ x, y, z, a, b, c });\n }\n }\n }\n }\n else\n {\n std::cout << \"file: \" << input << \" could not be found!\" << std::endl;\n return EXIT_FAILURE;\n }\n\n normals_data.resize(vertex_data.size());\n for (auto& idx : index_raw_data)\n {\n \/\/ TODO - normals data are currently disabled\n \/\/ normals_data[idx.x] = normals_raw_data[idx.a];\n \/\/ normals_data[idx.y] = normals_raw_data[idx.b];\n \/\/ normals_data[idx.z] = normals_raw_data[idx.c];\n index_data.push_back({ static_cast(idx.x - 1),\n static_cast(idx.y - 1),\n static_cast(idx.z - 1) });\n }\n\n size_t vertex_data_size = vertex_data.size() * sizeof(float3);\n size_t index_data_size = index_data.size() * sizeof(short3);\n \/\/size_t normals_data_size = normals_data.size() * sizeof(float3);\n\n std::vector data(vertex_data_size + index_data_size, 0);\n memcpy(data.data(), vertex_data.data(), vertex_data_size);\n memcpy(data.data() + vertex_data_size, index_data.data(), index_data_size);\n \/\/memcpy(data.data() + vertex_data_size + index_data_size, normals_data.data(), normals_data_size);\n\n \/\/ compress szSource into pchCompressed\n auto rawDataSize = (int)data.size();\n auto compressBufSize = LZ4_compressBound(rawDataSize);\n char* pchCompressed = new char[compressBufSize];\n memset(pchCompressed, compressBufSize, 0);\n int nCompressedSize = LZ4_compress_default((const char*)data.data(), pchCompressed, rawDataSize, compressBufSize);\n\n \n ofstream myfile;\n myfile.open(output);\n myfile << \"\/\/ License: Apache 2.0. See LICENSE file in root directory.\\n\";\n myfile << \"\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\\n\\n\";\n myfile << \"\/\/ This file is auto-generated from \" << name << \".obj using rs-embed tool version: \" << RS_EMBED_VERSION <<\"\\n\";\n myfile << \"\/\/ Generation time: \" << get_current_time() << \".\\n\\n\";\n myfile << \"#pragma once\\n\";\n myfile << \"static uint32_t \" << name << \"_obj_data [] { \";\n\n auto nAllignedCompressedSize = nCompressedSize;\n auto leftover = nCompressedSize % 4;\n if (leftover % 4 != 0) nAllignedCompressedSize += (4 - leftover);\n\n for (int i = 0; i < nAllignedCompressedSize; i += 4)\n {\n uint32_t* ptr = (uint32_t*)(pchCompressed + i);\n myfile << \"0x\" << std::hex << (int)(*ptr);\n if (i < nAllignedCompressedSize - 1) myfile << \",\";\n }\n\n myfile << \"};\\n\";\n\n myfile << \"#include \\n\";\n myfile << \"#include \\n\";\n\n myfile << \"inline void uncompress_\" << name << \"_obj(std::vector& vertex_data, std::vector& normals, std::vector& index_data)\\n\";\n myfile << \"{\\n\";\n myfile << \" std::vector uncompressed(0x\" << std::hex << rawDataSize << \", 0);\\n\";\n myfile << \" LZ4_decompress_safe((const char*)\" << name << \"_obj_data, uncompressed.data(), 0x\" << std::hex << nCompressedSize << \", 0x\" << std::hex << rawDataSize << \");\\n\";\n myfile << \" const int vertex_size = 0x\" << std::hex << vertex_data.size() << \" * sizeof(float3);\\n\";\n myfile << \" const int index_size = 0x\" << std::hex << index_data.size() << \" * sizeof(short3);\\n\";\n myfile << \" vertex_data.resize(0x\" << std::hex << vertex_data.size() << \");\\n\";\n myfile << \" memcpy(vertex_data.data(), uncompressed.data(), vertex_size);\\n\";\n myfile << \" index_data.resize(0x\" << std::hex << index_data.size() << \");\\n\";\n myfile << \" memcpy(index_data.data(), uncompressed.data() + vertex_size, index_size);\\n\";\n myfile << \" \/\/normals.resize(0x\" << std::hex << vertex_data.size() << \");\\n\";\n myfile << \" \/\/memcpy(normals.data(), uncompressed.data() + vertex_size + index_size, vertex_size);\\n\";\n myfile << \"}\\n\";\n\n myfile.close();\n }\n\n if (ends_with(input, \".png\"))\n {\n ifstream ifs(input, ios::binary | ios::ate);\n ifstream::pos_type pos = ifs.tellg();\n\n std::vector buffer(pos);\n\n ifs.seekg(0, ios::beg);\n ifs.read(&buffer[0], pos);\n\n ofstream myfile;\n myfile.open(output);\n myfile << \"\/\/ License: Apache 2.0. See LICENSE file in root directory.\\n\";\n myfile << \"\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\\n\\n\";\n myfile << \"\/\/ This file is auto-generated from \" << name << \".png using rs-embed tool version: \" << RS_EMBED_VERSION << \"\\n\";\n myfile << \"\/\/ Generation time: \" << get_current_time() << \".\\n\\n\";\n\n myfile << \"static uint32_t \" << name << \"_png_size = 0x\" << std::hex << buffer.size() << \";\\n\";\n\n myfile << \"static uint8_t \" << name << \"_png_data [] { \";\n for (int i = 0; i < buffer.size(); i++)\n {\n uint8_t byte = buffer[i];\n myfile << \"0x\" << std::hex << (int)byte;\n if (i < buffer.size() - 1) myfile << \",\";\n }\n myfile << \"};\\n\";\n\n myfile.close();\n }\n\n return EXIT_SUCCESS;\n}\ncatch (const exception& e)\n{\n cerr << e.what() << endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n cerr << \"some error\" << endl;\n return EXIT_FAILURE;\n}\nupdate includes brackets\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\n\n#include \n#include \n#include \/\/ memcpy\n#include \n#include \n\n#include \n#include \n\n#define STB_IMAGE_IMPLEMENTATION\n#include \n\n\n#define RS_EMBED_VERSION \"0.0.0.1\"\n\nstruct float3\n{\n float x, y, z;\n};\n\nstruct short3\n{\n uint16_t x, y, z;\n};\n\nusing namespace std;\nusing namespace TCLAP;\n\nbool file_exists(const std::string& name) {\n std::ifstream f(name.c_str());\n return f.good();\n}\n\nstruct int6\n{\n int x, y, z, a, b, c;\n};\n\nbool ends_with(const std::string& s, const std::string& suffix)\n{\n auto i = s.rbegin(), j = suffix.rbegin();\n for (; i != s.rend() && j != suffix.rend() && *i == *j;\n i++, j++);\n return j == suffix.rend();\n}\n\nstd::string get_current_time()\n{\n auto t = time(nullptr);\n char buffer[20] = {};\n const tm* time = localtime(&t);\n if (nullptr != time)\n strftime(buffer, sizeof(buffer), \"%m\/%d\/%Y %H:%M:%S\", time);\n return std::string(buffer);\n}\n\nint main(int argc, char** argv) try\n{\n \/\/ Parse command line arguments\n CmdLine cmd(\"librealsense rs-embed tool\", ' ', RS_EMBED_VERSION);\n ValueArg inputFilename(\"i\", \"input\", \"Input filename\", true, \"\", \"input-file\");\n ValueArg outputFilename(\"o\", \"output\", \"Output filename\", false, \"\", \"output-file\");\n ValueArg objectName(\"n\", \"name\", \"Name\", false, \"\", \"object-name\");\n\n cmd.add(inputFilename);\n cmd.add(outputFilename);\n cmd.add(objectName);\n cmd.parse(argc, argv);\n\n auto input = inputFilename.getValue();\n auto output = outputFilename.getValue();\n auto name = objectName.getValue();\n\n if (ends_with(input, \".obj\"))\n {\n std::vector vertex_data;\n std::vector normals_raw_data;\n std::vector normals_data;\n std::vector index_raw_data;\n std::vector index_data;\n\n if (file_exists(input))\n {\n std::ifstream file(input);\n std::string str;\n while (std::getline(file, str))\n {\n if (str.size())\n {\n if (str[0] == 'v')\n {\n float a, b, c;\n if (str[1] == 'n')\n {\n sscanf(str.c_str(), \"vn %f %f %f\", &a, &b, &c);\n normals_raw_data.push_back({ a, b, c });\n }\n else\n {\n sscanf(str.c_str(), \"v %f %f %f\", &a, &b, &c);\n vertex_data.push_back({ a, b, c });\n }\n }\n if (str[0] == 'f')\n {\n int x, y, z, a, b, c; \n sscanf(str.c_str(), \"f %d\/\/%d %d\/\/%d %d\/\/%d\", &x, &a, &y, &b, &z, &c);\n index_raw_data.push_back({ x, y, z, a, b, c });\n }\n }\n }\n }\n else\n {\n std::cout << \"file: \" << input << \" could not be found!\" << std::endl;\n return EXIT_FAILURE;\n }\n\n normals_data.resize(vertex_data.size());\n for (auto& idx : index_raw_data)\n {\n \/\/ TODO - normals data are currently disabled\n \/\/ normals_data[idx.x] = normals_raw_data[idx.a];\n \/\/ normals_data[idx.y] = normals_raw_data[idx.b];\n \/\/ normals_data[idx.z] = normals_raw_data[idx.c];\n index_data.push_back({ static_cast(idx.x - 1),\n static_cast(idx.y - 1),\n static_cast(idx.z - 1) });\n }\n\n size_t vertex_data_size = vertex_data.size() * sizeof(float3);\n size_t index_data_size = index_data.size() * sizeof(short3);\n \/\/size_t normals_data_size = normals_data.size() * sizeof(float3);\n\n std::vector data(vertex_data_size + index_data_size, 0);\n memcpy(data.data(), vertex_data.data(), vertex_data_size);\n memcpy(data.data() + vertex_data_size, index_data.data(), index_data_size);\n \/\/memcpy(data.data() + vertex_data_size + index_data_size, normals_data.data(), normals_data_size);\n\n \/\/ compress szSource into pchCompressed\n auto rawDataSize = (int)data.size();\n auto compressBufSize = LZ4_compressBound(rawDataSize);\n char* pchCompressed = new char[compressBufSize];\n memset(pchCompressed, compressBufSize, 0);\n int nCompressedSize = LZ4_compress_default((const char*)data.data(), pchCompressed, rawDataSize, compressBufSize);\n\n \n ofstream myfile;\n myfile.open(output);\n myfile << \"\/\/ License: Apache 2.0. See LICENSE file in root directory.\\n\";\n myfile << \"\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\\n\\n\";\n myfile << \"\/\/ This file is auto-generated from \" << name << \".obj using rs-embed tool version: \" << RS_EMBED_VERSION <<\"\\n\";\n myfile << \"\/\/ Generation time: \" << get_current_time() << \".\\n\\n\";\n myfile << \"#pragma once\\n\";\n myfile << \"static uint32_t \" << name << \"_obj_data [] { \";\n\n auto nAllignedCompressedSize = nCompressedSize;\n auto leftover = nCompressedSize % 4;\n if (leftover % 4 != 0) nAllignedCompressedSize += (4 - leftover);\n\n for (int i = 0; i < nAllignedCompressedSize; i += 4)\n {\n uint32_t* ptr = (uint32_t*)(pchCompressed + i);\n myfile << \"0x\" << std::hex << (int)(*ptr);\n if (i < nAllignedCompressedSize - 1) myfile << \",\";\n }\n\n myfile << \"};\\n\";\n\n myfile << \"#include \\n\";\n myfile << \"#include \\n\";\n\n myfile << \"inline void uncompress_\" << name << \"_obj(std::vector& vertex_data, std::vector& normals, std::vector& index_data)\\n\";\n myfile << \"{\\n\";\n myfile << \" std::vector uncompressed(0x\" << std::hex << rawDataSize << \", 0);\\n\";\n myfile << \" LZ4_decompress_safe((const char*)\" << name << \"_obj_data, uncompressed.data(), 0x\" << std::hex << nCompressedSize << \", 0x\" << std::hex << rawDataSize << \");\\n\";\n myfile << \" const int vertex_size = 0x\" << std::hex << vertex_data.size() << \" * sizeof(float3);\\n\";\n myfile << \" const int index_size = 0x\" << std::hex << index_data.size() << \" * sizeof(short3);\\n\";\n myfile << \" vertex_data.resize(0x\" << std::hex << vertex_data.size() << \");\\n\";\n myfile << \" memcpy(vertex_data.data(), uncompressed.data(), vertex_size);\\n\";\n myfile << \" index_data.resize(0x\" << std::hex << index_data.size() << \");\\n\";\n myfile << \" memcpy(index_data.data(), uncompressed.data() + vertex_size, index_size);\\n\";\n myfile << \" \/\/normals.resize(0x\" << std::hex << vertex_data.size() << \");\\n\";\n myfile << \" \/\/memcpy(normals.data(), uncompressed.data() + vertex_size + index_size, vertex_size);\\n\";\n myfile << \"}\\n\";\n\n myfile.close();\n }\n\n if (ends_with(input, \".png\"))\n {\n ifstream ifs(input, ios::binary | ios::ate);\n ifstream::pos_type pos = ifs.tellg();\n\n std::vector buffer(pos);\n\n ifs.seekg(0, ios::beg);\n ifs.read(&buffer[0], pos);\n\n ofstream myfile;\n myfile.open(output);\n myfile << \"\/\/ License: Apache 2.0. See LICENSE file in root directory.\\n\";\n myfile << \"\/\/ Copyright(c) 2021 Intel Corporation. All Rights Reserved.\\n\\n\";\n myfile << \"\/\/ This file is auto-generated from \" << name << \".png using rs-embed tool version: \" << RS_EMBED_VERSION << \"\\n\";\n myfile << \"\/\/ Generation time: \" << get_current_time() << \".\\n\\n\";\n\n myfile << \"static uint32_t \" << name << \"_png_size = 0x\" << std::hex << buffer.size() << \";\\n\";\n\n myfile << \"static uint8_t \" << name << \"_png_data [] { \";\n for (int i = 0; i < buffer.size(); i++)\n {\n uint8_t byte = buffer[i];\n myfile << \"0x\" << std::hex << (int)byte;\n if (i < buffer.size() - 1) myfile << \",\";\n }\n myfile << \"};\\n\";\n\n myfile.close();\n }\n\n return EXIT_SUCCESS;\n}\ncatch (const exception& e)\n{\n cerr << e.what() << endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n cerr << \"some error\" << endl;\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"\/\/ main.cpp\n\n#include \n#include \n#include \n\n#include \n\nint main(\n int argc,\n char** argv)\n{\n \/\/ TODO: parse arguments\n\n assert(argc >= 2);\n char const* inputPath = argv[1];\n\n \/\/ Slurp in the input file, so that we can compile and run it\n FILE* inputFile;\n fopen_s(&inputFile, inputPath, \"rb\");\n assert(inputFile);\n\n fseek(inputFile, 0, SEEK_END);\n size_t inputSize = ftell(inputFile);\n fseek(inputFile, 0, SEEK_SET);\n\n char* inputText = (char*) malloc(inputSize + 1);\n fread(inputText, inputSize, 1, inputFile);\n inputText[inputSize] = 0;\n fclose(inputFile);\n\n \/\/ TODO: scan through the text to find comments,\n \/\/ that instruct us how to generate input and\n \/\/ consume output when running the test.\n\n \/\/\n\n SlangSession* session = spCreateSession(nullptr);\n SlangCompileRequest* request = spCreateCompileRequest(session);\n\n spSetCompileFlags(\n request,\n SLANG_COMPILE_FLAG_USE_IR);\n\n spSetOutputContainerFormat(\n request,\n SLANG_CONTAINER_FORMAT_SLANG_MODULE);\n\n int translationUnitIndex = spAddTranslationUnit(\n request,\n SLANG_SOURCE_LANGUAGE_SLANG,\n nullptr);\n\n spAddTranslationUnitSourceString(\n request,\n translationUnitIndex,\n inputPath,\n inputText);\n\n int entryPointIndex = spAddEntryPoint(\n request,\n translationUnitIndex,\n \"main\",\n spFindProfile(session, \"cs_5_0\"));\n\n if( spCompile(request) != 0 )\n {\n char const* output = spGetDiagnosticOutput(request);\n fputs(output, stderr);\n exit(1);\n }\n\n \/\/ Things compiled, so now we need to run them...\n\n \/\/ Extract the bytecode\n size_t bytecodeSize = 0;\n void const* bytecode = spGetCompileRequestCode(request, &bytecodeSize);\n\n \/\/ Now we need to create an execution context to go and run the bytecode we got\n\n SlangVM* vm = SlangVM_create();\n\n SlangVMModule* vmModule = SlangVMModule_load(\n vm,\n bytecode,\n bytecodeSize);\n\n SlangVMFunc* vmFunc = (SlangVMFunc*)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"main\");\n\n int32_t*& inputArg = *(int32_t**)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"input\");\n\n int32_t*& outputArg = *(int32_t**)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"output\");\n\n SlangVMThread* vmThread = SlangVMThread_create(\n vm);\n\n int32_t inputData[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };\n int32_t outputData[8] = { 0 };\n\n inputArg = inputData;\n outputArg = outputData;\n\n \/\/ TODO: set arguments based on specification from the user...\n for (uint32_t threadID = 0; threadID < 8; ++threadID)\n {\n#if 0\n fprintf(stderr, \"\\n\\nthreadID = %u\\n\\n\", threadID);\n fflush(stderr);\n#endif\n\n SlangVMThread_beginCall(vmThread, vmFunc);\n\n SlangVMThread_setArg(\n vmThread,\n 0,\n &threadID,\n sizeof(threadID));\n\n SlangVMThread_resume(vmThread);\n }\n\n for (uint32_t ii = 0; ii < 8; ++ii)\n {\n fprintf(stdout, \"outputData[%u] = %d\\n\", ii, outputData[ii]);\n }\n\n spDestroyCompileRequest(request);\n spDestroySession(session);\n\n return 0;\n}\nfix linux build\/\/ main.cpp\n\n#include \n#include \n#include \n#include \"..\/..\/source\/core\/secure-crt.h\"\n#include \n\nint main(\n int argc,\n char** argv)\n{\n \/\/ TODO: parse arguments\n\n assert(argc >= 2);\n char const* inputPath = argv[1];\n\n \/\/ Slurp in the input file, so that we can compile and run it\n FILE* inputFile;\n fopen_s(&inputFile, inputPath, \"rb\");\n assert(inputFile);\n\n fseek(inputFile, 0, SEEK_END);\n size_t inputSize = ftell(inputFile);\n fseek(inputFile, 0, SEEK_SET);\n\n char* inputText = (char*) malloc(inputSize + 1);\n fread(inputText, inputSize, 1, inputFile);\n inputText[inputSize] = 0;\n fclose(inputFile);\n\n \/\/ TODO: scan through the text to find comments,\n \/\/ that instruct us how to generate input and\n \/\/ consume output when running the test.\n\n \/\/\n\n SlangSession* session = spCreateSession(nullptr);\n SlangCompileRequest* request = spCreateCompileRequest(session);\n\n spSetCompileFlags(\n request,\n SLANG_COMPILE_FLAG_USE_IR);\n\n spSetOutputContainerFormat(\n request,\n SLANG_CONTAINER_FORMAT_SLANG_MODULE);\n\n int translationUnitIndex = spAddTranslationUnit(\n request,\n SLANG_SOURCE_LANGUAGE_SLANG,\n nullptr);\n\n spAddTranslationUnitSourceString(\n request,\n translationUnitIndex,\n inputPath,\n inputText);\n\n int entryPointIndex = spAddEntryPoint(\n request,\n translationUnitIndex,\n \"main\",\n spFindProfile(session, \"cs_5_0\"));\n\n if( spCompile(request) != 0 )\n {\n char const* output = spGetDiagnosticOutput(request);\n fputs(output, stderr);\n exit(1);\n }\n\n \/\/ Things compiled, so now we need to run them...\n\n \/\/ Extract the bytecode\n size_t bytecodeSize = 0;\n void const* bytecode = spGetCompileRequestCode(request, &bytecodeSize);\n\n \/\/ Now we need to create an execution context to go and run the bytecode we got\n\n SlangVM* vm = SlangVM_create();\n\n SlangVMModule* vmModule = SlangVMModule_load(\n vm,\n bytecode,\n bytecodeSize);\n\n SlangVMFunc* vmFunc = (SlangVMFunc*)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"main\");\n\n int32_t*& inputArg = *(int32_t**)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"input\");\n\n int32_t*& outputArg = *(int32_t**)SlangVMModule_findGlobalSymbolPtr(\n vmModule,\n \"output\");\n\n SlangVMThread* vmThread = SlangVMThread_create(\n vm);\n\n int32_t inputData[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };\n int32_t outputData[8] = { 0 };\n\n inputArg = inputData;\n outputArg = outputData;\n\n \/\/ TODO: set arguments based on specification from the user...\n for (uint32_t threadID = 0; threadID < 8; ++threadID)\n {\n#if 0\n fprintf(stderr, \"\\n\\nthreadID = %u\\n\\n\", threadID);\n fflush(stderr);\n#endif\n\n SlangVMThread_beginCall(vmThread, vmFunc);\n\n SlangVMThread_setArg(\n vmThread,\n 0,\n &threadID,\n sizeof(threadID));\n\n SlangVMThread_resume(vmThread);\n }\n\n for (uint32_t ii = 0; ii < 8; ++ii)\n {\n fprintf(stdout, \"outputData[%u] = %d\\n\", ii, outputData[ii]);\n }\n\n spDestroyCompileRequest(request);\n spDestroySession(session);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \n#include \n#include \n\n#include \"DexClass.h\"\n#include \"PassRegistry.h\"\n#include \"Timer.h\"\n#include \"ToolsCommon.h\"\n\nnamespace {\n\nstruct Arguments {\n std::string input_ir_dir;\n std::string output_ir_dir;\n std::vector pass_names;\n RedexOptions redex_options;\n};\n\nArguments parse_args(int argc, char* argv[]) {\n namespace po = boost::program_options;\n po::options_description desc(\n \"Run one pass with dex and IR meta as input and output\");\n desc.add_options()(\"help,h\", \"produce help message\");\n desc.add_options()(\"input-ir,i\", po::value(),\n \"input dex and IR meta directory\");\n desc.add_options()(\"output-ir,o\",\n po::value(),\n \"output dex and IR meta directory\");\n desc.add_options()(\"pass-name,p\", po::value>(),\n \"pass name\");\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n desc.print(std::cout);\n exit(EXIT_SUCCESS);\n }\n\n Arguments args;\n\n if (vm.count(\"input-ir\")) {\n args.input_ir_dir = vm[\"input-ir\"].as();\n }\n\n if (vm.count(\"output-ir\")) {\n args.output_ir_dir = vm[\"output-ir\"].as();\n }\n if (args.output_ir_dir.empty()) {\n std::cerr << \"output-dir is empty\\n\";\n exit(EXIT_FAILURE);\n }\n boost::filesystem::create_directory(args.output_ir_dir);\n\n if (vm.count(\"pass-name\")) {\n args.pass_names = vm[\"pass-name\"].as>();\n }\n\n return args;\n}\n\n\/**\n * Process entry_data : Load config file and change the passes list\n *\/\nJson::Value process_entry_data(const Json::Value& entry_data,\n const Arguments& args) {\n Json::Value config_data =\n redex::parse_config(entry_data[\"config\"].asString());\n \/\/ Change passes list in config data.\n config_data[\"redex\"][\"passes\"] = Json::arrayValue;\n Json::Value& passes_list = config_data[\"redex\"][\"passes\"];\n for (const std::string& pass_name : args.pass_names) {\n passes_list.append(pass_name);\n }\n int len = config_data[\"redex\"][\"passes\"].size();\n if (len > 0 && passes_list[len - 1].asString() != \"RegAllocPass\") {\n passes_list.append(\"RegAllocPass\");\n }\n\n \/\/ apk_dir\n if (entry_data.isMember(\"apk_dir\")) {\n config_data[\"apk_dir\"] = entry_data[\"apk_dir\"].asString();\n }\n\n return config_data;\n}\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n Timer opt_timer(\"Redex-opt\");\n Arguments args = parse_args(argc, argv);\n\n g_redex = new RedexContext();\n\n Json::Value entry_data;\n\n DexStoresVector stores;\n\n redex::load_all_intermediate(args.input_ir_dir, stores, &entry_data);\n args.redex_options.deserialize(entry_data);\n\n Json::Value config_data = process_entry_data(entry_data, args);\n ConfigFiles cfg(std::move(config_data), args.output_ir_dir);\n\n const auto& passes = PassRegistry::get().get_passes();\n PassManager manager(passes, config_data, args.redex_options);\n manager.set_testing_mode();\n manager.run_passes(stores, cfg);\n\n redex::write_all_intermediate(cfg, args.output_ir_dir, args.redex_options,\n stores, entry_data);\n\n delete g_redex;\n return 0;\n}\nSet input dex magic to first DexStore\/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \n#include \n#include \n\n#include \"DexClass.h\"\n#include \"DexLoader.h\"\n#include \"PassRegistry.h\"\n#include \"Timer.h\"\n#include \"ToolsCommon.h\"\n\nnamespace {\n\nstruct Arguments {\n std::string input_ir_dir;\n std::string output_ir_dir;\n std::vector pass_names;\n RedexOptions redex_options;\n};\n\nArguments parse_args(int argc, char* argv[]) {\n namespace po = boost::program_options;\n po::options_description desc(\n \"Run one pass with dex and IR meta as input and output\");\n desc.add_options()(\"help,h\", \"produce help message\");\n desc.add_options()(\"input-ir,i\", po::value(),\n \"input dex and IR meta directory\");\n desc.add_options()(\"output-ir,o\",\n po::value(),\n \"output dex and IR meta directory\");\n desc.add_options()(\"pass-name,p\", po::value>(),\n \"pass name\");\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n desc.print(std::cout);\n exit(EXIT_SUCCESS);\n }\n\n Arguments args;\n\n if (vm.count(\"input-ir\")) {\n args.input_ir_dir = vm[\"input-ir\"].as();\n }\n\n if (vm.count(\"output-ir\")) {\n args.output_ir_dir = vm[\"output-ir\"].as();\n }\n if (args.output_ir_dir.empty()) {\n std::cerr << \"output-dir is empty\\n\";\n exit(EXIT_FAILURE);\n }\n boost::filesystem::create_directory(args.output_ir_dir);\n\n if (vm.count(\"pass-name\")) {\n args.pass_names = vm[\"pass-name\"].as>();\n }\n\n return args;\n}\n\n\/**\n * Process entry_data : Load config file and change the passes list\n *\/\nJson::Value process_entry_data(const Json::Value& entry_data,\n const Arguments& args) {\n Json::Value config_data =\n redex::parse_config(entry_data[\"config\"].asString());\n \/\/ Change passes list in config data.\n config_data[\"redex\"][\"passes\"] = Json::arrayValue;\n Json::Value& passes_list = config_data[\"redex\"][\"passes\"];\n for (const std::string& pass_name : args.pass_names) {\n passes_list.append(pass_name);\n }\n int len = config_data[\"redex\"][\"passes\"].size();\n if (len > 0 && passes_list[len - 1].asString() != \"RegAllocPass\") {\n passes_list.append(\"RegAllocPass\");\n }\n\n \/\/ apk_dir\n if (entry_data.isMember(\"apk_dir\")) {\n config_data[\"apk_dir\"] = entry_data[\"apk_dir\"].asString();\n }\n\n return config_data;\n}\n} \/\/ namespace\n\nint main(int argc, char* argv[]) {\n Timer opt_timer(\"Redex-opt\");\n Arguments args = parse_args(argc, argv);\n\n g_redex = new RedexContext();\n\n Json::Value entry_data;\n\n DexStoresVector stores;\n\n redex::load_all_intermediate(args.input_ir_dir, stores, &entry_data);\n\n \/\/ Set input dex magic to the first DexStore from the first dex file\n if (stores.size() > 0) {\n auto first_dex_path = boost::filesystem::path(args.input_ir_dir) \/\n entry_data[\"dex_list\"][0][\"list\"][0].asString();\n stores[0].set_dex_magic(load_dex_magic_from_dex(first_dex_path.c_str()));\n }\n\n args.redex_options.deserialize(entry_data);\n\n Json::Value config_data = process_entry_data(entry_data, args);\n ConfigFiles cfg(std::move(config_data), args.output_ir_dir);\n\n const auto& passes = PassRegistry::get().get_passes();\n PassManager manager(passes, config_data, args.redex_options);\n manager.set_testing_mode();\n manager.run_passes(stores, cfg);\n\n redex::write_all_intermediate(cfg, args.output_ir_dir, args.redex_options,\n stores, entry_data);\n\n delete g_redex;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/===--- SILOpt.cpp - SIL Optimization Driver -----------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is a tool for reading sil files and running sil passes on them. The\n\/\/ targeted usecase is debugging and testing SIL passes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Strings.h\"\n#include \"swift\/Subsystems.h\"\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/AST\/SILOptions.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Frontend\/DiagnosticVerifier.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SILOptimizer\/Analysis\/Analysis.h\"\n#include \"swift\/SILOptimizer\/PassManager\/Passes.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n#include \"swift\/Serialization\/SerializedModuleLoader.h\"\n#include \"swift\/Serialization\/SerializedSILLoader.h\"\n#include \"swift\/Serialization\/SerializationOptions.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\nusing namespace swift;\n\nnamespace {\n\nenum class OptGroup {\n Unknown, Diagnostics, Performance\n};\n\n} \/\/ end anonymous namespace\n\nstatic llvm::cl::opt\nInputFilename(llvm::cl::desc(\"input file\"), llvm::cl::init(\"-\"),\n llvm::cl::Positional);\n\nstatic llvm::cl::opt\nOutputFilename(\"o\", llvm::cl::desc(\"output filename\"));\n\nstatic llvm::cl::list\nImportPaths(\"I\", llvm::cl::desc(\"add a directory to the import search path\"));\n\nstatic llvm::cl::list\nFrameworkPaths(\"F\", llvm::cl::desc(\"add a directory to the framework search path\"));\n\nstatic llvm::cl::opt\nModuleName(\"module-name\", llvm::cl::desc(\"The name of the module if processing\"\n \" a module. Necessary for processing \"\n \"stdin.\"));\n\nstatic llvm::cl::opt\nEnableResilience(\"enable-resilience\",\n llvm::cl::desc(\"Compile the module to export resilient \"\n \"interfaces for all public declarations by \"\n \"default\"));\n\nstatic llvm::cl::opt\nResourceDir(\"resource-dir\",\n llvm::cl::desc(\"The directory that holds the compiler resource files\"));\n\nstatic llvm::cl::opt\nSDKPath(\"sdk\", llvm::cl::desc(\"The path to the SDK for use with the clang \"\n \"importer.\"),\n llvm::cl::init(\"\"));\n\nstatic llvm::cl::opt\nTarget(\"target\", llvm::cl::desc(\"target triple\"));\n\nstatic llvm::cl::opt OptimizationGroup(\n llvm::cl::desc(\"Predefined optimization groups:\"),\n llvm::cl::values(clEnumValN(OptGroup::Diagnostics, \"diagnostics\",\n \"Run diagnostic passes\"),\n clEnumValN(OptGroup::Performance, \"O\",\n \"Run performance passes\"),\n clEnumValEnd),\n llvm::cl::init(OptGroup::Unknown));\n\nstatic llvm::cl::list\nPasses(llvm::cl::desc(\"Passes:\"),\n llvm::cl::values(\n#define PASS(ID, NAME, DESCRIPTION) clEnumValN(PassKind::ID, NAME, DESCRIPTION),\n#include \"swift\/SILOptimizer\/PassManager\/Passes.def\"\n\t\t\tclEnumValEnd));\n\nstatic llvm::cl::opt\nPrintStats(\"print-stats\", llvm::cl::desc(\"Print various statistics\"));\n\nstatic llvm::cl::opt\nVerifyMode(\"verify\",\n llvm::cl::desc(\"verify diagnostics against expected-\"\n \"{error|warning|note} annotations\"));\n\nstatic llvm::cl::opt\nAssertConfId(\"assert-conf-id\", llvm::cl::Hidden,\n llvm::cl::init(0));\n\nstatic llvm::cl::opt\nSILInlineThreshold(\"sil-inline-threshold\", llvm::cl::Hidden,\n llvm::cl::init(-1));\n\nstatic llvm::cl::opt\nEnableSILVerifyAll(\"enable-sil-verify-all\",\n llvm::cl::Hidden,\n llvm::cl::init(true),\n llvm::cl::desc(\"Run sil verifications after every pass.\"));\n\nstatic llvm::cl::opt\nRemoveRuntimeAsserts(\"remove-runtime-asserts\",\n llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Remove runtime assertions (cond_fail).\"));\n\nstatic llvm::cl::opt\nEmitVerboseSIL(\"emit-verbose-sil\",\n llvm::cl::desc(\"Emit locations during sil emission.\"));\n\nstatic llvm::cl::opt\nEmitSIB(\"emit-sib\", llvm::cl::desc(\"Emit serialized AST + SIL file(s)\"));\n\nstatic llvm::cl::opt\nModuleCachePath(\"module-cache-path\", llvm::cl::desc(\"Clang module cache path\"));\n\nstatic llvm::cl::opt\nEnableSILSortOutput(\"sil-sort-output\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Sort Functions, VTables, Globals, \"\n \"WitnessTables by name to ease diffing.\"));\n\nstatic llvm::cl::opt\nDisableASTDump(\"sil-disable-ast-dump\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Do not dump AST.\"));\n\nstatic llvm::cl::opt\nASTVerifierProcessCount(\"ast-verifier-process-count\", llvm::cl::Hidden,\n llvm::cl::init(1));\n\nstatic llvm::cl::opt\nASTVerifierProcessId(\"ast-verifier-process-id\", llvm::cl::Hidden,\n llvm::cl::init(1));\n\nstatic llvm::cl::opt\nPerformWMO(\"wmo\", llvm::cl::desc(\"Enable whole-module optimizations\"));\n\nstatic void runCommandLineSelectedPasses(SILModule *Module) {\n SILPassManager PM(Module);\n\n for (auto Pass : Passes) {\n PM.addPass(Pass);\n }\n PM.run();\n}\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\nint main(int argc, char **argv) {\n INITIALIZE_LLVM(argc, argv);\n\n llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift SIL optimizer\\n\");\n\n if (PrintStats)\n llvm::EnableStatistics();\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(\n llvm::sys::fs::getMainExecutable(argv[0],\n reinterpret_cast(&anchorForGetMainExecutable)));\n\n \/\/ Give the context the list of search paths to use for modules.\n Invocation.setImportSearchPaths(ImportPaths);\n Invocation.setFrameworkSearchPaths(FrameworkPaths);\n \/\/ Set the SDK path and target if given.\n if (SDKPath.getNumOccurrences() == 0) {\n const char *SDKROOT = getenv(\"SDKROOT\");\n if (SDKROOT)\n SDKPath = SDKROOT;\n }\n if (!SDKPath.empty())\n Invocation.setSDKPath(SDKPath);\n if (!Target.empty())\n Invocation.setTargetTriple(Target);\n if (!ResourceDir.empty())\n Invocation.setRuntimeResourcePath(ResourceDir);\n Invocation.getFrontendOptions().EnableResilience = EnableResilience;\n \/\/ Set the module cache path. If not passed in we use the default swift module\n \/\/ cache.\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setParseStdlib();\n Invocation.getLangOptions().EnableAccessControl = false;\n Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;\n\n Invocation.getLangOptions().ASTVerifierProcessCount =\n ASTVerifierProcessCount;\n Invocation.getLangOptions().ASTVerifierProcessId =\n ASTVerifierProcessId;\n\n \/\/ Setup the SIL Options.\n SILOptions &SILOpts = Invocation.getSILOptions();\n SILOpts.InlineThreshold = SILInlineThreshold;\n SILOpts.VerifyAll = EnableSILVerifyAll;\n SILOpts.RemoveRuntimeAsserts = RemoveRuntimeAsserts;\n SILOpts.AssertConfig = AssertConfId;\n if (OptimizationGroup != OptGroup::Diagnostics)\n SILOpts.Optimization = SILOptions::SILOptMode::Optimize;\n\n\n \/\/ Load the input file.\n llvm::ErrorOr> FileBufOrErr =\n llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (!FileBufOrErr) {\n fprintf(stderr, \"Error! Failed to open file: %s\\n\", InputFilename.c_str());\n exit(-1);\n }\n\n \/\/ If it looks like we have an AST, set the source file kind to SIL and the\n \/\/ name of the module to the file's name.\n Invocation.addInputBuffer(FileBufOrErr.get().get());\n\n serialization::ExtendedValidationInfo extendedInfo;\n auto result = serialization::validateSerializedAST(\n FileBufOrErr.get()->getBuffer(), &extendedInfo);\n bool HasSerializedAST = result.status == serialization::Status::Valid;\n\n if (HasSerializedAST) {\n const StringRef Stem = ModuleName.size() ?\n StringRef(ModuleName) :\n llvm::sys::path::stem(InputFilename);\n Invocation.setModuleName(Stem);\n Invocation.setInputKind(InputFileKind::IFK_Swift_Library);\n } else {\n const StringRef Name = ModuleName.size() ? StringRef(ModuleName) : \"main\";\n Invocation.setModuleName(Name);\n Invocation.setInputKind(InputFileKind::IFK_SIL);\n }\n\n CompilerInstance CI;\n PrintingDiagnosticConsumer PrintDiags;\n CI.addDiagnosticConsumer(&PrintDiags);\n\n if (!PerformWMO) {\n auto &FrontendOpts = Invocation.getFrontendOptions();\n if (!InputFilename.empty() && InputFilename != \"-\") {\n FrontendOpts.PrimaryInput = SelectedInput(\n FrontendOpts.InputFilenames.size());\n } else {\n FrontendOpts.PrimaryInput = SelectedInput(\n FrontendOpts.InputBuffers.size(), SelectedInput::InputKind::Buffer);\n }\n }\n\n if (CI.setup(Invocation))\n return 1;\n\n CI.performSema();\n\n \/\/ If parsing produced an error, don't run any passes.\n if (CI.getASTContext().hadError())\n return 1;\n\n \/\/ Load the SIL if we have a module. We have to do this after SILParse\n \/\/ creating the unfortunate double if statement.\n if (HasSerializedAST) {\n assert(!CI.hasSILModule() &&\n \"performSema() should not create a SILModule.\");\n CI.setSILModule(SILModule::createEmptyModule(CI.getMainModule(),\n CI.getSILOptions()));\n std::unique_ptr SL = SerializedSILLoader::create(\n CI.getASTContext(), CI.getSILModule(), nullptr);\n\n if (extendedInfo.isSIB())\n SL->getAllForModule(CI.getMainModule()->getName(), nullptr);\n else\n SL->getAll();\n }\n\n \/\/ Run the SIL verifier after parsing, so that we verify the module\n \/\/ even if no optimization passes are being run.\n CI.getSILModule()->verify();\n\n \/\/ If we're in verify mode, install a custom diagnostic handling for\n \/\/ SourceMgr.\n if (VerifyMode)\n enableDiagnosticVerifier(CI.getSourceMgr());\n\n if (OptimizationGroup == OptGroup::Diagnostics) {\n runSILDiagnosticPasses(*CI.getSILModule());\n } else if (OptimizationGroup == OptGroup::Performance) {\n runSILOptimizationPasses(*CI.getSILModule());\n } else {\n runCommandLineSelectedPasses(CI.getSILModule());\n }\n\n if (EmitSIB) {\n llvm::SmallString<128> OutputFile;\n if (OutputFilename.size()) {\n OutputFile = OutputFilename;\n } else if (ModuleName.size()) {\n OutputFile = ModuleName;\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n } else {\n OutputFile = CI.getMainModule()->getName().str();\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n }\n\n SerializationOptions serializationOpts;\n serializationOpts.OutputPath = OutputFile.c_str();\n serializationOpts.SerializeAllSIL = true;\n serializationOpts.IsSIB = true;\n\n serialize(CI.getMainModule(), serializationOpts, CI.getSILModule());\n } else {\n const StringRef OutputFile = OutputFilename.size() ?\n StringRef(OutputFilename) : \"-\";\n\n if (OutputFile == \"-\") {\n CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n } else {\n std::error_code EC;\n llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None);\n if (EC) {\n llvm::errs() << \"while opening '\" << OutputFile << \"': \"\n << EC.message() << '\\n';\n return 1;\n }\n CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n }\n }\n\n bool HadError = CI.getASTContext().hadError();\n\n \/\/ If we're in -verify mode, we've buffered up all of the generated\n \/\/ diagnostics. Check now to ensure that they meet our expectations.\n if (VerifyMode) {\n HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs());\n DiagnosticEngine &diags = CI.getDiags();\n if (diags.hasFatalErrorOccurred() &&\n !Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {\n diags.resetHadAnyError();\n diags.diagnose(SourceLoc(), diag::verify_encountered_fatal);\n HadError = true;\n }\n }\n\n return HadError;\n}\nRevert \"sil-opt: Run SIL verifier after parsing\"\/\/===--- SILOpt.cpp - SIL Optimization Driver -----------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is a tool for reading sil files and running sil passes on them. The\n\/\/ targeted usecase is debugging and testing SIL passes.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Strings.h\"\n#include \"swift\/Subsystems.h\"\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/AST\/SILOptions.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Frontend\/DiagnosticVerifier.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SILOptimizer\/Analysis\/Analysis.h\"\n#include \"swift\/SILOptimizer\/PassManager\/Passes.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n#include \"swift\/Serialization\/SerializedModuleLoader.h\"\n#include \"swift\/Serialization\/SerializedSILLoader.h\"\n#include \"swift\/Serialization\/SerializationOptions.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\nusing namespace swift;\n\nnamespace {\n\nenum class OptGroup {\n Unknown, Diagnostics, Performance\n};\n\n} \/\/ end anonymous namespace\n\nstatic llvm::cl::opt\nInputFilename(llvm::cl::desc(\"input file\"), llvm::cl::init(\"-\"),\n llvm::cl::Positional);\n\nstatic llvm::cl::opt\nOutputFilename(\"o\", llvm::cl::desc(\"output filename\"));\n\nstatic llvm::cl::list\nImportPaths(\"I\", llvm::cl::desc(\"add a directory to the import search path\"));\n\nstatic llvm::cl::list\nFrameworkPaths(\"F\", llvm::cl::desc(\"add a directory to the framework search path\"));\n\nstatic llvm::cl::opt\nModuleName(\"module-name\", llvm::cl::desc(\"The name of the module if processing\"\n \" a module. Necessary for processing \"\n \"stdin.\"));\n\nstatic llvm::cl::opt\nEnableResilience(\"enable-resilience\",\n llvm::cl::desc(\"Compile the module to export resilient \"\n \"interfaces for all public declarations by \"\n \"default\"));\n\nstatic llvm::cl::opt\nResourceDir(\"resource-dir\",\n llvm::cl::desc(\"The directory that holds the compiler resource files\"));\n\nstatic llvm::cl::opt\nSDKPath(\"sdk\", llvm::cl::desc(\"The path to the SDK for use with the clang \"\n \"importer.\"),\n llvm::cl::init(\"\"));\n\nstatic llvm::cl::opt\nTarget(\"target\", llvm::cl::desc(\"target triple\"));\n\nstatic llvm::cl::opt OptimizationGroup(\n llvm::cl::desc(\"Predefined optimization groups:\"),\n llvm::cl::values(clEnumValN(OptGroup::Diagnostics, \"diagnostics\",\n \"Run diagnostic passes\"),\n clEnumValN(OptGroup::Performance, \"O\",\n \"Run performance passes\"),\n clEnumValEnd),\n llvm::cl::init(OptGroup::Unknown));\n\nstatic llvm::cl::list\nPasses(llvm::cl::desc(\"Passes:\"),\n llvm::cl::values(\n#define PASS(ID, NAME, DESCRIPTION) clEnumValN(PassKind::ID, NAME, DESCRIPTION),\n#include \"swift\/SILOptimizer\/PassManager\/Passes.def\"\n\t\t\tclEnumValEnd));\n\nstatic llvm::cl::opt\nPrintStats(\"print-stats\", llvm::cl::desc(\"Print various statistics\"));\n\nstatic llvm::cl::opt\nVerifyMode(\"verify\",\n llvm::cl::desc(\"verify diagnostics against expected-\"\n \"{error|warning|note} annotations\"));\n\nstatic llvm::cl::opt\nAssertConfId(\"assert-conf-id\", llvm::cl::Hidden,\n llvm::cl::init(0));\n\nstatic llvm::cl::opt\nSILInlineThreshold(\"sil-inline-threshold\", llvm::cl::Hidden,\n llvm::cl::init(-1));\n\nstatic llvm::cl::opt\nEnableSILVerifyAll(\"enable-sil-verify-all\",\n llvm::cl::Hidden,\n llvm::cl::init(true),\n llvm::cl::desc(\"Run sil verifications after every pass.\"));\n\nstatic llvm::cl::opt\nRemoveRuntimeAsserts(\"remove-runtime-asserts\",\n llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Remove runtime assertions (cond_fail).\"));\n\nstatic llvm::cl::opt\nEmitVerboseSIL(\"emit-verbose-sil\",\n llvm::cl::desc(\"Emit locations during sil emission.\"));\n\nstatic llvm::cl::opt\nEmitSIB(\"emit-sib\", llvm::cl::desc(\"Emit serialized AST + SIL file(s)\"));\n\nstatic llvm::cl::opt\nModuleCachePath(\"module-cache-path\", llvm::cl::desc(\"Clang module cache path\"));\n\nstatic llvm::cl::opt\nEnableSILSortOutput(\"sil-sort-output\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Sort Functions, VTables, Globals, \"\n \"WitnessTables by name to ease diffing.\"));\n\nstatic llvm::cl::opt\nDisableASTDump(\"sil-disable-ast-dump\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Do not dump AST.\"));\n\nstatic llvm::cl::opt\nASTVerifierProcessCount(\"ast-verifier-process-count\", llvm::cl::Hidden,\n llvm::cl::init(1));\n\nstatic llvm::cl::opt\nASTVerifierProcessId(\"ast-verifier-process-id\", llvm::cl::Hidden,\n llvm::cl::init(1));\n\nstatic llvm::cl::opt\nPerformWMO(\"wmo\", llvm::cl::desc(\"Enable whole-module optimizations\"));\n\nstatic void runCommandLineSelectedPasses(SILModule *Module) {\n SILPassManager PM(Module);\n\n for (auto Pass : Passes) {\n PM.addPass(Pass);\n }\n PM.run();\n}\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\nint main(int argc, char **argv) {\n INITIALIZE_LLVM(argc, argv);\n\n llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift SIL optimizer\\n\");\n\n if (PrintStats)\n llvm::EnableStatistics();\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(\n llvm::sys::fs::getMainExecutable(argv[0],\n reinterpret_cast(&anchorForGetMainExecutable)));\n\n \/\/ Give the context the list of search paths to use for modules.\n Invocation.setImportSearchPaths(ImportPaths);\n Invocation.setFrameworkSearchPaths(FrameworkPaths);\n \/\/ Set the SDK path and target if given.\n if (SDKPath.getNumOccurrences() == 0) {\n const char *SDKROOT = getenv(\"SDKROOT\");\n if (SDKROOT)\n SDKPath = SDKROOT;\n }\n if (!SDKPath.empty())\n Invocation.setSDKPath(SDKPath);\n if (!Target.empty())\n Invocation.setTargetTriple(Target);\n if (!ResourceDir.empty())\n Invocation.setRuntimeResourcePath(ResourceDir);\n Invocation.getFrontendOptions().EnableResilience = EnableResilience;\n \/\/ Set the module cache path. If not passed in we use the default swift module\n \/\/ cache.\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setParseStdlib();\n Invocation.getLangOptions().EnableAccessControl = false;\n Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;\n\n Invocation.getLangOptions().ASTVerifierProcessCount =\n ASTVerifierProcessCount;\n Invocation.getLangOptions().ASTVerifierProcessId =\n ASTVerifierProcessId;\n\n \/\/ Setup the SIL Options.\n SILOptions &SILOpts = Invocation.getSILOptions();\n SILOpts.InlineThreshold = SILInlineThreshold;\n SILOpts.VerifyAll = EnableSILVerifyAll;\n SILOpts.RemoveRuntimeAsserts = RemoveRuntimeAsserts;\n SILOpts.AssertConfig = AssertConfId;\n if (OptimizationGroup != OptGroup::Diagnostics)\n SILOpts.Optimization = SILOptions::SILOptMode::Optimize;\n\n\n \/\/ Load the input file.\n llvm::ErrorOr> FileBufOrErr =\n llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (!FileBufOrErr) {\n fprintf(stderr, \"Error! Failed to open file: %s\\n\", InputFilename.c_str());\n exit(-1);\n }\n\n \/\/ If it looks like we have an AST, set the source file kind to SIL and the\n \/\/ name of the module to the file's name.\n Invocation.addInputBuffer(FileBufOrErr.get().get());\n\n serialization::ExtendedValidationInfo extendedInfo;\n auto result = serialization::validateSerializedAST(\n FileBufOrErr.get()->getBuffer(), &extendedInfo);\n bool HasSerializedAST = result.status == serialization::Status::Valid;\n\n if (HasSerializedAST) {\n const StringRef Stem = ModuleName.size() ?\n StringRef(ModuleName) :\n llvm::sys::path::stem(InputFilename);\n Invocation.setModuleName(Stem);\n Invocation.setInputKind(InputFileKind::IFK_Swift_Library);\n } else {\n const StringRef Name = ModuleName.size() ? StringRef(ModuleName) : \"main\";\n Invocation.setModuleName(Name);\n Invocation.setInputKind(InputFileKind::IFK_SIL);\n }\n\n CompilerInstance CI;\n PrintingDiagnosticConsumer PrintDiags;\n CI.addDiagnosticConsumer(&PrintDiags);\n\n if (!PerformWMO) {\n auto &FrontendOpts = Invocation.getFrontendOptions();\n if (!InputFilename.empty() && InputFilename != \"-\") {\n FrontendOpts.PrimaryInput = SelectedInput(\n FrontendOpts.InputFilenames.size());\n } else {\n FrontendOpts.PrimaryInput = SelectedInput(\n FrontendOpts.InputBuffers.size(), SelectedInput::InputKind::Buffer);\n }\n }\n\n if (CI.setup(Invocation))\n return 1;\n\n CI.performSema();\n\n \/\/ If parsing produced an error, don't run any passes.\n if (CI.getASTContext().hadError())\n return 1;\n\n \/\/ Load the SIL if we have a module. We have to do this after SILParse\n \/\/ creating the unfortunate double if statement.\n if (HasSerializedAST) {\n assert(!CI.hasSILModule() &&\n \"performSema() should not create a SILModule.\");\n CI.setSILModule(SILModule::createEmptyModule(CI.getMainModule(),\n CI.getSILOptions()));\n std::unique_ptr SL = SerializedSILLoader::create(\n CI.getASTContext(), CI.getSILModule(), nullptr);\n\n if (extendedInfo.isSIB())\n SL->getAllForModule(CI.getMainModule()->getName(), nullptr);\n else\n SL->getAll();\n }\n\n \/\/ If we're in verify mode, install a custom diagnostic handling for\n \/\/ SourceMgr.\n if (VerifyMode)\n enableDiagnosticVerifier(CI.getSourceMgr());\n\n if (OptimizationGroup == OptGroup::Diagnostics) {\n runSILDiagnosticPasses(*CI.getSILModule());\n } else if (OptimizationGroup == OptGroup::Performance) {\n runSILOptimizationPasses(*CI.getSILModule());\n } else {\n runCommandLineSelectedPasses(CI.getSILModule());\n }\n\n if (EmitSIB) {\n llvm::SmallString<128> OutputFile;\n if (OutputFilename.size()) {\n OutputFile = OutputFilename;\n } else if (ModuleName.size()) {\n OutputFile = ModuleName;\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n } else {\n OutputFile = CI.getMainModule()->getName().str();\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n }\n\n SerializationOptions serializationOpts;\n serializationOpts.OutputPath = OutputFile.c_str();\n serializationOpts.SerializeAllSIL = true;\n serializationOpts.IsSIB = true;\n\n serialize(CI.getMainModule(), serializationOpts, CI.getSILModule());\n } else {\n const StringRef OutputFile = OutputFilename.size() ?\n StringRef(OutputFilename) : \"-\";\n\n if (OutputFile == \"-\") {\n CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n } else {\n std::error_code EC;\n llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None);\n if (EC) {\n llvm::errs() << \"while opening '\" << OutputFile << \"': \"\n << EC.message() << '\\n';\n return 1;\n }\n CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n }\n }\n\n bool HadError = CI.getASTContext().hadError();\n\n \/\/ If we're in -verify mode, we've buffered up all of the generated\n \/\/ diagnostics. Check now to ensure that they meet our expectations.\n if (VerifyMode) {\n HadError = verifyDiagnostics(CI.getSourceMgr(), CI.getInputBufferIDs());\n DiagnosticEngine &diags = CI.getDiags();\n if (diags.hasFatalErrorOccurred() &&\n !Invocation.getDiagnosticOptions().ShowDiagnosticsAfterFatalError) {\n diags.resetHadAnyError();\n diags.diagnose(SourceLoc(), diag::verify_encountered_fatal);\n HadError = true;\n }\n }\n\n return HadError;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n** Copyright (c) 2014-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \"test.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if defined(_OPENMP)\n# include \n#endif\n#include \n\n\nnamespace test_internal {\n\nLIBXSTREAM_TARGET(mic) void check(libxstream_bool* result, const void* buffer, size_t size, char pattern)\n{\n const libxstream_argument* arg = 0;\n libxstream_get_argument(buffer, &arg);\n size_t shape = 0;\n libxstream_get_shape(arg, &shape);\n bool ok = shape == size;\n\n const char *const values = reinterpret_cast(buffer);\n for (size_t i = 0; i < size && ok; ++i) {\n ok = pattern == values[i];\n }\n LIBXSTREAM_ASSERT(result);\n *result = ok;\n}\n\n} \/\/ namespace test_internal\n\n\ntest_type::test_type(int device)\n : m_device(device), m_stream(0), m_event(0)\n , m_host_mem(0), m_dev_mem(0)\n{\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_get_active_device(&m_device));\n\n size_t mem_free = 0, mem_avail = 0;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_info(m_device, &mem_free, &mem_avail));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_create(&m_stream, m_device, 0, 0, 0));\n\n const size_t size = 4711u * 1024u;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_allocate(-1, &m_host_mem, size, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_allocate(m_device, &m_dev_mem, size, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_info(m_device, &mem_free, &mem_avail));\n\n const char pattern_a = 'a', pattern_b = 'b';\n LIBXSTREAM_ASSERT(pattern_a != pattern_b);\n std::fill_n(reinterpret_cast(m_host_mem), size, pattern_a);\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_h2d(m_host_mem, m_dev_mem, size, m_stream));\n\n libxstream_bool ok = false;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_create_signature(&m_signature, 4));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_output(m_signature, 0, &ok, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 1, m_dev_mem, LIBXSTREAM_TYPE_BYTE, 1, &size));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 2, &size, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 3, &pattern_a, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_call(reinterpret_cast(test_internal::check), m_signature, m_stream, LIBXSTREAM_CALL_DEFAULT));\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_create(&m_event));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_synchronize(m_event));\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n\n std::fill_n(reinterpret_cast(m_host_mem), size, pattern_b);\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(m_dev_mem, m_host_mem, size, m_stream));\n\n const size_t size2 = size \/ 2;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memset_zero(m_dev_mem, size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memset_zero(reinterpret_cast(m_dev_mem) + size2, size - size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n\n int has_occured = 0;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_query(m_event, &has_occured));\n if (0 == has_occured) {\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_synchronize(m_event));\n }\n\n test_internal::check(&ok, m_host_mem, size, pattern_a);\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(m_dev_mem, m_host_mem, size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(reinterpret_cast(m_dev_mem) + size2, reinterpret_cast(m_host_mem) + size2, size - size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_sync(m_stream));\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_query(m_event, &has_occured));\n LIBXSTREAM_CHECK_CONDITION_RETURN(0 != has_occured);\n\n test_internal::check(&ok, m_host_mem, size, 0);\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n}\n\n\ntest_type::~test_type()\n{\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_destroy(m_event));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_deallocate(-1, m_host_mem));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_deallocate(m_device, m_dev_mem));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_destroy(m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_destroy_signature(m_signature));\n fprintf(stdout, \"TST successfully completed.\\n\");\n}\n\n\nint main(int argc, char* argv[])\n{\n try {\n#if defined(_OPENMP)\n const int ntasks = std::max(1 < argc ? std::atoi(argv[1]) : omp_get_max_threads(), 1);\n#else\n const int ntasks = 1;\n#endif\n\n size_t ndevices = 0;\n if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) {\n throw std::runtime_error(\"no device found!\");\n }\n\n#if defined(_OPENMP)\n# pragma omp parallel for schedule(dynamic,1)\n#endif\n for (int i = 0; i < ntasks; ++i) {\n const test_type test(i % ndevices);\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\nRemoved unnecessary header file from the list of included dependencies. Enables the code to compile with older tool chain (no ).\/******************************************************************************\n** Copyright (c) 2014-2015, Intel Corporation **\n** All rights reserved. **\n** **\n** Redistribution and use in source and binary forms, with or without **\n** modification, are permitted provided that the following conditions **\n** are met: **\n** 1. Redistributions of source code must retain the above copyright **\n** notice, this list of conditions and the following disclaimer. **\n** 2. Redistributions in binary form must reproduce the above copyright **\n** notice, this list of conditions and the following disclaimer in the **\n** documentation and\/or other materials provided with the distribution. **\n** 3. Neither the name of the copyright holder nor the names of its **\n** contributors may be used to endorse or promote products derived **\n** from this software without specific prior written permission. **\n** **\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **\n** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **\n** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **\n** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **\n** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **\n** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **\n** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **\n******************************************************************************\/\n\/* Hans Pabst (Intel Corp.)\n******************************************************************************\/\n#include \"test.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if defined(_OPENMP)\n# include \n#endif\n#include \n\n\nnamespace test_internal {\n\nLIBXSTREAM_TARGET(mic) void check(libxstream_bool* result, const void* buffer, size_t size, char pattern)\n{\n const libxstream_argument* arg = 0;\n libxstream_get_argument(buffer, &arg);\n size_t shape = 0;\n libxstream_get_shape(arg, &shape);\n bool ok = shape == size;\n\n const char *const values = reinterpret_cast(buffer);\n for (size_t i = 0; i < size && ok; ++i) {\n ok = pattern == values[i];\n }\n LIBXSTREAM_ASSERT(result);\n *result = ok;\n}\n\n} \/\/ namespace test_internal\n\n\ntest_type::test_type(int device)\n : m_device(device), m_stream(0), m_event(0)\n , m_host_mem(0), m_dev_mem(0)\n{\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_get_active_device(&m_device));\n\n size_t mem_free = 0, mem_avail = 0;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_info(m_device, &mem_free, &mem_avail));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_create(&m_stream, m_device, 0, 0, 0));\n\n const size_t size = 4711u * 1024u;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_allocate(-1, &m_host_mem, size, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_allocate(m_device, &m_dev_mem, size, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_info(m_device, &mem_free, &mem_avail));\n\n const char pattern_a = 'a', pattern_b = 'b';\n LIBXSTREAM_ASSERT(pattern_a != pattern_b);\n std::fill_n(reinterpret_cast(m_host_mem), size, pattern_a);\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_h2d(m_host_mem, m_dev_mem, size, m_stream));\n\n libxstream_bool ok = false;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_create_signature(&m_signature, 4));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_output(m_signature, 0, &ok, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 1, m_dev_mem, LIBXSTREAM_TYPE_BYTE, 1, &size));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 2, &size, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_input (m_signature, 3, &pattern_a, libxstream_type2value::value, 0, 0));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_call(reinterpret_cast(test_internal::check), m_signature, m_stream, LIBXSTREAM_CALL_DEFAULT));\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_create(&m_event));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_synchronize(m_event));\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n\n std::fill_n(reinterpret_cast(m_host_mem), size, pattern_b);\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(m_dev_mem, m_host_mem, size, m_stream));\n\n const size_t size2 = size \/ 2;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memset_zero(m_dev_mem, size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memset_zero(reinterpret_cast(m_dev_mem) + size2, size - size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n\n int has_occured = 0;\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_query(m_event, &has_occured));\n if (0 == has_occured) {\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_synchronize(m_event));\n }\n\n test_internal::check(&ok, m_host_mem, size, pattern_a);\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(m_dev_mem, m_host_mem, size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_memcpy_d2h(reinterpret_cast(m_dev_mem) + size2, reinterpret_cast(m_host_mem) + size2, size - size2, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_record(m_event, m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_sync(m_stream));\n\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_query(m_event, &has_occured));\n LIBXSTREAM_CHECK_CONDITION_RETURN(0 != has_occured);\n\n test_internal::check(&ok, m_host_mem, size, 0);\n LIBXSTREAM_CHECK_CONDITION_RETURN(ok);\n}\n\n\ntest_type::~test_type()\n{\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_event_destroy(m_event));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_deallocate(-1, m_host_mem));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_mem_deallocate(m_device, m_dev_mem));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_stream_destroy(m_stream));\n LIBXSTREAM_CHECK_CALL_RETURN(libxstream_fn_destroy_signature(m_signature));\n fprintf(stdout, \"TST successfully completed.\\n\");\n}\n\n\nint main(int argc, char* argv[])\n{\n try {\n#if defined(_OPENMP)\n const int ntasks = std::max(1 < argc ? std::atoi(argv[1]) : omp_get_max_threads(), 1);\n#else\n const int ntasks = 1;\n#endif\n\n size_t ndevices = 0;\n if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) {\n throw std::runtime_error(\"no device found!\");\n }\n\n#if defined(_OPENMP)\n# pragma omp parallel for schedule(dynamic,1)\n#endif\n for (int i = 0; i < ntasks; ++i) {\n const test_type test(i % ndevices);\n }\n }\n catch(const std::exception& e) {\n fprintf(stderr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n catch(...) {\n fprintf(stderr, \"Error: unknown exception caught!\\n\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of the Grantlee template system.\n\n Copyright (c) 2009,2010 Stephen Kelly \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 version\n 2.1 of the Licence, 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\n#include \"filterexpression.h\"\n\n#include \"exception.h\"\n#include \"filter.h\"\n#include \"grantlee_latin1literal_p.h\"\n#include \"metatype.h\"\n#include \"parser.h\"\n#include \"util.h\"\n\ntypedef QPair ArgFilter;\n\nnamespace Grantlee\n{\n\nclass FilterExpressionPrivate\n{\n FilterExpressionPrivate( FilterExpression *fe )\n : q_ptr( fe )\n {\n\n }\n\n Variable m_variable;\n QList m_filters;\n QStringList m_filterNames;\n\n Q_DECLARE_PUBLIC( FilterExpression )\n FilterExpression * const q_ptr;\n};\n\n}\n\nusing namespace Grantlee;\n\nstatic const char FILTER_SEPARATOR = '|';\nstatic const char FILTER_ARGUMENT_SEPARATOR = ':';\n\nstatic QRegExp getFilterRegexp()\n{\n const QString filterSep( QRegExp::escape( QChar::fromLatin1( FILTER_SEPARATOR ) ) );\n const QString argSep( QRegExp::escape( QChar::fromLatin1( FILTER_ARGUMENT_SEPARATOR ) ) );\n\n const QLatin1Literal varChars( \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.\" );\n const QLatin1Literal numChars( \"[-+\\\\.]?\\\\d[\\\\d\\\\.e]*\" );\n const QString i18nOpen( QRegExp::escape( QLatin1String( \"_(\" ) ) );\n const QLatin1Literal doubleQuoteStringLiteral( \"\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\"\" );\n const QLatin1Literal singleQuoteStringLiteral( \"\\'[^\\'\\\\\\\\]*(?:\\\\\\\\.[^\\'\\\\\\\\]*)*\\'\" );\n const QString i18nClose( QRegExp::escape( QLatin1String( \")\" ) ) );\n const QString variable = QLatin1Char( '[' ) + varChars + QLatin1Literal( \"]+\");\n\n const QString localizedExpression = QLatin1Literal( \"(?:\" ) + i18nOpen + doubleQuoteStringLiteral + i18nClose + QLatin1Char( '|' )\n + i18nOpen + singleQuoteStringLiteral + i18nClose + QLatin1Char( '|' )\n + i18nOpen + numChars + i18nClose + QLatin1Char( '|' )\n + i18nOpen + variable + i18nClose + QLatin1Char( ')' );\n\n const QString constantString = QLatin1Literal( \"(?:\" ) + doubleQuoteStringLiteral + QLatin1Char( '|' )\n + singleQuoteStringLiteral\n + QLatin1Char( ')' );\n\n const QString filterRawString = QLatin1Char( '^' ) + constantString + QLatin1Char( '|' )\n + QLatin1Char( '^' ) + localizedExpression + QLatin1Char( '|' )\n + QLatin1Char( '^' ) + variable + QLatin1Char( '|' )\n + numChars + QLatin1Char( '|' )\n + filterSep + QLatin1Literal( \"\\\\w+|\" )\n + argSep\n + QLatin1Literal( \"(?:\" )\n + constantString + QLatin1Char( '|' ) + localizedExpression\n + QLatin1Char( '|' )\n + variable\n + QLatin1Char( '|' )\n + numChars\n + QLatin1Char( '|' )\n + filterSep\n + QLatin1Literal( \"\\\\w+)\" );\n\n return QRegExp( filterRawString );\n}\n\nFilterExpression::FilterExpression( const QString &varString, Parser *parser )\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n Q_D( FilterExpression );\n\n int pos = 0;\n int lastPos = 0;\n int len;\n QString subString;\n\n QString vs = varString;\n\n static const QRegExp sFilterRe = getFilterRegexp();\n\n \/\/ This is one fo the few contstructors that can throw so we make sure to delete its d->pointer.\n try {\n while ( ( pos = sFilterRe.indexIn( vs, pos ) ) != -1 ) {\n len = sFilterRe.matchedLength();\n subString = vs.mid( pos, len );\n const int ssSize = subString.size();\n\n if ( pos != lastPos ) {\n throw Grantlee::Exception( TagSyntaxError,\n QString::fromLatin1( \"Could not parse some characters: \\\"%1\\\"\" ).arg( vs.mid( lastPos, pos ) ) );\n }\n\n if ( subString.startsWith( QLatin1Char( FILTER_SEPARATOR ) ) ) {\n subString = subString.right( ssSize - 1 );\n Filter::Ptr f = parser->getFilter( subString );\n\n Q_ASSERT( f );\n\n d->m_filterNames << subString;\n d->m_filters << qMakePair( f, Variable() );\n\n } else if ( subString.startsWith( QLatin1Char( FILTER_ARGUMENT_SEPARATOR ) ) ) {\n subString = subString.right( ssSize - 1 );\n const int lastFilter = d->m_filters.size();\n if ( subString.startsWith( QLatin1Char( FILTER_SEPARATOR ) ) )\n throw Grantlee::Exception( EmptyVariableError,\n QString::fromLatin1( \"Missing argument to filter: %1\" ).arg( d->m_filterNames[lastFilter -1] ) );\n\n d->m_filters[lastFilter -1].second = Variable( subString );\n } else {\n \/\/ Token is _(\"translated\"), or \"constant\", or a variable;\n d->m_variable = Variable( subString );\n }\n\n pos += len;\n lastPos = pos;\n }\n\n const QString remainder = vs.right( vs.size() - lastPos );\n if ( !remainder.isEmpty() ) {\n throw Grantlee::Exception( TagSyntaxError,\n QString::fromLatin1( \"Could not parse the remainder, %1 from %2\" ).arg( remainder ).arg( varString ) );\n }\n } catch ( ... ) {\n delete d_ptr;\n throw;\n }\n}\n\nFilterExpression::FilterExpression( const FilterExpression &other )\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n *this = other;\n}\n\nFilterExpression::FilterExpression()\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n}\n\nbool FilterExpression::isValid() const\n{\n Q_D( const FilterExpression );\n return d->m_variable.isValid();\n}\n\nFilterExpression::~FilterExpression()\n{\n delete d_ptr;\n}\n\nVariable FilterExpression::variable() const\n{\n Q_D( const FilterExpression );\n return d->m_variable;\n}\n\nFilterExpression &FilterExpression::operator=( const FilterExpression & other )\n{\n if (&other == this)\n return *this;\n d_ptr->m_variable = other.d_ptr->m_variable;\n d_ptr->m_filters = other.d_ptr->m_filters;\n d_ptr->m_filterNames = other.d_ptr->m_filterNames;\n return *this;\n}\n\nQVariant FilterExpression::resolve( OutputStream *stream, Context *c ) const\n{\n Q_D( const FilterExpression );\n QVariant var = d->m_variable.resolve( c );\n\n Q_FOREACH( const ArgFilter &argfilter, d->m_filters ) {\n Filter::Ptr filter = argfilter.first;\n filter->setStream( stream );\n const Variable argVar = argfilter.second;\n QVariant arg = argVar.resolve( c );\n\n if ( arg.isValid() ) {\n Grantlee::SafeString argString;\n if ( arg.userType() == qMetaTypeId() ) {\n argString = arg.value();\n } else if ( arg.type() == QVariant::String ) {\n argString = Grantlee::SafeString( arg.toString() );\n }\n if ( argVar.isConstant() ) {\n argString = markSafe( argString );\n }\n if ( !argString.get().isEmpty() ) {\n arg = argString;\n }\n }\n\n const SafeString varString = getSafeString( var );\n\n var = filter->doFilter( var, arg, c->autoEscape() );\n\n if ( var.userType() == qMetaTypeId() || var.type() == QVariant::String ) {\n if ( filter->isSafe() && varString.isSafe() ) {\n var = markSafe( getSafeString( var ) );\n } else if ( varString.needsEscape() ) {\n var = markForEscaping( getSafeString( var ) );\n } else {\n var = getSafeString( var );\n }\n }\n }\n ( *stream ) << getSafeString( var ).get();\n return var;\n}\n\nQVariant FilterExpression::resolve( Context *c ) const\n{\n OutputStream _dummy;\n return resolve( &_dummy, c );\n}\n\nQVariantList FilterExpression::toList( Context *c ) const\n{\n const QVariant var = resolve( c );\n return MetaType::toVariantList( var );\n}\n\nbool FilterExpression::isTrue( Context *c ) const\n{\n return variantIsTrue( resolve( c ) );\n}\n\nQStringList FilterExpression::filters() const\n{\n Q_D( const FilterExpression );\n return d->m_filterNames;\n}\n\nUse iterators instead of Q_FOREACH\/*\n This file is part of the Grantlee template system.\n\n Copyright (c) 2009,2010 Stephen Kelly \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 version\n 2.1 of the Licence, 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\n#include \"filterexpression.h\"\n\n#include \"exception.h\"\n#include \"filter.h\"\n#include \"grantlee_latin1literal_p.h\"\n#include \"metatype.h\"\n#include \"parser.h\"\n#include \"util.h\"\n\ntypedef QPair ArgFilter;\n\nnamespace Grantlee\n{\n\nclass FilterExpressionPrivate\n{\n FilterExpressionPrivate( FilterExpression *fe )\n : q_ptr( fe )\n {\n\n }\n\n Variable m_variable;\n QList m_filters;\n QStringList m_filterNames;\n\n Q_DECLARE_PUBLIC( FilterExpression )\n FilterExpression * const q_ptr;\n};\n\n}\n\nusing namespace Grantlee;\n\nstatic const char FILTER_SEPARATOR = '|';\nstatic const char FILTER_ARGUMENT_SEPARATOR = ':';\n\nstatic QRegExp getFilterRegexp()\n{\n const QString filterSep( QRegExp::escape( QChar::fromLatin1( FILTER_SEPARATOR ) ) );\n const QString argSep( QRegExp::escape( QChar::fromLatin1( FILTER_ARGUMENT_SEPARATOR ) ) );\n\n const QLatin1Literal varChars( \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.\" );\n const QLatin1Literal numChars( \"[-+\\\\.]?\\\\d[\\\\d\\\\.e]*\" );\n const QString i18nOpen( QRegExp::escape( QLatin1String( \"_(\" ) ) );\n const QLatin1Literal doubleQuoteStringLiteral( \"\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\"\" );\n const QLatin1Literal singleQuoteStringLiteral( \"\\'[^\\'\\\\\\\\]*(?:\\\\\\\\.[^\\'\\\\\\\\]*)*\\'\" );\n const QString i18nClose( QRegExp::escape( QLatin1String( \")\" ) ) );\n const QString variable = QLatin1Char( '[' ) + varChars + QLatin1Literal( \"]+\");\n\n const QString localizedExpression = QLatin1Literal( \"(?:\" ) + i18nOpen + doubleQuoteStringLiteral + i18nClose + QLatin1Char( '|' )\n + i18nOpen + singleQuoteStringLiteral + i18nClose + QLatin1Char( '|' )\n + i18nOpen + numChars + i18nClose + QLatin1Char( '|' )\n + i18nOpen + variable + i18nClose + QLatin1Char( ')' );\n\n const QString constantString = QLatin1Literal( \"(?:\" ) + doubleQuoteStringLiteral + QLatin1Char( '|' )\n + singleQuoteStringLiteral\n + QLatin1Char( ')' );\n\n const QString filterRawString = QLatin1Char( '^' ) + constantString + QLatin1Char( '|' )\n + QLatin1Char( '^' ) + localizedExpression + QLatin1Char( '|' )\n + QLatin1Char( '^' ) + variable + QLatin1Char( '|' )\n + numChars + QLatin1Char( '|' )\n + filterSep + QLatin1Literal( \"\\\\w+|\" )\n + argSep\n + QLatin1Literal( \"(?:\" )\n + constantString + QLatin1Char( '|' ) + localizedExpression\n + QLatin1Char( '|' )\n + variable\n + QLatin1Char( '|' )\n + numChars\n + QLatin1Char( '|' )\n + filterSep\n + QLatin1Literal( \"\\\\w+)\" );\n\n return QRegExp( filterRawString );\n}\n\nFilterExpression::FilterExpression( const QString &varString, Parser *parser )\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n Q_D( FilterExpression );\n\n int pos = 0;\n int lastPos = 0;\n int len;\n QString subString;\n\n QString vs = varString;\n\n static const QRegExp sFilterRe = getFilterRegexp();\n\n \/\/ This is one fo the few contstructors that can throw so we make sure to delete its d->pointer.\n try {\n while ( ( pos = sFilterRe.indexIn( vs, pos ) ) != -1 ) {\n len = sFilterRe.matchedLength();\n subString = vs.mid( pos, len );\n const int ssSize = subString.size();\n\n if ( pos != lastPos ) {\n throw Grantlee::Exception( TagSyntaxError,\n QString::fromLatin1( \"Could not parse some characters: \\\"%1\\\"\" ).arg( vs.mid( lastPos, pos ) ) );\n }\n\n if ( subString.startsWith( QLatin1Char( FILTER_SEPARATOR ) ) ) {\n subString = subString.right( ssSize - 1 );\n Filter::Ptr f = parser->getFilter( subString );\n\n Q_ASSERT( f );\n\n d->m_filterNames << subString;\n d->m_filters << qMakePair( f, Variable() );\n\n } else if ( subString.startsWith( QLatin1Char( FILTER_ARGUMENT_SEPARATOR ) ) ) {\n subString = subString.right( ssSize - 1 );\n const int lastFilter = d->m_filters.size();\n if ( subString.startsWith( QLatin1Char( FILTER_SEPARATOR ) ) )\n throw Grantlee::Exception( EmptyVariableError,\n QString::fromLatin1( \"Missing argument to filter: %1\" ).arg( d->m_filterNames[lastFilter -1] ) );\n\n d->m_filters[lastFilter -1].second = Variable( subString );\n } else {\n \/\/ Token is _(\"translated\"), or \"constant\", or a variable;\n d->m_variable = Variable( subString );\n }\n\n pos += len;\n lastPos = pos;\n }\n\n const QString remainder = vs.right( vs.size() - lastPos );\n if ( !remainder.isEmpty() ) {\n throw Grantlee::Exception( TagSyntaxError,\n QString::fromLatin1( \"Could not parse the remainder, %1 from %2\" ).arg( remainder ).arg( varString ) );\n }\n } catch ( ... ) {\n delete d_ptr;\n throw;\n }\n}\n\nFilterExpression::FilterExpression( const FilterExpression &other )\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n *this = other;\n}\n\nFilterExpression::FilterExpression()\n : d_ptr( new FilterExpressionPrivate( this ) )\n{\n}\n\nbool FilterExpression::isValid() const\n{\n Q_D( const FilterExpression );\n return d->m_variable.isValid();\n}\n\nFilterExpression::~FilterExpression()\n{\n delete d_ptr;\n}\n\nVariable FilterExpression::variable() const\n{\n Q_D( const FilterExpression );\n return d->m_variable;\n}\n\nFilterExpression &FilterExpression::operator=( const FilterExpression & other )\n{\n if (&other == this)\n return *this;\n d_ptr->m_variable = other.d_ptr->m_variable;\n d_ptr->m_filters = other.d_ptr->m_filters;\n d_ptr->m_filterNames = other.d_ptr->m_filterNames;\n return *this;\n}\n\nQVariant FilterExpression::resolve( OutputStream *stream, Context *c ) const\n{\n Q_D( const FilterExpression );\n QVariant var = d->m_variable.resolve( c );\n\n QList::const_iterator it = d->m_filters.constBegin();\n const QList::const_iterator end = d->m_filters.constEnd();\n for ( ; it != end; ++it ) {\n Filter::Ptr filter = it->first;\n filter->setStream( stream );\n const Variable argVar = it->second;\n QVariant arg = argVar.resolve( c );\n\n if ( arg.isValid() ) {\n Grantlee::SafeString argString;\n if ( arg.userType() == qMetaTypeId() ) {\n argString = arg.value();\n } else if ( arg.type() == QVariant::String ) {\n argString = Grantlee::SafeString( arg.toString() );\n }\n if ( argVar.isConstant() ) {\n argString = markSafe( argString );\n }\n if ( !argString.get().isEmpty() ) {\n arg = argString;\n }\n }\n\n const SafeString varString = getSafeString( var );\n\n var = filter->doFilter( var, arg, c->autoEscape() );\n\n if ( var.userType() == qMetaTypeId() || var.type() == QVariant::String ) {\n if ( filter->isSafe() && varString.isSafe() ) {\n var = markSafe( getSafeString( var ) );\n } else if ( varString.needsEscape() ) {\n var = markForEscaping( getSafeString( var ) );\n } else {\n var = getSafeString( var );\n }\n }\n }\n ( *stream ) << getSafeString( var ).get();\n return var;\n}\n\nQVariant FilterExpression::resolve( Context *c ) const\n{\n OutputStream _dummy;\n return resolve( &_dummy, c );\n}\n\nQVariantList FilterExpression::toList( Context *c ) const\n{\n const QVariant var = resolve( c );\n return MetaType::toVariantList( var );\n}\n\nbool FilterExpression::isTrue( Context *c ) const\n{\n return variantIsTrue( resolve( c ) );\n}\n\nQStringList FilterExpression::filters() const\n{\n Q_D( const FilterExpression );\n return d->m_filterNames;\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial Usage\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n** 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** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsparql_tracker_direct.h\"\n#include \"qsparql_tracker_direct_p.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nstatic void\nasync_cursor_next_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);\n\n if (error != 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::BackendError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n if (!active) {\n if (data->q->isBool()) {\n data->setBoolValue( data->results.count() == 1\n && data->results[0].count() == 1\n && data->results[0].binding(0).value().toBool());\n }\n\n data->terminate();\n return;\n }\n\n QSparqlResultRow resultRow;\n gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);\n\n if (data->columnNames.empty()) {\n for (int i = 0; i < n_columns; i++) {\n data->columnNames.append(QString::fromUtf8(tracker_sparql_cursor_get_variable_name(data->cursor, i)));\n }\n }\n\n for (int i = 0; i < n_columns; i++) {\n QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, 0));\n QSparqlBinding binding;\n binding.setName(data->columnNames[i]);\n TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(data->cursor, i);\n\n switch (type) {\n case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:\n break;\n case TRACKER_SPARQL_VALUE_TYPE_URI:\n binding.setValue(QUrl(value));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_STRING:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#string\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_INTEGER:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#integer\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#double\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_DATETIME:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#dateTime\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:\n binding.setBlankNodeLabel(value);\n break;\n case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:\n binding.setValue(value == QLatin1String(\"1\") ? QString::fromLatin1(\"true\") : QString::fromLatin1(\"false\"),\n QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#boolean\"));\n break;\n default:\n break;\n }\n\n resultRow.append(binding);\n }\n\n data->results.append(resultRow);\n data->dataReady(data->results.count());\n tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);\n}\n\nstatic void\nasync_query_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);\n\n if (error != 0 || data->cursor == 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::StatementError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);\n}\n\nstatic void\nasync_update_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);\n\n if (error != 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::StatementError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n data->terminate();\n}\n\nQTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp)\n: cursor(0), isFinished(false), loop(0), q(result), driverPrivate(dpp)\n{\n}\n\nQTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()\n{\n if (cursor != 0)\n g_object_unref(cursor);\n}\n\nvoid QTrackerDirectResultPrivate::terminate()\n{\n isFinished = true;\n q->emit finished();\n\n if (loop != 0)\n loop->exit();\n}\n\nvoid QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)\n{\n q->setLastError(e);\n}\n\nvoid QTrackerDirectResultPrivate::setBoolValue(bool v)\n{\n q->setBoolValue(v);\n}\n\nvoid QTrackerDirectResultPrivate::dataReady(int totalCount)\n{\n emit q->dataReady(totalCount);\n}\n\nQTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)\n{\n d = new QTrackerDirectResultPrivate(this, p);\n}\n\nQTrackerDirectResult::~QTrackerDirectResult()\n{\n delete d;\n}\n\nQTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,\n QSparqlQuery::StatementType type)\n{\n QTrackerDirectResult* res = new QTrackerDirectResult(d);\n res->setStatementType(type);\n\n switch (type) {\n case QSparqlQuery::AskStatement:\n case QSparqlQuery::SelectStatement:\n {\n tracker_sparql_connection_query_async( d->connection,\n query.toLatin1().constData(),\n 0,\n async_query_callback,\n res->d);\n break;\n }\n case QSparqlQuery::InsertStatement:\n case QSparqlQuery::DeleteStatement:\n tracker_sparql_connection_update_async( d->connection,\n query.toLatin1().constData(),\n 0,\n 0,\n async_update_callback,\n res->d);\n {\n break;\n }\n default:\n qWarning() << \"Tracker backend: unsupported statement type\";\n res->setLastError(QSparqlError(\n QLatin1String(\"Unsupported statement type\"),\n QSparqlError::BackendError));\n break;\n }\n return res;\n}\n\nvoid QTrackerDirectResult::cleanup()\n{\n setPos(QSparql::BeforeFirstRow);\n}\n\nQSparqlBinding QTrackerDirectResult::binding(int field) const\n{\n if (!isValid()) {\n return QSparqlBinding();\n }\n\n if (field >= d->results[pos()].count() || field < 0) {\n qWarning() << \"QTrackerDirectResult::data[\" << pos() << \"]: column\" << field << \"out of range\";\n return QSparqlBinding();\n }\n\n return d->results[pos()].binding(field);\n}\n\nQVariant QTrackerDirectResult::value(int field) const\n{\n if (!isValid()) {\n return QVariant();\n }\n\n if (field >= d->results[pos()].count() || field < 0) {\n qWarning() << \"QTrackerDirectResult::data[\" << pos() << \"]: column\" << field << \"out of range\";\n return QVariant();\n }\n\n return d->results[pos()].value(field);\n}\n\nvoid QTrackerDirectResult::waitForFinished()\n{\n if (d->isFinished)\n return;\n\n QEventLoop loop;\n d->loop = &loop;\n loop.exec();\n d->loop = 0;\n}\n\nbool QTrackerDirectResult::isFinished() const\n{\n return d->isFinished;\n}\n\nint QTrackerDirectResult::size() const\n{\n return d->results.count();\n}\n\nQSparqlResultRow QTrackerDirectResult::current() const\n{\n if (!isValid()) {\n return QSparqlResultRow();\n }\n\n if (pos() < 0 || pos() >= d->results.count())\n return QSparqlResultRow();\n\n return d->results[pos()];\n}\n\nQTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()\n{\n}\n\nQTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()\n{\n}\n\nQTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)\n : QSparqlDriver(parent)\n{\n d = new QTrackerDirectDriverPrivate();\n \/* Initialize GLib type system *\/\n g_type_init();\n\n}\n\nQTrackerDirectDriver::~QTrackerDirectDriver()\n{\n delete d;\n}\n\nbool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const\n{\n switch (f) {\n case QSparqlConnection::QuerySize:\n return true;\n case QSparqlConnection::AskQueries:\n return true;\n case QSparqlConnection::ConstructQueries:\n return false;\n case QSparqlConnection::UpdateQueries:\n return true;\n case QSparqlConnection::DefaultGraph:\n return true;\n }\n return false;\n}\n\nQAtomicInt connectionCounter = 0;\n\nbool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)\n{\n Q_UNUSED(options);\n\n if (isOpen())\n close();\n\n GError *error = 0;\n d->connection = tracker_sparql_connection_get(0, &error);\n \/\/ maybe-TODO: Add the GCancellable\n if (!d->connection) {\n qWarning(\"Couldn't obtain a direct connection to the Tracker store: %s\",\n error ? error->message : \"unknown error\");\n g_error_free(error);\n return false;\n }\n\n setOpen(true);\n setOpenError(false);\n\n return true;\n}\n\nvoid QTrackerDirectDriver::close()\n{\n g_object_unref(d->connection);\n\n if (isOpen()) {\n setOpen(false);\n setOpenError(false);\n }\n}\n\nQT_END_NAMESPACE\n* The direct driver was not setting the query text in result. Probably it should be done in QSparqlConnection::exec() anyway\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial Usage\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n** 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** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsparql_tracker_direct.h\"\n#include \"qsparql_tracker_direct_p.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nQT_BEGIN_NAMESPACE\n\nstatic void\nasync_cursor_next_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);\n\n if (error != 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::BackendError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n if (!active) {\n if (data->q->isBool()) {\n data->setBoolValue( data->results.count() == 1\n && data->results[0].count() == 1\n && data->results[0].binding(0).value().toBool());\n }\n\n data->terminate();\n return;\n }\n\n QSparqlResultRow resultRow;\n gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);\n\n if (data->columnNames.empty()) {\n for (int i = 0; i < n_columns; i++) {\n data->columnNames.append(QString::fromUtf8(tracker_sparql_cursor_get_variable_name(data->cursor, i)));\n }\n }\n\n for (int i = 0; i < n_columns; i++) {\n QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, 0));\n QSparqlBinding binding;\n binding.setName(data->columnNames[i]);\n TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(data->cursor, i);\n\n switch (type) {\n case TRACKER_SPARQL_VALUE_TYPE_UNBOUND:\n break;\n case TRACKER_SPARQL_VALUE_TYPE_URI:\n binding.setValue(QUrl(value));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_STRING:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#string\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_INTEGER:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#integer\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_DOUBLE:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#double\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_DATETIME:\n binding.setValue(value, QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#dateTime\"));\n break;\n case TRACKER_SPARQL_VALUE_TYPE_BLANK_NODE:\n binding.setBlankNodeLabel(value);\n break;\n case TRACKER_SPARQL_VALUE_TYPE_BOOLEAN:\n binding.setValue(value == QLatin1String(\"1\") ? QString::fromLatin1(\"true\") : QString::fromLatin1(\"false\"),\n QUrl::fromEncoded(\"http:\/\/www.w3.org\/2001\/XMLSchema#boolean\"));\n break;\n default:\n break;\n }\n\n resultRow.append(binding);\n }\n\n data->results.append(resultRow);\n data->dataReady(data->results.count());\n tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);\n}\n\nstatic void\nasync_query_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);\n\n if (error != 0 || data->cursor == 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::StatementError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n tracker_sparql_cursor_next_async(data->cursor, 0, async_cursor_next_callback, data);\n}\n\nstatic void\nasync_update_callback( GObject *source_object,\n GAsyncResult *result,\n gpointer user_data)\n{\n Q_UNUSED(source_object);\n QTrackerDirectResultPrivate *data = static_cast(user_data);\n GError *error = 0;\n tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);\n\n if (error != 0) {\n QSparqlError e(QString::fromLatin1(error ? error->message : \"unknown error\"));\n e.setType(QSparqlError::StatementError);\n data->setLastError(e);\n g_error_free(error);\n data->terminate();\n return;\n }\n\n data->terminate();\n}\n\nQTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp)\n: cursor(0), isFinished(false), loop(0), q(result), driverPrivate(dpp)\n{\n}\n\nQTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()\n{\n if (cursor != 0)\n g_object_unref(cursor);\n}\n\nvoid QTrackerDirectResultPrivate::terminate()\n{\n isFinished = true;\n q->emit finished();\n\n if (loop != 0)\n loop->exit();\n}\n\nvoid QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)\n{\n q->setLastError(e);\n}\n\nvoid QTrackerDirectResultPrivate::setBoolValue(bool v)\n{\n q->setBoolValue(v);\n}\n\nvoid QTrackerDirectResultPrivate::dataReady(int totalCount)\n{\n emit q->dataReady(totalCount);\n}\n\nQTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)\n{\n d = new QTrackerDirectResultPrivate(this, p);\n}\n\nQTrackerDirectResult::~QTrackerDirectResult()\n{\n delete d;\n}\n\nQTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,\n QSparqlQuery::StatementType type)\n{\n QTrackerDirectResult* res = new QTrackerDirectResult(d);\n res->setStatementType(type);\n res->setQuery(query);\n\n switch (type) {\n case QSparqlQuery::AskStatement:\n case QSparqlQuery::SelectStatement:\n {\n tracker_sparql_connection_query_async( d->connection,\n query.toLatin1().constData(),\n 0,\n async_query_callback,\n res->d);\n break;\n }\n case QSparqlQuery::InsertStatement:\n case QSparqlQuery::DeleteStatement:\n tracker_sparql_connection_update_async( d->connection,\n query.toLatin1().constData(),\n 0,\n 0,\n async_update_callback,\n res->d);\n {\n break;\n }\n default:\n qWarning() << \"Tracker backend: unsupported statement type\";\n res->setLastError(QSparqlError(\n QLatin1String(\"Unsupported statement type\"),\n QSparqlError::BackendError));\n break;\n }\n return res;\n}\n\nvoid QTrackerDirectResult::cleanup()\n{\n setPos(QSparql::BeforeFirstRow);\n}\n\nQSparqlBinding QTrackerDirectResult::binding(int field) const\n{\n if (!isValid()) {\n return QSparqlBinding();\n }\n\n if (field >= d->results[pos()].count() || field < 0) {\n qWarning() << \"QTrackerDirectResult::data[\" << pos() << \"]: column\" << field << \"out of range\";\n return QSparqlBinding();\n }\n\n return d->results[pos()].binding(field);\n}\n\nQVariant QTrackerDirectResult::value(int field) const\n{\n if (!isValid()) {\n return QVariant();\n }\n\n if (field >= d->results[pos()].count() || field < 0) {\n qWarning() << \"QTrackerDirectResult::data[\" << pos() << \"]: column\" << field << \"out of range\";\n return QVariant();\n }\n\n return d->results[pos()].value(field);\n}\n\nvoid QTrackerDirectResult::waitForFinished()\n{\n if (d->isFinished)\n return;\n\n QEventLoop loop;\n d->loop = &loop;\n loop.exec();\n d->loop = 0;\n}\n\nbool QTrackerDirectResult::isFinished() const\n{\n return d->isFinished;\n}\n\nint QTrackerDirectResult::size() const\n{\n return d->results.count();\n}\n\nQSparqlResultRow QTrackerDirectResult::current() const\n{\n if (!isValid()) {\n return QSparqlResultRow();\n }\n\n if (pos() < 0 || pos() >= d->results.count())\n return QSparqlResultRow();\n\n return d->results[pos()];\n}\n\nQTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()\n{\n}\n\nQTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()\n{\n}\n\nQTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)\n : QSparqlDriver(parent)\n{\n d = new QTrackerDirectDriverPrivate();\n \/* Initialize GLib type system *\/\n g_type_init();\n\n}\n\nQTrackerDirectDriver::~QTrackerDirectDriver()\n{\n delete d;\n}\n\nbool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const\n{\n switch (f) {\n case QSparqlConnection::QuerySize:\n return true;\n case QSparqlConnection::AskQueries:\n return true;\n case QSparqlConnection::ConstructQueries:\n return false;\n case QSparqlConnection::UpdateQueries:\n return true;\n case QSparqlConnection::DefaultGraph:\n return true;\n }\n return false;\n}\n\nQAtomicInt connectionCounter = 0;\n\nbool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)\n{\n Q_UNUSED(options);\n\n if (isOpen())\n close();\n\n GError *error = 0;\n d->connection = tracker_sparql_connection_get(0, &error);\n \/\/ maybe-TODO: Add the GCancellable\n if (!d->connection) {\n qWarning(\"Couldn't obtain a direct connection to the Tracker store: %s\",\n error ? error->message : \"unknown error\");\n g_error_free(error);\n return false;\n }\n\n setOpen(true);\n setOpenError(false);\n\n return true;\n}\n\nvoid QTrackerDirectDriver::close()\n{\n g_object_unref(d->connection);\n\n if (isOpen()) {\n setOpen(false);\n setOpenError(false);\n }\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * LibMemcached\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n\n#define MAX_ERROR_LENGTH 2048\nstruct memcached_error_t\n{\n memcached_st *root;\n uint64_t query_id;\n struct memcached_error_t *next;\n memcached_return_t rc;\n int local_errno;\n size_t size;\n char message[MAX_ERROR_LENGTH];\n};\n\nstatic void _set(memcached_st& memc, memcached_string_t *str, memcached_return_t &rc, const char *at, int local_errno= 0)\n{\n (void)at;\n if (memc.error_messages && memc.error_messages->query_id != memc.query_id)\n {\n memcached_error_free(&memc);\n }\n\n \/\/ For memory allocation we use our error since it is a bit more specific\n if (local_errno == ENOMEM and rc == MEMCACHED_ERRNO)\n {\n rc= MEMCACHED_MEMORY_ALLOCATION_FAILURE;\n }\n\n if (rc == MEMCACHED_MEMORY_ALLOCATION_FAILURE)\n {\n local_errno= ENOMEM;\n }\n\n if (rc == MEMCACHED_ERRNO and not local_errno)\n {\n local_errno= errno;\n rc= MEMCACHED_ERRNO;\n }\n\n if (rc == MEMCACHED_ERRNO and local_errno == ENOTCONN)\n {\n rc= MEMCACHED_CONNECTION_FAILURE;\n }\n\n if (local_errno == EINVAL)\n {\n rc= MEMCACHED_INVALID_ARGUMENTS;\n }\n\n if (local_errno == ECONNREFUSED)\n {\n rc= MEMCACHED_CONNECTION_FAILURE;\n }\n\n memcached_error_t *error= (struct memcached_error_t *)libmemcached_malloc(&memc, sizeof(struct memcached_error_t));\n if (not error) \/\/ Bad business if this happens\n return;\n\n error->root= &memc;\n error->query_id= memc.query_id;\n error->rc= rc;\n error->local_errno= local_errno;\n\n if (str and str->size and local_errno)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s(%s), %.*s -> %s\", \n memcached_strerror(&memc, rc), \n strerror(local_errno),\n memcached_string_printf(*str), at);\n }\n else if (local_errno)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s(%s) -> %s\", \n memcached_strerror(&memc, rc), \n strerror(local_errno), at);\n }\n else if (str and str->size)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s, %.*s -> %s\", \n memcached_strerror(&memc, rc), \n int(str->size), str->c_str, at);\n }\n else\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s -> %s\", \n memcached_strerror(&memc, rc), at);\n }\n\n error->next= memc.error_messages;\n memc.error_messages= error;\n}\n\nmemcached_return_t memcached_set_error(memcached_st& memc, memcached_return_t rc, const char *at, const char *str, size_t length)\n{\n assert(rc != MEMCACHED_ERRNO);\n memcached_string_t tmp= { str, length };\n return memcached_set_error(memc, rc, at, tmp);\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at, const char *str, size_t length)\n{\n assert(rc != MEMCACHED_ERRNO);\n memcached_string_t tmp= { str, length };\n return memcached_set_error(self, rc, at, tmp);\n}\n\nmemcached_return_t memcached_set_error(memcached_st& memc, memcached_return_t rc, const char *at, memcached_string_t& str)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n _set(memc, &str, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at, memcached_string_t& str)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size;\n if (str.size)\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"%.*s, host: %s:%d\",\n memcached_string_printf(str),\n self.hostname, int(self.port));\n }\n else\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n }\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n char hostname_port[NI_MAXHOST +NI_MAXSERV + sizeof(\"host : \")];\n int size= snprintf(hostname_port, sizeof(hostname_port), \"host: %s:%d\", self.hostname, int(self.port));\n\n memcached_string_t error_host= { hostname_port, size};\n\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_st& self, memcached_return_t rc, const char *at)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n _set(self, NULL, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& self, int local_errno, const char *at, const char *str, size_t length)\n{\n memcached_string_t tmp= { str, length };\n return memcached_set_errno(self, local_errno, at, tmp);\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at, const char *str, size_t length)\n{\n memcached_string_t tmp= { str, length };\n return memcached_set_errno(self, local_errno, at, tmp);\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& self, int local_errno, const char *at)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n _set(self, NULL, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& memc, int local_errno, const char *at, memcached_string_t& str)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n _set(memc, &str, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at, memcached_string_t& str)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size;\n if (str.size)\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"%.*s, host: %s:%d\",\n memcached_string_printf(str),\n self.hostname, int(self.port));\n }\n else\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n }\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n self.cached_errno= local_errno; \/\/ Store in the actual server\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size = snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n self.cached_errno= local_errno; \/\/ Store in the actual server\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at, local_errno);\n\n return rc;\n}\n\nstatic void _error_print(const memcached_error_t *error)\n{\n if (not error)\n return;\n\n if (not error->size)\n {\n fprintf(stderr, \"%s\\n\", memcached_strerror(NULL, error->rc) );\n }\n else\n {\n fprintf(stderr, \"%s %s\\n\", memcached_strerror(NULL, error->rc), error->message);\n }\n\n _error_print(error->next);\n}\n\nvoid memcached_error_print(const memcached_st *self)\n{\n if (not self)\n return;\n\n _error_print(self->error_messages);\n}\n\nstatic void _error_free(memcached_error_t *error)\n{\n if (not error)\n return;\n\n _error_free(error->next);\n\n if (error && error->root)\n {\n libmemcached_free(error->root, error);\n }\n else if (error)\n {\n free(error);\n }\n}\n\nvoid memcached_error_free(memcached_st *self)\n{\n if (not self)\n return;\n\n _error_free(self->error_messages);\n self->error_messages= NULL;\n}\n\nconst char *memcached_last_error_message(memcached_st *memc)\n{\n if (not memc)\n return memcached_strerror(memc, MEMCACHED_INVALID_ARGUMENTS);\n\n if (not memc->error_messages)\n return memcached_strerror(memc, MEMCACHED_SUCCESS);\n\n if (not memc->error_messages->size)\n return memcached_strerror(memc, memc->error_messages->rc);\n\n return memc->error_messages->message;\n}\n\n\nbool memcached_has_current_error(memcached_st &memc)\n{\n if (memc.error_messages \n and memc.error_messages->query_id == memc.query_id\n and memcached_failed(memc.error_messages->rc))\n {\n return true;\n }\n\n return false;\n}\n\nmemcached_return_t memcached_last_error(memcached_st *memc)\n{\n if (not memc)\n return MEMCACHED_INVALID_ARGUMENTS;\n\n if (not memc->error_messages)\n return MEMCACHED_SUCCESS;\n\n return memc->error_messages->rc;\n}\n\nint memcached_last_error_errno(memcached_st *memc)\n{\n if (not memc)\n return 0;\n\n if (not memc->error_messages)\n return 0;\n\n return memc->error_messages->local_errno;\n}\nMake sure we use the correct strerror() in case someone is using threads.\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * LibMemcached\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n\n#define MAX_ERROR_LENGTH 2048\nstruct memcached_error_t\n{\n memcached_st *root;\n uint64_t query_id;\n struct memcached_error_t *next;\n memcached_return_t rc;\n int local_errno;\n size_t size;\n char message[MAX_ERROR_LENGTH];\n};\n\nstatic void _set(memcached_st& memc, memcached_string_t *str, memcached_return_t &rc, const char *at, int local_errno= 0)\n{\n (void)at;\n if (memc.error_messages && memc.error_messages->query_id != memc.query_id)\n {\n memcached_error_free(&memc);\n }\n\n \/\/ For memory allocation we use our error since it is a bit more specific\n if (local_errno == ENOMEM and rc == MEMCACHED_ERRNO)\n {\n rc= MEMCACHED_MEMORY_ALLOCATION_FAILURE;\n }\n\n if (rc == MEMCACHED_MEMORY_ALLOCATION_FAILURE)\n {\n local_errno= ENOMEM;\n }\n\n if (rc == MEMCACHED_ERRNO and not local_errno)\n {\n local_errno= errno;\n rc= MEMCACHED_ERRNO;\n }\n\n if (rc == MEMCACHED_ERRNO and local_errno == ENOTCONN)\n {\n rc= MEMCACHED_CONNECTION_FAILURE;\n }\n\n if (local_errno == EINVAL)\n {\n rc= MEMCACHED_INVALID_ARGUMENTS;\n }\n\n if (local_errno == ECONNREFUSED)\n {\n rc= MEMCACHED_CONNECTION_FAILURE;\n }\n\n memcached_error_t *error= (struct memcached_error_t *)libmemcached_malloc(&memc, sizeof(struct memcached_error_t));\n if (not error) \/\/ Bad business if this happens\n return;\n\n error->root= &memc;\n error->query_id= memc.query_id;\n error->rc= rc;\n error->local_errno= local_errno;\n\n const char *errmsg_ptr;\n char errmsg[MAX_ERROR_LENGTH];\n errmsg[0]= 0;\n errmsg_ptr= errmsg;\n\n if (local_errno)\n {\n#ifdef STRERROR_R_CHAR_P\n errmsg_ptr= strerror_r(local_errno, errmsg, sizeof(errmsg));\n#else\n strerror_r(local_errno, errmsg, sizeof(errmsg));\n errmsg_ptr= errmsg;\n#endif\n }\n\n\n if (str and str->size and local_errno)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s(%s), %.*s -> %s\", \n memcached_strerror(&memc, rc), \n errmsg_ptr,\n memcached_string_printf(*str), at);\n }\n else if (local_errno)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s(%s) -> %s\", \n memcached_strerror(&memc, rc), \n errmsg_ptr,\n at);\n }\n else if (str and str->size)\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s, %.*s -> %s\", \n memcached_strerror(&memc, rc), \n int(str->size), str->c_str, at);\n }\n else\n {\n error->size= (int)snprintf(error->message, MAX_ERROR_LENGTH, \"%s -> %s\", \n memcached_strerror(&memc, rc), at);\n }\n\n error->next= memc.error_messages;\n memc.error_messages= error;\n}\n\nmemcached_return_t memcached_set_error(memcached_st& memc, memcached_return_t rc, const char *at, const char *str, size_t length)\n{\n assert(rc != MEMCACHED_ERRNO);\n memcached_string_t tmp= { str, length };\n return memcached_set_error(memc, rc, at, tmp);\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at, const char *str, size_t length)\n{\n assert(rc != MEMCACHED_ERRNO);\n memcached_string_t tmp= { str, length };\n return memcached_set_error(self, rc, at, tmp);\n}\n\nmemcached_return_t memcached_set_error(memcached_st& memc, memcached_return_t rc, const char *at, memcached_string_t& str)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n _set(memc, &str, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at, memcached_string_t& str)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size;\n if (str.size)\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"%.*s, host: %s:%d\",\n memcached_string_printf(str),\n self.hostname, int(self.port));\n }\n else\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n }\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_server_st& self, memcached_return_t rc, const char *at)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n char hostname_port[NI_MAXHOST +NI_MAXSERV + sizeof(\"host : \")];\n int size= snprintf(hostname_port, sizeof(hostname_port), \"host: %s:%d\", self.hostname, int(self.port));\n\n memcached_string_t error_host= { hostname_port, size};\n\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_error(memcached_st& self, memcached_return_t rc, const char *at)\n{\n assert(rc != MEMCACHED_ERRNO);\n if (memcached_success(rc))\n return MEMCACHED_SUCCESS;\n\n _set(self, NULL, rc, at);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& self, int local_errno, const char *at, const char *str, size_t length)\n{\n memcached_string_t tmp= { str, length };\n return memcached_set_errno(self, local_errno, at, tmp);\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at, const char *str, size_t length)\n{\n memcached_string_t tmp= { str, length };\n return memcached_set_errno(self, local_errno, at, tmp);\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& self, int local_errno, const char *at)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n _set(self, NULL, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_st& memc, int local_errno, const char *at, memcached_string_t& str)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n _set(memc, &str, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at, memcached_string_t& str)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size;\n if (str.size)\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"%.*s, host: %s:%d\",\n memcached_string_printf(str),\n self.hostname, int(self.port));\n }\n else\n {\n size= snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n }\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n self.cached_errno= local_errno; \/\/ Store in the actual server\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at, local_errno);\n\n return rc;\n}\n\nmemcached_return_t memcached_set_errno(memcached_server_st& self, int local_errno, const char *at)\n{\n if (not local_errno)\n return MEMCACHED_SUCCESS;\n\n char hostname_port_message[MAX_ERROR_LENGTH];\n int size = snprintf(hostname_port_message, sizeof(hostname_port_message), \"host: %s:%d\",\n self.hostname, int(self.port));\n\n memcached_string_t error_host= { hostname_port_message, size };\n\n self.cached_errno= local_errno; \/\/ Store in the actual server\n\n memcached_return_t rc= MEMCACHED_ERRNO;\n if (not self.root)\n return rc;\n\n _set(*self.root, &error_host, rc, at, local_errno);\n\n return rc;\n}\n\nstatic void _error_print(const memcached_error_t *error)\n{\n if (not error)\n return;\n\n if (not error->size)\n {\n fprintf(stderr, \"%s\\n\", memcached_strerror(NULL, error->rc) );\n }\n else\n {\n fprintf(stderr, \"%s %s\\n\", memcached_strerror(NULL, error->rc), error->message);\n }\n\n _error_print(error->next);\n}\n\nvoid memcached_error_print(const memcached_st *self)\n{\n if (not self)\n return;\n\n _error_print(self->error_messages);\n}\n\nstatic void _error_free(memcached_error_t *error)\n{\n if (not error)\n return;\n\n _error_free(error->next);\n\n if (error && error->root)\n {\n libmemcached_free(error->root, error);\n }\n else if (error)\n {\n free(error);\n }\n}\n\nvoid memcached_error_free(memcached_st *self)\n{\n if (not self)\n return;\n\n _error_free(self->error_messages);\n self->error_messages= NULL;\n}\n\nconst char *memcached_last_error_message(memcached_st *memc)\n{\n if (not memc)\n return memcached_strerror(memc, MEMCACHED_INVALID_ARGUMENTS);\n\n if (not memc->error_messages)\n return memcached_strerror(memc, MEMCACHED_SUCCESS);\n\n if (not memc->error_messages->size)\n return memcached_strerror(memc, memc->error_messages->rc);\n\n return memc->error_messages->message;\n}\n\n\nbool memcached_has_current_error(memcached_st &memc)\n{\n if (memc.error_messages \n and memc.error_messages->query_id == memc.query_id\n and memcached_failed(memc.error_messages->rc))\n {\n return true;\n }\n\n return false;\n}\n\nmemcached_return_t memcached_last_error(memcached_st *memc)\n{\n if (not memc)\n return MEMCACHED_INVALID_ARGUMENTS;\n\n if (not memc->error_messages)\n return MEMCACHED_SUCCESS;\n\n return memc->error_messages->rc;\n}\n\nint memcached_last_error_errno(memcached_st *memc)\n{\n if (not memc)\n return 0;\n\n if (not memc->error_messages)\n return 0;\n\n return memc->error_messages->local_errno;\n}\n<|endoftext|>"} {"text":"#ifndef __penglei_mempool_hpp__\n#define __penglei_mempool_hpp__\n\n#include \"valvec.hpp\"\n\nnamespace terark {\n\n\/\/\/ mempool which alloc mem block identified by\n\/\/\/ integer offset(relative address), not pointers(absolute address)\n\/\/\/ integer offset could be 32bit even in 64bit hardware.\n\/\/\/\n\/\/\/ the returned offset is aligned to align_size, this allows 32bit\n\/\/\/ integer could address up to 4G*align_size memory\n\/\/\/\n\/\/\/ when memory exhausted, valvec can realloc memory without memcpy\n\/\/\/ @see valvec\ntemplate\nclass MemPool : private valvec {\n\tBOOST_STATIC_ASSERT((AlignSize & (AlignSize-1)) == 0);\n typedef valvec mem;\n struct link_t { \/\/ just for readable\n size_t next;\n explicit link_t(size_t l) : next(l) {}\n };\n\tstruct HugeLink {\n\t\tsize_t next;\n\t\tsize_t size;\n\t};\n link_t* flarr; \/\/ free list array\n size_t fllen; \/\/ free list length\n\tsize_t nFree; \/\/ number of free bytes\n\tsize_t hugelist;\n\n static const size_t list_tail = ~size_t(0);\n\n\tvoid destroy_and_clean() {\n\t\tmem::clear();\n\t\tif (flarr) {\n\t\t\tfree(flarr);\n\t\t\tflarr = NULL;\n\t\t}\n\t\tfllen = 0;\n\t\tnFree = 0;\n\t\thugelist = list_tail;\n\t}\n\npublic:\n\t mem& get_data_byte_vec() { return *this; }\n\tconst mem& get_data_byte_vec() const { return *this; }\n\n static size_t align_to(size_t len) {\n return (len + align_size - 1) & ~size_t(align_size - 1);\n }\n enum { align_size = AlignSize };\n\n explicit MemPool(size_t maxBlockSize) {\n assert(maxBlockSize >= align_size);\n assert(maxBlockSize >= sizeof(HugeLink));\n maxBlockSize = align_to(maxBlockSize);\n fllen = maxBlockSize \/ align_size;\n flarr = (link_t*)malloc(sizeof(link_t) * fllen);\n if (NULL == flarr) {\n throw std::bad_alloc();\n }\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(list_tail));\n\t\thugelist = list_tail;\n }\n MemPool(const MemPool& y) : mem(y) {\n fllen = y.fllen;\n flarr = (link_t*)malloc(sizeof(link_t) * fllen);\n if (NULL == flarr) {\n throw std::bad_alloc();\n }\n\t\tnFree = y.nFree;\n memcpy(flarr, y.flarr, sizeof(link_t) * fllen);\n\t\thugelist = y.hugelist;\n }\n MemPool& operator=(const MemPool& y) {\n if (&y == this)\n return *this;\n\t\tdestroy_and_clean();\n MemPool(y).swap(*this);\n return *this;\n }\n ~MemPool() {\n if (flarr) {\n free(flarr);\n\t\t\tflarr = NULL;\n\t\t}\n }\n\n#ifdef HSM_HAS_MOVE\n MemPool(MemPool&& y) noexcept : mem(y) {\n\t\tassert(y.data() == NULL);\n\t\tassert(y.size() == 0);\n fllen = y.fllen;\n flarr = y.flarr;\n\t\tnFree = y.nFree;\n\t\thugelist = y.hugelist;\n\t\ty.fllen = 0;\n\t\ty.flarr = NULL;\n\t\ty.nFree = 0;\n\t\ty.hugelist = list_tail;\n }\n MemPool& operator=(MemPool&& y) noexcept {\n if (&y == this)\n return *this;\n this->~MemPool();\n new(this)MemPool(y);\n return *this;\n }\n#endif\n\n\tusing mem::data;\n using mem::size; \/\/ bring to public...\n\/\/ using mem::shrink_to_fit;\n using mem::reserve;\n using mem::capacity;\n\n\tunsigned char byte_at(size_t pos) const {\n\t\tassert(pos < n);\n\t\treturn p[pos];\n\t}\n\n\t\/\/ keep flarr\n void clear() {\n\t\thugelist = list_tail;\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(list_tail));\n\t\tmem::clear();\n\t}\n\n void erase_all() {\n\t\thugelist = list_tail;\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(list_tail));\n\t\tmem::erase_all();\n\t}\n\n void resize_no_init(size_t newsize) {\n assert(newsize % align_size == 0);\n\t\tassert(newsize >= mem::size());\n mem::resize_no_init(newsize);\n }\n\n\tvoid shrink_to_fit() {\n\t\tmem::shrink_to_fit();\n\t}\n\n template const U& at(size_t pos) const {\n assert(pos < n);\n \/\/ assert(pos + sizeof(U) < n);\n return *(U*)(p + pos);\n }\n template U& at(size_t pos) {\n assert(pos < n);\n \/\/ assert(pos + sizeof(U) < n);\n return *(U*)(p + pos);\n }\n\n \/\/ param request must be aligned by align_size\n size_t alloc(size_t request) {\n assert(request % align_size == 0);\n assert(request > 0);\n\t\trequest = std::max(sizeof(link_t), request);\n size_t res = list_tail;\n if (request <= fllen * align_size) {\n\t\t\tsize_t idx = request \/ align_size - 1;\n\t\t\tres = flarr[idx].next;\n\t\t\tif (list_tail != res) {\n\t\t\t\tassert(nFree >= request);\n\t\t\t\tassert(res + request <= this->n);\n\t\t\t\tflarr[idx] = at(res);\n\t\t\t\tnFree -= request;\n\t\t\t}\n\t\t}\n\t\telse { \/\/ find in freelist, use first match\n\t\t\tres = hugelist;\n\t\t\tsize_t* prev = &hugelist;\n\t\t\twhile (list_tail != res) {\n\t\t\t \tHugeLink* h = (HugeLink*)(p + res);\n\t\t\t\tassert(res + h->size <= this->n);\n\t\t\t\tif (h->size >= request) {\n\t\t\t\t\tsize_t remain = h->size - request;\n\t\t\t\t\tif (remain) {\n\t\t\t\t\t\tsize_t free_pos = res + request;\n\t\t\t\t\t\tif (res + h->size == this->n) {\n\t\t\t\t\t\t\t\/\/ this is the top most block, shrink the heap\n\t\t\t\t\t\t\tthis->n = free_pos;\n\t\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t\t\tnFree -= remain; \/\/ not in freelist\n\t\t\t\t\t\t} else if (remain <= fllen * align_size) {\n\t\t\t\t\t\t\tassert(remain >= sizeof(link_t));\n\t\t\t\t\t\t\tassert(remain >= align_size);\n\t\t\t\t\t\t\tsize_t idx = remain \/ align_size - 1;\n\t\t\t\t\t\t\tat(free_pos) = flarr[idx];\n\t\t\t\t\t\t\tflarr[idx].next = free_pos;\n\t\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ replace h with h2, the 2nd part of h\n\t\t\t\t\t\t\tHugeLink* h2 = (HugeLink*)(p + free_pos);\n\t\t\t\t\t\t\th2->next = h->next;\n\t\t\t\t\t\t\th2->size = remain;\n\t\t\t\t\t\t\t*prev = free_pos; \/\/ replace linked in pointer\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t}\n\t\t\t\t\tnFree -= request;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tres = h->next;\n\t\t\t\tprev = &h->next;\n\t\t\t}\n\t\t}\n\t\tif (list_tail == res) {\n\t\t\tensure_capacity(n + request);\n\t\t\tres = n;\n\t\t\tn += request;\n\t\t}\n\t\treturn res;\n\t}\n\n size_t alloc3(size_t pos, size_t oldlen, size_t newlen) {\n assert(newlen % align_size == 0);\n assert(newlen > 0);\n assert(oldlen % align_size == 0);\n assert(oldlen > 0);\n\t\toldlen = std::max(sizeof(link_t), oldlen);\n\t\tnewlen = std::max(sizeof(link_t), newlen);\n assert(pos < n);\n assert(pos + oldlen <= n);\n if (pos + oldlen == n) {\n ensure_capacity(pos + newlen);\n n = pos + newlen;\n return pos;\n }\n else if (newlen < oldlen) {\n\t\t\tassert(oldlen - newlen >= sizeof(link_t));\n\t\t\tassert(oldlen - newlen >= align_size);\n\t\t\tsfree(pos + newlen, oldlen - newlen);\n\t\t\treturn pos;\n\t\t}\n\t\telse if (newlen == oldlen) {\n\t\t\t\/\/ do nothing\n\t\t\treturn pos;\n\t\t}\n\t\telse {\n size_t newpos = alloc(newlen);\n memcpy(p + newpos, p + pos, std::min(oldlen, newlen));\n sfree(pos, oldlen);\n return newpos;\n }\n }\n\n void sfree(size_t pos, size_t len) {\n assert(len % align_size == 0);\n assert(len > 0);\n assert(pos < n);\n\t\tlen = std::max(sizeof(link_t), len);\n assert(pos + len <= n);\n if (pos + len == n) {\n n = pos;\n }\n\t \telse if (len <= fllen * align_size) {\n size_t idx = len \/ align_size - 1;\n at(pos) = flarr[idx];\n flarr[idx].next = pos;\n\t\t\tnFree += len;\n }\n\t\telse {\n\t\t\tHugeLink* h = (HugeLink*)(p + pos);\n\t\t\th->next = hugelist;\n\t\t\th->size = len;\n\t\t\thugelist = pos;\n\t\t\tnFree += len;\n\t\t}\n }\n\n\tsize_t free_size() const { return nFree; }\n\n void swap(MemPool& y) {\n mem::swap(y);\n std::swap(flarr, y.flarr);\n std::swap(fllen, y.fllen);\n\t\tstd::swap(nFree, y.nFree);\n\t\tstd::swap(hugelist, y.hugelist);\n }\n\n\ttemplate\n\tfriend void DataIO_loadObject(DataIO& dio, MemPool& self) {\n\t\ttypename DataIO::my_var_size_t var;\n\t\tself.clear();\n\t\tif (self.flarr)\n\t\t\t::free(self.flarr);\n\t\tself.flarr = NULL;\n\t\tself.fllen = 0;\n\t\tself.nFree = 0;\n\t\tself.hugelist = list_tail;\n\t\tdio >> var; self.hugelist = var.t;\n\t\tdio >> var; self.nFree = var.t;\n\t\tdio >> var; self.fllen = var.t;\n\t\tself.flarr = (link_t*)malloc(sizeof(link_t) * self.fllen);\n\t\tif (NULL == self.flarr) {\n\t\t\tself.flarr = NULL;\n\t\t\tself.fllen = 0;\n\t\t\tself.nFree = 0;\n\t\t\tself.hugelist = list_tail;\n\t\t\tthrow std::bad_alloc();\n\t\t}\n\t\tfor (size_t i = 0, n = self.fllen; i < n; ++i) {\n\t\t\tdio >> var;\n\t\t\tself.flarr[i].next = var.t;\n\t\t}\n\t\tdio >> static_cast(self);\n\t}\n\n\ttemplate\n\tfriend void DataIO_saveObject(DataIO& dio, const MemPool& self) {\n\t\ttypename DataIO::my_var_size_t var;\n\t\tdio << typename DataIO::my_var_size_t(self.hugelist);\n\t\tdio << typename DataIO::my_var_size_t(self.nFree);\n\t\tdio << typename DataIO::my_var_size_t(self.fllen);\n\t\tfor (size_t i = 0, n = self.fllen; i < n; ++i)\n\t\t\tdio << typename DataIO::my_var_size_t(self.flarr[i].next);\n\t\tdio << static_cast(self);\n\t}\n};\n\n} \/\/ namespace terark\n\n#endif\n\nFix MemPool<4> bug#ifndef __penglei_mempool_hpp__\n#define __penglei_mempool_hpp__\n\n#include \"valvec.hpp\"\n#include \n\nnamespace terark {\n\n\/\/\/ mempool which alloc mem block identified by\n\/\/\/ integer offset(relative address), not pointers(absolute address)\n\/\/\/ integer offset could be 32bit even in 64bit hardware.\n\/\/\/\n\/\/\/ the returned offset is aligned to align_size, this allows 32bit\n\/\/\/ integer could address up to 4G*align_size memory\n\/\/\/\n\/\/\/ when memory exhausted, valvec can realloc memory without memcpy\n\/\/\/ @see valvec\ntemplate\nclass MemPool : private valvec {\n\tBOOST_STATIC_ASSERT((AlignSize & (AlignSize-1)) == 0);\n\tBOOST_STATIC_ASSERT(AlignSize >= 4);\n typedef valvec mem;\n typedef typename boost::mpl::if_c::type link_size_t;\n \n static const size_t huge_list_tail = ~size_t(0);\n static const link_size_t free_list_tail = ~link_size_t(0);\n static const size_t offset_shift = AlignSize == 4 ? boost::static_log2::value : 0;\n\n struct link_t { \/\/ just for readable\n link_size_t next;\n explicit link_t(link_size_t l) : next(l) {}\n };\n\tstruct HugeLink {\n\t\tsize_t next;\n\t\tsize_t size;\n\t};\n link_t* flarr; \/\/ free list array\n size_t fllen; \/\/ free list length\n\tsize_t nFree; \/\/ number of free bytes\n\tsize_t hugelist;\n\n\tvoid destroy_and_clean() {\n\t\tmem::clear();\n\t\tif (flarr) {\n\t\t\tfree(flarr);\n\t\t\tflarr = NULL;\n\t\t}\n\t\tfllen = 0;\n\t\tnFree = 0;\n\t\thugelist = list_tail;\n\t}\n\npublic:\n\t mem& get_data_byte_vec() { return *this; }\n\tconst mem& get_data_byte_vec() const { return *this; }\n\n static size_t align_to(size_t len) {\n return (len + align_size - 1) & ~size_t(align_size - 1);\n }\n enum { align_size = AlignSize };\n\n explicit MemPool(size_t maxBlockSize) {\n assert(maxBlockSize >= align_size);\n assert(maxBlockSize >= sizeof(HugeLink));\n maxBlockSize = align_to(maxBlockSize);\n fllen = maxBlockSize \/ align_size;\n flarr = (link_t*)malloc(sizeof(link_t) * fllen);\n if (NULL == flarr) {\n throw std::bad_alloc();\n }\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(free_list_tail));\n\t\thugelist = huge_list_tail;\n }\n MemPool(const MemPool& y) : mem(y) {\n fllen = y.fllen;\n flarr = (link_t*)malloc(sizeof(link_t) * fllen);\n if (NULL == flarr) {\n throw std::bad_alloc();\n }\n\t\tnFree = y.nFree;\n memcpy(flarr, y.flarr, sizeof(link_t) * fllen);\n\t\thugelist = y.hugelist;\n }\n MemPool& operator=(const MemPool& y) {\n if (&y == this)\n return *this;\n\t\tdestroy_and_clean();\n MemPool(y).swap(*this);\n return *this;\n }\n ~MemPool() {\n if (flarr) {\n free(flarr);\n\t\t\tflarr = NULL;\n\t\t}\n }\n\n#ifdef HSM_HAS_MOVE\n MemPool(MemPool&& y) noexcept : mem(y) {\n\t\tassert(y.data() == NULL);\n\t\tassert(y.size() == 0);\n fllen = y.fllen;\n flarr = y.flarr;\n\t\tnFree = y.nFree;\n\t\thugelist = y.hugelist;\n\t\ty.fllen = 0;\n\t\ty.flarr = NULL;\n\t\ty.nFree = 0;\n\t\ty.hugelist = list_tail;\n }\n MemPool& operator=(MemPool&& y) noexcept {\n if (&y == this)\n return *this;\n this->~MemPool();\n new(this)MemPool(y);\n return *this;\n }\n#endif\n\n\tusing mem::data;\n using mem::size; \/\/ bring to public...\n\/\/ using mem::shrink_to_fit;\n using mem::reserve;\n using mem::capacity;\n\n\tunsigned char byte_at(size_t pos) const {\n\t\tassert(pos < n);\n\t\treturn p[pos];\n\t}\n\n\t\/\/ keep flarr\n void clear() {\n\t\thugelist = huge_list_tail;\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(free_list_tail));\n\t\tmem::clear();\n\t}\n\n void erase_all() {\n\t\thugelist = huge_list_tail;\n\t\tnFree = 0;\n std::uninitialized_fill_n(flarr, fllen, link_t(free_list_tail));\n\t\tmem::erase_all();\n\t}\n\n void resize_no_init(size_t newsize) {\n assert(newsize % align_size == 0);\n\t\tassert(newsize >= mem::size());\n mem::resize_no_init(newsize);\n }\n\n\tvoid shrink_to_fit() {\n\t\tmem::shrink_to_fit();\n\t}\n\n template const U& at(size_t pos) const {\n assert((pos << offset_shift) < n);\n \/\/ assert(pos + sizeof(U) < n);\n return *(U*)(p + (pos << offset_shift));\n }\n template U& at(size_t pos) {\n assert((pos << offset_shift) < n);\n \/\/ assert(pos + sizeof(U) < n);\n return *(U*)(p + (pos << offset_shift));\n }\n\n \/\/ param request must be aligned by align_size\n size_t alloc(size_t request) {\n assert(request % align_size == 0);\n assert(request > 0);\n\t\trequest = std::max(sizeof(link_t), request);\n size_t res = huge_list_tail;\n if (request <= fllen * align_size) {\n\t\t\tsize_t idx = request \/ align_size - 1;\n\t\t\tif (free_list_tail != flarr[idx].next) {\n\t\t\t\tassert(nFree >= request);\n\t\t\t res = size_t(flarr[idx].next) << offset_shift;\n\t\t\t\tassert(res + request <= this->n);\n\t\t\t\tflarr[idx] = at(flarr[idx].next);\n\t\t\t\tnFree -= request;\n\t\t\t}\n\t\t}\n\t\telse { \/\/ find in freelist, use first match\n\t\t\tres = hugelist;\n\t\t\tsize_t* prev = &hugelist;\n\t\t\twhile (huge_list_tail != res) {\n\t\t\t \tHugeLink* h = (HugeLink*)(p + res);\n\t\t\t\tassert(res + h->size <= this->n);\n\t\t\t\tif (h->size >= request) {\n\t\t\t\t\tsize_t remain = h->size - request;\n\t\t\t\t\tif (remain) {\n\t\t\t\t\t\tsize_t free_pos = res + request;\n\t\t\t\t\t\tif (res + h->size == this->n) {\n\t\t\t\t\t\t\t\/\/ this is the top most block, shrink the heap\n\t\t\t\t\t\t\tthis->n = free_pos;\n\t\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t\t\tnFree -= remain; \/\/ not in freelist\n\t\t\t\t\t\t} else if (remain <= fllen * align_size) {\n\t\t\t\t\t\t\tassert(remain >= sizeof(link_t));\n\t\t\t\t\t\t\tassert(remain >= align_size);\n\t\t\t\t\t\t\tsize_t idx = remain \/ align_size - 1;\n free_pos >>= offset_shift;\n\t\t\t\t\t\t\tat(free_pos) = flarr[idx];\n\t\t\t\t\t\t\tflarr[idx].next = link_size_t(free_pos);\n\t\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ replace h with h2, the 2nd part of h\n\t\t\t\t\t\t\tHugeLink* h2 = (HugeLink*)(p + free_pos);\n\t\t\t\t\t\t\th2->next = h->next;\n\t\t\t\t\t\t\th2->size = remain;\n\t\t\t\t\t\t\t*prev = free_pos; \/\/ replace linked in pointer\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t*prev = h->next; \/\/ remove from hugelist\n\t\t\t\t\t}\n\t\t\t\t\tnFree -= request;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tres = h->next;\n\t\t\t\tprev = &h->next;\n\t\t\t}\n\t\t}\n\t\tif (huge_list_tail == res) {\n\t\t\tensure_capacity(n + request);\n\t\t\tres = n;\n\t\t\tn += request;\n\t\t}\n\t\treturn res >> offset_shift;\n\t}\n\n size_t alloc3(size_t pos, size_t oldlen, size_t newlen) {\n assert(newlen % align_size == 0);\n assert(newlen > 0);\n assert(oldlen % align_size == 0);\n assert(oldlen > 0);\n pos <<= offset_shift;\n\t\toldlen = std::max(sizeof(link_t), oldlen);\n\t\tnewlen = std::max(sizeof(link_t), newlen);\n assert(pos < n);\n assert(pos + oldlen <= n);\n if (pos + oldlen == n) {\n ensure_capacity(pos + newlen);\n n = pos + newlen;\n return pos >> offset_shift;\n }\n else if (newlen < oldlen) {\n\t\t\tassert(oldlen - newlen >= sizeof(link_t));\n\t\t\tassert(oldlen - newlen >= align_size);\n\t\t\tsfree(pos + newlen, oldlen - newlen);\n return pos >> offset_shift;\n\t\t}\n\t\telse if (newlen == oldlen) {\n\t\t\t\/\/ do nothing\n return pos >> offset_shift;\n\t\t}\n\t\telse {\n size_t newpos = alloc(newlen);\n memcpy(p + newpos, p + pos, std::min(oldlen, newlen));\n sfree(pos, oldlen);\n return newpos >> offset_shift;\n }\n }\n\n void sfree(size_t pos, size_t len) {\n assert(len % align_size == 0);\n assert(len > 0);\n pos <<= offset_shift;\n assert(pos < n);\n\t\tlen = std::max(sizeof(link_t), len);\n assert(pos + len <= n);\n if (pos + len == n) {\n n = pos;\n }\n\t \telse if (len <= fllen * align_size) {\n size_t idx = len \/ align_size - 1;\n at(pos >> offset_shift) = flarr[idx];\n flarr[idx].next = link_size_t(pos >> offset_shift);\n\t\t\tnFree += len;\n }\n\t\telse {\n\t\t\tHugeLink* h = (HugeLink*)(p + pos);\n\t\t\th->next = hugelist;\n\t\t\th->size = len;\n\t\t\thugelist = pos;\n\t\t\tnFree += len;\n\t\t}\n }\n\n\tsize_t free_size() const { return nFree; }\n\n void swap(MemPool& y) {\n mem::swap(y);\n std::swap(flarr, y.flarr);\n std::swap(fllen, y.fllen);\n\t\tstd::swap(nFree, y.nFree);\n\t\tstd::swap(hugelist, y.hugelist);\n }\n\n\ttemplate\n\tfriend void DataIO_loadObject(DataIO& dio, MemPool& self) {\n\t\ttypename DataIO::my_var_size_t var;\n\t\tself.clear();\n\t\tif (self.flarr)\n\t\t\t::free(self.flarr);\n\t\tself.flarr = NULL;\n\t\tself.fllen = 0;\n\t\tself.nFree = 0;\n\t\tself.hugelist = list_tail;\n\t\tdio >> var; self.hugelist = var.t;\n\t\tdio >> var; self.nFree = var.t;\n\t\tdio >> var; self.fllen = var.t;\n\t\tself.flarr = (link_t*)malloc(sizeof(link_t) * self.fllen);\n\t\tif (NULL == self.flarr) {\n\t\t\tself.flarr = NULL;\n\t\t\tself.fllen = 0;\n\t\t\tself.nFree = 0;\n\t\t\tself.hugelist = list_tail;\n\t\t\tthrow std::bad_alloc();\n\t\t}\n\t\tfor (size_t i = 0, n = self.fllen; i < n; ++i) {\n\t\t\tdio >> var;\n\t\t\tself.flarr[i].next = var.t;\n\t\t}\n\t\tdio >> static_cast(self);\n\t}\n\n\ttemplate\n\tfriend void DataIO_saveObject(DataIO& dio, const MemPool& self) {\n\t\ttypename DataIO::my_var_size_t var;\n\t\tdio << typename DataIO::my_var_size_t(self.hugelist);\n\t\tdio << typename DataIO::my_var_size_t(self.nFree);\n\t\tdio << typename DataIO::my_var_size_t(self.fllen);\n\t\tfor (size_t i = 0, n = self.fllen; i < n; ++i)\n\t\t\tdio << typename DataIO::my_var_size_t(self.flarr[i].next);\n\t\tdio << static_cast(self);\n\t}\n};\n\n} \/\/ namespace terark\n\n#endif\n\n<|endoftext|>"} {"text":"#include \"GoogleLogFatalHandler.hpp\"\n\n#include \"Headers.hpp\"\n\nnamespace google {\nnamespace glog_internal_namespace_ {\nvoid DumpStackTraceToString(string* stacktrace);\n}\n} \/\/ namespace google\n\nstatic void DumpStackTraceToFileAndExit() {\n string s;\n google::glog_internal_namespace_::DumpStackTraceToString(&s);\n LOG(ERROR) << \"STACK TRACE:\\n\" << s;\n\n \/\/ TOOD(hamaji): Use signal instead of sigaction?\n if (google::glog_internal_namespace_::IsFailureSignalHandlerInstalled()) {\n\/\/ Set the default signal handler for SIGABRT, to avoid invoking our\n\/\/ own signal handler installed by InstallFailureSignalHandler().\n#ifdef HAVE_SIGACTION\n struct sigaction sig_action;\n memset(&sig_action, 0, sizeof(sig_action));\n sigemptyset(&sig_action.sa_mask);\n sig_action.sa_handler = SIG_DFL;\n sigaction(SIGABRT, &sig_action, NULL);\n#elif defined(OS_WINDOWS)\n signal(SIGABRT, SIG_DFL);\n#endif \/\/ HAVE_SIGACTION\n }\n\n abort();\n}\n\nnamespace et {\nvoid GoogleLogFatalHandler::handle() {\n google::InstallFailureFunction(&DumpStackTraceToFileAndExit);\n}\n\n} \/\/ namespace et\nRemove logic that isn't supported on Ubuntu\/Debian#include \"GoogleLogFatalHandler.hpp\"\n\n#include \"Headers.hpp\"\n\nnamespace google {\nnamespace glog_internal_namespace_ {\nvoid DumpStackTraceToString(string* stacktrace);\n}\n} \/\/ namespace google\n\nstatic void DumpStackTraceToFileAndExit() {\n string s;\n google::glog_internal_namespace_::DumpStackTraceToString(&s);\n LOG(ERROR) << \"STACK TRACE:\\n\" << s;\n abort();\n}\n\nnamespace et {\nvoid GoogleLogFatalHandler::handle() {\n google::InstallFailureFunction(&DumpStackTraceToFileAndExit);\n}\n\n} \/\/ namespace et\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ peer example program \n\/\/\n\/\/ main.cpp\n\/\/\n\/\/ Copyright (c) 2012-2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nbool g_bShutdown = false;\n\nvoid finish(int sig)\n{\n std::cout << \"Stopping...\" << std::endl;\n g_bShutdown = true;\n}\n\nusing namespace CoinQ;\nusing namespace std;\n\nvoid onOpen(Peer& peer)\n{\n cout << \"Peer \" << peer.name() << \" open.\" << endl;\n}\n\nvoid onClose(Peer& peer, int code, const std::string& message)\n{\n cout << \"Peer \" << peer.name() << \" closed with code \" << code << \": \" << message << \".\" << endl;\n\n g_bShutdown = true;\n}\n\nvoid onInv(Peer& peer, const Coin::Inventory& inv)\n{\n cout << endl << \"Received inventory from \" << peer.name() << endl << inv.toIndentedString() << endl;\n\n Coin::GetDataMessage getData;\n\n for (auto& item: inv.getItems()) {\n if (item.getType() == MSG_BLOCK || item.getType() == MSG_FILTERED_BLOCK) {\n getData.addItem(MSG_BLOCK, item.getItemHash());\n }\n else if (item.getType() == MSG_TX) {\n getData.addItem(MSG_TX, item.getItemHash());\n }\n }\n\n if (getData.getCount() > 0) peer.send(getData);\n}\n\nvoid onHeaders(Peer& peer, const Coin::HeadersMessage& headers)\n{\n cout << endl << \"Received headers message from peer \" << peer.name() << endl << headers.toIndentedString() << endl;\n}\n\nvoid onTx(Peer& peer, const Coin::Transaction& tx)\n{\n cout << endl << \"Received transaction \" << tx.getHashLittleEndian().getHex() << \" from peer \" << peer.name() << endl;\/\/ << tx.toIndentedString() << endl;\n}\n\nvoid onBlock(Peer& peer, const Coin::CoinBlock& block)\n{\n cout << endl << \"Received block from peer \" << peer.name() << endl << block.toRedactedIndentedString() << endl; \n}\n\nvoid onMerkleBlock(Peer& peer, const Coin::MerkleBlock& merkleBlock)\n{\n cout << endl << \"Received merkle block from peer \" << peer.name() << endl << merkleBlock.toIndentedString() << endl;\n\n Coin::MerkleTree tree;\n for (auto& hash: merkleBlock.hashes) { tree.addHash(hash); }\n cout << \"Merkle root: \" << tree.getRootLittleEndian().getHex() << endl;\n}\n\nint main(int argc, char* argv[])\n{\n try\n {\n NetworkSelector networkSelector;\n\n if (argc < 3)\n {\n cerr << \"# Usage: \" << argv[0] << \" [port]\" << endl\n << \"# Supported networks: \" << stdutils::delimited_list(networkSelector.getNetworkNames(), \", \") << endl;\n return -1;\n }\n\n CoinParams coinParams = networkSelector.getCoinParams(argv[1]);\n string host = argv[2];\n string port = (argc > 3) ? argv[3] : coinParams.default_port();\n\n CoinQ::io_service_t io_service;\n CoinQ::io_service_t::work work(io_service);\n boost::thread thread(boost::bind(&CoinQ::io_service_t::run, &io_service));\n\n\n cout << endl << \"Connecting to \" << coinParams.network_name() << \" peer\" << endl\n << \"-------------------------------------------\" << endl\n << \" host: \" << host << endl\n << \" port: \" << port << endl\n << \" magic bytes: \" << hex << coinParams.magic_bytes() << endl\n << \" protocol version: \" << dec << coinParams.protocol_version() << endl\n << endl;\n\n Peer peer(io_service);\n peer.set(host, port, coinParams.magic_bytes(), coinParams.protocol_version(), \"peer v1.0\", 0, true);\n\n peer.subscribeStart([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" started.\" << endl; });\n peer.subscribeStop([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" stopped.\" << endl; });\n peer.subscribeOpen(&onOpen);\n peer.subscribeClose(&onClose);\n\n peer.subscribeTimeout([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" timed out.\" << endl; });\n\n peer.subscribeInv(&onInv);\n peer.subscribeHeaders(&onHeaders);\n peer.subscribeTx(&onTx);\n peer.subscribeBlock(&onBlock);\n peer.subscribeMerkleBlock(&onMerkleBlock);\n\n signal(SIGINT, &finish);\n signal(SIGTERM, &finish);\n\n peer.start();\n while (!g_bShutdown) { usleep(200); }\n peer.stop();\n }\n catch (const exception& e)\n {\n cerr << \"Error: \" << e.what() << endl;\n return -2;\n }\n\n return 0;\n}\nAdded onError handler to CoinQ peer example.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ peer example program \n\/\/\n\/\/ main.cpp\n\/\/\n\/\/ Copyright (c) 2012-2014 Eric Lombrozo\n\/\/\n\/\/ All Rights Reserved.\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\nbool g_bShutdown = false;\n\nvoid finish(int sig)\n{\n std::cout << \"Stopping...\" << std::endl;\n g_bShutdown = true;\n}\n\nusing namespace CoinQ;\nusing namespace std;\n\nvoid onOpen(Peer& peer)\n{\n cout << \"Peer \" << peer.name() << \" open.\" << endl;\n}\n\nvoid onClose(Peer& peer, int code, const std::string& message)\n{\n cout << \"Peer \" << peer.name() << \" closed with code \" << code << \": \" << message << \".\" << endl;\n\n g_bShutdown = true;\n}\n\nvoid onError(Peer& peer, const std::string& message)\n{\n cout << \"Peer \" << peer.name() << \" error - \" << message << \".\" << endl;\n\n g_bShutdown = true;\n}\n\nvoid onInv(Peer& peer, const Coin::Inventory& inv)\n{\n cout << endl << \"Received inventory from \" << peer.name() << endl << inv.toIndentedString() << endl;\n\n Coin::GetDataMessage getData;\n\n for (auto& item: inv.getItems()) {\n if (item.getType() == MSG_BLOCK || item.getType() == MSG_FILTERED_BLOCK) {\n getData.addItem(MSG_BLOCK, item.getItemHash());\n }\n else if (item.getType() == MSG_TX) {\n getData.addItem(MSG_TX, item.getItemHash());\n }\n }\n\n if (getData.getCount() > 0) peer.send(getData);\n}\n\nvoid onHeaders(Peer& peer, const Coin::HeadersMessage& headers)\n{\n cout << endl << \"Received headers message from peer \" << peer.name() << endl << headers.toIndentedString() << endl;\n}\n\nvoid onTx(Peer& peer, const Coin::Transaction& tx)\n{\n cout << endl << \"Received transaction \" << tx.getHashLittleEndian().getHex() << \" from peer \" << peer.name() << endl;\/\/ << tx.toIndentedString() << endl;\n}\n\nvoid onBlock(Peer& peer, const Coin::CoinBlock& block)\n{\n cout << endl << \"Received block from peer \" << peer.name() << endl << block.toRedactedIndentedString() << endl; \n}\n\nvoid onMerkleBlock(Peer& peer, const Coin::MerkleBlock& merkleBlock)\n{\n cout << endl << \"Received merkle block from peer \" << peer.name() << endl << merkleBlock.toIndentedString() << endl;\n\n Coin::MerkleTree tree;\n for (auto& hash: merkleBlock.hashes) { tree.addHash(hash); }\n cout << \"Merkle root: \" << tree.getRootLittleEndian().getHex() << endl;\n}\n\nint main(int argc, char* argv[])\n{\n try\n {\n NetworkSelector networkSelector;\n\n if (argc < 3)\n {\n cerr << \"# Usage: \" << argv[0] << \" [port]\" << endl\n << \"# Supported networks: \" << stdutils::delimited_list(networkSelector.getNetworkNames(), \", \") << endl;\n return -1;\n }\n\n CoinParams coinParams = networkSelector.getCoinParams(argv[1]);\n string host = argv[2];\n string port = (argc > 3) ? argv[3] : coinParams.default_port();\n\n CoinQ::io_service_t io_service;\n CoinQ::io_service_t::work work(io_service);\n boost::thread thread(boost::bind(&CoinQ::io_service_t::run, &io_service));\n\n\n cout << endl << \"Connecting to \" << coinParams.network_name() << \" peer\" << endl\n << \"-------------------------------------------\" << endl\n << \" host: \" << host << endl\n << \" port: \" << port << endl\n << \" magic bytes: \" << hex << coinParams.magic_bytes() << endl\n << \" protocol version: \" << dec << coinParams.protocol_version() << endl\n << endl;\n\n Peer peer(io_service);\n peer.set(host, port, coinParams.magic_bytes(), coinParams.protocol_version(), \"peer v1.0\", 0, true);\n\n peer.subscribeStart([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" started.\" << endl; });\n peer.subscribeStop([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" stopped.\" << endl; });\n peer.subscribeOpen(&onOpen);\n peer.subscribeClose(&onClose);\n peer.subscribeError(&onError);\n\n peer.subscribeTimeout([&](Peer& peer) { cout << \"Peer \" << peer.name() << \" timed out.\" << endl; });\n\n peer.subscribeInv(&onInv);\n peer.subscribeHeaders(&onHeaders);\n peer.subscribeTx(&onTx);\n peer.subscribeBlock(&onBlock);\n peer.subscribeMerkleBlock(&onMerkleBlock);\n\n signal(SIGINT, &finish);\n signal(SIGTERM, &finish);\n\n peer.start();\n while (!g_bShutdown) { usleep(200); }\n peer.stop();\n }\n catch (const exception& e)\n {\n cerr << \"Error: \" << e.what() << endl;\n return -2;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\n\r\nvector solvePuzzle(string state);\r\nvector reconstructPath(map cameFrom, string current);\r\nvector findNeighbors(string state);\r\nfloat calcfScore(string state);\r\nbool isSolved(string state, string finalState);\r\n\r\nint main() {\r\n\r\n \/\/ For Testing Purposes, otherwise we don't need this function\r\n string state;\r\n getline(cin, state);\r\n\r\n vector neighbors = findNeighbors(state);\r\n for (int index = 0; index < neighbors.size(); index++) cout << neighbors[index] << endl;\r\n\r\n vector solution = solvePuzzle(state);\r\n cout << \"Solution: *****\" << endl;\r\n for (int index = 0; index < solution.size(); index++) cout << solution[index] << endl;\r\n\r\n return 0;\r\n}\r\n\r\n\r\nvector solvePuzzle(string state) {\r\n\r\n vector frontier;\r\n vector visited;\r\n map cameFrom;\r\n\r\n frontier.push_back(state);\r\n\r\n\r\n map fScore;\r\n map gScore;\r\n gScore[state] = 0;\r\n\r\n while (frontier.size() > 0) {\r\n\r\n int best_choice = 0;\r\n float minimum = 100;\r\n\r\n for (int index = 0; index < frontier.size(); index++) {\r\n if (fScore[frontier[index]] > minimum) best_choice = index;\r\n }\r\n\r\n string curr_state = frontier[best_choice];\r\n frontier.erase(frontier.begin() + best_choice);\r\n visited.push_back(curr_state);\r\n\r\n \/\/ DEBUGGING\r\n \/*\r\n cout << endl << curr_state << endl;\/\/ << \"Visited: \";\r\n \/\/for (int index = 0; index < visited.size(); index++) cout << visited[index];\r\n cout << endl << \"Frontier: \";\r\n for (int index = 0; index < frontier.size(); index++) cout << frontier[index];\r\n cout << endl;\r\n *\/\r\n\r\n string final = \"12345678 \";\r\n\r\n if (curr_state == final) {\r\n vector path = reconstructPath(cameFrom, curr_state);\r\n return path;\r\n }\r\n\r\n\r\n vector neighbors = findNeighbors(curr_state);\r\n\r\n for (unsigned int index = 0; index < neighbors.size(); index++) {\r\n\r\n string neighbor = neighbors[index];\r\n \/\/cout << neighbor;\r\n if (find(visited.begin(), visited.end(), neighbor) != visited.end()) {\r\n \/\/cout << \" terminated in visited.\" << endl;\r\n continue;\r\n }\r\n\r\n if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) {\r\n \/\/cout << \" \" << \"State not yet Visited. State inserted in Frontier.\" << endl;\r\n frontier.push_back(neighbor);\r\n\r\n } else if ((gScore[curr_state] + 1) >= gScore[neighbor]) {\r\n \/\/cout << \" terminated due to idiotic reasons.\" << endl;\r\n continue;\r\n }\r\n\r\n \/\/ This path is the best until now. Record it!\r\n cameFrom[neighbor] = curr_state;\r\n fScore[neighbor] = calcfScore(neighbor);\r\n gScore[neighbor] = gScore[curr_state] + 1;\r\n\r\n }\r\n\r\n\r\n \/\/ mapping >>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n \/\/for (std::map::iterator it=fScore.begin(); it!=fScore.end(); ++it) {\r\n \/\/ std::cout << it->first << \" => \" << it->second << '\\n';}\r\n\r\n }\r\n\r\n return vector();\r\n\r\n}\r\n\r\nvector reconstructPath(map cameFrom, string current) {\r\n\r\n vector totalPath;\r\n totalPath.push_back(current);\r\n\r\n while (cameFrom.find(current) != cameFrom.end()) {\r\n\r\n current = cameFrom[current];\r\n totalPath.insert(totalPath.begin(), current);\r\n }\r\n\r\n return totalPath;\r\n\r\n}\r\n\r\n\r\nfloat calcfScore(string state) {\r\n\r\n float fScore = 0;\r\n string final = \"12345678 \";\r\n\r\n for (int index = 1; index < 9; index++) {\r\n int loc = state.find(final[index - 1]);\r\n\r\n fScore += abs(loc - (index - 1));\r\n\r\n }\r\n\r\n return fScore;\r\n\r\n}\r\n\r\nvector findNeighbors(string state) {\r\n\r\n vector neighbors;\r\n int index = state.find(' ');\r\n\r\n if (index % 3 < 2) {\r\n string temp_state = state;\r\n temp_state[index] = state[index + 1];\r\n temp_state[index + 1] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index % 3 > 0) {\r\n string temp_state = state;\r\n temp_state[index] = state[index - 1];\r\n temp_state[index - 1] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index > 2) {\r\n string temp_state = state;\r\n temp_state[index] = state[index - 3];\r\n temp_state[index - 3] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index < 6) {\r\n string temp_state = state;\r\n temp_state[index] = state[index + 3];\r\n temp_state[index + 3] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n return neighbors;\r\n\r\n}\r\n\r\nbool isSolved(string state, string finalState) {\r\n\r\n if (state == finalState) return true;\r\n else return false;\r\n\r\n}\r\nUpdated algorithm.cpp#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\n\r\nvector solvePuzzle(string state);\r\nvector reconstructPath(map cameFrom, string current);\r\nvector findNeighbors(string state);\r\nfloat calcfScore(string state);\r\nbool isSolved(string state, string finalState);\r\n\r\nint main() {\r\n\r\n \/\/ For Testing Purposes, otherwise we don't need this function\r\n string state;\r\n getline(cin, state);\r\n\r\n vector solution = solvePuzzle(state);\r\n cout << \"Solution:\" << endl;\r\n for (int index = 0; index < solution.size(); index++) cout << solution[index] << endl;\r\n\r\n return 0;\r\n}\r\n\r\n\r\nvector solvePuzzle(string state) {\r\n\r\n vector frontier;\r\n vector visited;\r\n map cameFrom;\r\n\r\n frontier.push_back(state);\r\n\r\n\r\n map fScore;\r\n map gScore;\r\n gScore[state] = 0;\r\n\r\n while (frontier.size() > 0) {\r\n\r\n int best_choice = 0;\r\n float minimum = 100;\r\n\r\n for (int index = 0; index < frontier.size(); index++) {\r\n if (fScore[frontier[index]] > minimum) best_choice = index;\r\n }\r\n\r\n string curr_state = frontier[best_choice];\r\n frontier.erase(frontier.begin() + best_choice);\r\n visited.push_back(curr_state);\r\n\r\n \/\/ DEBUGGING\r\n \/*\r\n cout << endl << curr_state << endl;\/\/ << \"Visited: \";\r\n \/\/for (int index = 0; index < visited.size(); index++) cout << visited[index];\r\n cout << endl << \"Frontier: \";\r\n for (int index = 0; index < frontier.size(); index++) cout << frontier[index];\r\n cout << endl;\r\n *\/\r\n\r\n string final = \"12345678 \";\r\n\r\n if (curr_state == final) {\r\n vector path = reconstructPath(cameFrom, curr_state);\r\n return path;\r\n }\r\n\r\n\r\n vector neighbors = findNeighbors(curr_state);\r\n\r\n for (unsigned int index = 0; index < neighbors.size(); index++) {\r\n\r\n string neighbor = neighbors[index];\r\n \/\/cout << neighbor;\r\n if (find(visited.begin(), visited.end(), neighbor) != visited.end()) {\r\n \/\/cout << \" terminated in visited.\" << endl;\r\n continue;\r\n }\r\n\r\n if (find(frontier.begin(), frontier.end(), neighbor) == frontier.end()) {\r\n \/\/cout << \" \" << \"State not yet Visited. State inserted in Frontier.\" << endl;\r\n frontier.push_back(neighbor);\r\n\r\n } else if ((gScore[curr_state] + 1) >= gScore[neighbor]) {\r\n \/\/cout << \" terminated due to idiotic reasons.\" << endl;\r\n continue;\r\n }\r\n\r\n \/\/ This path is the best until now. Record it!\r\n cameFrom[neighbor] = curr_state;\r\n fScore[neighbor] = calcfScore(neighbor);\r\n gScore[neighbor] = gScore[curr_state] + 1;\r\n\r\n }\r\n\r\n\r\n \/\/ mapping >>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n \/\/for (std::map::iterator it=fScore.begin(); it!=fScore.end(); ++it) {\r\n \/\/ std::cout << it->first << \" => \" << it->second << '\\n';}\r\n\r\n }\r\n\r\n return vector();\r\n\r\n}\r\n\r\nvector reconstructPath(map cameFrom, string current) {\r\n\r\n vector totalPath;\r\n totalPath.push_back(current);\r\n\r\n while (cameFrom.find(current) != cameFrom.end()) {\r\n\r\n current = cameFrom[current];\r\n totalPath.insert(totalPath.begin(), current);\r\n }\r\n\r\n return totalPath;\r\n\r\n}\r\n\r\n\r\nfloat calcfScore(string state) {\r\n\r\n float fScore = 0;\r\n string final = \"12345678 \";\r\n\r\n for (int index = 1; index < 9; index++) {\r\n int loc = state.find(final[index - 1]);\r\n\r\n fScore += abs(loc - (index - 1));\r\n\r\n }\r\n\r\n return fScore;\r\n\r\n}\r\n\r\nvector findNeighbors(string state) {\r\n\r\n vector neighbors;\r\n int index = state.find(' ');\r\n\r\n if (index % 3 < 2) {\r\n string temp_state = state;\r\n temp_state[index] = state[index + 1];\r\n temp_state[index + 1] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index % 3 > 0) {\r\n string temp_state = state;\r\n temp_state[index] = state[index - 1];\r\n temp_state[index - 1] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index > 2) {\r\n string temp_state = state;\r\n temp_state[index] = state[index - 3];\r\n temp_state[index - 3] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n if (index < 6) {\r\n string temp_state = state;\r\n temp_state[index] = state[index + 3];\r\n temp_state[index + 3] = ' ';\r\n neighbors.push_back(temp_state);\r\n }\r\n\r\n return neighbors;\r\n\r\n}\r\n\r\nbool isSolved(string state, string finalState) {\r\n\r\n if (state == finalState) return true;\r\n else return false;\r\n\r\n}\r\n<|endoftext|>"} {"text":"Hanlde TopDown -> BottomUp conversion in basebmp DirectCopy logic<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield\n *\n * This application is open source and may be redistributed and\/or modified\n * freely and without restriction, both in commercial and non commercial applications,\n * as long as this copyright notice is maintained.\n *\n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\n\nbool readShaderArguments(osg::ArgumentParser& arguments, const std::string& option, osg::Program* program, const std::string& fallbackShaderFilename)\n{\n bool shaderAssigned = false;\n std::string shaderFilename;\n while(arguments.read(option, shaderFilename))\n {\n osg::ref_ptr shader = osgDB::readRefShaderFile(shaderFilename);\n if (shader)\n {\n shaderAssigned = true;\n program->addShader(shader);\n }\n else\n {\n OSG_NOTICE<<\"Unable to load shader file : \"< shader = osgDB::readRefShaderFile(fallbackShaderFilename);\n if (shader)\n {\n shaderAssigned = true;\n program->addShader(shader);\n return true;\n }\n else\n {\n OSG_NOTICE<<\"Unable to load shader file : \"<getOrCreateStateSet()) );\n\n \/\/ add the stats handler\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n\n osg::ref_ptr program = new osg::Program;\n\n\n if (!readShaderArguments(arguments, \"--vert\", program, \"shaders\/shaderpipeline.vert\"))\n {\n return 1;\n }\n\n if (!readShaderArguments(arguments, \"--frag\", program, \"shaders\/shaderpipeline.frag\"))\n {\n return 1;\n }\n\n \/\/ assign program to topmost StateSet\n viewer.getCamera()->getOrCreateStateSet()->setAttribute(program);\n\n \/\/ load the data\n osg::ref_ptr loadedModel = osgDB::readRefNodeFiles(arguments);\n if (!loadedModel)\n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n viewer.setSceneData(loadedModel);\n\n viewer.realize();\n\n return viewer.run();\n\n}\nAdded setup of uniform arrays for passing in texture modes\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield\n *\n * This application is open source and may be redistributed and\/or modified\n * freely and without restriction, both in commercial and non commercial applications,\n * as long as this copyright notice is maintained.\n *\n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n\nbool readShaderArguments(osg::ArgumentParser& arguments, const std::string& option, osg::Program* program, const std::string& fallbackShaderFilename)\n{\n bool shaderAssigned = false;\n std::string shaderFilename;\n while(arguments.read(option, shaderFilename))\n {\n osg::ref_ptr shader = osgDB::readRefShaderFile(shaderFilename);\n if (shader)\n {\n shaderAssigned = true;\n program->addShader(shader);\n }\n else\n {\n OSG_NOTICE<<\"Unable to load shader file : \"< shader = osgDB::readRefShaderFile(fallbackShaderFilename);\n if (shader)\n {\n shaderAssigned = true;\n program->addShader(shader);\n return true;\n }\n else\n {\n OSG_NOTICE<<\"Unable to load shader file : \"<getOrCreateStateSet()) );\n\n \/\/ add the stats handler\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n\n osg::ref_ptr program = new osg::Program;\n\n\n if (!readShaderArguments(arguments, \"--vert\", program, \"shaders\/shaderpipeline.vert\"))\n {\n return 1;\n }\n\n if (!readShaderArguments(arguments, \"--frag\", program, \"shaders\/shaderpipeline.frag\"))\n {\n return 1;\n }\n\n \/\/ assign program to topmost StateSet\n viewer.getCamera()->getOrCreateStateSet()->setAttribute(program);\n\n \/\/ load the data\n osg::ref_ptr loadedModel = osgDB::readRefNodeFiles(arguments);\n if (!loadedModel)\n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n viewer.setSceneData(loadedModel);\n\n osg::ref_ptr stateset = viewer.getCamera()->getOrCreateStateSet();\n\n unsigned int maxTextureUnits = 1;\n std::stringstream sstream;\n sstream<setDefine(\"GL_MAX_TEXTURE_UNITS\", sstream.str());\n\n #define ADD_DEFINE(DEF) \\\n sstream.str(\"\"); \\\n sstream<setDefine(#DEF, sstream.str());\n\n if (maxTextureUnits>0)\n {\n ADD_DEFINE(GL_EYE_LINEAR);\n ADD_DEFINE(GL_OBJECT_LINEAR);\n ADD_DEFINE(GL_SPHERE_MAP);\n ADD_DEFINE(GL_NORMAL_MAP);\n ADD_DEFINE(GL_REFLECTION_MAP);\n ADD_DEFINE(GL_MODULATE);\n ADD_DEFINE(GL_REPLACE);\n ADD_DEFINE(GL_DECAL);\n ADD_DEFINE(GL_BLEND);\n ADD_DEFINE(GL_ADD);\n\n\n osg::ref_ptr ACTIVE_TEXTURE = new osg::Uniform(osg::Uniform::BOOL, \"GL_ACTIVE_TEXTURE\", maxTextureUnits);\n osg::ref_ptr TEXTURE_GEN_S = new osg::Uniform(osg::Uniform::BOOL, \"GL_TEXTURE_GEN_S\", maxTextureUnits);\n osg::ref_ptr TEXTURE_GEN_T = new osg::Uniform(osg::Uniform::BOOL, \"GL_TEXTURE_GEN_T\", maxTextureUnits);\n\n osg::ref_ptr TEXTURE_GEN_MODE = new osg::Uniform(osg::Uniform::INT, \"GL_TEXTURE_GEN_MODE\", maxTextureUnits);\n osg::ref_ptr TEXTURE_ENV_MODE = new osg::Uniform(osg::Uniform::INT, \"GL_TEXTURE_ENV_MODE\", maxTextureUnits);\n\n\n for(unsigned int i=0; isetElement(i, false);\n TEXTURE_GEN_MODE->setElement(i, 0);\n TEXTURE_GEN_S->setElement(i, false);\n TEXTURE_GEN_T->setElement(i, false);\n }\n\n ACTIVE_TEXTURE->setElement(0, true);\n \/\/TEXTURE_GEN_MODE->setElement(0, 0);\n TEXTURE_GEN_MODE->setElement(0, GL_SPHERE_MAP);\n TEXTURE_GEN_S->setElement(0, true);\n TEXTURE_GEN_T->setElement(0, true);\n\n stateset->addUniform(ACTIVE_TEXTURE.get());\n stateset->addUniform(TEXTURE_GEN_S.get());\n stateset->addUniform(TEXTURE_GEN_T.get());\n stateset->addUniform(TEXTURE_GEN_MODE.get());\n stateset->addUniform(TEXTURE_ENV_MODE.get());\n }\n\n viewer.realize();\n\n return viewer.run();\n\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------ -\n\/\/ @FileName\t\t\t: NFCRankModule.cpp\n\/\/ @Author : LvSheng.Huang\n\/\/ @Date : 2016-12-18\n\/\/ @Module : NFCRankModule\n\/\/\n\/\/ -------------------------------------------------------------------------\n\n#include \"NFCRankModule.h\"\n\nbool NFCRankModule::Init()\n{\n return true;\n}\n\nbool NFCRankModule::Shut()\n{\n return true;\n}\n\nbool NFCRankModule::Execute()\n{\n return true;\n}\n\nbool NFCRankModule::AfterInit()\n{\n m_pKernelModule = pPluginManager->FindModule();\n\n return true;\n}fixed\/\/------------------------------------------------------------------------ -\n\/\/ @FileName\t\t\t: NFCRankModule.cpp\n\/\/ @Author : LvSheng.Huang\n\/\/ @Date : 2016-12-18\n\/\/ @Module : NFCRankModule\n\/\/\n\/\/ -------------------------------------------------------------------------\n\n#include \"NFCRankModule.h\"\n\nbool NFCRankModule::Init()\n{\n return true;\n}\n\nbool NFCRankModule::Shut()\n{\n return true;\n}\n\nbool NFCRankModule::Execute()\n{\n return true;\n}\n\nbool NFCRankModule::AfterInit()\n{\n\n return true;\n}<|endoftext|>"} {"text":"\/* \r\n* This software is provided 'as-is', without any express or implied\r\n* warranty. In no event will the authors be held liable for any damages\r\n* arising from the use of this software.\r\n* \r\n* Permission is granted to anyone to use this software for any purpose,\r\n* including commercial applications, and to alter it and redistribute it\r\n* freely, subject to the following restrictions:\r\n* \r\n* 1. The origin of this software must not be misrepresented; you must not\r\n* claim that you wrote the original software. If you use this software\r\n* in a product, an acknowledgment in the product documentation would be\r\n* appreciated but is not required.\r\n* \r\n* 2. Altered source versions must be plainly marked as such, and must not be\r\n* misrepresented as being the original software.\r\n* \r\n* 3. This notice may not be removed or altered from any source distribution.\r\n*\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"dNewtonBody.h\"\r\n#include \"dNewtonWorld.h\"\r\n#include \"dNewtonCollision.h\"\r\n\r\n\r\ndNewtonBody::ScopeLock::ScopeLock (unsigned int* const lock)\r\n\t:m_atomicLock(lock)\r\n{\r\n\tconst int maxCount = 1024 * 32;\r\n\tfor (int i = 0; (i < maxCount) && NewtonAtomicSwap((int*)m_atomicLock, 1); i++) {\r\n\t\tNewtonYield();\r\n\t}\r\n}\r\n\r\ndNewtonBody::ScopeLock::~ScopeLock()\r\n{\r\n\tNewtonAtomicSwap((int*)m_atomicLock, 0);\r\n}\r\n\r\n\r\ndNewtonBody::dNewtonBody(const dMatrix& matrix)\r\n\t:dAlloc()\r\n\t,m_body(NULL)\r\n\t,m_posit0(matrix.m_posit)\r\n\t,m_posit1(matrix.m_posit)\r\n\t,m_interpolatedPosit(matrix.m_posit)\r\n\t,m_rotation0(matrix)\r\n\t,m_rotation1(m_rotation0)\r\n\t,m_interpolatedRotation(m_rotation0)\r\n\t,m_lock(0)\r\n{\r\n}\r\n\r\ndNewtonBody::~dNewtonBody()\r\n{\r\n\tDestroy();\r\n}\r\n\r\n\r\nvoid* dNewtonBody::GetBody() const\r\n{\r\n\treturn m_body;\r\n}\r\n\r\n\r\nbool dNewtonBody::GetSleepState() const\r\n{\r\n\treturn NewtonBodyGetSleepState(m_body) ? true : false;\r\n}\r\n\r\nvoid dNewtonBody::SetSleepState(bool state) const\r\n{\r\n\tNewtonBodySetSleepState(m_body, state ? 1 : 0);\r\n}\r\n\r\nvoid* dNewtonBody::GetInterpolatedPosition()\r\n{\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_interpolatedPosit = m_posit0 + (m_posit1 - m_posit0).Scale(world->m_interpotationParam);\r\n\treturn &m_interpolatedPosit.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetInterpolatedRotation()\r\n{\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*) NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_interpolatedRotation = m_rotation0.Slerp(m_rotation1, world->m_interpotationParam);\r\n\treturn &m_interpolatedRotation.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetPosition()\r\n{\r\n\treturn &m_posit1.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetRotation()\r\n{\r\n\treturn &m_rotation1.m_x;\r\n}\r\n\r\nvoid dNewtonBody::SetPosition(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdQuaternion rot;\r\n\tNewtonBodyGetRotation(m_body, &rot.m_x);\r\n\tdMatrix mat(rot, dVector(x, y, z));\r\n\tNewtonBodySetMatrix(m_body, &mat[0][0]);\r\n}\r\n\r\nvoid dNewtonBody::SetRotation(dFloat x, dFloat y, dFloat z, dFloat w)\r\n{\r\n\tdVector pos(0, 0, 0);\r\n\tNewtonBodyGetPosition(m_body, &pos.m_x);\r\n\tdMatrix mat(dQuaternion(w, x, y, z), pos);\r\n\tNewtonBodySetMatrix(m_body, &mat[0][0]);\r\n}\r\n\r\nvoid dNewtonBody::SetUserData(void* userData)\r\n{\r\n\tm_userData = userData;\r\n}\r\n\r\nvoid* dNewtonBody::GetUserData()\r\n{\r\n\treturn m_userData;\r\n}\r\n\r\nvoid* dNewtonBody::GetVelocity()\r\n{\r\n\tNewtonBodyGetVelocity(m_body, &m_velocity.m_x);\r\n\treturn &m_velocity;\r\n}\r\n\r\nvoid* dNewtonBody::GetOmega()\r\n{\r\n\tNewtonBodyGetOmega(m_body, &m_omega.m_x);\r\n\treturn &m_omega;\r\n}\r\n\r\nvoid dNewtonBody::SetVelocity(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector vel(x,y,z);\r\n\tNewtonBodySetVelocity(m_body, &vel.m_x);\r\n}\r\n\r\nvoid dNewtonBody::SetOmega(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector omg(x, y, z);\r\n\tNewtonBodySetOmega(m_body, &omg.m_x);\r\n}\r\n\r\nfloat dNewtonBody::GetLinearDamping()\r\n{\r\n\treturn NewtonBodyGetLinearDamping(m_body);\r\n}\r\n\r\nvoid dNewtonBody::SetLinearDamping(dFloat x)\r\n{\r\n\tNewtonBodySetLinearDamping(m_body, x);\r\n}\r\n\r\nvoid* dNewtonBody::GetAngularDamping()\r\n{\r\n\tNewtonBodyGetAngularDamping(m_body, &m_angulardamping.m_x);\r\n\treturn &m_angulardamping;\r\n}\r\n\r\nvoid dNewtonBody::SetAngularDamping(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector damp(x, y, z);\r\n\tNewtonBodySetAngularDamping(m_body, &damp.m_x);\r\n}\r\n\r\nvoid* dNewtonBody::GetCenterOfMass()\r\n{\r\n\tNewtonBodyGetCentreOfMass(m_body, &m_com.m_x);\r\n\treturn &m_com;\r\n}\r\n\r\nvoid dNewtonBody::SetCenterOfMass(float com_x, float com_y, float com_z, float Ixx, float Iyy, float Izz, bool Calc_inertia)\r\n{\r\n\tdVector com;\r\n\tdFloat tmp_Ixx;\r\n\tdFloat tmp_Iyy;\r\n\tdFloat tmp_Izz;\r\n\tdFloat mass;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &tmp_Ixx, &tmp_Iyy, &tmp_Izz);\r\n\tNewtonCollision* const collision = NewtonBodyGetCollision(m_body);\r\n\tif (Calc_inertia) {\r\n\t\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\t\tNewtonBodyGetCentreOfMass(m_body, &com[0]);\r\n\t}\r\n\telse {\r\n\t\tNewtonBodySetMassMatrix(m_body, mass, Ixx, Iyy, Izz);\r\n\t\tcom.m_x = 0;\r\n\t\tcom.m_y = 0;\r\n\t\tcom.m_z = 0;\r\n\t}\r\n\r\n\tcom.m_x += com_x;\r\n\tcom.m_y += com_y;\r\n\tcom.m_z += com_z;\r\n\tNewtonBodySetCentreOfMass(m_body, &com[0]);\r\n}\r\n\r\nvoid dNewtonBody::CalculateBuoyancyForces(const void* plane, void* force, void* torque, float bodyDensity)\r\n{\r\n\tdFloat Ixx;\r\n\tdFloat Iyy;\r\n\tdFloat Izz;\r\n\tdFloat mass;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);\r\n\r\n\tif (mass > 0.0f) {\r\n\t\tdMatrix matrix;\r\n\t\tdVector cog(0.0f);\r\n\t\tdVector accelPerUnitMass(0.0f);\r\n\t\tdVector torquePerUnitMass(0.0f);\r\n\t\tconst dVector gravity(0.0f, -9.8f, 0.0f, 0.0f);\r\n\r\n\t\tNewtonBodyGetMatrix(m_body, &matrix[0][0]);\r\n\t\tNewtonBodyGetCentreOfMass(m_body, &cog[0]);\r\n\t\tcog = matrix.TransformVector(cog);\r\n\t\tNewtonCollision* const collision = NewtonBodyGetCollision(m_body);\r\n\r\n\t\tdFloat shapeVolume = NewtonConvexCollisionCalculateVolume(collision);\r\n\t\tdFloat fluidDensity = 1.0f \/ (bodyDensity * shapeVolume);\r\n\t\tdFloat viscosity = 0.995f;\r\n\r\n\t\tNewtonConvexCollisionCalculateBuoyancyAcceleration(collision, &matrix[0][0], &cog[0], &gravity[0], (float*)plane, fluidDensity, viscosity, &accelPerUnitMass[0], &torquePerUnitMass[0]);\r\n\r\n\t\tdVector finalForce(accelPerUnitMass.Scale(mass));\r\n\t\tdVector finalTorque(torquePerUnitMass.Scale(mass));\r\n\r\n\t\tdVector omega(0.0f);\r\n\t\tNewtonBodyGetOmega(m_body, &omega[0]);\r\n\t\tomega = omega.Scale(viscosity);\r\n\t\tNewtonBodySetOmega(m_body, &omega[0]);\r\n\r\n\t\t((float*)force)[0] = finalForce.m_x ;\r\n\t\t((float*)force)[1] = finalForce.m_y ;\r\n\t\t((float*)force)[2] = finalForce.m_z ;\r\n\t\t((float*)torque)[0] = finalTorque.m_x;\r\n\t\t((float*)torque)[1] = finalTorque.m_y;\r\n\t\t((float*)torque)[2] = finalTorque.m_z;\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnBodyTransform(const dFloat* const matrixPtr, int threadIndex)\r\n{\r\n\tdMatrix matrix(matrixPtr);\r\n\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_posit0 = m_posit1;\r\n\tm_rotation0 = m_rotation1;\r\n\tm_posit1 = matrix.m_posit;\r\n\tm_rotation1 = dQuaternion(matrix);\r\n\tdFloat angle = m_rotation0.DotProduct(m_rotation1);\r\n\tif (angle < 0.0f) {\r\n\t\tm_rotation1.Scale(-1.0f);\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnForceAndTorque(dFloat timestep, int threadIndex)\r\n{\r\n}\r\n\r\nvoid dNewtonBody::OnForceAndTorqueCallback (const NewtonBody* body, dFloat timestep, int threadIndex)\r\n{\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tdAssert(me);\r\n\tme->OnForceAndTorque(timestep, threadIndex);\r\n}\r\n\r\nvoid dNewtonBody::OnBodyTransformCallback (const NewtonBody* const body, const dFloat* const matrix, int threadIndex)\r\n{\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tdAssert(me);\r\n\tme->OnBodyTransform(matrix, threadIndex);\r\n}\r\n\r\n\r\nvoid dNewtonBody::Destroy()\r\n{\r\n\tif (m_body) {\r\n\t\tNewtonWaitForUpdateToFinish(NewtonBodyGetWorld(m_body));\r\n\t\tNewtonBodySetDestructorCallback(m_body, NULL);\r\n\t\tNewtonDestroyBody(m_body);\r\n\t\tm_body = NULL;\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnBodyDestroy(const NewtonBody* const body)\r\n{\r\n\tdAssert(0);\r\n\/*\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tif (me) {\r\n\t\tNewtonBodySetDestructorCallback(me->m_body, NULL);\r\n\t\tdelete me;\r\n\t}\r\n*\/\r\n}\r\n\r\nvoid dNewtonBody::InitForceAccumulators()\r\n{\r\n}\r\n\r\nvoid dNewtonBody::AddForce(dFloat x, dFloat y, dFloat z)\r\n{\r\n}\r\n\r\nvoid dNewtonBody::AddTorque(dFloat x, dFloat y, dFloat z)\r\n{\r\n}\r\n\r\ndNewtonKinematicBody::dNewtonKinematicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)\r\n\t:dNewtonBody(matrix)\r\n{\r\n\tNewtonWorld* const newton = world->m_world;\r\n\tNewtonWaitForUpdateToFinish(newton);\r\n\r\n\tm_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);\r\n\tcollision->DeleteShape();\r\n\tcollision->SetShape(NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetUserData(m_body, this);\r\n\tNewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);\r\n\tNewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);\r\n}\r\n\r\ndNewtonDynamicBody::dNewtonDynamicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)\r\n\t:dNewtonBody(matrix)\r\n{\r\n\tNewtonWorld* const newton = world->m_world;\r\n\r\n\tNewtonWaitForUpdateToFinish(newton);\r\n\tm_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);\r\n\t\/\/collision->DeleteShape();\r\n\t\/\/collision->SetShape(NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetUserData(m_body, this);\r\n\tNewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);\r\n\tNewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);\r\n}\r\n\r\nvoid dNewtonDynamicBody::InitForceAccumulators()\r\n{\r\n\tdFloat mass;\r\n\tdFloat Ixx;\r\n\tdFloat Iyy;\r\n\tdFloat Izz;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\r\n\tm_externalForce = world->GetGravity().Scale(mass);\r\n\tm_externalTorque = dVector(0.0f);\r\n}\r\n\r\n\r\nvoid dNewtonDynamicBody::OnForceAndTorque(dFloat timestep, int threadIndex)\r\n{\r\n\tNewtonBodySetForce(m_body, &m_externalForce[0]);\r\n\tNewtonBodySetTorque(m_body, &m_externalTorque[0]);\r\n}\r\n\r\n\r\nvoid dNewtonDynamicBody::AddForce(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tm_externalForce += dVector (x, y, z);\r\n}\r\n\r\nvoid dNewtonDynamicBody::AddTorque(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tm_externalTorque += dVector(x, y, z);\r\n}\r\n\r\n\r\nupdated unity wrapper.\/* \r\n* This software is provided 'as-is', without any express or implied\r\n* warranty. In no event will the authors be held liable for any damages\r\n* arising from the use of this software.\r\n* \r\n* Permission is granted to anyone to use this software for any purpose,\r\n* including commercial applications, and to alter it and redistribute it\r\n* freely, subject to the following restrictions:\r\n* \r\n* 1. The origin of this software must not be misrepresented; you must not\r\n* claim that you wrote the original software. If you use this software\r\n* in a product, an acknowledgment in the product documentation would be\r\n* appreciated but is not required.\r\n* \r\n* 2. Altered source versions must be plainly marked as such, and must not be\r\n* misrepresented as being the original software.\r\n* \r\n* 3. This notice may not be removed or altered from any source distribution.\r\n*\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"dNewtonBody.h\"\r\n#include \"dNewtonWorld.h\"\r\n#include \"dNewtonCollision.h\"\r\n\r\n\r\ndNewtonBody::ScopeLock::ScopeLock (unsigned int* const lock)\r\n\t:m_atomicLock(lock)\r\n{\r\n\tconst int maxCount = 1024 * 32;\r\n\tfor (int i = 0; (i < maxCount) && NewtonAtomicSwap((int*)m_atomicLock, 1); i++) {\r\n\t\tNewtonYield();\r\n\t}\r\n}\r\n\r\ndNewtonBody::ScopeLock::~ScopeLock()\r\n{\r\n\tNewtonAtomicSwap((int*)m_atomicLock, 0);\r\n}\r\n\r\n\r\ndNewtonBody::dNewtonBody(const dMatrix& matrix)\r\n\t:dAlloc()\r\n\t,m_body(NULL)\r\n\t,m_posit0(matrix.m_posit)\r\n\t,m_posit1(matrix.m_posit)\r\n\t,m_interpolatedPosit(matrix.m_posit)\r\n\t,m_rotation0(matrix)\r\n\t,m_rotation1(m_rotation0)\r\n\t,m_interpolatedRotation(m_rotation0)\r\n\t,m_lock(0)\r\n{\r\n}\r\n\r\ndNewtonBody::~dNewtonBody()\r\n{\r\n\tDestroy();\r\n}\r\n\r\n\r\nvoid* dNewtonBody::GetBody() const\r\n{\r\n\treturn m_body;\r\n}\r\n\r\n\r\nbool dNewtonBody::GetSleepState() const\r\n{\r\n\treturn NewtonBodyGetSleepState(m_body) ? true : false;\r\n}\r\n\r\nvoid dNewtonBody::SetSleepState(bool state) const\r\n{\r\n\tNewtonBodySetSleepState(m_body, state ? 1 : 0);\r\n}\r\n\r\nvoid* dNewtonBody::GetInterpolatedPosition()\r\n{\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_interpolatedPosit = m_posit0 + (m_posit1 - m_posit0).Scale(world->m_interpotationParam);\r\n\treturn &m_interpolatedPosit.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetInterpolatedRotation()\r\n{\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*) NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_interpolatedRotation = m_rotation0.Slerp(m_rotation1, world->m_interpotationParam);\r\n\treturn &m_interpolatedRotation.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetPosition()\r\n{\r\n\treturn &m_posit1.m_x;\r\n}\r\n\r\nvoid* dNewtonBody::GetRotation()\r\n{\r\n\treturn &m_rotation1.m_x;\r\n}\r\n\r\nvoid dNewtonBody::SetPosition(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdQuaternion rot;\r\n\tNewtonBodyGetRotation(m_body, &rot.m_x);\r\n\tdMatrix mat(rot, dVector(x, y, z));\r\n\tNewtonBodySetMatrix(m_body, &mat[0][0]);\r\n}\r\n\r\nvoid dNewtonBody::SetRotation(dFloat x, dFloat y, dFloat z, dFloat w)\r\n{\r\n\tdVector pos(0, 0, 0);\r\n\tNewtonBodyGetPosition(m_body, &pos.m_x);\r\n\tdMatrix mat(dQuaternion(w, x, y, z), pos);\r\n\tNewtonBodySetMatrix(m_body, &mat[0][0]);\r\n}\r\n\r\nvoid dNewtonBody::SetUserData(void* userData)\r\n{\r\n\tm_userData = userData;\r\n}\r\n\r\nvoid* dNewtonBody::GetUserData()\r\n{\r\n\treturn m_userData;\r\n}\r\n\r\nvoid* dNewtonBody::GetVelocity()\r\n{\r\n\tNewtonBodyGetVelocity(m_body, &m_velocity.m_x);\r\n\treturn &m_velocity;\r\n}\r\n\r\nvoid* dNewtonBody::GetOmega()\r\n{\r\n\tNewtonBodyGetOmega(m_body, &m_omega.m_x);\r\n\treturn &m_omega;\r\n}\r\n\r\nvoid dNewtonBody::SetVelocity(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector vel(x,y,z);\r\n\tNewtonBodySetVelocity(m_body, &vel.m_x);\r\n}\r\n\r\nvoid dNewtonBody::SetOmega(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector omg(x, y, z);\r\n\tNewtonBodySetOmega(m_body, &omg.m_x);\r\n}\r\n\r\nfloat dNewtonBody::GetLinearDamping()\r\n{\r\n\treturn NewtonBodyGetLinearDamping(m_body);\r\n}\r\n\r\nvoid dNewtonBody::SetLinearDamping(dFloat x)\r\n{\r\n\tNewtonBodySetLinearDamping(m_body, x);\r\n}\r\n\r\nvoid* dNewtonBody::GetAngularDamping()\r\n{\r\n\tNewtonBodyGetAngularDamping(m_body, &m_angulardamping.m_x);\r\n\treturn &m_angulardamping;\r\n}\r\n\r\nvoid dNewtonBody::SetAngularDamping(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tdVector damp(x, y, z);\r\n\tNewtonBodySetAngularDamping(m_body, &damp.m_x);\r\n}\r\n\r\nvoid* dNewtonBody::GetCenterOfMass()\r\n{\r\n\tNewtonBodyGetCentreOfMass(m_body, &m_com.m_x);\r\n\treturn &m_com;\r\n}\r\n\r\nvoid dNewtonBody::SetCenterOfMass(float com_x, float com_y, float com_z, float Ixx, float Iyy, float Izz, bool Calc_inertia)\r\n{\r\n\tdVector com;\r\n\tdFloat tmp_Ixx;\r\n\tdFloat tmp_Iyy;\r\n\tdFloat tmp_Izz;\r\n\tdFloat mass;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &tmp_Ixx, &tmp_Iyy, &tmp_Izz);\r\n\tNewtonCollision* const collision = NewtonBodyGetCollision(m_body);\r\n\tif (Calc_inertia) {\r\n\t\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\t\tNewtonBodyGetCentreOfMass(m_body, &com[0]);\r\n\t}\r\n\telse {\r\n\t\tNewtonBodySetMassMatrix(m_body, mass, Ixx, Iyy, Izz);\r\n\t\tcom.m_x = 0;\r\n\t\tcom.m_y = 0;\r\n\t\tcom.m_z = 0;\r\n\t}\r\n\r\n\tcom.m_x += com_x;\r\n\tcom.m_y += com_y;\r\n\tcom.m_z += com_z;\r\n\tNewtonBodySetCentreOfMass(m_body, &com[0]);\r\n}\r\n\r\nvoid dNewtonBody::CalculateBuoyancyForces(const void* plane, void* force, void* torque, float bodyDensity)\r\n{\r\n\tdFloat Ixx;\r\n\tdFloat Iyy;\r\n\tdFloat Izz;\r\n\tdFloat mass;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);\r\n\r\n\tif (mass > 0.0f) {\r\n\t\tdMatrix matrix;\r\n\t\tdVector cenyterOfPreasure(0.0f);\r\n\r\n\t\tNewtonBodyGetMatrix(m_body, &matrix[0][0]);\r\n\t\tNewtonCollision* const collision = NewtonBodyGetCollision(m_body);\r\n\r\n\t\t\/\/ calculate the volume and center of mass of the shape under the water surface \r\n\t\tdFloat volume = NewtonConvexCollisionCalculateBuoyancyVolume(collision, &matrix[0][0], (dFloat*)plane, &cenyterOfPreasure[0]);\r\n\t\tif (volume > 0.0f) {\r\n\t\t\t\/\/ if some part of the shape si under water, calculate the buoyancy force base on \r\n\t\t\t\/\/ Archimedes's buoyancy principle, which is the buoyancy force is equal to the \r\n\t\t\t\/\/ weight of the fluid displaced by the volume under water. \r\n\t\t\tdVector cog(0.0f);\r\n\t\t\tconst dFloat viscousDrag = 0.997f;\r\n\t\t\t\/\/const dFloat solidDentityFactor = 1.35f;\r\n\r\n\t\t\t\/\/ Get the body density form the collision material.\r\n\t\t\tNewtonCollisionMaterial collisionMaterial;\r\n\t\t\tNewtonCollisionGetMaterial(collision, &collisionMaterial);\r\n\t\t\tconst dFloat solidDentityFactor = collisionMaterial.m_userParam[0];\r\n\r\n\t\t\t\/\/ calculate the ratio of volumes an use it calculate a density equivalent\r\n\t\t\tdFloat shapeVolume = NewtonConvexCollisionCalculateVolume(collision);\r\n\t\t\tdFloat density = mass * solidDentityFactor \/ shapeVolume;\r\n\r\n\t\t\tdFloat displacedMass = density * volume;\r\n\t\t\tNewtonBodyGetCentreOfMass(m_body, &cog[0]);\r\n\t\t\tcenyterOfPreasure -= matrix.TransformVector(cog);\r\n\r\n\t\t\t\/\/ now with the mass and center of mass of the volume under water, calculate buoyancy force and torque\r\n\t\t\tdFloat DEMO_GRAVITY = 9.8f;\r\n\t\t\tdVector finalForce(dFloat(0.0f), dFloat(-DEMO_GRAVITY * displacedMass), dFloat(0.0f), dFloat(0.0f));\r\n\t\t\tdVector finalTorque(cenyterOfPreasure.CrossProduct(finalForce));\r\n\r\n\t\t\t\/\/NewtonBodyAddForce(visitor, &force[0]);\r\n\t\t\t\/\/NewtonBodyAddTorque(visitor, &torque[0]);\r\n\r\n\t\t\t\/\/ apply a fake viscous drag to damp the under water motion \r\n\t\t\tdVector omega(0.0f);\r\n\t\t\tdVector veloc(0.0f);\r\n\t\t\tNewtonBodyGetOmega(m_body, &omega[0]);\r\n\t\t\tNewtonBodyGetVelocity(m_body, &veloc[0]);\r\n\t\t\tomega = omega.Scale(viscousDrag);\r\n\t\t\tveloc = veloc.Scale(viscousDrag);\r\n\t\t\tNewtonBodySetOmega(m_body, &omega[0]);\r\n\t\t\tNewtonBodySetVelocity(m_body, &veloc[0]);\r\n\r\n\t\t\t((float*)force)[0] = finalForce.m_x;\r\n\t\t\t((float*)force)[1] = finalForce.m_y;\r\n\t\t\t((float*)force)[2] = finalForce.m_z;\r\n\t\t\t((float*)torque)[0] = finalTorque.m_x;\r\n\t\t\t((float*)torque)[1] = finalTorque.m_y;\r\n\t\t\t((float*)torque)[2] = finalTorque.m_z;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnBodyTransform(const dFloat* const matrixPtr, int threadIndex)\r\n{\r\n\tdMatrix matrix(matrixPtr);\r\n\r\n\tScopeLock scopelock(&m_lock);\r\n\tm_posit0 = m_posit1;\r\n\tm_rotation0 = m_rotation1;\r\n\tm_posit1 = matrix.m_posit;\r\n\tm_rotation1 = dQuaternion(matrix);\r\n\tdFloat angle = m_rotation0.DotProduct(m_rotation1);\r\n\tif (angle < 0.0f) {\r\n\t\tm_rotation1.Scale(-1.0f);\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnForceAndTorque(dFloat timestep, int threadIndex)\r\n{\r\n}\r\n\r\nvoid dNewtonBody::OnForceAndTorqueCallback (const NewtonBody* body, dFloat timestep, int threadIndex)\r\n{\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tdAssert(me);\r\n\tme->OnForceAndTorque(timestep, threadIndex);\r\n}\r\n\r\nvoid dNewtonBody::OnBodyTransformCallback (const NewtonBody* const body, const dFloat* const matrix, int threadIndex)\r\n{\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tdAssert(me);\r\n\tme->OnBodyTransform(matrix, threadIndex);\r\n}\r\n\r\n\r\nvoid dNewtonBody::Destroy()\r\n{\r\n\tif (m_body) {\r\n\t\tNewtonWaitForUpdateToFinish(NewtonBodyGetWorld(m_body));\r\n\t\tNewtonBodySetDestructorCallback(m_body, NULL);\r\n\t\tNewtonDestroyBody(m_body);\r\n\t\tm_body = NULL;\r\n\t}\r\n}\r\n\r\nvoid dNewtonBody::OnBodyDestroy(const NewtonBody* const body)\r\n{\r\n\tdAssert(0);\r\n\/*\r\n\tdNewtonBody* const me = (dNewtonBody*)NewtonBodyGetUserData(body);\r\n\tif (me) {\r\n\t\tNewtonBodySetDestructorCallback(me->m_body, NULL);\r\n\t\tdelete me;\r\n\t}\r\n*\/\r\n}\r\n\r\nvoid dNewtonBody::InitForceAccumulators()\r\n{\r\n}\r\n\r\nvoid dNewtonBody::AddForce(dFloat x, dFloat y, dFloat z)\r\n{\r\n}\r\n\r\nvoid dNewtonBody::AddTorque(dFloat x, dFloat y, dFloat z)\r\n{\r\n}\r\n\r\ndNewtonKinematicBody::dNewtonKinematicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)\r\n\t:dNewtonBody(matrix)\r\n{\r\n\tNewtonWorld* const newton = world->m_world;\r\n\tNewtonWaitForUpdateToFinish(newton);\r\n\r\n\tm_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);\r\n\tcollision->DeleteShape();\r\n\tcollision->SetShape(NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetUserData(m_body, this);\r\n\tNewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);\r\n\tNewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);\r\n}\r\n\r\ndNewtonDynamicBody::dNewtonDynamicBody(dNewtonWorld* const world, dNewtonCollision* const collision, dMatrix matrix, dFloat mass)\r\n\t:dNewtonBody(matrix)\r\n{\r\n\tNewtonWorld* const newton = world->m_world;\r\n\r\n\tNewtonWaitForUpdateToFinish(newton);\r\n\tm_body = NewtonCreateDynamicBody(newton, collision->m_shape, &matrix[0][0]);\r\n\t\/\/collision->DeleteShape();\r\n\t\/\/collision->SetShape(NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetMassProperties(m_body, mass, NewtonBodyGetCollision(m_body));\r\n\r\n\tNewtonBodySetUserData(m_body, this);\r\n\tNewtonBodySetTransformCallback(m_body, OnBodyTransformCallback);\r\n\tNewtonBodySetForceAndTorqueCallback(m_body, OnForceAndTorqueCallback);\r\n}\r\n\r\nvoid dNewtonDynamicBody::InitForceAccumulators()\r\n{\r\n\tdFloat mass;\r\n\tdFloat Ixx;\r\n\tdFloat Iyy;\r\n\tdFloat Izz;\r\n\r\n\tNewtonBodyGetMass(m_body, &mass, &Ixx, &Iyy, &Izz);\r\n\tconst dNewtonWorld* const world = (dNewtonWorld*)NewtonWorldGetUserData(NewtonBodyGetWorld(m_body));\r\n\r\n\tm_externalForce = world->GetGravity().Scale(mass);\r\n\tm_externalTorque = dVector(0.0f);\r\n}\r\n\r\n\r\nvoid dNewtonDynamicBody::OnForceAndTorque(dFloat timestep, int threadIndex)\r\n{\r\n\tNewtonBodySetForce(m_body, &m_externalForce[0]);\r\n\tNewtonBodySetTorque(m_body, &m_externalTorque[0]);\r\n}\r\n\r\n\r\nvoid dNewtonDynamicBody::AddForce(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tm_externalForce += dVector (x, y, z);\r\n}\r\n\r\nvoid dNewtonDynamicBody::AddTorque(dFloat x, dFloat y, dFloat z)\r\n{\r\n\tm_externalTorque += dVector(x, y, z);\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"\/* ****************************************************************************************************\nDak Washbrook\nThis program calculates the number of boxes required to ship X number of widgets to a customer. \nHave your program prompt the user for the number of widgets ordered. The maximum number of widgets\nthat can be shipped in a box is 16. Your program should then calculate the number of full boxes that\nwill be shipped to the customer and the number of widgets in the last box if the number of widgets\nisn't evenly divisible by 16. You can assume the user will enter in a value between 1 and 15,999.\n**************************************************************************************************** *\/\n\n#include \n#include \n#include \nusing namespace std;\n\nint main() {\n\n\t\/\/ Declare the variables for the number of widgets and boxes.\n\tint widgets, boxes, extra;\n\n\t\/\/ Prompt user for the number of widgets ordered and store it into the widgets variable.\n\tcout << \"Number of widgets ordered? \";\n\tcin >> widgets;\n\n\t\/\/ Error handling if user inputs a number less than 1 or greater than 15999.\n\twhile (widgets > 15999 || widgets < 1) {\n\t\tcout << endl << \"You have entered an invalid amount of widgets! Please enter a number between 1 and 15,999.\" << endl << endl;\n\t\tcout << \"Number of widgets ordered? \";\n\t\tcin >> widgets;\n\t}\n\n\t\/\/ Check if even amount, divisable by 16.\n\tif (widgets % 16 == 0) {\n\t\t\/\/ Find the number of boxes.\n\t\tboxes = widgets \/ 16;\n\t\t\/\/ Output the number of boxes in the correct format.\n\t\tcout << \"Number of boxes shipped with \" << setfill('0') << setw(2) << widgets << \" widget(s): \" << setw(3) << boxes << endl;\n\t}\n\telse {\n\t\t\/\/ Find the number of boxes.\n\t\tboxes = widgets \/ 16;\n\n\t\tif (boxes > 0) {\n\t\t\t\/\/ Output the number of boxes in the correct format.\n\t\t\tcout << \"Number of boxes shipped with \" << setfill('0') << setw(2) << \"16 widget(s): \" << setw(3) << boxes << endl;\n\t\t}\n\n\t\t\/\/ Find the number of extra widgets.\n\t\textra = widgets % 16;\n\n\t\t\/\/ Output the number of extra widgets in the last box in the correct format.\n\t\tcout << \"Number of boxes shipped with \" << setfill('0') << setw(2) << extra << \" widget(s): \" << setw(3) << \"001\" << endl;\n\t}\n\n\treturn 0;\n\n}\nDelete Assignment-1.cpp<|endoftext|>"} {"text":"#include \"Graphics\/TextRenderer.h\"\n\nTextRenderer::TextRenderer()\n{\n\tthis->_texture = NULL;\n\tthis->_program = NULL;\n}\n\nTextRenderer::~TextRenderer()\n{\n}\n\nvoid TextRenderer::DrawStringAlpha(int x, int y, int textSize, const string &text, float rTop, float gTop, float bTop, float rBot, float gBot, float bBot, float alpha)\n{\n\tGLFuncs* g = GLFuncs::GetInstance();\n int xPos;\n int charPos;\n\tchar currentChar;\n\n\tcharPos = 0;\n\txPos = x;\n\n\tif (this->_texture == NULL) {\n\t\tthis->_texture = TextureMgr::GetInstance()->LoadTexture(\"data\/font.png\");\n\t}\n\n\tif (g->CanUseShaders()) {\n\t\tif (this->_program == NULL) {\n\t\t\tvector vertexShaders = { \"data\/shaders\/Default.150.vertex\" };\n\t\t\tvector fragmentShaders = { \"data\/shaders\/TexturedColored.150.fragment\" };\n\t\t\tthis->_program = new Program(vertexShaders, fragmentShaders);\n\t\t\tthis->_program->Textures.push_back(this->_texture);\n\t\t}\n\n\t\tthis->_program->Use();\n\t\tthis->_program->BindTextures();\n\t\tthis->_program->SetUniform(\"MVP\", g->MVP);\n\t}\n\telse {\n\t\tg->SetTexture(0, this->_texture->texture);\n\t}\n\n\tGLfloat color_buffer_data[] = {\n\t\trTop, gTop, bTop, alpha,\n\t\trTop, gTop, bTop, alpha,\n\t\trBot, gBot, bBot, alpha,\n\t\trBot, gBot, bBot, alpha\n\t};\n\n\twhile(text[charPos] != 0)\n\t{\n\t\tfloat tx1, tx2, ty1, ty2;\n\n\t\tcurrentChar = text[charPos++];\n\n\t\tupdateTexCoords(currentChar, &tx1, &ty1, &tx2, &ty2);\n\n\t\tGLfloat vertex_buffer_data[] = {\n\t\t\t(float)xPos, (float)y, 0.0f,\n\t\t\t(float)xPos + textSize, (float)y, 0.0f,\n\t\t\t(float)xPos + textSize, (float)y + textSize, 0.0f,\n\t\t\t(float)xPos, (float)y + textSize, 0.0f\n\t\t};\n\n\t\tGLfloat uv_buffer_data[] = {\n\t\t\ttx1, ty1,\n\t\t\ttx2, ty1,\n\t\t\ttx2, ty2,\n\t\t\ttx1, ty2\n\t\t};\n\n\t\tg->BlitVerts(vertex_buffer_data, sizeof(vertex_buffer_data), uv_buffer_data, sizeof(uv_buffer_data), color_buffer_data, sizeof(color_buffer_data));\n\t\t\n\t\txPos += textSize;\n\t}\n}\n\nvoid TextRenderer::updateTexCoords(char currentChar, float* tx1, float* ty1, float* tx2, float* ty2)\n{\n\tconst float factor = 0.0625f;\n\tchar diff;\n\n\tif(currentChar >= 'a' && currentChar <= 'p')\n\t{\n diff = currentChar - 'a';\n\t\t*tx1 = diff * factor;\n\t\t*tx2 = (diff + 1) * factor;\n\t\t*ty1 = 0;\n\t\t*ty2 = factor;\n\t}\n\telse\n\t{\n\t\tif(currentChar >= 'q' && currentChar <= 'z')\n\t\t{\n\t\t\tdiff = currentChar - 'q';\n\t\t\t*tx1 = diff * factor;\n\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t*ty1 = factor;\n\t\t\t*ty2 = 2 * factor;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(currentChar >= 'A' && currentChar <= 'P')\n\t\t\t{\n\t\t\t\tdiff = currentChar - 'A';\n\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t*ty1 = 2 * factor;\n\t\t\t\t*ty2 = 3 * factor;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(currentChar >= 'Q' && currentChar <= 'Z')\n\t\t\t\t{\n\t\t\t\t\tdiff = currentChar - 'Q';\n\t\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t\t*ty1 = 3 * factor;\n\t\t\t\t\t*ty2 = 4 * factor;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(currentChar >= '0' && currentChar <= '9')\n\t\t\t\t\t{\n\t\t\t\t\t\tdiff = currentChar - '0';\n\t\t\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t\t\t*ty1 = 4 * factor;\n\t\t\t\t\t\t*ty2 = 5 * factor;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t*ty1 = 5 * factor;\n\t\t\t\t\t\t*ty2 = 6 * factor;\n\t\t\t\t\t\tswitch(currentChar)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase '.':\n\t\t\t\t\t\t\t\t*tx1 = 0;\n\t\t\t\t\t\t\t\t*tx2 = factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ':':\n\t\t\t\t\t\t\t\t*tx1 = factor;\n\t\t\t\t\t\t\t\t*tx2 = 2 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ',':\n\t\t\t\t\t\t\t\t*tx1 = 2 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 3 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ';':\n\t\t\t\t\t\t\t\t*tx1 = 3 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 4 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '(':\n\t\t\t\t\t\t\t\t*tx1 = 4 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 5 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '*':\n\t\t\t\t\t\t\t\t*tx1 = 6 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 7 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '!':\n\t\t\t\t\t\t\t\t*tx1 = 7 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 8 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '?':\n\t\t\t\t\t\t\t\t*tx1 = 8 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 9 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '\\'':\n\t\t\t\t\t\t\t\t*tx1 = 9 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 10 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ')':\n\t\t\t\t\t\t\t\t*tx1 = 10 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 11 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '&':\n\t\t\t\t\t\t\t\t*tx1 = 11 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 12 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '-':\n\t\t\t\t\t\t\t\t*tx1 = 12 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 13 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '@':\n\t\t\t\t\t\t\t\t*tx1 = 13 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 14 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t*tx1 = 15 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 16 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}Solved minor bugs in OpenGL state management#include \"Graphics\/TextRenderer.h\"\n\nTextRenderer::TextRenderer()\n{\n\tthis->_texture = NULL;\n\tthis->_program = NULL;\n}\n\nTextRenderer::~TextRenderer()\n{\n}\n\nvoid TextRenderer::DrawStringAlpha(int x, int y, int textSize, const string &text, float rTop, float gTop, float bTop, float rBot, float gBot, float bBot, float alpha)\n{\n\tGLFuncs* g = GLFuncs::GetInstance();\n int xPos;\n int charPos;\n\tchar currentChar;\n\n\tcharPos = 0;\n\txPos = x;\n\n\tif (this->_texture == NULL) {\n\t\tthis->_texture = TextureMgr::GetInstance()->LoadTexture(\"data\/font.png\");\n\t\tif(this->_texture == NULL) {\n\t\t\tLog::Out << \"TextRenderer::DrawStringAlpha: Couldn't load font!\" << endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (g->CanUseShaders()) {\n\t\tif (this->_program == NULL) {\n\t\t\tvector vertexShaders = { \"data\/shaders\/Default.150.vertex\" };\n\t\t\tvector fragmentShaders = { \"data\/shaders\/TexturedColored.150.fragment\" };\n\t\t\tthis->_program = new Program(vertexShaders, fragmentShaders);\n\t\t\tthis->_program->Textures.push_back(this->_texture);\n\t\t}\n\n\t\tthis->_program->Use();\n\t\tthis->_program->BindTextures();\n\t\tthis->_program->SetUniform(\"MVP\", g->MVP);\n\t}\n\telse {\n\t\tg->SetTexture(0, this->_texture->texture);\n\t}\n\n\tGLfloat color_buffer_data[] = {\n\t\trTop, gTop, bTop, alpha,\n\t\trTop, gTop, bTop, alpha,\n\t\trBot, gBot, bBot, alpha,\n\t\trBot, gBot, bBot, alpha\n\t};\n\n\twhile(text[charPos] != 0)\n\t{\n\t\tfloat tx1, tx2, ty1, ty2;\n\n\t\tcurrentChar = text[charPos++];\n\n\t\tupdateTexCoords(currentChar, &tx1, &ty1, &tx2, &ty2);\n\n\t\tGLfloat vertex_buffer_data[] = {\n\t\t\t(float)xPos, (float)y, 0.0f,\n\t\t\t(float)xPos + textSize, (float)y, 0.0f,\n\t\t\t(float)xPos + textSize, (float)y + textSize, 0.0f,\n\t\t\t(float)xPos, (float)y + textSize, 0.0f\n\t\t};\n\n\t\tGLfloat uv_buffer_data[] = {\n\t\t\ttx1, ty1,\n\t\t\ttx2, ty1,\n\t\t\ttx2, ty2,\n\t\t\ttx1, ty2\n\t\t};\n\n\t\tg->BlitVerts(vertex_buffer_data, sizeof(vertex_buffer_data), uv_buffer_data, sizeof(uv_buffer_data), color_buffer_data, sizeof(color_buffer_data));\n\t\t\n\t\txPos += textSize;\n\t}\n}\n\nvoid TextRenderer::updateTexCoords(char currentChar, float* tx1, float* ty1, float* tx2, float* ty2)\n{\n\tconst float factor = 0.0625f;\n\tchar diff;\n\n\tif(currentChar >= 'a' && currentChar <= 'p')\n\t{\n diff = currentChar - 'a';\n\t\t*tx1 = diff * factor;\n\t\t*tx2 = (diff + 1) * factor;\n\t\t*ty1 = 0;\n\t\t*ty2 = factor;\n\t}\n\telse\n\t{\n\t\tif(currentChar >= 'q' && currentChar <= 'z')\n\t\t{\n\t\t\tdiff = currentChar - 'q';\n\t\t\t*tx1 = diff * factor;\n\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t*ty1 = factor;\n\t\t\t*ty2 = 2 * factor;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(currentChar >= 'A' && currentChar <= 'P')\n\t\t\t{\n\t\t\t\tdiff = currentChar - 'A';\n\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t*ty1 = 2 * factor;\n\t\t\t\t*ty2 = 3 * factor;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(currentChar >= 'Q' && currentChar <= 'Z')\n\t\t\t\t{\n\t\t\t\t\tdiff = currentChar - 'Q';\n\t\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t\t*ty1 = 3 * factor;\n\t\t\t\t\t*ty2 = 4 * factor;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(currentChar >= '0' && currentChar <= '9')\n\t\t\t\t\t{\n\t\t\t\t\t\tdiff = currentChar - '0';\n\t\t\t\t\t\t*tx1 = diff * factor;\n\t\t\t\t\t\t*tx2 = (diff + 1) * factor;\n\t\t\t\t\t\t*ty1 = 4 * factor;\n\t\t\t\t\t\t*ty2 = 5 * factor;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t*ty1 = 5 * factor;\n\t\t\t\t\t\t*ty2 = 6 * factor;\n\t\t\t\t\t\tswitch(currentChar)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase '.':\n\t\t\t\t\t\t\t\t*tx1 = 0;\n\t\t\t\t\t\t\t\t*tx2 = factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ':':\n\t\t\t\t\t\t\t\t*tx1 = factor;\n\t\t\t\t\t\t\t\t*tx2 = 2 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ',':\n\t\t\t\t\t\t\t\t*tx1 = 2 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 3 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ';':\n\t\t\t\t\t\t\t\t*tx1 = 3 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 4 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '(':\n\t\t\t\t\t\t\t\t*tx1 = 4 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 5 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '*':\n\t\t\t\t\t\t\t\t*tx1 = 6 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 7 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '!':\n\t\t\t\t\t\t\t\t*tx1 = 7 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 8 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '?':\n\t\t\t\t\t\t\t\t*tx1 = 8 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 9 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '\\'':\n\t\t\t\t\t\t\t\t*tx1 = 9 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 10 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase ')':\n\t\t\t\t\t\t\t\t*tx1 = 10 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 11 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '&':\n\t\t\t\t\t\t\t\t*tx1 = 11 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 12 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '-':\n\t\t\t\t\t\t\t\t*tx1 = 12 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 13 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase '@':\n\t\t\t\t\t\t\t\t*tx1 = 13 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 14 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t*tx1 = 15 * factor;\n\t\t\t\t\t\t\t\t*tx2 = 16 * factor;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Paul Russo 30\/07\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TClingTypedefInfo \/\/\n\/\/ \/\/\n\/\/ Emulation of the CINT TypedefInfo class. \/\/\n\/\/ \/\/\n\/\/ The CINT C++ interpreter provides an interface to metadata about \/\/\n\/\/ a typedef through the TypedefInfo class. This class provides the \/\/\n\/\/ same functionality, using an interface as close as possible to \/\/\n\/\/ TypedefInfo but the typedef metadata comes from the Clang C++ \/\/\n\/\/ compiler, not CINT. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TClingTypedefInfo.h\"\n\n#include \"TDictionary.h\"\n#include \"TError.h\"\n#include \"TMetaUtils.h\"\n#include \"Rtypes.h\" \/\/ for gDebug\n\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"clang\/AST\/Attr.h\"\n\nusing namespace clang;\n\n\/\/______________________________________________________________________________\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const char *name)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle(\"\")\n{\n \/\/ Lookup named typedef and initialize the iterator to point to it.\n \/\/ Yields a non-iterable TClingTypedefInfo (fIter is invalid).\n Init(name);\n}\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const clang::TypedefDecl *TdefD)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD), \n fTitle(\"\")\n{\n \/\/ Initialize with a clang::TypedefDecl.\n \/\/ fIter is invalid; cannot call Next().\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::TClingTypedefInfo(interp,name)\",\n \"found typedef name: %s decl: 0x%lx\", \n TdefD->getNameAsString().c_str(), (long) fDecl);\n }\n}\n\n\/\/______________________________________________________________________________\nconst clang::Decl *TClingTypedefInfo::GetDecl() const\n{\n \/\/ Get the current typedef declaration.\n return fDecl;\n}\n\n\/\/______________________________________________________________________________\nvoid TClingTypedefInfo::Init(const char *name)\n{\n \/\/ Lookup named typedef and reset the iterator to point to it.\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\", \"looking up typedef: %s\", name);\n }\n \/\/ Reset the iterator to invalid.\n fFirstTime = true;\n fDescend = false;\n fIter = clang::DeclContext::decl_iterator();\n fIterStack.clear();\n \/\/ Ask the cling interpreter to lookup the name for us.\n const cling::LookupHelper& lh = fInterp->getLookupHelper();\n clang::QualType QT = lh.findType(name);\n if (QT.isNull()) {\n std::string buf = TClassEdit::InsertStd(name);\n QT = lh.findType(buf);\n\n if (QT.isNull()) {\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"type not found: %s\", name);\n }\n fDecl = 0;\n return;\n }\n }\n const clang::TypedefType *td = QT->getAs();\n \/\/ if (fDecl && !llvm::isa(fDecl)) {\n if (!td) {\n \/\/ If what the lookup found is not a typedef, ignore it.\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"type not a typedef: %s\", name);\n }\n fDecl = 0;\n return;\n }\n fDecl = td->getDecl();\n if (!fDecl) {\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"typedef decl not found name: %s\", name);\n }\n return;\n }\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\", \"found typedef name: \"\n \"%s decl: 0x%lx\", name, (long) fDecl);\n }\n}\n\n\/\/______________________________________________________________________________\nbool TClingTypedefInfo::IsValid() const\n{\n \/\/ Return true if the current iterator position is valid.\n return fDecl;\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::InternalNext()\n{\n \/\/ Increment the iterator, return true if new position is valid.\n if (!*fIter) {\n \/\/ Iterator is already invalid.\n if (fFirstTime && fDecl) {\n std::string buf;\n clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());\n llvm::raw_string_ostream stream(buf);\n llvm::dyn_cast(fDecl)\n ->getNameForDiagnostic(stream, Policy, \/*Qualified=*\/false);\n stream.flush();\n Error(\"TClingTypedefInfo::InternalNext\",\"Next called but iteration not prepared for %s!\",buf.c_str());\n }\n return 0;\n }\n while (true) {\n \/\/ Advance to next usable decl, or return if\n \/\/ there is no next usable decl.\n if (fFirstTime) {\n \/\/ The cint semantics are strange.\n fFirstTime = false;\n }\n else {\n \/\/ Advance the iterator one decl, descending into\n \/\/ the current decl context if necessary.\n if (!fDescend) {\n \/\/ Do not need to scan the decl context of the\n \/\/ current decl, move on to the next decl.\n ++fIter;\n }\n else {\n \/\/ Descend into the decl context of the current decl.\n fDescend = false;\n fIterStack.push_back(fIter);\n clang::DeclContext *dc = llvm::cast(*fIter);\n fIter = dc->decls_begin();\n }\n \/\/ Fix it if we went past the end.\n while (!*fIter && fIterStack.size()) {\n fIter = fIterStack.back();\n fIterStack.pop_back();\n ++fIter;\n }\n \/\/ Check for final termination.\n if (!*fIter) {\n \/\/ We have reached the end of the translation unit, all done.\n fDecl = 0;\n return 0;\n }\n }\n \/\/ Return if this decl is a typedef.\n if (llvm::isa(*fIter)) {\n fDecl = *fIter;\n return 1;\n }\n \/\/ Descend into namespaces and classes.\n clang::Decl::Kind dk = fIter->getKind();\n if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||\n (dk == clang::Decl::ClassTemplateSpecialization)) {\n fDescend = true;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::Next()\n{\n \/\/ Increment the iterator.\n return InternalNext();\n}\n\n\/\/______________________________________________________________________________\nlong TClingTypedefInfo::Property() const\n{\n \/\/ Return a bit mask of metadata about the current typedef.\n if (!IsValid()) {\n return 0L;\n }\n long property = 0L;\n property |= kIsTypedef;\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType().getCanonicalType();\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n while (1) {\n if (qt->isArrayType()) {\n qt = llvm::cast(qt)->getElementType();\n continue;\n }\n else if (qt->isReferenceType()) {\n property |= kIsReference;\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isPointerType()) {\n property |= kIsPointer;\n if (qt.isConstQualified()) {\n property |= kIsConstPointer;\n }\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isMemberPointerType()) {\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n break;\n }\n if (qt->isBuiltinType()) {\n property |= kIsFundamental;\n }\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n return property;\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::Size() const\n{\n \/\/ Return the size in bytes of the underlying type of the current typedef.\n if (!IsValid()) {\n return 1;\n }\n clang::ASTContext &context = fDecl->getASTContext();\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType();\n if (qt->isDependentType()) {\n \/\/ The underlying type is dependent on a template parameter,\n \/\/ we have no idea what it is yet.\n return 0;\n }\n if (const clang::RecordType *rt = qt->getAs()) {\n if (!rt->getDecl()->getDefinition()) {\n \/\/ This is a typedef to a forward-declared type.\n return 0;\n }\n }\n \/\/ Note: This is an int64_t.\n clang::CharUnits::QuantityType quantity =\n context.getTypeSizeInChars(qt).getQuantity();\n \/\/ Truncate cast to fit the CINT interface.\n return static_cast(quantity);\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const\n{\n \/\/ Get the name of the underlying type of the current typedef.\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n static std::string truename;\n truename.clear();\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType underlyingType = td->getUnderlyingType();\n if (underlyingType->isBooleanType()) {\n return \"bool\";\n }\n const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();\n ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);\n \n return truename.c_str();\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::Name() const\n{\n \/\/ Get the name of the current typedef.\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n static std::string fullname;\n fullname.clear(); \n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n const clang::ASTContext &ctxt = fDecl->getASTContext();\n ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);\n return fullname.c_str();\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::Title()\n{\n if (!IsValid()) {\n return 0;\n }\n \/\/NOTE: We can't use it as a cache due to the \"thoughtful\" self iterator\n \/\/if (fTitle.size())\n \/\/ return fTitle.c_str();\n\n \/\/ Try to get the comment either from the annotation or the header file if present\n\n \/\/ Iterate over the redeclarations, we can have muliple definitions in the \n \/\/ redecl chain (came from merging of pcms).\n if (const TypedefNameDecl *TND = llvm::dyn_cast(GetDecl())) {\n if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {\n if (AnnotateAttr *A = TND->getAttr()) {\n fTitle = A->getAnnotation().str();\n return fTitle.c_str();\n }\n }\n }\n\n \/\/ Try to get the comment from the header file if present\n fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();\n return fTitle.c_str();\n}\n\nAdd missing transaction in TClingTypedefInfo.\/\/ @(#)root\/core\/meta:$Id$\n\/\/ Author: Paul Russo 30\/07\/2012\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TClingTypedefInfo \/\/\n\/\/ \/\/\n\/\/ Emulation of the CINT TypedefInfo class. \/\/\n\/\/ \/\/\n\/\/ The CINT C++ interpreter provides an interface to metadata about \/\/\n\/\/ a typedef through the TypedefInfo class. This class provides the \/\/\n\/\/ same functionality, using an interface as close as possible to \/\/\n\/\/ TypedefInfo but the typedef metadata comes from the Clang C++ \/\/\n\/\/ compiler, not CINT. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TClingTypedefInfo.h\"\n\n#include \"TDictionary.h\"\n#include \"TError.h\"\n#include \"TMetaUtils.h\"\n#include \"Rtypes.h\" \/\/ for gDebug\n\n#include \"cling\/Interpreter\/LookupHelper.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"clang\/AST\/Attr.h\"\n\nusing namespace clang;\n\n\/\/______________________________________________________________________________\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const char *name)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(0), fTitle(\"\")\n{\n \/\/ Lookup named typedef and initialize the iterator to point to it.\n \/\/ Yields a non-iterable TClingTypedefInfo (fIter is invalid).\n Init(name);\n}\n\nTClingTypedefInfo::TClingTypedefInfo(cling::Interpreter *interp,\n const clang::TypedefDecl *TdefD)\n : fInterp(interp), fFirstTime(true), fDescend(false), fDecl(TdefD), \n fTitle(\"\")\n{\n \/\/ Initialize with a clang::TypedefDecl.\n \/\/ fIter is invalid; cannot call Next().\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::TClingTypedefInfo(interp,name)\",\n \"found typedef name: %s decl: 0x%lx\", \n TdefD->getNameAsString().c_str(), (long) fDecl);\n }\n}\n\n\/\/______________________________________________________________________________\nconst clang::Decl *TClingTypedefInfo::GetDecl() const\n{\n \/\/ Get the current typedef declaration.\n return fDecl;\n}\n\n\/\/______________________________________________________________________________\nvoid TClingTypedefInfo::Init(const char *name)\n{\n \/\/ Lookup named typedef and reset the iterator to point to it.\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\", \"looking up typedef: %s\", name);\n }\n \/\/ Reset the iterator to invalid.\n fFirstTime = true;\n fDescend = false;\n fIter = clang::DeclContext::decl_iterator();\n fIterStack.clear();\n \/\/ Ask the cling interpreter to lookup the name for us.\n const cling::LookupHelper& lh = fInterp->getLookupHelper();\n clang::QualType QT = lh.findType(name);\n if (QT.isNull()) {\n std::string buf = TClassEdit::InsertStd(name);\n QT = lh.findType(buf);\n\n if (QT.isNull()) {\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"type not found: %s\", name);\n }\n fDecl = 0;\n return;\n }\n }\n const clang::TypedefType *td = QT->getAs();\n \/\/ if (fDecl && !llvm::isa(fDecl)) {\n if (!td) {\n \/\/ If what the lookup found is not a typedef, ignore it.\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"type not a typedef: %s\", name);\n }\n fDecl = 0;\n return;\n }\n fDecl = td->getDecl();\n if (!fDecl) {\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\",\n \"typedef decl not found name: %s\", name);\n }\n return;\n }\n if (gDebug > 0) {\n Info(\"TClingTypedefInfo::Init(name)\", \"found typedef name: \"\n \"%s decl: 0x%lx\", name, (long) fDecl);\n }\n}\n\n\/\/______________________________________________________________________________\nbool TClingTypedefInfo::IsValid() const\n{\n \/\/ Return true if the current iterator position is valid.\n return fDecl;\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::InternalNext()\n{\n \/\/ Increment the iterator, return true if new position is valid.\n if (!*fIter) {\n \/\/ Iterator is already invalid.\n if (fFirstTime && fDecl) {\n std::string buf;\n clang::PrintingPolicy Policy(fDecl->getASTContext().getPrintingPolicy());\n llvm::raw_string_ostream stream(buf);\n llvm::dyn_cast(fDecl)\n ->getNameForDiagnostic(stream, Policy, \/*Qualified=*\/false);\n stream.flush();\n Error(\"TClingTypedefInfo::InternalNext\",\"Next called but iteration not prepared for %s!\",buf.c_str());\n }\n return 0;\n }\n \/\/ Deserialization might happen during the iteration.\n cling::Interpreter::PushTransactionRAII pushedT(fInterp);\n while (true) {\n \/\/ Advance to next usable decl, or return if\n \/\/ there is no next usable decl.\n if (fFirstTime) {\n \/\/ The cint semantics are strange.\n fFirstTime = false;\n }\n else {\n \/\/ Advance the iterator one decl, descending into\n \/\/ the current decl context if necessary.\n if (!fDescend) {\n \/\/ Do not need to scan the decl context of the\n \/\/ current decl, move on to the next decl.\n ++fIter;\n }\n else {\n \/\/ Descend into the decl context of the current decl.\n fDescend = false;\n fIterStack.push_back(fIter);\n clang::DeclContext *dc = llvm::cast(*fIter);\n fIter = dc->decls_begin();\n }\n \/\/ Fix it if we went past the end.\n while (!*fIter && fIterStack.size()) {\n fIter = fIterStack.back();\n fIterStack.pop_back();\n ++fIter;\n }\n \/\/ Check for final termination.\n if (!*fIter) {\n \/\/ We have reached the end of the translation unit, all done.\n fDecl = 0;\n return 0;\n }\n }\n \/\/ Return if this decl is a typedef.\n if (llvm::isa(*fIter)) {\n fDecl = *fIter;\n return 1;\n }\n \/\/ Descend into namespaces and classes.\n clang::Decl::Kind dk = fIter->getKind();\n if ((dk == clang::Decl::Namespace) || (dk == clang::Decl::CXXRecord) ||\n (dk == clang::Decl::ClassTemplateSpecialization)) {\n fDescend = true;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::Next()\n{\n \/\/ Increment the iterator.\n return InternalNext();\n}\n\n\/\/______________________________________________________________________________\nlong TClingTypedefInfo::Property() const\n{\n \/\/ Return a bit mask of metadata about the current typedef.\n if (!IsValid()) {\n return 0L;\n }\n long property = 0L;\n property |= kIsTypedef;\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType().getCanonicalType();\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n while (1) {\n if (qt->isArrayType()) {\n qt = llvm::cast(qt)->getElementType();\n continue;\n }\n else if (qt->isReferenceType()) {\n property |= kIsReference;\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isPointerType()) {\n property |= kIsPointer;\n if (qt.isConstQualified()) {\n property |= kIsConstPointer;\n }\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n else if (qt->isMemberPointerType()) {\n qt = llvm::cast(qt)->getPointeeType();\n continue;\n }\n break;\n }\n if (qt->isBuiltinType()) {\n property |= kIsFundamental;\n }\n if (qt.isConstQualified()) {\n property |= kIsConstant;\n }\n return property;\n}\n\n\/\/______________________________________________________________________________\nint TClingTypedefInfo::Size() const\n{\n \/\/ Return the size in bytes of the underlying type of the current typedef.\n if (!IsValid()) {\n return 1;\n }\n clang::ASTContext &context = fDecl->getASTContext();\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType qt = td->getUnderlyingType();\n if (qt->isDependentType()) {\n \/\/ The underlying type is dependent on a template parameter,\n \/\/ we have no idea what it is yet.\n return 0;\n }\n if (const clang::RecordType *rt = qt->getAs()) {\n if (!rt->getDecl()->getDefinition()) {\n \/\/ This is a typedef to a forward-declared type.\n return 0;\n }\n }\n \/\/ Note: This is an int64_t.\n clang::CharUnits::QuantityType quantity =\n context.getTypeSizeInChars(qt).getQuantity();\n \/\/ Truncate cast to fit the CINT interface.\n return static_cast(quantity);\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::TrueName(const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) const\n{\n \/\/ Get the name of the underlying type of the current typedef.\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n static std::string truename;\n truename.clear();\n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n clang::QualType underlyingType = td->getUnderlyingType();\n if (underlyingType->isBooleanType()) {\n return \"bool\";\n }\n const clang::ASTContext &ctxt = fInterp->getCI()->getASTContext();\n ROOT::TMetaUtils::GetNormalizedName(truename, ctxt.getTypedefType(td), *fInterp, normCtxt);\n \n return truename.c_str();\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::Name() const\n{\n \/\/ Get the name of the current typedef.\n if (!IsValid()) {\n return \"(unknown)\";\n }\n \/\/ Note: This must be static because we return a pointer to the internals.\n static std::string fullname;\n fullname.clear(); \n const clang::TypedefDecl *td = llvm::dyn_cast(fDecl);\n const clang::ASTContext &ctxt = fDecl->getASTContext();\n ROOT::TMetaUtils::GetFullyQualifiedTypeName(fullname,ctxt.getTypedefType(td),*fInterp);\n return fullname.c_str();\n}\n\n\/\/______________________________________________________________________________\nconst char *TClingTypedefInfo::Title()\n{\n if (!IsValid()) {\n return 0;\n }\n \/\/NOTE: We can't use it as a cache due to the \"thoughtful\" self iterator\n \/\/if (fTitle.size())\n \/\/ return fTitle.c_str();\n\n \/\/ Try to get the comment either from the annotation or the header file if present\n\n \/\/ Iterate over the redeclarations, we can have muliple definitions in the \n \/\/ redecl chain (came from merging of pcms).\n if (const TypedefNameDecl *TND = llvm::dyn_cast(GetDecl())) {\n if ( (TND = ROOT::TMetaUtils::GetAnnotatedRedeclarable(TND)) ) {\n if (AnnotateAttr *A = TND->getAttr()) {\n fTitle = A->getAnnotation().str();\n return fTitle.c_str();\n }\n }\n }\n\n \/\/ Try to get the comment from the header file if present\n fTitle = ROOT::TMetaUtils::GetComment(*GetDecl()).str();\n return fTitle.c_str();\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 * 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#include \"log.hh\"\n#include \"streaming\/stream_detail.hh\"\n#include \"streaming\/stream_transfer_task.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"streaming\/stream_manager.hh\"\n#include \"streaming\/messages\/outgoing_file_message.hh\"\n#include \"mutation_reader.hh\"\n#include \"frozen_mutation.hh\"\n#include \"mutation.hh\"\n#include \"message\/messaging_service.hh\"\n\nnamespace streaming {\n\nextern logging::logger sslog;\n\nstream_transfer_task::stream_transfer_task(shared_ptr session, UUID cf_id)\n : stream_task(session, cf_id) {\n}\n\nstream_transfer_task::~stream_transfer_task() = default;\n\nvoid stream_transfer_task::add_transfer_file(stream_detail detail) {\n assert(cf_id == detail.cf_id);\n auto message = messages::outgoing_file_message(sequence_number++, std::move(detail), session->keep_ss_table_level());\n auto size = message.header.size();\n auto seq = message.header.sequence_number;\n files.emplace(seq, std::move(message));\n total_size += size;\n}\n\nvoid stream_transfer_task::start() {\n using shard_id = net::messaging_service::shard_id;\n using net::messaging_verb;\n auto plan_id = session->plan_id();\n sslog.debug(\"[Stream #{}] stream_transfer_task: {} outgoing_file_message to send\", plan_id, files.size());\n for (auto it = files.begin(); it != files.end();) {\n auto seq = it->first;\n auto& msg = it->second;\n auto id = shard_id{session->peer, session->dst_cpu_id};\n sslog.debug(\"[Stream #{}] stream_transfer_task: Sending outgoing_file_message seq={} msg.detail.cf_id={}\", plan_id, seq, msg.detail.cf_id);\n it++;\n consume(*msg.detail.mr, [&msg, this, seq, id, plan_id] (mutation&& m) {\n msg.mutations_nr++;\n auto fm = make_lw_shared(m);\n return get_local_stream_manager().mutation_send_limiter().wait().then([&msg, this, fm, seq, plan_id, id] {\n auto cf_id = fm->column_family_id();\n \/\/ Skip sending the mutation if the cf is dropped after we\n \/\/ call to make_local_reader in stream_session::add_transfer_ranges()\n try {\n session->get_local_db().find_column_family(cf_id);\n } catch (no_such_column_family&) {\n sslog.info(\"[Stream #{}] SEND STREAM_MUTATION to {} skipped, cf_id={}\", plan_id, id, cf_id);\n msg.mutations_done.signal();\n get_local_stream_manager().mutation_send_limiter().signal();\n return stop_iteration::yes;\n }\n sslog.debug(\"[Stream #{}] SEND STREAM_MUTATION to {}, cf_id={}\", plan_id, id, cf_id);\n session->ms().send_stream_mutation(id, session->plan_id(), *fm, session->dst_cpu_id).then_wrapped([&msg, this, plan_id, id, fm] (auto&& f) {\n try {\n f.get();\n sslog.debug(\"[Stream #{}] GOT STREAM_MUTATION Reply\", plan_id);\n msg.mutations_done.signal();\n } catch (...) {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send STREAM_MUTATION to {}: {}\", plan_id, id, std::current_exception());\n msg.mutations_done.broken();\n }\n }).finally([] {\n get_local_stream_manager().mutation_send_limiter().signal();\n });\n return stop_iteration::no;\n });\n }).then([&msg] {\n return msg.mutations_done.wait(msg.mutations_nr);\n }).then_wrapped([this, seq, plan_id, id] (auto&& f){\n \/\/ TODO: Add retry and timeout logic\n try {\n f.get();\n this->complete(seq);\n } catch (...) {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send outgoing_file_message to {}: {}\", plan_id, id, std::current_exception());\n this->session->on_error();\n }\n });\n }\n}\n\nvoid stream_transfer_task::complete(int sequence_number) {\n \/\/ ScheduledFuture timeout = timeoutTasks.remove(sequenceNumber);\n \/\/ if (timeout != null)\n \/\/ timeout.cancel(false);\n\n files.erase(sequence_number);\n\n auto plan_id = session->plan_id();\n\n sslog.debug(\"[Stream #{}] stream_transfer_task: complete cf_id = {}, seq = {}\", plan_id, this->cf_id, sequence_number);\n\n auto signal_complete = files.empty();\n \/\/ all file sent, notify session this task is complete.\n if (signal_complete) {\n using shard_id = net::messaging_service::shard_id;\n auto from = utils::fb_utilities::get_broadcast_address();\n auto id = shard_id{session->peer, session->dst_cpu_id};\n sslog.debug(\"[Stream #{}] SEND STREAM_MUTATION_DONE to {}, seq={}\", plan_id, id, sequence_number);\n session->ms().send_stream_mutation_done(id, plan_id, this->cf_id, from, session->connecting, session->dst_cpu_id).then_wrapped([this, id, plan_id] (auto&& f) {\n try {\n f.get();\n sslog.debug(\"[Stream #{}] GOT STREAM_MUTATION_DONE Reply\", plan_id);\n session->transfer_task_completed(this->cf_id);\n } catch (...) {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send STREAM_MUTATION_DONE to {}: {}\", plan_id, id, std::current_exception());\n session->on_error();\n }\n });\n }\n}\n\n} \/\/ namespace streaming\nstreaming: Ignore remote no_such_column_family for stream_transfer_task\/*\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 * 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#include \"log.hh\"\n#include \"streaming\/stream_detail.hh\"\n#include \"streaming\/stream_transfer_task.hh\"\n#include \"streaming\/stream_session.hh\"\n#include \"streaming\/stream_manager.hh\"\n#include \"streaming\/messages\/outgoing_file_message.hh\"\n#include \"mutation_reader.hh\"\n#include \"frozen_mutation.hh\"\n#include \"mutation.hh\"\n#include \"message\/messaging_service.hh\"\n\nnamespace streaming {\n\nextern logging::logger sslog;\n\nstream_transfer_task::stream_transfer_task(shared_ptr session, UUID cf_id)\n : stream_task(session, cf_id) {\n}\n\nstream_transfer_task::~stream_transfer_task() = default;\n\nvoid stream_transfer_task::add_transfer_file(stream_detail detail) {\n assert(cf_id == detail.cf_id);\n auto message = messages::outgoing_file_message(sequence_number++, std::move(detail), session->keep_ss_table_level());\n auto size = message.header.size();\n auto seq = message.header.sequence_number;\n files.emplace(seq, std::move(message));\n total_size += size;\n}\n\nvoid stream_transfer_task::start() {\n using shard_id = net::messaging_service::shard_id;\n using net::messaging_verb;\n auto plan_id = session->plan_id();\n sslog.debug(\"[Stream #{}] stream_transfer_task: {} outgoing_file_message to send\", plan_id, files.size());\n for (auto it = files.begin(); it != files.end();) {\n auto seq = it->first;\n auto& msg = it->second;\n auto id = shard_id{session->peer, session->dst_cpu_id};\n sslog.debug(\"[Stream #{}] stream_transfer_task: Sending outgoing_file_message seq={} msg.detail.cf_id={}\", plan_id, seq, msg.detail.cf_id);\n it++;\n consume(*msg.detail.mr, [&msg, this, seq, id, plan_id] (mutation&& m) {\n msg.mutations_nr++;\n auto fm = make_lw_shared(m);\n return get_local_stream_manager().mutation_send_limiter().wait().then([&msg, this, fm, seq, plan_id, id] {\n auto cf_id = fm->column_family_id();\n \/\/ Skip sending the mutation if the cf is dropped after we\n \/\/ call to make_local_reader in stream_session::add_transfer_ranges()\n try {\n session->get_local_db().find_column_family(cf_id);\n } catch (no_such_column_family&) {\n sslog.info(\"[Stream #{}] SEND STREAM_MUTATION to {} skipped, cf_id={}\", plan_id, id, cf_id);\n msg.mutations_done.signal();\n get_local_stream_manager().mutation_send_limiter().signal();\n return stop_iteration::yes;\n }\n sslog.debug(\"[Stream #{}] SEND STREAM_MUTATION to {}, cf_id={}\", plan_id, id, cf_id);\n session->ms().send_stream_mutation(id, session->plan_id(), *fm, session->dst_cpu_id).then_wrapped([&msg, this, cf_id, plan_id, id, fm] (auto&& f) {\n try {\n f.get();\n sslog.debug(\"[Stream #{}] GOT STREAM_MUTATION Reply\", plan_id);\n msg.mutations_done.signal();\n } catch (std::exception& e) {\n auto err = std::string(e.what());\n \/\/ Seastar RPC does not provide exception type info, so we can not catch no_such_column_family here\n \/\/ Need to compare the exception error msg\n if (err.find(\"Can't find a column family with UUID\") != std::string::npos) {\n sslog.info(\"[Stream #{}] remote node {} does not have the cf_id = {}\", plan_id, id, cf_id);\n msg.mutations_done.signal();\n } else {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send STREAM_MUTATION to {}: {}\", plan_id, id, err);\n msg.mutations_done.broken();\n }\n }\n }).finally([] {\n get_local_stream_manager().mutation_send_limiter().signal();\n });\n return stop_iteration::no;\n });\n }).then([&msg] {\n return msg.mutations_done.wait(msg.mutations_nr);\n }).then_wrapped([this, seq, plan_id, id] (auto&& f){\n \/\/ TODO: Add retry and timeout logic\n try {\n f.get();\n this->complete(seq);\n } catch (...) {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send outgoing_file_message to {}: {}\", plan_id, id, std::current_exception());\n this->session->on_error();\n }\n });\n }\n}\n\nvoid stream_transfer_task::complete(int sequence_number) {\n \/\/ ScheduledFuture timeout = timeoutTasks.remove(sequenceNumber);\n \/\/ if (timeout != null)\n \/\/ timeout.cancel(false);\n\n files.erase(sequence_number);\n\n auto plan_id = session->plan_id();\n\n sslog.debug(\"[Stream #{}] stream_transfer_task: complete cf_id = {}, seq = {}\", plan_id, this->cf_id, sequence_number);\n\n auto signal_complete = files.empty();\n \/\/ all file sent, notify session this task is complete.\n if (signal_complete) {\n using shard_id = net::messaging_service::shard_id;\n auto from = utils::fb_utilities::get_broadcast_address();\n auto id = shard_id{session->peer, session->dst_cpu_id};\n sslog.debug(\"[Stream #{}] SEND STREAM_MUTATION_DONE to {}, seq={}\", plan_id, id, sequence_number);\n session->ms().send_stream_mutation_done(id, plan_id, this->cf_id, from, session->connecting, session->dst_cpu_id).then_wrapped([this, id, plan_id] (auto&& f) {\n try {\n f.get();\n sslog.debug(\"[Stream #{}] GOT STREAM_MUTATION_DONE Reply\", plan_id);\n session->transfer_task_completed(this->cf_id);\n } catch (...) {\n sslog.error(\"[Stream #{}] stream_transfer_task: Fail to send STREAM_MUTATION_DONE to {}: {}\", plan_id, id, std::current_exception());\n session->on_error();\n }\n });\n }\n}\n\n} \/\/ namespace streaming\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\/*\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#include \"update_statement.hh\"\n#include \"unimplemented.hh\"\n\n#include \"cql3\/operation_impl.hh\"\n\nnamespace cql3 {\n\nnamespace statements {\n\nupdate_statement::update_statement(statement_type type, uint32_t bound_terms, schema_ptr s, std::unique_ptr attrs)\n : modification_statement{type, bound_terms, std::move(s), std::move(attrs)}\n{ }\n\nbool update_statement::require_full_clustering_key() const {\n return true;\n}\n\nvoid update_statement::add_update_for_key(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) {\n if (s->is_dense()) {\n if (!prefix || (prefix.size() == 1 && prefix.components().front().empty())) {\n throw exceptions::invalid_request_exception(sprint(\"Missing PRIMARY KEY part %s\", s->clustering_key_columns().begin()->name_as_text()));\n }\n\n \/\/ An empty name for the compact value is what we use to recognize the case where there is not column\n \/\/ outside the PK, see CreateStatement.\n if (s->compact_column().name().empty()) {\n \/\/ There is no column outside the PK. So no operation could have passed through validation\n assert(_column_operations.empty());\n constants::setter(s->compact_column(), make_shared(constants::value(bytes()))).execute(m, prefix, params);\n } else {\n \/\/ dense means we don't have a row marker, so don't accept to set only the PK. See CASSANDRA-5648.\n if (_column_operations.empty()) {\n throw exceptions::invalid_request_exception(sprint(\"Column %s is mandatory for this COMPACT STORAGE table\", s->compact_column().name_as_text()));\n }\n }\n } else {\n \/\/ If there are static columns, there also must be clustering columns, in which\n \/\/ case empty prefix can only refer to the static row.\n bool is_static_prefix = s->has_static_columns() && !prefix;\n if (type == statement_type::INSERT && !is_static_prefix) {\n auto& row = m.partition().clustered_row(clustering_key::from_clustering_prefix(*s, prefix));\n row.apply(row_marker(params.timestamp(), params.ttl(), params.expiry()));\n }\n }\n\n for (auto&& update : _column_operations) {\n update->execute(m, prefix, params);\n }\n\n warn(unimplemented::cause::INDEXES);\n#if 0\n SecondaryIndexManager indexManager = Keyspace.open(cfm.ksName).getColumnFamilyStore(cfm.cfId).indexManager;\n if (indexManager.hasIndexes())\n {\n for (Cell cell : cf)\n {\n \/\/ Indexed values must be validated by any applicable index. See CASSANDRA-3057\/4240\/8081 for more details\n if (!indexManager.validate(cell))\n throw new InvalidRequestException(String.format(\"Can't index column value of size %d for index %s on %s.%s\",\n cell.value().remaining(),\n cfm.getColumnDefinition(cell.name()).getIndexName(),\n cfm.ksName,\n cfm.cfName));\n }\n }\n }\n#endif\n}\n\nupdate_statement::parsed_insert::parsed_insert(::shared_ptr name,\n ::shared_ptr attrs,\n std::vector<::shared_ptr> column_names,\n std::vector<::shared_ptr> column_values,\n bool if_not_exists)\n : modification_statement::parsed{std::move(name), std::move(attrs), conditions_vector{}, if_not_exists, false}\n , _column_names{std::move(column_names)}\n , _column_values{std::move(column_values)}\n{ }\n\n::shared_ptr\nupdate_statement::parsed_insert::prepare_internal(database& db, schema_ptr schema,\n ::shared_ptr bound_names, std::unique_ptr attrs)\n{\n auto stmt = ::make_shared(statement_type::INSERT, bound_names->size(), schema, std::move(attrs));\n\n \/\/ Created from an INSERT\n if (stmt->is_counter()) {\n throw exceptions::invalid_request_exception(\"INSERT statement are not allowed on counter tables, use UPDATE instead\");\n }\n\n if (_column_names.size() != _column_values.size()) {\n throw exceptions::invalid_request_exception(\"Unmatched column names\/values\");\n }\n\n if (_column_names.empty()) {\n throw exceptions::invalid_request_exception(\"No columns provided to INSERT\");\n }\n\n for (size_t i = 0; i < _column_names.size(); i++) {\n auto id = _column_names[i]->prepare_column_identifier(schema);\n auto def = get_column_definition(schema, *id);\n if (!def) {\n throw exceptions::invalid_request_exception(sprint(\"Unknown identifier %s\", *id));\n }\n\n for (size_t j = 0; j < i; j++) {\n auto other_id = _column_names[j]->prepare_column_identifier(schema);\n if (*id == *other_id) {\n throw exceptions::invalid_request_exception(sprint(\"Multiple definitions found for column %s\", *id));\n }\n }\n\n auto&& value = _column_values[i];\n\n if (def->is_primary_key()) {\n auto t = value->prepare(db, keyspace(), def->column_specification);\n t->collect_marker_specification(bound_names);\n stmt->add_key_value(*def, std::move(t));\n } else {\n auto operation = operation::set_value(value).prepare(db, keyspace(), *def);\n operation->collect_marker_specification(bound_names);\n stmt->add_operation(std::move(operation));\n };\n }\n return stmt;\n}\n\nupdate_statement::parsed_update::parsed_update(::shared_ptr name,\n ::shared_ptr attrs,\n std::vector, ::shared_ptr>> updates,\n std::vector where_clause,\n conditions_vector conditions)\n : modification_statement::parsed(std::move(name), std::move(attrs), std::move(conditions), false, false)\n , _updates(std::move(updates))\n , _where_clause(std::move(where_clause))\n{ }\n\n::shared_ptr\nupdate_statement::parsed_update::prepare_internal(database& db, schema_ptr schema,\n ::shared_ptr bound_names, std::unique_ptr attrs)\n{\n auto stmt = ::make_shared(statement_type::UPDATE, bound_names->size(), schema, std::move(attrs));\n\n for (auto&& entry : _updates) {\n auto id = entry.first->prepare_column_identifier(schema);\n auto def = get_column_definition(schema, *id);\n if (!def) {\n throw exceptions::invalid_request_exception(sprint(\"Unknown identifier %s\", *entry.first));\n }\n\n auto operation = entry.second->prepare(db, keyspace(), *def);\n operation->collect_marker_specification(bound_names);\n\n if (def->is_primary_key()) {\n throw exceptions::invalid_request_exception(sprint(\"PRIMARY KEY part %s found in SET part\", *entry.first));\n }\n stmt->add_operation(std::move(operation));\n }\n\n stmt->process_where_clause(db, _where_clause, bound_names);\n return stmt;\n}\n\n}\n\n}\ncql3: Fix quadratic behavior in update_statement::parsed_insert::prepare_internal()\/*\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\/*\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#include \"update_statement.hh\"\n#include \"unimplemented.hh\"\n\n#include \"cql3\/operation_impl.hh\"\n\nnamespace cql3 {\n\nnamespace statements {\n\nupdate_statement::update_statement(statement_type type, uint32_t bound_terms, schema_ptr s, std::unique_ptr attrs)\n : modification_statement{type, bound_terms, std::move(s), std::move(attrs)}\n{ }\n\nbool update_statement::require_full_clustering_key() const {\n return true;\n}\n\nvoid update_statement::add_update_for_key(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) {\n if (s->is_dense()) {\n if (!prefix || (prefix.size() == 1 && prefix.components().front().empty())) {\n throw exceptions::invalid_request_exception(sprint(\"Missing PRIMARY KEY part %s\", s->clustering_key_columns().begin()->name_as_text()));\n }\n\n \/\/ An empty name for the compact value is what we use to recognize the case where there is not column\n \/\/ outside the PK, see CreateStatement.\n if (s->compact_column().name().empty()) {\n \/\/ There is no column outside the PK. So no operation could have passed through validation\n assert(_column_operations.empty());\n constants::setter(s->compact_column(), make_shared(constants::value(bytes()))).execute(m, prefix, params);\n } else {\n \/\/ dense means we don't have a row marker, so don't accept to set only the PK. See CASSANDRA-5648.\n if (_column_operations.empty()) {\n throw exceptions::invalid_request_exception(sprint(\"Column %s is mandatory for this COMPACT STORAGE table\", s->compact_column().name_as_text()));\n }\n }\n } else {\n \/\/ If there are static columns, there also must be clustering columns, in which\n \/\/ case empty prefix can only refer to the static row.\n bool is_static_prefix = s->has_static_columns() && !prefix;\n if (type == statement_type::INSERT && !is_static_prefix) {\n auto& row = m.partition().clustered_row(clustering_key::from_clustering_prefix(*s, prefix));\n row.apply(row_marker(params.timestamp(), params.ttl(), params.expiry()));\n }\n }\n\n for (auto&& update : _column_operations) {\n update->execute(m, prefix, params);\n }\n\n warn(unimplemented::cause::INDEXES);\n#if 0\n SecondaryIndexManager indexManager = Keyspace.open(cfm.ksName).getColumnFamilyStore(cfm.cfId).indexManager;\n if (indexManager.hasIndexes())\n {\n for (Cell cell : cf)\n {\n \/\/ Indexed values must be validated by any applicable index. See CASSANDRA-3057\/4240\/8081 for more details\n if (!indexManager.validate(cell))\n throw new InvalidRequestException(String.format(\"Can't index column value of size %d for index %s on %s.%s\",\n cell.value().remaining(),\n cfm.getColumnDefinition(cell.name()).getIndexName(),\n cfm.ksName,\n cfm.cfName));\n }\n }\n }\n#endif\n}\n\nupdate_statement::parsed_insert::parsed_insert(::shared_ptr name,\n ::shared_ptr attrs,\n std::vector<::shared_ptr> column_names,\n std::vector<::shared_ptr> column_values,\n bool if_not_exists)\n : modification_statement::parsed{std::move(name), std::move(attrs), conditions_vector{}, if_not_exists, false}\n , _column_names{std::move(column_names)}\n , _column_values{std::move(column_values)}\n{ }\n\n::shared_ptr\nupdate_statement::parsed_insert::prepare_internal(database& db, schema_ptr schema,\n ::shared_ptr bound_names, std::unique_ptr attrs)\n{\n auto stmt = ::make_shared(statement_type::INSERT, bound_names->size(), schema, std::move(attrs));\n\n \/\/ Created from an INSERT\n if (stmt->is_counter()) {\n throw exceptions::invalid_request_exception(\"INSERT statement are not allowed on counter tables, use UPDATE instead\");\n }\n\n if (_column_names.size() != _column_values.size()) {\n throw exceptions::invalid_request_exception(\"Unmatched column names\/values\");\n }\n\n if (_column_names.empty()) {\n throw exceptions::invalid_request_exception(\"No columns provided to INSERT\");\n }\n\n std::unordered_set> column_ids;\n for (size_t i = 0; i < _column_names.size(); i++) {\n auto id = _column_names[i]->prepare_column_identifier(schema);\n auto def = get_column_definition(schema, *id);\n if (!def) {\n throw exceptions::invalid_request_exception(sprint(\"Unknown identifier %s\", *id));\n }\n if (column_ids.count(id)) {\n throw exceptions::invalid_request_exception(sprint(\"Multiple definitions found for column %s\", *id));\n }\n column_ids.emplace(id);\n\n auto&& value = _column_values[i];\n\n if (def->is_primary_key()) {\n auto t = value->prepare(db, keyspace(), def->column_specification);\n t->collect_marker_specification(bound_names);\n stmt->add_key_value(*def, std::move(t));\n } else {\n auto operation = operation::set_value(value).prepare(db, keyspace(), *def);\n operation->collect_marker_specification(bound_names);\n stmt->add_operation(std::move(operation));\n };\n }\n return stmt;\n}\n\nupdate_statement::parsed_update::parsed_update(::shared_ptr name,\n ::shared_ptr attrs,\n std::vector, ::shared_ptr>> updates,\n std::vector where_clause,\n conditions_vector conditions)\n : modification_statement::parsed(std::move(name), std::move(attrs), std::move(conditions), false, false)\n , _updates(std::move(updates))\n , _where_clause(std::move(where_clause))\n{ }\n\n::shared_ptr\nupdate_statement::parsed_update::prepare_internal(database& db, schema_ptr schema,\n ::shared_ptr bound_names, std::unique_ptr attrs)\n{\n auto stmt = ::make_shared(statement_type::UPDATE, bound_names->size(), schema, std::move(attrs));\n\n for (auto&& entry : _updates) {\n auto id = entry.first->prepare_column_identifier(schema);\n auto def = get_column_definition(schema, *id);\n if (!def) {\n throw exceptions::invalid_request_exception(sprint(\"Unknown identifier %s\", *entry.first));\n }\n\n auto operation = entry.second->prepare(db, keyspace(), *def);\n operation->collect_marker_specification(bound_names);\n\n if (def->is_primary_key()) {\n throw exceptions::invalid_request_exception(sprint(\"PRIMARY KEY part %s found in SET part\", *entry.first));\n }\n stmt->add_operation(std::move(operation));\n }\n\n stmt->process_where_clause(db, _where_clause, bound_names);\n return stmt;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef NO_ZLIB\n\n#include \"leveldb\/zlib_compressor.h\"\n\n#include \n#include \n\nnamespace leveldb {\n\n\tvoid ZlibCompressor::compressImpl(const char* input, size_t length, ::std::string& buffer) const\n\t{\n\t\tconst size_t BUFSIZE = 128 * 1024;\n\t\tunsigned char temp_buffer[BUFSIZE];\n\n\t\t\/\/reserve enough memory to not reallocate on the fly\n\t\tbuffer.reserve(compressBound(length));\n\n\t\tz_stream strm;\n\t\tstrm.zalloc = 0;\n\t\tstrm.zfree = 0;\n\t\tstrm.next_in = (unsigned char *)(input);\n\t\tstrm.avail_in = (uint32_t)length;\n\t\tstrm.next_out = temp_buffer;\n\t\tstrm.avail_out = BUFSIZE;\n\n\t\tdeflateInit(&strm, compressionLevel);\n\n\t\tint deflate_res = Z_OK;\n\t\twhile (strm.avail_in != 0)\n\t\t{\n\t\t\tint res = deflate(&strm, Z_NO_FLUSH);\n\t\t\tassert(res == Z_OK);\n\t\t\tif (strm.avail_out == 0)\n\t\t\t{\n\t\t\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);\n\t\t\t\tstrm.next_out = temp_buffer;\n\t\t\t\tstrm.avail_out = BUFSIZE;\n\t\t\t}\n\t\t}\n\n\t\twhile (deflate_res == Z_OK)\n\t\t{\n\t\t\tif (strm.avail_out == 0)\n\t\t\t{\n\t\t\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);\n\t\t\t\tstrm.next_out = temp_buffer;\n\t\t\t\tstrm.avail_out = BUFSIZE;\n\t\t\t}\n\t\t\tdeflate_res = deflate(&strm, Z_FINISH);\n\t\t}\n\n\t\tassert(deflate_res == Z_STREAM_END);\n\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out);\n\t\tdeflateEnd(&strm);\n\t}\n\n\tint _zlibInflate(const char* input, size_t length, ::std::string &output) {\n\t\tconst int CHUNK = 64 * 1024;\n\n\t\tint ret;\n\t\tsize_t have;\n\t\tz_stream strm;\n\t\tunsigned char out[CHUNK];\n\n\t\t\/* allocate inflate state *\/\n\t\tstrm.zalloc = Z_NULL;\n\t\tstrm.zfree = Z_NULL;\n\t\tstrm.opaque = Z_NULL;\n\t\tstrm.avail_in = (uint32_t)length;\n\t\tstrm.next_in = (Bytef*)input;\n\t\tret = inflateInit(&strm);\n\t\tif (ret != Z_OK)\n\t\t\treturn ret;\n\n\t\t\/* decompress until deflate stream ends or end of file *\/\n\t\tdo {\n\t\t\t\/* run inflate() on input until output buffer not full *\/\n\t\t\tdo {\n\n\t\t\t\tstrm.avail_out = CHUNK;\n\t\t\t\tstrm.next_out = out;\n\n\t\t\t\tret = inflate(&strm, Z_NO_FLUSH);\n\t\t\t\tassert(ret != Z_STREAM_ERROR); \/* state not clobbered *\/\n\t\t\t\tswitch (ret) {\n\t\t\t\tcase Z_NEED_DICT:\n\t\t\t\t\tret = Z_DATA_ERROR; \/* and fall through *\/\n\t\t\t\tcase Z_DATA_ERROR:\n\t\t\t\tcase Z_MEM_ERROR:\n\t\t\t\t\t(void)inflateEnd(&strm);\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\n\t\t\t\thave = CHUNK - strm.avail_out;\n\n\t\t\t\toutput.append((char*)out, have);\n\n\t\t\t} while (strm.avail_out == 0);\n\n\t\t\t\/* done when inflate() says it's done *\/\n\t\t} while (ret != Z_STREAM_END);\n\n\t\t\/* clean up and return *\/\n\t\t(void)inflateEnd(&strm);\n\t\treturn ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;\n\t}\n\n\tbool ZlibCompressor::decompress(const char* input, size_t length, ::std::string &output) const {\n\t\treturn _zlibInflate(input, length, output) == Z_OK;\n\t}\n\t\t\n}\n\n#endiffixed include inconsistency#ifndef NO_ZLIB\n\n#include \"leveldb\/zlib_compressor.h\"\n\n#include \n#include \n\nnamespace leveldb {\n\n\tvoid ZlibCompressor::compressImpl(const char* input, size_t length, ::std::string& buffer) const\n\t{\n\t\tconst size_t BUFSIZE = 128 * 1024;\n\t\tunsigned char temp_buffer[BUFSIZE];\n\n\t\t\/\/reserve enough memory to not reallocate on the fly\n\t\tbuffer.reserve(compressBound(length));\n\n\t\tz_stream strm;\n\t\tstrm.zalloc = 0;\n\t\tstrm.zfree = 0;\n\t\tstrm.next_in = (unsigned char *)(input);\n\t\tstrm.avail_in = (uint32_t)length;\n\t\tstrm.next_out = temp_buffer;\n\t\tstrm.avail_out = BUFSIZE;\n\n\t\tdeflateInit(&strm, compressionLevel);\n\n\t\tint deflate_res = Z_OK;\n\t\twhile (strm.avail_in != 0)\n\t\t{\n\t\t\tint res = deflate(&strm, Z_NO_FLUSH);\n\t\t\tassert(res == Z_OK);\n\t\t\tif (strm.avail_out == 0)\n\t\t\t{\n\t\t\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);\n\t\t\t\tstrm.next_out = temp_buffer;\n\t\t\t\tstrm.avail_out = BUFSIZE;\n\t\t\t}\n\t\t}\n\n\t\twhile (deflate_res == Z_OK)\n\t\t{\n\t\t\tif (strm.avail_out == 0)\n\t\t\t{\n\t\t\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE);\n\t\t\t\tstrm.next_out = temp_buffer;\n\t\t\t\tstrm.avail_out = BUFSIZE;\n\t\t\t}\n\t\t\tdeflate_res = deflate(&strm, Z_FINISH);\n\t\t}\n\n\t\tassert(deflate_res == Z_STREAM_END);\n\t\tbuffer.insert(buffer.end(), temp_buffer, temp_buffer + BUFSIZE - strm.avail_out);\n\t\tdeflateEnd(&strm);\n\t}\n\n\tint _zlibInflate(const char* input, size_t length, ::std::string &output) {\n\t\tconst int CHUNK = 64 * 1024;\n\n\t\tint ret;\n\t\tsize_t have;\n\t\tz_stream strm;\n\t\tunsigned char out[CHUNK];\n\n\t\t\/* allocate inflate state *\/\n\t\tstrm.zalloc = Z_NULL;\n\t\tstrm.zfree = Z_NULL;\n\t\tstrm.opaque = Z_NULL;\n\t\tstrm.avail_in = (uint32_t)length;\n\t\tstrm.next_in = (Bytef*)input;\n\t\tret = inflateInit(&strm);\n\t\tif (ret != Z_OK)\n\t\t\treturn ret;\n\n\t\t\/* decompress until deflate stream ends or end of file *\/\n\t\tdo {\n\t\t\t\/* run inflate() on input until output buffer not full *\/\n\t\t\tdo {\n\n\t\t\t\tstrm.avail_out = CHUNK;\n\t\t\t\tstrm.next_out = out;\n\n\t\t\t\tret = inflate(&strm, Z_NO_FLUSH);\n\t\t\t\tassert(ret != Z_STREAM_ERROR); \/* state not clobbered *\/\n\t\t\t\tswitch (ret) {\n\t\t\t\tcase Z_NEED_DICT:\n\t\t\t\t\tret = Z_DATA_ERROR; \/* and fall through *\/\n\t\t\t\tcase Z_DATA_ERROR:\n\t\t\t\tcase Z_MEM_ERROR:\n\t\t\t\t\t(void)inflateEnd(&strm);\n\t\t\t\t\treturn ret;\n\t\t\t\t}\n\n\t\t\t\thave = CHUNK - strm.avail_out;\n\n\t\t\t\toutput.append((char*)out, have);\n\n\t\t\t} while (strm.avail_out == 0);\n\n\t\t\t\/* done when inflate() says it's done *\/\n\t\t} while (ret != Z_STREAM_END);\n\n\t\t\/* clean up and return *\/\n\t\t(void)inflateEnd(&strm);\n\t\treturn ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;\n\t}\n\n\tbool ZlibCompressor::decompress(const char* input, size_t length, ::std::string &output) const {\n\t\treturn _zlibInflate(input, length, output) == Z_OK;\n\t}\n\t\t\n}\n\n#endif<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"Stroika\/Frameworks\/StroikaPreComp.h\"\n\n#include \n\n#include \"Stroika\/Foundation\/Characters\/FloatConversion.h\"\n#include \"Stroika\/Foundation\/Characters\/String2Int.h\"\n#include \"Stroika\/Foundation\/Characters\/String_Constant.h\"\n#include \"Stroika\/Foundation\/Characters\/ToString.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Exception.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Methods.h\"\n#include \"Stroika\/Foundation\/Streams\/TextReader.h\"\n\n#include \"Stroika\/Frameworks\/WebServer\/ConnectionManager.h\"\n#include \"Stroika\/Frameworks\/WebServer\/Router.h\"\n#include \"Stroika\/Frameworks\/WebService\/Server\/Basic.h\"\n#include \"Stroika\/Frameworks\/WebService\/Server\/VariantValue.h\"\n\n#include \"WebServer.h\"\n\n#include \"AppVersion.h\"\n\nusing namespace std;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::IO::Network;\nusing namespace Stroika::Foundation::IO::Network::HTTP;\nusing namespace Stroika::Frameworks::WebServer;\nusing namespace Stroika::Frameworks::WebService;\nusing namespace Stroika::Frameworks::WebService::Server;\nusing namespace Stroika::Frameworks::WebService::Server::VariantValue;\n\nusing Memory::BLOB;\n\nusing namespace StroikaSample::WebServices;\n\n\/*\n * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up\n * all the logic \/options for HTTP interface.\n *\n * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler)\n * and accesss them from the Route handler functions.\n *\/\nclass WebServer::Rep_ {\npublic:\n const Router kRouter_; \/\/ rules saying how to map urls to code\n shared_ptr fWSImpl_; \/\/ application logic actually handling webservices\n ConnectionManager fConnectionMgr_; \/\/ manage http connection objects, thread pool, etc\n\n static const WebServiceMethodDescription kVariables_;\n\n static const WebServiceMethodDescription kPlus_;\n static const WebServiceMethodDescription kMinus;\n static const WebServiceMethodDescription kTimes;\n static const WebServiceMethodDescription kDivide;\n\n Rep_ (uint16_t portNumber, const shared_ptr& wsImpl)\n : kRouter_{\n Sequence{\n Route{\n MethodsRegularExpressions::kOptions,\n RegularExpression::kAny,\n [] ([[maybe_unused]] Message* m) { Lambda_Arg_Unused_BWA (m); }},\n\n Route{L\"\"_RegEx, DefaultPage_},\n\n Route{MethodsRegularExpressions::kPost, L\"SetAppState\"_RegEx, SetAppState_},\n\n Route{MethodsRegularExpressions::kGet, L\"FRED\"_RegEx, [] (Request*, Response* response) {\n response->write (L\"FRED\");\n response->SetContentType (DataExchange::PredefinedInternetMediaType::kText);\n }},\n\n \/*\n * the 'variable' API demonstrates a typical REST style CRUD usage - where the 'arguments' mainly come from \n * the URL itself.\n *\/\n Route{MethodsRegularExpressions::kGet, L\"variables(\/?)\"_RegEx, [this] (Message* m) {\n WriteResponse (m->PeekResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET ()));\n }},\n Route{MethodsRegularExpressions::kGet, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n WriteResponse (m->PeekResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET (varName)));\n }},\n Route{MethodsRegularExpressions::kPostOrPut, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n optional number;\n \/\/ demo getting argument from the body\n if (not number) {\n \/\/ read if content-type is text (not json)\n if (m->PeekRequest ()->GetContentType () and m->PeekRequest ()->GetContentType ()->IsA (Stroika::Foundation::DataExchange::PredefinedInternetMediaType::Text_CT ())) {\n String argsAsString = Streams::TextReader::New (m->PeekRequest ()->GetBody ()).ReadAll ();\n number = kMapper.ToObject (DataExchange::VariantValue (argsAsString));\n }\n }\n \/\/ demo getting argument from the query argument\n if (not number) {\n static const String kValueParamName_ = L\"value\"sv;\n Mapping args = PickoutParamValuesFromURL (m->PeekRequest ());\n number = Model::kMapper.ToObject (args.LookupValue (kValueParamName_));\n }\n \/\/ demo getting either query arg, or url encoded arg\n if (not number) {\n static const String kValueParamName_ = L\"value\"sv;\n \/\/ NOTE - PickoutParamValues combines PickoutParamValuesFromURL, and PickoutParamValuesFromBody. You can use\n \/\/ Either one of those instead. PickoutParamValuesFromURL assumes you know the name of the parameter, and its\n \/\/ encoded in the query string. PickoutParamValuesFromBody assumes you have something equivilent you can parse ouf\n \/\/ of the body, either json encoded or form-encoded (as of 2.1d23, only json encoded supported)\n Mapping args = PickoutParamValues (m->PeekRequest ());\n number = Model::kMapper.ToObject (args.LookupValue (kValueParamName_));\n }\n if (not number) {\n Execution::Throw (ClientErrorException (L\"Expected argument to PUT\/POST variable\"sv));\n }\n fWSImpl_->Variables_SET (varName, *number);\n WriteResponse (m->PeekResponse (), kVariables_);\n }},\n Route{MethodsRegularExpressions::kDelete, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n fWSImpl_->Variables_DELETE (varName);\n WriteResponse (m->PeekResponse (), kVariables_);\n }},\n\n \/*\n * plus, minus, times, and divide, test-void-return all all demonstrate passing in variables through either the POST body, or query-arguments.\n *\/\n Route{L\"plus\"_RegEx, mkRequestHandler (kPlus_, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[=] (Number arg1, Number arg2) { return fWSImpl_->plus (arg1, arg2); }})},\n Route{L\"minus\"_RegEx, mkRequestHandler (kMinus, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[=] (Number arg1, Number arg2) { return fWSImpl_->minus (arg1, arg2); }})},\n Route{L\"times\"_RegEx, mkRequestHandler (kTimes, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[=] (Number arg1, Number arg2) { return fWSImpl_->times (arg1, arg2); }})},\n Route{L\"divide\"_RegEx, mkRequestHandler (kDivide, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[=] (Number arg1, Number arg2) { return fWSImpl_->divide (arg1, arg2); }})},\n Route{L\"test-void-return\"_RegEx, mkRequestHandler (WebServiceMethodDescription{}, Model::kMapper, Traversal::Iterable{L\"err-if-more-than-10\"}, function{[=] (double check) {\n if (check > 10) {\n Execution::Throw (Execution::Exception (L\"more than 10\"sv));\n } }})},\n\n }}\n , fWSImpl_{wsImpl}\n , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), kRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L\"Stroika-Sample-WebServices\/\"} + AppVersion::kVersion.AsMajorMinorString ()}}\n {\n \/\/ @todo - move this to some framework-specific regtests...\n using VariantValue = DataExchange::VariantValue;\n Sequence tmp = OrderParamValues (Iterable{L\"page\", L\"xxx\"}, PickoutParamValuesFromURL (URI{L\"http:\/\/www.sophist.com?page=5\"}));\n Assert (tmp.size () == 2);\n Assert (tmp[0] == 5);\n Assert (tmp[1] == nullptr);\n }\n \/\/ Can declare arguments as Request*,Response*\n static void DefaultPage_ (Request*, Response* response)\n {\n WriteDocsPage (\n response,\n Sequence{\n kVariables_,\n kPlus_,\n kMinus,\n kTimes,\n kDivide,\n\n },\n DocsOptions{L\"Stroika Sample WebService - Web Methods\"_k});\n }\n static void SetAppState_ (Message* message)\n {\n String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll ();\n message->PeekResponse ()->writeln (L\"

      Hi SetAppState (\" + argsAsString.As () + L\")<\/p><\/body><\/html>\");\n message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML);\n }\n};\n\n\/*\n * Documentation on WSAPIs\n *\/\nconst WebServiceMethodDescription WebServer::Rep_::kVariables_{\n L\"variables\"_k,\n Set{Methods::kGet, Methods::kPost, Methods::kDelete},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl http:\/\/localhost:8080\/variables -v --output -\",\n L\"curl http:\/\/localhost:8080\/variables\/x -v --output -\",\n L\"curl -X POST http:\/\/localhost:8080\/variables\/x -v --output -\",\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"value\\\": 3}' http:\/\/localhost:8080\/variables\/x --output -\",\n L\"curl -H \\\"Content-Type: text\/plain\\\" -X POST -d '3' http:\/\/localhost:8080\/variables\/x --output -\"},\n Sequence{L\"@todo - this is a rough draft (but functional). It could use alot of cleanup and review to see WHICH way I recommend using, and just provide the recommended ways in samples\"},\n};\n\nconst WebServiceMethodDescription WebServer::Rep_::kPlus_{\n L\"plus\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\": 3, \\\"arg2\\\": 5 }' http:\/\/localhost:8080\/plus --output -\",\n },\n Sequence{L\"add the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kMinus{\n L\"minus\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\": 4.5, \\\"arg2\\\": -3.23 }' http:\/\/localhost:8080\/minus --output -\",\n },\n Sequence{L\"subtract the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kTimes{\n L\"times\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + 4i\\\", \\\"arg2\\\": 3.2 }' http:\/\/localhost:8080\/times --output -\",\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + i\\\", \\\"arg2\\\": \\\"2 - i\\\" }' http:\/\/localhost:8080\/times --output -\",\n },\n Sequence{L\"multiply the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kDivide{\n L\"divide\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + i\\\", \\\"arg2\\\": 0 }' http:\/\/localhost:8080\/divide --output -\",\n },\n Sequence{L\"divide the two argument numbers\"},\n};\n\nWebServer::WebServer (uint16_t portNumber, const shared_ptr& wsImpl)\n : fRep_ (make_shared (portNumber, wsImpl))\n{\n}\nc++20 cleanup\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"Stroika\/Frameworks\/StroikaPreComp.h\"\n\n#include \n\n#include \"Stroika\/Foundation\/Characters\/FloatConversion.h\"\n#include \"Stroika\/Foundation\/Characters\/String2Int.h\"\n#include \"Stroika\/Foundation\/Characters\/String_Constant.h\"\n#include \"Stroika\/Foundation\/Characters\/ToString.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Exception.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n#include \"Stroika\/Foundation\/IO\/Network\/HTTP\/Methods.h\"\n#include \"Stroika\/Foundation\/Streams\/TextReader.h\"\n\n#include \"Stroika\/Frameworks\/WebServer\/ConnectionManager.h\"\n#include \"Stroika\/Frameworks\/WebServer\/Router.h\"\n#include \"Stroika\/Frameworks\/WebService\/Server\/Basic.h\"\n#include \"Stroika\/Frameworks\/WebService\/Server\/VariantValue.h\"\n\n#include \"WebServer.h\"\n\n#include \"AppVersion.h\"\n\nusing namespace std;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::IO::Network;\nusing namespace Stroika::Foundation::IO::Network::HTTP;\nusing namespace Stroika::Frameworks::WebServer;\nusing namespace Stroika::Frameworks::WebService;\nusing namespace Stroika::Frameworks::WebService::Server;\nusing namespace Stroika::Frameworks::WebService::Server::VariantValue;\n\nusing Memory::BLOB;\n\nusing namespace StroikaSample::WebServices;\n\n\/*\n * It's often helpful to structure together, routes, special interceptors, with your connection manager, to package up\n * all the logic \/options for HTTP interface.\n *\n * This particular organization also makes it easy to save instance variables with the webserver (like a pointer to a handler)\n * and accesss them from the Route handler functions.\n *\/\nclass WebServer::Rep_ {\npublic:\n const Router kRouter_; \/\/ rules saying how to map urls to code\n shared_ptr fWSImpl_; \/\/ application logic actually handling webservices\n ConnectionManager fConnectionMgr_; \/\/ manage http connection objects, thread pool, etc\n\n static const WebServiceMethodDescription kVariables_;\n\n static const WebServiceMethodDescription kPlus_;\n static const WebServiceMethodDescription kMinus;\n static const WebServiceMethodDescription kTimes;\n static const WebServiceMethodDescription kDivide;\n\n Rep_ (uint16_t portNumber, const shared_ptr& wsImpl)\n : kRouter_{\n Sequence{\n Route{\n MethodsRegularExpressions::kOptions,\n RegularExpression::kAny,\n [] ([[maybe_unused]] Message* m) { Lambda_Arg_Unused_BWA (m); }},\n\n Route{L\"\"_RegEx, DefaultPage_},\n\n Route{MethodsRegularExpressions::kPost, L\"SetAppState\"_RegEx, SetAppState_},\n\n Route{MethodsRegularExpressions::kGet, L\"FRED\"_RegEx, [] (Request*, Response* response) {\n response->write (L\"FRED\");\n response->SetContentType (DataExchange::PredefinedInternetMediaType::kText);\n }},\n\n \/*\n * the 'variable' API demonstrates a typical REST style CRUD usage - where the 'arguments' mainly come from \n * the URL itself.\n *\/\n Route{MethodsRegularExpressions::kGet, L\"variables(\/?)\"_RegEx, [this] (Message* m) {\n WriteResponse (m->PeekResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET ()));\n }},\n Route{MethodsRegularExpressions::kGet, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n WriteResponse (m->PeekResponse (), kVariables_, kMapper.FromObject (fWSImpl_->Variables_GET (varName)));\n }},\n Route{MethodsRegularExpressions::kPostOrPut, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n optional number;\n \/\/ demo getting argument from the body\n if (not number) {\n \/\/ read if content-type is text (not json)\n if (m->PeekRequest ()->GetContentType () and m->PeekRequest ()->GetContentType ()->IsA (Stroika::Foundation::DataExchange::PredefinedInternetMediaType::Text_CT ())) {\n String argsAsString = Streams::TextReader::New (m->PeekRequest ()->GetBody ()).ReadAll ();\n number = kMapper.ToObject (DataExchange::VariantValue (argsAsString));\n }\n }\n \/\/ demo getting argument from the query argument\n if (not number) {\n static const String kValueParamName_ = L\"value\"sv;\n Mapping args = PickoutParamValuesFromURL (m->PeekRequest ());\n number = Model::kMapper.ToObject (args.LookupValue (kValueParamName_));\n }\n \/\/ demo getting either query arg, or url encoded arg\n if (not number) {\n static const String kValueParamName_ = L\"value\"sv;\n \/\/ NOTE - PickoutParamValues combines PickoutParamValuesFromURL, and PickoutParamValuesFromBody. You can use\n \/\/ Either one of those instead. PickoutParamValuesFromURL assumes you know the name of the parameter, and its\n \/\/ encoded in the query string. PickoutParamValuesFromBody assumes you have something equivilent you can parse ouf\n \/\/ of the body, either json encoded or form-encoded (as of 2.1d23, only json encoded supported)\n Mapping args = PickoutParamValues (m->PeekRequest ());\n number = Model::kMapper.ToObject (args.LookupValue (kValueParamName_));\n }\n if (not number) {\n Execution::Throw (ClientErrorException (L\"Expected argument to PUT\/POST variable\"sv));\n }\n fWSImpl_->Variables_SET (varName, *number);\n WriteResponse (m->PeekResponse (), kVariables_);\n }},\n Route{MethodsRegularExpressions::kDelete, L\"variables\/(.+)\"_RegEx, [this] (Message* m, const String& varName) {\n fWSImpl_->Variables_DELETE (varName);\n WriteResponse (m->PeekResponse (), kVariables_);\n }},\n\n \/*\n * plus, minus, times, and divide, test-void-return all all demonstrate passing in variables through either the POST body, or query-arguments.\n *\/\n Route{L\"plus\"_RegEx, mkRequestHandler (kPlus_, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[this] (Number arg1, Number arg2) { return fWSImpl_->plus (arg1, arg2); }})},\n Route{L\"minus\"_RegEx, mkRequestHandler (kMinus, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[this] (Number arg1, Number arg2) { return fWSImpl_->minus (arg1, arg2); }})},\n Route{L\"times\"_RegEx, mkRequestHandler (kTimes, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[this] (Number arg1, Number arg2) { return fWSImpl_->times (arg1, arg2); }})},\n Route{L\"divide\"_RegEx, mkRequestHandler (kDivide, Model::kMapper, Traversal::Iterable{L\"arg1\", L\"arg2\"}, function{[this] (Number arg1, Number arg2) { return fWSImpl_->divide (arg1, arg2); }})},\n Route{L\"test-void-return\"_RegEx, mkRequestHandler (WebServiceMethodDescription{}, Model::kMapper, Traversal::Iterable{L\"err-if-more-than-10\"}, function{[] (double check) {\n if (check > 10) {\n Execution::Throw (Execution::Exception (L\"more than 10\"sv));\n } }})},\n\n }}\n , fWSImpl_{wsImpl}\n , fConnectionMgr_{SocketAddresses (InternetAddresses_Any (), portNumber), kRouter_, ConnectionManager::Options{{}, Socket::BindFlags{}, String{L\"Stroika-Sample-WebServices\/\"} + AppVersion::kVersion.AsMajorMinorString ()}}\n {\n \/\/ @todo - move this to some framework-specific regtests...\n using VariantValue = DataExchange::VariantValue;\n Sequence tmp = OrderParamValues (Iterable{L\"page\", L\"xxx\"}, PickoutParamValuesFromURL (URI{L\"http:\/\/www.sophist.com?page=5\"}));\n Assert (tmp.size () == 2);\n Assert (tmp[0] == 5);\n Assert (tmp[1] == nullptr);\n }\n \/\/ Can declare arguments as Request*,Response*\n static void DefaultPage_ (Request*, Response* response)\n {\n WriteDocsPage (\n response,\n Sequence{\n kVariables_,\n kPlus_,\n kMinus,\n kTimes,\n kDivide,\n\n },\n DocsOptions{L\"Stroika Sample WebService - Web Methods\"_k});\n }\n static void SetAppState_ (Message* message)\n {\n String argsAsString = Streams::TextReader::New (message->PeekRequest ()->GetBody ()).ReadAll ();\n message->PeekResponse ()->writeln (L\"

      Hi SetAppState (\" + argsAsString.As () + L\")<\/p><\/body><\/html>\");\n message->PeekResponse ()->SetContentType (DataExchange::PredefinedInternetMediaType::kText_HTML);\n }\n};\n\n\/*\n * Documentation on WSAPIs\n *\/\nconst WebServiceMethodDescription WebServer::Rep_::kVariables_{\n L\"variables\"_k,\n Set{Methods::kGet, Methods::kPost, Methods::kDelete},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl http:\/\/localhost:8080\/variables -v --output -\",\n L\"curl http:\/\/localhost:8080\/variables\/x -v --output -\",\n L\"curl -X POST http:\/\/localhost:8080\/variables\/x -v --output -\",\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"value\\\": 3}' http:\/\/localhost:8080\/variables\/x --output -\",\n L\"curl -H \\\"Content-Type: text\/plain\\\" -X POST -d '3' http:\/\/localhost:8080\/variables\/x --output -\"},\n Sequence{L\"@todo - this is a rough draft (but functional). It could use alot of cleanup and review to see WHICH way I recommend using, and just provide the recommended ways in samples\"},\n};\n\nconst WebServiceMethodDescription WebServer::Rep_::kPlus_{\n L\"plus\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\": 3, \\\"arg2\\\": 5 }' http:\/\/localhost:8080\/plus --output -\",\n },\n Sequence{L\"add the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kMinus{\n L\"minus\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\": 4.5, \\\"arg2\\\": -3.23 }' http:\/\/localhost:8080\/minus --output -\",\n },\n Sequence{L\"subtract the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kTimes{\n L\"times\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + 4i\\\", \\\"arg2\\\": 3.2 }' http:\/\/localhost:8080\/times --output -\",\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + i\\\", \\\"arg2\\\": \\\"2 - i\\\" }' http:\/\/localhost:8080\/times --output -\",\n },\n Sequence{L\"multiply the two argument numbers\"},\n};\nconst WebServiceMethodDescription WebServer::Rep_::kDivide{\n L\"divide\"_k,\n Set{String_Constant{Methods::kPost}},\n DataExchange::PredefinedInternetMediaType::kJSON,\n {},\n Sequence{\n L\"curl -H \\\"Content-Type: application\/json\\\" -X POST -d '{\\\"arg1\\\":\\\"2 + i\\\", \\\"arg2\\\": 0 }' http:\/\/localhost:8080\/divide --output -\",\n },\n Sequence{L\"divide the two argument numbers\"},\n};\n\nWebServer::WebServer (uint16_t portNumber, const shared_ptr& wsImpl)\n : fRep_ (make_shared (portNumber, wsImpl))\n{\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: SpellAttrib.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-09-17 14:12:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#pragma hdrstop\n\n#ifndef _SVX_SPELL_ATTRIB\n#include \n#endif\n#ifndef _SV_FONT_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_\n#include \n#endif\nusing namespace svx;\nusing namespace com::sun::star::linguistic2;\nusing namespace com::sun::star::uno;\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::SpellErrorAttrib(Reference xAlt) :\n TextAttrib(TEXTATTR_SPELL_ERROR),\n m_xAlternatives(xAlt)\n{\n}\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_ERROR),\n m_xAlternatives( rAttr.m_xAlternatives )\n{\n}\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::~SpellErrorAttrib()\n{\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellErrorAttrib::SetFont( Font& rFont ) const\n{\n \/\/this attribute doesn't have a visual effect\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellErrorAttrib::Clone() const\n{\n return new SpellErrorAttrib(*this);\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_xAlternatives.get() == static_cast(rAttr).m_xAlternatives.get();\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) :\n TextAttrib(TEXTATTR_SPELL_LANGUAGE),\n m_eLanguage(eLang)\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_LANGUAGE),\n m_eLanguage(rAttr.m_eLanguage)\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::~SpellLanguageAttrib()\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellLanguageAttrib::SetFont( Font& rFont ) const\n{\n \/\/no visual effect\n}\n\/*-- 10.09.2003 14:27:44---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellLanguageAttrib::Clone() const\n{\n return new SpellLanguageAttrib(*this);\n}\n\/*-- 10.09.2003 14:27:44---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_eLanguage == static_cast(rAttr).m_eLanguage;\n}\n\/*-- 31.10.2003 16:07:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) :\n TextAttrib(TEXTATTR_SPELL_BACKGROUND),\n m_aBackgroundColor(rCol)\n{\n}\n\/*-- 31.10.2003 16:07:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_BACKGROUND),\n m_aBackgroundColor(rAttr.m_aBackgroundColor)\n{\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::~SpellBackgroundAttrib()\n{\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellBackgroundAttrib::SetFont( Font& rFont ) const\n{\n rFont.SetFillColor(m_aBackgroundColor);\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellBackgroundAttrib::Clone() const\n{\n return new SpellBackgroundAttrib(*this);\n}\n\/*-- 31.10.2003 16:07:47---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_aBackgroundColor == static_cast(rAttr).m_aBackgroundColor;\n}\n\nINTEGRATION: CWS visibility01 (1.2.78); FILE MERGED 2004\/11\/01 20:17:11 mhu 1.2.78.1: #i35758# Undefine SVX_DLLIMPLEMENTATION for objects going into 'cui' library.\/*************************************************************************\n *\n * $RCSfile: SpellAttrib.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:25: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#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n#ifndef _SVX_SPELL_ATTRIB\n#include \n#endif\n#ifndef _SV_FONT_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XSPELLALTERNATIVES_HPP_\n#include \n#endif\nusing namespace svx;\nusing namespace com::sun::star::linguistic2;\nusing namespace com::sun::star::uno;\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::SpellErrorAttrib(Reference xAlt) :\n TextAttrib(TEXTATTR_SPELL_ERROR),\n m_xAlternatives(xAlt)\n{\n}\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::SpellErrorAttrib( const SpellErrorAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_ERROR),\n m_xAlternatives( rAttr.m_xAlternatives )\n{\n}\n\/*-- 10.09.2003 12:54:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellErrorAttrib::~SpellErrorAttrib()\n{\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellErrorAttrib::SetFont( Font& rFont ) const\n{\n \/\/this attribute doesn't have a visual effect\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellErrorAttrib::Clone() const\n{\n return new SpellErrorAttrib(*this);\n}\n\/*-- 10.09.2003 12:54:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellErrorAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_xAlternatives.get() == static_cast(rAttr).m_xAlternatives.get();\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::SpellLanguageAttrib(LanguageType eLang) :\n TextAttrib(TEXTATTR_SPELL_LANGUAGE),\n m_eLanguage(eLang)\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::SpellLanguageAttrib( const SpellLanguageAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_LANGUAGE),\n m_eLanguage(rAttr.m_eLanguage)\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellLanguageAttrib::~SpellLanguageAttrib()\n{\n}\n\/*-- 10.09.2003 14:27:43---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellLanguageAttrib::SetFont( Font& rFont ) const\n{\n \/\/no visual effect\n}\n\/*-- 10.09.2003 14:27:44---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellLanguageAttrib::Clone() const\n{\n return new SpellLanguageAttrib(*this);\n}\n\/*-- 10.09.2003 14:27:44---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellLanguageAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_eLanguage == static_cast(rAttr).m_eLanguage;\n}\n\/*-- 31.10.2003 16:07:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::SpellBackgroundAttrib(const Color& rCol) :\n TextAttrib(TEXTATTR_SPELL_BACKGROUND),\n m_aBackgroundColor(rCol)\n{\n}\n\/*-- 31.10.2003 16:07:45---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::SpellBackgroundAttrib( const SpellBackgroundAttrib& rAttr ) :\n TextAttrib(TEXTATTR_SPELL_BACKGROUND),\n m_aBackgroundColor(rAttr.m_aBackgroundColor)\n{\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSpellBackgroundAttrib::~SpellBackgroundAttrib()\n{\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SpellBackgroundAttrib::SetFont( Font& rFont ) const\n{\n rFont.SetFillColor(m_aBackgroundColor);\n}\n\/*-- 31.10.2003 16:07:46---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nTextAttrib* SpellBackgroundAttrib::Clone() const\n{\n return new SpellBackgroundAttrib(*this);\n}\n\/*-- 31.10.2003 16:07:47---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nint SpellBackgroundAttrib::operator==( const TextAttrib& rAttr ) const\n{\n return Which() == rAttr.Which() &&\n m_aBackgroundColor == static_cast(rAttr).m_aBackgroundColor;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cuihyperdlg.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 20:52:04 $\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#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _SV_SETTINGS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX\n#include \n#endif\n\n#include \"cuihyperdlg.hxx\"\n\n#include \"hlinettp.hxx\"\n#include \"hlmailtp.hxx\"\n#include \"hldoctp.hxx\"\n#include \"hldocntp.hxx\"\n\n#include \"hyperdlg.hrc\"\n\n\/\/########################################################################\n\/\/# #\n\/\/# Childwindow-Wrapper-Class #\n\/\/# #\n\/\/########################################################################\n\nSvxHlinkCtrl::SvxHlinkCtrl( USHORT nId, SfxBindings & rBindings, SvxHpLinkDlg* pDlg )\n: SfxControllerItem ( nId, rBindings ),\n aRdOnlyForwarder ( SID_READONLY_MODE, *this ),\n aOnlineForwarder ( SID_INTERNET_ONLINE , *this )\n{\n pParent = pDlg;\n}\n\nvoid SvxHlinkCtrl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n if ( eState == SFX_ITEM_AVAILABLE )\n {\n switch ( nSID )\n {\n case SID_INTERNET_ONLINE :\n {\n pParent->EnableInetBrowse( !( (SfxBoolItem*)pState)->GetValue() );\n }\n break;\n case SID_HYPERLINK_GETLINK :\n {\n pParent->SetPage ( (SvxHyperlinkItem*)pState);\n }\n break;\n case SID_READONLY_MODE :\n {\n pParent->SetReadOnlyMode( ( (SfxBoolItem*)pState)->GetValue() == TRUE );\n }\n break;\n }\n }\n}\n\n\n\n\/\/ -----------------------------------------------------------------------\n\n\n\n\/\/########################################################################\n\/\/# #\n\/\/# Hyperlink - Dialog #\n\/\/# #\n\/\/########################################################################\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHpLinkDlg::SvxHpLinkDlg (Window* pParent, SfxBindings* pBindings)\n: IconChoiceDialog( pParent, SVX_RES ( RID_SVXDLG_NEWHYPERLINK ) ),\n maCtrl ( SID_HYPERLINK_GETLINK, *pBindings, this ),\n mpBindings ( pBindings ),\n mbIsHTMLDoc ( sal_False ),\n mbReadOnly ( sal_False )\n{\n mbGrabFocus = sal_True;\n \/\/ insert pages\n Image aImage;\n Image aImageHC;\n String aStrTitle;\n SvxIconChoiceCtrlEntry* pEntry = NULL;\n\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLINETTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLINETTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_INTERNET, aStrTitle, aImage, aImageHC, SvxHyperlinkInternetTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLMAILTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLMAILTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_MAIL, aStrTitle, aImage, aImageHC, SvxHyperlinkMailTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_DOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkDocTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_NEWDOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkNewDocTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP_HELP ) );\n\n \/\/ all tab pages set -> create mnemonics\n \/\/ CreateIconTextAutoMnemonics(); #99671# not useful, because this is not what user expects when using mnemonics on the pages\n\n \/\/ create itemset for tabpages\n mpItemSet = new SfxItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,\n SID_HYPERLINK_SETLINK );\n\n SvxHyperlinkItem aItem;\n mpItemSet->Put (aItem, SID_HYPERLINK_GETLINK);\n\n SetInputSet (mpItemSet);\n\n \/\/ Init Dialog\n Start (FALSE);\n\n pBindings->Update( SID_READONLY_MODE );\n\n \/\/ set OK\/Cancel - button\n GetOKButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_APPLYBUT) );\n GetCancelButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_CLOSEBUT) );\n\n GetOKButton().SetClickHdl ( LINK ( this, SvxHpLinkDlg, ClickApplyHdl_Impl ) );\n GetCancelButton().SetClickHdl( LINK ( this, SvxHpLinkDlg, ClickCloseHdl_Impl ) );\n}\n\nSvxHpLinkDlg::~SvxHpLinkDlg ()\n{\n \/\/ delete config item, so the base class (IconChoiceDialog) can not load it on the next start\n SvtViewOptions aViewOpt( E_TABDIALOG, String::CreateFromInt32( SID_HYPERLINK_DIALOG ) );\n aViewOpt.Delete();\n\n delete mpItemSet;\n}\n\n\/*************************************************************************\n|*\n|* Close Dialog-Window\n|*\n|************************************************************************\/\n\nBOOL SvxHpLinkDlg::Close()\n{\n GetDispatcher()->Execute( SID_HYPERLINK_DIALOG,\n SFX_CALLMODE_ASYNCHRON |\n SFX_CALLMODE_RECORD);\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* When extrawindow is visible and its never moved by user, then move that\n|* window, too.\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::Move()\n{\n SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )\n GetTabPage ( GetCurPageId() );\n\n if( pCurrentPage->IsMarkWndVisible () )\n {\n \/\/ Pos&Size of this dialog-window\n Point aDlgPos ( GetPosPixel () );\n Size aDlgSize ( GetSizePixel () );\n\n \/\/ Size of Office-Main-Window\n Size aWindowSize( SFX_APP()->GetTopWindow()->GetSizePixel() );\n\n \/\/ Size of Extrawindow\n Size aExtraWndSize( pCurrentPage->GetSizeExtraWnd() );\n\n BOOL bDoInvalid ;\n if( aDlgPos.X()+(1.02*aDlgSize.Width())+aExtraWndSize.Width() > aWindowSize.Width() )\n {\n if( aDlgPos.X() - ( 0.02*aDlgSize.Width() ) - aExtraWndSize.Width() < 0 )\n {\n \/\/ Pos Extrawindow anywhere\n bDoInvalid = pCurrentPage->MoveToExtraWnd( Point( 1, long(1.1*aDlgPos.Y()) ), TRUE );\n }\n else\n {\n \/\/ Pos Extrawindow on the left side of Dialog\n bDoInvalid = pCurrentPage->MoveToExtraWnd( aDlgPos -\n Point( long(0.02*aDlgSize.Width()), 0 ) -\n Point( aExtraWndSize.Width(), 0 ) );\n }\n }\n else\n {\n \/\/ Pos Extrawindow on the right side of Dialog\n bDoInvalid = pCurrentPage->MoveToExtraWnd ( aDlgPos + Point( long(1.02*aDlgSize.Width()), 0 ) );\n }\n\n if ( bDoInvalid )\n Invalidate(INVALIDATE_BACKGROUND);\n }\n\n Window::Move();\n}\n\n\/*long SvxHpLinkDlg::PreNotify( NotifyEvent& rNEvt )\n{\n long nRet = 0;\n\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n DBG_ASSERT( rNEvt.GetKeyEvent(), \"-SvxHpLinkDlg::PreNotify(): no KeyEvent for key event?!\" );\n\n const KeyEvent* pKEvt = rNEvt.GetKeyEvent();\n\n if( KEY_MOD2 == pKEvt->GetKeyCode().GetModifier() && pKEvt->GetCharCode() && HandleShortCutKey( *pKEvt ) )\n nRet = 1;\n }\n\n if( !nRet )\n nRet = IconChoiceDialog::PreNotify( rNEvt );\n\n return nRet;\n}*\/\n\n\/*************************************************************************\n|*\n|* Click on Apply-button\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHpLinkDlg, ClickApplyHdl_Impl, void *, EMPTYARG )\n{\n SfxItemSet aItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,\n SID_HYPERLINK_SETLINK );\n\n SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)\n GetTabPage ( GetCurPageId() );\n\n if ( pCurrentPage->AskApply() )\n {\n pCurrentPage->FillItemSet( aItemSet );\n\n SvxHyperlinkItem *aItem = (SvxHyperlinkItem *)\n aItemSet.GetItem (SID_HYPERLINK_SETLINK);\n\n String aStrEmpty;\n if ( aItem->GetURL() != aStrEmpty )\n GetDispatcher()->Execute( SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON |\n SFX_CALLMODE_RECORD, aItem, 0L);\n\n ( (SvxHyperlinkTabPageBase*)GetTabPage ( GetCurPageId() ) )->DoApply();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on Close-button\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHpLinkDlg, ClickCloseHdl_Impl, void *, EMPTYARG )\n{\n Close();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Set Page\n|*\n|************************************************************************\/\n\nUSHORT SvxHpLinkDlg::SetPage ( SvxHyperlinkItem* pItem )\n{\n USHORT nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;\n\n String aStrURL ( pItem->GetURL() );\n INetURLObject aURL ( aStrURL );\n INetProtocol eProtocolTyp = aURL.GetProtocol();\n\n switch ( eProtocolTyp )\n {\n case INET_PROT_HTTP :\n case INET_PROT_FTP :\n case INET_PROT_TELNET :\n nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;\n break;\n case INET_PROT_FILE :\n case INET_PROT_POP3 :\n case INET_PROT_IMAP :\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n break;\n case INET_PROT_MAILTO :\n case INET_PROT_NEWS :\n nPageId = RID_SVXPAGE_HYPERLINK_MAIL;\n break;\n default :\n sal_Char const sNewsSrvScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\n\n if ( aStrURL.SearchAscii( sNewsSrvScheme ) == 0 )\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n else\n {\n sal_Char const sHash[] = \"#\";\n if( aStrURL.SearchAscii( sHash ) == 0 )\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n else\n {\n eProtocolTyp = INET_PROT_NOT_VALID;\n nPageId = GetCurPageId();\n }\n }\n break;\n }\n\n ShowPage (nPageId);\n\n SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)GetTabPage( nPageId );\n\n mbIsHTMLDoc = BOOL( pItem->GetInsertMode() & HLINK_HTMLMODE );\n\n SfxItemSet& aPageSet = (SfxItemSet&)GetTabPage (nPageId)->GetItemSet ();\n aPageSet.Put ( *pItem );\n\n pCurrentPage->Reset( aPageSet );\n if ( mbGrabFocus )\n {\n pCurrentPage->SetInitFocus(); \/\/ #92535# grab the focus only once at initialization\n mbGrabFocus = sal_False;\n }\n return nPageId;\n}\n\n\/*************************************************************************\n|*\n|* Enable\/Disable to browse targets in a html-doc\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::EnableInetBrowse( sal_Bool bEnable )\n{\n SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )\n GetTabPage ( GetCurPageId() );\n pCurrentPage->SetOnlineMode( bEnable );\n}\n\n\/*************************************************************************\n|*\n|* Enable\/Disable ReadOnly mode\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::SetReadOnlyMode( sal_Bool bRdOnly )\n{\n mbReadOnly = bRdOnly;\n if ( bRdOnly )\n GetOKButton().Disable();\n else\n GetOKButton().Enable();\n}\n\nINTEGRATION: CWS warnings01 (1.4.222); FILE MERGED 2006\/05\/04 14:46:50 os 1.4.222.1: warnings removed\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cuihyperdlg.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 15:04:47 $\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#ifdef SVX_DLLIMPLEMENTATION\n#undef SVX_DLLIMPLEMENTATION\n#endif\n\n\/\/ include ---------------------------------------------------------------\n\n#ifndef _SV_SETTINGS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX\n#include \n#endif\n\n#include \"cuihyperdlg.hxx\"\n\n#include \"hlinettp.hxx\"\n#include \"hlmailtp.hxx\"\n#include \"hldoctp.hxx\"\n#include \"hldocntp.hxx\"\n\n#include \"hyperdlg.hrc\"\n\n\/\/########################################################################\n\/\/# #\n\/\/# Childwindow-Wrapper-Class #\n\/\/# #\n\/\/########################################################################\n\nSvxHlinkCtrl::SvxHlinkCtrl( USHORT _nId, SfxBindings & rBindings, SvxHpLinkDlg* pDlg )\n: SfxControllerItem ( _nId, rBindings )\n ,aOnlineForwarder ( SID_INTERNET_ONLINE , *this )\n ,aRdOnlyForwarder ( SID_READONLY_MODE, *this )\n{\n pParent = pDlg;\n}\n\nvoid SvxHlinkCtrl::StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState )\n{\n if ( eState == SFX_ITEM_AVAILABLE )\n {\n switch ( nSID )\n {\n case SID_INTERNET_ONLINE :\n {\n pParent->EnableInetBrowse( !( (SfxBoolItem*)pState)->GetValue() );\n }\n break;\n case SID_HYPERLINK_GETLINK :\n {\n pParent->SetPage ( (SvxHyperlinkItem*)pState);\n }\n break;\n case SID_READONLY_MODE :\n {\n pParent->SetReadOnlyMode( ( (SfxBoolItem*)pState)->GetValue() == TRUE );\n }\n break;\n }\n }\n}\n\n\n\n\/\/ -----------------------------------------------------------------------\n\n\n\n\/\/########################################################################\n\/\/# #\n\/\/# Hyperlink - Dialog #\n\/\/# #\n\/\/########################################################################\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHpLinkDlg::SvxHpLinkDlg (Window* pParent, SfxBindings* pBindings)\n: IconChoiceDialog( pParent, SVX_RES ( RID_SVXDLG_NEWHYPERLINK ) ),\n maCtrl ( SID_HYPERLINK_GETLINK, *pBindings, this ),\n mpBindings ( pBindings ),\n mbReadOnly ( sal_False ),\n mbIsHTMLDoc ( sal_False )\n{\n mbGrabFocus = sal_True;\n \/\/ insert pages\n Image aImage;\n Image aImageHC;\n String aStrTitle;\n SvxIconChoiceCtrlEntry* pEntry = NULL;\n\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLINETTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLINETTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_INTERNET, aStrTitle, aImage, aImageHC, SvxHyperlinkInternetTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLINETTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLMAILTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLMAILTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_MAIL, aStrTitle, aImage, aImageHC, SvxHyperlinkMailTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLMAILTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_DOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkDocTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCTP_HELP ) );\n aStrTitle = SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP );\n aImage = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP ) );\n aImageHC = Image( SVX_RES ( RID_SVXBMP_HLDOCNTP_H ) );\n pEntry = AddTabPage ( RID_SVXPAGE_HYPERLINK_NEWDOCUMENT, aStrTitle, aImage, aImageHC, SvxHyperlinkNewDocTp::Create );\n pEntry->SetQuickHelpText( SVX_RESSTR( RID_SVXSTR_HYPERDLG_HLDOCNTP_HELP ) );\n\n \/\/ all tab pages set -> create mnemonics\n \/\/ CreateIconTextAutoMnemonics(); #99671# not useful, because this is not what user expects when using mnemonics on the pages\n\n \/\/ create itemset for tabpages\n mpItemSet = new SfxItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,\n SID_HYPERLINK_SETLINK );\n\n SvxHyperlinkItem aItem;\n mpItemSet->Put (aItem, SID_HYPERLINK_GETLINK);\n\n SetInputSet (mpItemSet);\n\n \/\/ Init Dialog\n Start (FALSE);\n\n pBindings->Update( SID_READONLY_MODE );\n\n \/\/ set OK\/Cancel - button\n GetOKButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_APPLYBUT) );\n GetCancelButton().SetText ( SVX_RESSTR(RID_SVXSTR_HYPDLG_CLOSEBUT) );\n\n GetOKButton().SetClickHdl ( LINK ( this, SvxHpLinkDlg, ClickApplyHdl_Impl ) );\n GetCancelButton().SetClickHdl( LINK ( this, SvxHpLinkDlg, ClickCloseHdl_Impl ) );\n}\n\nSvxHpLinkDlg::~SvxHpLinkDlg ()\n{\n \/\/ delete config item, so the base class (IconChoiceDialog) can not load it on the next start\n SvtViewOptions aViewOpt( E_TABDIALOG, String::CreateFromInt32( SID_HYPERLINK_DIALOG ) );\n aViewOpt.Delete();\n\n delete mpItemSet;\n}\n\n\/*************************************************************************\n|*\n|* Close Dialog-Window\n|*\n|************************************************************************\/\n\nBOOL SvxHpLinkDlg::Close()\n{\n GetDispatcher()->Execute( SID_HYPERLINK_DIALOG,\n SFX_CALLMODE_ASYNCHRON |\n SFX_CALLMODE_RECORD);\n return TRUE;\n}\n\n\/*************************************************************************\n|*\n|* When extrawindow is visible and its never moved by user, then move that\n|* window, too.\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::Move()\n{\n SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )\n GetTabPage ( GetCurPageId() );\n\n if( pCurrentPage->IsMarkWndVisible () )\n {\n \/\/ Pos&Size of this dialog-window\n Point aDlgPos ( GetPosPixel () );\n Size aDlgSize ( GetSizePixel () );\n\n \/\/ Size of Office-Main-Window\n Size aWindowSize( SFX_APP()->GetTopWindow()->GetSizePixel() );\n\n \/\/ Size of Extrawindow\n Size aExtraWndSize( pCurrentPage->GetSizeExtraWnd() );\n\n BOOL bDoInvalid ;\n if( aDlgPos.X()+(1.02*aDlgSize.Width())+aExtraWndSize.Width() > aWindowSize.Width() )\n {\n if( aDlgPos.X() - ( 0.02*aDlgSize.Width() ) - aExtraWndSize.Width() < 0 )\n {\n \/\/ Pos Extrawindow anywhere\n bDoInvalid = pCurrentPage->MoveToExtraWnd( Point( 1, long(1.1*aDlgPos.Y()) ), TRUE );\n }\n else\n {\n \/\/ Pos Extrawindow on the left side of Dialog\n bDoInvalid = pCurrentPage->MoveToExtraWnd( aDlgPos -\n Point( long(0.02*aDlgSize.Width()), 0 ) -\n Point( aExtraWndSize.Width(), 0 ) );\n }\n }\n else\n {\n \/\/ Pos Extrawindow on the right side of Dialog\n bDoInvalid = pCurrentPage->MoveToExtraWnd ( aDlgPos + Point( long(1.02*aDlgSize.Width()), 0 ) );\n }\n\n if ( bDoInvalid )\n Invalidate(INVALIDATE_BACKGROUND);\n }\n\n Window::Move();\n}\n\n\/*long SvxHpLinkDlg::PreNotify( NotifyEvent& rNEvt )\n{\n long nRet = 0;\n\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n DBG_ASSERT( rNEvt.GetKeyEvent(), \"-SvxHpLinkDlg::PreNotify(): no KeyEvent for key event?!\" );\n\n const KeyEvent* pKEvt = rNEvt.GetKeyEvent();\n\n if( KEY_MOD2 == pKEvt->GetKeyCode().GetModifier() && pKEvt->GetCharCode() && HandleShortCutKey( *pKEvt ) )\n nRet = 1;\n }\n\n if( !nRet )\n nRet = IconChoiceDialog::PreNotify( rNEvt );\n\n return nRet;\n}*\/\n\n\/*************************************************************************\n|*\n|* Click on Apply-button\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHpLinkDlg, ClickApplyHdl_Impl, void *, EMPTYARG )\n{\n SfxItemSet aItemSet( SFX_APP()->GetPool(), SID_HYPERLINK_GETLINK,\n SID_HYPERLINK_SETLINK );\n\n SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)\n GetTabPage ( GetCurPageId() );\n\n if ( pCurrentPage->AskApply() )\n {\n pCurrentPage->FillItemSet( aItemSet );\n\n SvxHyperlinkItem *aItem = (SvxHyperlinkItem *)\n aItemSet.GetItem (SID_HYPERLINK_SETLINK);\n\n String aStrEmpty;\n if ( aItem->GetURL() != aStrEmpty )\n GetDispatcher()->Execute( SID_HYPERLINK_SETLINK, SFX_CALLMODE_ASYNCHRON |\n SFX_CALLMODE_RECORD, aItem, 0L);\n\n ( (SvxHyperlinkTabPageBase*)GetTabPage ( GetCurPageId() ) )->DoApply();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on Close-button\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHpLinkDlg, ClickCloseHdl_Impl, void *, EMPTYARG )\n{\n Close();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Set Page\n|*\n|************************************************************************\/\n\nUSHORT SvxHpLinkDlg::SetPage ( SvxHyperlinkItem* pItem )\n{\n USHORT nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;\n\n String aStrURL ( pItem->GetURL() );\n INetURLObject aURL ( aStrURL );\n INetProtocol eProtocolTyp = aURL.GetProtocol();\n\n switch ( eProtocolTyp )\n {\n case INET_PROT_HTTP :\n case INET_PROT_FTP :\n case INET_PROT_TELNET :\n nPageId = RID_SVXPAGE_HYPERLINK_INTERNET;\n break;\n case INET_PROT_FILE :\n case INET_PROT_POP3 :\n case INET_PROT_IMAP :\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n break;\n case INET_PROT_MAILTO :\n case INET_PROT_NEWS :\n nPageId = RID_SVXPAGE_HYPERLINK_MAIL;\n break;\n default :\n sal_Char const sNewsSrvScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\n\n if ( aStrURL.SearchAscii( sNewsSrvScheme ) == 0 )\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n else\n {\n sal_Char const sHash[] = \"#\";\n if( aStrURL.SearchAscii( sHash ) == 0 )\n nPageId = RID_SVXPAGE_HYPERLINK_DOCUMENT;\n else\n {\n eProtocolTyp = INET_PROT_NOT_VALID;\n nPageId = GetCurPageId();\n }\n }\n break;\n }\n\n ShowPage (nPageId);\n\n SvxHyperlinkTabPageBase* pCurrentPage = (SvxHyperlinkTabPageBase*)GetTabPage( nPageId );\n\n mbIsHTMLDoc = BOOL( pItem->GetInsertMode() & HLINK_HTMLMODE );\n\n SfxItemSet& aPageSet = (SfxItemSet&)GetTabPage (nPageId)->GetItemSet ();\n aPageSet.Put ( *pItem );\n\n pCurrentPage->Reset( aPageSet );\n if ( mbGrabFocus )\n {\n pCurrentPage->SetInitFocus(); \/\/ #92535# grab the focus only once at initialization\n mbGrabFocus = sal_False;\n }\n return nPageId;\n}\n\n\/*************************************************************************\n|*\n|* Enable\/Disable to browse targets in a html-doc\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::EnableInetBrowse( sal_Bool bEnable )\n{\n SvxHyperlinkTabPageBase* pCurrentPage = ( SvxHyperlinkTabPageBase* )\n GetTabPage ( GetCurPageId() );\n pCurrentPage->SetOnlineMode( bEnable );\n}\n\n\/*************************************************************************\n|*\n|* Enable\/Disable ReadOnly mode\n|*\n|************************************************************************\/\n\nvoid SvxHpLinkDlg::SetReadOnlyMode( sal_Bool bRdOnly )\n{\n mbReadOnly = bRdOnly;\n if ( bRdOnly )\n GetOKButton().Disable();\n else\n GetOKButton().Enable();\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: checkit.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 13:41:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _CHECKIT_HXX\n#include \n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace drafts::com::sun::star::i18n;\n\nSwCheckIt::SwCheckIt()\n{\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n Reference < XInterface > xI = xMSF->createInstance(\n ::rtl::OUString::createFromAscii( \"com.sun.star.i18n.InputSequenceChecker\" ) );\n if ( xI.is() )\n {\n Any x = xI->queryInterface( ::getCppuType((const Reference< XInputSequenceChecker >*)0) );\n x >>= xCheck;\n }\n}\n\nINTEGRATION: CWS i18napi (1.1.166); FILE MERGED 2003\/04\/19 20:27:00 er 1.1.166.1: #107686# move drafts.com.sun.star.i18n to com.sun.star.i18n\/*************************************************************************\n *\n * $RCSfile: checkit.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-24 10:53:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _CHECKIT_HXX\n#include \n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::i18n;\n\nSwCheckIt::SwCheckIt()\n{\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n Reference < XInterface > xI = xMSF->createInstance(\n ::rtl::OUString::createFromAscii( \"com.sun.star.i18n.InputSequenceChecker\" ) );\n if ( xI.is() )\n {\n Any x = xI->queryInterface( ::getCppuType((const Reference< XInputSequenceChecker >*)0) );\n x >>= xCheck;\n }\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX\n#define INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX\n\n#include \n#include \n#include \n\nclass SwDoc;\nclass SwFrm;\nclass SwLayoutFrm;\nclass SwPageFrm;\nclass SwFlyFrm;\nclass SwSectionFrm;\nclass SwSectionNode;\nclass SvStream;\n\n\/*************************************************************************\n * class SwLayCacheImpl\n * contains the page break information and the text frame positions\n * of the document (after loading)\n * and is used inside the constructor of the layout rootframe to\n * insert content and text frames at the right pages.\n * For every page of the main text (body content, no footnotes, text frames etc.)\n * we have the nodeindex of the first content at the page,\n * the type of content ( table or paragraph )\n * and if it's not the first part of the table\/paragraph,\n * the row\/character-offset inside the table\/paragraph.\n * The text frame positions are stored in the SwPageFlyCache array.\n *************************************************************************\/\n\nclass SwFlyCache;\ntypedef boost::ptr_vector SwPageFlyCache;\n\nclass SwLayCacheImpl : public std::vector\n{\n std::deque aOffset;\n std::vector aType;\n SwPageFlyCache aFlyCache;\n bool bUseFlyCache;\n void Insert( sal_uInt16 nType, sal_uLong nIndex, sal_Int32 nOffset );\n\npublic:\n SwLayCacheImpl() {}\n bool Read( SvStream& rStream );\n\n sal_uLong GetBreakIndex( sal_uInt16 nIdx ) const { return std::vector::operator[]( nIdx ); }\n sal_Int32 GetBreakOfst( size_t nIdx ) const { return aOffset[ nIdx ]; }\n sal_uInt16 GetBreakType( sal_uInt16 nIdx ) const { return aType[ nIdx ]; }\n\n sal_uInt16 GetFlyCount() const { return aFlyCache.size(); }\n SwFlyCache *GetFlyCache( sal_uInt16 nIdx ) { return &aFlyCache[ nIdx ]; }\n\n bool IsUseFlyCache() const { return bUseFlyCache; }\n};\n\n\/*************************************************************************\n * class SwActualSection\n * helps to create the sectionframes during the _InsertCnt-function\n * by controlling nested sections.\n *************************************************************************\/\n\nclass SwActualSection\n{\n SwActualSection *pUpper;\n SwSectionFrm *pSectFrm;\n SwSectionNode *pSectNode;\npublic:\n SwActualSection( SwActualSection *pUpper,\n SwSectionFrm *pSect,\n SwSectionNode *pNd );\n\n SwSectionFrm *GetSectionFrm() { return pSectFrm; }\n void SetSectionFrm( SwSectionFrm *p ) { pSectFrm = p; }\n SwSectionNode *GetSectionNode() { return pSectNode;}\n SwActualSection *GetUpper() { return pUpper; }\n};\n\n\/*************************************************************************\n * class SwLayHelper\n * helps during the _InsertCnt-function to create new pages.\n * If there's a layoutcache available, this information is used.\n *************************************************************************\/\n\nclass SwLayHelper\n{\n SwFrm* &rpFrm;\n SwFrm* &rpPrv;\n SwPageFrm* &rpPage;\n SwLayoutFrm* &rpLay;\n SwActualSection* &rpActualSection;\n sal_Bool &rbBreakAfter;\n SwDoc* pDoc;\n SwLayCacheImpl* pImpl;\n sal_uLong nMaxParaPerPage;\n sal_uLong nParagraphCnt;\n sal_uLong nStartOfContent;\n sal_uInt16 nIndex; \/\/ the index in the page break array\n sal_uInt16 nFlyIdx; \/\/ the index in the fly cache array\n bool bFirst : 1;\n void _CheckFlyCache( SwPageFrm* pPage );\npublic:\n SwLayHelper( SwDoc *pD, SwFrm* &rpF, SwFrm* &rpP, SwPageFrm* &rpPg,\n SwLayoutFrm* &rpL, SwActualSection* &rpA, sal_Bool &rBrk,\n sal_uLong nNodeIndex, bool bCache );\n ~SwLayHelper();\n sal_uLong CalcPageCount();\n bool CheckInsert( sal_uLong nNodeIndex );\n\n bool CheckInsertPage();\n\n \/\/ Look for fresh text frames at this (new) page and set them to the right\n \/\/ position, if they are in the fly cache.\n void CheckFlyCache( SwPageFrm* pPage )\n { if( pImpl && nFlyIdx < pImpl->GetFlyCount() ) _CheckFlyCache( pPage ); }\n\n \/\/ Look for this text frame and set it to the right position,\n \/\/ if it's in the fly cache.\n static bool CheckPageFlyCache( SwPageFrm* &rpPage, SwFlyFrm* pFly );\n};\n\n\/*************************************************************************\n * class SwLayCacheIoImpl\n * contains the data structures that are required to read and write a\n * layout cache.\n *************************************************************************\/\n\n#define SW_LAYCACHE_IO_REC_PAGES 'p'\n#define SW_LAYCACHE_IO_REC_PARA 'P'\n#define SW_LAYCACHE_IO_REC_TABLE 'T'\n#define SW_LAYCACHE_IO_REC_FLY 'F'\n\n#define SW_LAYCACHE_IO_VERSION_MAJOR 1\n#define SW_LAYCACHE_IO_VERSION_MINOR 1\n\nclass SwLayCacheIoImpl\n{\nprivate:\n struct RecTypeSize {\n sal_uInt8 type;\n sal_uLong size;\n RecTypeSize(sal_uInt8 typ, sal_uLong siz) : type(typ), size(siz) {}\n };\n std::vector aRecords;\n\n SvStream *pStream;\n\n sal_uLong nFlagRecEnd;\n\n sal_uInt16 nMajorVersion;\n sal_uInt16 nMinorVersion;\n\n bool bWriteMode : 1;\n bool bError : 1;\n\npublic:\n SwLayCacheIoImpl( SvStream& rStrm, bool bWrtMd );\n\n \/\/ Get input or output stream\n SvStream& GetStream() const { return *pStream; }\n\n \/\/ Open a record of type \"nType\"\n bool OpenRec( sal_uInt8 nType );\n\n \/\/ Close a record of type \"nType\". This skips any unread data that\n \/\/ remains in the record.\n bool CloseRec( sal_uInt8 nType );\n\n \/\/ Return the number of bytes contained in the current record that\n \/\/ haven't been read by now.\n sal_uInt32 BytesLeft();\n\n \/\/ Return the current record's type\n sal_uInt8 Peek();\n\n \/\/ Skip the current record\n void SkipRec();\n\n \/\/ Open a flag record for reading. The uppermost four bits are flags,\n \/\/ while the lowermost are the flag record's size. Flag records cannot\n \/\/ be nested.\n sal_uInt8 OpenFlagRec();\n\n \/\/ Open flag record for writing;\n void OpenFlagRec( sal_uInt8 nFlags, sal_uInt8 nLen );\n\n \/\/ Close a flag record. Any bytes left are skipped.\n void CloseFlagRec();\n\n bool HasError() const { return bError; }\n\n sal_uInt16 GetMajorVersion() const { return nMajorVersion; }\n sal_uInt16 GetMinorVersion() const { return nMinorVersion; }\n};\n\n\/\/ Stored information about text frames:\nclass SwFlyCache : public SwRect \/\/ position and size\n{\npublic:\n sal_uLong nOrdNum; \/\/ Id to recognize text frames\n sal_uInt16 nPageNum; \/\/ page number\n SwFlyCache( sal_uInt16 nP, sal_uLong nO, long nXL, long nYL, long nWL, long nHL ) :\n SwRect( nXL, nYL, nWL, nHL ), nOrdNum( nO ), nPageNum( nP ){}\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#708427 Unitialized scalar field\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX\n#define INCLUDED_SW_SOURCE_CORE_LAYOUT_LAYHELP_HXX\n\n#include \n#include \n#include \n\nclass SwDoc;\nclass SwFrm;\nclass SwLayoutFrm;\nclass SwPageFrm;\nclass SwFlyFrm;\nclass SwSectionFrm;\nclass SwSectionNode;\nclass SvStream;\n\n\/*************************************************************************\n * class SwLayCacheImpl\n * contains the page break information and the text frame positions\n * of the document (after loading)\n * and is used inside the constructor of the layout rootframe to\n * insert content and text frames at the right pages.\n * For every page of the main text (body content, no footnotes, text frames etc.)\n * we have the nodeindex of the first content at the page,\n * the type of content ( table or paragraph )\n * and if it's not the first part of the table\/paragraph,\n * the row\/character-offset inside the table\/paragraph.\n * The text frame positions are stored in the SwPageFlyCache array.\n *************************************************************************\/\n\nclass SwFlyCache;\ntypedef boost::ptr_vector SwPageFlyCache;\n\nclass SwLayCacheImpl : public std::vector\n{\n std::deque aOffset;\n std::vector aType;\n SwPageFlyCache aFlyCache;\n bool bUseFlyCache;\n void Insert( sal_uInt16 nType, sal_uLong nIndex, sal_Int32 nOffset );\n\npublic:\n SwLayCacheImpl() : bUseFlyCache(false) {}\n bool Read( SvStream& rStream );\n\n sal_uLong GetBreakIndex( sal_uInt16 nIdx ) const { return std::vector::operator[]( nIdx ); }\n sal_Int32 GetBreakOfst( size_t nIdx ) const { return aOffset[ nIdx ]; }\n sal_uInt16 GetBreakType( sal_uInt16 nIdx ) const { return aType[ nIdx ]; }\n\n sal_uInt16 GetFlyCount() const { return aFlyCache.size(); }\n SwFlyCache *GetFlyCache( sal_uInt16 nIdx ) { return &aFlyCache[ nIdx ]; }\n\n bool IsUseFlyCache() const { return bUseFlyCache; }\n};\n\n\/*************************************************************************\n * class SwActualSection\n * helps to create the sectionframes during the _InsertCnt-function\n * by controlling nested sections.\n *************************************************************************\/\n\nclass SwActualSection\n{\n SwActualSection *pUpper;\n SwSectionFrm *pSectFrm;\n SwSectionNode *pSectNode;\npublic:\n SwActualSection( SwActualSection *pUpper,\n SwSectionFrm *pSect,\n SwSectionNode *pNd );\n\n SwSectionFrm *GetSectionFrm() { return pSectFrm; }\n void SetSectionFrm( SwSectionFrm *p ) { pSectFrm = p; }\n SwSectionNode *GetSectionNode() { return pSectNode;}\n SwActualSection *GetUpper() { return pUpper; }\n};\n\n\/*************************************************************************\n * class SwLayHelper\n * helps during the _InsertCnt-function to create new pages.\n * If there's a layoutcache available, this information is used.\n *************************************************************************\/\n\nclass SwLayHelper\n{\n SwFrm* &rpFrm;\n SwFrm* &rpPrv;\n SwPageFrm* &rpPage;\n SwLayoutFrm* &rpLay;\n SwActualSection* &rpActualSection;\n sal_Bool &rbBreakAfter;\n SwDoc* pDoc;\n SwLayCacheImpl* pImpl;\n sal_uLong nMaxParaPerPage;\n sal_uLong nParagraphCnt;\n sal_uLong nStartOfContent;\n sal_uInt16 nIndex; \/\/ the index in the page break array\n sal_uInt16 nFlyIdx; \/\/ the index in the fly cache array\n bool bFirst : 1;\n void _CheckFlyCache( SwPageFrm* pPage );\npublic:\n SwLayHelper( SwDoc *pD, SwFrm* &rpF, SwFrm* &rpP, SwPageFrm* &rpPg,\n SwLayoutFrm* &rpL, SwActualSection* &rpA, sal_Bool &rBrk,\n sal_uLong nNodeIndex, bool bCache );\n ~SwLayHelper();\n sal_uLong CalcPageCount();\n bool CheckInsert( sal_uLong nNodeIndex );\n\n bool CheckInsertPage();\n\n \/\/ Look for fresh text frames at this (new) page and set them to the right\n \/\/ position, if they are in the fly cache.\n void CheckFlyCache( SwPageFrm* pPage )\n { if( pImpl && nFlyIdx < pImpl->GetFlyCount() ) _CheckFlyCache( pPage ); }\n\n \/\/ Look for this text frame and set it to the right position,\n \/\/ if it's in the fly cache.\n static bool CheckPageFlyCache( SwPageFrm* &rpPage, SwFlyFrm* pFly );\n};\n\n\/*************************************************************************\n * class SwLayCacheIoImpl\n * contains the data structures that are required to read and write a\n * layout cache.\n *************************************************************************\/\n\n#define SW_LAYCACHE_IO_REC_PAGES 'p'\n#define SW_LAYCACHE_IO_REC_PARA 'P'\n#define SW_LAYCACHE_IO_REC_TABLE 'T'\n#define SW_LAYCACHE_IO_REC_FLY 'F'\n\n#define SW_LAYCACHE_IO_VERSION_MAJOR 1\n#define SW_LAYCACHE_IO_VERSION_MINOR 1\n\nclass SwLayCacheIoImpl\n{\nprivate:\n struct RecTypeSize {\n sal_uInt8 type;\n sal_uLong size;\n RecTypeSize(sal_uInt8 typ, sal_uLong siz) : type(typ), size(siz) {}\n };\n std::vector aRecords;\n\n SvStream *pStream;\n\n sal_uLong nFlagRecEnd;\n\n sal_uInt16 nMajorVersion;\n sal_uInt16 nMinorVersion;\n\n bool bWriteMode : 1;\n bool bError : 1;\n\npublic:\n SwLayCacheIoImpl( SvStream& rStrm, bool bWrtMd );\n\n \/\/ Get input or output stream\n SvStream& GetStream() const { return *pStream; }\n\n \/\/ Open a record of type \"nType\"\n bool OpenRec( sal_uInt8 nType );\n\n \/\/ Close a record of type \"nType\". This skips any unread data that\n \/\/ remains in the record.\n bool CloseRec( sal_uInt8 nType );\n\n \/\/ Return the number of bytes contained in the current record that\n \/\/ haven't been read by now.\n sal_uInt32 BytesLeft();\n\n \/\/ Return the current record's type\n sal_uInt8 Peek();\n\n \/\/ Skip the current record\n void SkipRec();\n\n \/\/ Open a flag record for reading. The uppermost four bits are flags,\n \/\/ while the lowermost are the flag record's size. Flag records cannot\n \/\/ be nested.\n sal_uInt8 OpenFlagRec();\n\n \/\/ Open flag record for writing;\n void OpenFlagRec( sal_uInt8 nFlags, sal_uInt8 nLen );\n\n \/\/ Close a flag record. Any bytes left are skipped.\n void CloseFlagRec();\n\n bool HasError() const { return bError; }\n\n sal_uInt16 GetMajorVersion() const { return nMajorVersion; }\n sal_uInt16 GetMinorVersion() const { return nMinorVersion; }\n};\n\n\/\/ Stored information about text frames:\nclass SwFlyCache : public SwRect \/\/ position and size\n{\npublic:\n sal_uLong nOrdNum; \/\/ Id to recognize text frames\n sal_uInt16 nPageNum; \/\/ page number\n SwFlyCache( sal_uInt16 nP, sal_uLong nO, long nXL, long nYL, long nWL, long nHL ) :\n SwRect( nXL, nYL, nWL, nHL ), nOrdNum( nO ), nPageNum( nP ){}\n};\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ RUN: %clangxx_msan -m64 -O0 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O1 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O2 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O3 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\n#include \nint main(int argc, char **argv) {\n int x;\n int *volatile p = &x;\n if (*p)\n exit(0);\n \/\/ CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value\n \/\/ CHECK: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-3]]\n\n \/\/ CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'main'\n\n \/\/ CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin.cc:.* main}}\n return 0;\n}\n[msan] Add source file:line to stack origin reports.\/\/ RUN: %clangxx_msan -m64 -O0 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O1 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O2 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\/\/ RUN: %clangxx_msan -m64 -O3 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out\n\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O0 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O1 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O2 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\/\/ RUN: %clangxx_msan -fsanitize-memory-track-origins -m64 -O3 %s -o %t && not %t >%t.out 2>&1\n\/\/ RUN: FileCheck %s < %t.out && FileCheck %s --check-prefix=CHECK-ORIGINS < %t.out\n\n#include \nint main(int argc, char **argv) {\n int x;\n int *volatile p = &x;\n if (*p)\n exit(0);\n \/\/ CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value\n \/\/ CHECK: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-3]]\n\n \/\/ CHECK-ORIGINS: Uninitialized value was created by an allocation of 'x' in the stack frame of function 'main'\n \/\/ CHECK-ORIGINS: {{#0 0x.* in main .*stack-origin.cc:}}[[@LINE-9]]\n\n \/\/ CHECK: SUMMARY: MemorySanitizer: use-of-uninitialized-value {{.*stack-origin.cc:.* main}}\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#include \"device\/pal\/palkernel.hpp\"\n#include \"device\/pal\/palwavelimiter.hpp\"\n#include \"os\/os.hpp\"\n#include \"utils\/flags.hpp\"\n\n#include \nusing namespace std;\n\nnamespace pal {\n\nuint WaveLimiter::MaxWave;\nuint WaveLimiter::RunCount;\nuint WaveLimiter::AdaptCount;\n\nWaveLimiter::WaveLimiter(WaveLimiterManager* manager, uint seqNum, bool enable, bool enableDump)\n : manager_(manager), dumper_(manager_->name() + \"_\" + std::to_string(seqNum), enableDump) {\n setIfNotDefault(SIMDPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, manager->getSimdPerSH());\n MaxWave = GPU_WAVE_LIMIT_MAX_WAVE;\n RunCount = GPU_WAVE_LIMIT_RUN * MaxWave;\n AdaptCount = MaxContinuousSamples * 2 * (MaxWave + 1);\n\n state_ = WARMUP;\n if (!flagIsDefault(GPU_WAVE_LIMIT_TRACE)) {\n traceStream_.open(std::string(GPU_WAVE_LIMIT_TRACE) + manager_->name() + \".txt\");\n }\n\n waves_ = MaxWave;\n enable_ = (SIMDPerSH_ == 0) ? false : enable;\n bestWave_ = (enable_) ? MaxWave : 0;\n sampleCount_ = 0;\n resultCount_ = 0;\n numContinuousSamples_ = 0;\n}\n\nWaveLimiter::~WaveLimiter() {\n if (traceStream_.is_open()) {\n traceStream_.close();\n }\n}\n\nuint WaveLimiter::getWavesPerSH() {\n \/\/ Generate different wave counts in the adaptation mode\n if ((state_ == ADAPT) && (sampleCount_ < AdaptCount)) {\n if (numContinuousSamples_ == 0) {\n waves_ = (++waves_) % (MaxWave + 1);\n }\n numContinuousSamples_ = (++numContinuousSamples_) % MaxContinuousSamples;\n ++sampleCount_;\n }\n else {\n waves_ = bestWave_;\n }\n return waves_ * SIMDPerSH_;\n}\n\nWLAlgorithmSmooth::WLAlgorithmSmooth(WaveLimiterManager* manager, uint seqNum, bool enable,\n bool enableDump)\n : WaveLimiter(manager, seqNum, enable, enableDump) {\n dynRunCount_ = RunCount;\n adpMeasure_.resize(MaxWave + 1);\n adpSampleCnt_.resize(MaxWave + 1);\n runMeasure_.resize(MaxWave + 1);\n runSampleCnt_.resize(MaxWave + 1);\n\n clearData();\n}\n\nWLAlgorithmSmooth::~WLAlgorithmSmooth() {}\n\nvoid WLAlgorithmSmooth::clearData() {\n waves_ = MaxWave;\n countAll_ = 0;\n clear(adpMeasure_);\n clear(adpSampleCnt_);\n dataCount_ = 0;\n}\n\nvoid WLAlgorithmSmooth::updateData(ulong time) {\n\n}\n\nvoid WLAlgorithmSmooth::outputTrace() {\n if (!traceStream_.is_open()) {\n return;\n }\n\n traceStream_ << \"[WaveLimiter] \" << manager_->name() << \" state=\" << state_\n << \" waves=\" << waves_ << \" bestWave=\" << bestWave_ << '\\n';\n output(traceStream_, \"\\n adaptive measure = \", adpMeasure_);\n output(traceStream_, \"\\n adaptive smaple count = \", adpSampleCnt_);\n output(traceStream_, \"\\n run measure = \", runMeasure_);\n output(traceStream_, \"\\n run smaple count = \", runSampleCnt_);\n traceStream_ << \"\\n % time from the previous runs to the best wave: \";\n float min = static_cast(adpMeasure_[bestWave_]) \/ adpSampleCnt_[bestWave_];\n for (uint i = 0; i < (MaxWave + 1); ++i) {\n runSampleCnt_[i] = (runSampleCnt_[i] == 0) ? 1 : runSampleCnt_[i];\n float average = static_cast(runMeasure_[i]) \/ runSampleCnt_[i];\n traceStream_ << (average * 100 \/ min) << \" \";\n }\n traceStream_ << \"\\n run count = \" << dynRunCount_;\n traceStream_ << \"\\n\\n\";\n}\n\n\nvoid WLAlgorithmSmooth::callback(ulong duration, uint32_t waves) {\n dumper_.addData(duration, waves, static_cast(state_));\n\n if (!enable_ || (duration == 0)) {\n return;\n }\n\n countAll_++;\n\n waves \/= SIMDPerSH_;\n \/\/ Collect the time for the current wave count\n runMeasure_[waves] += duration;\n runSampleCnt_[waves]++;\n\n switch (state_) {\n case ADAPT:\n assert(duration > 0);\n \/\/ Wave count 0 indicates the satrt of adaptation\n if ((waves == 0) || (resultCount_ > 0)) {\n \/\/ Scale time to us\n adpMeasure_[waves] += duration;\n adpSampleCnt_[waves]++;\n resultCount_++;\n \/\/ If the end of adaptation is reached, then analyze the results\n if (resultCount_ == AdaptCount) {\n \/\/ Reset the counters\n resultCount_ = sampleCount_ = 0;\n float min = std::numeric_limits::max();\n uint32_t best = bestWave_;\n \/\/ Check performance for the previous run if it's available\n if (runSampleCnt_[bestWave_] > 0) {\n min = static_cast(runMeasure_[bestWave_]) \/ runSampleCnt_[bestWave_];\n }\n else if (adpSampleCnt_[MaxWave] > 0) {\n min = static_cast(adpMeasure_[MaxWave]) \/ adpSampleCnt_[MaxWave];\n bestWave_ = MaxWave;\n }\n \/\/ Find the fastest average time\n float reference = min;\n for (uint i = MaxWave; i > 0; --i) {\n float average;\n if (adpSampleCnt_[i] > 0) {\n average = static_cast(adpMeasure_[i]) \/ adpSampleCnt_[i];\n }\n else {\n average = 0.0f;\n }\n if (average < min) {\n min = average;\n bestWave_ = i;\n }\n }\n \/\/ Check for 5% acceptance\n if ((min * 1.05f > reference) || (bestWave_ == best)) {\n bestWave_ = best;\n \/\/ Increase the run time if the same wave count is the best\n dynRunCount_ += RunCount;\n dynRunCount_++;\n }\n else {\n dynRunCount_ = RunCount;\n }\n state_ = RUN;\n outputTrace();\n \/\/ Start to collect the new data for the best wave\n countAll_ = 0;\n runMeasure_[bestWave_] = 0;\n runSampleCnt_[bestWave_] = 0;\n }\n }\n return;\n case WARMUP:\n case RUN:\n if (countAll_ < dynRunCount_) {\n return;\n }\n if (state_ == WARMUP) {\n runSampleCnt_[bestWave_] = 0;\n }\n state_ = ADAPT;\n clearData();\n return;\n }\n}\n\nWaveLimiter::DataDumper::DataDumper(const std::string& kernelName, bool enable) {\n enable_ = enable;\n if (enable_) {\n fileName_ = std::string(GPU_WAVE_LIMIT_DUMP) + kernelName + \".csv\";\n }\n}\n\nWaveLimiter::DataDumper::~DataDumper() {\n if (!enable_) {\n return;\n }\n\n std::ofstream OFS(fileName_);\n for (size_t i = 0, e = time_.size(); i != e; ++i) {\n OFS << i << ',' << time_[i] << ',' << wavePerSIMD_[i] << ',' << static_cast(state_[i])\n << '\\n';\n }\n OFS.close();\n}\n\nvoid WaveLimiter::DataDumper::addData(ulong time, uint wave, char state) {\n if (!enable_) {\n return;\n }\n\n time_.push_back(time);\n wavePerSIMD_.push_back(wave);\n state_.push_back(state);\n}\n\nWaveLimiterManager::WaveLimiterManager(device::Kernel* kernel, const uint simdPerSH)\n : owner_(kernel), enable_(false), enableDump_(!flagIsDefault(GPU_WAVE_LIMIT_DUMP)) {\n setIfNotDefault(simdPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, simdPerSH);\n fixed_ = GPU_WAVES_PER_SIMD * simdPerSH_;\n}\n\nWaveLimiterManager::~WaveLimiterManager() {\n for (auto& I : limiters_) {\n delete I.second;\n }\n}\n\nuint WaveLimiterManager::getWavesPerSH(const device::VirtualDevice* vdev) const {\n if (fixed_ > 0) {\n return fixed_;\n }\n if (!enable_) {\n return 0;\n }\n auto loc = limiters_.find(vdev);\n if (loc == limiters_.end()) {\n return 0;\n }\n assert(loc->second != nullptr);\n return loc->second->getWavesPerSH();\n}\n\namd::ProfilingCallback* WaveLimiterManager::getProfilingCallback(\n const device::VirtualDevice* vdev) {\n assert(vdev != nullptr);\n if (!enable_ && !enableDump_) {\n return nullptr;\n }\n\n amd::ScopedLock SL(monitor_);\n auto loc = limiters_.find(vdev);\n if (loc != limiters_.end()) {\n return loc->second;\n }\n\n auto limiter = new WLAlgorithmSmooth(this, limiters_.size(), enable_, enableDump_);\n if (limiter == nullptr) {\n enable_ = false;\n return nullptr;\n }\n limiters_[vdev] = limiter;\n return limiter;\n}\n\nvoid WaveLimiterManager::enable() {\n if (fixed_ > 0) {\n return;\n }\n\n \/\/ Enable it only for CI+, unless GPU_WAVE_LIMIT_ENABLE is set to 1\n \/\/ Disabled for SI due to bug #10817\n if (!flagIsDefault(GPU_WAVE_LIMIT_ENABLE)) {\n enable_ = GPU_WAVE_LIMIT_ENABLE;\n } else {\n if (owner_->workGroupInfo()->wavesPerSimdHint_ == 0) {\n enable_ = true;\n } else if (owner_->workGroupInfo()->wavesPerSimdHint_ <= GPU_WAVE_LIMIT_MAX_WAVE) {\n fixed_ = owner_->workGroupInfo()->wavesPerSimdHint_ * getSimdPerSH();\n }\n }\n}\n\n} \/\/ namespace pal\nP4 to Git Change 1507894 by gandryey@gera-lnx-rcf on 2018\/01\/25 11:38:47\/\/\n\/\/ Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#include \"device\/pal\/palkernel.hpp\"\n#include \"device\/pal\/palwavelimiter.hpp\"\n#include \"os\/os.hpp\"\n#include \"utils\/flags.hpp\"\n\n#include \nusing namespace std;\n\nnamespace pal {\n\nuint WaveLimiter::MaxWave;\nuint WaveLimiter::RunCount;\nuint WaveLimiter::AdaptCount;\n\nWaveLimiter::WaveLimiter(WaveLimiterManager* manager, uint seqNum, bool enable, bool enableDump)\n : manager_(manager), dumper_(manager_->name() + \"_\" + std::to_string(seqNum), enableDump) {\n setIfNotDefault(SIMDPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, manager->getSimdPerSH());\n MaxWave = GPU_WAVE_LIMIT_MAX_WAVE;\n RunCount = GPU_WAVE_LIMIT_RUN * MaxWave;\n AdaptCount = MaxContinuousSamples * 2 * (MaxWave + 1);\n\n state_ = WARMUP;\n if (!flagIsDefault(GPU_WAVE_LIMIT_TRACE)) {\n traceStream_.open(std::string(GPU_WAVE_LIMIT_TRACE) + manager_->name() + \".txt\");\n }\n\n waves_ = MaxWave;\n enable_ = (SIMDPerSH_ == 0) ? false : enable;\n bestWave_ = (enable_) ? MaxWave : 0;\n sampleCount_ = 0;\n resultCount_ = 0;\n numContinuousSamples_ = 0;\n}\n\nWaveLimiter::~WaveLimiter() {\n if (traceStream_.is_open()) {\n traceStream_.close();\n }\n}\n\nuint WaveLimiter::getWavesPerSH() {\n \/\/ Generate different wave counts in the adaptation mode\n if ((state_ == ADAPT) && (sampleCount_ < AdaptCount)) {\n if (numContinuousSamples_ == 0) {\n ++waves_;\n waves_ %= MaxWave + 1;\n }\n ++numContinuousSamples_;\n numContinuousSamples_ %= MaxContinuousSamples;\n ++sampleCount_;\n }\n else {\n waves_ = bestWave_;\n }\n return waves_ * SIMDPerSH_;\n}\n\nWLAlgorithmSmooth::WLAlgorithmSmooth(WaveLimiterManager* manager, uint seqNum, bool enable,\n bool enableDump)\n : WaveLimiter(manager, seqNum, enable, enableDump) {\n dynRunCount_ = RunCount;\n adpMeasure_.resize(MaxWave + 1);\n adpSampleCnt_.resize(MaxWave + 1);\n runMeasure_.resize(MaxWave + 1);\n runSampleCnt_.resize(MaxWave + 1);\n\n clearData();\n}\n\nWLAlgorithmSmooth::~WLAlgorithmSmooth() {}\n\nvoid WLAlgorithmSmooth::clearData() {\n waves_ = MaxWave;\n countAll_ = 0;\n clear(adpMeasure_);\n clear(adpSampleCnt_);\n dataCount_ = 0;\n}\n\nvoid WLAlgorithmSmooth::updateData(ulong time) {\n\n}\n\nvoid WLAlgorithmSmooth::outputTrace() {\n if (!traceStream_.is_open()) {\n return;\n }\n\n traceStream_ << \"[WaveLimiter] \" << manager_->name() << \" state=\" << state_\n << \" waves=\" << waves_ << \" bestWave=\" << bestWave_ << '\\n';\n output(traceStream_, \"\\n adaptive measure = \", adpMeasure_);\n output(traceStream_, \"\\n adaptive smaple count = \", adpSampleCnt_);\n output(traceStream_, \"\\n run measure = \", runMeasure_);\n output(traceStream_, \"\\n run smaple count = \", runSampleCnt_);\n traceStream_ << \"\\n % time from the previous runs to the best wave: \";\n float min = static_cast(adpMeasure_[bestWave_]) \/ adpSampleCnt_[bestWave_];\n for (uint i = 0; i < (MaxWave + 1); ++i) {\n runSampleCnt_[i] = (runSampleCnt_[i] == 0) ? 1 : runSampleCnt_[i];\n float average = static_cast(runMeasure_[i]) \/ runSampleCnt_[i];\n traceStream_ << (average * 100 \/ min) << \" \";\n }\n traceStream_ << \"\\n run count = \" << dynRunCount_;\n traceStream_ << \"\\n\\n\";\n}\n\n\nvoid WLAlgorithmSmooth::callback(ulong duration, uint32_t waves) {\n dumper_.addData(duration, waves, static_cast(state_));\n\n if (!enable_ || (duration == 0)) {\n return;\n }\n\n countAll_++;\n\n waves \/= SIMDPerSH_;\n \/\/ Collect the time for the current wave count\n runMeasure_[waves] += duration;\n runSampleCnt_[waves]++;\n\n switch (state_) {\n case ADAPT:\n assert(duration > 0);\n \/\/ Wave count 0 indicates the satrt of adaptation\n if ((waves == 0) || (resultCount_ > 0)) {\n \/\/ Scale time to us\n adpMeasure_[waves] += duration;\n adpSampleCnt_[waves]++;\n resultCount_++;\n \/\/ If the end of adaptation is reached, then analyze the results\n if (resultCount_ == AdaptCount) {\n \/\/ Reset the counters\n resultCount_ = sampleCount_ = 0;\n float min = std::numeric_limits::max();\n uint32_t best = bestWave_;\n \/\/ Check performance for the previous run if it's available\n if (runSampleCnt_[bestWave_] > 0) {\n min = static_cast(runMeasure_[bestWave_]) \/ runSampleCnt_[bestWave_];\n }\n else if (adpSampleCnt_[MaxWave] > 0) {\n min = static_cast(adpMeasure_[MaxWave]) \/ adpSampleCnt_[MaxWave];\n bestWave_ = MaxWave;\n }\n \/\/ Find the fastest average time\n float reference = min;\n for (uint i = MaxWave; i > 0; --i) {\n float average;\n if (adpSampleCnt_[i] > 0) {\n average = static_cast(adpMeasure_[i]) \/ adpSampleCnt_[i];\n }\n else {\n average = 0.0f;\n }\n if (average < min) {\n min = average;\n bestWave_ = i;\n }\n }\n \/\/ Check for 5% acceptance\n if ((min * 1.05f > reference) || (bestWave_ == best)) {\n bestWave_ = best;\n \/\/ Increase the run time if the same wave count is the best\n dynRunCount_ += RunCount;\n dynRunCount_++;\n }\n else {\n dynRunCount_ = RunCount;\n }\n state_ = RUN;\n outputTrace();\n \/\/ Start to collect the new data for the best wave\n countAll_ = 0;\n runMeasure_[bestWave_] = 0;\n runSampleCnt_[bestWave_] = 0;\n }\n }\n return;\n case WARMUP:\n case RUN:\n if (countAll_ < dynRunCount_) {\n return;\n }\n if (state_ == WARMUP) {\n runSampleCnt_[bestWave_] = 0;\n }\n state_ = ADAPT;\n clearData();\n return;\n }\n}\n\nWaveLimiter::DataDumper::DataDumper(const std::string& kernelName, bool enable) {\n enable_ = enable;\n if (enable_) {\n fileName_ = std::string(GPU_WAVE_LIMIT_DUMP) + kernelName + \".csv\";\n }\n}\n\nWaveLimiter::DataDumper::~DataDumper() {\n if (!enable_) {\n return;\n }\n\n std::ofstream OFS(fileName_);\n for (size_t i = 0, e = time_.size(); i != e; ++i) {\n OFS << i << ',' << time_[i] << ',' << wavePerSIMD_[i] << ',' << static_cast(state_[i])\n << '\\n';\n }\n OFS.close();\n}\n\nvoid WaveLimiter::DataDumper::addData(ulong time, uint wave, char state) {\n if (!enable_) {\n return;\n }\n\n time_.push_back(time);\n wavePerSIMD_.push_back(wave);\n state_.push_back(state);\n}\n\nWaveLimiterManager::WaveLimiterManager(device::Kernel* kernel, const uint simdPerSH)\n : owner_(kernel), enable_(false), enableDump_(!flagIsDefault(GPU_WAVE_LIMIT_DUMP)) {\n setIfNotDefault(simdPerSH_, GPU_WAVE_LIMIT_CU_PER_SH, simdPerSH);\n fixed_ = GPU_WAVES_PER_SIMD * simdPerSH_;\n}\n\nWaveLimiterManager::~WaveLimiterManager() {\n for (auto& I : limiters_) {\n delete I.second;\n }\n}\n\nuint WaveLimiterManager::getWavesPerSH(const device::VirtualDevice* vdev) const {\n if (fixed_ > 0) {\n return fixed_;\n }\n if (!enable_) {\n return 0;\n }\n auto loc = limiters_.find(vdev);\n if (loc == limiters_.end()) {\n return 0;\n }\n assert(loc->second != nullptr);\n return loc->second->getWavesPerSH();\n}\n\namd::ProfilingCallback* WaveLimiterManager::getProfilingCallback(\n const device::VirtualDevice* vdev) {\n assert(vdev != nullptr);\n if (!enable_ && !enableDump_) {\n return nullptr;\n }\n\n amd::ScopedLock SL(monitor_);\n auto loc = limiters_.find(vdev);\n if (loc != limiters_.end()) {\n return loc->second;\n }\n\n auto limiter = new WLAlgorithmSmooth(this, limiters_.size(), enable_, enableDump_);\n if (limiter == nullptr) {\n enable_ = false;\n return nullptr;\n }\n limiters_[vdev] = limiter;\n return limiter;\n}\n\nvoid WaveLimiterManager::enable() {\n if (fixed_ > 0) {\n return;\n }\n\n \/\/ Enable it only for CI+, unless GPU_WAVE_LIMIT_ENABLE is set to 1\n \/\/ Disabled for SI due to bug #10817\n if (!flagIsDefault(GPU_WAVE_LIMIT_ENABLE)) {\n enable_ = GPU_WAVE_LIMIT_ENABLE;\n } else {\n if (owner_->workGroupInfo()->wavesPerSimdHint_ == 0) {\n enable_ = true;\n } else if (owner_->workGroupInfo()->wavesPerSimdHint_ <= GPU_WAVE_LIMIT_MAX_WAVE) {\n fixed_ = owner_->workGroupInfo()->wavesPerSimdHint_ * getSimdPerSH();\n }\n }\n}\n\n} \/\/ namespace pal\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DBTypeWizDlgSetup.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 16:48:47 $\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 DBAUI_DBTYPEWIZDLGSETUP_HXX\n#define DBAUI_DBTYPEWIZDLGSETUP_HXX\n\n#ifndef _DBAUI_UNOADMIN_\n#include \"unoadmin.hxx\"\n#endif\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\/\/=========================================================================\n\/\/= ODBTypeWizDialogSetup\n\/\/=========================================================================\nclass ODBTypeWizDialogSetup\n :public ODatabaseAdministrationDialog\n ,public ::comphelper::OPropertyArrayUsageHelper< ODBTypeWizDialogSetup >\n{\n ::rtl::OUString m_sExistingDocToOpen;\n sal_Bool m_bOpenDatabase;\n sal_Bool m_bStartTableWizard;\n\nprotected:\n ODBTypeWizDialogSetup(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);\n\npublic:\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo - static methods\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >\n SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\nprotected:\n\/\/ OGenericUnoDialog overridables\n virtual Dialog* createDialog(Window* _pParent);\n virtual void executedDialog(sal_Int16 _nExecutionResult);\n};\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ DBAUI_DBTYPEWIZDLG_HXX\n\nINTEGRATION: CWS changefileheader (1.5.434); FILE MERGED 2008\/03\/31 13:28:09 rt 1.5.434.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: DBTypeWizDlgSetup.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef DBAUI_DBTYPEWIZDLGSETUP_HXX\n#define DBAUI_DBTYPEWIZDLGSETUP_HXX\n\n#ifndef _DBAUI_UNOADMIN_\n#include \"unoadmin.hxx\"\n#endif\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n\/\/=========================================================================\n\/\/= ODBTypeWizDialogSetup\n\/\/=========================================================================\nclass ODBTypeWizDialogSetup\n :public ODatabaseAdministrationDialog\n ,public ::comphelper::OPropertyArrayUsageHelper< ODBTypeWizDialogSetup >\n{\n ::rtl::OUString m_sExistingDocToOpen;\n sal_Bool m_bOpenDatabase;\n sal_Bool m_bStartTableWizard;\n\nprotected:\n ODBTypeWizDialogSetup(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);\n\npublic:\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo - static methods\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >\n SAL_CALL Create(const ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >&);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\nprotected:\n\/\/ OGenericUnoDialog overridables\n virtual Dialog* createDialog(Window* _pParent);\n virtual void executedDialog(sal_Int16 _nExecutionResult);\n};\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n\n#endif \/\/ DBAUI_DBTYPEWIZDLG_HXX\n\n<|endoftext|>"} {"text":"CWS-TOOLING: integrate CWS calc33stopper3<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\nnamespace {\n\tclass SessionEVP : public CryptoEncryption::Session {\n\t\tLogHandle log_;\n\t\tconst EVP_CIPHER *cipher_;\n\t\tEVP_CIPHER_CTX ctx_;\n\tpublic:\n\t\tSessionEVP(const EVP_CIPHER *xcipher)\n\t\t: log_(\"\/crypto\/encryption\/session\/openssl\"),\n\t\t cipher_(xcipher),\n\t\t ctx_()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_init(&ctx_);\n\t\t}\n\n\t\t~SessionEVP()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_cleanup(&ctx_);\n\t\t}\n\n\t\tunsigned block_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_block_size(cipher_));\n\t\t}\n\n\t\tunsigned key_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_key_length(cipher_));\n\t\t}\n\n\t\tunsigned iv_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_iv_length(cipher_));\n\t\t}\n\n\t\tSession *clone(void) const\n\t\t{\n\t\t\treturn (new SessionEVP(cipher_));\n\t\t}\n\n\t\tbool initialize(CryptoEncryption::Operation operation, const Buffer *key, const Buffer *iv)\n\t\t{\n\t\t\tif (key->length() < (size_t)EVP_CIPHER_key_length(cipher_))\n\t\t\t\treturn (false);\n\n\t\t\tif (iv->length() < (size_t)EVP_CIPHER_iv_length(cipher_))\n\t\t\t\treturn (false);\n\n\t\t\tint enc;\n\t\t\tswitch (operation) {\n\t\t\tcase CryptoEncryption::Encrypt:\n\t\t\t\tenc = 1;\n\t\t\t\tbreak;\n\t\t\tcase CryptoEncryption::Decrypt:\n\t\t\t\tenc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn (false);\n\t\t\t}\n\n\t\t\tuint8_t keydata[key->length()];\n\t\t\tkey->copyout(keydata, sizeof keydata);\n\n\t\t\tuint8_t ivdata[iv->length()];\n\t\t\tiv->copyout(ivdata, sizeof ivdata);\n\n\t\t\tint rv = EVP_CipherInit(&ctx_, cipher_, keydata, ivdata, enc);\n\t\t\tif (rv == 0)\n\t\t\t\treturn (false);\n\n\t\t\treturn (true);\n\t\t}\n\n\t\tbool cipher(Buffer *out, const Buffer *in)\n\t\t{\n\t\t\t\/*\n\t\t\t * We process a single, large, linear byte buffer here rather\n\t\t\t * than going a BufferSegment at a time, even though the byte\n\t\t\t * buffer is less efficient than some alternatives, because\n\t\t\t * there are padding and buffering implications if each\n\t\t\t * BufferSegment's length is not modular to the block size.\n\t\t\t *\/\n\t\t\tuint8_t indata[in->length()];\n\t\t\tin->copyout(indata, sizeof indata);\n\n\t\t\tuint8_t outdata[sizeof indata];\n\t\t\tint rv = EVP_Cipher(&ctx_, outdata, indata, sizeof indata);\n\t\t\tif (rv == 0)\n\t\t\t\treturn (false);\n\t\t\tout->append(outdata, sizeof outdata);\n\t\t\treturn (true);\n\t\t}\n\n\t\tAction *submit(Buffer *in, EventCallback *cb)\n\t\t{\n\t\t\tBuffer out;\n\t\t\tif (!cipher(&out, in)) {\n\t\t\t\tin->clear();\n\t\t\t\tcb->param(Event::Error);\n\t\t\t\treturn (cb->schedule());\n\t\t\t}\n\t\t\tin->clear();\n\t\t\tcb->param(Event(Event::Done, out));\n\t\t\treturn (cb->schedule());\n\t\t}\n\t};\n\n\tclass MethodOpenSSL : public CryptoEncryption::Method {\n\t\tLogHandle log_;\n\t\tFactoryMap cipher_map_;\n\tpublic:\n\t\tMethodOpenSSL(void)\n\t\t: CryptoEncryption::Method(\"OpenSSL\"),\n\t\t log_(\"\/crypto\/encryption\/openssl\"),\n\t\t cipher_map_()\n\t\t{\n\t\t\tOpenSSL_add_all_algorithms();\n\n\t\t\tfactory evp_factory;\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::TripleDES, CryptoEncryption::CBC), evp_factory(EVP_des_ede3_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CBC), evp_factory(EVP_aes_128_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CBC), evp_factory(EVP_aes_192_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CBC), evp_factory(EVP_aes_256_cbc()));\n#if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x00907000L) && !defined(__APPLE__)\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CTR), evp_factory(EVP_aes_128_ctr()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CTR), evp_factory(EVP_aes_192_ctr()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CTR), evp_factory(EVP_aes_256_ctr()));\n#endif\n\n\t\t\t\/* XXX Register. *\/\n\t\t}\n\n\t\t~MethodOpenSSL()\n\t\t{\n\t\t\t\/* XXX Unregister. *\/\n\t\t}\n\n\t\tstd::set ciphers(void) const\n\t\t{\n\t\t\treturn (cipher_map_.keys());\n\t\t}\n\n\t\tCryptoEncryption::Session *session(CryptoEncryption::Cipher cipher) const\n\t\t{\n\t\t\treturn (cipher_map_.create(cipher));\n\t\t}\n\t};\n\n\tstatic MethodOpenSSL crypto_encryption_method_openssl;\n}\nFreeBSD lies, too. Bleh.#include \n\n#include \n\n#include \n\nnamespace {\n\tclass SessionEVP : public CryptoEncryption::Session {\n\t\tLogHandle log_;\n\t\tconst EVP_CIPHER *cipher_;\n\t\tEVP_CIPHER_CTX ctx_;\n\tpublic:\n\t\tSessionEVP(const EVP_CIPHER *xcipher)\n\t\t: log_(\"\/crypto\/encryption\/session\/openssl\"),\n\t\t cipher_(xcipher),\n\t\t ctx_()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_init(&ctx_);\n\t\t}\n\n\t\t~SessionEVP()\n\t\t{\n\t\t\tEVP_CIPHER_CTX_cleanup(&ctx_);\n\t\t}\n\n\t\tunsigned block_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_block_size(cipher_));\n\t\t}\n\n\t\tunsigned key_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_key_length(cipher_));\n\t\t}\n\n\t\tunsigned iv_size(void) const\n\t\t{\n\t\t\treturn (EVP_CIPHER_iv_length(cipher_));\n\t\t}\n\n\t\tSession *clone(void) const\n\t\t{\n\t\t\treturn (new SessionEVP(cipher_));\n\t\t}\n\n\t\tbool initialize(CryptoEncryption::Operation operation, const Buffer *key, const Buffer *iv)\n\t\t{\n\t\t\tif (key->length() < (size_t)EVP_CIPHER_key_length(cipher_))\n\t\t\t\treturn (false);\n\n\t\t\tif (iv->length() < (size_t)EVP_CIPHER_iv_length(cipher_))\n\t\t\t\treturn (false);\n\n\t\t\tint enc;\n\t\t\tswitch (operation) {\n\t\t\tcase CryptoEncryption::Encrypt:\n\t\t\t\tenc = 1;\n\t\t\t\tbreak;\n\t\t\tcase CryptoEncryption::Decrypt:\n\t\t\t\tenc = 0;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn (false);\n\t\t\t}\n\n\t\t\tuint8_t keydata[key->length()];\n\t\t\tkey->copyout(keydata, sizeof keydata);\n\n\t\t\tuint8_t ivdata[iv->length()];\n\t\t\tiv->copyout(ivdata, sizeof ivdata);\n\n\t\t\tint rv = EVP_CipherInit(&ctx_, cipher_, keydata, ivdata, enc);\n\t\t\tif (rv == 0)\n\t\t\t\treturn (false);\n\n\t\t\treturn (true);\n\t\t}\n\n\t\tbool cipher(Buffer *out, const Buffer *in)\n\t\t{\n\t\t\t\/*\n\t\t\t * We process a single, large, linear byte buffer here rather\n\t\t\t * than going a BufferSegment at a time, even though the byte\n\t\t\t * buffer is less efficient than some alternatives, because\n\t\t\t * there are padding and buffering implications if each\n\t\t\t * BufferSegment's length is not modular to the block size.\n\t\t\t *\/\n\t\t\tuint8_t indata[in->length()];\n\t\t\tin->copyout(indata, sizeof indata);\n\n\t\t\tuint8_t outdata[sizeof indata];\n\t\t\tint rv = EVP_Cipher(&ctx_, outdata, indata, sizeof indata);\n\t\t\tif (rv == 0)\n\t\t\t\treturn (false);\n\t\t\tout->append(outdata, sizeof outdata);\n\t\t\treturn (true);\n\t\t}\n\n\t\tAction *submit(Buffer *in, EventCallback *cb)\n\t\t{\n\t\t\tBuffer out;\n\t\t\tif (!cipher(&out, in)) {\n\t\t\t\tin->clear();\n\t\t\t\tcb->param(Event::Error);\n\t\t\t\treturn (cb->schedule());\n\t\t\t}\n\t\t\tin->clear();\n\t\t\tcb->param(Event(Event::Done, out));\n\t\t\treturn (cb->schedule());\n\t\t}\n\t};\n\n\tclass MethodOpenSSL : public CryptoEncryption::Method {\n\t\tLogHandle log_;\n\t\tFactoryMap cipher_map_;\n\tpublic:\n\t\tMethodOpenSSL(void)\n\t\t: CryptoEncryption::Method(\"OpenSSL\"),\n\t\t log_(\"\/crypto\/encryption\/openssl\"),\n\t\t cipher_map_()\n\t\t{\n\t\t\tOpenSSL_add_all_algorithms();\n\n\t\t\tfactory evp_factory;\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::TripleDES, CryptoEncryption::CBC), evp_factory(EVP_des_ede3_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CBC), evp_factory(EVP_aes_128_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CBC), evp_factory(EVP_aes_192_cbc()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CBC), evp_factory(EVP_aes_256_cbc()));\n#if 0\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES128, CryptoEncryption::CTR), evp_factory(EVP_aes_128_ctr()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES192, CryptoEncryption::CTR), evp_factory(EVP_aes_192_ctr()));\n\t\t\tcipher_map_.enter(CryptoEncryption::Cipher(CryptoEncryption::AES256, CryptoEncryption::CTR), evp_factory(EVP_aes_256_ctr()));\n#endif\n\n\t\t\t\/* XXX Register. *\/\n\t\t}\n\n\t\t~MethodOpenSSL()\n\t\t{\n\t\t\t\/* XXX Unregister. *\/\n\t\t}\n\n\t\tstd::set ciphers(void) const\n\t\t{\n\t\t\treturn (cipher_map_.keys());\n\t\t}\n\n\t\tCryptoEncryption::Session *session(CryptoEncryption::Cipher cipher) const\n\t\t{\n\t\t\treturn (cipher_map_.create(cipher));\n\t\t}\n\t};\n\n\tstatic MethodOpenSSL crypto_encryption_method_openssl;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sal { namespace program_options {\n__sal_begin\n\n\nnamespace {\n\nconstexpr bool is_json_punct (int ch)\n{\n return ch == ','\n || ch == ':'\n || ch == '='\n || ch == '['\n || ch == ']'\n || ch == '{'\n || ch == '}'\n ;\n}\n\nconstexpr bool is_bare_key_char (int it)\n{\n return it == '-'\n || it == '_'\n || (it >= 'A' && it <= 'Z')\n || (it >= 'a' && it <= 'z')\n || (it >= '0' && it <= '9')\n ;\n\n}\n\n} \/\/ namespace\n\n\nstruct config_reader_t::impl_t\n{\n std::istream &input;\n\n std::string cache{};\n std::string::const_iterator cache_it = cache.end();\n size_t line = 0;\n int it = 0;\n\n\n struct node_t\n {\n using stack_t = std::deque;\n\n bool(impl_t::*context)(node_t &) = &impl_t::any;\n std::string key{};\n bool allow_comma = false;\n\n node_t () = default;\n\n node_t (bool(impl_t::*context)(node_t &))\n : context(context)\n {}\n\n node_t (bool(impl_t::*context)(node_t &), const std::string &key)\n : context(context)\n , key(key)\n {}\n\n void set (bool(impl_t::*to)(node_t &))\n {\n context = to;\n }\n };\n node_t::stack_t objects{};\n std::string current_value{};\n\n\n impl_t (std::istream &input);\n\n impl_t (const impl_t &) = delete;\n impl_t &operator= (const impl_t &) = delete;\n\n\n \/\/ extract option\/argument\n \/\/ returns true if has more, false otherwise\n bool extract (std::string *option, std::string *argument);\n bool key_and_value (std::string *option, std::string *argument);\n\n\n \/\/ return current column number\n size_t column () const\n {\n return cache_it - cache.begin();\n }\n\n\n \/\/ read next character, caching line if necessary\n bool next ()\n {\n if (cache_it != cache.end() || load_cache())\n {\n it = *cache_it++;\n }\n else\n {\n it = 0;\n }\n return it != 0;\n }\n\n\n bool load_cache ();\n\n\n \/\/ peek at following char\n int peek () const noexcept\n {\n return *cache_it;\n }\n\n\n int unescape (int ch) const\n {\n switch (ch)\n {\n case '\"': return '\"';\n case '\\\\': return '\\\\';\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n }\n throw_unexpected(\"escaped character\");\n }\n\n\n \/\/\n \/\/ state handlers\n \/\/\n\n bool any (node_t &node);\n bool object (node_t &node);\n bool array (node_t &node);\n bool assign (node_t &node);\n bool value (node_t &node);\n\n\n\n \/\/\n \/\/ token extractors\n \/\/\n\n bool skip_spaces_and_comments ();\n\n \/\/ different kind of extractors\n std::string extract_string (bool is_key);\n std::string extract_bare_key ();\n std::string extract_quoteless_string ();\n std::string extract_basic_string (bool allow_multiline);\n std::string extract_literal_string (bool allow_multiline);\n std::string extract_basic_multiline_string ();\n std::string extract_literal_multiline_string ();\n\n\n \/\/\n \/\/ errors\n \/\/\n\n void throw_not_supported [[noreturn]] (const char *what) const\n {\n throw_error(what, \" is not supported \",\n '(', line, ',', column(), ')'\n );\n }\n\n\n void throw_expected [[noreturn]] (const char *what) const\n {\n throw_error(\"expected \", what, ' ',\n '(', line, ',', column(), ')'\n );\n }\n\n\n void throw_unexpected [[noreturn]] (const char *what) const\n {\n throw_error(\"unexpected \", what, ' ',\n '(', line, ',', column(), ')'\n );\n }\n};\n\n\nconfig_reader_t::config_reader_t (std::istream &input)\n : impl_(std::make_unique(input))\n{}\n\n\nconfig_reader_t::~config_reader_t () = default;\n\n\nbool config_reader_t::operator() (const option_set_t &,\n std::string *option,\n std::string *argument)\n{\n return impl_->extract(option, argument);\n}\n\n\nconfig_reader_t::impl_t::impl_t (std::istream &input)\n : input(input)\n{\n objects.emplace_back();\n if (next() && skip_spaces_and_comments() && it == '{')\n {\n object(objects.back());\n }\n}\n\n\nbool config_reader_t::impl_t::extract (std::string *option,\n std::string *argument)\n{\n while (skip_spaces_and_comments())\n {\n if (objects.empty())\n {\n throw_unexpected(\"end of object\");\n }\n auto &node = objects.back();\n if (!(this->*node.context)(node))\n {\n return key_and_value(option, argument);\n }\n }\n\n while (objects.size())\n {\n const auto &node = objects.back();\n if (node.context == &impl_t::value)\n {\n return key_and_value(option, argument);\n }\n else if (node.context != &impl_t::any)\n {\n throw_unexpected(\"end of input\");\n }\n objects.pop_back();\n }\n\n return false;\n}\n\n\nbool config_reader_t::impl_t::key_and_value (std::string *option,\n std::string *argument)\n{\n std::string key;\n for (const auto &object: objects)\n {\n if (object.key.size()\n && (object.context == &impl_t::object\n || object.context == &impl_t::array\n || object.context == &impl_t::value))\n {\n key += object.key;\n key += '.';\n }\n }\n if (key.size() && key.back() == '.')\n {\n key.pop_back();\n }\n\n *sal_check_ptr(argument) = std::move(current_value);\n *sal_check_ptr(option) = std::move(key);\n\n auto &back = objects.back();\n if (back.context != &impl_t::array)\n {\n back.set(&impl_t::any);\n }\n back.allow_comma = true;\n return true;\n}\n\n\nbool config_reader_t::impl_t::any (node_t &node)\n{\n if (it == '}')\n {\n objects.pop_back();\n return true;\n }\n else if (it == ',')\n {\n if (!node.allow_comma)\n {\n throw_unexpected(\"comma\");\n }\n node.allow_comma = false;\n }\n else if (it == '\"' || it == '\\'' || is_bare_key_char(it))\n {\n node.key = extract_string(true);\n node.set(&impl_t::assign);\n return true;\n }\n else\n {\n throw_unexpected(\"character\");\n }\n return next();\n}\n\n\nbool config_reader_t::impl_t::object (node_t &node)\n{\n if (it == '{')\n {\n node.set(&impl_t::object);\n objects.emplace_back();\n return next();\n }\n else if (it == '}')\n {\n objects.pop_back();\n next();\n if (objects.size())\n {\n return true;\n }\n }\n\n objects.emplace_back();\n objects.back().allow_comma = true;\n return true;\n}\n\n\nbool config_reader_t::impl_t::array (node_t &node)\n{\n if (it == ']')\n {\n objects.back().set(&impl_t::any);\n return next();\n }\n else if (it == ',')\n {\n if (!node.allow_comma)\n {\n throw_unexpected(\"comma\");\n }\n node.allow_comma = false;\n return next();\n }\n else if (it == '[' || it == '{')\n {\n throw_not_supported(\"array of arrays or objects\");\n }\n else if (is_json_punct(it))\n {\n throw_unexpected(\"character\");\n }\n current_value = extract_string(false);\n node.allow_comma = true;\n return false;\n}\n\n\nbool config_reader_t::impl_t::assign (node_t &node)\n{\n if (it == '=' || it == ':')\n {\n node.set(&impl_t::value);\n return next();\n }\n throw_expected(\"':' or '='\");\n}\n\n\nbool config_reader_t::impl_t::value (node_t &node)\n{\n if (it == '{')\n {\n node.set(&impl_t::object);\n objects.emplace_back();\n return next();\n }\n else if (it == '[')\n {\n node.set(&impl_t::array);\n return next();\n }\n current_value = extract_string(false);\n return false;\n}\n\n\nstd::string config_reader_t::impl_t::extract_string (bool is_key)\n{\n if (it == '\"')\n {\n return extract_basic_string(is_key == false);\n }\n else if (it == '\\'')\n {\n return extract_literal_string(is_key == false);\n }\n else\n {\n return is_key ? extract_bare_key() : extract_quoteless_string();\n }\n}\n\n\nstd::string config_reader_t::impl_t::extract_bare_key ()\n{\n std::string result;\n while (is_bare_key_char(it))\n {\n result += static_cast(it);\n next();\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_quoteless_string ()\n{\n std::string result;\n while (!is_json_punct(it) && !std::isspace(it))\n {\n if (it == '\/')\n {\n auto ch = peek();\n if (ch == '\/' || ch == '*')\n {\n break;\n }\n }\n result += static_cast(it);\n next();\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_basic_string (bool allow_multiline)\n{\n next();\n if (allow_multiline && it == '\"' && peek() == '\"')\n {\n next(), next();\n return extract_basic_multiline_string();\n }\n\n std::string result;\n while (it != '\"')\n {\n if (it == '\\n')\n {\n throw_unexpected(\"newline\");\n }\n else if (it == '\\\\')\n {\n next();\n it = unescape(it);\n }\n result += static_cast(it);\n next();\n }\n next();\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_literal_string (bool allow_multiline)\n{\n next();\n if (allow_multiline && it == '\\'' && peek() == '\\'')\n {\n next(), next();\n return extract_literal_multiline_string();\n }\n\n std::string result;\n while (it != '\\'')\n {\n if (it == '\\n')\n {\n throw_unexpected(\"newline\");\n }\n result += static_cast(it);\n next();\n }\n next();\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_basic_multiline_string ()\n{\n std::string result;\n\n if (it == '\\n')\n {\n next();\n }\n\n bool skip_whitespaces = false;\n for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())\n {\n if (skip_whitespaces && std::isspace(it))\n {\n continue;\n }\n skip_whitespaces = false;\n\n result += static_cast(it);\n\n if (it == '\"')\n {\n ++consecutive_quotes;\n continue;\n }\n consecutive_quotes = 0;\n\n if (it == '\\\\')\n {\n next();\n if (it != '\\n')\n {\n result.back() = static_cast(unescape(it));\n }\n else\n {\n result.pop_back();\n skip_whitespaces = true;\n }\n }\n }\n\n if (it)\n {\n result.erase(result.size() - 3);\n }\n else\n {\n throw_unexpected(\"end of input\");\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_literal_multiline_string ()\n{\n std::string result;\n\n if (it == '\\n')\n {\n next();\n }\n\n for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())\n {\n result += static_cast(it);\n if (it != '\\'')\n {\n consecutive_quotes = 0;\n }\n else\n {\n ++consecutive_quotes;\n }\n }\n\n if (it)\n {\n result.erase(result.size() - 3);\n }\n else\n {\n throw_unexpected(\"end of input\");\n }\n\n return result;\n}\n\n\nbool config_reader_t::impl_t::load_cache ()\n{\n if (!std::getline(input, cache))\n {\n return false;\n }\n\n while (cache.size()\n && std::isspace(static_cast(cache.back())))\n {\n cache.pop_back();\n }\n\n line++;\n cache.push_back('\\n');\n cache_it = cache.begin();\n\n return true;\n}\n\n\nbool config_reader_t::impl_t::skip_spaces_and_comments ()\n{\n auto comment_recursion_depth = 0U;\n\n do\n {\n if (!it)\n {\n break;\n }\n else if (it == '\/' && peek() == '*')\n {\n comment_recursion_depth++;\n next();\n }\n else if (it == '*' && peek() == '\/')\n {\n comment_recursion_depth--;\n next();\n }\n else if (!comment_recursion_depth)\n {\n if (it == '\/' && peek() == '\/')\n {\n cache_it = cache.end();\n }\n else if (!std::isspace(it))\n {\n return true;\n }\n }\n } while (next());\n\n if (comment_recursion_depth)\n {\n throw_unexpected(\"end of input\");\n }\n\n return false;\n}\n\n\n__sal_end\n}} \/\/ namespace sal::program_options\nconfig_reader: improve next() logic to silence static analyser#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sal { namespace program_options {\n__sal_begin\n\n\nnamespace {\n\nconstexpr bool is_json_punct (int ch)\n{\n return ch == ','\n || ch == ':'\n || ch == '='\n || ch == '['\n || ch == ']'\n || ch == '{'\n || ch == '}'\n ;\n}\n\nconstexpr bool is_bare_key_char (int it)\n{\n return it == '-'\n || it == '_'\n || (it >= 'A' && it <= 'Z')\n || (it >= 'a' && it <= 'z')\n || (it >= '0' && it <= '9')\n ;\n\n}\n\n} \/\/ namespace\n\n\nstruct config_reader_t::impl_t\n{\n std::istream &input;\n\n std::string cache{};\n std::string::const_iterator cache_it = cache.end();\n size_t line = 0;\n int it = 0;\n\n\n struct node_t\n {\n using stack_t = std::deque;\n\n bool(impl_t::*context)(node_t &) = &impl_t::any;\n std::string key{};\n bool allow_comma = false;\n\n node_t () = default;\n\n node_t (bool(impl_t::*context)(node_t &))\n : context(context)\n {}\n\n node_t (bool(impl_t::*context)(node_t &), const std::string &key)\n : context(context)\n , key(key)\n {}\n\n void set (bool(impl_t::*to)(node_t &))\n {\n context = to;\n }\n };\n node_t::stack_t objects{};\n std::string current_value{};\n\n\n impl_t (std::istream &input);\n\n impl_t (const impl_t &) = delete;\n impl_t &operator= (const impl_t &) = delete;\n\n\n \/\/ extract option\/argument\n \/\/ returns true if has more, false otherwise\n bool extract (std::string *option, std::string *argument);\n bool key_and_value (std::string *option, std::string *argument);\n\n\n \/\/ return current column number\n size_t column () const\n {\n return cache_it - cache.begin();\n }\n\n\n \/\/ read next character, caching line if necessary\n bool next ();\n std::string next_line ();\n\n\n \/\/ peek at following char\n int peek () const noexcept\n {\n return *cache_it;\n }\n\n\n int unescape (int ch) const\n {\n switch (ch)\n {\n case '\"': return '\"';\n case '\\\\': return '\\\\';\n case 'b': return '\\b';\n case 'f': return '\\f';\n case 'n': return '\\n';\n case 'r': return '\\r';\n case 't': return '\\t';\n }\n throw_unexpected(\"escaped character\");\n }\n\n\n \/\/\n \/\/ state handlers\n \/\/\n\n bool any (node_t &node);\n bool object (node_t &node);\n bool array (node_t &node);\n bool assign (node_t &node);\n bool value (node_t &node);\n\n\n\n \/\/\n \/\/ token extractors\n \/\/\n\n bool skip_spaces_and_comments ();\n\n \/\/ different kind of extractors\n std::string extract_string (bool is_key);\n std::string extract_bare_key ();\n std::string extract_quoteless_string ();\n std::string extract_basic_string (bool allow_multiline);\n std::string extract_literal_string (bool allow_multiline);\n std::string extract_basic_multiline_string ();\n std::string extract_literal_multiline_string ();\n\n\n \/\/\n \/\/ errors\n \/\/\n\n void throw_not_supported [[noreturn]] (const char *what) const\n {\n throw_error(what, \" is not supported \",\n '(', line, ',', column(), ')'\n );\n }\n\n\n void throw_expected [[noreturn]] (const char *what) const\n {\n throw_error(\"expected \", what, ' ',\n '(', line, ',', column(), ')'\n );\n }\n\n\n void throw_unexpected [[noreturn]] (const char *what) const\n {\n throw_error(\"unexpected \", what, ' ',\n '(', line, ',', column(), ')'\n );\n }\n};\n\n\nconfig_reader_t::config_reader_t (std::istream &input)\n : impl_(std::make_unique(input))\n{}\n\n\nconfig_reader_t::~config_reader_t () = default;\n\n\nbool config_reader_t::operator() (const option_set_t &,\n std::string *option,\n std::string *argument)\n{\n return impl_->extract(option, argument);\n}\n\n\nconfig_reader_t::impl_t::impl_t (std::istream &input)\n : input(input)\n{\n objects.emplace_back();\n if (next() && skip_spaces_and_comments() && it == '{')\n {\n object(objects.back());\n }\n}\n\n\nbool config_reader_t::impl_t::extract (std::string *option,\n std::string *argument)\n{\n while (skip_spaces_and_comments())\n {\n if (objects.empty())\n {\n throw_unexpected(\"end of object\");\n }\n auto &node = objects.back();\n if (!(this->*node.context)(node))\n {\n return key_and_value(option, argument);\n }\n }\n\n while (objects.size())\n {\n const auto &node = objects.back();\n if (node.context == &impl_t::value)\n {\n return key_and_value(option, argument);\n }\n else if (node.context != &impl_t::any)\n {\n throw_unexpected(\"end of input\");\n }\n objects.pop_back();\n }\n\n return false;\n}\n\n\nbool config_reader_t::impl_t::key_and_value (std::string *option,\n std::string *argument)\n{\n std::string key;\n for (const auto &object: objects)\n {\n if (object.key.size()\n && (object.context == &impl_t::object\n || object.context == &impl_t::array\n || object.context == &impl_t::value))\n {\n key += object.key;\n key += '.';\n }\n }\n if (key.size() && key.back() == '.')\n {\n key.pop_back();\n }\n\n *sal_check_ptr(argument) = std::move(current_value);\n *sal_check_ptr(option) = std::move(key);\n\n auto &back = objects.back();\n if (back.context != &impl_t::array)\n {\n back.set(&impl_t::any);\n }\n back.allow_comma = true;\n return true;\n}\n\n\nbool config_reader_t::impl_t::any (node_t &node)\n{\n if (it == '}')\n {\n objects.pop_back();\n return true;\n }\n else if (it == ',')\n {\n if (!node.allow_comma)\n {\n throw_unexpected(\"comma\");\n }\n node.allow_comma = false;\n }\n else if (it == '\"' || it == '\\'' || is_bare_key_char(it))\n {\n node.key = extract_string(true);\n node.set(&impl_t::assign);\n return true;\n }\n else\n {\n throw_unexpected(\"character\");\n }\n return next();\n}\n\n\nbool config_reader_t::impl_t::object (node_t &node)\n{\n if (it == '{')\n {\n node.set(&impl_t::object);\n objects.emplace_back();\n return next();\n }\n else if (it == '}')\n {\n objects.pop_back();\n next();\n if (objects.size())\n {\n return true;\n }\n }\n\n objects.emplace_back();\n objects.back().allow_comma = true;\n return true;\n}\n\n\nbool config_reader_t::impl_t::array (node_t &node)\n{\n if (it == ']')\n {\n objects.back().set(&impl_t::any);\n return next();\n }\n else if (it == ',')\n {\n if (!node.allow_comma)\n {\n throw_unexpected(\"comma\");\n }\n node.allow_comma = false;\n return next();\n }\n else if (it == '[' || it == '{')\n {\n throw_not_supported(\"array of arrays or objects\");\n }\n else if (is_json_punct(it))\n {\n throw_unexpected(\"character\");\n }\n current_value = extract_string(false);\n node.allow_comma = true;\n return false;\n}\n\n\nbool config_reader_t::impl_t::assign (node_t &node)\n{\n if (it == '=' || it == ':')\n {\n node.set(&impl_t::value);\n return next();\n }\n throw_expected(\"':' or '='\");\n}\n\n\nbool config_reader_t::impl_t::value (node_t &node)\n{\n if (it == '{')\n {\n node.set(&impl_t::object);\n objects.emplace_back();\n return next();\n }\n else if (it == '[')\n {\n node.set(&impl_t::array);\n return next();\n }\n current_value = extract_string(false);\n return false;\n}\n\n\nstd::string config_reader_t::impl_t::extract_string (bool is_key)\n{\n if (it == '\"')\n {\n return extract_basic_string(is_key == false);\n }\n else if (it == '\\'')\n {\n return extract_literal_string(is_key == false);\n }\n else\n {\n return is_key ? extract_bare_key() : extract_quoteless_string();\n }\n}\n\n\nstd::string config_reader_t::impl_t::extract_bare_key ()\n{\n std::string result;\n while (is_bare_key_char(it))\n {\n result += static_cast(it);\n next();\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_quoteless_string ()\n{\n std::string result;\n while (!is_json_punct(it) && !std::isspace(it))\n {\n if (it == '\/')\n {\n auto ch = peek();\n if (ch == '\/' || ch == '*')\n {\n break;\n }\n }\n result += static_cast(it);\n next();\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_basic_string (bool allow_multiline)\n{\n next();\n if (allow_multiline && it == '\"' && peek() == '\"')\n {\n next(), next();\n return extract_basic_multiline_string();\n }\n\n std::string result;\n while (it != '\"')\n {\n if (it == '\\n')\n {\n throw_unexpected(\"newline\");\n }\n else if (it == '\\\\')\n {\n next();\n it = unescape(it);\n }\n result += static_cast(it);\n next();\n }\n next();\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_literal_string (bool allow_multiline)\n{\n next();\n if (allow_multiline && it == '\\'' && peek() == '\\'')\n {\n next(), next();\n return extract_literal_multiline_string();\n }\n\n std::string result;\n while (it != '\\'')\n {\n if (it == '\\n')\n {\n throw_unexpected(\"newline\");\n }\n result += static_cast(it);\n next();\n }\n next();\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_basic_multiline_string ()\n{\n std::string result;\n\n if (it == '\\n')\n {\n next();\n }\n\n bool skip_whitespaces = false;\n for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())\n {\n if (skip_whitespaces && std::isspace(it))\n {\n continue;\n }\n skip_whitespaces = false;\n\n result += static_cast(it);\n\n if (it == '\"')\n {\n ++consecutive_quotes;\n continue;\n }\n consecutive_quotes = 0;\n\n if (it == '\\\\')\n {\n next();\n if (it != '\\n')\n {\n result.back() = static_cast(unescape(it));\n }\n else\n {\n result.pop_back();\n skip_whitespaces = true;\n }\n }\n }\n\n if (it)\n {\n result.erase(result.size() - 3);\n }\n else\n {\n throw_unexpected(\"end of input\");\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::extract_literal_multiline_string ()\n{\n std::string result;\n\n if (it == '\\n')\n {\n next();\n }\n\n for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())\n {\n result += static_cast(it);\n if (it != '\\'')\n {\n consecutive_quotes = 0;\n }\n else\n {\n ++consecutive_quotes;\n }\n }\n\n if (it)\n {\n result.erase(result.size() - 3);\n }\n else\n {\n throw_unexpected(\"end of input\");\n }\n\n return result;\n}\n\n\nstd::string config_reader_t::impl_t::next_line ()\n{\n std::string result;\n\n if (std::getline(input, result))\n {\n while (result.size()\n && std::isspace(static_cast(result.back())))\n {\n result.pop_back();\n }\n result.push_back('\\n');\n line++;\n }\n\n return result;\n}\n\n\nbool config_reader_t::impl_t::next ()\n{\n if (cache_it == cache.end())\n {\n cache = next_line();\n cache_it = cache.begin();\n }\n\n if (cache_it != cache.end())\n {\n it = *cache_it++;\n }\n else\n {\n it = 0;\n }\n return it != 0;\n}\n\n\nbool config_reader_t::impl_t::skip_spaces_and_comments ()\n{\n auto comment_recursion_depth = 0U;\n\n do\n {\n if (!it)\n {\n break;\n }\n else if (it == '\/' && peek() == '*')\n {\n comment_recursion_depth++;\n next();\n }\n else if (it == '*' && peek() == '\/')\n {\n comment_recursion_depth--;\n next();\n }\n else if (!comment_recursion_depth)\n {\n if (it == '\/' && peek() == '\/')\n {\n cache_it = cache.end();\n }\n else if (!std::isspace(it))\n {\n return true;\n }\n }\n } while (next());\n\n if (comment_recursion_depth)\n {\n throw_unexpected(\"end of input\");\n }\n\n return false;\n}\n\n\n__sal_end\n}} \/\/ namespace sal::program_options\n<|endoftext|>"} {"text":"make that file platform independent<|endoftext|>"} {"text":"#ifndef MJOLNIR_INPUT_UTILITY_HPP\n#define MJOLNIR_INPUT_UTILITY_HPP\n#include \n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\n\/\/ This check all the keys in a table are found in a list.\n\/\/ If there is a key that is not found in the range, it warns about the\n\/\/ corresponding value will be ignored.\n\/\/ In order to allow optional keys, it only checks all the keys are found\n\/\/ in the specified container.\n\/\/\n\/\/ Use it as the following.\n\/\/ ```cpp\n\/\/ check_keys_available(table, {\"foo\"_s, \"bar\"_s, \"baz\"_s});\n\/\/ ```\ninline bool check_keys_available(const toml::value& table,\n std::initializer_list list)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n \/\/ no logger scope here. use the parent scope.\n\n bool all_available = true;\n for(const auto& kv : table.as_table())\n {\n if(list.end() == std::find(list.begin(), list.end(), kv.first))\n {\n std::ostringstream oss;\n oss << \"unknown value \\\"\" << kv.first << \"\\\" found. this \"\n << kv.second.type() << \" will never be used.\";\n MJOLNIR_LOG_WARN(toml::format_error(oss.str(),\n kv.second, \"this will be ignored\"));\n all_available = false;\n }\n }\n return all_available;\n}\n\ntemplate\ntypename std::enable_if>::value, T>::type\nfind_parameter(const toml::value& params, const toml::value& env,\n const std::string& name)\n{\n using ::mjolnir::literals::string_literals::operator\"\" _s;\n if(!params.is_table() || params.as_table().count(name) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] value \"_s + name +\n \" does not exists\"_s, params, \"in this table\"_s));\n }\n const toml::value& p = params.as_table().at(name);\n if(p.is_string())\n {\n \/\/ search inside of `env`\n const std::string& var = p.as_string();\n if(env.is_uninitialized())\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" used but no env is defined\"_s, params, \"used here\"_s));\n }\n if(!env.is_table() || env.as_table().count(var) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" does not exists\"_s, env, \"in this table\"_s));\n }\n return toml::get(env.as_table().at(var));\n }\n return toml::get(p);\n}\n\n\/\/ If the expected value is std::string, it is difficult to distinguish\n\/\/ variable name and the value itself. In that case, env would just be ignored.\ntemplate\ntypename std::enable_if::value, std::string>::type\nfind_parameter(const toml::value& params, const toml::value& \/* env *\/,\n const std::string& name)\n{\n if(!params.is_table() || params.as_table().count(name) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] value \\\"\"_s + name +\n \"\\\" does not exists\"_s, params, \"in this table\"_s));\n }\n const toml::value& p = params.as_table().at(name);\n return toml::get(p);\n}\n\n\/\/ The current version of Mjolnir allow to use unicode character when defining\n\/\/ a parameter. But since it is a bit ambiguous because of some reasons. E.g.\n\/\/ - The same character might appear in the unicode table several time with\n\/\/ different styles\n\/\/ - When the different parameters appear in different names, it is ofcourse\n\/\/ ambiguous which one to be used.\n\/\/\n\/\/ So I decided to deprecate them. At first I thought that a unicode names\n\/\/ ware covenient to reduce the size of input file. But now, since env is\n\/\/ introduced, it is more effective for reducing the file size. So if it works\n\/\/ nice after the next release, I will deprecate unicode names and warn if used.\n\/\/\n\/\/ This function was introduced to support those\n\/\/ multi-named parameters but is planned to be removed in the later release.\ntemplate\ntypename std::enable_if>::value, T>::type\nfind_parameter(const toml::value& params, const toml::value& env,\n const std::string& name1, const std::string& name2)\n{\n if(!params.is_table() || (params.as_table().count(name1) == 0 &&\n params.as_table().count(name2) == 0))\n {\n throw std::out_of_range(toml::format_error(\"[error] value \\\"\"_s + name1 +\n \"\\\" or \\\"\"_s + name2 + \"\\\" does not exists\"_s, params, \"in this table\"_s));\n }\n \/\/ name1 has priority.\n const toml::value& p = (params.as_table().count(name1) == 1) ?\n params.as_table().at(name1) :\n params.as_table().at(name2) ;\n if(p.is_string())\n {\n \/\/ search inside of `env`\n const std::string& var = p.as_string();\n if(env.is_uninitialized())\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" used but no env is defined\"_s, params, \"used here\"_s));\n }\n if(!env.is_table() || env.as_table().count(var) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" does not exists\"_s, env, \"in this table\"_s));\n }\n return toml::get(env.as_table().at(var));\n }\n return toml::get(p);\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_INPUT_UTILITY_HPP\nart: remove [error] prefix inserted by toml11#ifndef MJOLNIR_INPUT_UTILITY_HPP\n#define MJOLNIR_INPUT_UTILITY_HPP\n#include \n#include \n#include \n#include \n\nnamespace mjolnir\n{\n\n\/\/ This check all the keys in a table are found in a list.\n\/\/ If there is a key that is not found in the range, it warns about the\n\/\/ corresponding value will be ignored.\n\/\/ In order to allow optional keys, it only checks all the keys are found\n\/\/ in the specified container.\n\/\/\n\/\/ Use it as the following.\n\/\/ ```cpp\n\/\/ check_keys_available(table, {\"foo\"_s, \"bar\"_s, \"baz\"_s});\n\/\/ ```\ninline bool check_keys_available(const toml::value& table,\n std::initializer_list list)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n \/\/ no logger scope here. use the parent scope.\n\n bool all_available = true;\n for(const auto& kv : table.as_table())\n {\n if(list.end() == std::find(list.begin(), list.end(), kv.first))\n {\n std::ostringstream oss;\n oss << \"unknown value \\\"\" << kv.first << \"\\\" found. this \"\n << kv.second.type() << \" will never be used.\";\n const auto err_msg = toml::format_error(\n oss.str(), kv.second, \"this will be ignored\");\n \/\/ workaround to skip auto-added [error].\n \/\/ Normally this function is called only when the input file\n \/\/ contains an invalid key. So it should not be a hotspot.\n MJOLNIR_LOG_WARN(err_msg.substr(err_msg.find(oss.str())));\n all_available = false;\n }\n }\n return all_available;\n}\n\ntemplate\ntypename std::enable_if>::value, T>::type\nfind_parameter(const toml::value& params, const toml::value& env,\n const std::string& name)\n{\n using ::mjolnir::literals::string_literals::operator\"\" _s;\n if(!params.is_table() || params.as_table().count(name) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] value \"_s + name +\n \" does not exists\"_s, params, \"in this table\"_s));\n }\n const toml::value& p = params.as_table().at(name);\n if(p.is_string())\n {\n \/\/ search inside of `env`\n const std::string& var = p.as_string();\n if(env.is_uninitialized())\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" used but no env is defined\"_s, params, \"used here\"_s));\n }\n if(!env.is_table() || env.as_table().count(var) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" does not exists\"_s, env, \"in this table\"_s));\n }\n return toml::get(env.as_table().at(var));\n }\n return toml::get(p);\n}\n\n\/\/ If the expected value is std::string, it is difficult to distinguish\n\/\/ variable name and the value itself. In that case, env would just be ignored.\ntemplate\ntypename std::enable_if::value, std::string>::type\nfind_parameter(const toml::value& params, const toml::value& \/* env *\/,\n const std::string& name)\n{\n if(!params.is_table() || params.as_table().count(name) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] value \\\"\"_s + name +\n \"\\\" does not exists\"_s, params, \"in this table\"_s));\n }\n const toml::value& p = params.as_table().at(name);\n return toml::get(p);\n}\n\n\/\/ The current version of Mjolnir allow to use unicode character when defining\n\/\/ a parameter. But since it is a bit ambiguous because of some reasons. E.g.\n\/\/ - The same character might appear in the unicode table several time with\n\/\/ different styles\n\/\/ - When the different parameters appear in different names, it is ofcourse\n\/\/ ambiguous which one to be used.\n\/\/\n\/\/ So I decided to deprecate them. At first I thought that a unicode names\n\/\/ ware covenient to reduce the size of input file. But now, since env is\n\/\/ introduced, it is more effective for reducing the file size. So if it works\n\/\/ nice after the next release, I will deprecate unicode names and warn if used.\n\/\/\n\/\/ This function was introduced to support those\n\/\/ multi-named parameters but is planned to be removed in the later release.\ntemplate\ntypename std::enable_if>::value, T>::type\nfind_parameter(const toml::value& params, const toml::value& env,\n const std::string& name1, const std::string& name2)\n{\n if(!params.is_table() || (params.as_table().count(name1) == 0 &&\n params.as_table().count(name2) == 0))\n {\n throw std::out_of_range(toml::format_error(\"[error] value \\\"\"_s + name1 +\n \"\\\" or \\\"\"_s + name2 + \"\\\" does not exists\"_s, params, \"in this table\"_s));\n }\n \/\/ name1 has priority.\n const toml::value& p = (params.as_table().count(name1) == 1) ?\n params.as_table().at(name1) :\n params.as_table().at(name2) ;\n if(p.is_string())\n {\n \/\/ search inside of `env`\n const std::string& var = p.as_string();\n if(env.is_uninitialized())\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" used but no env is defined\"_s, params, \"used here\"_s));\n }\n if(!env.is_table() || env.as_table().count(var) != 1)\n {\n throw std::out_of_range(toml::format_error(\"[error] named variable \\\"\"_s +\n var + \"\\\" does not exists\"_s, env, \"in this table\"_s));\n }\n return toml::get(env.as_table().at(var));\n }\n return toml::get(p);\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_INPUT_UTILITY_HPP\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2006 by Till Adam *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n#include \n#include \n\n#include \"akonadiconnection.h\"\n#include \"handler.h\"\n#include \"response.h\"\n\nusing namespace Akonadi;\n\nAkonadiConnection::AkonadiConnection( int socketDescriptor, QObject *parent )\n : QThread(parent)\n , m_socketDescriptor(socketDescriptor)\n , m_tcpSocket( 0 )\n , m_currentHandler( 0 )\n , m_connectionState( NonAuthenticated )\n{\n}\n\n\nAkonadiConnection::~AkonadiConnection()\n{\n qDebug() << \"Connection closed\";\n delete m_tcpSocket;\n}\n\nvoid AkonadiConnection::run()\n{\n m_tcpSocket = new QTcpSocket();\n\n if ( !m_tcpSocket->setSocketDescriptor( m_socketDescriptor ) ) {\n emit error(m_tcpSocket->error());\n return;\n }\n\n writeOut( \"* OK Akonadi Almost IMAP Server\");\n\n \/* Start a local event loop and start processing incoming data. Whenever\n * a full command has been read, it is delegated to the responsible\n * handler and processed by that. If that command needs to do something\n * asynchronous such as ask the db for data, it returns and the input\n * queue can continue to be processed. Whenever there is something to\n * be sent back to the user it is queued in the form of a Response object.\n * All this is meant to make it possible to process large incoming or\n * outgoing data transfers in a streaming manner, without having to\n * hold them in memory 'en gros'. *\/\n\n connect( m_tcpSocket, SIGNAL( readyRead() ),\n this, SLOT( slotNewData() ) );\n connect( m_tcpSocket, SIGNAL( disconnected() ),\n this, SLOT( slotDisconnected() ) );\n exec();\n}\n\nvoid AkonadiConnection::slotDisconnected()\n{\n quit();\n}\n\nvoid AkonadiConnection::slotNewData()\n{\n QByteArray line = m_tcpSocket->readLine().trimmed();\n qDebug() << \"GOT:\" << line << endl;\n if ( !m_currentHandler ) {\n \/\/ this is a new command, which means the line must start with a tag\n \/\/ followed by a non-empty command. First get the tag\n int separator = line.indexOf(' ');\n if ( separator == -1 || separator == line.size() ) {\n writeOut( \"* BAD Untagged client command cannot be processed\" );\n return;\n }\n \/\/ parse our the tag\n const QByteArray tag = line.left( separator );\n \/\/ and the command\n int commandStart = line.indexOf( ' ', 0 ) + 1;\n int commandEnd = line.indexOf( ' ', commandStart );\n if ( commandEnd == -1 ) commandEnd = line.size();\n const QByteArray command = line.mid( commandStart, commandEnd - commandStart ).toUpper();\n\n m_currentHandler = findHandlerForCommand( command );\n m_currentHandler->setTag( tag );\n assert( m_currentHandler );\n connect( m_currentHandler, SIGNAL( responseAvailable( const Response & ) ),\n this, SLOT( slotResponseAvailable( const Response & ) ) );\n connect( m_currentHandler, SIGNAL( connectionStateChange( ConnectionState ) ),\n this, SLOT( slotConnectionStateChange( ConnectionState ) ) );\n }\n if ( m_currentHandler->handleLine( line ) )\n m_currentHandler = 0;\n}\n\nvoid AkonadiConnection::writeOut( const char* str )\n{\n qDebug() << \"writing out: \" << str << endl;\n QByteArray block;\n QTextStream out(&block, QIODevice::WriteOnly);\n out << str << endl;\n out.flush();\n m_tcpSocket->write(block);\n m_tcpSocket->waitForBytesWritten();\n}\n\n\nHandler * AkonadiConnection::findHandlerForCommand( const QByteArray & command )\n{\n Handler * handler = Handler::findHandlerForCommandAlwaysAllowed( command );\n if ( handler ) return handler;\n \n switch ( m_connectionState ) {\n case NonAuthenticated:\n handler = Handler::findHandlerForCommandNonAuthenticated( command ); break;\n case Authenticated:\n handler = Handler::findHandlerForCommandAuthenticated( command );\n break;\n case Selected:\n break;\n case LoggingOut:\n break; \n }\n \/\/ we didn't have a handler for this, let the default one do its thing\n if ( !handler ) handler = new Handler();\n return handler;\n}\n\nvoid AkonadiConnection::slotResponseAvailable( const Response& response )\n{\n \/\/ FIXME handle reentrancy in the presence of continuation. Something like:\n \/\/ \"if continuation pending, queue responses, once continuation is done, replay them\"\n writeOut( response.asString().data() );\n}\n\nvoid AkonadiConnection::slotConnectionStateChange( ConnectionState state )\n{\n if ( state == m_connectionState ) return;\n m_connectionState = state;\n switch ( m_connectionState ) {\n case NonAuthenticated:\n assert( 0 ); \/\/ can't happen, it's only the initial state, we can't go back to it\n break;\n case Authenticated:\n break;\n case Selected:\n break;\n case LoggingOut:\n m_tcpSocket->disconnectFromHost();\n break;\n }\n}\nbuild\/***************************************************************************\n * Copyright (C) 2006 by Till Adam *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n#include \n#include \n\n#include \"akonadiconnection.h\"\n#include \"handler.h\"\n#include \"response.h\"\n\n#include \n\nusing namespace Akonadi;\n\nAkonadiConnection::AkonadiConnection( int socketDescriptor, QObject *parent )\n : QThread(parent)\n , m_socketDescriptor(socketDescriptor)\n , m_tcpSocket( 0 )\n , m_currentHandler( 0 )\n , m_connectionState( NonAuthenticated )\n{\n}\n\n\nAkonadiConnection::~AkonadiConnection()\n{\n qDebug() << \"Connection closed\";\n delete m_tcpSocket;\n}\n\nvoid AkonadiConnection::run()\n{\n m_tcpSocket = new QTcpSocket();\n\n if ( !m_tcpSocket->setSocketDescriptor( m_socketDescriptor ) ) {\n emit error(m_tcpSocket->error());\n return;\n }\n\n writeOut( \"* OK Akonadi Almost IMAP Server\");\n\n \/* Start a local event loop and start processing incoming data. Whenever\n * a full command has been read, it is delegated to the responsible\n * handler and processed by that. If that command needs to do something\n * asynchronous such as ask the db for data, it returns and the input\n * queue can continue to be processed. Whenever there is something to\n * be sent back to the user it is queued in the form of a Response object.\n * All this is meant to make it possible to process large incoming or\n * outgoing data transfers in a streaming manner, without having to\n * hold them in memory 'en gros'. *\/\n\n connect( m_tcpSocket, SIGNAL( readyRead() ),\n this, SLOT( slotNewData() ) );\n connect( m_tcpSocket, SIGNAL( disconnected() ),\n this, SLOT( slotDisconnected() ) );\n exec();\n}\n\nvoid AkonadiConnection::slotDisconnected()\n{\n quit();\n}\n\nvoid AkonadiConnection::slotNewData()\n{\n QByteArray line = m_tcpSocket->readLine().trimmed();\n qDebug() << \"GOT:\" << line << endl;\n if ( !m_currentHandler ) {\n \/\/ this is a new command, which means the line must start with a tag\n \/\/ followed by a non-empty command. First get the tag\n int separator = line.indexOf(' ');\n if ( separator == -1 || separator == line.size() ) {\n writeOut( \"* BAD Untagged client command cannot be processed\" );\n return;\n }\n \/\/ parse our the tag\n const QByteArray tag = line.left( separator );\n \/\/ and the command\n int commandStart = line.indexOf( ' ', 0 ) + 1;\n int commandEnd = line.indexOf( ' ', commandStart );\n if ( commandEnd == -1 ) commandEnd = line.size();\n const QByteArray command = line.mid( commandStart, commandEnd - commandStart ).toUpper();\n\n m_currentHandler = findHandlerForCommand( command );\n m_currentHandler->setTag( tag );\n assert( m_currentHandler );\n connect( m_currentHandler, SIGNAL( responseAvailable( const Response & ) ),\n this, SLOT( slotResponseAvailable( const Response & ) ) );\n connect( m_currentHandler, SIGNAL( connectionStateChange( ConnectionState ) ),\n this, SLOT( slotConnectionStateChange( ConnectionState ) ) );\n }\n if ( m_currentHandler->handleLine( line ) )\n m_currentHandler = 0;\n}\n\nvoid AkonadiConnection::writeOut( const char* str )\n{\n qDebug() << \"writing out: \" << str << endl;\n QByteArray block;\n QTextStream out(&block, QIODevice::WriteOnly);\n out << str << endl;\n out.flush();\n m_tcpSocket->write(block);\n m_tcpSocket->waitForBytesWritten();\n}\n\n\nHandler * AkonadiConnection::findHandlerForCommand( const QByteArray & command )\n{\n Handler * handler = Handler::findHandlerForCommandAlwaysAllowed( command );\n if ( handler ) return handler;\n \n switch ( m_connectionState ) {\n case NonAuthenticated:\n handler = Handler::findHandlerForCommandNonAuthenticated( command ); break;\n case Authenticated:\n handler = Handler::findHandlerForCommandAuthenticated( command );\n break;\n case Selected:\n break;\n case LoggingOut:\n break; \n }\n \/\/ we didn't have a handler for this, let the default one do its thing\n if ( !handler ) handler = new Handler();\n return handler;\n}\n\nvoid AkonadiConnection::slotResponseAvailable( const Response& response )\n{\n \/\/ FIXME handle reentrancy in the presence of continuation. Something like:\n \/\/ \"if continuation pending, queue responses, once continuation is done, replay them\"\n writeOut( response.asString().data() );\n}\n\nvoid AkonadiConnection::slotConnectionStateChange( ConnectionState state )\n{\n if ( state == m_connectionState ) return;\n m_connectionState = state;\n switch ( m_connectionState ) {\n case NonAuthenticated:\n assert( 0 ); \/\/ can't happen, it's only the initial state, we can't go back to it\n break;\n case Authenticated:\n break;\n case Selected:\n break;\n case LoggingOut:\n m_tcpSocket->disconnectFromHost();\n break;\n }\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2006 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 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#include \"alsadeviceenumerator.h\"\n#include \"alsadeviceenumerator_p.h\"\n#include \"alsadevice_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Phonon\n{\n\nAlsaDeviceEnumerator *AlsaDeviceEnumerator::s_instance = 0;\n\nAlsaDeviceEnumerator *AlsaDeviceEnumerator::self()\n{\n if (!s_instance) {\n s_instance = new AlsaDeviceEnumerator;\n s_instance->d->findDevices();\n }\n return s_instance;\n}\n\nAlsaDevice *AlsaDeviceEnumerator::deviceFor(const QString &internalId)\n{\n for (int i = 0; i < d->devicelist.size(); ++i) {\n if (d->devicelist[i].d->internalId == internalId) {\n return &d->devicelist[i];\n }\n }\n return 0;\n}\n\nAlsaDeviceEnumerator::AlsaDeviceEnumerator(QObject *parent)\n : QObject(parent),\n d(new AlsaDeviceEnumeratorPrivate)\n{\n}\n\nvoid AlsaDeviceEnumeratorPrivate::findDevices()\n{\n \/\/ first check the 'default' device and the devices defined in ~\/.asoundrc and \/etc\/asound.conf\n AlsaDevice defaultCtlDevice(QLatin1String(\"default\"), AlsaDevice::ControlAndPcm);\n if (defaultCtlDevice.isValid()) {\n devicelist << defaultCtlDevice;\n }\n findAsoundrcDevices(QDir::homePath() + \"\/.asoundrc\");\n findAsoundrcDevices(\"\/etc\/asound.conf\");\n\n \/\/ then ask Solid for the available audio hardware\n Solid::DeviceManager &manager = Solid::DeviceManager::self();\n\n Solid::DeviceList devices = manager.findDevicesFromQuery(QString(), Solid::Capability::AudioHw,\n Solid::Predicate(Solid::Capability::AudioHw, QLatin1String(\"driver\"), Solid::AudioHw::Alsa));\n foreach (Solid::Device device, devices) {\n Solid::AudioHw *audiohw = device.as();\n Q_ASSERT(audiohw);\n Q_ASSERT(audiohw->driver() == Solid::AudioHw::Alsa);\n QString handle = audiohw->driverHandler();\n kDebug(603) << k_funcinfo << handle << \", \" << audiohw->name() << \", \" << audiohw->driver() << \", \" << audiohw->type() << endl;\n if (audiohw->type() & Solid::AudioHw::AudioOutput) {\n handle = handle.right(handle.size() - handle.indexOf(':') - 1);\n int comma = handle.indexOf(',');\n int devicenum = -1;\n if (comma > -1) {\n \/\/devicenum = handle.right(handle.size() - 1 - comma).toInt();\n handle = handle.left(comma);\n }\n AlsaDevice dev(handle.toInt(), devicenum);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }\n }\n\n \/\/ look at the list of currently available devices\n \/*int card = -1;\n while (snd_card_next(&card) >= 0 && card >= 0) {\n AlsaDevice dev(card);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }*\/\n\n \/\/ TODO register with Solid to emit the devicePlugged\/deviceUnplugged signals\n}\n\nvoid AlsaDeviceEnumeratorPrivate::findAsoundrcDevices(const QString &fileName)\n{\n QFile asoundrcFile(fileName);\n asoundrcFile.open(QIODevice::ReadOnly);\n QTextStream asoundrcStream(&asoundrcFile);\n QString line;\n QStringList words;\n int depth = 0;\n while (!asoundrcStream.atEnd()) {\n line = asoundrcStream.readLine().simplified();\n \/\/kDebug(603) << \"'\" << line << \"'\" << endl;\n if (line.startsWith('#')) {\n continue; \/\/skip comment lines\n }\n if (line.contains('#')) { \/\/ truncate comments at the end of the line\n line = line.left(line.indexOf('#'));\n \/\/kDebug(603) << \"'\" << line << \"'\" << endl;\n }\n words = line.split(' ', QString::SkipEmptyParts);\n foreach (QString word, words) {\n if (word == QLatin1String(\"{\")) {\n ++depth;\n } else if (word == QLatin1String(\"}\")) {\n --depth;\n } else if (depth == 0) {\n int index = word.indexOf('.');\n if (index != -1) {\n QString type = word.left(index).toLower();\n if (type == QLatin1String(\"ctl\")) {\n QString deviceName = word.right(word.size() - index - 1);\n if (deviceName.startsWith('!')) {\n deviceName = deviceName.right(deviceName.size() - 1);\n }\n AlsaDevice dev(deviceName, AlsaDevice::Control);\n if (dev.isValid()) {\n devicelist << dev;\n }\n } else if (type == QLatin1String(\"pcm\")) {\n QString deviceName = word.right(word.size() - index - 1);\n if (deviceName.startsWith('!')) {\n deviceName = deviceName.right(deviceName.size() - 1);\n }\n AlsaDevice dev(deviceName, AlsaDevice::Pcm);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }\n }\n }\n }\n }\n}\n\nAlsaDeviceEnumerator::~AlsaDeviceEnumerator()\n{\n delete d;\n d = 0;\n}\n\nQList AlsaDeviceEnumerator::availableDevices()\n{\n return self()->d->devicelist;\n}\n\n} \/\/ namespace Phonon\n#include \"alsadeviceenumerator.moc\"\n\n\/\/ vim: sw=4 sts=4 et tw=100\nQString deviceHandle -> QStringList deviceHandles (only on the frontend, the frontend can now add logic for a preference of device handles for the same device (needed for ALSA)\/* This file is part of the KDE project\n Copyright (C) 2006 Matthias Kretz \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 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#include \"alsadeviceenumerator.h\"\n#include \"alsadeviceenumerator_p.h\"\n#include \"alsadevice_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Phonon\n{\n\nAlsaDeviceEnumerator *AlsaDeviceEnumerator::s_instance = 0;\n\nAlsaDeviceEnumerator *AlsaDeviceEnumerator::self()\n{\n if (!s_instance) {\n s_instance = new AlsaDeviceEnumerator;\n s_instance->d->findDevices();\n }\n return s_instance;\n}\n\nAlsaDevice *AlsaDeviceEnumerator::deviceFor(const QString &internalId)\n{\n for (int i = 0; i < d->devicelist.size(); ++i) {\n if (d->devicelist[i].d->internalId == internalId) {\n return &d->devicelist[i];\n }\n }\n return 0;\n}\n\nAlsaDeviceEnumerator::AlsaDeviceEnumerator(QObject *parent)\n : QObject(parent),\n d(new AlsaDeviceEnumeratorPrivate)\n{\n}\n\nvoid AlsaDeviceEnumeratorPrivate::findDevices()\n{\n \/\/ first check the 'default' device and the devices defined in ~\/.asoundrc and \/etc\/asound.conf\n AlsaDevice defaultCtlDevice(QLatin1String(\"default\"), AlsaDevice::ControlAndPcm);\n if (defaultCtlDevice.isValid()) {\n devicelist << defaultCtlDevice;\n }\n findAsoundrcDevices(QDir::homePath() + \"\/.asoundrc\");\n findAsoundrcDevices(\"\/etc\/asound.conf\");\n\n \/\/ then ask Solid for the available audio hardware\n Solid::DeviceManager &manager = Solid::DeviceManager::self();\n\n Solid::DeviceList devices = manager.findDevicesFromQuery(QString(), Solid::Capability::AudioHw,\n Solid::Predicate(Solid::Capability::AudioHw, QLatin1String(\"driver\"), Solid::AudioHw::Alsa));\n foreach (Solid::Device device, devices) {\n Solid::AudioHw *audiohw = device.as();\n Q_ASSERT(audiohw);\n Q_ASSERT(audiohw->driver() == Solid::AudioHw::Alsa);\n QStringList handles = audiohw->driverHandles();\n kDebug(603) << k_funcinfo << handles << \", \" << audiohw->name() << \", \" << audiohw->driver() << \", \" << audiohw->deviceType() << endl;\n if (audiohw->deviceType() & Solid::AudioHw::AudioOutput) {\n QString handle = handles.last();\n handle = handle.right(handle.size() - handle.indexOf(':') - 1);\n int comma = handle.indexOf(',');\n int devicenum = -1;\n if (comma > -1) {\n \/\/devicenum = handle.right(handle.size() - 1 - comma).toInt();\n handle = handle.left(comma);\n }\n AlsaDevice dev(handle.toInt(), devicenum);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }\n }\n\n \/\/ look at the list of currently available devices\n \/*int card = -1;\n while (snd_card_next(&card) >= 0 && card >= 0) {\n AlsaDevice dev(card);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }*\/\n\n \/\/ TODO register with Solid to emit the devicePlugged\/deviceUnplugged signals\n}\n\nvoid AlsaDeviceEnumeratorPrivate::findAsoundrcDevices(const QString &fileName)\n{\n QFile asoundrcFile(fileName);\n asoundrcFile.open(QIODevice::ReadOnly);\n QTextStream asoundrcStream(&asoundrcFile);\n QString line;\n QStringList words;\n int depth = 0;\n while (!asoundrcStream.atEnd()) {\n line = asoundrcStream.readLine().simplified();\n \/\/kDebug(603) << \"'\" << line << \"'\" << endl;\n if (line.startsWith('#')) {\n continue; \/\/skip comment lines\n }\n if (line.contains('#')) { \/\/ truncate comments at the end of the line\n line = line.left(line.indexOf('#'));\n \/\/kDebug(603) << \"'\" << line << \"'\" << endl;\n }\n words = line.split(' ', QString::SkipEmptyParts);\n foreach (QString word, words) {\n if (word == QLatin1String(\"{\")) {\n ++depth;\n } else if (word == QLatin1String(\"}\")) {\n --depth;\n } else if (depth == 0) {\n int index = word.indexOf('.');\n if (index != -1) {\n QString type = word.left(index).toLower();\n if (type == QLatin1String(\"ctl\")) {\n QString deviceName = word.right(word.size() - index - 1);\n if (deviceName.startsWith('!')) {\n deviceName = deviceName.right(deviceName.size() - 1);\n }\n AlsaDevice dev(deviceName, AlsaDevice::Control);\n if (dev.isValid()) {\n devicelist << dev;\n }\n } else if (type == QLatin1String(\"pcm\")) {\n QString deviceName = word.right(word.size() - index - 1);\n if (deviceName.startsWith('!')) {\n deviceName = deviceName.right(deviceName.size() - 1);\n }\n AlsaDevice dev(deviceName, AlsaDevice::Pcm);\n if (dev.isValid()) {\n devicelist << dev;\n }\n }\n }\n }\n }\n }\n}\n\nAlsaDeviceEnumerator::~AlsaDeviceEnumerator()\n{\n delete d;\n d = 0;\n}\n\nQList AlsaDeviceEnumerator::availableDevices()\n{\n return self()->d->devicelist;\n}\n\n} \/\/ namespace Phonon\n#include \"alsadeviceenumerator.moc\"\n\n\/\/ vim: sw=4 sts=4 et tw=100\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\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 * @author Dmitriy S. Matveev, Viskov Nikolay \n * @version $Revision$\n *\/\n#include \"Font.h\"\n#include \"Environment.h\"\n#include \"TTFont.h\"\n#include \"T1Font.h\"\n#include \n\nFont::Font() {\n _famName = NULL;\n}\n\nFont::~Font() {\n\tfor( std::map::iterator iter = _glyphMap.begin(); iter != _glyphMap.end(); iter++ ) {\t\t\n\t\tdelete iter->second;\t\t\n\t}\n\n\tdelete[] _famName;\n\n\t\/*ufshort famLength = fwcslen((fwchar_t *)_famName);\n\tfchar *family = new fchar[famLength+1];\n\n\tufshort i;\n\tfor (i = 0;i < famLength;i++) {\n\t\t(family)[i] = _famName[i];\n\t}\n\t(family)[i] = '\\0';\n\n\tFontHeader* fh = GraphicsEnvironment::getAllFonts()->_head;\n\t\/\/printf(\"\\nfaund = -%s-\\n\", family);\n\tfor(fint i=0; i_familyName);\n\t\tif (strcmp(fh->_familyName,family)==0 && fh->_style == _style) {\n\t\t\tfh->_font = NULL;\n\t\t\tbreak;\n\t\t}\n\n\t\tfh=fh->_nextHeader;\n\t}\n\n\tdelete[] family;*\/\n}\n\nGlyph* Font::createGlyph(ufshort unicode, ufshort size){\n\treturn NULL; \n}\n\nfwchar_t* Font::getPSName()\n{\n\treturn NULL;\n}\n\nffloat* Font::getLineMetrics()\n{\n\treturn NULL;\n}\n\nfint\tFont::getMissingGlyphCode()\n{\n\treturn 0;\n}\n\nbool Font::canDisplay(ufshort c)\n{\n\treturn 0;\n}\n\nufshort Font::getUnicodeByIndex(ufshort ind)\n{\n\treturn 0;\n}\n\n\/\/unicode = 0 - default glyph\nGlyph* Font::getGlyph(ufshort unicode, ufshort size) {\n\tuflong id;\n \n\t\/\/printf(\"unicode = %lu, size = %lu\\n\", unicode,size);\n\n if (!canDisplay(unicode)) {\n\t\tid = (uflong)(size << 16);\n unicode = 0;\n } else {\n\t\tid = (uflong)(size << 16) + unicode;\n }\t\n\n \/\/printf(\"unicode = %lu, size = %lu, id = %lu\\n\", unicode,size,id);\n\n\tstd::map::iterator iter = _glyphMap.find(id);\t\n\tif (iter != _glyphMap.end()) {\n\/\/printf(\"return the glyph\");\n\t\treturn (Glyph *)(*iter).second;\t\n\t}\n\/\/printf(\"creation of the glyph\");\n\tGlyph *glyph = createGlyph(unicode, size);\n\t\n\t_glyphMap[id] = glyph;\n\n\treturn glyph;\t\n}\n\n\/\/ Creation of font depending on font type\nFont* createFont(fchar* family, StyleName sn) {\n\tfint nLen = (fint) strlen(family);\n\tfwchar_t* name = new fwchar_t[nLen+1];\n\tfor (fint i = 0; i <= nLen; i++)\n\t\tname[i] = family[i];\n\n\tFont* retFont = createFont(name, sn);\n\n\tdelete[] name;\n\n\treturn retFont;\n}\n\n\/\/ Creation of font depending on font type\nFont* createFont(fwchar_t* family, StyleName sn) \n{\n\tFont* retFont;\n\tbool isFound = false;\n\n\tif (Environment::getAllFonts() == NULL)\treturn NULL;\n\n\tfor(FontHeader* fh = Environment::getAllFonts();\n\t\tfh != NULL; fh=fh->_nextHeader)\n\t{\n\n\t\tif (fwcscmp(fh->_familyName,family)==0 && fh->_style == sn)\n\t\t{\n\n\t\t\tswitch(fh->_fType)\n\t\t\t{\n\t\t\t\tcase TrueType:\n\t\t\t\t\t\tretFont = new TTFont(fh->_filePath);\n\t\t\t\t\t\tfh->_font=retFont;\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase Type1:\t\t\t\t\t\n\t\t\t\t\t\tretFont = new T1Font(family,sn,fh->_filePath);\n\t\t\t\t\t\tfh->_font=retFont;\n\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tisFound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!isFound)\n\t{\n\/\/\t\tprintf(\"Font not found\");\n\t\treturn 0; \/\/ \n\t} \n\treturn retFont;\n}\nFix for HARMONY-6033 ([classlib][awt] - remove unrecognized char in file Font.cpp)\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\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 * @author Dmitriy S. Matveev, Viskov Nikolay \n * @version $Revision$\n *\/\n#include \"Font.h\"\n#include \"Environment.h\"\n#include \"TTFont.h\"\n#include \"T1Font.h\"\n#include \n\nFont::Font() {\n _famName = NULL;\n}\n\nFont::~Font() {\n\tfor( std::map::iterator iter = _glyphMap.begin(); iter != _glyphMap.end(); iter++ ) {\t\t\n\t\tdelete iter->second;\t\t\n\t}\n\n\tdelete[] _famName;\n\n\t\/*ufshort famLength = fwcslen((fwchar_t *)_famName);\n\tfchar *family = new fchar[famLength+1];\n\n\tufshort i;\n\tfor (i = 0;i < famLength;i++) {\n\t\t(family)[i] = _famName[i];\n\t}\n\t(family)[i] = '\\0';\n\n\tFontHeader* fh = GraphicsEnvironment::getAllFonts()->_head;\n\t\/\/printf(\"\\nfaund = -%s-\\n\", family);\n\tfor(fint i=0; i_familyName);\n\t\tif (strcmp(fh->_familyName,family)==0 && fh->_style == _style) {\n\t\t\tfh->_font = NULL;\n\t\t\tbreak;\n\t\t}\n\n\t\tfh=fh->_nextHeader;\n\t}\n\n\tdelete[] family;*\/\n}\n\nGlyph* Font::createGlyph(ufshort unicode, ufshort size){\n\treturn NULL; \n}\n\nfwchar_t* Font::getPSName()\n{\n\treturn NULL;\n}\n\nffloat* Font::getLineMetrics()\n{\n\treturn NULL;\n}\n\nfint\tFont::getMissingGlyphCode()\n{\n\treturn 0;\n}\n\nbool Font::canDisplay(ufshort c)\n{\n\treturn 0;\n}\n\nufshort Font::getUnicodeByIndex(ufshort ind)\n{\n\treturn 0;\n}\n\n\/\/unicode = 0 - default glyph\nGlyph* Font::getGlyph(ufshort unicode, ufshort size) {\n\tuflong id;\n \n\t\/\/printf(\"unicode = %lu, size = %lu\\n\", unicode,size);\n\n if (!canDisplay(unicode)) {\n\t\tid = (uflong)(size << 16);\n unicode = 0;\n } else {\n\t\tid = (uflong)(size << 16) + unicode;\n }\t\n\n \/\/printf(\"unicode = %lu, size = %lu, id = %lu\\n\", unicode,size,id);\n\n\tstd::map::iterator iter = _glyphMap.find(id);\t\n\tif (iter != _glyphMap.end()) {\n\/\/printf(\"return the glyph\");\n\t\treturn (Glyph *)(*iter).second;\t\n\t}\n\/\/printf(\"creation of the glyph\");\n\tGlyph *glyph = createGlyph(unicode, size);\n\t\n\t_glyphMap[id] = glyph;\n\n\treturn glyph;\t\n}\n\n\/\/ Creation of font depending on font type\nFont* createFont(fchar* family, StyleName sn) {\n\tfint nLen = (fint) strlen(family);\n\tfwchar_t* name = new fwchar_t[nLen+1];\n\tfor (fint i = 0; i <= nLen; i++)\n\t\tname[i] = family[i];\n\n\tFont* retFont = createFont(name, sn);\n\n\tdelete[] name;\n\n\treturn retFont;\n}\n\n\/\/ Creation of font depending on font type\nFont* createFont(fwchar_t* family, StyleName sn) \n{\n\tFont* retFont;\n\tbool isFound = false;\n\n\tif (Environment::getAllFonts() == NULL)\treturn NULL;\n\n\tfor(FontHeader* fh = Environment::getAllFonts();\n\t\tfh != NULL; fh=fh->_nextHeader)\n\t{\n\n\t\tif (fwcscmp(fh->_familyName,family)==0 && fh->_style == sn)\n\t\t{\n\n\t\t\tswitch(fh->_fType)\n\t\t\t{\n\t\t\t\tcase TrueType:\n\t\t\t\t\t\tretFont = new TTFont(fh->_filePath);\n\t\t\t\t\t\tfh->_font=retFont;\n\n\t\t\t\t\tbreak;\n\t\t\t\tcase Type1:\t\t\t\t\t\n\t\t\t\t\t\tretFont = new T1Font(family,sn,fh->_filePath);\n\t\t\t\t\t\tfh->_font=retFont;\n\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tisFound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!isFound)\n\t{\n\/\/\t\tprintf(\"Font not found\");\n\t\treturn 0; \/\/Font not found\n\t} \n\treturn retFont;\n}\n<|endoftext|>"} {"text":"add missing file<|endoftext|>"} {"text":"\/*\n * Copyright © 2012, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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 * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n*\/\n\n\/**\n * @file MuscleNP.cpp\n * @brief Definition of a massless cable with contact dynamics\n * $Id$\n *\/\n\n\/\/ This object\n#include \"MuscleNP.h\"\n\n\/\/ NTRT\n#include \"tgcreator\/tgUtil.h\"\n#include \"core\/muscleAnchor.h\"\n#include \"core\/tgCast.h\"\n#include \"core\/tgBulletUtil.h\"\n#include \"core\/tgWorld.h\"\n\/\/ The Bullet Physics library\n#include \"btBulletDynamicsCommon.h\"\n#include \"BulletCollision\/CollisionDispatch\/btGhostObject.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btOverlappingPairCache.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btCollisionAlgorithm.h\"\n#include \"BulletCollision\/CollisionDispatch\/btCollisionWorld.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btDispatcher.h\"\n#include \"BulletDynamics\/Dynamics\/btDynamicsWorld.h\"\n#include \"BulletDynamics\/Dynamics\/btActionInterface.h\"\n#include \"LinearMath\/btDefaultMotionState.h\"\n#include \"LinearMath\/btQuaternion.h\"\n\n\/\/ The C++ Standard Library\n#include \n#include \/\/ std::sort\n\nMuscleNP::MuscleNP(btPairCachingGhostObject* ghostObject,\n tgWorld& world,\n btRigidBody * body1,\n btVector3 pos1,\n btRigidBody * body2,\n btVector3 pos2,\n double coefK,\n double dampingCoefficient) :\nMuscle2P (body1, pos1, body2, pos2, coefK, dampingCoefficient),\nm_ghostObject(ghostObject),\nm_overlappingPairCache(tgBulletUtil::worldToDynamicsWorld(world).getBroadphase()),\nm_dispatcher(tgBulletUtil::worldToDynamicsWorld(world).getDispatcher()),\nm_ac(anchor1, anchor2)\n{\n\n}\n \nMuscleNP::~MuscleNP()\n{\n\t\n}\n\nconst btScalar MuscleNP::getActualLength() const\n{\n btScalar length = 0;\n \n std::size_t n = m_anchors.size() - 1;\n for (std::size_t i = 0; i < n; i++)\n {\n length += (m_anchors[i]->getWorldPosition() - m_anchors[i+1]->getWorldPosition()).length(); \n }\n \n return length;\n}\n\nbtVector3 MuscleNP::calculateAndApplyForce(double dt)\n{\n\t\n\tupdateAnchorList(dt);\n\t\n \/\/ Apply forces\n \n updateCollisionObject();\n}\n\nvoid MuscleNP::updateAnchorList(double dt)\n{\n\tstd::vector::iterator it = m_anchors.begin();\n muscleAnchor* temp;\n\tfor (it = m_anchors.begin(); it != m_anchors.end(); it++)\n\t{\n\t\tif ((*it)->permanent == false)\n {\n delete *it;\n }\n\t}\n\t\n m_anchors.clear();\n \n\tm_anchors.insert(m_anchors.begin(), anchor1);\n\tm_anchors.insert(m_anchors.end(), anchor2);\n\t\n\t\n\t\n\tbtManifoldArray\tm_manifoldArray;\n\tbtVector3 m_touchingNormal;\n\t\n\t\/\/std::cout << m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs() << std::endl;\n\n\t\/\/ Only caches the pairs, they don't have a lot of useful information\n\tbtBroadphasePairArray& pairArray = m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray();\n\tint numPairs = pairArray.size();\n\n\tfor (int i=0;igetOverlappingPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1);\n\n\t\tbtCollisionObject* obj0 = static_cast(collisionPair->m_pProxy0->m_clientObject);\n btCollisionObject* obj1 = static_cast(collisionPair->m_pProxy1->m_clientObject);\n\n\t\tif (collisionPair->m_algorithm)\n\t\t\tcollisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray);\n\t\t\n\t\t\/\/std::cout << m_manifoldArray.size() << std::endl;\n\t\t\n\t\tfor (int j=0;jgetBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0);\n\t\t\tfor (int p=0;pgetNumContacts();p++)\n\t\t\t{\n\t\t\t\tconst btManifoldPoint&pt = manifold->getContactPoint(p);\n\n\t\t\t\tbtScalar dist = pt.getDistance();\n\t\t\t\t\n\t\t\t\t\/\/ Ensures the force is pointed outwards - may need to double check\n\t\t\t\tif (dist < 0.0)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tm_touchingNormal = pt.m_normalWorldOnB * directionSign;\/\/??\n\t\t\t\t\t\n\t\t\t\t\tbtRigidBody* rb = NULL;\n\t\t\t\t\tbtVector3 pos;\n\t\t\t\t\t\n\t\t\t\t\tif (directionSign < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\trb = btRigidBody::upcast(obj1);\n\t\t\t\t\t\tpos = pt.m_positionWorldOnB;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\trb = btRigidBody::upcast(obj0);\n\t\t\t\t\t\tpos = pt.m_positionWorldOnA;\n\t\t\t\t\t}\t\n\t\t\t\t\t\n\t\t\t\t\tif(rb)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst muscleAnchor* newAnchor = new muscleAnchor(rb, pos, m_touchingNormal, false, true);\n\t\t\t\t\t\tm_anchors.push_back(newAnchor);\n\t\t\t\t\t\t\n \/* \n\t\t\t\t\t\tbtScalar mass = rb->getInvMass() == 0 ? 0.0 : 1.0 \/ rb->getInvMass();\n\t\t\t\t\t\tbtVector3 impulse = mass * dt * m_touchingNormal * getTension() \/ getActualLength() * -1.0* dist;\n\t\t\t\t\t\trb->applyImpulse(impulse, pos);\n *\/\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t}\n \n std::sort (m_anchors.begin(), m_anchors.end(), m_ac);\n \n std::size_t n = m_anchors.size();\n for (int i = 0; i < n; i++)\n {\n std::cout << m_anchors[i]->getWorldPosition() << std::endl;\n }\n \n}\n\n\/\/ This works ok at the moment. Need an effective way of determining if the rope is under an object\nvoid MuscleNP::updateCollisionObject()\n{\n btVector3 maxes(anchor2->getWorldPosition());\n btVector3 mins(anchor1->getWorldPosition());\n \n std::size_t n = m_anchors.size();\n for (std::size_t i = 1; i < n; i++)\n {\n btVector3 worldPos = m_anchors[i]->getWorldPosition();\n for (std::size_t j = 0; j < 3; j++)\n {\n if (worldPos[j] > maxes[j])\n {\n maxes[j] = worldPos[j];\n }\n else if (worldPos[j] < mins[j])\n {\n mins[j] = worldPos[j];\n }\n }\n }\n\t\n btVector3 from = anchor1->getWorldPosition();\n\tbtVector3 to = anchor2->getWorldPosition();\n\t\n\tbtTransform transform = tgUtil::getTransform(from, to);\n\t\n\t\/\/std::cout << (to - from).length()\/2.0 << std::endl;\n\n \n btQuaternion rot = transform.getRotation();\n \n btVector3 newDimensions = (maxes - mins).rotate(rot.getAxis(), rot.getAngle()) \/ 2.0;\n \n for (std::size_t i = 0; i < 3; i++)\n {\n \/\/\/@todo make configurable\n if (std::abs(newDimensions[i]) < 0.01)\n {\n newDimensions[i] = 0.01;\n }\n else\n {\n newDimensions[i] = std::abs(newDimensions[i]);\n }\n }\n \n\tbtBoxShape* shape = tgCast::cast(*m_ghostObject->getCollisionShape());\n\t\/* Note that 1) this is listed as \"use with care\" in Bullet's documentation and\n\t * 2) we had to remove the object from DemoApplication's render function in order for it to render properly\n\t * changing from a non-contact object will break that behavior.\n\t *\/ \n\tshape->setImplicitShapeDimensions(newDimensions);\n\tm_ghostObject->setCollisionShape(shape);\n\t\n\n m_ghostObject->setWorldTransform(transform);\n\n \/\/ Erwin recommends this after changing collision shape: http:\/\/www.bulletphysics.org\/Bullet\/phpBB3\/viewtopic.php?f=9&t=4611\n \/\/ Doesn't seem to make much of a difference for us\n \/\/m_ghostObject->getOverlappingPairCache()->cleanProxyFromPairs(m_ghostObject->getBroadphaseHandle(), m_dispatcher);\n \n}\n\nMuscleNP::anchorCompare::anchorCompare(const muscleAnchor* m1, const muscleAnchor* m2) :\nma1(m1),\nma2(m2)\n{\n\t\n}\n\nbool MuscleNP::anchorCompare::operator() (const muscleAnchor* lhs, const muscleAnchor* rhs)\n{\n btVector3 pt1 = ma1->getWorldPosition();\n btVector3 ptN = ma2->getWorldPosition();\n \n btVector3 pt2 = lhs->getWorldPosition();\n btVector3 pt3 = rhs->getWorldPosition();\n \n btScalar lhDot = (ptN - pt1).dot(pt2);\n btScalar rhDot = (ptN - pt1).dot(pt3);\n \n return lhDot < rhDot;\n} \n\nFirst cut point pruning algorithm\/*\n * Copyright © 2012, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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 * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n*\/\n\n\/**\n * @file MuscleNP.cpp\n * @brief Definition of a massless cable with contact dynamics\n * $Id$\n *\/\n\n\/\/ This object\n#include \"MuscleNP.h\"\n\n\/\/ NTRT\n#include \"tgcreator\/tgUtil.h\"\n#include \"core\/muscleAnchor.h\"\n#include \"core\/tgCast.h\"\n#include \"core\/tgBulletUtil.h\"\n#include \"core\/tgWorld.h\"\n\/\/ The Bullet Physics library\n#include \"btBulletDynamicsCommon.h\"\n#include \"BulletCollision\/CollisionDispatch\/btGhostObject.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btOverlappingPairCache.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btCollisionAlgorithm.h\"\n#include \"BulletCollision\/CollisionDispatch\/btCollisionWorld.h\"\n#include \"BulletCollision\/BroadphaseCollision\/btDispatcher.h\"\n#include \"BulletDynamics\/Dynamics\/btDynamicsWorld.h\"\n#include \"BulletDynamics\/Dynamics\/btActionInterface.h\"\n#include \"LinearMath\/btDefaultMotionState.h\"\n#include \"LinearMath\/btQuaternion.h\"\n\n\/\/ The C++ Standard Library\n#include \n#include \/\/ std::sort\n#include \n\nMuscleNP::MuscleNP(btPairCachingGhostObject* ghostObject,\n tgWorld& world,\n btRigidBody * body1,\n btVector3 pos1,\n btRigidBody * body2,\n btVector3 pos2,\n double coefK,\n double dampingCoefficient) :\nMuscle2P (body1, pos1, body2, pos2, coefK, dampingCoefficient),\nm_ghostObject(ghostObject),\nm_overlappingPairCache(tgBulletUtil::worldToDynamicsWorld(world).getBroadphase()),\nm_dispatcher(tgBulletUtil::worldToDynamicsWorld(world).getDispatcher()),\nm_ac(anchor1, anchor2)\n{\n\n}\n \nMuscleNP::~MuscleNP()\n{\n\t\n}\n\nconst btScalar MuscleNP::getActualLength() const\n{\n btScalar length = 0;\n \n std::size_t n = m_anchors.size() - 1;\n for (std::size_t i = 0; i < n; i++)\n {\n length += (m_anchors[i]->getWorldPosition() - m_anchors[i+1]->getWorldPosition()).length(); \n }\n \n return length;\n}\n\nbtVector3 MuscleNP::calculateAndApplyForce(double dt)\n{\n\t\n\tupdateAnchorList(dt);\n\t\n \/\/ Apply forces\n \n updateCollisionObject();\n}\n\nvoid MuscleNP::updateAnchorList(double dt)\n{\n\tstd::vector::iterator it = m_anchors.begin();\n muscleAnchor* temp;\n\tfor (it = m_anchors.begin(); it != m_anchors.end(); it++)\n\t{\n\t\tif ((*it)->permanent == false)\n {\n delete *it;\n }\n\t}\n\t\n m_anchors.clear();\n \n\tbtManifoldArray\tm_manifoldArray;\n\tbtVector3 m_touchingNormal;\n\t\n\t\/\/std::cout << m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs() << std::endl;\n\n\t\/\/ Only caches the pairs, they don't have a lot of useful information\n\tbtBroadphasePairArray& pairArray = m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray();\n\tint numPairs = pairArray.size();\n\n\tfor (int i=0;igetOverlappingPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1);\n\n\t\tbtCollisionObject* obj0 = static_cast(collisionPair->m_pProxy0->m_clientObject);\n btCollisionObject* obj1 = static_cast(collisionPair->m_pProxy1->m_clientObject);\n\n\t\tif (collisionPair->m_algorithm)\n\t\t\tcollisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray);\n\t\t\n\t\t\/\/std::cout << m_manifoldArray.size() << std::endl;\n\t\t\n\t\tfor (int j=0;jgetBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0);\n\t\t\tfor (int p=0;pgetNumContacts();p++)\n\t\t\t{\n\t\t\t\tconst btManifoldPoint&pt = manifold->getContactPoint(p);\n\n\t\t\t\tbtScalar dist = pt.getDistance();\n\t\t\t\t\n\t\t\t\t\/\/ Ensures the force is pointed outwards - may need to double check\n\t\t\t\tif (dist < 0.0)\n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tm_touchingNormal = pt.m_normalWorldOnB * directionSign;\/\/??\n\t\t\t\t\t\n\t\t\t\t\tbtRigidBody* rb = NULL;\n\t\t\t\t\tbtVector3 pos;\n\t\t\t\t\t\n\t\t\t\t\tif (directionSign < 0)\n\t\t\t\t\t{\n\t\t\t\t\t\trb = btRigidBody::upcast(obj1);\n\t\t\t\t\t\tpos = pt.m_positionWorldOnB;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\trb = btRigidBody::upcast(obj0);\n\t\t\t\t\t\tpos = pt.m_positionWorldOnA;\n\t\t\t\t\t}\t\n\t\t\t\t\t\n\t\t\t\t\tif(rb)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst muscleAnchor* newAnchor = new muscleAnchor(rb, pos, m_touchingNormal, false, true);\n\t\t\t\t\t\tm_anchors.push_back(newAnchor);\n\t\t\t\t\t\t\n \/* \n\t\t\t\t\t\tbtScalar mass = rb->getInvMass() == 0 ? 0.0 : 1.0 \/ rb->getInvMass();\n\t\t\t\t\t\tbtVector3 impulse = mass * dt * m_touchingNormal * getTension() \/ getActualLength() * -1.0* dist;\n\t\t\t\t\t\trb->applyImpulse(impulse, pos);\n *\/\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t}\n \n std::sort (m_anchors.begin(), m_anchors.end(), m_ac);\n \n \/\/ Add these last to ensure we're in the right order\n m_anchors.insert(m_anchors.begin(), anchor1);\n\tm_anchors.insert(m_anchors.end(), anchor2);\n \n \/\/ Find way to enter the loop without BS data\n int numPruned = 1;\n std::size_t i;\n while (numPruned > 0)\n {\n numPruned = 0;\n i = 1;\n while (i < m_anchors.size() - 1)\n {\n btVector3 back = m_anchors[i - 1]->getWorldPosition(); \n btVector3 forward = m_anchors[i + 1]->getWorldPosition(); \n \n btVector3 line = forward - back;\n \n \/\/ Maybe change to double if Bullet uses double?\n \/\/std::cout << \"Normals \" << std::abs(line.dot( m_anchors[i]->contactNormal)) << std::endl;\n btScalar normalValue = std::abs(line.dot( m_anchors[i]->contactNormal));\n if (normalValue > 0.1)\n { \n std::cout << \"Erased: \" << normalValue << \" \"; \n delete m_anchors[i];\n m_anchors.erase(m_anchors.begin() + i);\n numPruned++;\n } \n \/\/\/ @todo make configurable! \n #if (0)\n else if((m_anchors[i]->getWorldPosition() - m_anchors[i-1]->getWorldPosition()).length() < 0.01)\n {\n delete m_anchors[i];\n m_anchors.erase(m_anchors.begin() + i);\n numPruned++;\n }\n #endif\n else\n {\n i++;\n }\n std::cout << m_anchors.size() << \" \";\n \n }\n \n std::cout << \"Pruned: \" << numPruned << std::endl;\n }\n \n std::size_t n = m_anchors.size();\n for (i = 0; i < n; i++)\n { \n std::cout << m_anchors[i]->getWorldPosition(); \n \n if (i != 0 && i != n-1)\n {\n btVector3 back = m_anchors[i - 1]->getWorldPosition(); \n btVector3 forward = m_anchors[i + 1]->getWorldPosition(); \n \n btVector3 line = forward - back;\n \n std::cout << \" \" << line.dot( m_anchors[i]->contactNormal);\n } \n \n std::cout << std::endl;\n }\n \n}\n\n\/\/ This works ok at the moment. Need an effective way of determining if the rope is under an object\nvoid MuscleNP::updateCollisionObject()\n{\n btVector3 maxes(anchor2->getWorldPosition());\n btVector3 mins(anchor1->getWorldPosition());\n \n std::size_t n = m_anchors.size();\n for (std::size_t i = 1; i < n; i++)\n {\n btVector3 worldPos = m_anchors[i]->getWorldPosition();\n for (std::size_t j = 0; j < 3; j++)\n {\n if (worldPos[j] > maxes[j])\n {\n maxes[j] = worldPos[j];\n }\n else if (worldPos[j] < mins[j])\n {\n mins[j] = worldPos[j];\n }\n }\n }\n\t\n btVector3 from = anchor1->getWorldPosition();\n\tbtVector3 to = anchor2->getWorldPosition();\n\t\n\tbtTransform transform = tgUtil::getTransform(from, to);\n\t\n\t\/\/std::cout << (to - from).length()\/2.0 << std::endl;\n\n \n btQuaternion rot = transform.getRotation();\n \n btVector3 newDimensions = (maxes - mins).rotate(rot.getAxis(), rot.getAngle()) \/ 2.0;\n \n for (std::size_t i = 0; i < 3; i++)\n {\n \/\/\/@todo make configurable\n if (std::abs(newDimensions[i]) < 0.01)\n {\n newDimensions[i] = 0.01;\n }\n else\n {\n newDimensions[i] = std::abs(newDimensions[i]);\n }\n }\n \n\tbtBoxShape* shape = tgCast::cast(*m_ghostObject->getCollisionShape());\n\t\/* Note that 1) this is listed as \"use with care\" in Bullet's documentation and\n\t * 2) we had to remove the object from DemoApplication's render function in order for it to render properly\n\t * changing from a non-contact object will break that behavior.\n\t *\/ \n\tshape->setImplicitShapeDimensions(newDimensions);\n\tm_ghostObject->setCollisionShape(shape);\n\t\n\n m_ghostObject->setWorldTransform(transform);\n\n \/\/ Erwin recommends this after changing collision shape: http:\/\/www.bulletphysics.org\/Bullet\/phpBB3\/viewtopic.php?f=9&t=4611\n \/\/ Doesn't seem to make much of a difference for us\n \/\/m_ghostObject->getOverlappingPairCache()->cleanProxyFromPairs(m_ghostObject->getBroadphaseHandle(), m_dispatcher);\n \n}\n\nMuscleNP::anchorCompare::anchorCompare(const muscleAnchor* m1, const muscleAnchor* m2) :\nma1(m1),\nma2(m2)\n{\n\t\n}\n\nbool MuscleNP::anchorCompare::operator() (const muscleAnchor* lhs, const muscleAnchor* rhs)\n{\n btVector3 pt1 = ma1->getWorldPosition();\n btVector3 ptN = ma2->getWorldPosition();\n \n btVector3 pt2 = lhs->getWorldPosition();\n btVector3 pt3 = rhs->getWorldPosition();\n \n btScalar lhDot = (ptN - pt1).dot(pt2);\n btScalar rhDot = (ptN - pt1).dot(pt3);\n \n return lhDot < rhDot;\n} \n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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 \"UBLOX_PPP_CellularNetwork.h\"\n\nusing namespace mbed;\n\nUBLOX_PPP_CellularNetwork::UBLOX_PPP_CellularNetwork(ATHandler &atHandler) : AT_CellularNetwork(atHandler)\n{\n}\n\nUBLOX_PPP_CellularNetwork::~UBLOX_PPP_CellularNetwork()\n{\n}\n\nbool UBLOX_PPP_CellularNetwork::get_modem_stack_type(nsapi_ip_stack_t requested_stack)\n{\n return requested_stack == IPV4_STACK ? true : false;\n}\n\nbool UBLOX_PPP_CellularNetwork::has_registration(RegistrationType reg_type)\n{\n return (reg_type == C_REG || reg_type == C_GREG);\n}\n\nnsapi_error_t UBLOX_LISA_U_CellularNetwork::set_access_technology_impl(RadioAccessTechnology opRat)\n{\n _op_act = RAT_UNKNOWN;\n return NSAPI_ERROR_UNSUPPORTED;\n}\nCellular: Fixed rebase error.\/*\n * Copyright (c) 2017, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\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 \"UBLOX_PPP_CellularNetwork.h\"\n\nusing namespace mbed;\n\nUBLOX_PPP_CellularNetwork::UBLOX_PPP_CellularNetwork(ATHandler &atHandler) : AT_CellularNetwork(atHandler)\n{\n}\n\nUBLOX_PPP_CellularNetwork::~UBLOX_PPP_CellularNetwork()\n{\n}\n\nbool UBLOX_PPP_CellularNetwork::get_modem_stack_type(nsapi_ip_stack_t requested_stack)\n{\n return requested_stack == IPV4_STACK ? true : false;\n}\n\nbool UBLOX_PPP_CellularNetwork::has_registration(RegistrationType reg_type)\n{\n return (reg_type == C_REG || reg_type == C_GREG);\n}\n\nnsapi_error_t UBLOX_PPP_CellularNetwork::set_access_technology_impl(RadioAccessTechnology opRat)\n{\n _op_act = RAT_UNKNOWN;\n return NSAPI_ERROR_UNSUPPORTED;\n}\n<|endoftext|>"} {"text":"#88614# page has a backgroundobject only if it realy has one<|endoftext|>"} {"text":"\/*****************************************************************************\n * menus.hpp : Menus handling\n ****************************************************************************\n * Copyright (C) 2006 the VideoLAN team\n * $Id$\n *\n * Authors: Clément Stenac \n * Jean-Baptiste Kempf \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#ifndef QVLC_MENUS_H_\n#define QVLC_MENUS_H_\n\n#include \"qt4.hpp\"\n\n#include \n#include \n#include \n\n\/* Folder vs. Directory *\/\n#if defined( WIN32 ) || defined(__APPLE__)\n#define I_OPEN_FOLDER N_(\"Open &Folder...\")\n#else\n#define I_OPEN_FOLDER N_(\"Open D&irectory...\")\n#endif \/\/WIN32\n\nusing namespace std;\n\nclass QMenu;\nclass QMenuBar;\nclass QSystemTrayIcon;\n\nclass MenuItemData : public QObject\n{\n Q_OBJECT\n\npublic:\n MenuItemData( QObject* parent, vlc_object_t *_p_obj, int _i_type,\n vlc_value_t _val, const char *_var ) : QObject( parent )\n {\n p_obj = _p_obj;\n i_val_type = _i_type;\n val = _val;\n psz_var = strdup( _var );\n }\n virtual ~MenuItemData()\n {\n free( psz_var );\n if( ( i_val_type & VLC_VAR_TYPE) == VLC_VAR_STRING )\n free( val.psz_string );\n }\n\n vlc_object_t *p_obj;\n vlc_value_t val;\n char *psz_var;\n\nprivate:\n int i_val_type;\n};\n\nclass QVLCMenu : public QObject\n{\n Q_OBJECT;\n friend class MenuFunc;\n\npublic:\n \/* Main bar creation *\/\n static void createMenuBar( MainInterface *mi, intf_thread_t * );\n\n \/* Popups Menus *\/\n static void PopupMenu( intf_thread_t *, bool );\n static void AudioPopupMenu( intf_thread_t * );\n static void VideoPopupMenu( intf_thread_t * );\n static void MiscPopupMenu( intf_thread_t * );\n\n \/* Systray *\/\n static void updateSystrayMenu( MainInterface *,intf_thread_t *,\n bool b_force_visible = false);\n\n \/* Actions *\/\n static void DoAction( QObject * );\n\nprivate:\n \/* All main Menus *\/\n static QMenu *FileMenu( intf_thread_t *, QWidget * );\n static QMenu *SDMenu( intf_thread_t *, QWidget * );\n\n static QMenu *ToolsMenu( QMenu * );\n static QMenu *ToolsMenu( QWidget * );\n\n static QMenu *ViewMenu( intf_thread_t *, MainInterface *,\n bool with = true );\n static QMenu *InterfacesMenu( intf_thread_t *p_intf, QMenu * );\n\n static QMenu *NavigMenu( intf_thread_t *, QMenu * );\n static QMenu *NavigMenu( intf_thread_t *, QWidget * );\n static QMenu *RebuildNavigMenu( intf_thread_t *, QMenu *);\n\n static QMenu *VideoMenu( intf_thread_t *, QMenu * );\n static QMenu *VideoMenu( intf_thread_t *, QWidget * );\n\n static QMenu *AudioMenu( intf_thread_t *, QMenu * );\n static QMenu *AudioMenu( intf_thread_t *, QWidget * );\n\n static QMenu *HelpMenu( QWidget * );\n\n \/* Popups Menus *\/\n static void PopupMenuStaticEntries( QMenu *menu );\n static void PopupPlayEntries( QMenu *menu, intf_thread_t *p_intf,\n input_thread_t *p_input );\n static void PopupMenuControlEntries( QMenu *menu, intf_thread_t *p_intf );\n static void PopupMenuPlaylistControlEntries( QMenu *menu, intf_thread_t *p_intf );\n\n \/* Generic automenu methods *\/\n static QMenu * Populate( intf_thread_t *, QMenu *current,\n vector&, vector& );\n\n static void CreateAndConnect( QMenu *, const char *, QString, QString,\n int, vlc_object_t *, vlc_value_t, int,\n bool c = false );\n static void UpdateItem( intf_thread_t *, QMenu *, const char *,\n vlc_object_t *, bool );\n static int CreateChoicesMenu( QMenu *,const char *, vlc_object_t *, bool );\n\n \/* recentMRL menu *\/\n static QMenu *recentsMenu;\n\npublic slots:\n static void updateRecents( intf_thread_t * );\n};\n\nclass MenuFunc : public QObject\n{\n Q_OBJECT\n\npublic:\n MenuFunc( QMenu *_menu, int _id ) : QObject( (QObject *)_menu ),\n menu( _menu ), id( _id ){}\n\n void doFunc( intf_thread_t *p_intf)\n {\n switch( id )\n {\n case 1: QVLCMenu::AudioMenu( p_intf, menu ); break;\n case 2: QVLCMenu::VideoMenu( p_intf, menu ); break;\n case 3: QVLCMenu::RebuildNavigMenu( p_intf, menu ); break;\n case 4: QVLCMenu::InterfacesMenu( p_intf, menu ); break;\n }\n }\nprivate:\n int id;\n QMenu *menu;\n};\n\n#endif\nQt4: hold objet while the popup menu is active\/*****************************************************************************\n * menus.hpp : Menus handling\n ****************************************************************************\n * Copyright (C) 2006 the VideoLAN team\n * $Id$\n *\n * Authors: Clément Stenac \n * Jean-Baptiste Kempf \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#ifndef QVLC_MENUS_H_\n#define QVLC_MENUS_H_\n\n#include \"qt4.hpp\"\n\n#include \n#include \n#include \n\n\/* Folder vs. Directory *\/\n#if defined( WIN32 ) || defined(__APPLE__)\n#define I_OPEN_FOLDER N_(\"Open &Folder...\")\n#else\n#define I_OPEN_FOLDER N_(\"Open D&irectory...\")\n#endif \/\/WIN32\n\nusing namespace std;\n\nclass QMenu;\nclass QMenuBar;\nclass QSystemTrayIcon;\n\nclass MenuItemData : public QObject\n{\n Q_OBJECT\n\npublic:\n MenuItemData( QObject* parent, vlc_object_t *_p_obj, int _i_type,\n vlc_value_t _val, const char *_var ) : QObject( parent )\n {\n p_obj = _p_obj;\n if( p_obj )\n vlc_object_hold( p_obj );\n i_val_type = _i_type;\n val = _val;\n psz_var = strdup( _var );\n }\n virtual ~MenuItemData()\n {\n free( psz_var );\n if( ( i_val_type & VLC_VAR_TYPE) == VLC_VAR_STRING )\n free( val.psz_string );\n if( p_obj )\n vlc_object_release( p_obj );\n }\n\n vlc_object_t *p_obj;\n vlc_value_t val;\n char *psz_var;\n\nprivate:\n int i_val_type;\n};\n\nclass QVLCMenu : public QObject\n{\n Q_OBJECT;\n friend class MenuFunc;\n\npublic:\n \/* Main bar creation *\/\n static void createMenuBar( MainInterface *mi, intf_thread_t * );\n\n \/* Popups Menus *\/\n static void PopupMenu( intf_thread_t *, bool );\n static void AudioPopupMenu( intf_thread_t * );\n static void VideoPopupMenu( intf_thread_t * );\n static void MiscPopupMenu( intf_thread_t * );\n\n \/* Systray *\/\n static void updateSystrayMenu( MainInterface *,intf_thread_t *,\n bool b_force_visible = false);\n\n \/* Actions *\/\n static void DoAction( QObject * );\n\nprivate:\n \/* All main Menus *\/\n static QMenu *FileMenu( intf_thread_t *, QWidget * );\n static QMenu *SDMenu( intf_thread_t *, QWidget * );\n\n static QMenu *ToolsMenu( QMenu * );\n static QMenu *ToolsMenu( QWidget * );\n\n static QMenu *ViewMenu( intf_thread_t *, MainInterface *,\n bool with = true );\n static QMenu *InterfacesMenu( intf_thread_t *p_intf, QMenu * );\n\n static QMenu *NavigMenu( intf_thread_t *, QMenu * );\n static QMenu *NavigMenu( intf_thread_t *, QWidget * );\n static QMenu *RebuildNavigMenu( intf_thread_t *, QMenu *);\n\n static QMenu *VideoMenu( intf_thread_t *, QMenu * );\n static QMenu *VideoMenu( intf_thread_t *, QWidget * );\n\n static QMenu *AudioMenu( intf_thread_t *, QMenu * );\n static QMenu *AudioMenu( intf_thread_t *, QWidget * );\n\n static QMenu *HelpMenu( QWidget * );\n\n \/* Popups Menus *\/\n static void PopupMenuStaticEntries( QMenu *menu );\n static void PopupPlayEntries( QMenu *menu, intf_thread_t *p_intf,\n input_thread_t *p_input );\n static void PopupMenuControlEntries( QMenu *menu, intf_thread_t *p_intf );\n static void PopupMenuPlaylistControlEntries( QMenu *menu, intf_thread_t *p_intf );\n\n \/* Generic automenu methods *\/\n static QMenu * Populate( intf_thread_t *, QMenu *current,\n vector&, vector& );\n\n static void CreateAndConnect( QMenu *, const char *, QString, QString,\n int, vlc_object_t *, vlc_value_t, int,\n bool c = false );\n static void UpdateItem( intf_thread_t *, QMenu *, const char *,\n vlc_object_t *, bool );\n static int CreateChoicesMenu( QMenu *,const char *, vlc_object_t *, bool );\n\n \/* recentMRL menu *\/\n static QMenu *recentsMenu;\n\npublic slots:\n static void updateRecents( intf_thread_t * );\n};\n\nclass MenuFunc : public QObject\n{\n Q_OBJECT\n\npublic:\n MenuFunc( QMenu *_menu, int _id ) : QObject( (QObject *)_menu ),\n menu( _menu ), id( _id ){}\n\n void doFunc( intf_thread_t *p_intf)\n {\n switch( id )\n {\n case 1: QVLCMenu::AudioMenu( p_intf, menu ); break;\n case 2: QVLCMenu::VideoMenu( p_intf, menu ); break;\n case 3: QVLCMenu::RebuildNavigMenu( p_intf, menu ); break;\n case 4: QVLCMenu::InterfacesMenu( p_intf, menu ); break;\n }\n }\nprivate:\n int id;\n QMenu *menu;\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \nusing namespace liu;\n\nstatic std::vector timestamps;\nstatic buffer_t bloberino;\n\nstatic void boot_save(Storage& storage, const buffer_t* blob)\n{\n timestamps.push_back(OS::nanos_since_boot());\n storage.add_vector(0, timestamps);\n assert(blob != nullptr);\n storage.add_buffer(2, *blob);\n}\nstatic void boot_resume_all(Restore& thing)\n{\n timestamps = thing.as_vector(); thing.go_next();\n \/\/ calculate time spent\n auto t1 = timestamps.back();\n auto t2 = OS::nanos_since_boot();\n \/\/ set final time\n timestamps.back() = t2 - t1;\n \/\/ retrieve old blob\n bloberino = thing.as_buffer(); thing.go_next();\n\n thing.pop_marker();\n}\n\nLiveUpdate::storage_func begin_test_boot()\n{\n if (LiveUpdate::resume(\"test\", boot_resume_all))\n {\n if (timestamps.size() >= 30)\n {\n \/\/ calculate median by sorting\n std::sort(timestamps.begin(), timestamps.end());\n auto median = timestamps[timestamps.size()\/2];\n \/\/ show information\n printf(\"Median boot time over %lu samples: %.2f millis\\n\",\n timestamps.size(), median \/ 1000000.0);\n \/*\n for (auto& stamp : timestamps) {\n printf(\"%lld\\n\", stamp);\n }\n *\/\n printf(\"SUCCESS\\n\");\n OS::shutdown();\n }\n else {\n \/\/ immediately liveupdate\n LiveUpdate::exec(bloberino, \"test\", boot_save);\n }\n }\n \/\/ wait for update\n return boot_save;\n}\ntest: Verify timers are started after live update#include \n#include \n#include \nusing namespace liu;\n\nstatic std::vector timestamps;\nstatic buffer_t bloberino;\n\nstatic void boot_save(Storage& storage, const buffer_t* blob)\n{\n timestamps.push_back(OS::nanos_since_boot());\n storage.add_vector(0, timestamps);\n assert(blob != nullptr);\n storage.add_buffer(2, *blob);\n}\nstatic void boot_resume_all(Restore& thing)\n{\n timestamps = thing.as_vector(); thing.go_next();\n \/\/ calculate time spent\n auto t1 = timestamps.back();\n auto t2 = OS::nanos_since_boot();\n \/\/ set final time\n timestamps.back() = t2 - t1;\n \/\/ retrieve old blob\n bloberino = thing.as_buffer(); thing.go_next();\n\n thing.pop_marker();\n}\n\nLiveUpdate::storage_func begin_test_boot()\n{\n if (LiveUpdate::resume(\"test\", boot_resume_all))\n {\n if (timestamps.size() >= 30)\n {\n \/\/ calculate median by sorting\n std::sort(timestamps.begin(), timestamps.end());\n auto median = timestamps[timestamps.size()\/2];\n \/\/ show information\n printf(\"Median boot time over %lu samples: %.2f millis\\n\",\n timestamps.size(), median \/ 1000000.0);\n \/*\n for (auto& stamp : timestamps) {\n printf(\"%lld\\n\", stamp);\n }\n *\/\n printf(\"Verifying that timers are started...\\n\");\n using namespace std::chrono;\n Timers::oneshot(5ms,[] (int) {\n printf(\"SUCCESS\\n\");\n OS::shutdown();\n });\n }\n else {\n \/\/ immediately liveupdate\n LiveUpdate::exec(bloberino, \"test\", boot_save);\n }\n }\n \/\/ wait for update\n return boot_save;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5pp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Author: Jan Kotanski \n\/\/ Created on: Nov 12, 2018\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace hdf5;\nnamespace fs = boost::filesystem;\n\nclass DatasetReadSpeedTest : public testing::Test\n{\n protected:\n virtual void SetUp()\n {\n#if H5_VERSION_GE(1, 10, 0)\n property::FileCreationList fcpl;\n property::FileAccessList fapl;\n property::DatasetCreationList dcpl;\n property::LinkCreationList lcpl;\n property::DatasetAccessList dapl;\n fapl.library_version_bounds(property::LibVersion::LATEST,\n property::LibVersion::LATEST);\n file::File f = file::create(\"dataset_read_speed.h5\", file::AccessFlags::TRUNCATE, fcpl, fapl);\n#else\n file::File f = file::create(\"dataset_read_speed.h5\", file::AccessFlags::TRUNCATE);\n#endif\n node::Group root = f.root();\n long long unsigned int xdim = 867;\n long long unsigned int ydim = 700;\n long long unsigned int nframe = 33;\n\n dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,\n\t dataspace::Simple::UNLIMITED,\n\t dataspace::Simple::UNLIMITED}};\n dcpl.layout(property::DatasetLayout::CHUNKED);\n dcpl.chunk({1, xdim, ydim});\n node::Dataset data = node::Dataset(root,\n\t\t\t\t \"data\",\n\t\t\t\t datatype::create(),\n\t\t\t\t space,lcpl,dcpl,dapl);\n std::vector frame(xdim*ydim);\n dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}};\n for(long long unsigned int i = 0; i != nframe; i++){\n data.extent(0, 1);\n framespace.offset({i, 0, 0});\n data.write(frame, framespace);\n\n }\n }\n};\n\n\nTEST_F(DatasetReadSpeedTest, read)\n{\n struct timeval stime1;\n struct timeval etime1;\n struct timeval stime0;\n struct timeval etime0;\n\n file::File f0 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root0 = f0.root();\n auto dataset0 = root0.get_dataset(\"\/data\");\n hdf5::dataspace::Simple dataspace(dataset0.dataspace());\n const auto dims = dataspace.current_dimensions();\n std::vector buffer(dims[0]*dims[1]*dims[2]);\n auto datatype = dataset0.datatype();\n\n hdf5::Dimensions frameoffset{0, 0, 0};\n hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]};\n hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};\n \/\/ time0\n gettimeofday(&stime0, NULL);\n dataset0.read(buffer, datatype, dataspace, selected_frames);\n gettimeofday(&etime0, NULL);\n f0.close();\n\n file::File f1 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root1 = f1.root();\n auto dataset1 = root1.get_dataset(\"\/data\");\n \/\/ time1\n gettimeofday(&stime1, NULL);\n dataset1.read(buffer);\n gettimeofday(&etime1, NULL);\n f1.close();\n\n double time0 = (double)(etime0.tv_sec - stime0.tv_sec)\n + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;\n double time1 = (double)(etime1.tv_sec - stime1.tv_sec)\n + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;\n\n EXPECT_GT(2*time1, time0);\n EXPECT_GT(2*time0, time1);\n}\n\nTEST_F(DatasetReadSpeedTest, read_hyperslab)\n{\n struct timeval stime1;\n struct timeval etime1;\n struct timeval stime0;\n struct timeval etime0;\n\n file::File f0 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root0 = f0.root();\n auto dataset0 = root0.get_dataset(\"\/data\");\n hdf5::dataspace::Simple dataspace(dataset0.dataspace());\n const auto dims = dataspace.current_dimensions();\n std::vector buffer(11*dims[1]*dims[2]);\n auto datatype = dataset0.datatype();\n\n hdf5::Dimensions frameoffset{10, 0, 0};\n hdf5::Dimensions frameblock{11, dims[1], dims[2]};\n hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};\n dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]}));\n \/\/ time0\n gettimeofday(&stime0, NULL);\n dataset0.read(buffer, datatype, dataspace0, selected_frames);\n gettimeofday(&etime0, NULL);\n f0.close();\n\n file::File f1 = file::open(\"dataset_read_speed.h5\",\n \t\t\t file::AccessFlags::READONLY);\n auto root1 = f1.root();\n auto dataset1 = root1.get_dataset(\"\/data\");\n \/\/ time1\n gettimeofday(&stime1, NULL);\n dataset1.read(buffer, selected_frames);\n gettimeofday(&etime1, NULL);\n f1.close();\n\n double time0 = (double)(etime0.tv_sec - stime0.tv_sec)\n + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;\n double time1 = (double)(etime1.tv_sec - stime1.tv_sec)\n + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;\n\n EXPECT_GT(2*time1, time0);\n EXPECT_GT(2*time0, time1);\n}\nrelax tests\/\/\n\/\/ (c) Copyright 2017 DESY,ESS\n\/\/\n\/\/ This file is part of h5pp.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this library; if not, write to the\n\/\/ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor\n\/\/ Boston, MA 02110-1301 USA\n\/\/ ===========================================================================\n\/\/\n\/\/ Author: Jan Kotanski \n\/\/ Created on: Nov 12, 2018\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace hdf5;\nnamespace fs = boost::filesystem;\n\nclass DatasetReadSpeedTest : public testing::Test\n{\n protected:\n virtual void SetUp()\n {\n#if H5_VERSION_GE(1, 10, 0)\n property::FileCreationList fcpl;\n property::FileAccessList fapl;\n property::DatasetCreationList dcpl;\n property::LinkCreationList lcpl;\n property::DatasetAccessList dapl;\n fapl.library_version_bounds(property::LibVersion::LATEST,\n property::LibVersion::LATEST);\n file::File f = file::create(\"dataset_read_speed.h5\", file::AccessFlags::TRUNCATE, fcpl, fapl);\n#else\n file::File f = file::create(\"dataset_read_speed.h5\", file::AccessFlags::TRUNCATE);\n#endif\n node::Group root = f.root();\n long long unsigned int xdim = 867;\n long long unsigned int ydim = 700;\n long long unsigned int nframe = 33;\n\n dataspace::Simple space {{0, xdim, ydim}, {dataspace::Simple::UNLIMITED,\n\t dataspace::Simple::UNLIMITED,\n\t dataspace::Simple::UNLIMITED}};\n dcpl.layout(property::DatasetLayout::CHUNKED);\n dcpl.chunk({1, xdim, ydim});\n node::Dataset data = node::Dataset(root,\n\t\t\t\t \"data\",\n\t\t\t\t datatype::create(),\n\t\t\t\t space,lcpl,dcpl,dapl);\n std::vector frame(xdim*ydim);\n dataspace::Hyperslab framespace{{0, 0, 0}, {1, xdim, ydim}};\n for(long long unsigned int i = 0; i != nframe; i++){\n data.extent(0, 1);\n framespace.offset({i, 0, 0});\n data.write(frame, framespace);\n\n }\n }\n};\n\n#ifndef _MSC_VER\nTEST_F(DatasetReadSpeedTest, read)\n{\n struct timeval stime1;\n struct timeval etime1;\n struct timeval stime0;\n struct timeval etime0;\n\n file::File f0 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root0 = f0.root();\n auto dataset0 = root0.get_dataset(\"\/data\");\n hdf5::dataspace::Simple dataspace(dataset0.dataspace());\n const auto dims = dataspace.current_dimensions();\n std::vector buffer(dims[0]*dims[1]*dims[2]);\n auto datatype = dataset0.datatype();\n\n hdf5::Dimensions frameoffset{0, 0, 0};\n hdf5::Dimensions frameblock{dims[0], dims[1], dims[2]};\n hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};\n \/\/ time0\n gettimeofday(&stime0, NULL);\n dataset0.read(buffer, datatype, dataspace, selected_frames);\n gettimeofday(&etime0, NULL);\n f0.close();\n\n file::File f1 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root1 = f1.root();\n auto dataset1 = root1.get_dataset(\"\/data\");\n \/\/ time1\n gettimeofday(&stime1, NULL);\n dataset1.read(buffer);\n gettimeofday(&etime1, NULL);\n f1.close();\n\n double time0 = (double)(etime0.tv_sec - stime0.tv_sec)\n + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;\n double time1 = (double)(etime1.tv_sec - stime1.tv_sec)\n + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;\n\n EXPECT_GT(8*time1, time0);\n EXPECT_GT(8*time0, time1);\n}\n\nTEST_F(DatasetReadSpeedTest, read_hyperslab)\n{\n struct timeval stime1;\n struct timeval etime1;\n struct timeval stime0;\n struct timeval etime0;\n\n file::File f0 = file::open(\"dataset_read_speed.h5\",\n\t\t\t file::AccessFlags::READONLY);\n auto root0 = f0.root();\n auto dataset0 = root0.get_dataset(\"\/data\");\n hdf5::dataspace::Simple dataspace(dataset0.dataspace());\n const auto dims = dataspace.current_dimensions();\n std::vector buffer(11*dims[1]*dims[2]);\n auto datatype = dataset0.datatype();\n\n hdf5::Dimensions frameoffset{10, 0, 0};\n hdf5::Dimensions frameblock{11, dims[1], dims[2]};\n hdf5::dataspace::Hyperslab selected_frames{frameoffset, frameblock};\n dataspace::Simple dataspace0(Dimensions({11, dims[1], dims[2]}));\n \/\/ time0\n gettimeofday(&stime0, NULL);\n dataset0.read(buffer, datatype, dataspace0, selected_frames);\n gettimeofday(&etime0, NULL);\n f0.close();\n\n file::File f1 = file::open(\"dataset_read_speed.h5\",\n \t\t\t file::AccessFlags::READONLY);\n auto root1 = f1.root();\n auto dataset1 = root1.get_dataset(\"\/data\");\n \/\/ time1\n gettimeofday(&stime1, NULL);\n dataset1.read(buffer, selected_frames);\n gettimeofday(&etime1, NULL);\n f1.close();\n\n double time0 = (double)(etime0.tv_sec - stime0.tv_sec)\n + (double)(etime0.tv_usec - stime0.tv_usec)*0.000001;\n double time1 = (double)(etime1.tv_sec - stime1.tv_sec)\n + (double)(etime1.tv_usec - stime1.tv_usec)*0.000001;\n\n EXPECT_GT(8*time1, time0);\n EXPECT_GT(8*time0, time1);\n}\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\nclass test_vari : public vari {\n public:\n explicit test_vari() : vari(0.0) {\n }\n\n virtual void chain() {\n stan::math::nested_rev_autodiff nested;\n\n \/\/ Add enough vars to make the the var_stack_ vector reallocate\n int N_new_vars = ChainableStack::instance_->var_stack_.capacity() + 1;\n \n var total = 0.0;\n for (int i = 0; i < N_new_vars; ++i) {\n total += i;\n }\n\n total.grad();\n }\n};\n\n}\n}\n\nTEST(AgradRev, grad_in_reverse_mode) {\n using stan::math::var;\n\n var total = 0.0;\n for (int i = 0; i < 2; ++i) {\n total += i;\n }\n\n var test_var(new stan::math::test_vari());\n\n test_var.grad();\n}\n[Jenkins] auto-formatting by clang-format version 6.0.0#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\nclass test_vari : public vari {\n public:\n explicit test_vari() : vari(0.0) {}\n\n virtual void chain() {\n stan::math::nested_rev_autodiff nested;\n\n \/\/ Add enough vars to make the the var_stack_ vector reallocate\n int N_new_vars = ChainableStack::instance_->var_stack_.capacity() + 1;\n\n var total = 0.0;\n for (int i = 0; i < N_new_vars; ++i) {\n total += i;\n }\n\n total.grad();\n }\n};\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\nTEST(AgradRev, grad_in_reverse_mode) {\n using stan::math::var;\n\n var total = 0.0;\n for (int i = 0; i < 2; ++i) {\n total += i;\n }\n\n var test_var(new stan::math::test_vari());\n\n test_var.grad();\n}\n<|endoftext|>"} {"text":"#include \"test_helper.h\"\n\n#include \n#include \n#include \n\n#include \"log.h\"\n\nconst char *molds[] = {\n \"basic_keyval\",\n \"basic_section\",\n \"json_test_mold\",\n \"restriction_keyval_numeric_types\",\n \"restriction_entries\",\n \"restriction_config_parent_keyval_min_entry\",\n \"restriction_config_parent_keyval_max_entry\",\n \"restriction_config_parent_section_max_entry\",\n \"restriction_section_parent_keyval_max_entry\",\n \"basic_version_difference\",\n \"complex_section\",\n \"config_query_permutations\",\n};\n\nclass SerializeUnserializeTest : public ::testing::DisirTestTestPlugin,\n public ::testing::WithParamInterface\n{\npublic:\n void serialize_unserialize_config (const char *entry,\n dio_serialize_config func_serialize,\n dio_unserialize_config func_unserialize)\n {\n struct disir_config *config_original = NULL;\n struct disir_config *config_parsed = NULL;\n struct disir_context *context_config1 = NULL;\n struct disir_context *context_config2 = NULL;\n FILE *file = NULL;\n struct disir_mold *mold = NULL;\n\n log_test (\"SerializeUnserialize %s\", entry);\n\n \/\/ read the current entry\n status = disir_config_read (instance, \"test\", entry,\n NULL, &config_original);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n {\n log_test (\"config_read failed: %s\", disir_status_string (status));\n goto out;\n }\n\n \/\/ open file for reading and writing\n char filepath[4098];\n snprintf (filepath, 4098, \"\/tmp\/disir_plugin_serialize_unserialize_%s.toml\", entry);\n file = fopen (filepath, \"w+\");\n EXPECT_TRUE (file != NULL);\n if (file == NULL)\n {\n log_test (\"Failed to open file...\");\n goto out;\n }\n\n \/\/ Serialize the current entry config\n status = func_serialize (instance, config_original, file);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n \/\/ Unserialize the previously serialized config\n \/\/ XXX: Cheat by extracting the mold directly from the config.\n mold = config_original->cf_mold;\n fseek (file, 0, SEEK_SET);\n status = func_unserialize (instance, file, mold, &config_parsed);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n \/\/ compare the two\n context_config1 = dc_config_getcontext (config_original);\n context_config2 = dc_config_getcontext (config_parsed);\n EXPECT_TRUE (context_config1 != NULL);\n EXPECT_TRUE (context_config2 != NULL);\n if (context_config1 == NULL || context_config2 == NULL)\n goto out;\n status = dc_compare (context_config1, context_config2, NULL);\n EXPECT_STATUS (DISIR_STATUS_OK, status)\n\n out:\n log_test (\"compare serialize-unserialize out clause\");\n \/\/ Cleanup this entry and move to the next\n if (file != NULL)\n {\n fclose (file);\n }\n dc_putcontext (&context_config1);\n dc_putcontext (&context_config2);\n disir_config_finished (&config_original);\n disir_config_finished (&config_parsed);\n }\n};\n\nTEST_P(SerializeUnserializeTest, toml)\n{\n const char *key= GetParam();\n\n ASSERT_NO_FATAL_FAILURE (\n serialize_unserialize_config (key, dio_toml_serialize_config, dio_toml_unserialize_config);\n );\n}\n\nTEST_P(SerializeUnserializeTest, config_json)\n{\n const char *key= GetParam();\n\n ASSERT_NO_FATAL_FAILURE (\n serialize_unserialize_config (key, dio_json_serialize_config, dio_json_unserialize_config);\n );\n}\n\nINSTANTIATE_TEST_CASE_P(MoldKey, SerializeUnserializeTest, ::testing::ValuesIn(molds));\n\nplugin test: Mold serialize\/unserialize test#include \"test_helper.h\"\n\n#include \n#include \n#include \n\n#include \"log.h\"\n\nconst char *molds[] = {\n \"basic_keyval\",\n \"basic_section\",\n \"json_test_mold\",\n \"restriction_keyval_numeric_types\",\n \"restriction_entries\",\n \"restriction_config_parent_keyval_min_entry\",\n \"restriction_config_parent_keyval_max_entry\",\n \"restriction_config_parent_section_max_entry\",\n \"restriction_section_parent_keyval_max_entry\",\n \"basic_version_difference\",\n \"complex_section\",\n \"config_query_permutations\",\n};\n\nclass SerializeUnserializeTest : public ::testing::DisirTestTestPlugin,\n public ::testing::WithParamInterface\n{\npublic:\n void serialize_unserialize_mold (const char *entry,\n const char *suffix,\n dio_serialize_mold func_serialize,\n dio_unserialize_mold func_unserialize)\n {\n struct disir_mold *mold_original = NULL;\n struct disir_mold *mold_parsed = NULL;\n struct disir_context *context_mold1 = NULL;\n struct disir_context *context_mold2 = NULL;\n FILE *file = NULL;\n\n log_test (\"SerializeUnserialize mold %s\", entry);\n\n status = disir_mold_read (instance, \"test\", entry, &mold_original);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n {\n log_test (\"mold_read failed: %s\", disir_status_string (status));\n goto out;\n }\n\n char filepath[4098];\n snprintf (filepath, 4098, \"\/tmp\/disir_plugin_serialize_unserialize_%s.%s\", entry, suffix);\n file = fopen (filepath, \"w+\");\n EXPECT_TRUE (file != NULL);\n if (file == NULL)\n {\n log_test (\"Failed to open file...\");\n goto out;\n }\n status = func_serialize (instance, mold_original, file);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n fseek (file, 0, SEEK_SET);\n\n status = func_unserialize (instance, file, &mold_parsed);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n context_mold1 = dc_mold_getcontext (mold_original);\n context_mold2 = dc_mold_getcontext (mold_parsed);\n EXPECT_TRUE (context_mold1 != NULL);\n EXPECT_TRUE (context_mold2 != NULL);\n if (context_mold1 == NULL || context_mold2 == NULL)\n goto out;\n\n status = dc_compare (context_mold1, context_mold2, NULL);\n EXPECT_STATUS (DISIR_STATUS_OK, status)\n out:\n log_test (\"compare serialize-unserialize mold out clause\");\n \/\/ Cleanup this entry and move to the next\n if (file != NULL)\n {\n fclose (file);\n }\n dc_putcontext (&context_mold1);\n dc_putcontext (&context_mold2);\n disir_mold_finished (&mold_original);\n disir_mold_finished (&mold_parsed);\n }\n\n void serialize_unserialize_config (const char *entry,\n dio_serialize_config func_serialize,\n dio_unserialize_config func_unserialize)\n {\n struct disir_config *config_original = NULL;\n struct disir_config *config_parsed = NULL;\n struct disir_context *context_config1 = NULL;\n struct disir_context *context_config2 = NULL;\n FILE *file = NULL;\n struct disir_mold *mold = NULL;\n\n log_test (\"SerializeUnserialize %s\", entry);\n\n \/\/ read the current entry\n status = disir_config_read (instance, \"test\", entry,\n NULL, &config_original);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n {\n log_test (\"config_read failed: %s\", disir_status_string (status));\n goto out;\n }\n\n \/\/ open file for reading and writing\n char filepath[4098];\n snprintf (filepath, 4098, \"\/tmp\/disir_plugin_serialize_unserialize_%s.toml\", entry);\n file = fopen (filepath, \"w+\");\n EXPECT_TRUE (file != NULL);\n if (file == NULL)\n {\n log_test (\"Failed to open file...\");\n goto out;\n }\n\n \/\/ Serialize the current entry config\n status = func_serialize (instance, config_original, file);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n \/\/ Unserialize the previously serialized config\n \/\/ XXX: Cheat by extracting the mold directly from the config.\n mold = config_original->cf_mold;\n fseek (file, 0, SEEK_SET);\n status = func_unserialize (instance, file, mold, &config_parsed);\n EXPECT_STATUS (DISIR_STATUS_OK, status);\n if (status != DISIR_STATUS_OK)\n goto out;\n\n \/\/ compare the two\n context_config1 = dc_config_getcontext (config_original);\n context_config2 = dc_config_getcontext (config_parsed);\n EXPECT_TRUE (context_config1 != NULL);\n EXPECT_TRUE (context_config2 != NULL);\n if (context_config1 == NULL || context_config2 == NULL)\n goto out;\n status = dc_compare (context_config1, context_config2, NULL);\n EXPECT_STATUS (DISIR_STATUS_OK, status)\n\n out:\n log_test (\"compare serialize-unserialize out clause\");\n \/\/ Cleanup this entry and move to the next\n if (file != NULL)\n {\n fclose (file);\n }\n dc_putcontext (&context_config1);\n dc_putcontext (&context_config2);\n disir_config_finished (&config_original);\n disir_config_finished (&config_parsed);\n }\n};\n\nTEST_P(SerializeUnserializeTest, toml)\n{\n const char *key= GetParam();\n\n ASSERT_NO_FATAL_FAILURE (\n serialize_unserialize_config (key, dio_toml_serialize_config, dio_toml_unserialize_config);\n );\n}\n\nTEST_P(SerializeUnserializeTest, config_json)\n{\n const char *key= GetParam();\n\n ASSERT_NO_FATAL_FAILURE (\n serialize_unserialize_config (key, dio_json_serialize_config, dio_json_unserialize_config);\n );\n}\n\nTEST_P(SerializeUnserializeTest, mold_json)\n{\n const char *key= GetParam();\n\n ASSERT_NO_FATAL_FAILURE (\n serialize_unserialize_mold (key, \"json\", dio_json_serialize_mold, dio_json_unserialize_mold);\n );\n}\n\nINSTANTIATE_TEST_CASE_P(MoldKey, SerializeUnserializeTest, ::testing::ValuesIn(molds));\n\n<|endoftext|>"} {"text":"#include \n\n#define CATCH_CONFIG_MAIN\n#include \n\nstruct FibContext;\n\n\/\/ declare data type for fibonacci\ntypedef unsigned long long fib_type;\n\nstruct FibStep\n{\n int execute(const int &tag, FibContext &context) const;\n};\n\nstruct FibContext : public CnC::Context\n{\n CnC::StepCollection steps;\n CnC::ItemCollection fibs;\n\n FibContext() : CnC::Context(), \n steps(*this), \n fibs()\n {\n }\n};\n\nint FibStep::execute(const int &tag, FibContext &context) const\n{\n \/\/ std::cout << \"start \" << tag << std::endl;\n\n \/\/ get previous 2 results\n fib_type f_1; context.fibs.get(tag - 1, f_1);\n fib_type f_2; context.fibs.get(tag - 2, f_2);\n\n \/\/ std::cout << f_1 << \" + \" << f_2 << \" = \" << (f_1 + f_2) << std::endl;\n\n \/\/ put our result\n context.fibs.put(tag, f_1 + f_2);\n\n \/\/ std::cout << \"end \" << tag << std::endl;\n\n return 0;\n}\n\nTEST_CASE(\"Get fibonacci number\", \"[fib]\")\n{\n int n = 42;\n\n \/\/ create context\n FibContext context;\n\n \/\/ seed\n context.fibs.put(0, 0);\n context.fibs.put(1, 1);\n\n \/\/ put tags to initiate evaluation\n for (int i = 2; i <= n; ++i)\n context.steps.put(i);\n\n \/\/ wait for completion\n uv_run(uv_default_loop(), UV_RUN_DEFAULT);\n\n \/\/ get result\n fib_type result;\n context.fibs.get(n, result);\n\n \/\/ check result\n REQUIRE(result == 267914296);\n}fib example (not test)#include \n\nstruct FibContext;\n\n\/\/ declare data type for fibonacci\ntypedef unsigned long long fib_type;\n\nstruct FibStep\n{\n int execute(const int &tag, FibContext &context) const;\n};\n\nstruct FibContext : public CnC::Context\n{\n CnC::StepCollection steps;\n CnC::ItemCollection fibs;\n\n FibContext() : CnC::Context(), \n steps(*this), \n fibs()\n {\n }\n};\n\nint FibStep::execute(const int &tag, FibContext &context) const\n{\n \/\/ std::cout << \"start \" << tag << std::endl;\n\n \/\/ get previous 2 results\n fib_type f_1; context.fibs.get(tag - 1, f_1);\n fib_type f_2; context.fibs.get(tag - 2, f_2);\n\n \/\/ std::cout << f_1 << \" + \" << f_2 << \" = \" << (f_1 + f_2) << std::endl;\n\n \/\/ put our result\n context.fibs.put(tag, f_1 + f_2);\n\n \/\/ std::cout << \"end \" << tag << std::endl;\n\n return 0;\n}\n\nint main()\n{\n const int n = 42;\n\n \/\/ create context\n FibContext context;\n\n \/\/ seed\n context.fibs.put(0, 0);\n context.fibs.put(1, 1);\n\n \/\/ put tags to initiate evaluation\n for (int i = 2; i <= n; ++i)\n context.steps.put(i);\n\n \/\/ wait for completion\n uv_run(uv_default_loop(), UV_RUN_DEFAULT);\n\n \/\/ get result\n fib_type result;\n context.fibs.get(n, result);\n\n \/\/ check result\n\tif (result == 267914296)\n\t\tstd::cout << \"fib(\" << n << \") = \" << result << std::endl;\n\telse\n\t\tstd::cout << \"wrong answer: \" << result << std::endl;\n}<|endoftext|>"} {"text":"\/\/\n\/\/ ASTInstructionBlockNode.cpp\n\/\/ lut-lang\n\/\/\n\/\/ Created by Robin Ricard on 22\/03\/15.\n\/\/ Copyright (c) 2015 INSA Lyon. All rights reserved.\n\/\/\n\n#include \"ASTInstructionBlockNode.h\"\n\n#include \n\nusing std::cout;\nusing std::endl;\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = expression;\n this->identifier = NULL;\n this->prev = prev;\n}\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTTokenNode* identifier,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = NULL;\n this->identifier = identifier;\n this->prev = prev;\n}\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,\n ASTTokenNode* identifier,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = expression;\n this->identifier = identifier;\n this->prev = prev;\n}\n\nASTFirstLevelExpressionNode* ASTInstructionBlockNode::getExpression() {\n return this->expression;\n}\n\nASTTokenNode* ASTInstructionBlockNode::getIdentifier() {\n return this->identifier;\n}\n\nASTInstructionBlockNode* ASTInstructionBlockNode::getPrev() {\n return this->prev;\n}\n\nbool ASTInstructionBlockNode::analyze(analyze_table* table) {\n return true;\n}\n\nint64_t ASTInstructionBlockNode::exec(exec_table* table) {\n return 0;\n}\n\nvoid ASTInstructionBlockNode::print() {\n if (this->expression != NULL && this->identifier != NULL) { \/\/ Assignment\n this->identifier->print();\n cout << \" := \";\n this->expression->print();\n } else if (this->expression != NULL) { \/\/ Write\n cout << \"ecrire \";\n this->expression->print();\n } else if (this->identifier != NULL) { \/\/ Read\n cout << \"lire \";\n this->identifier->print();\n }\n cout << \";\" << endl;\n}\nPrev inst print\/\/\n\/\/ ASTInstructionBlockNode.cpp\n\/\/ lut-lang\n\/\/\n\/\/ Created by Robin Ricard on 22\/03\/15.\n\/\/ Copyright (c) 2015 INSA Lyon. All rights reserved.\n\/\/\n\n#include \"ASTInstructionBlockNode.h\"\n\n#include \n\nusing std::cout;\nusing std::endl;\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = expression;\n this->identifier = NULL;\n this->prev = prev;\n}\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTTokenNode* identifier,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = NULL;\n this->identifier = identifier;\n this->prev = prev;\n}\n\nASTInstructionBlockNode::ASTInstructionBlockNode(ASTFirstLevelExpressionNode* expression,\n ASTTokenNode* identifier,\n ASTInstructionBlockNode* prev,\n TokenType type) : ASTNode(type) {\n this->expression = expression;\n this->identifier = identifier;\n this->prev = prev;\n}\n\nASTFirstLevelExpressionNode* ASTInstructionBlockNode::getExpression() {\n return this->expression;\n}\n\nASTTokenNode* ASTInstructionBlockNode::getIdentifier() {\n return this->identifier;\n}\n\nASTInstructionBlockNode* ASTInstructionBlockNode::getPrev() {\n return this->prev;\n}\n\nbool ASTInstructionBlockNode::analyze(analyze_table* table) {\n return true;\n}\n\nint64_t ASTInstructionBlockNode::exec(exec_table* table) {\n return 0;\n}\n\nvoid ASTInstructionBlockNode::print() {\n if (this->prev != NULL) {\n this->prev->print();\n }\n if (this->expression != NULL && this->identifier != NULL) { \/\/ Assignment\n this->identifier->print();\n cout << \" := \";\n this->expression->print();\n } else if (this->expression != NULL) { \/\/ Write\n cout << \"ecrire \";\n this->expression->print();\n } else if (this->identifier != NULL) { \/\/ Read\n cout << \"lire \";\n this->identifier->print();\n }\n cout << \";\" << endl;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iree\/compiler\/Dialect\/HAL\/Conversion\/StandardToHAL\/ConvertStandardToHAL.h\"\n#include \"iree\/compiler\/Dialect\/HAL\/IR\/HALOps.h\"\n#include \"iree\/compiler\/Dialect\/HAL\/IR\/HALTypes.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\"\n#include \"mlir\/IR\/Attributes.h\"\n#include \"mlir\/IR\/BlockAndValueMapping.h\"\n#include \"mlir\/IR\/Builders.h\"\n#include \"mlir\/IR\/BuiltinOps.h\"\n#include \"mlir\/IR\/Matchers.h\"\n#include \"mlir\/Transforms\/DialectConversion.h\"\n\nnamespace mlir {\nnamespace iree_compiler {\nnamespace {\n\nclass FuncOpSignatureConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::FuncOp funcOp, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n auto &typeConverter = *getTypeConverter();\n\n \/\/ Convert the input signature types.\n \/\/ TODO(benvanik): dynamic shapes by passing in tensor dynamic dims.\n auto originalType = funcOp.getType();\n TypeConverter::SignatureConversion newSignature(\n originalType.getNumInputs());\n for (auto argType : llvm::enumerate(originalType.getInputs())) {\n if (failed(typeConverter.convertSignatureArg(\n argType.index(), argType.value(), newSignature))) {\n return failure();\n }\n }\n SmallVector newResultTypes;\n if (failed(typeConverter.convertTypes(originalType.getResults(),\n newResultTypes))) {\n return failure();\n }\n\n \/\/ Replace function.\n auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);\n newFuncOp.getBlocks().clear();\n rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),\n newFuncOp.end());\n newFuncOp.setType(rewriter.getFunctionType(newSignature.getConvertedTypes(),\n newResultTypes));\n if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,\n &newSignature))) {\n return failure();\n }\n\n rewriter.eraseOp(funcOp);\n return success();\n }\n};\n\nclass CallOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::CallOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::CallOpAdaptor adaptor(operands);\n SmallVector resultTypes;\n if (failed(getTypeConverter()->convertTypes(op.getResultTypes(),\n resultTypes))) {\n return rewriter.notifyMatchFailure(op, \"unable to convert result types\");\n }\n rewriter.replaceOpWithNewOp(op, resultTypes, op.callee(),\n adaptor.operands());\n return success();\n }\n};\n\nclass BranchOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::BranchOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::BranchOpAdaptor adaptor(operands);\n rewriter.replaceOpWithNewOp(op, op.dest(),\n adaptor.destOperands());\n return success();\n }\n};\n\nclass CondBranchOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::CondBranchOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::CondBranchOpAdaptor adaptor(operands,\n op.getOperation()->getAttrDictionary());\n rewriter.replaceOpWithNewOp(\n op, adaptor.condition(), op.trueDest(), adaptor.trueDestOperands(),\n op.falseDest(), op.falseDestOperands());\n return success();\n }\n};\n\nclass ReturnOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::ReturnOp returnOp, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n rewriter.replaceOpWithNewOp(returnOp, operands);\n return success();\n }\n};\n\n} \/\/ namespace\n\nvoid populateStandardStructuralToHALPatterns(MLIRContext *context,\n OwningRewritePatternList &patterns,\n TypeConverter &converter) {\n patterns\n .insert(converter, context);\n}\n\n} \/\/ namespace iree_compiler\n} \/\/ namespace mlir\nUse adaptor when converting cond_br (latent bug). (#5875)\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iree\/compiler\/Dialect\/HAL\/Conversion\/StandardToHAL\/ConvertStandardToHAL.h\"\n#include \"iree\/compiler\/Dialect\/HAL\/IR\/HALOps.h\"\n#include \"iree\/compiler\/Dialect\/HAL\/IR\/HALTypes.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"mlir\/Dialect\/StandardOps\/IR\/Ops.h\"\n#include \"mlir\/IR\/Attributes.h\"\n#include \"mlir\/IR\/BlockAndValueMapping.h\"\n#include \"mlir\/IR\/Builders.h\"\n#include \"mlir\/IR\/BuiltinOps.h\"\n#include \"mlir\/IR\/Matchers.h\"\n#include \"mlir\/Transforms\/DialectConversion.h\"\n\nnamespace mlir {\nnamespace iree_compiler {\nnamespace {\n\nclass FuncOpSignatureConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::FuncOp funcOp, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n auto &typeConverter = *getTypeConverter();\n\n \/\/ Convert the input signature types.\n \/\/ TODO(benvanik): dynamic shapes by passing in tensor dynamic dims.\n auto originalType = funcOp.getType();\n TypeConverter::SignatureConversion newSignature(\n originalType.getNumInputs());\n for (auto argType : llvm::enumerate(originalType.getInputs())) {\n if (failed(typeConverter.convertSignatureArg(\n argType.index(), argType.value(), newSignature))) {\n return failure();\n }\n }\n SmallVector newResultTypes;\n if (failed(typeConverter.convertTypes(originalType.getResults(),\n newResultTypes))) {\n return failure();\n }\n\n \/\/ Replace function.\n auto newFuncOp = rewriter.cloneWithoutRegions(funcOp);\n newFuncOp.getBlocks().clear();\n rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),\n newFuncOp.end());\n newFuncOp.setType(rewriter.getFunctionType(newSignature.getConvertedTypes(),\n newResultTypes));\n if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,\n &newSignature))) {\n return failure();\n }\n\n rewriter.eraseOp(funcOp);\n return success();\n }\n};\n\nclass CallOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::CallOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::CallOpAdaptor adaptor(operands);\n SmallVector resultTypes;\n if (failed(getTypeConverter()->convertTypes(op.getResultTypes(),\n resultTypes))) {\n return rewriter.notifyMatchFailure(op, \"unable to convert result types\");\n }\n rewriter.replaceOpWithNewOp(op, resultTypes, op.callee(),\n adaptor.operands());\n return success();\n }\n};\n\nclass BranchOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::BranchOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::BranchOpAdaptor adaptor(operands);\n rewriter.replaceOpWithNewOp(op, op.dest(),\n adaptor.destOperands());\n return success();\n }\n};\n\nclass CondBranchOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::CondBranchOp op, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n mlir::CondBranchOpAdaptor adaptor(operands,\n op.getOperation()->getAttrDictionary());\n rewriter.replaceOpWithNewOp(\n op, adaptor.condition(), op.trueDest(), adaptor.trueDestOperands(),\n op.falseDest(), adaptor.falseDestOperands());\n return success();\n }\n};\n\nclass ReturnOpConversion : public OpConversionPattern {\n public:\n using OpConversionPattern::OpConversionPattern;\n\n LogicalResult matchAndRewrite(\n mlir::ReturnOp returnOp, llvm::ArrayRef operands,\n ConversionPatternRewriter &rewriter) const override {\n rewriter.replaceOpWithNewOp(returnOp, operands);\n return success();\n }\n};\n\n} \/\/ namespace\n\nvoid populateStandardStructuralToHALPatterns(MLIRContext *context,\n OwningRewritePatternList &patterns,\n TypeConverter &converter) {\n patterns\n .insert(converter, context);\n}\n\n} \/\/ namespace iree_compiler\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\n\/* Copyright (c) FFLAS-FFPACK\n* ========LICENCE========\n* This file is part of the library FFLAS-FFPACK.\n*\n* FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n* 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* ========LICENCE========\n*\/\n\n#include \n#include \n#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \"fflas-ffpack\/fflas-ffpack.h\"\n#include \"fflas-ffpack\/utils\/fflas_io.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n \n if (argc != 3){\n std::cerr<<\"Usage: pluq

      \"< F(p);\n\n \/\/ Reading the matrix from a file\n double *A;\n FFLAS::ReadMatrix (file.c_str(),F,m,n,A);\n\n size_t * P = FFLAS::fflas_new(m);\n size_t * Q = FFLAS::fflas_new(n);\n\n size_t r = FFPACK::PLUQ (F, FFLAS::FflasNonUnit, m, n, A, n, P, Q);\n\n\n FFLAS::WritePermutation (std::cout<<\"P = \"<(m * r);\n double * U = FFLAS::fflas_new(r * n);\n FFPACK::getTriangular(F, FFLAS::FflasLower, FFLAS::FflasUnit, m, n, r, A, n, L, r);\n FFPACK::getTriangular(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, m, n, r, A, n, U, n);\n FFLAS::WriteMatrix(std::cout<<\"L = \"<delete L and U\/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/\/ vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\\:0,t0,+0,=s\n\n\n\/* Copyright (c) FFLAS-FFPACK\n* ========LICENCE========\n* This file is part of the library FFLAS-FFPACK.\n*\n* FFLAS-FFPACK is free software: you can redistribute it and\/or modify\n* 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* ========LICENCE========\n*\/\n\n#include \n#include \n#include \"fflas-ffpack\/fflas-ffpack-config.h\"\n#include \"fflas-ffpack\/fflas-ffpack.h\"\n#include \"fflas-ffpack\/utils\/fflas_io.h\"\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n \n if (argc != 3){\n std::cerr<<\"Usage: pluq

      \"< F(p);\n\n \/\/ Reading the matrix from a file\n double *A;\n FFLAS::ReadMatrix (file.c_str(),F,m,n,A);\n\n size_t * P = FFLAS::fflas_new(m);\n size_t * Q = FFLAS::fflas_new(n);\n\n size_t r = FFPACK::PLUQ (F, FFLAS::FflasNonUnit, m, n, A, n, P, Q);\n\n\n FFLAS::WritePermutation (std::cout<<\"P = \"<(m * r);\n double * U = FFLAS::fflas_new(r * n);\n FFPACK::getTriangular(F, FFLAS::FflasLower, FFLAS::FflasUnit, m, n, r, A, n, L, r);\n FFPACK::getTriangular(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, m, n, r, A, n, U, n);\n FFLAS::WriteMatrix(std::cout<<\"L = \"<"} {"text":"#include \"stdafx.h\"\n\/*\n* Copyright (c) 2007-2010 SlimDX Group\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\nusing namespace testing;\nusing namespace System;\nusing namespace SlimDX;\n\nTEST( Vector3Tests, ConstructDefault )\n{\n\tVector3 vector = Vector3();\n\n\tASSERT_EQ( 0.0f, vector.X );\n\tASSERT_EQ( 0.0f, vector.Y );\n\tASSERT_EQ( 0.0f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithX )\n{\n\tVector3 vector = Vector3( 0.75f );\n\n\tASSERT_EQ( 0.75f, vector.X );\n\tASSERT_EQ( 0.75f, vector.Y );\n\tASSERT_EQ( 0.75f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithXYZ )\n{\n\tVector3 vector = Vector3( 0.75f, 1.25f, 1.75f );\n\n\tASSERT_EQ( 0.75f, vector.X );\n\tASSERT_EQ( 1.25f, vector.Y );\n\tASSERT_EQ( 1.75f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithVector2 )\n{\n\tVector2 source = Vector2( 1.0f, 2.0f );\n\tVector3 vector = Vector3( source, 3.0f );\n\n\tASSERT_EQ( 1.0f, vector.X );\n\tASSERT_EQ( 2.0f, vector.Y );\n\tASSERT_EQ( 3.0f, vector.Z );\n}\nTesting parameterized build.#include \"stdafx.h\"\n\/*\n* Copyright (c) 2007-2010 SlimDX Group\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\nusing namespace testing;\nusing namespace System;\nusing namespace SlimDX;\n\nTEST( Vector3Tests, ConstructDefault )\n{\n\tVector3 vector = Vector3();\n\n\tASSERT_EQ( 0.0f, vector.X );\n\tASSERT_EQ( 0.0f, vector.Y );\n\tASSERT_EQ( 0.0f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithX )\n{\n\tVector3 vector = Vector3( 0.75f );\n\n\tASSERT_EQ( 0.75f, vector.X );\n\tASSERT_EQ( 0.75f, vector.Y );\n\tASSERT_EQ( 0.75f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithXYZ )\n{\n\tVector3 vector = Vector3( 0.75f, 1.25f, 1.75f );\n\n\tASSERT_EQ( 0.75f, vector.X );\n\tASSERT_EQ( 1.25f, vector.Y );\n\tASSERT_EQ( 1.75f, vector.Z );\n}\n\nTEST( Vector3Tests, ConstructWithVector2 )\n{\n\tVector2 source = Vector2( 1.0f, 2.0f );\n\tVector3 vector = Vector3( source, 3.0f );\n\n\tASSERT_EQ( 1.0f, vector.X );\n\tASSERT_EQ( 2.0f, vector.Y );\n\tASSERT_EQ( 3.0f, vector.Z );\n}\n\nTEST( Vector3Tests, Add)\n{\n\tVector3 v1(5.6f, 2.1f, 8.3f);\n\tVector3 v2(3.4f, 7.9f, 7.7f);\n\tVector3 v3 = v1 + v2;\n\n\tASSERT_EQ(9.0f, v3.X);\n\tASSERT_EQ(10.0f, v3.Y);\n\tASSERT_EQ(16.0f, v3.Z);\n}<|endoftext|>"} {"text":"\/\/ BELONG TO \\REVIEW\n#include \n#include \n#include \n\n\/\/ NEW\n#include \"itkQuadEdgeMeshBorderTransform.h\"\n#include \"itkQuadEdgeMeshParamMatrixCoefficients.h\"\n\n\/\/ TIMING\n#include \n\n#ifdef QuadEdgePARAM_TAUCS\n #include \"TAUCSSparseSolverTraits.h\"\n#else\n #include \"VNLIterativeSparseSolverTraits.h\"\n#endif\n\n#include \"itkQuadEdgeMeshParam.h\"\n\nusing namespace itk;\n\nint itkQuadEdgeMeshLinearParameterizationTest( int argc, char** argv )\n{\n \/\/ ** ERROR MESSAGE AND HELP ** \/\/\n if( argc < 5 )\n {\n std::cout <<\"Requires 4 arguments: \" < MeshType;\n typedef VTKPolyDataReader< MeshType > ReaderType;\n typedef VTKPolyDataWriter< MeshType > WriterType;\n typedef QuadEdgeMeshBorderTransform< MeshType, MeshType > BorderTransformType;\n#ifdef QuadEdgePARAM_TAUCS\n typedef TAUCSSolverTraits< Coord > SolverTraits;\n#else\n typedef VNLIterativeSparseSolverTraits< Coord > SolverTraits;\n#endif\n typedef QuadEdgeMeshParam< MeshType, MeshType, SolverTraits > ParametrizationType;\n\n\n \/\/ ** READ THE FILE IN **\n ReaderType::Pointer reader = ReaderType::New( );\n reader->SetFileName( argv[1] );\n try\n {\n reader->Update( );\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown while reading the input file \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\n MeshType::Pointer mesh = reader->GetOutput( );\n\n \/\/ ** CHOSE< COMPUTE AND SET BORDER TRANSFORM **\n \/\/ clock_t start = clock( );\n BorderTransformType::Pointer border_transform = BorderTransformType::New( );\n border_transform->SetInput( mesh );\n\n int border;\n std::stringstream ssout( argv[2] );\n ssout >>border;\n switch( border ) \/\/ choose border type\n {\n case 0: \/\/ square shaped domain\n border_transform->SetTransformType(\n BorderTransformType::SQUARE_BORDER_TRANSFORM ); \n break;\n case 1: \/\/ disk shaped domain\n border_transform->SetTransformType(\n BorderTransformType::DISK_BORDER_TRANSFORM ); \n break;\n default: \/\/ handle .... user ....\n std::cerr <<\"2nd argument must be \"< coeff0;\n InverseEuclideanDistanceMatrixCoefficients< MeshType > coeff1;\n ConformalMatrixCoefficients< MeshType > coeff2;\n AuthalicMatrixCoefficients< MeshType > coeff3;\n HarmonicMatrixCoefficients< MeshType > coeff4;\n\n ParametrizationType::Pointer param = ParametrizationType::New( );\n param->SetInput( mesh );\n param->SetBorderTransform( border_transform );\n\n int param_type;\n std::stringstream ssout3( argv[3] );\n ssout3 >>param_type;\n\n switch( param_type )\n {\n case 0:\n param->SetCoefficientsMethod( &coeff0 );\n break;\n case 1:\n param->SetCoefficientsMethod( &coeff1 );\n break;\n case 2:\n param->SetCoefficientsMethod( &coeff2 );\n break;\n case 3:\n param->SetCoefficientsMethod( &coeff3 );\n break;\n case 4:\n param->SetCoefficientsMethod( &coeff4 );\n break;\n default:\n std::cerr <<\"3rd argument must be \"<Update( );\n MeshType::Pointer output = param->GetOutput( );\n\n \/\/ ** TIMING **\n \/\/ clock_t end = clock( );\n \/\/ std::cout <<\"Time: \";\n \/\/ std::cout <( end - start ) \/\n \/\/ static_cast< double >( CLOCKS_PER_SEC ) <<\" s\" <SetInput( param->GetOutput( ) );\n writer->SetFileName( argv[4] );\n writer->Update( );\n\n \/\/ GET OUT OF HERE AND GET (YET ANOTHER) COFFEE\n return EXIT_SUCCESS;\n}\nBUG: wrong signature for main program.\/\/ BELONG TO \\REVIEW\n#include \n#include \n#include \n\n\/\/ NEW\n#include \"itkQuadEdgeMeshBorderTransform.h\"\n#include \"itkQuadEdgeMeshParamMatrixCoefficients.h\"\n\n\/\/ TIMING\n#include \n\n#ifdef QuadEdgePARAM_TAUCS\n #include \"TAUCSSparseSolverTraits.h\"\n#else\n #include \"VNLIterativeSparseSolverTraits.h\"\n#endif\n\n#include \"itkQuadEdgeMeshParam.h\"\n\nusing namespace itk;\n\nint itkQuadEdgeMeshLinearParameterizationTest( int argc, char* argv[] )\n{\n \/\/ ** ERROR MESSAGE AND HELP ** \/\/\n if( argc < 5 )\n {\n std::cout <<\"Requires 4 arguments: \" < MeshType;\n typedef VTKPolyDataReader< MeshType > ReaderType;\n typedef VTKPolyDataWriter< MeshType > WriterType;\n typedef QuadEdgeMeshBorderTransform< MeshType, MeshType > BorderTransformType;\n#ifdef QuadEdgePARAM_TAUCS\n typedef TAUCSSolverTraits< Coord > SolverTraits;\n#else\n typedef VNLIterativeSparseSolverTraits< Coord > SolverTraits;\n#endif\n typedef QuadEdgeMeshParam< MeshType, MeshType, SolverTraits > ParametrizationType;\n\n\n \/\/ ** READ THE FILE IN **\n ReaderType::Pointer reader = ReaderType::New( );\n reader->SetFileName( argv[1] );\n try\n {\n reader->Update( );\n }\n catch( itk::ExceptionObject & exp )\n {\n std::cerr << \"Exception thrown while reading the input file \" << std::endl;\n std::cerr << exp << std::endl;\n return EXIT_FAILURE;\n }\n\n MeshType::Pointer mesh = reader->GetOutput( );\n\n \/\/ ** CHOSE< COMPUTE AND SET BORDER TRANSFORM **\n \/\/ clock_t start = clock( );\n BorderTransformType::Pointer border_transform = BorderTransformType::New( );\n border_transform->SetInput( mesh );\n\n int border;\n std::stringstream ssout( argv[2] );\n ssout >>border;\n switch( border ) \/\/ choose border type\n {\n case 0: \/\/ square shaped domain\n border_transform->SetTransformType(\n BorderTransformType::SQUARE_BORDER_TRANSFORM ); \n break;\n case 1: \/\/ disk shaped domain\n border_transform->SetTransformType(\n BorderTransformType::DISK_BORDER_TRANSFORM ); \n break;\n default: \/\/ handle .... user ....\n std::cerr <<\"2nd argument must be \"< coeff0;\n InverseEuclideanDistanceMatrixCoefficients< MeshType > coeff1;\n ConformalMatrixCoefficients< MeshType > coeff2;\n AuthalicMatrixCoefficients< MeshType > coeff3;\n HarmonicMatrixCoefficients< MeshType > coeff4;\n\n ParametrizationType::Pointer param = ParametrizationType::New( );\n param->SetInput( mesh );\n param->SetBorderTransform( border_transform );\n\n int param_type;\n std::stringstream ssout3( argv[3] );\n ssout3 >>param_type;\n\n switch( param_type )\n {\n case 0:\n param->SetCoefficientsMethod( &coeff0 );\n break;\n case 1:\n param->SetCoefficientsMethod( &coeff1 );\n break;\n case 2:\n param->SetCoefficientsMethod( &coeff2 );\n break;\n case 3:\n param->SetCoefficientsMethod( &coeff3 );\n break;\n case 4:\n param->SetCoefficientsMethod( &coeff4 );\n break;\n default:\n std::cerr <<\"3rd argument must be \"<Update( );\n MeshType::Pointer output = param->GetOutput( );\n\n \/\/ ** TIMING **\n \/\/ clock_t end = clock( );\n \/\/ std::cout <<\"Time: \";\n \/\/ std::cout <( end - start ) \/\n \/\/ static_cast< double >( CLOCKS_PER_SEC ) <<\" s\" <SetInput( param->GetOutput( ) );\n writer->SetFileName( argv[4] );\n writer->Update( );\n\n \/\/ GET OUT OF HERE AND GET (YET ANOTHER) COFFEE\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: test_segmentation.cpp 3564 2011-12-16 06:11:13Z rusu $\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\n\nPointCloud::Ptr cloud_;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (SACSegmentation, Segmentation)\n{\n ModelCoefficients::Ptr sphere_coefficients (new ModelCoefficients);\n PointIndices::Ptr inliers (new PointIndices);\n\n SACSegmentation seg;\n seg.setOptimizeCoefficients (true);\n seg.setModelType (SACMODEL_SPHERE);\n seg.setMethodType (SAC_RANSAC);\n seg.setMaxIterations (10000);\n seg.setDistanceThreshold (0.01);\n seg.setRadiusLimits (0.03, 0.07); \/\/ true radius is 0.05\n seg.setInputCloud (cloud_);\n seg.segment (*inliers, *sphere_coefficients);\n\n EXPECT_NEAR (sphere_coefficients->values[0], 0.998776, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[1], 0.752023, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[2], 1.24558, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[3], 0.0536238, 1e-2);\n\n EXPECT_NEAR (static_cast (inliers->indices.size ()), 3516, 10);\n}\n\n\/\/* ---[ *\/\nint\n main (int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"No test file given. Please download `noisy_slice_displaced.pcd` and pass its path to the test.\" << std::endl;\n return (-1);\n }\n\n \/\/ Load a standard PCD file from disk\n PointCloud cloud;\n if (loadPCDFile (argv[1], cloud) < 0)\n {\n std::cerr << \"Failed to read test file. Please download `noisy_slice_displaced.pcd` and pass its path to the test.\" << std::endl;\n return (-1);\n }\n\n cloud_ = cloud.makeShared ();\n\n testing::InitGoogleTest (&argc, argv);\n return (RUN_ALL_TESTS ());\n}\n\/* ]--- *\/\nIncrease threshold for expected value in test_non_linear\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: test_segmentation.cpp 3564 2011-12-16 06:11:13Z rusu $\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace pcl;\nusing namespace pcl::io;\n\nPointCloud::Ptr cloud_;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTEST (SACSegmentation, Segmentation)\n{\n ModelCoefficients::Ptr sphere_coefficients (new ModelCoefficients);\n PointIndices::Ptr inliers (new PointIndices);\n\n SACSegmentation seg;\n seg.setOptimizeCoefficients (true);\n seg.setModelType (SACMODEL_SPHERE);\n seg.setMethodType (SAC_RANSAC);\n seg.setMaxIterations (10000);\n seg.setDistanceThreshold (0.01);\n seg.setRadiusLimits (0.03, 0.07); \/\/ true radius is 0.05\n seg.setInputCloud (cloud_);\n seg.segment (*inliers, *sphere_coefficients);\n\n EXPECT_NEAR (sphere_coefficients->values[0], 0.998776, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[1], 0.752023, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[2], 1.24558, 1e-2);\n EXPECT_NEAR (sphere_coefficients->values[3], 0.0536238, 1e-2);\n\n EXPECT_NEAR (static_cast (inliers->indices.size ()), 3516, 15);\n}\n\n\/\/* ---[ *\/\nint\n main (int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"No test file given. Please download `noisy_slice_displaced.pcd` and pass its path to the test.\" << std::endl;\n return (-1);\n }\n\n \/\/ Load a standard PCD file from disk\n PointCloud cloud;\n if (loadPCDFile (argv[1], cloud) < 0)\n {\n std::cerr << \"Failed to read test file. Please download `noisy_slice_displaced.pcd` and pass its path to the test.\" << std::endl;\n return (-1);\n }\n\n cloud_ = cloud.makeShared ();\n\n testing::InitGoogleTest (&argc, argv);\n return (RUN_ALL_TESTS ());\n}\n\/* ]--- *\/\n<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s\n\/\/ RUN: %clang_cc1 -fms-extensions -fdelayed-template-parsing -fsyntax-only -verify %s\n\nclass A {\npublic:\n template A(U p) {}\n template<> A(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'A' within class scope is a Microsoft extension}}\n }\n\n template void f(U p) {}\n\n template<> void f(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}\n }\n\n void f(int p) {}\n};\n\nvoid test1() {\n A a(3);\n char *b;\n a.f(b);\n a.f(99);\n a.f(100);\n}\n\ntemplate class B {\npublic:\n template B(U p) {}\n template<> B(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'B' within class scope is a Microsoft extension}}\n }\n\n template void f(U p) { T y = 9; }\n\n template<> void f(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}\n T a = 3;\n }\n\n void f(int p) { T a = 3; }\n};\n\nvoid test2() {\n B b(3);\n char *ptr;\n b.f(ptr);\n b.f(99);\n b.f(100);\n}\n\nnamespace PR12709 {\n\ntemplate class TemplateClass {\n void member_function() { specialized_member_template(); }\n\n template void specialized_member_template() {}\n\n template<> void specialized_member_template() {\n \/\/ expected-warning@-1 {{explicit specialization of 'specialized_member_template' within class scope is a Microsoft extension}}\n }\n};\n\nvoid f() { TemplateClass t; }\n}\nAdd a testcase and a FIXME for an accepts-invalid.\/\/ RUN: %clang_cc1 -fms-extensions -fsyntax-only -verify %s\n\/\/ RUN: %clang_cc1 -fms-extensions -fdelayed-template-parsing -fsyntax-only -verify %s\n\nclass A {\npublic:\n template A(U p) {}\n template<> A(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'A' within class scope is a Microsoft extension}}\n }\n\n template void f(U p) {}\n\n template<> void f(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}\n }\n\n void f(int p) {}\n};\n\nvoid test1() {\n A a(3);\n char *b;\n a.f(b);\n a.f(99);\n a.f(100);\n}\n\ntemplate class B {\npublic:\n template B(U p) {}\n template<> B(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'B' within class scope is a Microsoft extension}}\n }\n\n template void f(U p) { T y = 9; }\n\n template<> void f(int p) {\n \/\/ expected-warning@-1 {{explicit specialization of 'f' within class scope is a Microsoft extension}}\n T a = 3;\n }\n\n void f(int p) { T a = 3; }\n};\n\nvoid test2() {\n B b(3);\n char *ptr;\n b.f(ptr);\n b.f(99);\n b.f(100);\n}\n\nnamespace PR12709 {\n template class TemplateClass {\n void member_function() { specialized_member_template(); }\n\n template void specialized_member_template() {}\n\n template<> void specialized_member_template() {\n \/\/ expected-warning@-1 {{explicit specialization of 'specialized_member_template' within class scope is a Microsoft extension}}\n }\n };\n\n void f() { TemplateClass t; }\n}\n\nnamespace Duplicates {\n template struct A {\n template void f();\n template<> void f() {} \/\/ expected-warning {{Microsoft extension}}\n template<> void f() {} \/\/ expected-warning {{Microsoft extension}}\n };\n\n \/\/ FIXME: We should diagnose the duplicate explicit specialization definitions\n \/\/ here.\n template struct A;\n}\n<|endoftext|>"} {"text":"\/*\t____________________________________________________________________________\n\n\t Scanner Component for the Micro A Compiler\n\n\t mscan.h\n\n\t Version 2007 - 2016\n \n\t James L. Richards\n\t Last Update: August 28, 2007\n\t \t Nelson A Castillo\n\t Last Update: January 31, 2016\n\n\tThe routines in this unit are based on those provided in the book \n\t\"Crafting A Compiler\" by Charles N. Fischer and Richard J. LeBlanc, Jr., \n\tBenjamin Cummings Publishing Co. (1991).\n\n\tSee Section 2.2, pp. 25-29.\n\t____________________________________________________________________________\n*\/\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nextern ifstream sourceFile;\nextern ofstream outFile, listFile;\n\n#include \"mscan.h\"\n\n\/\/ *******************\n\/\/ ** Constructor **\n\/\/ *******************\n\nScanner::Scanner()\n{\n\ttokenBuffer = \"\";\n\tlineBuffer = \"\";\n\tlineNumber = 0;\n}\n\n\/\/ ********************************\n\/\/ ** Private Member Functions **\n\/\/ ********************************\n\nvoid Scanner::BufferChar(char c)\n{\n\tif (tokenBuffer.length() < ID_STRING_LEN){\n\t\ttokenBuffer += c;\n\t}\n\t\/\/cerr << tokenBuffer << endl;\n}\nvoid Scanner::BufferString(char c)\n{\n\tstringBuffer += c;\n\t\/\/cerr << tokenBuffer << endl;\n}\n\nToken Scanner::CheckReserved()\n{\n\t\/* Convert the string to lower case *\/\n\ttransform(tokenBuffer.begin(), tokenBuffer.end(), \\\n\t\t\t\ttokenBuffer.begin(), ::tolower);\n\t\/* Check the converted words *\/\n\tif ((tokenBuffer) == \"bool\") return BOOL_SYM;\n\tif ((tokenBuffer) == \"break\") return BREAK_SYM;\n\tif ((tokenBuffer) == \"case\") return CASE_SYM;\n\tif ((tokenBuffer) == \"cheese\") return CHEESE_SYM;\n\tif ((tokenBuffer) == \"decs\") return DECS_SYM;\n\tif ((tokenBuffer) == \"do\") return DO_SYM;\n\tif ((tokenBuffer) == \"else\") return ELSE_SYM;\n\tif ((tokenBuffer) == \"end\") return END_SYM;\n\tif ((tokenBuffer) == \"false\") return FALSE_SYM;\n\tif ((tokenBuffer) == \"float\") return FLOAT_SYM;\n\tif ((tokenBuffer) == \"for\") return FOR_SYM;\n\tif ((tokenBuffer) == \"hiphip\") return HIPHIP_SYM;\n\tif ((tokenBuffer) == \"if\") return IF_SYM;\n\tif ((tokenBuffer) == \"int\") return INT_SYM;\n\tif ((tokenBuffer) == \"listen\") return LISTEN_SYM;\n\tif ((tokenBuffer) == \"otherwise\") return OTHERWISE_SYM;\n\tif ((tokenBuffer) == \"select\") return SELECT_SYM;\n\tif ((tokenBuffer) == \"shout\") return SHOUT_SYM;\n\tif ((tokenBuffer) == \"then\") return THEN_SYM;\n\tif ((tokenBuffer) == \"true\") return TRUE_SYM;\n\tif ((tokenBuffer) == \"while\") return WHILE_SYM;\n\n\treturn ID;\n}\n\nvoid Scanner::ClearBuffer()\n{\n\ttokenBuffer = \"\";\n\tstringBuffer = \"\";\n}\n\nvoid Scanner::LexicalError(char& c)\n{\t\n\tcout << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << endl;\n\tlistFile << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << endl;\n\n\tc = NextChar();\n}\nvoid Scanner::LexicalError(char& c, const string& errorExp)\n{\n\tcout << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << '\\n'\n\t\t<< errorExp << endl;\n\tlistFile << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << '\\n'\n\t\t<< errorExp << endl;\n\n\tc = NextChar();\n}\n\nchar Scanner::NextChar()\n{\n\tchar c;\n\n\tsourceFile.get(c);\n\tif (c == '\\n')\n\t{\n\t\tlistFile.width(6);\n\t\tlistFile << ++lineNumber << \" \" << lineBuffer << endl;\n\t\tlineBuffer = \"\";\n\t} else{\n\t\tlineBuffer += c;\n\t}\n\treturn c;\n}\n\n\/\/ *******************************\n\/\/ ** Public Member Functions **\n\/\/ *******************************\n\nToken Scanner::GetNextToken()\n{\n\tchar currentChar, c;\n\n\tClearBuffer();\n\tcurrentChar = NextChar();\n\twhile (!sourceFile.eof())\n\t{\n\t\tif (isspace(currentChar)) {\n\t\t\t\/* do nothing *\/\n\t\t\tcurrentChar = NextChar();\n\t\t} else if (isalpha(currentChar)) {\n\t\t\t\/* identifier *\/\n\t\t\tBufferChar(currentChar);\n\t\t\tc = sourceFile.peek();\n\t\t\twhile (isalnum(c) || c == '_') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\tc = sourceFile.peek();\n\t\t\t}\n\t\t\treturn CheckReserved();\n\t\t} else if (isdigit(currentChar)) {\n\t\t\t\/* integer or float literals *\/\n\t\t\tBufferChar(currentChar);\n\t\t\tc = sourceFile.peek();\n\t\t\twhile (isdigit(c)) {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\tc = sourceFile.peek();\n\t\t\t}\n\t\t\t\/* check if it is a float *\/\n\t\t\tif (c == '.') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\/* check for a digit after the '.' *\/\n\t\t\t\tif (!isdigit(c)) \n\t\t\t\t\tLexicalError(currentChar, to_string(c)+\" Boolean needs a digit after the '.'\");\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\twhile (isdigit(c)) {\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t}\n\t\t\t\t\/* check for power of 10 multipliers *\/\n\t\t\t\tif (c == 'e' || c == 'E') {\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\tif (c != '+' && c!= '-') {\n\t\t\t\t\t\tLexicalError(currentChar, to_string(c)+\" Boolean needs a '+' or a '-' after 'E' \");\n\t\t\t\t\t}\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\tif (!isdigit(c)) \n\t\t\t\t\t\tLexicalError(currentChar, to_string(c)+\"Boolean needs a digit after '+' or '-'\");\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\twhile (isdigit(c)) {\n\t\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn FLOAT_LIT;\n\t\t\t}\n\t\t\treturn INT_LIT;\n\t\t} else if (currentChar == '\"') {\n\t\t\t\/\/ string literal\n\t\t\t\/\/ BufferString(currentChar);\n\t\t\tdo {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\/\/ cout << currentChar <') {\n\t\t\tif (sourceFile.peek() == '=') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\treturn GE_OP;\n\t\t\t}\n\t\t\tcurrentChar = NextChar();\n\t\t\treturn GT_OP;\n\t\t} else if (currentChar == '-') {\n\t\t\t\/* check if it is a comment or a minus symbol *\/\n\t\t\tif (sourceFile.peek() == '-') { \/* comment *\/\n\t\t\t\tdo { \/* skip comment *\/\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t} while (currentChar != '\\n');\n\t\t\t} else { \/* minus operator *\/\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\treturn MINUS_OP;\n\t\t\t}\n\t\t} else {\n\t\t\t\/* Unrecognized character *\/\n\t\t\tLexicalError(currentChar, to_string(c)+\" Unrecognized character\");\n\t\t}\n\t} \/* end while *\/\n\n\treturn EOF_SYM;\n}\nscan: consume and buffer chars properly.\/*\t____________________________________________________________________________\n\n\t Scanner Component for the Micro A Compiler\n\n\t mscan.h\n\n\t Version 2007 - 2016\n \n\t James L. Richards\n\t Last Update: August 28, 2007\n\t \t Nelson A Castillo\n\t Last Update: January 31, 2016\n\n\tThe routines in this unit are based on those provided in the book \n\t\"Crafting A Compiler\" by Charles N. Fischer and Richard J. LeBlanc, Jr., \n\tBenjamin Cummings Publishing Co. (1991).\n\n\tSee Section 2.2, pp. 25-29.\n\t____________________________________________________________________________\n*\/\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nextern ifstream sourceFile;\nextern ofstream outFile, listFile;\n\n#include \"mscan.h\"\n\n\/\/ *******************\n\/\/ ** Constructor **\n\/\/ *******************\n\nScanner::Scanner()\n{\n\ttokenBuffer = \"\";\n\tlineBuffer = \"\";\n\tlineNumber = 0;\n}\n\n\/\/ ********************************\n\/\/ ** Private Member Functions **\n\/\/ ********************************\n\nvoid Scanner::BufferChar(char c)\n{\n\tif (tokenBuffer.length() < ID_STRING_LEN){\n\t\ttokenBuffer += c;\n\t}\n\t\/\/cerr << tokenBuffer << endl;\n}\nvoid Scanner::BufferString(char c)\n{\n\tstringBuffer += c;\n\t\/\/cerr << tokenBuffer << endl;\n}\n\nToken Scanner::CheckReserved()\n{\n\t\/* Convert the string to lower case *\/\n\ttransform(tokenBuffer.begin(), tokenBuffer.end(), \\\n\t\t\t\ttokenBuffer.begin(), ::tolower);\n\t\/* Check the converted words *\/\n\tif ((tokenBuffer) == \"bool\") return BOOL_SYM;\n\tif ((tokenBuffer) == \"break\") return BREAK_SYM;\n\tif ((tokenBuffer) == \"case\") return CASE_SYM;\n\tif ((tokenBuffer) == \"cheese\") return CHEESE_SYM;\n\tif ((tokenBuffer) == \"decs\") return DECS_SYM;\n\tif ((tokenBuffer) == \"do\") return DO_SYM;\n\tif ((tokenBuffer) == \"else\") return ELSE_SYM;\n\tif ((tokenBuffer) == \"end\") return END_SYM;\n\tif ((tokenBuffer) == \"false\") return FALSE_SYM;\n\tif ((tokenBuffer) == \"float\") return FLOAT_SYM;\n\tif ((tokenBuffer) == \"for\") return FOR_SYM;\n\tif ((tokenBuffer) == \"hiphip\") return HIPHIP_SYM;\n\tif ((tokenBuffer) == \"if\") return IF_SYM;\n\tif ((tokenBuffer) == \"int\") return INT_SYM;\n\tif ((tokenBuffer) == \"listen\") return LISTEN_SYM;\n\tif ((tokenBuffer) == \"otherwise\") return OTHERWISE_SYM;\n\tif ((tokenBuffer) == \"select\") return SELECT_SYM;\n\tif ((tokenBuffer) == \"shout\") return SHOUT_SYM;\n\tif ((tokenBuffer) == \"then\") return THEN_SYM;\n\tif ((tokenBuffer) == \"true\") return TRUE_SYM;\n\tif ((tokenBuffer) == \"while\") return WHILE_SYM;\n\n\treturn ID;\n}\n\nvoid Scanner::ClearBuffer()\n{\n\ttokenBuffer = \"\";\n\tstringBuffer = \"\";\n}\n\nvoid Scanner::LexicalError(char& c)\n{\t\n\tcout << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << endl;\n\tlistFile << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << endl;\n\n\tc = NextChar();\n}\nvoid Scanner::LexicalError(char& c, const string& errorExp)\n{\n\tcout << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << '\\n'\n\t\t<< errorExp << endl;\n\tlistFile << \" *** Lexical Error: '\" << c\n\t\t<< \"' ignored at position \" << int(lineBuffer.size())\n\t\t<< \" on line #\" << lineNumber + 1 << '.' << '\\n'\n\t\t<< errorExp << endl;\n\n\tc = NextChar();\n}\n\nchar Scanner::NextChar()\n{\n\tchar c;\n\n\tsourceFile.get(c);\n\tif (c == '\\n')\n\t{\n\t\tlistFile.width(6);\n\t\tlistFile << ++lineNumber << \" \" << lineBuffer << endl;\n\t\tlineBuffer = \"\";\n\t} else{\n\t\tlineBuffer += c;\n\t}\n\treturn c;\n}\n\n\/\/ *******************************\n\/\/ ** Public Member Functions **\n\/\/ *******************************\n\nToken Scanner::GetNextToken()\n{\n\tchar currentChar, c;\n\n\tClearBuffer();\n\tcurrentChar = NextChar();\n\twhile (!sourceFile.eof())\n\t{\n\t\tif (isspace(currentChar)) {\n\t\t\t\/* do nothing *\/\n\t\t\tcurrentChar = NextChar();\n\t\t} else if (isalpha(currentChar)) {\n\t\t\t\/* identifier *\/\n\t\t\tBufferChar(currentChar);\n\t\t\tc = sourceFile.peek();\n\t\t\twhile (isalnum(c) || c == '_') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\tc = sourceFile.peek();\n\t\t\t}\n\t\t\treturn CheckReserved();\n\t\t} else if (isdigit(currentChar)) {\n\t\t\t\/* integer or float literals *\/\n\t\t\tBufferChar(currentChar);\n\t\t\tc = sourceFile.peek();\n\t\t\twhile (isdigit(c)) {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\tc = sourceFile.peek();\n\t\t\t}\n\t\t\t\/* check if it is a float *\/\n\t\t\tif (c == '.') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\/* check for a digit after the '.' *\/\n\t\t\t\tif (!isdigit(c)) \n\t\t\t\t\tLexicalError(currentChar, to_string(c)+\" Boolean needs a digit after the '.'\");\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\twhile (isdigit(c)) {\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t}\n\t\t\t\t\/* check for power of 10 multipliers *\/\n\t\t\t\tif (c == 'e' || c == 'E') {\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\tif (c != '+' && c!= '-') {\n\t\t\t\t\t\tLexicalError(currentChar, to_string(c)+\" Boolean needs a '+' or a '-' after 'E' \");\n\t\t\t\t\t}\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\tif (!isdigit(c)) \n\t\t\t\t\t\tLexicalError(currentChar, to_string(c)+\"Boolean needs a digit after '+' or '-'\");\n\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\twhile (isdigit(c)) {\n\t\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\t\tBufferChar(currentChar);\n\t\t\t\t\t\tc = sourceFile.peek();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn FLOAT_LIT;\n\t\t\t}\n\t\t\treturn INT_LIT;\n\t\t} else if (currentChar == '\"') {\n\t\t\t\/\/ string literal\n\t\t\t\/\/ BufferString(currentChar);\n\t\t\tdo {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t\/\/ cout << currentChar <') {\n\t\t\tBufferChar(currentChar);\n\t\t\tif (sourceFile.peek() == '=') {\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\treturn GE_OP;\n\t\t\t}\n\t\t\tcurrentChar = NextChar();\n\t\t\treturn GT_OP;\n\t\t} else if (currentChar == '-') {\n\t\t\t\/* check if it is a comment or a minus symbol *\/\n\t\t\tif (sourceFile.peek() == '-') { \/* comment *\/\n\t\t\t\tdo { \/* skip comment *\/\n\t\t\t\t\tcurrentChar = NextChar();\n\t\t\t\t} while (currentChar != '\\n');\n\t\t\t} else { \/* minus operator *\/\n\t\t\t\tBufferChar(currentChar);\n\t\t\t\tcurrentChar = NextChar();\n\t\t\t\treturn MINUS_OP;\n\t\t\t}\n\t\t} else {\n\t\t\t\/* Unrecognized character *\/\n\t\t\tLexicalError(currentChar, to_string(c)+\" Unrecognized character\");\n\t\t}\n\t} \/* end while *\/\n\n\treturn EOF_SYM;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unocontrolmodel.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:52:52 $\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 _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n#define _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n\n#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_WEAKAGG_HXX_\n#include \n#endif\n\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#include \n#include \n\n#include \n#include \n\nclass ImplPropertyTable;\n\n\/\/ ----------------------------------------------------\n\/\/ class UnoControlModel\n\/\/ ----------------------------------------------------\n\nclass UnoControlModel : public ::com::sun::star::awt::XControlModel,\n public ::com::sun::star::beans::XPropertyState,\n public ::com::sun::star::io::XPersistObject,\n public ::com::sun::star::lang::XComponent,\n public ::com::sun::star::lang::XServiceInfo,\n public ::com::sun::star::lang::XTypeProvider,\n public ::com::sun::star::lang::XUnoTunnel,\n public ::com::sun::star::util::XCloneable,\n public MutexAndBroadcastHelper,\n public ::cppu::OPropertySetHelper,\n public ::cppu::OWeakAggObject\n{\nprivate:\n ImplPropertyTable* mpData;\n EventListenerMultiplexer maDisposeListeners;\n\nprotected:\n void ImplRegisterProperty( sal_uInt16 nPropType );\n void ImplRegisterProperty( sal_uInt16 nPropId, const ::com::sun::star::uno::Any& rDefault );\n ::com::sun::star::uno::Sequence ImplGetPropertyIds() const;\n virtual void ImplPropertyChanged( sal_uInt16 nPropId );\n virtual ::com::sun::star::uno::Any ImplGetDefaultValue( sal_uInt16 nPropId ) const;\n sal_Bool ImplHasProperty( sal_uInt16 nPropId ) const;\n\n \/** called before setting multiple properties, allows to care for property dependencies\n\n

      When multiple property values are set (e.g. XPropertySet::setPropertyValues), it may happen that some\n of them are dependent. For this, derivees which know such dependencies can affect the order in which\n the properties are internally really set.<\/p>\n *\/\n virtual void ImplNormalizePropertySequence(\n const sal_Int32 _nCount, \/\/\/ the number of entries in the arrays\n sal_Int32* _pHandles, \/\/\/ the handles of the properties to set\n ::com::sun::star::uno::Any* _pValues, \/\/\/ the values of the properties to set\n sal_Int32* _pValidHandles \/\/\/ pointer to the valid handles, allowed to be adjusted\n ) const SAL_THROW(());\n\npublic:\n UnoControlModel();\n UnoControlModel( const UnoControlModel& rModel );\n ~UnoControlModel();\n\n virtual UnoControlModel* Clone() const = 0;\n\n \/\/ ::com::sun::star::uno::XAggregation\n ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return OWeakAggObject::queryInterface(rType); }\n void SAL_CALL acquire() throw() { OWeakAggObject::acquire(); }\n void SAL_CALL release() throw() { OWeakAggObject::release(); }\n\n ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XUnoTunnel\n static const ::com::sun::star::uno::Sequence< sal_Int8 >& GetUnoTunnelId() throw();\n static UnoControlModel* GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();\n sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::util::XCloneable\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XTypeProvider\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::awt::XControlModel\n\n \/\/ ::com::sun::star::lang::XComponent\n void SAL_CALL dispose( ) throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::beans::XPropertyState\n ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::io::XPersistObject\n ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL write( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& OutStream ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL read( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& InStream ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::cppu::OPropertySetHelper\n ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() = 0;\n sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException);\n void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception);\n void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n\n \/\/ setValue-Methoden ueberladen, um die Einzelproperties des FontDescriptors abzufangen\n \/\/ ::com::sun::star::beans::XPropertySet\n void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n \/\/ ::com::sun::star::beans::XFastPropertySet\n void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n \/\/ ::com::sun::star::beans::XMultiPropertySet\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) = 0;\n void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n};\n\n\n\n\n#endif \/\/ _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n\nINTEGRATION: CWS warnings01 (1.5.26); FILE MERGED 2005\/11\/14 10:36:06 pl 1.5.26.1: #i55991# removed warnings\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unocontrolmodel.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 22:56:46 $\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 _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n#define _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n\n#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_IO_XPERSISTOBJECT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCLONEABLE_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_WEAKAGG_HXX_\n#include \n#endif\n\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#include \n#include \n\n#include \n#include \n\nclass ImplPropertyTable;\n\n\/\/ ----------------------------------------------------\n\/\/ class UnoControlModel\n\/\/ ----------------------------------------------------\n\nclass UnoControlModel : public ::com::sun::star::awt::XControlModel,\n public ::com::sun::star::beans::XPropertyState,\n public ::com::sun::star::io::XPersistObject,\n public ::com::sun::star::lang::XComponent,\n public ::com::sun::star::lang::XServiceInfo,\n public ::com::sun::star::lang::XTypeProvider,\n public ::com::sun::star::lang::XUnoTunnel,\n public ::com::sun::star::util::XCloneable,\n public MutexAndBroadcastHelper,\n public ::cppu::OPropertySetHelper,\n public ::cppu::OWeakAggObject\n{\nprivate:\n ImplPropertyTable* mpData;\n EventListenerMultiplexer maDisposeListeners;\n\nprotected:\n void ImplRegisterProperty( sal_uInt16 nPropType );\n void ImplRegisterProperty( sal_uInt16 nPropId, const ::com::sun::star::uno::Any& rDefault );\n ::com::sun::star::uno::Sequence ImplGetPropertyIds() const;\n virtual void ImplPropertyChanged( sal_uInt16 nPropId );\n virtual ::com::sun::star::uno::Any ImplGetDefaultValue( sal_uInt16 nPropId ) const;\n sal_Bool ImplHasProperty( sal_uInt16 nPropId ) const;\n\n \/** called before setting multiple properties, allows to care for property dependencies\n\n

      When multiple property values are set (e.g. XPropertySet::setPropertyValues), it may happen that some\n of them are dependent. For this, derivees which know such dependencies can affect the order in which\n the properties are internally really set.<\/p>\n *\/\n virtual void ImplNormalizePropertySequence(\n const sal_Int32 _nCount, \/\/\/ the number of entries in the arrays\n sal_Int32* _pHandles, \/\/\/ the handles of the properties to set\n ::com::sun::star::uno::Any* _pValues, \/\/\/ the values of the properties to set\n sal_Int32* _pValidHandles \/\/\/ pointer to the valid handles, allowed to be adjusted\n ) const SAL_THROW(());\n\npublic:\n UnoControlModel();\n UnoControlModel( const UnoControlModel& rModel );\n ~UnoControlModel();\n\n virtual UnoControlModel* Clone() const = 0;\n\n \/\/ ::com::sun::star::uno::XAggregation\n ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { return OWeakAggObject::queryInterface(rType); }\n void SAL_CALL acquire() throw() { OWeakAggObject::acquire(); }\n void SAL_CALL release() throw() { OWeakAggObject::release(); }\n\n ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XUnoTunnel\n static const ::com::sun::star::uno::Sequence< sal_Int8 >& GetUnoTunnelId() throw();\n static UnoControlModel* GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();\n sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::util::XCloneable\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable > SAL_CALL createClone() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XTypeProvider\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw(::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::awt::XControlModel\n\n \/\/ ::com::sun::star::lang::XComponent\n void SAL_CALL dispose( ) throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::beans::XPropertyState\n ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::io::XPersistObject\n ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);\n void SAL_CALL write( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& OutStream ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL read( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& InStream ) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ ::com::sun::star::lang::XServiceInfo\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ ::cppu::OPropertySetHelper\n ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper() = 0;\n sal_Bool SAL_CALL convertFastPropertyValue( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException);\n void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception);\n using cppu::OPropertySetHelper::getFastPropertyValue;\n void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n\n \/\/ setValue-Methoden ueberladen, um die Einzelproperties des FontDescriptors abzufangen\n \/\/ ::com::sun::star::beans::XPropertySet\n void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n \/\/ ::com::sun::star::beans::XFastPropertySet\n void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n \/\/ ::com::sun::star::beans::XMultiPropertySet\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) = 0;\n void SAL_CALL setPropertyValues( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& PropertyNames, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Values ) throw(::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n};\n\n\n\n\n#endif \/\/ _TOOLKIT_AWT_UNOCONTROLMODEL_HXX_\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"PathOpsCubicIntersectionTestData.h\"\n#include \"PathOpsQuadIntersectionTestData.h\"\n#include \"PathOpsTestCommon.h\"\n#include \"SkIntersections.h\"\n#include \"SkPathOpsRect.h\"\n#include \"SkReduceOrder.h\"\n#include \"Test.h\"\n\nstatic bool controls_inside(const SkDCubic& cubic) {\n return between(cubic[0].fX, cubic[1].fX, cubic[3].fX)\n && between(cubic[0].fX, cubic[2].fX, cubic[3].fX)\n && between(cubic[0].fY, cubic[1].fY, cubic[3].fY)\n && between(cubic[0].fY, cubic[2].fY, cubic[3].fY);\n}\n\nstatic bool tiny(const SkDCubic& cubic) {\n int index, minX, maxX, minY, maxY;\n minX = maxX = minY = maxY = 0;\n for (index = 1; index < 4; ++index) {\n if (cubic[minX].fX > cubic[index].fX) {\n minX = index;\n }\n if (cubic[minY].fY > cubic[index].fY) {\n minY = index;\n }\n if (cubic[maxX].fX < cubic[index].fX) {\n maxX = index;\n }\n if (cubic[maxY].fY < cubic[index].fY) {\n maxY = index;\n }\n }\n return approximately_equal(cubic[maxX].fX, cubic[minX].fX)\n && approximately_equal(cubic[maxY].fY, cubic[minY].fY);\n}\n\n#if 0 \/\/ disable test until stroke reduction is supported\nstatic void find_tight_bounds(const SkDCubic& cubic, SkDRect& bounds) {\n SkDCubicPair cubicPair = cubic.chopAt(0.5);\n if (!tiny(cubicPair.first()) && !controls_inside(cubicPair.first())) {\n find_tight_bounds(cubicPair.first(), bounds);\n } else {\n bounds.add(cubicPair.first()[0]);\n bounds.add(cubicPair.first()[3]);\n }\n if (!tiny(cubicPair.second()) && !controls_inside(cubicPair.second())) {\n find_tight_bounds(cubicPair.second(), bounds);\n } else {\n bounds.add(cubicPair.second()[0]);\n bounds.add(cubicPair.second()[3]);\n }\n}\n#endif\n\nstatic void PathOpsReduceOrderCubicTest(skiatest::Reporter* reporter) {\n size_t index;\n SkReduceOrder reducer;\n int order;\n enum {\n RunAll,\n RunPointDegenerates,\n RunNotPointDegenerates,\n RunLines,\n RunNotLines,\n RunModEpsilonLines,\n RunLessEpsilonLines,\n RunNegEpsilonLines,\n RunQuadraticLines,\n RunQuadraticPoints,\n RunQuadraticModLines,\n RunComputedLines,\n RunNone\n } run = RunAll;\n int firstTestIndex = 0;\n#if 0\n run = RunComputedLines;\n firstTestIndex = 18;\n#endif\n int firstPointDegeneratesTest = run == RunAll ? 0 : run == RunPointDegenerates\n ? firstTestIndex : SK_MaxS32;\n int firstNotPointDegeneratesTest = run == RunAll ? 0 : run == RunNotPointDegenerates\n ? firstTestIndex : SK_MaxS32;\n int firstLinesTest = run == RunAll ? 0 : run == RunLines ? firstTestIndex : SK_MaxS32;\n int firstNotLinesTest = run == RunAll ? 0 : run == RunNotLines ? firstTestIndex : SK_MaxS32;\n int firstModEpsilonTest = run == RunAll ? 0 : run == RunModEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstLessEpsilonTest = run == RunAll ? 0 : run == RunLessEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstNegEpsilonTest = run == RunAll ? 0 : run == RunNegEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticPointTest = run == RunAll ? 0 : run == RunQuadraticPoints\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticLineTest = run == RunAll ? 0 : run == RunQuadraticLines\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticModLineTest = run == RunAll ? 0 : run == RunQuadraticModLines\n ? firstTestIndex : SK_MaxS32;\n#if 0\n int firstComputedLinesTest = run == RunAll ? 0 : run == RunComputedLines\n ? firstTestIndex : SK_MaxS32;\n#endif\n for (index = firstPointDegeneratesTest; index < pointDegenerates_count; ++index) {\n const SkDCubic& cubic = pointDegenerates[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 1) {\n SkDebugf(\"[%d] pointDegenerates order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNotPointDegeneratesTest; index < notPointDegenerates_count; ++index) {\n const SkDCubic& cubic = notPointDegenerates[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 1) {\n SkDebugf(\"[%d] notPointDegenerates order=%d\\n\", static_cast(index), order);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstLinesTest; index < lines_count; ++index) {\n const SkDCubic& cubic = lines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] lines order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNotLinesTest; index < notLines_count; ++index) {\n const SkDCubic& cubic = notLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 2) {\n SkDebugf(\"[%d] notLines order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstModEpsilonTest; index < modEpsilonLines_count; ++index) {\n const SkDCubic& cubic = modEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 2) {\n SkDebugf(\"[%d] line mod by epsilon order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstLessEpsilonTest; index < lessEpsilonLines_count; ++index) {\n const SkDCubic& cubic = lessEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line less by epsilon\/2 order=%d\\n\", static_cast(index), order);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNegEpsilonTest; index < negEpsilonLines_count; ++index) {\n const SkDCubic& cubic = negEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line neg by epsilon\/2 order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticPointTest; index < quadraticPoints_count; ++index) {\n const SkDQuad& quad = quadraticPoints[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 1) {\n SkDebugf(\"[%d] point quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticLineTest; index < quadraticLines_count; ++index) {\n const SkDQuad& quad = quadraticLines[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticModLineTest; index < quadraticModEpsilonLines_count; ++index) {\n const SkDQuad& quad = quadraticModEpsilonLines[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 3) {\n SkDebugf(\"[%d] line mod quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n\n#if 0 \/\/ disable test until stroke reduction is supported\n\/\/ test if computed line end points are valid\n for (index = firstComputedLinesTest; index < lines_count; ++index) {\n const SkDCubic& cubic = lines[index];\n SkASSERT(ValidCubic(cubic));\n bool controlsInside = controls_inside(cubic);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics,\n SkReduceOrder::kStroke_Style);\n if (order == 2 && reducer.fLine[0] == reducer.fLine[1]) {\n SkDebugf(\"[%d] line computed ends match order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n if (controlsInside) {\n if ( (reducer.fLine[0].fX != cubic[0].fX && reducer.fLine[0].fX != cubic[3].fX)\n || (reducer.fLine[0].fY != cubic[0].fY && reducer.fLine[0].fY != cubic[3].fY)\n || (reducer.fLine[1].fX != cubic[0].fX && reducer.fLine[1].fX != cubic[3].fX)\n || (reducer.fLine[1].fY != cubic[0].fY && reducer.fLine[1].fY != cubic[3].fY)) {\n SkDebugf(\"[%d] line computed ends order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n } else {\n \/\/ binary search for extrema, compare against actual results\n \/\/ while a control point is outside of bounding box formed by end points, split\n SkDRect bounds = {DBL_MAX, DBL_MAX, -DBL_MAX, -DBL_MAX};\n find_tight_bounds(cubic, bounds);\n if ( (!AlmostEqualUlps(reducer.fLine[0].fX, bounds.fLeft)\n && !AlmostEqualUlps(reducer.fLine[0].fX, bounds.fRight))\n || (!AlmostEqualUlps(reducer.fLine[0].fY, bounds.fTop)\n && !AlmostEqualUlps(reducer.fLine[0].fY, bounds.fBottom))\n || (!AlmostEqualUlps(reducer.fLine[1].fX, bounds.fLeft)\n && !AlmostEqualUlps(reducer.fLine[1].fX, bounds.fRight))\n || (!AlmostEqualUlps(reducer.fLine[1].fY, bounds.fTop)\n && !AlmostEqualUlps(reducer.fLine[1].fY, bounds.fBottom))) {\n SkDebugf(\"[%d] line computed tight bounds order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n }\n#endif\n}\n\n#include \"TestClassDef.h\"\n\nDEFINE_TESTCLASS_SHORT(PathOpsReduceOrderCubicTest)\nremove more unused static functions\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"PathOpsCubicIntersectionTestData.h\"\n#include \"PathOpsQuadIntersectionTestData.h\"\n#include \"PathOpsTestCommon.h\"\n#include \"SkIntersections.h\"\n#include \"SkPathOpsRect.h\"\n#include \"SkReduceOrder.h\"\n#include \"Test.h\"\n\n#if 0 \/\/ disable test until stroke reduction is supported\nstatic bool controls_inside(const SkDCubic& cubic) {\n return between(cubic[0].fX, cubic[1].fX, cubic[3].fX)\n && between(cubic[0].fX, cubic[2].fX, cubic[3].fX)\n && between(cubic[0].fY, cubic[1].fY, cubic[3].fY)\n && between(cubic[0].fY, cubic[2].fY, cubic[3].fY);\n}\n\nstatic bool tiny(const SkDCubic& cubic) {\n int index, minX, maxX, minY, maxY;\n minX = maxX = minY = maxY = 0;\n for (index = 1; index < 4; ++index) {\n if (cubic[minX].fX > cubic[index].fX) {\n minX = index;\n }\n if (cubic[minY].fY > cubic[index].fY) {\n minY = index;\n }\n if (cubic[maxX].fX < cubic[index].fX) {\n maxX = index;\n }\n if (cubic[maxY].fY < cubic[index].fY) {\n maxY = index;\n }\n }\n return approximately_equal(cubic[maxX].fX, cubic[minX].fX)\n && approximately_equal(cubic[maxY].fY, cubic[minY].fY);\n}\n\nstatic void find_tight_bounds(const SkDCubic& cubic, SkDRect& bounds) {\n SkDCubicPair cubicPair = cubic.chopAt(0.5);\n if (!tiny(cubicPair.first()) && !controls_inside(cubicPair.first())) {\n find_tight_bounds(cubicPair.first(), bounds);\n } else {\n bounds.add(cubicPair.first()[0]);\n bounds.add(cubicPair.first()[3]);\n }\n if (!tiny(cubicPair.second()) && !controls_inside(cubicPair.second())) {\n find_tight_bounds(cubicPair.second(), bounds);\n } else {\n bounds.add(cubicPair.second()[0]);\n bounds.add(cubicPair.second()[3]);\n }\n}\n#endif\n\nstatic void PathOpsReduceOrderCubicTest(skiatest::Reporter* reporter) {\n size_t index;\n SkReduceOrder reducer;\n int order;\n enum {\n RunAll,\n RunPointDegenerates,\n RunNotPointDegenerates,\n RunLines,\n RunNotLines,\n RunModEpsilonLines,\n RunLessEpsilonLines,\n RunNegEpsilonLines,\n RunQuadraticLines,\n RunQuadraticPoints,\n RunQuadraticModLines,\n RunComputedLines,\n RunNone\n } run = RunAll;\n int firstTestIndex = 0;\n#if 0\n run = RunComputedLines;\n firstTestIndex = 18;\n#endif\n int firstPointDegeneratesTest = run == RunAll ? 0 : run == RunPointDegenerates\n ? firstTestIndex : SK_MaxS32;\n int firstNotPointDegeneratesTest = run == RunAll ? 0 : run == RunNotPointDegenerates\n ? firstTestIndex : SK_MaxS32;\n int firstLinesTest = run == RunAll ? 0 : run == RunLines ? firstTestIndex : SK_MaxS32;\n int firstNotLinesTest = run == RunAll ? 0 : run == RunNotLines ? firstTestIndex : SK_MaxS32;\n int firstModEpsilonTest = run == RunAll ? 0 : run == RunModEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstLessEpsilonTest = run == RunAll ? 0 : run == RunLessEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstNegEpsilonTest = run == RunAll ? 0 : run == RunNegEpsilonLines\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticPointTest = run == RunAll ? 0 : run == RunQuadraticPoints\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticLineTest = run == RunAll ? 0 : run == RunQuadraticLines\n ? firstTestIndex : SK_MaxS32;\n int firstQuadraticModLineTest = run == RunAll ? 0 : run == RunQuadraticModLines\n ? firstTestIndex : SK_MaxS32;\n#if 0\n int firstComputedLinesTest = run == RunAll ? 0 : run == RunComputedLines\n ? firstTestIndex : SK_MaxS32;\n#endif\n for (index = firstPointDegeneratesTest; index < pointDegenerates_count; ++index) {\n const SkDCubic& cubic = pointDegenerates[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 1) {\n SkDebugf(\"[%d] pointDegenerates order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNotPointDegeneratesTest; index < notPointDegenerates_count; ++index) {\n const SkDCubic& cubic = notPointDegenerates[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 1) {\n SkDebugf(\"[%d] notPointDegenerates order=%d\\n\", static_cast(index), order);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstLinesTest; index < lines_count; ++index) {\n const SkDCubic& cubic = lines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] lines order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNotLinesTest; index < notLines_count; ++index) {\n const SkDCubic& cubic = notLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 2) {\n SkDebugf(\"[%d] notLines order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstModEpsilonTest; index < modEpsilonLines_count; ++index) {\n const SkDCubic& cubic = modEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order == 2) {\n SkDebugf(\"[%d] line mod by epsilon order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstLessEpsilonTest; index < lessEpsilonLines_count; ++index) {\n const SkDCubic& cubic = lessEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line less by epsilon\/2 order=%d\\n\", static_cast(index), order);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstNegEpsilonTest; index < negEpsilonLines_count; ++index) {\n const SkDCubic& cubic = negEpsilonLines[index];\n SkASSERT(ValidCubic(cubic));\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line neg by epsilon\/2 order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticPointTest; index < quadraticPoints_count; ++index) {\n const SkDQuad& quad = quadraticPoints[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 1) {\n SkDebugf(\"[%d] point quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticLineTest; index < quadraticLines_count; ++index) {\n const SkDQuad& quad = quadraticLines[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 2) {\n SkDebugf(\"[%d] line quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n for (index = firstQuadraticModLineTest; index < quadraticModEpsilonLines_count; ++index) {\n const SkDQuad& quad = quadraticModEpsilonLines[index];\n SkASSERT(ValidQuad(quad));\n SkDCubic cubic = quad.toCubic();\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics);\n if (order != 3) {\n SkDebugf(\"[%d] line mod quad order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n\n#if 0 \/\/ disable test until stroke reduction is supported\n\/\/ test if computed line end points are valid\n for (index = firstComputedLinesTest; index < lines_count; ++index) {\n const SkDCubic& cubic = lines[index];\n SkASSERT(ValidCubic(cubic));\n bool controlsInside = controls_inside(cubic);\n order = reducer.reduce(cubic, SkReduceOrder::kAllow_Quadratics,\n SkReduceOrder::kStroke_Style);\n if (order == 2 && reducer.fLine[0] == reducer.fLine[1]) {\n SkDebugf(\"[%d] line computed ends match order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n if (controlsInside) {\n if ( (reducer.fLine[0].fX != cubic[0].fX && reducer.fLine[0].fX != cubic[3].fX)\n || (reducer.fLine[0].fY != cubic[0].fY && reducer.fLine[0].fY != cubic[3].fY)\n || (reducer.fLine[1].fX != cubic[0].fX && reducer.fLine[1].fX != cubic[3].fX)\n || (reducer.fLine[1].fY != cubic[0].fY && reducer.fLine[1].fY != cubic[3].fY)) {\n SkDebugf(\"[%d] line computed ends order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n } else {\n \/\/ binary search for extrema, compare against actual results\n \/\/ while a control point is outside of bounding box formed by end points, split\n SkDRect bounds = {DBL_MAX, DBL_MAX, -DBL_MAX, -DBL_MAX};\n find_tight_bounds(cubic, bounds);\n if ( (!AlmostEqualUlps(reducer.fLine[0].fX, bounds.fLeft)\n && !AlmostEqualUlps(reducer.fLine[0].fX, bounds.fRight))\n || (!AlmostEqualUlps(reducer.fLine[0].fY, bounds.fTop)\n && !AlmostEqualUlps(reducer.fLine[0].fY, bounds.fBottom))\n || (!AlmostEqualUlps(reducer.fLine[1].fX, bounds.fLeft)\n && !AlmostEqualUlps(reducer.fLine[1].fX, bounds.fRight))\n || (!AlmostEqualUlps(reducer.fLine[1].fY, bounds.fTop)\n && !AlmostEqualUlps(reducer.fLine[1].fY, bounds.fBottom))) {\n SkDebugf(\"[%d] line computed tight bounds order=%d\\n\", static_cast(index), order);\n REPORTER_ASSERT(reporter, 0);\n }\n }\n }\n#endif\n}\n\n#include \"TestClassDef.h\"\n\nDEFINE_TESTCLASS_SHORT(PathOpsReduceOrderCubicTest)\n<|endoftext|>"} {"text":"\/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/linspace_op.h\"\n#include \n\nnamespace paddle {\nnamespace operators {\n\nclass LinspaceOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext *ctx) const override {\n OP_INOUT_CHECK(ctx->HasInput(\"Start\"), \"Input\", \"Start\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasInput(\"Stop\"), \"Input\", \"Stop\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasInput(\"Num\"), \"Input\", \"Num\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasOutput(\"Out\"), \"Output\", \"Out\", \"linspace\");\n\n auto s_dims = ctx->GetInputDim(\"Start\");\n PADDLE_ENFORCE_EQ((s_dims.size() == 1) && (s_dims[0] == 1), true,\n platform::errors::InvalidArgument(\n \"The shape of Input(Start) must be [1],\"\n \"but received input shape is [%s].\",\n s_dims));\n auto e_dims = ctx->GetInputDim(\"Stop\");\n PADDLE_ENFORCE_EQ((e_dims.size() == 1) && (e_dims[0] == 1), true,\n platform::errors::InvalidArgument(\n \"The shape of Input(Stop) must be [1],\"\n \"but received input shape is [%s].\",\n e_dims));\n auto step_dims = ctx->GetInputDim(\"Num\");\n PADDLE_ENFORCE_EQ(\n (step_dims.size() == 1) && (step_dims[0] == 1), true,\n platform::errors::InvalidArgument(\"The shape of Input(Num) must be [1],\"\n \"but received input shape is [%s].\",\n step_dims));\n ctx->SetOutputDim(\"Out\", {-1});\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext &ctx) const override {\n return framework::OpKernelType(\n framework::proto::VarType::Type(ctx.Attr(\"dtype\")),\n ctx.GetPlace());\n }\n\n framework::OpKernelType GetKernelTypeForVar(\n const std::string &var_name, const framework::Tensor &tensor,\n const framework::OpKernelType &expected_kernel_type) const override {\n return expected_kernel_type;\n }\n};\n\nclass LinspaceOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"Start\",\n \"First entry in the sequence. It is a tensor of shape [1], should \"\n \"be of type float32 or float64.\");\n AddInput(\"Stop\",\n \"Last entry in the sequence. It is a tensor of shape [1], should \"\n \"be of type float32 or float64.\");\n AddInput(\"Num\",\n \"Number of entry in the sequence. It is a tensor of shape [1], \"\n \"should be of type int32.\");\n AddAttr(\"dtype\", \"The output data type.\");\n AddOutput(\"Out\", \"A sequence of numbers.\");\n AddComment(R\"DOC(\n Return fixed number of evenly spaced values within a given interval. First entry is start, and last entry is stop. In the case when Num is 1, only Start is returned. Like linspace function of numpy.\n)DOC\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP_WITHOUT_GRADIENT(linspace, ops::LinspaceOp, ops::LinspaceOpMaker);\nREGISTER_OP_CPU_KERNEL(linspace, ops::CPULinspaceKernel,\n ops::CPULinspaceKernel,\n ops::CPULinspaceKernel,\n ops::CPULinspaceKernel);\nRegister op version for linspace,test=op_version (#30025)\/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/linspace_op.h\"\n#include \n#include \"paddle\/fluid\/framework\/op_version_registry.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass LinspaceOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext *ctx) const override {\n OP_INOUT_CHECK(ctx->HasInput(\"Start\"), \"Input\", \"Start\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasInput(\"Stop\"), \"Input\", \"Stop\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasInput(\"Num\"), \"Input\", \"Num\", \"linspace\");\n OP_INOUT_CHECK(ctx->HasOutput(\"Out\"), \"Output\", \"Out\", \"linspace\");\n\n auto s_dims = ctx->GetInputDim(\"Start\");\n PADDLE_ENFORCE_EQ((s_dims.size() == 1) && (s_dims[0] == 1), true,\n platform::errors::InvalidArgument(\n \"The shape of Input(Start) must be [1],\"\n \"but received input shape is [%s].\",\n s_dims));\n auto e_dims = ctx->GetInputDim(\"Stop\");\n PADDLE_ENFORCE_EQ((e_dims.size() == 1) && (e_dims[0] == 1), true,\n platform::errors::InvalidArgument(\n \"The shape of Input(Stop) must be [1],\"\n \"but received input shape is [%s].\",\n e_dims));\n auto step_dims = ctx->GetInputDim(\"Num\");\n PADDLE_ENFORCE_EQ(\n (step_dims.size() == 1) && (step_dims[0] == 1), true,\n platform::errors::InvalidArgument(\"The shape of Input(Num) must be [1],\"\n \"but received input shape is [%s].\",\n step_dims));\n ctx->SetOutputDim(\"Out\", {-1});\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext &ctx) const override {\n return framework::OpKernelType(\n framework::proto::VarType::Type(ctx.Attr(\"dtype\")),\n ctx.GetPlace());\n }\n\n framework::OpKernelType GetKernelTypeForVar(\n const std::string &var_name, const framework::Tensor &tensor,\n const framework::OpKernelType &expected_kernel_type) const override {\n return expected_kernel_type;\n }\n};\n\nclass LinspaceOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"Start\",\n \"First entry in the sequence. It is a tensor of shape [1], should \"\n \"be of type float32 or float64.\");\n AddInput(\"Stop\",\n \"Last entry in the sequence. It is a tensor of shape [1], should \"\n \"be of type float32 or float64.\");\n AddInput(\"Num\",\n \"Number of entry in the sequence. It is a tensor of shape [1], \"\n \"should be of type int32.\");\n AddAttr(\"dtype\", \"The output data type.\");\n AddOutput(\"Out\", \"A sequence of numbers.\");\n AddComment(R\"DOC(\n Return fixed number of evenly spaced values within a given interval. First entry is start, and last entry is stop. In the case when Num is 1, only Start is returned. Like linspace function of numpy.\n)DOC\");\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP_WITHOUT_GRADIENT(linspace, ops::LinspaceOp, ops::LinspaceOpMaker);\nREGISTER_OP_CPU_KERNEL(linspace, ops::CPULinspaceKernel,\n ops::CPULinspaceKernel,\n ops::CPULinspaceKernel,\n ops::CPULinspaceKernel);\n\nREGISTER_OP_VERSION(linspace)\n .AddCheckpoint(\n R\"ROC(\n Upgrade linspace to add a new attribute [dtype].\n )ROC\",\n paddle::framework::compatible::OpVersionDesc().NewAttr(\n \"dtype\", \"In order to change output data type \", 5));\n<|endoftext|>"} {"text":"\/*\n * Tests for the scalar example solving the test equation\n *\/\n#include \n\n#include \n#include \n\nusing namespace ::testing;\n\n#define PFASST_UNIT_TESTING\n#include \"..\/examples\/scalar\/scalar_sdc.cpp\"\n#undef PFASST_UNIT_TESTING\n\n\/*\n * parameterized test fixture with number of nodes as parameter\n *\/\nclass ConvergenceTest\n : public ::testing::TestWithParam\n{\n protected:\n size_t nnodes; \/\/ parameter\n\n const complex lambda = complex(-1.0, 1.0);\n const double Tend = 4.0;\n const vector nsteps = { 2, 5, 10, 15, 20 };\n size_t nsteps_l;\n vector err;\n vector convrate;\n vector convrate_legendre;\n double dt;\n size_t niters;\n pfasst::QuadratureType nodetype = pfasst::QuadratureType::GaussLobatto;\n\n public:\n virtual void SetUp()\n {\n this->nnodes = this->GetParam();\n this->nsteps_l = this->nsteps.size();\n this->err.resize(this->nsteps.size());\n this->convrate.resize(this->nsteps.size());\n \n \/\/ Run first for Lobatto nodes\n\n\n \/\/ Expect convergence rate of 2*nodes-2 from collocation formula,\n \/\/ doing an identical number of iteration should suffice to reach this as each\n \/\/ iteration should increase order by one\n this->niters = 2 * nnodes - 2;\n\n \/\/ run to compute errors\n for (size_t i = 0; i <= nsteps_l - 1; ++i) {\n dt = Tend \/ double(nsteps[i]);\n err[i] = run_scalar_sdc(nsteps[i], dt, nnodes, niters, lambda, nodetype);\n }\n\n \/\/ compute convergence rates\n for (size_t i = 0; i <= nsteps_l - 2; ++i) {\n convrate[i] = log10(err[i+1] \/ err[i]) \/ log10(double(nsteps[i]) \/ double(nsteps[i + 1]));\n }\n \n \/\/ Run for Legendre nodes\n nodetype = pfasst::QuadratureType::GaussLegendre;\n this->convrate_legendre.resize(this->nsteps.size());\n \n \/\/ NOTE: Setting M for Legendre nodes actually only results in M-2 \"real\" nodes,\n \/\/ because the first and the last are used for initial and final value.\n this->niters = 2*(nnodes-2);\n \n }\n\n virtual void TearDown()\n {}\n};\n\n\/*\n * For Lobatto nodes, the resulting method should of order 2*M-2 with M=number of nodes\n * The test below verifies that the code approximately (up to a safety factor) reproduces\n * the theoretically expected rate of convergence \n *\/\nTEST_P(ConvergenceTest, GaussLobattoNodes)\n{\n for (size_t i = 0; i <= nsteps_l - 2; ++i) {\n\n EXPECT_THAT(convrate[i],\n testing::DoubleNear(double(2 * nnodes - 2), 0.99)) << \"Convergence rate at node \"\n << i\n << \" not within expected range\";\n }\n}\n\nINSTANTIATE_TEST_CASE_P(ScalarSDC, ConvergenceTest, Range(2, 7));\n\nint main(int argc, char** argv)\n{\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\ntest_scalar now also checks legendre nodes, but the test with DoubleNear fail, because we encounter better-than-expected convergence. Need a DoubleMore, but I did not get a corresponding matcher to run properly\/*\n * Tests for the scalar example solving the test equation\n *\/\n#include \n\n#include \n#include \n\nusing namespace ::testing;\n\n#define PFASST_UNIT_TESTING\n#include \"..\/examples\/scalar\/scalar_sdc.cpp\"\n#undef PFASST_UNIT_TESTING\n\nMATCHER(MyDoubleMore, \"\")\n{\n return get<0>(arg) > get<1>(arg);\n}\n\n\n\/*\n * parameterized test fixture with number of nodes as parameter\n *\/\nclass ConvergenceTest\n : public ::testing::TestWithParam\n{\n protected:\n size_t nnodes; \/\/ parameter\n\n complex lambda = complex(-1.0, 1.0);\n double Tend = 4.0;\n vector nsteps = { 2, 5, 10, 15, 20 };\n size_t nsteps_l;\n vector err;\n vector convrate_lobatto;\n vector convrate_legendre;\n double dt;\n size_t niters;\n pfasst::QuadratureType nodetype = pfasst::QuadratureType::GaussLobatto;\n\n public:\n virtual void SetUp()\n {\n this->nnodes = this->GetParam();\n this->nsteps_l = this->nsteps.size();\n this->err.resize(this->nsteps.size());\n this->convrate_lobatto.resize(this->nsteps.size());\n \n \/\/ Run first for Lobatto nodes which is the default nodetype\n\n \/\/ Expect convergence rate of 2*nodes-2 from collocation formula,\n \/\/ doing an identical number of iteration should suffice to reach this as each\n \/\/ iteration should increase order by one\n this->niters = 2 * nnodes - 2;\n\n \/\/ run to compute errors\n for (size_t i = 0; i <= nsteps_l - 1; ++i) {\n dt = Tend \/ double(nsteps[i]);\n err[i] = run_scalar_sdc(nsteps[i], dt, nnodes, niters, lambda, nodetype);\n }\n\n \/\/ compute convergence rates\n for (size_t i = 0; i <= nsteps_l - 2; ++i) {\n convrate_lobatto[i] = log10(err[i+1] \/ err[i]) \/ log10(double(nsteps[i]) \/ double(nsteps[i + 1]));\n }\n \n \/\/ Run for Legendre nodes\n nodetype = pfasst::QuadratureType::GaussLegendre;\n this->convrate_legendre.resize(this->nsteps.size());\n \n \/\/ refine parameter\n complex lambda = complex(-1.0, 4.0); \n this->Tend = 5.0;\n this->nsteps = { 5, 7, 9, 11, 13 };\n this->niters = 2*nnodes;\n \n \/\/ run to compute errors\n for (size_t i = 0; i <= nsteps_l - 1; ++i) {\n dt = Tend \/ double(nsteps[i]);\n \n \/\/ NOTE: Setting M for Legendre nodes actually only results in M-2 \"real\" nodes,\n \/\/ because the first and the last are used for initial and final value. \n \/\/ Hence us nnodes+2 as argument \n err[i] = run_scalar_sdc(nsteps[i], dt, nnodes+2, niters, lambda, nodetype);\n }\n \n for (size_t i = 0; i <= nsteps_l - 2; ++i) {\n convrate_legendre[i] = log10(err[i+1] \/ err[i]) \/ log10(double(nsteps[i]) \/ double(nsteps[i + 1]));\n }\n \n }\n\n virtual void TearDown()\n {}\n};\n\n\/*\n * For Lobatto nodes, the resulting method should of order 2*M-2 with M=number of nodes\n * The test below verifies that the code approximately (up to a safety factor) reproduces\n * the theoretically expected rate of convergence \n *\/\nTEST_P(ConvergenceTest, GaussNodes)\n{\n for (size_t i = 0; i <= nsteps_l - 2; ++i) {\n\n EXPECT_THAT(convrate_lobatto[i],\n testing::DoubleNear(double(2 * nnodes - 2), 0.99)) << \"Convergence rate at node \"\n << i\n << \" not within expected range\";\n EXPECT_THAT(convrate_legendre[i],\n testing::DoubleNear(double(2 * nnodes ), 0.9)) << \"Convergence rate at node \"\n << i\n << \" not within expected range\"; \n\n }\n}\n\nINSTANTIATE_TEST_CASE_P(ScalarSDC, ConvergenceTest, Range(2, 7));\n\nint main(int argc, char** argv)\n{\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/************************************************************************************\nThis source file is part of the Theora Video Playback Library\nFor latest info, see http:\/\/libtheoraplayer.googlecode.com\n*************************************************************************************\nCopyright (c) 2008-2014 Kresimir Spes (kspes@cateia.com)\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n*************************************************************************************\/\n#include \n#include \n#include \n#include \"TheoraDataSource.h\"\n#include \"TheoraException.h\"\n#include \"TheoraVideoManager.h\"\n#include \"TheoraUtil.h\"\n\nTheoraDataSource::~TheoraDataSource()\n{\n\n}\n\nTheoraFileDataSource::TheoraFileDataSource(std::string filename)\n{\n\tmFilename = filename;\n\tmFilePtr = NULL;\n}\n\nTheoraFileDataSource::~TheoraFileDataSource()\n{\n\tif (mFilePtr)\n\t{\n\t\tfclose(mFilePtr);\n\t\tmFilePtr = NULL;\n\t}\n}\n\nvoid TheoraFileDataSource::openFile()\n{\n\tif (mFilePtr == NULL)\n\t{\n\t\tmFilePtr = fopen(mFilename.c_str(), \"rb\");\n\t\tif (!mFilePtr)\n {\n std::string msg = \"Can't open video file: \" + mFilename;\n th_writelog(msg);\n throw TheoraGenericException(msg);\n }\n\n\t\t\n#ifdef _WIN32\n\t\tstruct _stat64 s;\n\t\t_fstati64(_fileno(mFilePtr), &s);\n#else\n\t\tstruct stat s;\n\t\tfstat(fileno(mFilePtr), &s);\n#endif\n\t\tmSize = (uint64_t) s.st_size;\n\t}\n}\n\nint TheoraFileDataSource::read(void* output, int nBytes)\n{\n\tif (mFilePtr == NULL) openFile();\n\tuint64_t n = fread(output, 1, nBytes, mFilePtr);\n\treturn (int) n;\n}\n\nvoid TheoraFileDataSource::seek(uint64_t byte_index)\n{\n\tif (mFilePtr == NULL) openFile();\n\tfpos_t fpos = byte_index;\n\tfsetpos(mFilePtr, &fpos);\n}\n\nuint64_t TheoraFileDataSource::size()\n{\n\tif (mFilePtr == NULL) openFile();\n\treturn mSize;\n}\n\nuint64_t TheoraFileDataSource::tell()\n{\n\tif (mFilePtr == NULL) return 0;\n\tfpos_t pos;\n\tfgetpos(mFilePtr, &pos);\n\treturn (uint64_t) pos;\n}\n\nTheoraMemoryFileDataSource::TheoraMemoryFileDataSource(std::string filename) :\n\tmReadPointer(0),\n\tmData(0)\n{\n\tmFilename=filename;\n\tFILE* f = fopen(filename.c_str(),\"rb\");\n\tif (!f) throw TheoraGenericException(\"Can't open video file: \" + filename);\n\n#ifdef _WIN32\n\tstruct _stat64 s;\n\t_fstati64(_fileno(f), &s);\n#else\n\tstruct stat s;\n\tfstat(fileno(f), &s);\n#endif\n\tmSize = (uint64_t) s.st_size;\n\tmData = new unsigned char[(unsigned int) mSize];\n\tif (mSize < UINT_MAX)\n\t{\n\t\tfread(mData, 1, (size_t) mSize, f);\n\t}\n\telse\n\t{\n\t\tthrow TheoraGenericException(\"Unable to preload file to memory, file is too large.\");\n\t}\n\n\tfclose(f);\n}\n\nTheoraMemoryFileDataSource::TheoraMemoryFileDataSource(unsigned char* data, long size, const std::string& filename)\n{\n\tmFilename = filename;\n\tmData = data;\n\tmSize = size;\n\tmReadPointer = 0;\n}\n\nTheoraMemoryFileDataSource::~TheoraMemoryFileDataSource()\n{\n\tif (mData) delete [] mData;\n}\n\nint TheoraMemoryFileDataSource::read(void* output, int nBytes)\n{\n\tint n = (int) ((mReadPointer+nBytes <= mSize) ? nBytes : mSize - mReadPointer);\n\tif (!n) return 0;\n\tmemcpy(output, mData + mReadPointer, n);\n\tmReadPointer += n;\n\treturn n;\n}\n\nvoid TheoraMemoryFileDataSource::seek(uint64_t byte_index)\n{\n\tmReadPointer = byte_index;\n}\n\nuint64_t TheoraMemoryFileDataSource::size()\n{\n\treturn mSize;\n}\n\nuint64_t TheoraMemoryFileDataSource::tell()\n{\n\treturn mReadPointer;\n}\nadded an informative exception in memory data source indicating that memory preloaded files larger than 4GB are not supported.\/************************************************************************************\nThis source file is part of the Theora Video Playback Library\nFor latest info, see http:\/\/libtheoraplayer.googlecode.com\n*************************************************************************************\nCopyright (c) 2008-2014 Kresimir Spes (kspes@cateia.com)\nThis program is free software; you can redistribute it and\/or modify it under\nthe terms of the BSD license: http:\/\/opensource.org\/licenses\/BSD-3-Clause\n*************************************************************************************\/\n#include \n#include \n#include \n#include \"TheoraDataSource.h\"\n#include \"TheoraException.h\"\n#include \"TheoraVideoManager.h\"\n#include \"TheoraUtil.h\"\n\nTheoraDataSource::~TheoraDataSource()\n{\n\n}\n\nTheoraFileDataSource::TheoraFileDataSource(std::string filename)\n{\n\tmFilename = filename;\n\tmFilePtr = NULL;\n}\n\nTheoraFileDataSource::~TheoraFileDataSource()\n{\n\tif (mFilePtr)\n\t{\n\t\tfclose(mFilePtr);\n\t\tmFilePtr = NULL;\n\t}\n}\n\nvoid TheoraFileDataSource::openFile()\n{\n\tif (mFilePtr == NULL)\n\t{\n\t\tmFilePtr = fopen(mFilename.c_str(), \"rb\");\n\t\tif (!mFilePtr)\n {\n std::string msg = \"Can't open video file: \" + mFilename;\n th_writelog(msg);\n throw TheoraGenericException(msg);\n }\n\n\t\t\n#ifdef _WIN32\n\t\tstruct _stat64 s;\n\t\t_fstati64(_fileno(mFilePtr), &s);\n#else\n\t\tstruct stat s;\n\t\tfstat(fileno(mFilePtr), &s);\n#endif\n\t\tmSize = (uint64_t) s.st_size;\n\t}\n}\n\nint TheoraFileDataSource::read(void* output, int nBytes)\n{\n\tif (mFilePtr == NULL) openFile();\n\tuint64_t n = fread(output, 1, nBytes, mFilePtr);\n\treturn (int) n;\n}\n\nvoid TheoraFileDataSource::seek(uint64_t byte_index)\n{\n\tif (mFilePtr == NULL) openFile();\n\tfpos_t fpos = byte_index;\n\tfsetpos(mFilePtr, &fpos);\n}\n\nuint64_t TheoraFileDataSource::size()\n{\n\tif (mFilePtr == NULL) openFile();\n\treturn mSize;\n}\n\nuint64_t TheoraFileDataSource::tell()\n{\n\tif (mFilePtr == NULL) return 0;\n\tfpos_t pos;\n\tfgetpos(mFilePtr, &pos);\n\treturn (uint64_t) pos;\n}\n\nTheoraMemoryFileDataSource::TheoraMemoryFileDataSource(std::string filename) :\n\tmReadPointer(0),\n\tmData(0)\n{\n\tmFilename = filename;\n\tFILE* f = fopen(filename.c_str(),\"rb\");\n\tif (!f) throw TheoraGenericException(\"Can't open video file: \" + filename);\n\n#ifdef _WIN32\n\tstruct _stat64 s;\n\t_fstati64(_fileno(f), &s);\n#else\n\tstruct stat s;\n\tfstat(fileno(f), &s);\n#endif\n\tmSize = (uint64_t) s.st_size;\n\tif (mSize > 0xFFFFFFFF)\n\t{\n\t\tthrow TheoraGenericException(\"TheoraMemoryFileDataSource doesn't support files larger than 4GB!\");\n\t}\n\tmData = new unsigned char[(unsigned int) mSize];\n\tif (mSize < UINT_MAX)\n\t{\n\t\tfread(mData, 1, (size_t) mSize, f);\n\t}\n\telse\n\t{\n\t\tthrow TheoraGenericException(\"Unable to preload file to memory, file is too large.\");\n\t}\n\n\tfclose(f);\n}\n\nTheoraMemoryFileDataSource::TheoraMemoryFileDataSource(unsigned char* data, long size, const std::string& filename)\n{\n\tmFilename = filename;\n\tmData = data;\n\tmSize = size;\n\tmReadPointer = 0;\n}\n\nTheoraMemoryFileDataSource::~TheoraMemoryFileDataSource()\n{\n\tif (mData) delete [] mData;\n}\n\nint TheoraMemoryFileDataSource::read(void* output, int nBytes)\n{\n\tint n = (int) ((mReadPointer+nBytes <= mSize) ? nBytes : mSize - mReadPointer);\n\tif (!n) return 0;\n\tmemcpy(output, mData + mReadPointer, n);\n\tmReadPointer += n;\n\treturn n;\n}\n\nvoid TheoraMemoryFileDataSource::seek(uint64_t byte_index)\n{\n\tmReadPointer = byte_index;\n}\n\nuint64_t TheoraMemoryFileDataSource::size()\n{\n\treturn mSize;\n}\n\nuint64_t TheoraMemoryFileDataSource::tell()\n{\n\treturn mReadPointer;\n}\n<|endoftext|>"} {"text":"#ifndef PERSISTENT_HPP\n#define PERSISTENT_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"HLC.hpp\"\n#include \"PersistException.hpp\"\n#include \"PersistLog.hpp\"\n#include \"FilePersistLog.hpp\"\n#include \"SerializationSupport.hpp\"\n\nusing namespace mutils;\n\nnamespace ns_persistent {\n\n \/\/ #define DEFINE_PERSIST_VAR(_t,_n) DEFINE_PERSIST_VAR(_t,_n,ST_FILE)\n #define DEFINE_PERSIST_VAR(_t,_n,_s) \\\n Persistent<_t, _s> _n(# _n)\n #define DECLARE_PERSIST_VAR(_t,_n,_s) \\\n extern DEFINE_PERSIST_VAR(_t,_n,_s)\n\n \/* deprecated\n \/\/ number of versions in the cache\n #define MAX_NUM_CACHED_VERSION (1024)\n #define VERSION_HASH(v) ( (int)((v) & (MAX_NUM_CACHED_VERSION-1)) )\n\n \/\/ invalid version:\n #define INVALID_VERSION (-1ll)\n\n \/\/ read from cache\n #define VERSION_IS_CACHED(v) (this->m_aCache[VERSION_HASH(v)].ver == (v))\n #define GET_CACHED_OBJ_PTR(v) (this->m_aCache[VERSION_HASH(v)].obj)\n *\/\n\n \/\/ function types to be registered for create version\n \/\/ or persist version\n using VersionFunc = std::function;\n using PersistFunc = std::function;\n using FuncRegisterCallback = std::function;\n\n \/\/ Persistent represents a variable backed up by persistent storage. The\n \/\/ backend is PersistLog class. PersistLog handles only raw bytes and this\n \/\/ class is repsonsible for converting it back and forth between raw bytes\n \/\/ and ObjectType. But, the serialization\/deserialization functionality is\n \/\/ actually defined by ObjectType and provided by Persistent users.\n \/\/ - ObjectType: user-defined type of the variable it is required to support\n \/\/ serialization and deserialization as follows:\n \/\/ \/\/ serialize\n \/\/ void * ObjectType::serialize(const ObjectType & obj, uint64_t *psize)\n \/\/ - obj: obj is the reference to the object to be serialized\n \/\/ - psize: psize is a uint64_t pointer to receive the size of the serialized\n \/\/ data.\n \/\/ - Return value is a pointer to a new malloced buffer with the serialized\n \/\/ \/\/TODO: this may not be efficient for large object...open to be changed.\n \/\/ \/\/ deserialize\n \/\/ ObjectType * ObjectType::deserialize(const void *pdata)\n \/\/ - pdata: a buffer of the serialized data\n \/\/ - Return value is a pointer to a new created ObjectType deserialized from\n \/\/ 'pdata' buffer.\n \/\/ - StorageType: storage type is defined in PersistLog. The value could be\n \/\/ ST_FILE\/ST_MEM\/ST_3DXP ... I will start with ST_FILE and extend it to\n \/\/ other persistent Storage.\n \/\/ TODO:comments\n template \n class Persistent{\n public:\n \/** The constructor\n * @param func_register_cb Call this to register myself to Replicated\n * @param object_name This name is used for persistent data in file.\n *\/\n Persistent(FuncRegisterCallback func_register_cb=nullptr,\n const char * object_name = (*Persistent::getNameMaker().make()).c_str())\n noexcept(false) {\n \/\/ Initialize log\n this->m_pLog = NULL;\n switch(storageType){\n \/\/ file system\n case ST_FILE:\n this->m_pLog = new FilePersistLog(object_name);\n if(this->m_pLog == NULL){\n throw PERSIST_EXP_NEW_FAILED_UNKNOWN;\n }\n break;\n \/\/ volatile\n case ST_MEM:\n {\n const string tmpfsPath = \"\/dev\/shm\/volatile_t\";\n this->m_pLog = new FilePersistLog(object_name, tmpfsPath);\n if(this->m_pLog == NULL){\n throw PERSIST_EXP_NEW_FAILED_UNKNOWN;\n }\n break;\n }\n \/\/default\n default:\n throw PERSIST_EXP_STORAGE_TYPE_UNKNOWN(storageType);\n }\n \/\/register the version creator and persist callback\n if(func_register_cb != nullptr){\n func_register_cb(\n std::bind(&Persistent::version,this,std::placeholders::_1),\n std::bind(&Persistent::persist,this)\n );\n }\n }\n \/\/ destructor: release the resources\n virtual ~Persistent() noexcept(false){\n \/\/ destroy the in-memory log\n if(this->m_pLog != NULL){\n delete this->m_pLog;\n }\n \/\/TODO:unregister the version creator and persist callback,\n \/\/ if the Persistent is added to the pool dynamically.\n };\n\n \/**\n * * operator to get the memory version\n * @return ObjectType&\n *\/\n ObjectType& operator * (){\n return this->wrapped_obj;\n }\n\n \/\/ get the latest Value of T. The user lambda will be fed with the latest object\n \/\/ zerocopy:this object will not live once it returns.\n \/\/ return value is decided by user lambda\n template \n auto get (\n const Func& fun, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return this->getByIndex(-1L,fun,dm);\n };\n\n \/\/ get the latest Value of T, returns a unique pointer to the object\n std::unique_ptr get ( DeserializationManager *dm=nullptr)\n noexcept(false) {\n return this->getByIndex(-1L,dm);\n };\n\n \/\/ get a version of Value T. the user lambda will be fed with the given object\n \/\/ zerocopy:this object will not live once it returns.\n \/\/ return value is decided by user lambda\n template \n auto getByIndex (\n int64_t idx, \n const Func& fun, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return deserialize_and_run(dm,(char *)this->m_pLog->getEntryByIndex(idx),fun);\n };\n\n \/\/ get a version of value T. returns a unique pointer to the object\n std::unique_ptr getByIndex(\n int64_t idx, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return from_bytes(dm,(char const *)this->m_pLog->getEntryByIndex(idx)); \n };\n\n \/\/ get a version of Value T, specified by version. the user lambda will be fed with\n \/\/ an object of T.\n \/\/ zerocopy: this object will not live once it returns.\n \/\/ return value is decided by the user lambda.\n template \n auto get (\n const __int128 & ver,\n const Func& fun,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char * pdat = (char*)this->m_pLog->getEntry(ver);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_VERSION;\n }\n return deserialize_and_run(dm,pdat,fun);\n };\n\n \/\/ get a version of value T. specified version.\n \/\/ return a deserialized copy for the variable.\n std::unique_ptr get(\n const __int128 & ver,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char const * pdat = (char const *)this->m_pLog->getEntry(ver);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_VERSION;\n }\n\n return from_bytes(dm,pdat);\n }\n\n template \n void trim (const TKey &k) noexcept(false) {\n dbg_trace(\"trim.\");\n this->m_pLog->trim(k);\n dbg_trace(\"trim...done\");\n }\n\n \/\/ get a version of Value T, specified by HLC clock. the user lambda will be fed with\n \/\/ an object of T.\n \/\/ zerocopy: this object will not live once it returns.\n \/\/ return value is decided by the user lambda.\n template \n auto get (\n const HLC& hlc,\n const Func& fun,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char * pdat = (char*)this->m_pLog->getEntry(hlc);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_HLC;\n }\n return deserialize_and_run(dm,pdat,fun);\n };\n\n \/\/ get a version of value T. specified by HLC clock.\n std::unique_ptr get(\n const HLC& hlc,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char const * pdat = (char const *)this->m_pLog->getEntry(hlc);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_HLC;\n }\n\n return from_bytes(dm,pdat);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](int64_t idx)\n noexcept(false) {\n return this->getByIndex(idx);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](const __int128 ver)\n noexcept(false) {\n return this->get(ver);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](const HLC & hlc)\n noexcept(false) {\n return this->get(hlc);\n }\n\n \/\/ get number of the versions\n virtual int64_t getNumOfVersions() noexcept(false) {\n return this->m_pLog->getLength();\n };\n\n virtual int64_t getEarliestIndex() noexcept(false) {\n return this->m_pLog->getEarliestIndex();\n }\n\n \/\/ make a version with version and mhlc clock\n virtual void set(const ObjectType &v, const __int128 & ver, const HLC &mhlc) \n noexcept(false) {\n auto size = bytes_size(v);\n char buf[size];\n bzero(buf,size);\n to_bytes(v,buf);\n this->m_pLog->append((void*)buf,size,ver,mhlc);\n };\n\n \/\/ make a version with version\n virtual void set(const ObjectType &v, const __int128 & ver)\n noexcept(false) {\n HLC mhlc; \/\/ generate a default timestamp for it.\n this->set(v,ver,mhlc);\n }\n\n \/\/ make a version\n virtual void version(const __int128 & ver)\n noexcept(false) {\n this->set(this->wrapped_obj,ver);\n }\n\n \/** persist till version\n * @param ver version number\n * @return the given version to be persisted.\n *\/\n virtual const __int128 persist()\n noexcept(false){\n return this->m_pLog->persist();\n }\n\n \/\/ internal _NameMaker class\n class _NameMaker{\n public:\n \/\/ Constructor\n _NameMaker() noexcept(false):\n m_sObjectTypeName(typeid(ObjectType).name()) {\n this->m_iCounter = 0;\n if (pthread_spin_init(&this->m_oLck,PTHREAD_PROCESS_SHARED) != 0) {\n throw PERSIST_EXP_SPIN_INIT(errno);\n }\n }\n\n \/\/ Destructor\n virtual ~_NameMaker() noexcept(true) {\n pthread_spin_destroy(&this->m_oLck);\n }\n\n \/\/ guess a name\n std::unique_ptr make() noexcept(false) {\n int cnt;\n if (pthread_spin_lock(&this->m_oLck) != 0) {\n throw PERSIST_EXP_SPIN_LOCK(errno);\n }\n cnt = this->m_iCounter++;\n if (pthread_spin_unlock(&this->m_oLck) != 0) {\n throw PERSIST_EXP_SPIN_UNLOCK(errno);\n }\n std::unique_ptr ret = std::make_unique();\n \/\/char * buf = (char *)malloc((strlen(this->m_sObjectTypeName)+13)\/8*8);\n char buf[256];\n sprintf(buf,\"%s-%d\",this->m_sObjectTypeName,cnt);\n \/\/ return std::make_shared((const char*)buf);\n *ret = buf;\n return ret;\n }\n\n private:\n int m_iCounter;\n const char *m_sObjectTypeName;\n pthread_spinlock_t m_oLck;\n };\n\n private:\n \/\/ wrapped objected\n ObjectType wrapped_obj;\n \n \/\/ PersistLog\n PersistLog * m_pLog;\n\n \/\/ get the static name maker.\n static _NameMaker & getNameMaker();\n };\n\n \/\/ How many times the constructor was called.\n template \n typename Persistent::_NameMaker & \n Persistent::getNameMaker() noexcept(false) {\n static Persistent::_NameMaker nameMaker;\n return nameMaker;\n }\n\n template \n class Volatile: public Persistent{\n public:\n \/\/ constructor: this will guess the objectname form ObjectType\n Volatile() noexcept(false):\n Persistent(){\n };\n \/\/ destructor:\n virtual ~Volatile() noexcept(false){\n \/\/ do nothing\n };\n };\n}\n\n\n#endif\/\/PERSIST_VAR_H\nadded registry definition to Persistent, TODO: add registry to Replicate.#ifndef PERSISTENT_HPP\n#define PERSISTENT_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"HLC.hpp\"\n#include \"PersistException.hpp\"\n#include \"PersistLog.hpp\"\n#include \"FilePersistLog.hpp\"\n#include \"SerializationSupport.hpp\"\n\nusing namespace mutils;\n\nnamespace ns_persistent {\n\n \/\/ #define DEFINE_PERSIST_VAR(_t,_n) DEFINE_PERSIST_VAR(_t,_n,ST_FILE)\n #define DEFINE_PERSIST_VAR(_t,_n,_s) \\\n Persistent<_t, _s> _n(# _n)\n #define DECLARE_PERSIST_VAR(_t,_n,_s) \\\n extern DEFINE_PERSIST_VAR(_t,_n,_s)\n\n \/* deprecated\n \/\/ number of versions in the cache\n #define MAX_NUM_CACHED_VERSION (1024)\n #define VERSION_HASH(v) ( (int)((v) & (MAX_NUM_CACHED_VERSION-1)) )\n\n \/\/ invalid version:\n #define INVALID_VERSION (-1ll)\n\n \/\/ read from cache\n #define VERSION_IS_CACHED(v) (this->m_aCache[VERSION_HASH(v)].ver == (v))\n #define GET_CACHED_OBJ_PTR(v) (this->m_aCache[VERSION_HASH(v)].obj)\n *\/\n\n \/\/ function types to be registered for create version\n \/\/ , persist version, and trim a version\n using VersionFunc = std::function;\n using PersistFunc = std::function;\n using TrimFunc = std::function;\n using FuncRegisterCallback = std::function;\n\n \/\/ Persistent represents a variable backed up by persistent storage. The\n \/\/ backend is PersistLog class. PersistLog handles only raw bytes and this\n \/\/ class is repsonsible for converting it back and forth between raw bytes\n \/\/ and ObjectType. But, the serialization\/deserialization functionality is\n \/\/ actually defined by ObjectType and provided by Persistent users.\n \/\/ - ObjectType: user-defined type of the variable it is required to support\n \/\/ serialization and deserialization as follows:\n \/\/ \/\/ serialize\n \/\/ void * ObjectType::serialize(const ObjectType & obj, uint64_t *psize)\n \/\/ - obj: obj is the reference to the object to be serialized\n \/\/ - psize: psize is a uint64_t pointer to receive the size of the serialized\n \/\/ data.\n \/\/ - Return value is a pointer to a new malloced buffer with the serialized\n \/\/ \/\/TODO: this may not be efficient for large object...open to be changed.\n \/\/ \/\/ deserialize\n \/\/ ObjectType * ObjectType::deserialize(const void *pdata)\n \/\/ - pdata: a buffer of the serialized data\n \/\/ - Return value is a pointer to a new created ObjectType deserialized from\n \/\/ 'pdata' buffer.\n \/\/ - StorageType: storage type is defined in PersistLog. The value could be\n \/\/ ST_FILE\/ST_MEM\/ST_3DXP ... I will start with ST_FILE and extend it to\n \/\/ other persistent Storage.\n \/\/ TODO:comments\n template \n class Persistent{\n public:\n \/** The constructor\n * @param func_register_cb Call this to register myself to Replicated\n * @param object_name This name is used for persistent data in file.\n *\/\n Persistent(FuncRegisterCallback func_register_cb=nullptr,\n const char * object_name = (*Persistent::getNameMaker().make()).c_str())\n noexcept(false) {\n \/\/ Initialize log\n this->m_pLog = NULL;\n switch(storageType){\n \/\/ file system\n case ST_FILE:\n this->m_pLog = new FilePersistLog(object_name);\n if(this->m_pLog == NULL){\n throw PERSIST_EXP_NEW_FAILED_UNKNOWN;\n }\n break;\n \/\/ volatile\n case ST_MEM:\n {\n const string tmpfsPath = \"\/dev\/shm\/volatile_t\";\n this->m_pLog = new FilePersistLog(object_name, tmpfsPath);\n if(this->m_pLog == NULL){\n throw PERSIST_EXP_NEW_FAILED_UNKNOWN;\n }\n break;\n }\n \/\/default\n default:\n throw PERSIST_EXP_STORAGE_TYPE_UNKNOWN(storageType);\n }\n \/\/register the version creator and persist callback\n if(func_register_cb != nullptr){\n func_register_cb(\n std::bind(&Persistent::version,this,std::placeholders::_1),\n std::bind(&Persistent::persist,this),\n std::bind(&Persistent::trim,this,std::placeholders::_1) \/\/trim by version:(const __int128)\n );\n }\n }\n \/\/ destructor: release the resources\n virtual ~Persistent() noexcept(false){\n \/\/ destroy the in-memory log\n if(this->m_pLog != NULL){\n delete this->m_pLog;\n }\n \/\/TODO:unregister the version creator and persist callback,\n \/\/ if the Persistent is added to the pool dynamically.\n };\n\n \/**\n * * operator to get the memory version\n * @return ObjectType&\n *\/\n ObjectType& operator * (){\n return this->wrapped_obj;\n }\n\n \/\/ get the latest Value of T. The user lambda will be fed with the latest object\n \/\/ zerocopy:this object will not live once it returns.\n \/\/ return value is decided by user lambda\n template \n auto get (\n const Func& fun, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return this->getByIndex(-1L,fun,dm);\n };\n\n \/\/ get the latest Value of T, returns a unique pointer to the object\n std::unique_ptr get ( DeserializationManager *dm=nullptr)\n noexcept(false) {\n return this->getByIndex(-1L,dm);\n };\n\n \/\/ get a version of Value T. the user lambda will be fed with the given object\n \/\/ zerocopy:this object will not live once it returns.\n \/\/ return value is decided by user lambda\n template \n auto getByIndex (\n int64_t idx, \n const Func& fun, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return deserialize_and_run(dm,(char *)this->m_pLog->getEntryByIndex(idx),fun);\n };\n\n \/\/ get a version of value T. returns a unique pointer to the object\n std::unique_ptr getByIndex(\n int64_t idx, \n DeserializationManager *dm=nullptr)\n noexcept(false) {\n return from_bytes(dm,(char const *)this->m_pLog->getEntryByIndex(idx)); \n };\n\n \/\/ get a version of Value T, specified by version. the user lambda will be fed with\n \/\/ an object of T.\n \/\/ zerocopy: this object will not live once it returns.\n \/\/ return value is decided by the user lambda.\n template \n auto get (\n const __int128 & ver,\n const Func& fun,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char * pdat = (char*)this->m_pLog->getEntry(ver);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_VERSION;\n }\n return deserialize_and_run(dm,pdat,fun);\n };\n\n \/\/ get a version of value T. specified version.\n \/\/ return a deserialized copy for the variable.\n std::unique_ptr get(\n const __int128 & ver,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char const * pdat = (char const *)this->m_pLog->getEntry(ver);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_VERSION;\n }\n\n return from_bytes(dm,pdat);\n }\n\n template \n void trim (const TKey &k) noexcept(false) {\n dbg_trace(\"trim.\");\n this->m_pLog->trim(k);\n dbg_trace(\"trim...done\");\n }\n\n \/\/ get a version of Value T, specified by HLC clock. the user lambda will be fed with\n \/\/ an object of T.\n \/\/ zerocopy: this object will not live once it returns.\n \/\/ return value is decided by the user lambda.\n template \n auto get (\n const HLC& hlc,\n const Func& fun,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char * pdat = (char*)this->m_pLog->getEntry(hlc);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_HLC;\n }\n return deserialize_and_run(dm,pdat,fun);\n };\n\n \/\/ get a version of value T. specified by HLC clock.\n std::unique_ptr get(\n const HLC& hlc,\n DeserializationManager *dm=nullptr)\n noexcept(false) {\n char const * pdat = (char const *)this->m_pLog->getEntry(hlc);\n if (pdat == nullptr) {\n throw PERSIST_EXP_INV_HLC;\n }\n\n return from_bytes(dm,pdat);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](int64_t idx)\n noexcept(false) {\n return this->getByIndex(idx);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](const __int128 ver)\n noexcept(false) {\n return this->get(ver);\n }\n\n \/\/ syntax sugar: get a specified version of T without DSM\n std::unique_ptr operator [](const HLC & hlc)\n noexcept(false) {\n return this->get(hlc);\n }\n\n \/\/ get number of the versions\n virtual int64_t getNumOfVersions() noexcept(false) {\n return this->m_pLog->getLength();\n };\n\n virtual int64_t getEarliestIndex() noexcept(false) {\n return this->m_pLog->getEarliestIndex();\n }\n\n \/\/ make a version with version and mhlc clock\n virtual void set(const ObjectType &v, const __int128 & ver, const HLC &mhlc) \n noexcept(false) {\n auto size = bytes_size(v);\n char buf[size];\n bzero(buf,size);\n to_bytes(v,buf);\n this->m_pLog->append((void*)buf,size,ver,mhlc);\n };\n\n \/\/ make a version with version\n virtual void set(const ObjectType &v, const __int128 & ver)\n noexcept(false) {\n HLC mhlc; \/\/ generate a default timestamp for it.\n this->set(v,ver,mhlc);\n }\n\n \/\/ make a version\n virtual void version(const __int128 & ver)\n noexcept(false) {\n \/\/TODO: compare if value has been changed?\n this->set(this->wrapped_obj,ver);\n }\n\n \/** persist till version\n * @param ver version number\n * @return the given version to be persisted.\n *\/\n virtual const __int128 persist()\n noexcept(false){\n return this->m_pLog->persist();\n }\n\n \/\/ internal _NameMaker class\n class _NameMaker{\n public:\n \/\/ Constructor\n _NameMaker() noexcept(false):\n m_sObjectTypeName(typeid(ObjectType).name()) {\n this->m_iCounter = 0;\n if (pthread_spin_init(&this->m_oLck,PTHREAD_PROCESS_SHARED) != 0) {\n throw PERSIST_EXP_SPIN_INIT(errno);\n }\n }\n\n \/\/ Destructor\n virtual ~_NameMaker() noexcept(true) {\n pthread_spin_destroy(&this->m_oLck);\n }\n\n \/\/ guess a name\n std::unique_ptr make() noexcept(false) {\n int cnt;\n if (pthread_spin_lock(&this->m_oLck) != 0) {\n throw PERSIST_EXP_SPIN_LOCK(errno);\n }\n cnt = this->m_iCounter++;\n if (pthread_spin_unlock(&this->m_oLck) != 0) {\n throw PERSIST_EXP_SPIN_UNLOCK(errno);\n }\n std::unique_ptr ret = std::make_unique();\n \/\/char * buf = (char *)malloc((strlen(this->m_sObjectTypeName)+13)\/8*8);\n char buf[256];\n sprintf(buf,\"%s-%d\",this->m_sObjectTypeName,cnt);\n \/\/ return std::make_shared((const char*)buf);\n *ret = buf;\n return ret;\n }\n\n private:\n int m_iCounter;\n const char *m_sObjectTypeName;\n pthread_spinlock_t m_oLck;\n };\n\n protected:\n \/\/ wrapped objected\n ObjectType wrapped_obj;\n \n \/\/ PersistLog\n PersistLog * m_pLog;\n\n \/\/ get the static name maker.\n static _NameMaker & getNameMaker();\n };\n\n \/\/ How many times the constructor was called.\n template \n typename Persistent::_NameMaker & \n Persistent::getNameMaker() noexcept(false) {\n static Persistent::_NameMaker nameMaker;\n return nameMaker;\n }\n\n template \n class Volatile: public Persistent{\n public:\n \/\/ constructor: this will guess the objectname form ObjectType\n Volatile (\n FuncRegisterCallback func_register_cb=nullptr,\n const char * object_name = (*Persistent::getNameMaker().make()).c_str())\n noexcept(false):\n Persistent(func_register_cb,object_name){\n };\n \/\/ destructor:\n virtual ~Volatile() noexcept(false){\n \/\/ do nothing\n };\n };\n\n \/*\n * PersistentRegistry is a book for all the Persistent or Volatile\n * variables. Replicated class should maintain such a registry to perform\n * the following operations:\n * - makeVersion(const __int128 & ver): create a version \n * - persist(): persist the existing versions\n * - trim(const __int128 & ver): trim all versions earlier than ver\n *\/\n class PersistentRegistry{\n public:\n PersistentRegistry() {\n \/\/\n };\n virtual ~PersistentRegistry() {\n this->_registry.clear();\n };\n #define VERSION_FUNC_IDX (0)\n #define PERSIST_FUNC_IDX (1)\n #define TRIM_FUNC_IDX (2)\n void makeVersion(const __int128 & ver) noexcept(false) {\n callFunc(ver);\n };\n void persist() noexcept(false) {\n callFunc();\n };\n void trim(const __int128 & ver) noexcept(false) {\n callFunc(ver);\n };\n void registerPersist(const VersionFunc &vf,const PersistFunc &pf,const TrimFunc &tf) noexcept(false) {\n \/\/this->_registry.push_back(std::make_tuple(\n this->_registry.push_back(std::make_tuple(vf,pf,tf));\n };\n protected:\n std::vector> _registry;\n template\n void callFunc(Args ... args) {\n for (auto itr = this->_registry.begin();\n itr != this->_registry.end(); ++itr) {\n std::get(*itr)(args ...);\n }\n };\n };\n}\n\n#endif\/\/PERSIST_VAR_H\n<|endoftext|>"} {"text":"\/\/ ------------------------------------------------------------------------\n\/\/ Pion is a development platform for building Reactors that process Events\n\/\/ ------------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Pion is free software: you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Affero General Public License as published by the Free\n\/\/ Software Foundation, either version 3 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ Pion is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pion. If not, see .\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"LogInputReactor.hpp\"\n\nusing namespace pion::platform;\nnamespace bfs = boost::filesystem;\n\n\nnamespace pion {\t\t\/\/ begin namespace pion\nnamespace plugins {\t\t\/\/ begin namespace plugins\n\n\n\/\/ static members of LogInputReactor\n\t\nconst boost::uint32_t\t\tLogInputReactor::DEFAULT_FREQUENCY = 1;\nconst std::string\t\t\tLogInputReactor::CODEC_ELEMENT_NAME = \"Codec\";\nconst std::string\t\t\tLogInputReactor::DIRECTORY_ELEMENT_NAME = \"Directory\";\nconst std::string\t\t\tLogInputReactor::FILENAME_ELEMENT_NAME = \"Filename\";\nconst std::string\t\t\tLogInputReactor::JUST_ONE_ELEMENT_NAME = \"JustOne\";\nconst std::string\t\t\tLogInputReactor::FREQUENCY_ELEMENT_NAME = \"Frequency\";\n\n\t\n\/\/ LogInputReactor member functions\n\nvoid LogInputReactor::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)\n{\n\t\/\/ first set config options for the Reactor base class\n\tboost::unique_lock reactor_lock(m_mutex);\n\tReactor::setConfig(v, config_ptr);\n\t\n\t\/\/ get the Codec that the Reactor should use\n\tif (! ConfigManager::getConfigOption(CODEC_ELEMENT_NAME, m_codec_id, config_ptr))\n\t\tthrow EmptyCodecException(getId());\n\tm_codec_ptr = getCodecFactory().getCodec(m_codec_id);\n\tPION_ASSERT(m_codec_ptr);\n\t\n\t\/\/ get the directory where the Reactor will look for new log files\n\tif (! ConfigManager::getConfigOption(DIRECTORY_ELEMENT_NAME, m_log_directory, config_ptr))\n\t\tthrow EmptyDirectoryException(getId());\n\t\n\t\/\/ resolve paths relative to the ReactionEngine's config file location\n\tm_log_directory = getReactionEngine().resolveRelativePath(m_log_directory);\n\n\t\/\/ make sure that the directory exists\n\tif (! boost::filesystem::exists(m_log_directory) )\n\t\tthrow DirectoryNotFoundException(m_log_directory);\n\tif (! boost::filesystem::is_directory(m_log_directory) )\n\t\tthrow NotADirectoryException(m_log_directory);\n\t\n\t\/\/ get the filename regex to use for finding log files\n\tstd::string filename_str;\n\tif (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, filename_str, config_ptr))\n\t\tthrow EmptyFilenameException(getId());\n\tm_log_regex = filename_str;\n\t\n\t\/\/ check if the the Reactor should only read the first Event & duplicate it (for testing)\n\tm_just_one = false;\n\tstd::string just_one_option;\n\tif (ConfigManager::getConfigOption(JUST_ONE_ELEMENT_NAME, just_one_option,\n\t\t\t\t\t\t\t\t\t config_ptr))\n\t{\n\t\tif (just_one_option == \"true\")\n\t\t\tm_just_one = true;\n\t}\n\n\t\/\/ get the frequency to check for new logs (if defined)\n\tstd::string frequency_str;\n\tif (ConfigManager::getConfigOption(FREQUENCY_ELEMENT_NAME, frequency_str, config_ptr)) {\n\t\tconst boost::uint32_t frequency_value = boost::lexical_cast(frequency_str);\n\t\tif (frequency_value <= 0)\n\t\t\tthrow BadFrequencyException(getId());\n\t\tm_frequency = frequency_value;\n\t} else {\n\t\tm_frequency = DEFAULT_FREQUENCY;\n\t}\n}\n\t\nvoid LogInputReactor::updateVocabulary(const Vocabulary& v)\n{\n\t\/\/ first update anything in the Reactor base class that might be needed\n\tboost::unique_lock reactor_lock(m_mutex);\n\tReactor::updateVocabulary(v);\n\tif (m_codec_ptr)\n\t\tm_codec_ptr->updateVocabulary(v);\n}\n\nvoid LogInputReactor::updateCodecs(void)\n{\n\t\/\/ check if the codec was deleted (if so, stop now!)\n\tif (! getCodecFactory().hasPlugin(m_codec_id)) {\n\t\tstop();\n\t boost::unique_lock reactor_lock(m_mutex);\n\t\tm_codec_ptr.reset();\n\t} else {\n\t\t\/\/ update the codec pointer\n \tboost::unique_lock reactor_lock(m_mutex);\n\t\tm_codec_ptr = getCodecFactory().getCodec(m_codec_id);\n\t}\n}\n\nvoid LogInputReactor::operator()(const EventPtr& e)\n{\n\tif (isRunning()) {\n\t\tboost::mutex::scoped_lock reactor_lock(m_mutex);\n\t\tincrementEventsIn();\n\t\tdeliverEvent(e);\n\t}\n}\n\nvoid LogInputReactor::start(void)\n{\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (! m_is_running) {\n\t\t\/\/ schedule a check for new log files\n\t\tscheduleLogFileCheck(0);\n\t\tm_is_running = true;\n\t}\n}\n\t\nvoid LogInputReactor::stop(void)\n{\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (m_is_running) {\n\t\t\/\/ set flag to notify reader thread to shutdown\n\t\tPION_LOG_DEBUG(m_logger, \"Stopping input log thread: \" << getId());\n\t\tm_is_running = false;\n\t\tm_timer_ptr.reset();\n\t}\n}\n\nvoid LogInputReactor::scheduleLogFileCheck(boost::uint32_t seconds)\n{\n\tif (seconds == 0) {\n\t\tgetScheduler().post(boost::bind(&LogInputReactor::checkForLogFiles, this));\n\t} else {\n\t\tif (! m_timer_ptr)\n\t\t\tm_timer_ptr.reset(new boost::asio::deadline_timer(getScheduler().getIOService()));\n\t\tm_timer_ptr->expires_from_now(boost::posix_time::seconds(seconds));\n\t\tm_timer_ptr->async_wait(boost::bind(&LogInputReactor::checkForLogFiles, this));\n\t}\n}\n\nvoid LogInputReactor::checkForLogFiles(void)\n{\n\t\/\/ make sure that the reactor is still running\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (! isRunning())\n\t\treturn;\n\n\tPION_LOG_DEBUG(m_logger, \"Checking for new log files in \" << m_log_directory);\n\n\t\/\/ get the current logs located in the log directory\n\tLogFileCollection current_logs;\n\tgetLogFilesInLogDirectory(current_logs);\n\n\t\/\/ remove logs from the consumed collection that are no longer there\n\tLogFileCollection::iterator temp_itr;\n\tLogFileCollection::iterator log_itr = m_logs_consumed.begin();\n\twhile (log_itr != m_logs_consumed.end()) {\n\t\ttemp_itr = log_itr++;\n\t\tif (current_logs.find(*temp_itr) == current_logs.end())\n\t\t\tm_logs_consumed.erase(temp_itr);\n\t}\n\t\n\t\/\/ check for an existing log that has not yet been consumed\n\tfor (log_itr = current_logs.begin(); log_itr != current_logs.end(); ++log_itr) {\n\t\tif (m_logs_consumed.find(*log_itr) == m_logs_consumed.end())\n\t\t\tbreak;\n\t}\n\t\t\n\tif (log_itr == current_logs.end()) {\n\t\t\/\/ no new logs to consume\n\n\t\t\/\/ sleep until it is time to check again\n\t\tPION_LOG_DEBUG(m_logger, \"No new logs (sleeping for \" << m_frequency\n\t\t\t\t\t << \" seconds): \" << m_log_directory);\n\t\tscheduleLogFileCheck(m_frequency);\n\t\t\n\t} else {\n\t\t\/\/ found a new log to consume\n\t\tm_logs_consumed.insert(*log_itr);\n\t\t\n\t\t\/\/ re-calculate the full path to the file\n\t\tbfs::path full_path(m_log_directory);\n\t\tfull_path \/= *log_itr;\n\t\tm_log_file = full_path.file_string();\n\n\t\tPION_LOG_DEBUG(m_logger, \"Found a new log file to consume: \" << m_log_file);\n\t\tscheduleReadFromLog(true);\n\t}\n}\n\nvoid LogInputReactor::readFromLog(bool use_one_thread)\n{\n\t\/\/ make sure that the reactor is still running\n\tif (! isRunning())\n\t\treturn;\n\n\ttry {\n\t\t\/\/ open up the log file for reading (if not open already)\n\t\tif (! m_log_stream.is_open()) {\n\t\t\tm_log_stream.open(m_log_file.c_str(), std::ios::in | std::ios::binary);\n\t\t\tif (! m_log_stream.is_open())\n\t\t\t\tthrow OpenLogException(m_log_file);\n\t\t\telse if (m_log_stream.eof())\n\t\t\t\tthrow EmptyLogException(m_log_file);\n\t\t}\n\t\t\n\t\tEventPtr event_ptr;\n\t\tdo {\n\t\t\t\/\/ read an Event from the log file (convert into an Event using the Codec)\n \tboost::unique_lock reactor_lock(m_mutex);\n\t\t\tevent_ptr = EventFactory::create(m_codec_ptr->getEventType());\n\t\t\tif (! m_codec_ptr->read(m_log_stream, *event_ptr))\n\t\t\t\tthrow ReadEventException(m_log_file);\n\t\t\t\/\/ done with the codec (which is all that needs protecting here)\n\t\t\t\/\/reactor_lock.unlock();\n\n\t\t\t\/\/ check if only Event should be read\n\t\t\tif (m_just_one) {\n\t\t\t\tPION_LOG_DEBUG(m_logger, \"JustOne: generating lots of event copies for testing\");\n\t\t\t\tm_log_stream.close();\n\t\t\t\tm_log_stream.clear();\n\t\t\t\t\n\t\t\t\t\/\/ just duplicate the event repeatedly until the Reactor is stopped\n\t\t\t\tEventPtr original_event_ptr(event_ptr);\n\t\t\t\twhile (isRunning()) {\n\t\t\t\t\t\/\/ duplicate the original event\n\t\t\t\t\tevent_ptr = EventFactory::create(m_codec_ptr->getEventType());\n\t\t\t\t\t*event_ptr += *original_event_ptr;\n\t\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\t\tincrementEventsIn();\n\t\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ check for end of file\n\t\t\tif (m_log_stream.eof()) {\n\t\t\t\t\/\/ all done with this log file\n\t\t\t\tPION_LOG_DEBUG(m_logger, \"Finished consuming log file: \" << m_log_file);\n\t\t\t\tm_log_stream.close();\n\t\t\t\tm_log_stream.clear();\n\n\t\t\t\t\/\/ check for more logs\n\t\t\t\tscheduleLogFileCheck(0);\n\n\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\tincrementEventsIn();\n\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\t\/\/ more available: schedule another read operation?\n\t\t\t\tif (! use_one_thread) {\n\t\t\t\t\tscheduleReadFromLog(false);\n\n\t\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\t\tincrementEventsIn();\n\t\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\tincrementEventsIn();\n\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t}\n\n\t\t} while (isRunning()); \n\n\t} catch (std::exception& e) {\n\t\tPION_LOG_ERROR(m_logger, e.what());\n\t\tm_log_stream.close();\n\t\tm_log_stream.clear();\n\t\tscheduleLogFileCheck(0);\n\t}\n}\n\nvoid LogInputReactor::getLogFilesInLogDirectory(LogFileCollection& files)\n{\n\tbfs::path dir_path(m_log_directory);\n\tfor (bfs::directory_iterator itr(dir_path); itr!=bfs::directory_iterator(); ++itr) {\n\t\tif (bfs::is_regular(itr->status())) {\n\t\t\tconst std::string filename(itr->path().leaf());\n\t\t\tif (boost::regex_search(filename, m_log_regex))\n\t\t\t\tfiles.insert(filename);\n\t\t}\n\t}\n}\n\n\t\n}\t\/\/ end namespace plugins\n}\t\/\/ end namespace pion\n\n\n\/\/\/ creates new LogInputReactor objects\nextern \"C\" PION_PLUGIN_API pion::platform::Reactor *pion_create_LogInputReactor(void) {\n\treturn new pion::plugins::LogInputReactor();\n}\n\n\/\/\/ destroys LogInputReactor objects\nextern \"C\" PION_PLUGIN_API void pion_destroy_LogInputReactor(pion::plugins::LogInputReactor *reactor_ptr) {\n\tdelete reactor_ptr;\n}\nMinor formatting cleanup\/\/ ------------------------------------------------------------------------\n\/\/ Pion is a development platform for building Reactors that process Events\n\/\/ ------------------------------------------------------------------------\n\/\/ Copyright (C) 2007-2008 Atomic Labs, Inc. (http:\/\/www.atomiclabs.com)\n\/\/\n\/\/ Pion is free software: you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Affero General Public License as published by the Free\n\/\/ Software Foundation, either version 3 of the License, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ Pion is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for\n\/\/ more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pion. If not, see .\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"LogInputReactor.hpp\"\n\nusing namespace pion::platform;\nnamespace bfs = boost::filesystem;\n\n\nnamespace pion {\t\t\/\/ begin namespace pion\nnamespace plugins {\t\t\/\/ begin namespace plugins\n\n\n\/\/ static members of LogInputReactor\n\t\nconst boost::uint32_t\t\tLogInputReactor::DEFAULT_FREQUENCY = 1;\nconst std::string\t\t\tLogInputReactor::CODEC_ELEMENT_NAME = \"Codec\";\nconst std::string\t\t\tLogInputReactor::DIRECTORY_ELEMENT_NAME = \"Directory\";\nconst std::string\t\t\tLogInputReactor::FILENAME_ELEMENT_NAME = \"Filename\";\nconst std::string\t\t\tLogInputReactor::JUST_ONE_ELEMENT_NAME = \"JustOne\";\nconst std::string\t\t\tLogInputReactor::FREQUENCY_ELEMENT_NAME = \"Frequency\";\n\n\t\n\/\/ LogInputReactor member functions\n\nvoid LogInputReactor::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)\n{\n\t\/\/ first set config options for the Reactor base class\n\tboost::unique_lock reactor_lock(m_mutex);\n\tReactor::setConfig(v, config_ptr);\n\t\n\t\/\/ get the Codec that the Reactor should use\n\tif (! ConfigManager::getConfigOption(CODEC_ELEMENT_NAME, m_codec_id, config_ptr))\n\t\tthrow EmptyCodecException(getId());\n\tm_codec_ptr = getCodecFactory().getCodec(m_codec_id);\n\tPION_ASSERT(m_codec_ptr);\n\t\n\t\/\/ get the directory where the Reactor will look for new log files\n\tif (! ConfigManager::getConfigOption(DIRECTORY_ELEMENT_NAME, m_log_directory, config_ptr))\n\t\tthrow EmptyDirectoryException(getId());\n\t\n\t\/\/ resolve paths relative to the ReactionEngine's config file location\n\tm_log_directory = getReactionEngine().resolveRelativePath(m_log_directory);\n\n\t\/\/ make sure that the directory exists\n\tif (! boost::filesystem::exists(m_log_directory) )\n\t\tthrow DirectoryNotFoundException(m_log_directory);\n\tif (! boost::filesystem::is_directory(m_log_directory) )\n\t\tthrow NotADirectoryException(m_log_directory);\n\t\n\t\/\/ get the filename regex to use for finding log files\n\tstd::string filename_str;\n\tif (! ConfigManager::getConfigOption(FILENAME_ELEMENT_NAME, filename_str, config_ptr))\n\t\tthrow EmptyFilenameException(getId());\n\tm_log_regex = filename_str;\n\t\n\t\/\/ check if the the Reactor should only read the first Event & duplicate it (for testing)\n\tm_just_one = false;\n\tstd::string just_one_option;\n\tif (ConfigManager::getConfigOption(JUST_ONE_ELEMENT_NAME, just_one_option,\n\t\t\t\t\t\t\t\t\t config_ptr))\n\t{\n\t\tif (just_one_option == \"true\")\n\t\t\tm_just_one = true;\n\t}\n\n\t\/\/ get the frequency to check for new logs (if defined)\n\tstd::string frequency_str;\n\tif (ConfigManager::getConfigOption(FREQUENCY_ELEMENT_NAME, frequency_str, config_ptr)) {\n\t\tconst boost::uint32_t frequency_value = boost::lexical_cast(frequency_str);\n\t\tif (frequency_value <= 0)\n\t\t\tthrow BadFrequencyException(getId());\n\t\tm_frequency = frequency_value;\n\t} else {\n\t\tm_frequency = DEFAULT_FREQUENCY;\n\t}\n}\n\t\nvoid LogInputReactor::updateVocabulary(const Vocabulary& v)\n{\n\t\/\/ first update anything in the Reactor base class that might be needed\n\tboost::unique_lock reactor_lock(m_mutex);\n\tReactor::updateVocabulary(v);\n\tif (m_codec_ptr)\n\t\tm_codec_ptr->updateVocabulary(v);\n}\n\nvoid LogInputReactor::updateCodecs(void)\n{\n\t\/\/ check if the codec was deleted (if so, stop now!)\n\tif (! getCodecFactory().hasPlugin(m_codec_id)) {\n\t\tstop();\n\t boost::unique_lock reactor_lock(m_mutex);\n\t\tm_codec_ptr.reset();\n\t} else {\n\t\t\/\/ update the codec pointer\n \tboost::unique_lock reactor_lock(m_mutex);\n\t\tm_codec_ptr = getCodecFactory().getCodec(m_codec_id);\n\t}\n}\n\nvoid LogInputReactor::operator()(const EventPtr& e)\n{\n\tif (isRunning()) {\n\t\tboost::mutex::scoped_lock reactor_lock(m_mutex);\n\t\tincrementEventsIn();\n\t\tdeliverEvent(e);\n\t}\n}\n\nvoid LogInputReactor::start(void)\n{\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (! m_is_running) {\n\t\t\/\/ schedule a check for new log files\n\t\tscheduleLogFileCheck(0);\n\t\tm_is_running = true;\n\t}\n}\n\t\nvoid LogInputReactor::stop(void)\n{\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (m_is_running) {\n\t\t\/\/ set flag to notify reader thread to shutdown\n\t\tPION_LOG_DEBUG(m_logger, \"Stopping input log thread: \" << getId());\n\t\tm_is_running = false;\n\t\tm_timer_ptr.reset();\n\t}\n}\n\nvoid LogInputReactor::scheduleLogFileCheck(boost::uint32_t seconds)\n{\n\tif (seconds == 0) {\n\t\tgetScheduler().post(boost::bind(&LogInputReactor::checkForLogFiles, this));\n\t} else {\n\t\tif (! m_timer_ptr)\n\t\t\tm_timer_ptr.reset(new boost::asio::deadline_timer(getScheduler().getIOService()));\n\t\tm_timer_ptr->expires_from_now(boost::posix_time::seconds(seconds));\n\t\tm_timer_ptr->async_wait(boost::bind(&LogInputReactor::checkForLogFiles, this));\n\t}\n}\n\nvoid LogInputReactor::checkForLogFiles(void)\n{\n\t\/\/ make sure that the reactor is still running\n\tboost::unique_lock reactor_lock(m_mutex);\n\tif (! isRunning())\n\t\treturn;\n\n\tPION_LOG_DEBUG(m_logger, \"Checking for new log files in \" << m_log_directory);\n\n\t\/\/ get the current logs located in the log directory\n\tLogFileCollection current_logs;\n\tgetLogFilesInLogDirectory(current_logs);\n\n\t\/\/ remove logs from the consumed collection that are no longer there\n\tLogFileCollection::iterator temp_itr;\n\tLogFileCollection::iterator log_itr = m_logs_consumed.begin();\n\twhile (log_itr != m_logs_consumed.end()) {\n\t\ttemp_itr = log_itr++;\n\t\tif (current_logs.find(*temp_itr) == current_logs.end())\n\t\t\tm_logs_consumed.erase(temp_itr);\n\t}\n\t\n\t\/\/ check for an existing log that has not yet been consumed\n\tfor (log_itr = current_logs.begin(); log_itr != current_logs.end(); ++log_itr) {\n\t\tif (m_logs_consumed.find(*log_itr) == m_logs_consumed.end())\n\t\t\tbreak;\n\t}\n\t\t\n\tif (log_itr == current_logs.end()) {\n\t\t\/\/ no new logs to consume\n\n\t\t\/\/ sleep until it is time to check again\n\t\tPION_LOG_DEBUG(m_logger, \"No new logs (sleeping for \" << m_frequency\n\t\t\t\t\t << \" seconds): \" << m_log_directory);\n\t\tscheduleLogFileCheck(m_frequency);\n\t\t\n\t} else {\n\t\t\/\/ found a new log to consume\n\t\tm_logs_consumed.insert(*log_itr);\n\t\t\n\t\t\/\/ re-calculate the full path to the file\n\t\tbfs::path full_path(m_log_directory);\n\t\tfull_path \/= *log_itr;\n\t\tm_log_file = full_path.file_string();\n\n\t\tPION_LOG_DEBUG(m_logger, \"Found a new log file to consume: \" << m_log_file);\n\t\tscheduleReadFromLog(true);\n\t}\n}\n\nvoid LogInputReactor::readFromLog(bool use_one_thread)\n{\n\t\/\/ make sure that the reactor is still running\n\tif (! isRunning())\n\t\treturn;\n\n\ttry {\n\t\t\/\/ open up the log file for reading (if not open already)\n\t\tif (! m_log_stream.is_open()) {\n\t\t\tm_log_stream.open(m_log_file.c_str(), std::ios::in | std::ios::binary);\n\t\t\tif (! m_log_stream.is_open())\n\t\t\t\tthrow OpenLogException(m_log_file);\n\t\t\telse if (m_log_stream.eof())\n\t\t\t\tthrow EmptyLogException(m_log_file);\n\t\t}\n\t\t\n\t\tEventPtr event_ptr;\n\t\tdo {\n\t\t\t\/\/ read an Event from the log file (convert into an Event using the Codec)\n\t\t\tboost::unique_lock reactor_lock(m_mutex);\n\t\t\tevent_ptr = EventFactory::create(m_codec_ptr->getEventType());\n\t\t\tif (! m_codec_ptr->read(m_log_stream, *event_ptr))\n\t\t\t\tthrow ReadEventException(m_log_file);\n\n\t\t\t\/\/ check if only Event should be read\n\t\t\tif (m_just_one) {\n\t\t\t\tPION_LOG_DEBUG(m_logger, \"JustOne: generating lots of event copies for testing\");\n\t\t\t\tm_log_stream.close();\n\t\t\t\tm_log_stream.clear();\n\t\t\t\t\n\t\t\t\t\/\/ just duplicate the event repeatedly until the Reactor is stopped\n\t\t\t\tEventPtr original_event_ptr(event_ptr);\n\t\t\t\twhile (isRunning()) {\n\t\t\t\t\t\/\/ duplicate the original event\n\t\t\t\t\tevent_ptr = EventFactory::create(m_codec_ptr->getEventType());\n\t\t\t\t\t*event_ptr += *original_event_ptr;\n\t\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\t\tincrementEventsIn();\n\t\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ check for end of file\n\t\t\tif (m_log_stream.eof()) {\n\t\t\t\t\/\/ all done with this log file\n\t\t\t\tPION_LOG_DEBUG(m_logger, \"Finished consuming log file: \" << m_log_file);\n\t\t\t\tm_log_stream.close();\n\t\t\t\tm_log_stream.clear();\n\n\t\t\t\t\/\/ check for more logs\n\t\t\t\tscheduleLogFileCheck(0);\n\n\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\tincrementEventsIn();\n\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\t\/\/ more available: schedule another read operation?\n\t\t\t\tif (! use_one_thread) {\n\t\t\t\t\tscheduleReadFromLog(false);\n\n\t\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\t\tincrementEventsIn();\n\t\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ deliver the Event to connected Reactors\n\t\t\t\tincrementEventsIn();\n\t\t\t\tdeliverEvent(event_ptr);\n\t\t\t}\n\n\t\t} while (isRunning()); \n\n\t} catch (std::exception& e) {\n\t\tPION_LOG_ERROR(m_logger, e.what());\n\t\tm_log_stream.close();\n\t\tm_log_stream.clear();\n\t\tscheduleLogFileCheck(0);\n\t}\n}\n\nvoid LogInputReactor::getLogFilesInLogDirectory(LogFileCollection& files)\n{\n\tbfs::path dir_path(m_log_directory);\n\tfor (bfs::directory_iterator itr(dir_path); itr!=bfs::directory_iterator(); ++itr) {\n\t\tif (bfs::is_regular(itr->status())) {\n\t\t\tconst std::string filename(itr->path().leaf());\n\t\t\tif (boost::regex_search(filename, m_log_regex))\n\t\t\t\tfiles.insert(filename);\n\t\t}\n\t}\n}\n\n\t\n}\t\/\/ end namespace plugins\n}\t\/\/ end namespace pion\n\n\n\/\/\/ creates new LogInputReactor objects\nextern \"C\" PION_PLUGIN_API pion::platform::Reactor *pion_create_LogInputReactor(void) {\n\treturn new pion::plugins::LogInputReactor();\n}\n\n\/\/\/ destroys LogInputReactor objects\nextern \"C\" PION_PLUGIN_API void pion_destroy_LogInputReactor(pion::plugins::LogInputReactor *reactor_ptr) {\n\tdelete reactor_ptr;\n}\n<|endoftext|>"} {"text":"\/*********************************************************************** \nOpenSync Plugin for KDE 3.x\nCopyright (C) 2004 Stewart Heitmann \n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License version 2 as\npublished by the Free Software Foundation;\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY\nCLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES \nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN \nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF \nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, \nCOPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS \nSOFTWARE IS DISCLAIMED.\n*************************************************************************\/\n\/*\n * 03 Nov 2004 - Eduardo Pereira Habkost \n * - Ported to OpenSync plugin interface\n *\/\n\nextern \"C\"\n{\n#include \n#include \"kaddrbook.h\"\n}\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstatic\nvoid unfold_vcard(char *vcard, size_t *size)\n{\n char* in = vcard;\n char* out = vcard;\n char *end = vcard + *size;\n while ( in < end)\n {\n \/* remove any occurrences of \"=[CR][LF]\" *\/\n \/* these denote folded line markers in VCARD format. *\/\n \/* Dont know why, but Evolution uses the leading \"=\" *\/\n \/* character to (presumably) denote a control sequence. *\/\n \/* This is not quite how I interpret the VCARD RFC2426 *\/\n \/* spec (section 2.6 line delimiting and folding). *\/\n \/* This seems to work though, so thats the main thing! *\/\n if (in[0]=='=' && in[1]==13 && in[2]==10)\n in+=3;\n else\n *out++ = *in++;\n }\n *size = out - vcard;\n}\n\nclass kaddrbook\n{\n private:\n KABC::AddressBook* addressbookptr; \n KABC::Ticket* addressbookticket;\n QDateTime syncdate, newsyncdate;\n\n OSyncMember *member;\n OSyncHashTable *hashtable;\n\n public: \n kaddrbook(OSyncMember *memb)\n :member(memb)\n {\n \/\/printf(\"kdepim_plugin: %s(%s)\\n\", __FUNCTION__);\n\n \/\/get a handle to the standard KDE addressbook\n addressbookptr = KABC::StdAddressBook::self();\n\n \/\/ensure a NULL Ticket ptr\n addressbookticket=NULL;\n\n hashtable = osync_hashtable_new();\n osync_hashtable_load(hashtable, member);\n\n };\n\n\n int get_changes(OSyncContext *ctx)\n {\n \/\/printf(\"kdepim_plugin: kaddrbook::%s(newdbs=%d)\\n\", __FUNCTION__, newdbs);\n\n const char* multisync_debug = getenv(\"MULTISYNC_DEBUG\");\n\n \/\/remember when we started this current sync\n newsyncdate = QDateTime::currentDateTime();\n\n \/\/ We must reload the KDE addressbook in order to retrieve the latest changes.\n if (!addressbookptr->load())\n {\n if (multisync_debug)\n printf(\"kdepim_plugin: couldnt reload KDE addressbook, aborting sync.\\n\");\n return -1;\n }\n if (multisync_debug)\n printf(\"kdepim_plugin: KDE addressbook reloaded OK.\\n\");\n\n \/\/Lock the addressbook\n addressbookticket = addressbookptr->requestSaveTicket();\n if (!addressbookticket)\n {\n if (multisync_debug)\n printf(\"kdepim_plugin: couldnt lock KDE addressbook, aborting sync.\\n\");\n return -1;\n }\n if (multisync_debug)\n printf(\"kdepim_plugin: KDE addressbook locked OK.\\n\");\n\n \/\/printf(\"%s: %s : plugin UID list has %d entries\\n\", __FILE__, __FUNCTION__, uidlist.count());\n\n \/\/Check the entries of the KDE addressbook against the last entries seen by the sync-engine\n for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) {\n \/\/Get the revision date of the KDE addressbook entry.\n \/\/Regard entries with invalid revision dates as having just been changed.\n QDateTime revdate = it->revision();\n if (!revdate.isValid())\n {\n revdate = newsyncdate; \/\/use date of this sync as the revision date.\n it->setRevision(revdate); \/\/update the Addressbook entry for future reference.\n } \n\n \/\/ gmalloc a changed_object for this phonebook entry \n \/\/FIXME: deallocate it somewhere\n OSyncChange *chg= osync_change_new();\n\n QCString hash(revdate.toString());\n\n osync_change_set_hash(chg, hash);\n osync_change_set_uid(chg, it->uid().latin1());\n\n \/\/ Convert the VCARD data into a string\n KABC::VCardConverter converter;\n QString card = converter.createVCard(*it);\n QString data(card.latin1());\n \/\/FIXME: deallocate data somewhere\n osync_change_set_data(chg, strdup(data), data.length(), 1);\n\n \/\/ set the remaining fields\n osync_change_set_objtype_string(chg, \"contact\");\n osync_change_set_objformat_string(chg, \"vcard\");\n osync_change_set_hash(chg, hash.data());\n \/*FIXME: slowsync *\/\n if (osync_hashtable_detect_change(hashtable, chg, 0)) {\n osync_context_report_change(ctx, chg);\n osync_hashtable_update_hash(hashtable, chg);\n }\n\n \/\/Append the changed_object to the return list\n osync_context_report_change(ctx, chg);\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, 0);\n\n return 0;\n }\n\n\n int modify(OSyncChange *chg)\n {\n \/\/printf(\"kdepim_plugin: kaddrbook::%s()\\n\",__FUNCTION__);\n\n int result = 0;\n const char* multisync_debug = getenv(\"MULTISYNC_DEBUG\");\n \n \/\/ Ensure we still have a lock on the KDE addressbook (we ought to)\n if (addressbookticket==NULL)\n {\n \/\/This should never happen, but just in case....\n if (multisync_debug)\n printf(\"kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\\n\");\n return -1;\n }\n\n KABC::VCardConverter converter;\n \n \/* allocate and initialize return struct for this change entry *\/\n \/\/FIXME: check how to return errors safely\n \/\/modify_result = (syncobj_modify_result*)g_malloc0(sizeof(syncobj_modify_result));\n \/\/modify_result->result = SYNC_MSG_MODIFYERROR;\n \/\/modify_result->returnuid = NULL;\n \n OSyncObjType *type = osync_change_get_objtype(chg);\n \/\/ Do database modifications according to object type\n if (!strcmp(osync_objtype_get_name(type), \"contact\"))\n {\n\n OSyncChangeType chtype = osync_change_get_changetype(chg);\n char *uid = osync_change_get_uid(chg);\n \/* treat modified objects without UIDs as if they were newly added objects *\/\n if (chtype == CHANGE_MODIFIED && !uid)\n chtype = CHANGE_ADDED;\n \n \/\/ convert VCARD string from obj->comp into an Addresse object.\n char *data;\n size_t data_size;\n data = (char*)osync_change_get_data(chg);\n data_size = osync_change_get_datasize(chg);\n\n switch(chtype)\n {\n case CHANGE_MODIFIED:\n {\n unfold_vcard(data, &data_size);\n\n KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));\n\n \/\/ ensure it has the correct UID\n addressee.setUid(QString(uid));\n\n \/\/ replace the current addressbook entry (if any) with the new one\n addressbookptr->insertAddressee(addressee);\n\n if (multisync_debug)\n {\n printf(\"kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)\\n\", uid); \n }\n result = 0;\n break;\n }\n \n case CHANGE_ADDED:\n {\n \/\/ convert VCARD string from obj->comp into an Addresse object\n \/\/ KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first.\n unfold_vcard(data, &data_size);\n KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));\n\n \/\/ ensure it has a NULL UID\n addressee.setUid(QString(NULL));\n\n \/\/ add the new address to the addressbook\n addressbookptr->insertAddressee(addressee);\n\n if (multisync_debug)\n {\n printf(\"kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)\\n\", addressee.uid().latin1());\n }\n\n\n \/\/ return the UID of the new entry along with the result\n osync_change_set_uid(chg, addressee.uid().latin1());\n result = 0;\n break;\n }\n \n case CHANGE_DELETED:\n {\n if (uid==NULL)\n {\n result = 1;\n break;\n }\n\n \/\/find addressbook entry with matching UID and delete it\n KABC::Addressee addressee = addressbookptr->findByUid(QString(uid));\n if(!addressee.isEmpty())\n addressbookptr->removeAddressee(addressee);\n\n if (multisync_debug)\n printf(\"kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)\\n\", uid);\n\n result = 0;\n break;\n }\n default:\n result = 0;\n } \n }\n \/\/FIXME: handle unsupported objtypes\n \n return result;\n }\n\n\n void sync_done(bool success) \n {\n \/\/printf(\"kdepim_plugin: kaddrbook::%s(%d)\\n\", __FUNCTION__, success);\n const char* multisync_debug = getenv(\"MULTISYNC_DEBUG\");\n\n if (!addressbookticket)\n {\n \/\/This should never happen, but just in case....\n if (multisync_debug)\n printf(\"kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\\n\");\n\n return;\n }\n\n if (success)\n {\n \/\/ Save and unlock the KDE addressbook\n addressbookptr->save(addressbookticket);\n if (multisync_debug)\n printf(\"kdepim_plugin: KDE addressbook saved and unlocked.\\n\");\n \n \/\/update the syncdate \n syncdate = newsyncdate; \n }\n else\n {\n \/\/ Unlock the KDE addressbook and discard all changes\n addressbookptr->releaseSaveTicket(addressbookticket);\n if (multisync_debug)\n printf(\"kdepim_plugin: KDE addressbook unlocked and changes discarded.\\n\");\n\n }\n \n addressbookticket=NULL;\n }\n \n};\n\nstatic KApplication *applicationptr=NULL;\nstatic char name[] = \"kde-opensync-plugin\";\nstatic char *argv[] = {name,0};\n\nstatic kaddrbook *addrbook_for_context(OSyncContext *ctx)\n{\n return (kaddrbook *)osync_context_get_plugin_data(ctx);\n}\n\nstatic void *kde_initialize(OSyncMember *member)\n{\n kaddrbook *addrbook;\n\n if (getenv (\"MULTISYNC_DEBUG\"))\n printf(\"kdepim_plugin: %s()\\n\",__FUNCTION__);\n\n printf(\"kdepim_plugin: %s\\n\", __FUNCTION__);\n KCmdLineArgs::init(1, argv, \"kde-opensync-plugin\", i18n(\"KOpenSync\"), \"KDE OpenSync plugin\", \"0.1\", false);\n applicationptr = new KApplication();\n\n \/* Allocate and initialise a kaddrbook object. *\/\n addrbook = new kaddrbook(member);\n if (!addrbook)\n \/\/FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case\n return NULL;\n\n \/* Return kaddrbook object to the sync engine *\/\n return (void*)addrbook;\n}\n\nstatic void kde_finalize(void *data)\n{\n printf(\"kdepim_plugin: %s()\\n\", __FUNCTION__);\n\n kaddrbook *addrbook = (kaddrbook *)data;\n delete addrbook;\n\n if (applicationptr) {\n delete applicationptr;\n applicationptr = 0;\n }\n}\n\nstatic void kde_connect(OSyncContext *ctx)\n{\n osync_context_report_success(ctx);\n}\n\n\nstatic void kde_disconnect(OSyncContext *ctx)\n{\n osync_context_report_success(ctx);\n}\n\nstatic void kde_get_changeinfo(OSyncContext *ctx)\n{\n kaddrbook *addrbook = addrbook_for_context(ctx);\n if (getenv (\"MULTISYNC_DEBUG\"))\n printf(\"kdepim_plugin: %s\\n\",__FUNCTION__);\n\n int err = addrbook->get_changes(ctx);\n if (err) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't access KDE addressbook\");\n return;\n }\n osync_context_report_success(ctx);\n return;\n}\n\n\nstatic osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change)\n{\n kaddrbook *addrbook = addrbook_for_context(ctx);\n int err;\n\n if (getenv (\"MULTISYNC_DEBUG\"))\n printf(\"kdepim_plugin: %s()\\n\",__FUNCTION__);\n\n err = addrbook->modify(change); \n\n \/\/FIXME: check when call sync_done()\n addrbook->sync_done(!err);\n if (err)\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't update KDE addressbook\");\n else \n osync_context_report_success(ctx);\n\n \/*FIXME: What should be returned? *\/\n return true;\n}\n\nextern \"C\" {\nvoid get_info(OSyncPluginInfo *info)\n{\n info->version = 1;\n info->name = \"kde-sync\";\n info->description = i18n(\"Plugin for the KDE 3.x Addressbook\");\n\n info->functions.initialize = kde_initialize;\n info->functions.connect = kde_connect;\n info->functions.disconnect = kde_disconnect;\n info->functions.finalize = kde_finalize;\n info->functions.get_changeinfo = kde_get_changeinfo;\n\n osync_plugin_accept_objtype(info, \"contact\");\n osync_plugin_accept_objformat(info, \"contact\", \"vcard\");\n \/*FIXME: check the differences between commit_change() and access() *\/\n osync_plugin_set_commit_objformat(info, \"contact\", \"vcard\", kde_commit_change);\n osync_plugin_set_access_objformat(info, \"contact\", \"vcard\", kde_commit_change);\n\n}\n\n}\/\/ extern \"C\"\nChanged printf() calls to osync_debug() Stupid bug fixed: don't report the changes twice\/*********************************************************************** \nOpenSync Plugin for KDE 3.x\nCopyright (C) 2004 Stewart Heitmann \n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License version 2 as\npublished by the Free Software Foundation;\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.\nIN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY\nCLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES \nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN \nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF \nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, \nCOPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS \nSOFTWARE IS DISCLAIMED.\n*************************************************************************\/\n\/*\n * 03 Nov 2004 - Eduardo Pereira Habkost \n * - Ported to OpenSync plugin interface\n *\/\n\nextern \"C\"\n{\n#include \n#include \"kaddrbook.h\"\n}\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstatic\nvoid unfold_vcard(char *vcard, size_t *size)\n{\n char* in = vcard;\n char* out = vcard;\n char *end = vcard + *size;\n while ( in < end)\n {\n \/* remove any occurrences of \"=[CR][LF]\" *\/\n \/* these denote folded line markers in VCARD format. *\/\n \/* Dont know why, but Evolution uses the leading \"=\" *\/\n \/* character to (presumably) denote a control sequence. *\/\n \/* This is not quite how I interpret the VCARD RFC2426 *\/\n \/* spec (section 2.6 line delimiting and folding). *\/\n \/* This seems to work though, so thats the main thing! *\/\n if (in[0]=='=' && in[1]==13 && in[2]==10)\n in+=3;\n else\n *out++ = *in++;\n }\n *size = out - vcard;\n}\n\nclass kaddrbook\n{\n private:\n KABC::AddressBook* addressbookptr; \n KABC::Ticket* addressbookticket;\n QDateTime syncdate, newsyncdate;\n\n OSyncMember *member;\n OSyncHashTable *hashtable;\n\n public: \n kaddrbook(OSyncMember *memb)\n :member(memb)\n {\n \/\/osync_debug(\"kde\", 3, \"kdepim_plugin: %s(%s)\\n\", __FUNCTION__);\n\n \/\/get a handle to the standard KDE addressbook\n addressbookptr = KABC::StdAddressBook::self();\n\n \/\/ensure a NULL Ticket ptr\n addressbookticket=NULL;\n\n hashtable = osync_hashtable_new();\n osync_hashtable_load(hashtable, member);\n\n };\n\n\n int get_changes(OSyncContext *ctx)\n {\n \/\/osync_debug(\"kde\", 3, \"kdepim_plugin: kaddrbook::%s(newdbs=%d)\\n\", __FUNCTION__, newdbs);\n\n \/\/remember when we started this current sync\n newsyncdate = QDateTime::currentDateTime();\n\n \/\/ We must reload the KDE addressbook in order to retrieve the latest changes.\n if (!addressbookptr->load())\n {\n osync_debug(\"kde\", 3, \"kdepim_plugin: couldnt reload KDE addressbook, aborting sync.\\n\");\n return -1;\n }\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE addressbook reloaded OK.\\n\");\n\n \/\/Lock the addressbook\n addressbookticket = addressbookptr->requestSaveTicket();\n if (!addressbookticket)\n {\n osync_debug(\"kde\", 3, \"kdepim_plugin: couldnt lock KDE addressbook, aborting sync.\\n\");\n return -1;\n }\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE addressbook locked OK.\\n\");\n\n \/\/osync_debug(\"kde\", 3, \"%s: %s : plugin UID list has %d entries\\n\", __FILE__, __FUNCTION__, uidlist.count());\n\n \/\/Check the entries of the KDE addressbook against the last entries seen by the sync-engine\n for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) {\n \/\/Get the revision date of the KDE addressbook entry.\n \/\/Regard entries with invalid revision dates as having just been changed.\n osync_debug(\"kde\", 3, \"new entry, uid: %s\\n\", it->uid().latin1());\n\n QDateTime revdate = it->revision();\n if (!revdate.isValid())\n {\n revdate = newsyncdate; \/\/use date of this sync as the revision date.\n it->setRevision(revdate); \/\/update the Addressbook entry for future reference.\n } \n\n \/\/ gmalloc a changed_object for this phonebook entry \n \/\/FIXME: deallocate it somewhere\n OSyncChange *chg= osync_change_new();\n osync_change_set_member(chg, member);\n\n QCString hash(revdate.toString());\n\n osync_change_set_hash(chg, hash);\n osync_change_set_uid(chg, it->uid().latin1());\n\n \/\/ Convert the VCARD data into a string\n KABC::VCardConverter converter;\n QString card = converter.createVCard(*it);\n QString data(card.latin1());\n \/\/FIXME: deallocate data somewhere\n osync_change_set_data(chg, strdup(data), data.length(), 1);\n\n \/\/ set the remaining fields\n osync_change_set_objtype_string(chg, \"contact\");\n osync_change_set_objformat_string(chg, \"vcard\");\n osync_change_set_hash(chg, hash.data());\n \/*FIXME: slowsync *\/\n if (osync_hashtable_detect_change(hashtable, chg, 0)) {\n osync_context_report_change(ctx, chg);\n osync_hashtable_update_hash(hashtable, chg);\n }\n }\n\n osync_hashtable_report_deleted(hashtable, ctx, 0);\n\n return 0;\n }\n\n\n int modify(OSyncChange *chg)\n {\n \/\/osync_debug(\"kde\", 3, \"kdepim_plugin: kaddrbook::%s()\\n\",__FUNCTION__);\n\n int result = 0;\n \n \/\/ Ensure we still have a lock on the KDE addressbook (we ought to)\n if (addressbookticket==NULL)\n {\n \/\/This should never happen, but just in case....\n osync_debug(\"kde\", 3, \"kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\\n\");\n return -1;\n }\n\n KABC::VCardConverter converter;\n \n \/* allocate and initialize return struct for this change entry *\/\n \/\/FIXME: check how to return errors safely\n \/\/modify_result = (syncobj_modify_result*)g_malloc0(sizeof(syncobj_modify_result));\n \/\/modify_result->result = SYNC_MSG_MODIFYERROR;\n \/\/modify_result->returnuid = NULL;\n \n OSyncObjType *type = osync_change_get_objtype(chg);\n \/\/ Do database modifications according to object type\n if (!strcmp(osync_objtype_get_name(type), \"contact\"))\n {\n\n OSyncChangeType chtype = osync_change_get_changetype(chg);\n char *uid = osync_change_get_uid(chg);\n \/* treat modified objects without UIDs as if they were newly added objects *\/\n if (chtype == CHANGE_MODIFIED && !uid)\n chtype = CHANGE_ADDED;\n \n \/\/ convert VCARD string from obj->comp into an Addresse object.\n char *data;\n size_t data_size;\n data = (char*)osync_change_get_data(chg);\n data_size = osync_change_get_datasize(chg);\n\n switch(chtype)\n {\n case CHANGE_MODIFIED:\n {\n unfold_vcard(data, &data_size);\n\n KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));\n\n \/\/ ensure it has the correct UID\n addressee.setUid(QString(uid));\n\n \/\/ replace the current addressbook entry (if any) with the new one\n addressbookptr->insertAddressee(addressee);\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)\\n\", uid); \n result = 0;\n break;\n }\n \n case CHANGE_ADDED:\n {\n \/\/ convert VCARD string from obj->comp into an Addresse object\n \/\/ KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first.\n unfold_vcard(data, &data_size);\n KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size));\n\n \/\/ ensure it has a NULL UID\n addressee.setUid(QString(NULL));\n\n \/\/ add the new address to the addressbook\n addressbookptr->insertAddressee(addressee);\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)\\n\", addressee.uid().latin1());\n\n\n \/\/ return the UID of the new entry along with the result\n osync_change_set_uid(chg, addressee.uid().latin1());\n result = 0;\n break;\n }\n \n case CHANGE_DELETED:\n {\n if (uid==NULL)\n {\n result = 1;\n break;\n }\n\n \/\/find addressbook entry with matching UID and delete it\n KABC::Addressee addressee = addressbookptr->findByUid(QString(uid));\n if(!addressee.isEmpty())\n addressbookptr->removeAddressee(addressee);\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)\\n\", uid);\n\n result = 0;\n break;\n }\n default:\n result = 0;\n } \n }\n \/\/FIXME: handle unsupported objtypes\n \n return result;\n }\n\n\n void sync_done(bool success) \n {\n \/\/osync_debug(\"kde\", 3, \"kdepim_plugin: kaddrbook::%s(%d)\\n\", __FUNCTION__, success);\n\n if (!addressbookticket)\n {\n \/\/This should never happen, but just in case\n osync_debug(\"kde\", 3, \"kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\\n\");\n\n return;\n }\n\n if (success)\n {\n \/\/ Save and unlock the KDE addressbook\n addressbookptr->save(addressbookticket);\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE addressbook saved and unlocked.\\n\");\n \n \/\/update the syncdate \n syncdate = newsyncdate; \n }\n else\n {\n \/\/ Unlock the KDE addressbook and discard all changes\n addressbookptr->releaseSaveTicket(addressbookticket);\n osync_debug(\"kde\", 3, \"kdepim_plugin: KDE addressbook unlocked and changes discarded.\\n\");\n\n }\n \n addressbookticket=NULL;\n }\n \n};\n\nstatic KApplication *applicationptr=NULL;\nstatic char name[] = \"kde-opensync-plugin\";\nstatic char *argv[] = {name,0};\n\nstatic kaddrbook *addrbook_for_context(OSyncContext *ctx)\n{\n return (kaddrbook *)osync_context_get_plugin_data(ctx);\n}\n\nstatic void *kde_initialize(OSyncMember *member)\n{\n kaddrbook *addrbook;\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: %s()\\n\",__FUNCTION__);\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: %s\\n\", __FUNCTION__);\n KCmdLineArgs::init(1, argv, \"kde-opensync-plugin\", i18n(\"KOpenSync\"), \"KDE OpenSync plugin\", \"0.1\", false);\n applicationptr = new KApplication();\n\n \/* Allocate and initialise a kaddrbook object. *\/\n addrbook = new kaddrbook(member);\n if (!addrbook)\n \/\/FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case\n return NULL;\n\n \/* Return kaddrbook object to the sync engine *\/\n return (void*)addrbook;\n}\n\nstatic void kde_finalize(void *data)\n{\n osync_debug(\"kde\", 3, \"kdepim_plugin: %s()\\n\", __FUNCTION__);\n\n kaddrbook *addrbook = (kaddrbook *)data;\n delete addrbook;\n\n if (applicationptr) {\n delete applicationptr;\n applicationptr = 0;\n }\n}\n\nstatic void kde_connect(OSyncContext *ctx)\n{\n osync_context_report_success(ctx);\n}\n\n\nstatic void kde_disconnect(OSyncContext *ctx)\n{\n osync_context_report_success(ctx);\n}\n\nstatic void kde_get_changeinfo(OSyncContext *ctx)\n{\n kaddrbook *addrbook = addrbook_for_context(ctx);\n osync_debug(\"kde\", 3, \"kdepim_plugin: %s\\n\",__FUNCTION__);\n\n int err = addrbook->get_changes(ctx);\n if (err) {\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't access KDE addressbook\");\n return;\n }\n osync_context_report_success(ctx);\n return;\n}\n\n\nstatic osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change)\n{\n kaddrbook *addrbook = addrbook_for_context(ctx);\n int err;\n\n osync_debug(\"kde\", 3, \"kdepim_plugin: %s()\\n\",__FUNCTION__);\n\n err = addrbook->modify(change); \n\n \/\/FIXME: check when call sync_done()\n addrbook->sync_done(!err);\n if (err)\n osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, \"Couldn't update KDE addressbook\");\n else \n osync_context_report_success(ctx);\n\n \/*FIXME: What should be returned? *\/\n return true;\n}\n\nextern \"C\" {\nvoid get_info(OSyncPluginInfo *info)\n{\n info->version = 1;\n info->name = \"kde-sync\";\n info->description = i18n(\"Plugin for the KDE 3.x Addressbook\");\n\n info->functions.initialize = kde_initialize;\n info->functions.connect = kde_connect;\n info->functions.disconnect = kde_disconnect;\n info->functions.finalize = kde_finalize;\n info->functions.get_changeinfo = kde_get_changeinfo;\n\n osync_plugin_accept_objtype(info, \"contact\");\n osync_plugin_accept_objformat(info, \"contact\", \"vcard\");\n \/*FIXME: check the differences between commit_change() and access() *\/\n osync_plugin_set_commit_objformat(info, \"contact\", \"vcard\", kde_commit_change);\n osync_plugin_set_access_objformat(info, \"contact\", \"vcard\", kde_commit_change);\n\n}\n\n}\/\/ extern \"C\"\n<|endoftext|>"} {"text":"\/*----------------------------------------------\r\n POPPRNT.C -- Popup Editor Printing Functions\r\n ----------------------------------------------*\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"poppad.h\"\r\n#include \"resource.h\"\r\n#include \"Footy2.h\"\r\n\r\nextern int activeFootyID;\r\n\r\nBOOL bUserAbort ;\r\nHWND hDlgPrint ;\r\n\r\nBOOL CALLBACK PrintDlgProc (HWND hDlg, UINT msg, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/)\r\n {\r\n switch (msg)\r\n {\r\n case WM_INITDIALOG :\r\n EnableMenuItem (GetSystemMenu (hDlg, FALSE), SC_CLOSE,\r\n MF_GRAYED) ;\r\n return TRUE ;\r\n\r\n case WM_COMMAND :\r\n bUserAbort = TRUE ;\r\n EnableWindow (GetParent (hDlg), TRUE) ;\r\n DestroyWindow (hDlg) ;\r\n hDlgPrint = 0 ;\r\n return TRUE ;\r\n }\r\n return FALSE ;\r\n } \r\n\r\nBOOL CALLBACK AbortProc (HDC \/*hPrinterDC*\/, int \/*iCode*\/)\r\n {\r\n MSG msg ;\r\n\r\n while (!bUserAbort && PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))\r\n {\r\n if (!hDlgPrint || !IsDialogMessage (hDlgPrint, &msg))\r\n {\r\n TranslateMessage (&msg) ;\r\n DispatchMessage (&msg) ;\r\n }\r\n }\r\n return !bUserAbort ;\r\n }\r\n\r\nBOOL PopPrntPrintFile (HINSTANCE hInst, HWND hwnd, HWND \/*hwndEdit*\/, \r\n LPSTR szTitleName)\r\n {\r\n static DOCINFO di = { sizeof (DOCINFO), \"\", NULL } ;\r\n static PRINTDLG pd ;\r\n BOOL bSuccess ;\r\n int yChar, iCharsPerLine, iLinesPerPage, iTotalLines,\r\n iTotalPages, iPage, iLine, iLineNum ;\r\n TEXTMETRIC tm ;\r\n WORD iColCopy, iNoiColCopy ;\r\n\r\n pd.lStructSize = sizeof (PRINTDLG) ;\r\n pd.hwndOwner = hwnd ;\r\n pd.hDevMode = NULL ;\r\n pd.hDevNames = NULL ;\r\n pd.hDC = NULL ;\r\n pd.Flags = PD_ALLPAGES | PD_COLLATE | PD_RETURNDC ;\r\n pd.nFromPage = 0 ;\r\n pd.nToPage = 0 ;\r\n pd.nMinPage = 0 ;\r\n pd.nMaxPage = 0 ;\r\n pd.nCopies = 1 ;\r\n pd.hInstance = NULL ;\r\n pd.lCustData = 0L ;\r\n pd.lpfnPrintHook = NULL ;\r\n pd.lpfnSetupHook = NULL ;\r\n pd.lpPrintTemplateName = NULL ;\r\n pd.lpSetupTemplateName = NULL ;\r\n pd.hPrintTemplate = NULL ;\r\n pd.hSetupTemplate = NULL ;\r\n\r\n if (!PrintDlg (&pd))\r\n return TRUE ;\r\n\r\n\/\/ iTotalLines = (short) SendMessage (hwndEdit, EM_GETLINECOUNT, 0, 0L) ;\r\n\t iTotalLines = (short)Footy2GetLines(activeFootyID);\r\n \r\n if (iTotalLines == 0)\r\n return TRUE ;\r\n\r\n GetTextMetrics (pd.hDC, &tm) ;\r\n yChar = tm.tmHeight + tm.tmExternalLeading ;\r\n\r\n iCharsPerLine = GetDeviceCaps (pd.hDC, HORZRES) \/ tm.tmAveCharWidth ;\r\n iLinesPerPage = GetDeviceCaps (pd.hDC, VERTRES) \/ yChar ;\r\n iTotalPages = (iTotalLines + iLinesPerPage - 1) \/ iLinesPerPage ;\r\n\r\n EnableWindow (hwnd, FALSE) ;\r\n\r\n bSuccess = TRUE ;\r\n bUserAbort = FALSE ;\r\n\r\n hDlgPrint = CreateDialog (hInst, (LPCTSTR) \"PrintDlgBox\", hwnd, (DLGPROC)PrintDlgProc) ;\r\n SetDlgItemText (hDlgPrint, IDD_FNAME, szTitleName) ;\r\n\r\n SetAbortProc (pd.hDC, (ABORTPROC)AbortProc) ;\r\n\r\n\t di.lpszDocName = szTitleName;\r\n\r\n if (StartDoc (pd.hDC, &di) > 0)\r\n {\r\n for (iColCopy = 0 ;\r\n iColCopy < ((WORD) pd.Flags & PD_COLLATE ? pd.nCopies : 1) ;\r\n iColCopy++)\r\n {\r\n for (iPage = 0 ; iPage < iTotalPages ; iPage++)\r\n {\r\n for (iNoiColCopy = 0 ;\r\n iNoiColCopy < (pd.Flags & PD_COLLATE ? 1 : pd.nCopies) ;\r\n iNoiColCopy++)\r\n {\r\n\r\n if (StartPage (pd.hDC) < 0)\r\n {\r\n bSuccess = FALSE ;\r\n break ;\r\n }\r\n\r\n for (iLine = 0 ; iLine < iLinesPerPage ; iLine++)\r\n {\r\n iLineNum = iLinesPerPage * iPage + iLine ;\r\n\r\n if (iLineNum >= iTotalLines)\r\n break ;\r\n\r\n\/\/ TextOut (pd.hDC, 0, yChar * iLine, pstrBuffer,\r\n\/\/ (int) SendMessage (hwndEdit, EM_GETLINE,\r\n\/\/ (WPARAM) iLineNum, (LPARAM) pstrBuffer)) ;\r\n\t\t\t\t\t\/\/\t\t pstrBuffer = FootyGetLineData(activeFootyID, iLineNum+1);\t\/\/ 2008-02-17 Shark++ \r\n\t\t\t\t\t\/\/\t\t TextOut(pd.hDC, 0, yChar * iLine, pstrBuffer, \r\n\t\t\t\t\t\/\/\t\t\t FootyGetLineLen(activeFootyID, iLineNum+1));\r\n\t\t\t\t\t\t\t LPCWSTR pstrBufferW = Footy2GetLineW(activeFootyID, iLineNum);\t\/\/ 2008-02-28 Shark++ SpE܂Ԃ()\r\n\t\t\t\t\t\t\t TextOutW(pd.hDC, 0, yChar * iLine, pstrBufferW, \r\n\t\t\t\t\t\t\t\t Footy2GetLineLengthW(activeFootyID, iLineNum));\r\n }\r\n\r\n if (EndPage (pd.hDC) < 0)\r\n {\r\n bSuccess = FALSE ;\r\n break ;\r\n }\r\n\r\n if (bUserAbort)\r\n break ;\r\n }\r\n\r\n if (!bSuccess || bUserAbort)\r\n break ;\r\n }\r\n\r\n if (!bSuccess || bUserAbort)\r\n break ;\r\n }\r\n }\r\n else\r\n bSuccess = FALSE ;\r\n\r\n if (bSuccess)\r\n EndDoc (pd.hDC) ;\r\n\r\n if (!bUserAbort)\r\n {\r\n EnableWindow (hwnd, TRUE) ;\r\n DestroyWindow (hDlgPrint) ;\r\n }\r\n\r\n DeleteDC (pd.hDC) ;\r\n\r\n return bSuccess && !bUserAbort ;\r\n }\r\n印刷機能にタブの反映・行番号の追加・フォント設定などをテスト実装\/*----------------------------------------------\r\n POPPRNT.C -- Popup Editor Printing Functions\r\n ----------------------------------------------*\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"poppad.h\"\r\n#include \"resource.h\"\r\n#include \"Footy2.h\"\r\n\r\nextern int activeFootyID;\r\n\r\nBOOL bUserAbort ;\r\nHWND hDlgPrint ;\r\n\r\nBOOL CALLBACK PrintDlgProc (HWND hDlg, UINT msg, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/)\r\n {\r\n switch (msg)\r\n {\r\n case WM_INITDIALOG :\r\n EnableMenuItem (GetSystemMenu (hDlg, FALSE), SC_CLOSE,\r\n MF_GRAYED) ;\r\n return TRUE ;\r\n\r\n case WM_COMMAND :\r\n bUserAbort = TRUE ;\r\n EnableWindow (GetParent (hDlg), TRUE) ;\r\n DestroyWindow (hDlg) ;\r\n hDlgPrint = 0 ;\r\n return TRUE ;\r\n }\r\n return FALSE ;\r\n } \r\n\r\nBOOL CALLBACK AbortProc (HDC \/*hPrinterDC*\/, int \/*iCode*\/)\r\n {\r\n MSG msg ;\r\n\r\n while (!bUserAbort && PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))\r\n {\r\n if (!hDlgPrint || !IsDialogMessage (hDlgPrint, &msg))\r\n {\r\n TranslateMessage (&msg) ;\r\n DispatchMessage (&msg) ;\r\n }\r\n }\r\n return !bUserAbort ;\r\n }\r\n\r\nBOOL PopPrntPrintFile (HINSTANCE hInst, HWND hwnd, HWND \/*hwndEdit*\/, \r\n LPSTR szTitleName)\r\n {\r\n static DOCINFO di = { sizeof (DOCINFO), \"\", NULL } ;\r\n static PRINTDLG pd ;\r\n BOOL bSuccess ;\r\n int yChar, iCharsPerLine, iLinesPerPage, iTotalLines,\r\n iTotalPages, iPage, iLine, iLineNum ;\r\n TEXTMETRIC tm ;\r\n WORD iColCopy, iNoiColCopy ;\r\n\r\n pd.lStructSize = sizeof (PRINTDLG) ;\r\n pd.hwndOwner = hwnd ;\r\n pd.hDevMode = NULL ;\r\n pd.hDevNames = NULL ;\r\n pd.hDC = NULL ;\r\n pd.Flags = PD_ALLPAGES | PD_COLLATE | PD_RETURNDC ;\r\n pd.nFromPage = 0 ;\r\n pd.nToPage = 0 ;\r\n pd.nMinPage = 0 ;\r\n pd.nMaxPage = 0 ;\r\n pd.nCopies = 1 ;\r\n pd.hInstance = NULL ;\r\n pd.lCustData = 0L ;\r\n pd.lpfnPrintHook = NULL ;\r\n pd.lpfnSetupHook = NULL ;\r\n pd.lpPrintTemplateName = NULL ;\r\n pd.lpSetupTemplateName = NULL ;\r\n pd.hPrintTemplate = NULL ;\r\n pd.hSetupTemplate = NULL ;\r\n\r\n if (!PrintDlg (&pd))\r\n return TRUE ;\r\n\r\n\/\/ iTotalLines = (short) SendMessage (hwndEdit, EM_GETLINECOUNT, 0, 0L) ;\r\n\t iTotalLines = (short)Footy2GetLines(activeFootyID);\r\n \r\n if (iTotalLines == 0)\r\n return TRUE ;\r\n\r\n\t TCHAR szLineNumber[64];\r\n\t int nLineNumberCharWidth = 1;\r\n\t _stprintf(szLineNumber, \"%d:\", iTotalLines);\r\n\t nLineNumberCharWidth = lstrlen(szLineNumber) - 1;\r\n\r\n\/\/\t DEVMODE dm;\r\n\/\/\t GetDeviceCaps(\r\n\r\n\t HFONT hFont = CreateFont(-MulDiv(10, GetDeviceCaps(pd.hDC, LOGPIXELSY), 72), 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET,\r\n\t\t\t\tOUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, \"lr SVbN\");\r\n\t HFONT hFoltOld = (HFONT)SelectObject(pd.hDC, hFont);\r\n\r\n\t RECT rc = {0};\r\n\t DrawText(pd.hDC, szLineNumber, -1, &rc, DT_CALCRECT);\r\n\t int nLineNumberWidth = rc.right - rc.left;\r\n\r\n\t DRAWTEXTPARAMS dtp = { sizeof(DRAWTEXTPARAMS), 4, };\r\n\r\n GetTextMetrics (pd.hDC, &tm) ;\r\n yChar = tm.tmHeight + tm.tmExternalLeading ;\r\n\r\n\t SIZE sizePage;\r\n\t sizePage.cx = GetDeviceCaps (pd.hDC, HORZRES);\r\n\t sizePage.cy = GetDeviceCaps (pd.hDC, VERTRES);\r\n iCharsPerLine = sizePage.cx \/ tm.tmAveCharWidth ;\r\n iLinesPerPage = sizePage.cy \/ yChar ;\r\n iTotalPages = (iTotalLines + iLinesPerPage - 1) \/ iLinesPerPage ;\r\n\r\n EnableWindow (hwnd, FALSE) ;\r\n\r\n bSuccess = TRUE ;\r\n bUserAbort = FALSE ;\r\n\r\n hDlgPrint = CreateDialog (hInst, (LPCTSTR) \"PrintDlgBox\", hwnd, (DLGPROC)PrintDlgProc) ;\r\n SetDlgItemText (hDlgPrint, IDD_FNAME, szTitleName) ;\r\n\r\n SetAbortProc (pd.hDC, (ABORTPROC)AbortProc) ;\r\n\r\n\t di.lpszDocName = szTitleName;\r\n\r\n if (StartDoc (pd.hDC, &di) > 0)\r\n {\r\n for (iColCopy = 0 ;\r\n iColCopy < ((WORD) pd.Flags & PD_COLLATE ? pd.nCopies : 1) ;\r\n iColCopy++)\r\n {\r\n for (iPage = 0 ; iPage < iTotalPages ; iPage++)\r\n {\r\n for (iNoiColCopy = 0 ;\r\n iNoiColCopy < (pd.Flags & PD_COLLATE ? 1 : pd.nCopies) ;\r\n iNoiColCopy++)\r\n {\r\n\r\n if (StartPage (pd.hDC) < 0)\r\n {\r\n bSuccess = FALSE ;\r\n break ;\r\n }\r\n\r\n for (iLine = 0 ; iLine < iLinesPerPage ; iLine++)\r\n {\r\n iLineNum = iLinesPerPage * iPage + iLine ;\r\n\r\n if (iLineNum >= iTotalLines)\r\n break ;\r\n\r\n\/\/ TextOut (pd.hDC, 0, yChar * iLine, pstrBuffer,\r\n\/\/ (int) SendMessage (hwndEdit, EM_GETLINE,\r\n\/\/ (WPARAM) iLineNum, (LPARAM) pstrBuffer)) ;\r\n\t\t\t\t\t\/\/\t\t pstrBuffer = FootyGetLineData(activeFootyID, iLineNum+1);\t\/\/ 2008-02-17 Shark++ \r\n\t\t\t\t\t\/\/\t\t TextOut(pd.hDC, 0, yChar * iLine, pstrBuffer, \r\n\t\t\t\t\t\/\/\t\t\t FootyGetLineLen(activeFootyID, iLineNum+1));\r\n\t\t\t\t\t\t\t \/\/ sԍ\r\n\t\t\t\t\t\t\t _stprintf(szLineNumber, \"%*d \", nLineNumberCharWidth, iLineNum + 1);\r\n\t\t\t\t\t\t\t TextOut(pd.hDC, 0, yChar * iLine, szLineNumber, lstrlen(szLineNumber));\r\n\t\t\t\t\t\t\t \/\/ se\r\n\t\t\t\t\t\t\t LPCWSTR pstrBufferW = Footy2GetLineW(activeFootyID, iLineNum);\t\/\/ 2008-02-28 Shark++ SpE܂Ԃ()\r\n\t\t\t\t\t\t\t SetRect(&rc, nLineNumberWidth, yChar * iLine, nLineNumberWidth + sizePage.cx, yChar * iLine + yChar);\r\n\t\t\t\t\t\t\t DrawTextExW(pd.hDC, (LPWSTR)pstrBufferW, \r\n\t\t\t\t\t\t\t\t Footy2GetLineLengthW(activeFootyID, iLineNum)\r\n\t\t\t\t\t\t\t\t , &rc, DT_SINGLELINE|DT_EXPANDTABS|DT_NOPREFIX|DT_TABSTOP, &dtp);\r\n }\r\n\r\n if (EndPage (pd.hDC) < 0)\r\n {\r\n bSuccess = FALSE ;\r\n break ;\r\n }\r\n\r\n if (bUserAbort)\r\n break ;\r\n }\r\n\r\n if (!bSuccess || bUserAbort)\r\n break ;\r\n }\r\n\r\n if (!bSuccess || bUserAbort)\r\n break ;\r\n }\r\n }\r\n else\r\n bSuccess = FALSE ;\r\n\r\n if (bSuccess)\r\n EndDoc (pd.hDC) ;\r\n\r\n if (!bUserAbort)\r\n {\r\n EnableWindow (hwnd, TRUE) ;\r\n DestroyWindow (hDlgPrint) ;\r\n }\r\n\r\n\t DeleteObject( SelectObject(pd.hDC, hFoltOld) );\r\n\r\n\t DeleteDC (pd.hDC) ;\r\n\r\n return bSuccess && !bUserAbort ;\r\n }\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \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\nusing search::feature_t;\nusing namespace search::fef;\nusing namespace search::fef::test;\nusing namespace search::features;\nusing search::AttributeFactory;\nusing search::IntegerAttribute;\nusing search::StringAttribute;\nusing vespalib::eval::Value;\nusing vespalib::eval::Function;\nusing vespalib::tensor::Tensor;\n\ntypedef search::attribute::Config AVC;\ntypedef search::attribute::BasicType AVBT;\ntypedef search::attribute::CollectionType AVCT;\ntypedef search::AttributeVector::SP AttributePtr;\ntypedef FtTestApp FTA;\n\nstruct SetupFixture\n{\n TensorFromLabelsBlueprint blueprint;\n IndexEnvironment indexEnv;\n SetupFixture()\n : blueprint(),\n indexEnv()\n {\n }\n};\n\nTEST_F(\"require that blueprint can be created from factory\", SetupFixture)\n{\n EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, \"tensorFromLabels\"));\n}\n\nTEST_F(\"require that setup fails if source spec is invalid\", SetupFixture)\n{\n FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add(\"source(foo)\"));\n}\n\nTEST_F(\"require that setup succeeds with attribute source\", SetupFixture)\n{\n FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add(\"attribute(foo)\"),\n StringList(), StringList().add(\"tensor\"));\n}\n\nTEST_F(\"require that setup succeeds with query source\", SetupFixture)\n{\n FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add(\"query(foo)\"),\n StringList(), StringList().add(\"tensor\"));\n}\n\nstruct ExecFixture\n{\n BlueprintFactory factory;\n FtFeatureTest test;\n ExecFixture(const vespalib::string &feature)\n : factory(),\n test(factory, feature)\n {\n setup_search_features(factory);\n setupAttributeVectors();\n setupQueryEnvironment();\n ASSERT_TRUE(test.setup());\n }\n void setupAttributeVectors() {\n std::vector attrs;\n attrs.push_back(AttributeFactory::createAttribute(\"astr\", AVC(AVBT::STRING, AVCT::ARRAY)));\n attrs.push_back(AttributeFactory::createAttribute(\"aint\", AVC(AVBT::INT32, AVCT::ARRAY)));\n attrs.push_back(AttributeFactory::createAttribute(\"wsstr\", AVC(AVBT::STRING, AVCT::WSET)));\n\n for (const auto &attr : attrs) {\n attr->addReservedDoc();\n attr->addDocs(1);\n test.getIndexEnv().getAttributeManager().add(attr);\n }\n\n StringAttribute *astr = static_cast(attrs[0].get());\n \/\/ Note that the weight parameter is not used\n astr->append(1, \"a\", 0);\n astr->append(1, \"b\", 0);\n astr->append(1, \"c\", 0);\n\n IntegerAttribute *aint = static_cast(attrs[1].get());\n aint->append(1, 3, 0);\n aint->append(1, 5, 0);\n aint->append(1, 7, 0);\n\n for (const auto &attr : attrs) {\n attr->commit();\n }\n }\n void setupQueryEnvironment() {\n test.getQueryEnv().getProperties().add(\"astr_query\", \"[d e f]\");\n test.getQueryEnv().getProperties().add(\"aint_query\", \"[11 13 17]\");\n }\n const Tensor &extractTensor() {\n const Value::CREF *value = test.resolveObjectFeature();\n ASSERT_TRUE(value != nullptr);\n ASSERT_TRUE(value->get().is_tensor());\n return static_cast(*value->get().as_tensor());\n }\n const Tensor &execute() {\n test.executeOnly();\n return extractTensor();\n }\n};\n\n\/\/ Tests for attribute source:\n\nTEST_F(\"require that array string attribute can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(astr))\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {astr:a}:1, {astr:b}:1, {astr:c}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that array string attribute can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(astr),dim)\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {dim:a}:1, {dim:b}:1, {dim:c}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that array integer attribute can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(aint))\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {aint:7}:1, {aint:3}:1, {aint:5}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that array attribute can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(aint),dim)\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {dim:7}:1, {dim:3}:1, {dim:5}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if attribute does not exists\",\n ExecFixture(\"tensorFromLabels(attribute(null))\"))\n{\n EXPECT_EQUAL(AsEmptyTensor(\"tensor(null{})\"), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if attribute type is not supported\",\n ExecFixture(\"tensorFromLabels(attribute(wsstr))\"))\n{\n EXPECT_EQUAL(AsEmptyTensor(\"tensor(wsstr{})\"), f.execute());\n}\n\n\n\/\/ Tests for query source:\n\nTEST_F(\"require that string array from query can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(query(astr_query))\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {astr_query:d}:1, {astr_query:e}:1, {astr_query:f}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that integer array from query can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(query(aint_query))\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {aint_query:13}:1, {aint_query:17}:1, {aint_query:11}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that string array from query can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(query(astr_query),dim)\"))\n{\n EXPECT_EQUAL(AsTensor(\"{ {dim:d}:1, {dim:e}:1, {dim:f}:1 }\"), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if query parameter is not found\",\n ExecFixture(\"tensorFromLabels(query(null))\"))\n{\n EXPECT_EQUAL(AsEmptyTensor(\"tensor(null{})\"), f.execute());\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\nuse spec to make tensors\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\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#include \n\nusing search::feature_t;\nusing namespace search::fef;\nusing namespace search::fef::test;\nusing namespace search::features;\nusing search::AttributeFactory;\nusing search::IntegerAttribute;\nusing search::StringAttribute;\nusing vespalib::eval::Value;\nusing vespalib::eval::Function;\nusing vespalib::eval::TensorSpec;\nusing vespalib::tensor::DefaultTensorEngine;\nusing vespalib::tensor::Tensor;\n\ntypedef search::attribute::Config AVC;\ntypedef search::attribute::BasicType AVBT;\ntypedef search::attribute::CollectionType AVCT;\ntypedef search::AttributeVector::SP AttributePtr;\ntypedef FtTestApp FTA;\n\nTensor::UP make_tensor(const TensorSpec &spec) {\n auto tensor = DefaultTensorEngine::ref().create(spec);\n return Tensor::UP(dynamic_cast(tensor.release()));\n}\n\nTensor::UP make_empty(const vespalib::string &type) {\n return make_tensor(TensorSpec(type));\n}\n\nstruct SetupFixture\n{\n TensorFromLabelsBlueprint blueprint;\n IndexEnvironment indexEnv;\n SetupFixture()\n : blueprint(),\n indexEnv()\n {\n }\n};\n\nTEST_F(\"require that blueprint can be created from factory\", SetupFixture)\n{\n EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, \"tensorFromLabels\"));\n}\n\nTEST_F(\"require that setup fails if source spec is invalid\", SetupFixture)\n{\n FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add(\"source(foo)\"));\n}\n\nTEST_F(\"require that setup succeeds with attribute source\", SetupFixture)\n{\n FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add(\"attribute(foo)\"),\n StringList(), StringList().add(\"tensor\"));\n}\n\nTEST_F(\"require that setup succeeds with query source\", SetupFixture)\n{\n FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add(\"query(foo)\"),\n StringList(), StringList().add(\"tensor\"));\n}\n\nstruct ExecFixture\n{\n BlueprintFactory factory;\n FtFeatureTest test;\n ExecFixture(const vespalib::string &feature)\n : factory(),\n test(factory, feature)\n {\n setup_search_features(factory);\n setupAttributeVectors();\n setupQueryEnvironment();\n ASSERT_TRUE(test.setup());\n }\n void setupAttributeVectors() {\n std::vector attrs;\n attrs.push_back(AttributeFactory::createAttribute(\"astr\", AVC(AVBT::STRING, AVCT::ARRAY)));\n attrs.push_back(AttributeFactory::createAttribute(\"aint\", AVC(AVBT::INT32, AVCT::ARRAY)));\n attrs.push_back(AttributeFactory::createAttribute(\"wsstr\", AVC(AVBT::STRING, AVCT::WSET)));\n\n for (const auto &attr : attrs) {\n attr->addReservedDoc();\n attr->addDocs(1);\n test.getIndexEnv().getAttributeManager().add(attr);\n }\n\n StringAttribute *astr = static_cast(attrs[0].get());\n \/\/ Note that the weight parameter is not used\n astr->append(1, \"a\", 0);\n astr->append(1, \"b\", 0);\n astr->append(1, \"c\", 0);\n\n IntegerAttribute *aint = static_cast(attrs[1].get());\n aint->append(1, 3, 0);\n aint->append(1, 5, 0);\n aint->append(1, 7, 0);\n\n for (const auto &attr : attrs) {\n attr->commit();\n }\n }\n void setupQueryEnvironment() {\n test.getQueryEnv().getProperties().add(\"astr_query\", \"[d e f]\");\n test.getQueryEnv().getProperties().add(\"aint_query\", \"[11 13 17]\");\n }\n const Tensor &extractTensor() {\n const Value::CREF *value = test.resolveObjectFeature();\n ASSERT_TRUE(value != nullptr);\n ASSERT_TRUE(value->get().is_tensor());\n return static_cast(*value->get().as_tensor());\n }\n const Tensor &execute() {\n test.executeOnly();\n return extractTensor();\n }\n};\n\n\/\/ Tests for attribute source:\n\nTEST_F(\"require that array string attribute can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(astr))\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(astr{})\")\n .add({{\"astr\", \"a\"}}, 1)\n .add({{\"astr\", \"b\"}}, 1)\n .add({{\"astr\", \"c\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that array string attribute can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(astr),dim)\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(dim{})\")\n .add({{\"dim\", \"a\"}}, 1)\n .add({{\"dim\", \"b\"}}, 1)\n .add({{\"dim\", \"c\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that array integer attribute can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(aint))\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(aint{})\")\n .add({{\"aint\", \"7\"}}, 1)\n .add({{\"aint\", \"3\"}}, 1)\n .add({{\"aint\", \"5\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that array attribute can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(attribute(aint),dim)\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(dim{})\")\n .add({{\"dim\", \"7\"}}, 1)\n .add({{\"dim\", \"3\"}}, 1)\n .add({{\"dim\", \"5\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if attribute does not exists\",\n ExecFixture(\"tensorFromLabels(attribute(null))\"))\n{\n EXPECT_EQUAL(*make_empty(\"tensor(null{})\"), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if attribute type is not supported\",\n ExecFixture(\"tensorFromLabels(attribute(wsstr))\"))\n{\n EXPECT_EQUAL(*make_empty(\"tensor(wsstr{})\"), f.execute());\n}\n\n\n\/\/ Tests for query source:\n\nTEST_F(\"require that string array from query can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(query(astr_query))\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(astr_query{})\")\n .add({{\"astr_query\", \"d\"}}, 1)\n .add({{\"astr_query\", \"e\"}}, 1)\n .add({{\"astr_query\", \"f\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that integer array from query can be converted to tensor (default dimension)\",\n ExecFixture(\"tensorFromLabels(query(aint_query))\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(aint_query{})\")\n .add({{\"aint_query\", \"13\"}}, 1)\n .add({{\"aint_query\", \"17\"}}, 1)\n .add({{\"aint_query\", \"11\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that string array from query can be converted to tensor (explicit dimension)\",\n ExecFixture(\"tensorFromLabels(query(astr_query),dim)\"))\n{\n EXPECT_EQUAL(*make_tensor(TensorSpec(\"tensor(dim{})\")\n .add({{\"dim\", \"d\"}}, 1)\n .add({{\"dim\", \"e\"}}, 1)\n .add({{\"dim\", \"f\"}}, 1)), f.execute());\n}\n\nTEST_F(\"require that empty tensor is created if query parameter is not found\",\n ExecFixture(\"tensorFromLabels(query(null))\"))\n{\n EXPECT_EQUAL(*make_empty(\"tensor(null{})\"), f.execute());\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping_3d\/sparse_pose_graph\/optimization_problem.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Eigen\/Core\"\n#include \"cartographer\/common\/ceres_solver_options.h\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer\/common\/math.h\"\n#include \"cartographer\/common\/time.h\"\n#include \"cartographer\/mapping_3d\/acceleration_cost_function.h\"\n#include \"cartographer\/mapping_3d\/ceres_pose.h\"\n#include \"cartographer\/mapping_3d\/imu_integration.h\"\n#include \"cartographer\/mapping_3d\/rotation_cost_function.h\"\n#include \"cartographer\/mapping_3d\/rotation_parameterization.h\"\n#include \"cartographer\/mapping_3d\/sparse_pose_graph\/spa_cost_function.h\"\n#include \"cartographer\/transform\/transform.h\"\n#include \"ceres\/ceres.h\"\n#include \"ceres\/jet.h\"\n#include \"ceres\/rotation.h\"\n#include \"glog\/logging.h\"\n\nnamespace cartographer {\nnamespace mapping_3d {\nnamespace sparse_pose_graph {\n\nOptimizationProblem::OptimizationProblem(\n const mapping::sparse_pose_graph::proto::OptimizationProblemOptions&\n options,\n FixZ fix_z)\n : options_(options), fix_z_(fix_z) {}\n\nOptimizationProblem::~OptimizationProblem() {}\n\nvoid OptimizationProblem::AddImuData(const int trajectory_id,\n const sensor::ImuData& imu_data) {\n CHECK_GE(trajectory_id, 0);\n imu_data_.resize(\n std::max(imu_data_.size(), static_cast(trajectory_id) + 1));\n imu_data_[trajectory_id].push_back(imu_data);\n}\n\nvoid OptimizationProblem::AddFixedFramePoseData(\n const int trajectory_id,\n const sensor::FixedFramePoseData& fixed_frame_pose_data) {\n CHECK_GE(trajectory_id, 0);\n fixed_frame_pose_data_.resize(std::max(\n fixed_frame_pose_data_.size(), static_cast(trajectory_id) + 1));\n fixed_frame_pose_data_[trajectory_id].Push(fixed_frame_pose_data.time,\n fixed_frame_pose_data.pose);\n}\n\nvoid OptimizationProblem::AddTrajectoryNode(\n const int trajectory_id, const common::Time time,\n const transform::Rigid3d& point_cloud_pose) {\n CHECK_GE(trajectory_id, 0);\n node_data_.resize(\n std::max(node_data_.size(), static_cast(trajectory_id) + 1));\n node_data_[trajectory_id].push_back(NodeData{time, point_cloud_pose});\n}\n\nvoid OptimizationProblem::AddSubmap(const int trajectory_id,\n const transform::Rigid3d& submap_pose) {\n CHECK_GE(trajectory_id, 0);\n submap_data_.resize(\n std::max(submap_data_.size(), static_cast(trajectory_id) + 1));\n submap_data_[trajectory_id].push_back(SubmapData{submap_pose});\n}\n\nvoid OptimizationProblem::SetMaxNumIterations(const int32 max_num_iterations) {\n options_.mutable_ceres_solver_options()->set_max_num_iterations(\n max_num_iterations);\n}\n\nvoid OptimizationProblem::Solve(const std::vector& constraints,\n const std::set& frozen_trajectories) {\n if (node_data_.empty()) {\n \/\/ Nothing to optimize.\n return;\n }\n\n ceres::Problem::Options problem_options;\n ceres::Problem problem(problem_options);\n\n const auto translation_parameterization =\n [this]() -> std::unique_ptr {\n return fix_z_ == FixZ::kYes\n ? common::make_unique(\n 3, std::vector{2})\n : nullptr;\n };\n\n \/\/ Set the starting point.\n CHECK(!submap_data_.empty());\n CHECK(!submap_data_[0].empty());\n \/\/ TODO(hrapp): Move ceres data into SubmapData.\n std::vector> C_submaps(submap_data_.size());\n std::vector> C_nodes(node_data_.size());\n for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();\n ++trajectory_id) {\n const bool frozen = frozen_trajectories.count(trajectory_id);\n for (size_t submap_index = 0;\n submap_index != submap_data_[trajectory_id].size(); ++submap_index) {\n if (trajectory_id == 0 && submap_index == 0) {\n \/\/ Tie the first submap of the first trajectory to the origin.\n C_submaps[trajectory_id].emplace_back(\n transform::Rigid3d::Identity(), translation_parameterization(),\n common::make_unique>(),\n &problem);\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().translation());\n } else {\n C_submaps[trajectory_id].emplace_back(\n submap_data_[trajectory_id][submap_index].pose,\n translation_parameterization(),\n common::make_unique(), &problem);\n }\n if (frozen) {\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().rotation());\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().translation());\n }\n }\n }\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n const bool frozen = frozen_trajectories.count(trajectory_id);\n for (size_t node_index = 0; node_index != node_data_[trajectory_id].size();\n ++node_index) {\n C_nodes[trajectory_id].emplace_back(\n node_data_[trajectory_id][node_index].point_cloud_pose,\n translation_parameterization(),\n common::make_unique(), &problem);\n if (frozen) {\n problem.SetParameterBlockConstant(\n C_nodes[trajectory_id].back().rotation());\n problem.SetParameterBlockConstant(\n C_nodes[trajectory_id].back().translation());\n }\n }\n }\n\n \/\/ Add cost functions for intra- and inter-submap constraints.\n for (const Constraint& constraint : constraints) {\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new SpaCostFunction(constraint.pose)),\n \/\/ Only loop closure constraints should have a loss function.\n constraint.tag == Constraint::INTER_SUBMAP\n ? new ceres::HuberLoss(options_.huber_scale())\n : nullptr,\n C_submaps.at(constraint.submap_id.trajectory_id)\n .at(constraint.submap_id.submap_index)\n .rotation(),\n C_submaps.at(constraint.submap_id.trajectory_id)\n .at(constraint.submap_id.submap_index)\n .translation(),\n C_nodes.at(constraint.node_id.trajectory_id)\n .at(constraint.node_id.node_index)\n .rotation(),\n C_nodes.at(constraint.node_id.trajectory_id)\n .at(constraint.node_id.node_index)\n .translation());\n }\n\n \/\/ Add constraints based on IMU observations of angular velocities and\n \/\/ linear acceleration.\n trajectory_data_.resize(imu_data_.size());\n CHECK_GE(trajectory_data_.size(), node_data_.size());\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n const auto& node_data = node_data_[trajectory_id];\n if (node_data.empty()) {\n \/\/ We skip empty trajectories which might not have any IMU data.\n continue;\n }\n TrajectoryData& trajectory_data = trajectory_data_.at(trajectory_id);\n problem.AddParameterBlock(trajectory_data.imu_calibration.data(), 4,\n new ceres::QuaternionParameterization());\n const std::deque& imu_data = imu_data_.at(trajectory_id);\n CHECK(!imu_data.empty());\n\n \/\/ Skip IMU data before the first node of this trajectory.\n auto it = imu_data.cbegin();\n while ((it + 1) != imu_data.cend() && (it + 1)->time <= node_data[0].time) {\n ++it;\n }\n\n for (size_t node_index = 1; node_index < node_data.size(); ++node_index) {\n auto it2 = it;\n const IntegrateImuResult result =\n IntegrateImu(imu_data, node_data[node_index - 1].time,\n node_data[node_index].time, &it);\n if (node_index + 1 < node_data.size()) {\n const common::Time first_time = node_data[node_index - 1].time;\n const common::Time second_time = node_data[node_index].time;\n const common::Time third_time = node_data[node_index + 1].time;\n const common::Duration first_duration = second_time - first_time;\n const common::Duration second_duration = third_time - second_time;\n const common::Time first_center = first_time + first_duration \/ 2;\n const common::Time second_center = second_time + second_duration \/ 2;\n const IntegrateImuResult result_to_first_center =\n IntegrateImu(imu_data, first_time, first_center, &it2);\n const IntegrateImuResult result_center_to_center =\n IntegrateImu(imu_data, first_center, second_center, &it2);\n \/\/ 'delta_velocity' is the change in velocity from the point in time\n \/\/ halfway between the first and second poses to halfway between second\n \/\/ and third pose. It is computed from IMU data and still contains a\n \/\/ delta due to gravity. The orientation of this vector is in the IMU\n \/\/ frame at the second pose.\n const Eigen::Vector3d delta_velocity =\n (result.delta_rotation.inverse() *\n result_to_first_center.delta_rotation) *\n result_center_to_center.delta_velocity;\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new AccelerationCostFunction(\n options_.acceleration_weight(), delta_velocity,\n common::ToSeconds(first_duration),\n common::ToSeconds(second_duration))),\n nullptr, C_nodes[trajectory_id].at(node_index).rotation(),\n C_nodes[trajectory_id].at(node_index - 1).translation(),\n C_nodes[trajectory_id].at(node_index).translation(),\n C_nodes[trajectory_id].at(node_index + 1).translation(),\n &trajectory_data.gravity_constant,\n trajectory_data.imu_calibration.data());\n }\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new RotationCostFunction(options_.rotation_weight(),\n result.delta_rotation)),\n nullptr, C_nodes[trajectory_id].at(node_index - 1).rotation(),\n C_nodes[trajectory_id].at(node_index).rotation(),\n trajectory_data.imu_calibration.data());\n }\n }\n\n \/\/ Solve.\n ceres::Solver::Summary summary;\n ceres::Solve(\n common::CreateCeresSolverOptions(options_.ceres_solver_options()),\n &problem, &summary);\n\n if (options_.log_solver_summary()) {\n LOG(INFO) << summary.FullReport();\n for (size_t trajectory_id = 0; trajectory_id != trajectory_data_.size();\n ++trajectory_id) {\n if (trajectory_id != 0) {\n LOG(INFO) << \"Trajectory \" << trajectory_id << \":\";\n }\n LOG(INFO) << \"Gravity was: \"\n << trajectory_data_[trajectory_id].gravity_constant;\n const auto& imu_calibration =\n trajectory_data_[trajectory_id].imu_calibration;\n LOG(INFO) << \"IMU correction was: \"\n << common::RadToDeg(2. * std::acos(imu_calibration[0]))\n << \" deg (\" << imu_calibration[0] << \", \" << imu_calibration[1]\n << \", \" << imu_calibration[2] << \", \" << imu_calibration[3]\n << \")\";\n }\n }\n\n \/\/ Store the result.\n for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();\n ++trajectory_id) {\n for (size_t submap_index = 0;\n submap_index != submap_data_[trajectory_id].size(); ++submap_index) {\n submap_data_[trajectory_id][submap_index].pose =\n C_submaps[trajectory_id][submap_index].ToRigid();\n }\n }\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n for (size_t node_index = 0; node_index != node_data_[trajectory_id].size();\n ++node_index) {\n node_data_[trajectory_id][node_index].point_cloud_pose =\n C_nodes[trajectory_id][node_index].ToRigid();\n }\n }\n}\n\nconst std::vector>& OptimizationProblem::node_data()\n const {\n return node_data_;\n}\n\nconst std::vector>& OptimizationProblem::submap_data()\n const {\n return submap_data_;\n}\n\n} \/\/ namespace sparse_pose_graph\n} \/\/ namespace mapping_3d\n} \/\/ namespace cartographer\nAdd fixed frame pose constraints to 3D problem. (#480)\/*\n * Copyright 2016 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping_3d\/sparse_pose_graph\/optimization_problem.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Eigen\/Core\"\n#include \"cartographer\/common\/ceres_solver_options.h\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer\/common\/math.h\"\n#include \"cartographer\/common\/time.h\"\n#include \"cartographer\/mapping_3d\/acceleration_cost_function.h\"\n#include \"cartographer\/mapping_3d\/ceres_pose.h\"\n#include \"cartographer\/mapping_3d\/imu_integration.h\"\n#include \"cartographer\/mapping_3d\/rotation_cost_function.h\"\n#include \"cartographer\/mapping_3d\/rotation_parameterization.h\"\n#include \"cartographer\/mapping_3d\/sparse_pose_graph\/spa_cost_function.h\"\n#include \"cartographer\/transform\/transform.h\"\n#include \"ceres\/ceres.h\"\n#include \"ceres\/jet.h\"\n#include \"ceres\/rotation.h\"\n#include \"glog\/logging.h\"\n\nnamespace cartographer {\nnamespace mapping_3d {\nnamespace sparse_pose_graph {\n\nOptimizationProblem::OptimizationProblem(\n const mapping::sparse_pose_graph::proto::OptimizationProblemOptions&\n options,\n FixZ fix_z)\n : options_(options), fix_z_(fix_z) {}\n\nOptimizationProblem::~OptimizationProblem() {}\n\nvoid OptimizationProblem::AddImuData(const int trajectory_id,\n const sensor::ImuData& imu_data) {\n CHECK_GE(trajectory_id, 0);\n imu_data_.resize(\n std::max(imu_data_.size(), static_cast(trajectory_id) + 1));\n imu_data_[trajectory_id].push_back(imu_data);\n}\n\nvoid OptimizationProblem::AddFixedFramePoseData(\n const int trajectory_id,\n const sensor::FixedFramePoseData& fixed_frame_pose_data) {\n CHECK_GE(trajectory_id, 0);\n fixed_frame_pose_data_.resize(std::max(\n fixed_frame_pose_data_.size(), static_cast(trajectory_id) + 1));\n fixed_frame_pose_data_[trajectory_id].Push(fixed_frame_pose_data.time,\n fixed_frame_pose_data.pose);\n}\n\nvoid OptimizationProblem::AddTrajectoryNode(\n const int trajectory_id, const common::Time time,\n const transform::Rigid3d& point_cloud_pose) {\n CHECK_GE(trajectory_id, 0);\n node_data_.resize(\n std::max(node_data_.size(), static_cast(trajectory_id) + 1));\n node_data_[trajectory_id].push_back(NodeData{time, point_cloud_pose});\n}\n\nvoid OptimizationProblem::AddSubmap(const int trajectory_id,\n const transform::Rigid3d& submap_pose) {\n CHECK_GE(trajectory_id, 0);\n submap_data_.resize(\n std::max(submap_data_.size(), static_cast(trajectory_id) + 1));\n submap_data_[trajectory_id].push_back(SubmapData{submap_pose});\n}\n\nvoid OptimizationProblem::SetMaxNumIterations(const int32 max_num_iterations) {\n options_.mutable_ceres_solver_options()->set_max_num_iterations(\n max_num_iterations);\n}\n\nvoid OptimizationProblem::Solve(const std::vector& constraints,\n const std::set& frozen_trajectories) {\n if (node_data_.empty()) {\n \/\/ Nothing to optimize.\n return;\n }\n\n ceres::Problem::Options problem_options;\n ceres::Problem problem(problem_options);\n\n const auto translation_parameterization =\n [this]() -> std::unique_ptr {\n return fix_z_ == FixZ::kYes\n ? common::make_unique(\n 3, std::vector{2})\n : nullptr;\n };\n\n \/\/ Set the starting point.\n CHECK(!submap_data_.empty());\n CHECK(!submap_data_[0].empty());\n \/\/ TODO(hrapp): Move ceres data into SubmapData.\n std::vector> C_submaps(submap_data_.size());\n std::vector> C_nodes(node_data_.size());\n for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();\n ++trajectory_id) {\n const bool frozen = frozen_trajectories.count(trajectory_id);\n for (size_t submap_index = 0;\n submap_index != submap_data_[trajectory_id].size(); ++submap_index) {\n if (trajectory_id == 0 && submap_index == 0) {\n \/\/ Tie the first submap of the first trajectory to the origin.\n C_submaps[trajectory_id].emplace_back(\n transform::Rigid3d::Identity(), translation_parameterization(),\n common::make_unique>(),\n &problem);\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().translation());\n } else {\n C_submaps[trajectory_id].emplace_back(\n submap_data_[trajectory_id][submap_index].pose,\n translation_parameterization(),\n common::make_unique(), &problem);\n }\n if (frozen) {\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().rotation());\n problem.SetParameterBlockConstant(\n C_submaps[trajectory_id].back().translation());\n }\n }\n }\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n const bool frozen = frozen_trajectories.count(trajectory_id);\n for (size_t node_index = 0; node_index != node_data_[trajectory_id].size();\n ++node_index) {\n C_nodes[trajectory_id].emplace_back(\n node_data_[trajectory_id][node_index].point_cloud_pose,\n translation_parameterization(),\n common::make_unique(), &problem);\n if (frozen) {\n problem.SetParameterBlockConstant(\n C_nodes[trajectory_id].back().rotation());\n problem.SetParameterBlockConstant(\n C_nodes[trajectory_id].back().translation());\n }\n }\n }\n\n \/\/ Add cost functions for intra- and inter-submap constraints.\n for (const Constraint& constraint : constraints) {\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new SpaCostFunction(constraint.pose)),\n \/\/ Only loop closure constraints should have a loss function.\n constraint.tag == Constraint::INTER_SUBMAP\n ? new ceres::HuberLoss(options_.huber_scale())\n : nullptr,\n C_submaps.at(constraint.submap_id.trajectory_id)\n .at(constraint.submap_id.submap_index)\n .rotation(),\n C_submaps.at(constraint.submap_id.trajectory_id)\n .at(constraint.submap_id.submap_index)\n .translation(),\n C_nodes.at(constraint.node_id.trajectory_id)\n .at(constraint.node_id.node_index)\n .rotation(),\n C_nodes.at(constraint.node_id.trajectory_id)\n .at(constraint.node_id.node_index)\n .translation());\n }\n\n \/\/ Add constraints based on IMU observations of angular velocities and\n \/\/ linear acceleration.\n trajectory_data_.resize(imu_data_.size());\n CHECK_GE(trajectory_data_.size(), node_data_.size());\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n const auto& node_data = node_data_[trajectory_id];\n if (node_data.empty()) {\n \/\/ We skip empty trajectories which might not have any IMU data.\n continue;\n }\n TrajectoryData& trajectory_data = trajectory_data_.at(trajectory_id);\n problem.AddParameterBlock(trajectory_data.imu_calibration.data(), 4,\n new ceres::QuaternionParameterization());\n const std::deque& imu_data = imu_data_.at(trajectory_id);\n CHECK(!imu_data.empty());\n\n \/\/ Skip IMU data before the first node of this trajectory.\n auto it = imu_data.cbegin();\n while ((it + 1) != imu_data.cend() && (it + 1)->time <= node_data[0].time) {\n ++it;\n }\n\n for (size_t node_index = 1; node_index < node_data.size(); ++node_index) {\n auto it2 = it;\n const IntegrateImuResult result =\n IntegrateImu(imu_data, node_data[node_index - 1].time,\n node_data[node_index].time, &it);\n if (node_index + 1 < node_data.size()) {\n const common::Time first_time = node_data[node_index - 1].time;\n const common::Time second_time = node_data[node_index].time;\n const common::Time third_time = node_data[node_index + 1].time;\n const common::Duration first_duration = second_time - first_time;\n const common::Duration second_duration = third_time - second_time;\n const common::Time first_center = first_time + first_duration \/ 2;\n const common::Time second_center = second_time + second_duration \/ 2;\n const IntegrateImuResult result_to_first_center =\n IntegrateImu(imu_data, first_time, first_center, &it2);\n const IntegrateImuResult result_center_to_center =\n IntegrateImu(imu_data, first_center, second_center, &it2);\n \/\/ 'delta_velocity' is the change in velocity from the point in time\n \/\/ halfway between the first and second poses to halfway between second\n \/\/ and third pose. It is computed from IMU data and still contains a\n \/\/ delta due to gravity. The orientation of this vector is in the IMU\n \/\/ frame at the second pose.\n const Eigen::Vector3d delta_velocity =\n (result.delta_rotation.inverse() *\n result_to_first_center.delta_rotation) *\n result_center_to_center.delta_velocity;\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new AccelerationCostFunction(\n options_.acceleration_weight(), delta_velocity,\n common::ToSeconds(first_duration),\n common::ToSeconds(second_duration))),\n nullptr, C_nodes[trajectory_id].at(node_index).rotation(),\n C_nodes[trajectory_id].at(node_index - 1).translation(),\n C_nodes[trajectory_id].at(node_index).translation(),\n C_nodes[trajectory_id].at(node_index + 1).translation(),\n &trajectory_data.gravity_constant,\n trajectory_data.imu_calibration.data());\n }\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new RotationCostFunction(options_.rotation_weight(),\n result.delta_rotation)),\n nullptr, C_nodes[trajectory_id].at(node_index - 1).rotation(),\n C_nodes[trajectory_id].at(node_index).rotation(),\n trajectory_data.imu_calibration.data());\n }\n }\n\n \/\/ Add fixed frame pose constraints.\n std::deque C_fixed_frames;\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n if (trajectory_id >= fixed_frame_pose_data_.size()) {\n break;\n }\n\n bool fixed_frame_pose_initialized = false;\n\n const auto& node_data = node_data_[trajectory_id];\n for (size_t node_index = 0; node_index < node_data.size(); ++node_index) {\n if (!fixed_frame_pose_data_.at(trajectory_id)\n .Has(node_data[node_index].time)) {\n continue;\n }\n\n const mapping::SparsePoseGraph::Constraint::Pose constraint_pose{\n fixed_frame_pose_data_.at(trajectory_id)\n .Lookup(node_data[node_index].time),\n options_.fixed_frame_pose_translation_weight(),\n options_.fixed_frame_pose_rotation_weight()};\n\n if (!fixed_frame_pose_initialized) {\n const transform::Rigid3d fixed_frame_pose_in_map =\n node_data[node_index].point_cloud_pose *\n constraint_pose.zbar_ij.inverse();\n C_fixed_frames.emplace_back(\n transform::Rigid3d(\n fixed_frame_pose_in_map.translation(),\n Eigen::AngleAxisd(\n transform::GetYaw(fixed_frame_pose_in_map.rotation()),\n Eigen::Vector3d::UnitZ())),\n nullptr,\n common::make_unique>(),\n &problem);\n fixed_frame_pose_initialized = true;\n }\n\n problem.AddResidualBlock(\n new ceres::AutoDiffCostFunction(\n new SpaCostFunction(constraint_pose)),\n nullptr, C_fixed_frames.back().rotation(),\n C_fixed_frames.back().translation(),\n C_nodes.at(trajectory_id).at(node_index).rotation(),\n C_nodes.at(trajectory_id).at(node_index).translation());\n }\n }\n\n \/\/ Solve.\n ceres::Solver::Summary summary;\n ceres::Solve(\n common::CreateCeresSolverOptions(options_.ceres_solver_options()),\n &problem, &summary);\n\n if (options_.log_solver_summary()) {\n LOG(INFO) << summary.FullReport();\n for (size_t trajectory_id = 0; trajectory_id != trajectory_data_.size();\n ++trajectory_id) {\n if (trajectory_id != 0) {\n LOG(INFO) << \"Trajectory \" << trajectory_id << \":\";\n }\n LOG(INFO) << \"Gravity was: \"\n << trajectory_data_[trajectory_id].gravity_constant;\n const auto& imu_calibration =\n trajectory_data_[trajectory_id].imu_calibration;\n LOG(INFO) << \"IMU correction was: \"\n << common::RadToDeg(2. * std::acos(imu_calibration[0]))\n << \" deg (\" << imu_calibration[0] << \", \" << imu_calibration[1]\n << \", \" << imu_calibration[2] << \", \" << imu_calibration[3]\n << \")\";\n }\n }\n\n \/\/ Store the result.\n for (size_t trajectory_id = 0; trajectory_id != submap_data_.size();\n ++trajectory_id) {\n for (size_t submap_index = 0;\n submap_index != submap_data_[trajectory_id].size(); ++submap_index) {\n submap_data_[trajectory_id][submap_index].pose =\n C_submaps[trajectory_id][submap_index].ToRigid();\n }\n }\n for (size_t trajectory_id = 0; trajectory_id != node_data_.size();\n ++trajectory_id) {\n for (size_t node_index = 0; node_index != node_data_[trajectory_id].size();\n ++node_index) {\n node_data_[trajectory_id][node_index].point_cloud_pose =\n C_nodes[trajectory_id][node_index].ToRigid();\n }\n }\n}\n\nconst std::vector>& OptimizationProblem::node_data()\n const {\n return node_data_;\n}\n\nconst std::vector>& OptimizationProblem::submap_data()\n const {\n return submap_data_;\n}\n\n} \/\/ namespace sparse_pose_graph\n} \/\/ namespace mapping_3d\n} \/\/ namespace cartographer\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace urbi\n{\n\n const USyncClient::options USyncClient::options::default_options =\n USyncClient::options();\n\n USyncClient::options::options()\n : timeout_(0)\n , mtag_(0)\n , mmod_(0)\n {}\n\n USyncClient::options&\n USyncClient::options::timeout(libport::utime_t usec)\n {\n timeout_ = usec;\n return *this;\n }\n\n USyncClient::options&\n USyncClient::options::tag(const char* tag, const char* mod)\n {\n mtag_ = tag;\n mmod_ = mod;\n return *this;\n }\n\n USyncClient::USyncClient(const std::string& host,\n\t\t\t unsigned port,\n\t\t\t size_t buflen,\n\t\t\t bool server,\n bool startCallbackThread,\n\t\t\t unsigned semListenInc)\n : UClient(host, port, buflen, server, semListenInc)\n , sem_()\n , queueLock_()\n , message_(0)\n , syncLock_()\n , syncTag()\n , default_options_()\n , stopCallbackThread_(!startCallbackThread)\n , cbThread(0)\n {\n if (error())\n return;\n\n if (startCallbackThread)\n cbThread = libport::startThread(this, &USyncClient::callbackThread);\n if (!defaultClient)\n defaultClient = this;\n\n listenSem_++;\n callbackSem_++;\n }\n\n USyncClient::~USyncClient()\n {\n closeUClient();\n\n if (cbThread)\n joinCallbackThread_();\n }\n\n void USyncClient::callbackThread()\n {\n callbackSem_--;\n\n while (true)\n {\n sem_--;\n if (stopCallbackThread_)\n {\n\t\/\/ The call to stopCallbackThread is\n\t\/\/ waiting on stopCallbackSem_.\n\tstopCallbackSem_++;\n\treturn;\n }\n queueLock_.lock();\n if (queue.empty())\n {\n\t\/\/ Only explanation: processEvents from another thread stole our\n\t\/\/ message.\n\tsem_++; \/\/ Give back the token we took without popping a message.\n\tqueueLock_.unlock();\n\tcontinue;\n }\n UMessage *m = queue.front();\n queue.pop_front();\n queueLock_.unlock();\n UAbstractClient::notifyCallbacks(*m);\n delete m;\n }\n }\n\n void USyncClient::stopCallbackThread()\n {\n if (stopCallbackThread_)\n return;\n stopCallbackThread_ = true;\n sem_++;\n \/\/ Wait until the callback thread is actually stopped to avoid both\n \/\/ processEvents and the callbackThread running at the same time.\n stopCallbackSem_--;\n }\n\n bool USyncClient::processEvents(libport::utime_t timeout)\n {\n bool res = false;\n libport::utime_t startTime = libport::utime();\n while (timeout < 0 || libport::utime() - startTime <= timeout)\n {\n queueLock_.lock();\n if (queue.empty())\n {\n\tqueueLock_.unlock();\n\treturn res;\n }\n res = true;\n UMessage *m = queue.front();\n queue.pop_front();\n sem_--; \/\/ Will not block since queue was not empty.\n queueLock_.unlock();\n UAbstractClient::notifyCallbacks(*m);\n delete m;\n }\n return res;\n }\n\n int USyncClient::joinCallbackThread_()\n {\n stopCallbackThread();\n if (cbThread)\n {\n pthread_join(cbThread, 0);\n cbThread = 0;\n }\n return 0;\n }\n\n void\n USyncClient::notifyCallbacks(const UMessage& msg)\n {\n queueLock_.lock();\n \/\/ If waiting for a tag, pass it to the user.\n if (!syncTag.empty() && syncTag == msg.tag)\n {\n message_ = new UMessage(msg);\n syncTag.clear();\n syncLock_++;\n }\n else\n {\n queue.push_back(new UMessage(msg));\n sem_++;\n }\n queueLock_.unlock();\n }\n\n UMessage*\n USyncClient::waitForTag(const std::string& tag, libport::utime_t useconds)\n {\n syncTag = tag;\n queueLock_.unlock();\n \/\/ syncTag is reset by the other thread.\n UMessage *res = syncLock_.uget(useconds) ? message_ : 0;\n if (!res)\n std::cerr << \"Timed out\" << std::endl;\n else if (res->type == MESSAGE_ERROR)\n std::cerr << \"Received error message: \" << *res << std::endl;\n message_ = 0;\n return res;\n }\n\n namespace\n {\n \/\/\/ Check that \\a cp looks like \"foo <\" or \"foo :\".\n \/\/\/ I venture this is an attempt to see if there is a \"tag\" or a\n \/\/\/ channel.\n static\n bool\n has_tag(const char* cp)\n {\n while (*cp == ' ')\n ++cp;\n while (isalpha(*cp))\n ++cp;\n while (*cp == ' ')\n ++cp;\n return *cp == ':' || *cp == '<';\n }\n\n \/\/\/ Return the concatenation of t1 and t2, make it unique\n \/\/\/ if they are empty.\n static\n std::string\n make_tag(UAbstractClient& cl, const USyncClient::options& opt)\n {\n std::string res;\n if (opt.mtag_)\n {\n res = opt.mtag_;\n if (opt.mmod_)\n res += opt.mmod_;\n }\n else\n res = cl.fresh();\n return res;\n }\n }\n\n UMessage*\n USyncClient::syncGet_(const char* format, va_list& arg,\n\t\t\tconst USyncClient::options& options)\n {\n const USyncClient::options& opt_used = getOptions(options);\n if (has_tag(format))\n return 0;\n sendBufferLock.lock();\n rc = vpack(format, arg);\n if (rc < 0)\n {\n sendBufferLock.unlock();\n return 0;\n }\n std::string tag = make_tag(*this, opt_used);\n effective_send(compatibility::evaluate_in_channel_open(tag));\n queueLock_.lock();\n rc = effective_send(sendBuffer);\n sendBuffer[0] = 0;\n sendBufferLock.unlock();\n effective_send(compatibility::evaluate_in_channel_close(tag));\n return waitForTag(opt_used.mtag_ ? opt_used.mtag_ : tag,\n opt_used.timeout_);\n }\n\n UMessage*\n USyncClient::syncGet(const char* format, ...)\n {\n va_list arg;\n va_start(arg, format);\n UMessage* res = syncGet_(format, arg);\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGet(const std::string& msg)\n {\n \/\/ Yes, this is studid, as it will copy uselessly. But that's the\n \/\/ only safe way to do it. The interface should be redesigned,\n \/\/ without buffers actually.\n return syncGet(\"%s\", msg.c_str());\n }\n\n UMessage*\n USyncClient::syncGet(libport::utime_t useconds,\n const char* format, ...)\n {\n va_list arg;\n va_start(arg, format);\n UMessage* res = syncGet_(format, arg, options().timeout(useconds));\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGetTag(const char* format,\n const char* mtag, const char* mmod, ...)\n {\n va_list arg;\n va_start(arg, mmod);\n UMessage* res = syncGet_(format, arg, options().tag(mtag, mmod));\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGetTag(libport::utime_t useconds,\n const char* format,\n const char* mtag,\n const char* mmod, ...)\n {\n va_list arg;\n va_start(arg, mmod);\n UMessage* res = syncGet_(format, arg,\n\t\t\t options().tag(mtag, mmod).timeout(useconds));\n va_end(arg);\n return res;\n }\n\n int\n USyncClient::syncGetImage(const char* camera,\n\t\t\t void* buffer, size_t& buffersize,\n\t\t\t int format, int transmitFormat,\n\t\t\t size_t& width, size_t& height,\n\t\t\t libport::utime_t useconds)\n {\n int f = format == IMAGE_JPEG || transmitFormat == URBI_TRANSMIT_JPEG;\n \/\/XXX required to ensure format change is applied\n send(\"%s.format = %d;\\n\"\n \"noop;\\n\"\n \"noop;\\n\", camera, f);\n UMessage *m = syncGet(useconds, \"%s.val;\\n\", camera);\n if (!m)\n return 0;\n if (m->value->binary->type != BINARY_IMAGE)\n {\n delete m;\n return 0;\n }\n width = m->value->binary->image.width;\n height = m->value->binary->image.height;\n\n size_t osize = buffersize;\n if (f == 1 && format != IMAGE_JPEG)\n {\n \/\/uncompress jpeg\n if (format == IMAGE_YCbCr)\n\tconvertJPEGtoYCrCb((const byte*) m->value->binary->image.data,\n\t\t\t m->value->binary->image.size, (byte*) buffer,\n\t\t\t buffersize);\n else\n\tconvertJPEGtoRGB((const byte*) m->value->binary->image.data,\n\t\t\t m->value->binary->image.size, (byte*) buffer,\n\t\t\t buffersize);\n }\n else if (format == IMAGE_RGB || format == IMAGE_PPM)\n {\n buffersize = std::min(m->value->binary->image.size,\n\t\t\t static_cast (buffersize));\n if (m->value->binary->image.imageFormat == IMAGE_YCbCr)\n\tconvertYCrCbtoRGB((const byte*) m->value->binary->image.data,\n\t\t\t buffersize, (byte*) buffer);\n else\n\tmemcpy(buffer, m->value->binary->image.data, buffersize);\n\n }\n else\n {\n \/\/jpeg jpeg, or ycrcb ycrcb\n buffersize = std::min(m->value->binary->image.size,\n\t\t\t static_cast(buffersize));\n memcpy(buffer, m->value->binary->image.data, buffersize);\n }\n if (format == IMAGE_PPM)\n {\n char p6h[20];\n sprintf(p6h, \"P6\\n%zu %zu\\n255\\n\", width, height);\n size_t p6len = strlen(p6h);\n size_t mlen = osize > buffersize + p6len ? buffersize : osize - p6len;\n memmove((void *) (((long) buffer) + p6len), buffer, mlen);\n memcpy(buffer, p6h, p6len);\n buffersize += p6len;\n }\n delete m;\n return 1;\n }\n\n int\n USyncClient::syncGetNormalizedDevice(const char* device, double& val,\n\t\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.valn;\\n\", device), val);\n }\n\n int\n USyncClient::syncGetValue(const char* valName, UValue& val,\n\t\t\t libport::utime_t useconds)\n {\n return syncGetValue(0, valName, val, useconds);\n }\n\n int\n USyncClient::syncGetValue(const char* tag, const char* valName, UValue& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGetTag(useconds, \"%s;\\n\", tag, 0, valName), val);\n }\n\n int\n USyncClient::syncGetDevice(const char* device, double& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.val;\\n\", device), val);\n }\n\n int\n USyncClient::syncGetResult(const char* command, double& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s\", command), val);\n }\n\n\n int\n USyncClient::syncGetDevice(const char* device, const char* access,\n\t\t\t double& val, libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.%s;\", device, access), val);\n }\n\n\n int\n USyncClient::syncGetSound(const char* device, int duration, USound& sound,\n\t\t\t libport::utime_t useconds)\n {\n send(\"syncgetsound = BIN 0;\\n\"\n\t \"loopsound: loop syncgetsound = syncgetsound + %s.val,\\n\"\n\t \" {\\n\"\n\t \" sleep(%d);\\n\"\n\t \" stop loopsound;\\n\"\n\t \" noop;\\n\"\n\t \" noop;\\n\"\n\t \" };\\n\", device, duration);\n UMessage* m = syncGet(useconds, \"%s\", \"syncgetsound;\");\n if (!m)\n return 0;\n if (m->type != MESSAGE_DATA\n\t|| m->value->type != DATA_BINARY\n\t|| m->value->binary->type != BINARY_SOUND)\n {\n delete m;\n return 0;\n }\n convert(m->value->binary->sound, sound);\n delete m;\n return 1;\n }\n\n int\n USyncClient::syncSend(const void* buffer, size_t length)\n {\n if (rc != 0)\n return -1;\n sendBufferLock.lock();\n size_t sent = 0;\n while (sent < length)\n {\n int res = ::write(sd, (char*) buffer + sent, length - sent);\n if (res < 0)\n {\n\trc = res;\n\tsendBufferLock.unlock();\n\treturn res;\n }\n sent += res;\n }\n sendBufferLock.unlock();\n return 0;\n }\n\n void\n USyncClient::waitForKernelVersion(bool hasProcessingThread)\n {\n \/\/ Do not call kernelMajor() which precisely requires kernelMajor_\n \/\/ to be defined.\n while (kernelMajor_ < 0 && !error())\n {\n if (!hasProcessingThread)\n processEvents();\n usleep(100000);\n }\n }\n\n void\n USyncClient::setDefaultOptions(const USyncClient::options& opt)\n {\n default_options_ = opt;\n }\n\n const USyncClient::options&\n USyncClient::getOptions(const USyncClient::options& opt) const\n {\n return (&opt == &USyncClient::options::default_options) ?\n default_options_ : opt;\n }\n\n} \/\/ namespace urbi\nusyncclient: simplifications.#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace urbi\n{\n\n const USyncClient::options USyncClient::options::default_options =\n USyncClient::options();\n\n USyncClient::options::options()\n : timeout_(0)\n , mtag_(0)\n , mmod_(0)\n {}\n\n USyncClient::options&\n USyncClient::options::timeout(libport::utime_t usec)\n {\n timeout_ = usec;\n return *this;\n }\n\n USyncClient::options&\n USyncClient::options::tag(const char* tag, const char* mod)\n {\n mtag_ = tag;\n mmod_ = mod;\n return *this;\n }\n\n USyncClient::USyncClient(const std::string& host,\n\t\t\t unsigned port,\n\t\t\t size_t buflen,\n\t\t\t bool server,\n bool startCallbackThread,\n\t\t\t unsigned semListenInc)\n : UClient(host, port, buflen, server, semListenInc)\n , sem_()\n , queueLock_()\n , message_(0)\n , syncLock_()\n , syncTag()\n , default_options_()\n , stopCallbackThread_(!startCallbackThread)\n , cbThread(0)\n {\n if (error())\n return;\n\n if (startCallbackThread)\n cbThread = libport::startThread(this, &USyncClient::callbackThread);\n if (!defaultClient)\n defaultClient = this;\n\n listenSem_++;\n callbackSem_++;\n }\n\n USyncClient::~USyncClient()\n {\n closeUClient();\n\n if (cbThread)\n joinCallbackThread_();\n }\n\n void USyncClient::callbackThread()\n {\n callbackSem_--;\n\n while (true)\n {\n sem_--;\n if (stopCallbackThread_)\n {\n\t\/\/ The call to stopCallbackThread is\n\t\/\/ waiting on stopCallbackSem_.\n\tstopCallbackSem_++;\n\treturn;\n }\n queueLock_.lock();\n if (queue.empty())\n {\n\t\/\/ Only explanation: processEvents from another thread stole our\n\t\/\/ message.\n\tsem_++; \/\/ Give back the token we took without popping a message.\n\tqueueLock_.unlock();\n\tcontinue;\n }\n UMessage *m = queue.front();\n queue.pop_front();\n queueLock_.unlock();\n UAbstractClient::notifyCallbacks(*m);\n delete m;\n }\n }\n\n void USyncClient::stopCallbackThread()\n {\n if (stopCallbackThread_)\n return;\n stopCallbackThread_ = true;\n sem_++;\n \/\/ Wait until the callback thread is actually stopped to avoid both\n \/\/ processEvents and the callbackThread running at the same time.\n stopCallbackSem_--;\n }\n\n bool USyncClient::processEvents(libport::utime_t timeout)\n {\n bool res = false;\n libport::utime_t startTime = libport::utime();\n while (timeout < 0 || libport::utime() - startTime <= timeout)\n {\n queueLock_.lock();\n if (queue.empty())\n {\n\tqueueLock_.unlock();\n\treturn res;\n }\n res = true;\n UMessage *m = queue.front();\n queue.pop_front();\n sem_--; \/\/ Will not block since queue was not empty.\n queueLock_.unlock();\n UAbstractClient::notifyCallbacks(*m);\n delete m;\n }\n return res;\n }\n\n int USyncClient::joinCallbackThread_()\n {\n stopCallbackThread();\n if (cbThread)\n {\n pthread_join(cbThread, 0);\n cbThread = 0;\n }\n return 0;\n }\n\n void\n USyncClient::notifyCallbacks(const UMessage& msg)\n {\n queueLock_.lock();\n \/\/ If waiting for a tag, pass it to the user.\n if (!syncTag.empty() && syncTag == msg.tag)\n {\n message_ = new UMessage(msg);\n syncTag.clear();\n syncLock_++;\n }\n else\n {\n queue.push_back(new UMessage(msg));\n sem_++;\n }\n queueLock_.unlock();\n }\n\n UMessage*\n USyncClient::waitForTag(const std::string& tag, libport::utime_t useconds)\n {\n syncTag = tag;\n queueLock_.unlock();\n \/\/ syncTag is reset by the other thread.\n UMessage *res = syncLock_.uget(useconds) ? message_ : 0;\n if (!res)\n std::cerr << \"Timed out\" << std::endl;\n else if (res->type == MESSAGE_ERROR)\n std::cerr << \"Received error message: \" << *res << std::endl;\n message_ = 0;\n return res;\n }\n\n namespace\n {\n \/\/\/ Check that \\a cp looks like \"foo <\" or \"foo :\".\n \/\/\/ I venture this is an attempt to see if there is a \"tag\" or a\n \/\/\/ channel.\n static\n bool\n has_tag(const char* cp)\n {\n while (*cp == ' ')\n ++cp;\n while (isalpha(*cp))\n ++cp;\n while (*cp == ' ')\n ++cp;\n return *cp == ':' || *cp == '<';\n }\n\n \/\/\/ Return the concatenation of t1 and t2, make it unique\n \/\/\/ if they are empty.\n static\n std::string\n make_tag(UAbstractClient& cl, const USyncClient::options& opt)\n {\n std::string res;\n if (opt.mtag_)\n {\n res = opt.mtag_;\n if (opt.mmod_)\n res += opt.mmod_;\n }\n else\n res = cl.fresh();\n return res;\n }\n }\n\n UMessage*\n USyncClient::syncGet_(const char* format, va_list& arg,\n\t\t\tconst USyncClient::options& options)\n {\n const USyncClient::options& opt_used = getOptions(options);\n if (has_tag(format))\n return 0;\n sendBufferLock.lock();\n rc = vpack(format, arg);\n if (rc < 0)\n {\n sendBufferLock.unlock();\n return 0;\n }\n std::string tag = make_tag(*this, opt_used);\n effective_send(compatibility::evaluate_in_channel_open(tag));\n queueLock_.lock();\n rc = effective_send(sendBuffer);\n sendBuffer[0] = 0;\n sendBufferLock.unlock();\n effective_send(compatibility::evaluate_in_channel_close(tag));\n return waitForTag(opt_used.mtag_ ? opt_used.mtag_ : tag,\n opt_used.timeout_);\n }\n\n UMessage*\n USyncClient::syncGet(const char* format, ...)\n {\n va_list arg;\n va_start(arg, format);\n UMessage* res = syncGet_(format, arg);\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGet(const std::string& msg)\n {\n \/\/ Yes, this is studid, as it will copy uselessly. But that's the\n \/\/ only safe way to do it. The interface should be redesigned,\n \/\/ without buffers actually.\n return syncGet(\"%s\", msg.c_str());\n }\n\n UMessage*\n USyncClient::syncGet(libport::utime_t useconds,\n const char* format, ...)\n {\n va_list arg;\n va_start(arg, format);\n UMessage* res = syncGet_(format, arg, options().timeout(useconds));\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGetTag(const char* format,\n const char* mtag, const char* mmod, ...)\n {\n va_list arg;\n va_start(arg, mmod);\n UMessage* res = syncGet_(format, arg, options().tag(mtag, mmod));\n va_end(arg);\n return res;\n }\n\n UMessage*\n USyncClient::syncGetTag(libport::utime_t useconds,\n const char* format,\n const char* mtag,\n const char* mmod, ...)\n {\n va_list arg;\n va_start(arg, mmod);\n UMessage* res = syncGet_(format, arg,\n\t\t\t options().tag(mtag, mmod).timeout(useconds));\n va_end(arg);\n return res;\n }\n\n int\n USyncClient::syncGetImage(const char* camera,\n\t\t\t void* buffer, size_t& buffersize,\n\t\t\t int format, int transmitFormat,\n\t\t\t size_t& width, size_t& height,\n\t\t\t libport::utime_t useconds)\n {\n int f = format == IMAGE_JPEG || transmitFormat == URBI_TRANSMIT_JPEG;\n \/\/XXX required to ensure format change is applied\n send(\"%s.format = %d;\\n\"\n \"noop;\\n\"\n \"noop;\\n\", camera, f);\n UMessage *m = syncGet(useconds, \"%s.val\", camera);\n if (!m)\n return 0;\n if (m->value->binary->type != BINARY_IMAGE)\n {\n delete m;\n return 0;\n }\n width = m->value->binary->image.width;\n height = m->value->binary->image.height;\n\n size_t osize = buffersize;\n if (f == 1 && format != IMAGE_JPEG)\n {\n \/\/uncompress jpeg\n if (format == IMAGE_YCbCr)\n\tconvertJPEGtoYCrCb((const byte*) m->value->binary->image.data,\n\t\t\t m->value->binary->image.size, (byte*) buffer,\n\t\t\t buffersize);\n else\n\tconvertJPEGtoRGB((const byte*) m->value->binary->image.data,\n\t\t\t m->value->binary->image.size, (byte*) buffer,\n\t\t\t buffersize);\n }\n else if (format == IMAGE_RGB || format == IMAGE_PPM)\n {\n buffersize = std::min(m->value->binary->image.size,\n\t\t\t static_cast (buffersize));\n if (m->value->binary->image.imageFormat == IMAGE_YCbCr)\n\tconvertYCrCbtoRGB((const byte*) m->value->binary->image.data,\n\t\t\t buffersize, (byte*) buffer);\n else\n\tmemcpy(buffer, m->value->binary->image.data, buffersize);\n\n }\n else\n {\n \/\/jpeg jpeg, or ycrcb ycrcb\n buffersize = std::min(m->value->binary->image.size,\n\t\t\t static_cast(buffersize));\n memcpy(buffer, m->value->binary->image.data, buffersize);\n }\n if (format == IMAGE_PPM)\n {\n char p6h[20];\n sprintf(p6h, \"P6\\n%zu %zu\\n255\\n\", width, height);\n size_t p6len = strlen(p6h);\n size_t mlen = osize > buffersize + p6len ? buffersize : osize - p6len;\n memmove((void *) (((long) buffer) + p6len), buffer, mlen);\n memcpy(buffer, p6h, p6len);\n buffersize += p6len;\n }\n delete m;\n return 1;\n }\n\n int\n USyncClient::syncGetNormalizedDevice(const char* device, double& val,\n\t\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.valn\", device), val);\n }\n\n int\n USyncClient::syncGetValue(const char* valName, UValue& val,\n\t\t\t libport::utime_t useconds)\n {\n return syncGetValue(0, valName, val, useconds);\n }\n\n int\n USyncClient::syncGetValue(const char* tag, const char* valName, UValue& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGetTag(useconds, \"%s\", tag, 0, valName), val);\n }\n\n int\n USyncClient::syncGetDevice(const char* device, double& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.val\", device), val);\n }\n\n int\n USyncClient::syncGetResult(const char* command, double& val,\n\t\t\t libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s\", command), val);\n }\n\n\n int\n USyncClient::syncGetDevice(const char* device, const char* access,\n\t\t\t double& val, libport::utime_t useconds)\n {\n return getValue(syncGet(useconds, \"%s.%s\", device, access), val);\n }\n\n\n int\n USyncClient::syncGetSound(const char* device, int duration, USound& sound,\n\t\t\t libport::utime_t useconds)\n {\n send(\"syncgetsound = BIN 0;\\n\"\n\t \"loopsound: loop syncgetsound = syncgetsound + %s.val,\\n\"\n\t \" {\\n\"\n\t \" sleep(%d);\\n\"\n\t \" stop loopsound;\\n\"\n\t \" noop;\\n\"\n\t \" noop;\\n\"\n\t \" };\\n\", device, duration);\n UMessage* m = syncGet(useconds, \"%s\", \"syncgetsound;\");\n if (!m)\n return 0;\n if (m->type != MESSAGE_DATA\n\t|| m->value->type != DATA_BINARY\n\t|| m->value->binary->type != BINARY_SOUND)\n {\n delete m;\n return 0;\n }\n convert(m->value->binary->sound, sound);\n delete m;\n return 1;\n }\n\n int\n USyncClient::syncSend(const void* buffer, size_t length)\n {\n if (rc != 0)\n return -1;\n sendBufferLock.lock();\n size_t sent = 0;\n while (sent < length)\n {\n int res = ::write(sd, (char*) buffer + sent, length - sent);\n if (res < 0)\n {\n\trc = res;\n\tsendBufferLock.unlock();\n\treturn res;\n }\n sent += res;\n }\n sendBufferLock.unlock();\n return 0;\n }\n\n void\n USyncClient::waitForKernelVersion(bool hasProcessingThread)\n {\n \/\/ Do not call kernelMajor() which precisely requires kernelMajor_\n \/\/ to be defined.\n while (kernelMajor_ < 0 && !error())\n {\n if (!hasProcessingThread)\n processEvents();\n usleep(100000);\n }\n }\n\n void\n USyncClient::setDefaultOptions(const USyncClient::options& opt)\n {\n default_options_ = opt;\n }\n\n const USyncClient::options&\n USyncClient::getOptions(const USyncClient::options& opt) const\n {\n return (&opt == &USyncClient::options::default_options) ?\n default_options_ : opt;\n }\n\n} \/\/ namespace urbi\n<|endoftext|>"} {"text":"\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#include \"fusionHost.hpp\"\n#include \n\/\/#include \n\nusing ptr_FusionPlanDesc = MIOPEN_MANAGE_PTR(miopenFusionPlanDescriptor_t,\n miopenDestroyFusionPlanDescriptor);\nusing ptr_FusionPlanArgs = MIOPEN_MANAGE_PTR(miopenOperatorArgs_t, miopenDestroyOperatorArgs);\nusing ptr_ActivationDesc = MIOPEN_MANAGE_PTR(miopenActivationDescriptor_t,\n miopenDestroyActivationDescriptor);\n\nptr_FusionPlanDesc GetManagedFusionPlanDesc(miopenTensorDescriptor_t inputDesc)\n{\n miopenFusionPlanDescriptor_t fusePlanDesc;\n miopenCreateFusionPlan(&fusePlanDesc, miopenVerticalFusion, inputDesc);\n return ptr_FusionPlanDesc{fusePlanDesc};\n}\n\nptr_FusionPlanArgs GetManageFusionPlanArgs()\n{\n miopenOperatorArgs_t fusionArgs;\n miopenCreateOperatorArgs(&fusionArgs);\n return ptr_FusionPlanArgs{fusionArgs};\n}\n\nptr_ActivationDesc GetManagedActivDesc()\n{\n miopenActivationDescriptor_t activdesc;\n miopenCreateActivationDescriptor(&activdesc);\n return ptr_ActivationDesc{activdesc};\n}\ntemplate \nstruct verify_inference_batchnorm_activ\n{\n tensor input;\n miopenTensorDescriptor_t inputDesc{};\n miopenActivationDescriptor_t activDesc{};\n miopenTensorDescriptor_t biasScaleTensor{};\n tensor bnscale{};\n tensor bnbias{};\n tensor estMean{};\n tensor estVariance{};\n miopenBatchNormMode_t bnmode;\n miopenFusionPlanDescriptor_t fusionplan;\n miopenFusionOpDescriptor_t bNormOp;\n miopenFusionOpDescriptor_t activOp;\n\n double epsilon;\n\n verify_inference_batchnorm_activ(miopenFusionPlanDescriptor_t pfusionplan,\n tensor& pinput,\n miopenActivationDescriptor_t pactivDesc,\n tensor& pbnscale,\n tensor& pbnbias,\n tensor& pestMean,\n tensor& pestVariance,\n miopenBatchNormMode_t pbnmode,\n miopenFusionOpDescriptor_t pbNormOp,\n miopenFusionOpDescriptor_t pactivOp)\n {\n input = pinput;\n inputDesc = &pinput.desc;\n activDesc = pactivDesc;\n biasScaleTensor = &pbnscale.desc;\n bnscale = pbnscale;\n bnbias = pbnbias;\n estMean = pestMean;\n estVariance = pestVariance;\n bnmode = pbnmode;\n fusionplan = pfusionplan;\n bNormOp = pbNormOp;\n activOp = pactivOp;\n epsilon = 1.0e-5;\n }\n\n tensor cpu() const\n {\n auto bout = input;\n std::fill(bout.begin(), bout.end(), 0.);\n auto aout = input;\n std::fill(aout.begin(), aout.end(), 0.);\n\n double activ_alpha, activ_beta, activ_gamma;\n miopenActivationMode_t activ_mode;\n miopenGetActivationDescriptor(\n activDesc, &activ_mode, &activ_alpha, &activ_beta, &activ_gamma);\n \n if(bnmode == miopenBNPerActivation)\n {\n batchNormPerActivHostInference(\n input, bout, bnscale, bnbias, epsilon, estMean, estVariance);\n }\n else\n {\n batchNormSpatialHostInference(\n input, bout, bnscale, bnbias, epsilon, estMean, estVariance);\n }\n\n activationHostInfer(\n activ_mode, activ_gamma, activ_beta, activ_alpha, bout.data, aout.data);\n \n return aout;\n }\n\n tensor gpu() const\n {\n auto&& handle = get_handle();\n auto baout = input;\n std::fill(baout.begin(), baout.end(), 0.);\n auto in_dev = handle.Write(input.data);\n auto out_dev = handle.Write(baout.data);\n auto bnscale_dev = handle.Write(bnscale.data);\n auto bnbias_dev = handle.Write(bnbias.data);\n auto estMean_dev = handle.Write(estMean.data);\n auto estVariance_dev = handle.Write(estVariance.data);\n\n double activ_alpha, activ_beta, activ_gamma;\n miopenActivationMode_t activ_mode;\n miopenGetActivationDescriptor(\n activDesc, &activ_mode, &activ_alpha, &activ_beta, &activ_gamma);\n\n double alpha = 1., beta = 0.;\n auto ptr_fusionargs = GetManageFusionPlanArgs();\n miopenSetOpArgsBatchNormInference(ptr_fusionargs.get(),\n bNormOp,\n &alpha,\n &beta,\n bnscale_dev.get(),\n bnbias_dev.get(),\n estMean_dev.get(),\n estVariance_dev.get(),\n epsilon);\n miopenSetOpArgsActivForward(\n ptr_fusionargs.get(), activOp, &alpha, &beta, activ_alpha, activ_beta, activ_gamma);\n miopenExecuteFusionPlan(&handle,\n fusionplan,\n inputDesc,\n in_dev.get(),\n inputDesc,\n out_dev.get(),\n ptr_fusionargs.get());\n baout.data = handle.Read(out_dev, baout.data.size());\n return baout;\n }\n\n void fail(float = 0) const { std::cerr << \"BatchNorm+Activation Inference:\" << std::endl; }\n};\n\nstatic std::string transform_mode(std::string s)\n{\n return miopen::RemovePrefix(miopen::ToUpper(s), \"MIOPENACTIVATION\");\n}\n\ntemplate \nstruct na_fusion_driver : test_driver\n{\n tensor input;\n tensor scale;\n tensor shift;\n tensor estMean;\n tensor estVariance;\n ptr_ActivationDesc ptr_activdesc = nullptr;\n\n miopenActivationMode_t activ_mode = miopenActivationRELU;\n std::string amode;\n miopenBatchNormMode_t bnmode{};\n int batchnormMode = 0;\n\n unsigned long max_value = miopen_type{} == miopenHalf ? 5 : 17;\n double alpha = 0., beta = 0., gamma = 0.;\n\n na_fusion_driver()\n {\n add(input, \"input\", get_input_tensor());\n add(alpha, \"alpha\", generate_data({\/*1.,*\/ 0.5}));\n add(beta, \"beta\", generate_data({\/*0.,*\/ 0.5}));\n add(gamma, \"gamma\", generate_data({\/*1.,*\/ 0.5}));\n add(amode,\n \"amode\",\n generate_data(\n {\"MIOPENACTIVATIONRELU\", \"MIOPENACTIVATIONLOGISTIC\", \"MIOPENACTIVATIONABS\"}));\n add(batchnormMode, \"batch-norm-mode\", generate_data({0, 1}));\n }\n\n void run()\n {\n amode = transform_mode(amode);\n\n if(amode == \"PASSTHRU\")\n activ_mode = miopenActivationPASTHRU;\n else if(amode == \"LOGISTIC\")\n activ_mode = miopenActivationLOGISTIC;\n else if(amode == \"TANH\")\n activ_mode = miopenActivationTANH;\n else if(amode == \"RELU\")\n activ_mode = miopenActivationRELU;\n else if(amode == \"SOFTRELU\")\n activ_mode = miopenActivationSOFTRELU;\n else if(amode == \"ABS\")\n activ_mode = miopenActivationABS;\n else if(amode == \"POWER\")\n activ_mode = miopenActivationPOWER;\n else if(amode == \"CLIPPEDRELU\")\n activ_mode = miopenActivationCLIPPEDRELU;\n else if(amode == \"LEAKYRELU\")\n activ_mode = miopenActivationLEAKYRELU;\n else if(amode == \"ELU\")\n activ_mode = miopenActivationELU;\n\n int input_c, input_h, input_w;\n std::tie(std::ignore, input_c, input_h, input_w) = miopen::tien<4>(input.desc.GetLengths());\n ptr_activdesc = GetManagedActivDesc();\n miopenSetActivationDescriptor(ptr_activdesc.get(), activ_mode, alpha, beta, gamma);\n\n if(batchnormMode == 1)\n {\n bnmode = miopenBNSpatial;\n }\n else if(batchnormMode == 0)\n {\n bnmode = miopenBNPerActivation;\n }\n\n std::size_t ssn, ssc, ssh, ssw;\n auto derivedBnDesc = miopen::TensorDescriptor{};\n miopen::DeriveBNTensorDescriptor(derivedBnDesc, input.desc, bnmode);\n std::tie(ssn, ssc, ssh, ssw) = miopen::tien<4>(derivedBnDesc.GetLengths());\n\n if(input.desc.GetType() == miopenFloat)\n {\n scale = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n shift = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n estMean = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n estVariance = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n }\n else\n {\n scale = tensor{ssn, ssc, ssh, ssw};\n shift = tensor{ssn, ssc, ssh, ssw};\n estMean = tensor{ssn, ssc, ssh, ssw};\n estVariance = tensor{ssn, ssc, ssh, ssw};\n\n srand(0);\n for(int i = 0; i < scale.desc.GetElementSize(); i++)\n {\n scale[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n shift[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n estMean[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n estVariance[i] = std::fabs((((rand() % 2) == 1) ? -1 : 1) * 1e-2 * T(rand() % 100));\n }\n for(int i = 0; i < input.desc.GetElementSize(); i++)\n {\n input[i] = (((rand() % 2) == 1) ? -1 : 1) * T(rand() % 100);\n }\n }\n\n auto&& handle = get_handle();\n\n miopenFusionOpDescriptor_t bNormOp = nullptr;\n miopenFusionOpDescriptor_t activOp = nullptr;\n\n auto ptr_fusionplan = GetManagedFusionPlanDesc(&input.desc);\n\n miopenCreateOpBatchNormInference(ptr_fusionplan.get(), &bNormOp, bnmode, &scale.desc);\n miopenCreateOpActivationForward(ptr_fusionplan.get(), &activOp, activ_mode);\n\n miopenStatus_t miopenError = miopenCompileFusionPlan(&handle, ptr_fusionplan.get());\n if(miopenError != miopenStatusSuccess)\n {\n std::cerr << \"BatchNorm+Activation Inference plan not supported.\" << std::endl;\n }\n else\n {\n verify(verify_inference_batchnorm_activ{\n ptr_fusionplan.get(), input, ptr_activdesc.get(), \n scale, shift, estMean, estVariance, bnmode, bNormOp, activOp});\n }\n\n }\n};\n\nint main(int argc, const char* argv[]) { test_drive(argc, argv); }\nFormatting.\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#include \"fusionHost.hpp\"\n#include \n\/\/#include \n\nusing ptr_FusionPlanDesc = MIOPEN_MANAGE_PTR(miopenFusionPlanDescriptor_t,\n miopenDestroyFusionPlanDescriptor);\nusing ptr_FusionPlanArgs = MIOPEN_MANAGE_PTR(miopenOperatorArgs_t, miopenDestroyOperatorArgs);\nusing ptr_ActivationDesc = MIOPEN_MANAGE_PTR(miopenActivationDescriptor_t,\n miopenDestroyActivationDescriptor);\n\nptr_FusionPlanDesc GetManagedFusionPlanDesc(miopenTensorDescriptor_t inputDesc)\n{\n miopenFusionPlanDescriptor_t fusePlanDesc;\n miopenCreateFusionPlan(&fusePlanDesc, miopenVerticalFusion, inputDesc);\n return ptr_FusionPlanDesc{fusePlanDesc};\n}\n\nptr_FusionPlanArgs GetManageFusionPlanArgs()\n{\n miopenOperatorArgs_t fusionArgs;\n miopenCreateOperatorArgs(&fusionArgs);\n return ptr_FusionPlanArgs{fusionArgs};\n}\n\nptr_ActivationDesc GetManagedActivDesc()\n{\n miopenActivationDescriptor_t activdesc;\n miopenCreateActivationDescriptor(&activdesc);\n return ptr_ActivationDesc{activdesc};\n}\ntemplate \nstruct verify_inference_batchnorm_activ\n{\n tensor input;\n miopenTensorDescriptor_t inputDesc{};\n miopenActivationDescriptor_t activDesc{};\n miopenTensorDescriptor_t biasScaleTensor{};\n tensor bnscale{};\n tensor bnbias{};\n tensor estMean{};\n tensor estVariance{};\n miopenBatchNormMode_t bnmode;\n miopenFusionPlanDescriptor_t fusionplan;\n miopenFusionOpDescriptor_t bNormOp;\n miopenFusionOpDescriptor_t activOp;\n\n double epsilon;\n\n verify_inference_batchnorm_activ(miopenFusionPlanDescriptor_t pfusionplan,\n tensor& pinput,\n miopenActivationDescriptor_t pactivDesc,\n tensor& pbnscale,\n tensor& pbnbias,\n tensor& pestMean,\n tensor& pestVariance,\n miopenBatchNormMode_t pbnmode,\n miopenFusionOpDescriptor_t pbNormOp,\n miopenFusionOpDescriptor_t pactivOp)\n {\n input = pinput;\n inputDesc = &pinput.desc;\n activDesc = pactivDesc;\n biasScaleTensor = &pbnscale.desc;\n bnscale = pbnscale;\n bnbias = pbnbias;\n estMean = pestMean;\n estVariance = pestVariance;\n bnmode = pbnmode;\n fusionplan = pfusionplan;\n bNormOp = pbNormOp;\n activOp = pactivOp;\n epsilon = 1.0e-5;\n }\n\n tensor cpu() const\n {\n auto bout = input;\n std::fill(bout.begin(), bout.end(), 0.);\n auto aout = input;\n std::fill(aout.begin(), aout.end(), 0.);\n\n double activ_alpha, activ_beta, activ_gamma;\n miopenActivationMode_t activ_mode;\n miopenGetActivationDescriptor(\n activDesc, &activ_mode, &activ_alpha, &activ_beta, &activ_gamma);\n\n if(bnmode == miopenBNPerActivation)\n {\n batchNormPerActivHostInference(\n input, bout, bnscale, bnbias, epsilon, estMean, estVariance);\n }\n else\n {\n batchNormSpatialHostInference(\n input, bout, bnscale, bnbias, epsilon, estMean, estVariance);\n }\n\n activationHostInfer(activ_mode, activ_gamma, activ_beta, activ_alpha, bout.data, aout.data);\n\n return aout;\n }\n\n tensor gpu() const\n {\n auto&& handle = get_handle();\n auto baout = input;\n std::fill(baout.begin(), baout.end(), 0.);\n auto in_dev = handle.Write(input.data);\n auto out_dev = handle.Write(baout.data);\n auto bnscale_dev = handle.Write(bnscale.data);\n auto bnbias_dev = handle.Write(bnbias.data);\n auto estMean_dev = handle.Write(estMean.data);\n auto estVariance_dev = handle.Write(estVariance.data);\n\n double activ_alpha, activ_beta, activ_gamma;\n miopenActivationMode_t activ_mode;\n miopenGetActivationDescriptor(\n activDesc, &activ_mode, &activ_alpha, &activ_beta, &activ_gamma);\n\n double alpha = 1., beta = 0.;\n auto ptr_fusionargs = GetManageFusionPlanArgs();\n miopenSetOpArgsBatchNormInference(ptr_fusionargs.get(),\n bNormOp,\n &alpha,\n &beta,\n bnscale_dev.get(),\n bnbias_dev.get(),\n estMean_dev.get(),\n estVariance_dev.get(),\n epsilon);\n miopenSetOpArgsActivForward(\n ptr_fusionargs.get(), activOp, &alpha, &beta, activ_alpha, activ_beta, activ_gamma);\n miopenExecuteFusionPlan(&handle,\n fusionplan,\n inputDesc,\n in_dev.get(),\n inputDesc,\n out_dev.get(),\n ptr_fusionargs.get());\n baout.data = handle.Read(out_dev, baout.data.size());\n return baout;\n }\n\n void fail(float = 0) const { std::cerr << \"BatchNorm+Activation Inference:\" << std::endl; }\n};\n\nstatic std::string transform_mode(std::string s)\n{\n return miopen::RemovePrefix(miopen::ToUpper(s), \"MIOPENACTIVATION\");\n}\n\ntemplate \nstruct na_fusion_driver : test_driver\n{\n tensor input;\n tensor scale;\n tensor shift;\n tensor estMean;\n tensor estVariance;\n ptr_ActivationDesc ptr_activdesc = nullptr;\n\n miopenActivationMode_t activ_mode = miopenActivationRELU;\n std::string amode;\n miopenBatchNormMode_t bnmode{};\n int batchnormMode = 0;\n\n unsigned long max_value = miopen_type{} == miopenHalf ? 5 : 17;\n double alpha = 0., beta = 0., gamma = 0.;\n\n na_fusion_driver()\n {\n add(input, \"input\", get_input_tensor());\n add(alpha, \"alpha\", generate_data({\/*1.,*\/ 0.5}));\n add(beta, \"beta\", generate_data({\/*0.,*\/ 0.5}));\n add(gamma, \"gamma\", generate_data({\/*1.,*\/ 0.5}));\n add(amode,\n \"amode\",\n generate_data(\n {\"MIOPENACTIVATIONRELU\", \"MIOPENACTIVATIONLOGISTIC\", \"MIOPENACTIVATIONABS\"}));\n add(batchnormMode, \"batch-norm-mode\", generate_data({0, 1}));\n }\n\n void run()\n {\n amode = transform_mode(amode);\n\n if(amode == \"PASSTHRU\")\n activ_mode = miopenActivationPASTHRU;\n else if(amode == \"LOGISTIC\")\n activ_mode = miopenActivationLOGISTIC;\n else if(amode == \"TANH\")\n activ_mode = miopenActivationTANH;\n else if(amode == \"RELU\")\n activ_mode = miopenActivationRELU;\n else if(amode == \"SOFTRELU\")\n activ_mode = miopenActivationSOFTRELU;\n else if(amode == \"ABS\")\n activ_mode = miopenActivationABS;\n else if(amode == \"POWER\")\n activ_mode = miopenActivationPOWER;\n else if(amode == \"CLIPPEDRELU\")\n activ_mode = miopenActivationCLIPPEDRELU;\n else if(amode == \"LEAKYRELU\")\n activ_mode = miopenActivationLEAKYRELU;\n else if(amode == \"ELU\")\n activ_mode = miopenActivationELU;\n\n int input_c, input_h, input_w;\n std::tie(std::ignore, input_c, input_h, input_w) = miopen::tien<4>(input.desc.GetLengths());\n ptr_activdesc = GetManagedActivDesc();\n miopenSetActivationDescriptor(ptr_activdesc.get(), activ_mode, alpha, beta, gamma);\n\n if(batchnormMode == 1)\n {\n bnmode = miopenBNSpatial;\n }\n else if(batchnormMode == 0)\n {\n bnmode = miopenBNPerActivation;\n }\n\n std::size_t ssn, ssc, ssh, ssw;\n auto derivedBnDesc = miopen::TensorDescriptor{};\n miopen::DeriveBNTensorDescriptor(derivedBnDesc, input.desc, bnmode);\n std::tie(ssn, ssc, ssh, ssw) = miopen::tien<4>(derivedBnDesc.GetLengths());\n\n if(input.desc.GetType() == miopenFloat)\n {\n scale = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n shift = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n estMean = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n estVariance = tensor{ssn, ssc, ssh, ssw}.generate(rand_gen{});\n }\n else\n {\n scale = tensor{ssn, ssc, ssh, ssw};\n shift = tensor{ssn, ssc, ssh, ssw};\n estMean = tensor{ssn, ssc, ssh, ssw};\n estVariance = tensor{ssn, ssc, ssh, ssw};\n\n srand(0);\n for(int i = 0; i < scale.desc.GetElementSize(); i++)\n {\n scale[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n shift[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n estMean[i] = (((rand() % 2) == 1) ? -1 : 1) * 1e-4 * T(rand() % 100);\n estVariance[i] = std::fabs((((rand() % 2) == 1) ? -1 : 1) * 1e-2 * T(rand() % 100));\n }\n for(int i = 0; i < input.desc.GetElementSize(); i++)\n {\n input[i] = (((rand() % 2) == 1) ? -1 : 1) * T(rand() % 100);\n }\n }\n\n auto&& handle = get_handle();\n\n miopenFusionOpDescriptor_t bNormOp = nullptr;\n miopenFusionOpDescriptor_t activOp = nullptr;\n\n auto ptr_fusionplan = GetManagedFusionPlanDesc(&input.desc);\n\n miopenCreateOpBatchNormInference(ptr_fusionplan.get(), &bNormOp, bnmode, &scale.desc);\n miopenCreateOpActivationForward(ptr_fusionplan.get(), &activOp, activ_mode);\n\n miopenStatus_t miopenError = miopenCompileFusionPlan(&handle, ptr_fusionplan.get());\n if(miopenError != miopenStatusSuccess)\n {\n std::cerr << \"BatchNorm+Activation Inference plan not supported.\" << std::endl;\n }\n else\n {\n verify(verify_inference_batchnorm_activ{ptr_fusionplan.get(),\n input,\n ptr_activdesc.get(),\n scale,\n shift,\n estMean,\n estVariance,\n bnmode,\n bNormOp,\n activOp});\n }\n }\n};\n\nint main(int argc, const char* argv[]) { test_drive(argc, argv); }\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: datasourcehandling.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-06-02 08:04:05 $\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 EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n#define EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef EXTENSIONS_ABP_ABPTYPES_HXX\n#include \"abptypes.hxx\"\n#endif\n\n\/\/========================================================================\nnamespace com { namespace sun { namespace star {\n namespace lang {\n class XMultiServiceFactory;\n }\n namespace beans {\n class XPropertySet;\n }\n} } }\n\nclass Window;\n\n\n\/\/.........................................................................\nnamespace abp\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= ODataSourceContext\n \/\/=====================================================================\n struct ODataSourceContextImpl;\n class ODataSource;\n \/\/\/ a non-UNO wrapper for the data source context\n class ODataSourceContext\n {\n private:\n ODataSourceContextImpl* m_pImpl;\n\n public:\n ODataSourceContext(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n );\n\n \/\/\/ retrieves the names of all data sources\n void getDataSourceNames( StringBag& _rNames ) const SAL_THROW (( ));\n\n \/\/\/ disambiguates the given name by appending auccessive numbers\n ::rtl::OUString& disambiguate(::rtl::OUString& _rDataSourceName);\n\n \/\/\/ creates a new MORK data source\n ODataSource createNewMORK( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Evolution data source\n ODataSource createNewEvolution( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new LDAP data source\n ODataSource createNewLDAP( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Outlook data source\n ODataSource createNewOutlook( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Outlook express data source\n ODataSource createNewOE( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new dBase data source\n ODataSource createNewDBase( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n };\n\n \/\/=====================================================================\n \/\/= ODataSource\n \/\/=====================================================================\n struct ODataSourceImpl;\n struct PackageAccessControl;\n \/** a non-UNO wrapper for a data source\n

      This class allows to access data sources without the need to compile the respective file with\n exception handling enabled (hopefully :).<\/p>\n

      In addition to wrapping an UNO data source, an instance of this class can handle at most\n one valid connection, as obtained from the data source.<\/p>\n *\/\n class ODataSource\n {\n private:\n ODataSourceImpl* m_pImpl;\n\n public:\n \/\/ ----------------------------------------------------------------\n \/\/ - ctor\/dtor\/assignment\n \/\/ ----------------------------------------------------------------\n \/** ctor\n @param _rxORB\n the service factory to use to access the UNO objects\n @param _rName\n the name of the data source the object should represent\n *\/\n ODataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,\n const ::rtl::OUString& _rName\n );\n\n \/\/\/ constructs an object which is initially invalid\n ODataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n );\n\n \/\/\/ copy ctor\n ODataSource( const ODataSource& _rSource );\n\n \/\/\/ dtor\n ~ODataSource( );\n\n \/\/\/ assignment\n ODataSource& operator=( const ODataSource& _rSource );\n\n \/\/ ----------------------------------------------------------------\n \/\/\/ checks whether or not the object represents a valid data source\n sal_Bool isValid() const SAL_THROW (( ));\n\n \/\/ ----------------------------------------------------------------\n \/\/\/ removes the data source represented by the object from the data source context\n void remove() SAL_THROW (( ));\n \/\/ TODO: put this into the context class\n\n \/\/\/ returns the name of the data source\n ::rtl::OUString\n getName() const SAL_THROW (( ));\n\n \/\/\/ renames the data source\n sal_Bool rename( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n \/\/ TODO: put this into the context class\n\n \/\/ ----------------------------------------------------------------\n \/\/ - connection handling\n \/\/ ----------------------------------------------------------------\n \/** connects to the data source represented by this object\n @param _pMessageParent\n the window to use as parent for any error messages. If this is , no messages are displayed\n at all.\n @see isConnected\n *\/\n sal_Bool connect( Window* _pMessageParent ) SAL_THROW (( ));\n\n \/\/\/ returns if the object has a valid connection, obtained from it's data source\n sal_Bool isConnected( ) const SAL_THROW (( ));\n\n \/\/\/ disconnects from the data source (i.e. disposes the UNO connection hold internally)\n void disconnect( ) SAL_THROW (( ));\n\n \/\/ ----------------------------------------------------------------\n \/** retrieves the tables names from the connection\n

      to be called when isConnection<\/method> returns only<\/p>\n *\/\n const StringBag& getTableNames() const SAL_THROW (( ));\n\n \/\/ ----------------------------------------------------------------\n \/** set a new data source.\n

      Available to selected clients only<\/p>\n *\/\n void setDataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDS,\n PackageAccessControl\n );\n\n protected:\n \/\/\/ a unsafe version of getName()\n ::rtl::OUString\n implGetName() const SAL_THROW (( ::com::sun::star::uno::Exception ));\n\n private:\n ODataSource( ); \/\/ never implemented\n };\n\n\/\/.........................................................................\n} \/\/ namespace abp\n\/\/.........................................................................\n\n#endif \/\/ EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n\nINTEGRATION: CWS insight01 (1.3.148); FILE MERGED 2004\/04\/16 12:07:04 oj 1.3.148.2: correct alignment and default 2004\/03\/05 07:38:43 oj 1.3.148.1: #111090# changes for the new prop dialogs\/*************************************************************************\n *\n * $RCSfile: datasourcehandling.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 17:36:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER 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 EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n#define EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef EXTENSIONS_ABP_ABPTYPES_HXX\n#include \"abptypes.hxx\"\n#endif\n\n\/\/========================================================================\nnamespace com { namespace sun { namespace star {\n namespace lang {\n class XMultiServiceFactory;\n }\n namespace beans {\n class XPropertySet;\n }\n} } }\n\nclass Window;\n\n\n\/\/.........................................................................\nnamespace abp\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= ODataSourceContext\n \/\/=====================================================================\n struct ODataSourceContextImpl;\n class ODataSource;\n \/\/\/ a non-UNO wrapper for the data source context\n class ODataSourceContext\n {\n private:\n ODataSourceContextImpl* m_pImpl;\n\n public:\n ODataSourceContext(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n );\n\n \/\/\/ retrieves the names of all data sources\n void getDataSourceNames( StringBag& _rNames ) const SAL_THROW (( ));\n\n \/\/\/ disambiguates the given name by appending auccessive numbers\n ::rtl::OUString& disambiguate(::rtl::OUString& _rDataSourceName);\n\n \/\/\/ creates a new MORK data source\n ODataSource createNewMORK( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Evolution data source\n ODataSource createNewEvolution( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new LDAP data source\n ODataSource createNewLDAP( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Outlook data source\n ODataSource createNewOutlook( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new Outlook express data source\n ODataSource createNewOE( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n\n \/\/\/ creates a new dBase data source\n ODataSource createNewDBase( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n };\n\n \/\/=====================================================================\n \/\/= ODataSource\n \/\/=====================================================================\n struct ODataSourceImpl;\n struct PackageAccessControl;\n \/** a non-UNO wrapper for a data source\n

      This class allows to access data sources without the need to compile the respective file with\n exception handling enabled (hopefully :).<\/p>\n

      In addition to wrapping an UNO data source, an instance of this class can handle at most\n one valid connection, as obtained from the data source.<\/p>\n *\/\n class ODataSource\n {\n private:\n ODataSourceImpl* m_pImpl;\n\n public:\n \/\/ ----------------------------------------------------------------\n \/\/ - ctor\/dtor\/assignment\n \/\/ ----------------------------------------------------------------\n \/** ctor\n @param _rxORB\n the service factory to use to access the UNO objects\n @param _rName\n the name of the data source the object should represent\n *\/\n ODataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB,\n const ::rtl::OUString& _rName\n );\n\n \/\/\/ constructs an object which is initially invalid\n ODataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n );\n\n \/\/\/ copy ctor\n ODataSource( const ODataSource& _rSource );\n\n \/\/\/ dtor\n ~ODataSource( );\n\n \/\/\/ assignment\n ODataSource& operator=( const ODataSource& _rSource );\n\n \/\/ ----------------------------------------------------------------\n \/\/\/ checks whether or not the object represents a valid data source\n sal_Bool isValid() const SAL_THROW (( ));\n\n \/\/ ----------------------------------------------------------------\n \/\/\/ removes the data source represented by the object from the data source context\n void remove() SAL_THROW (( ));\n \/\/ TODO: put this into the context class\n\n \/\/\/ returns the name of the data source\n ::rtl::OUString\n getName() const SAL_THROW (( ));\n\n \/\/\/ renames the data source\n sal_Bool rename( const ::rtl::OUString& _rName ) SAL_THROW (( ));\n \/\/ TODO: put this into the context class\n\n \/\/ ----------------------------------------------------------------\n \/\/ - connection handling\n \/\/ ----------------------------------------------------------------\n \/** connects to the data source represented by this object\n @param _pMessageParent\n the window to use as parent for any error messages. If this is , no messages are displayed\n at all.\n @see isConnected\n *\/\n sal_Bool connect( Window* _pMessageParent ) SAL_THROW (( ));\n\n \/\/\/ returns if the object has a valid connection, obtained from it's data source\n sal_Bool isConnected( ) const SAL_THROW (( ));\n\n \/\/\/ disconnects from the data source (i.e. disposes the UNO connection hold internally)\n void disconnect( ) SAL_THROW (( ));\n\n \/\/\/ stores the database file\n void store() SAL_THROW (( ));\n\n \/\/\/ register the data source under the given name in the configuration\n void registerDataSource( const ::rtl::OUString& _sRegisteredDataSourceName ) SAL_THROW (( ));\n\n \/\/ ----------------------------------------------------------------\n \/** retrieves the tables names from the connection\n

      to be called when isConnection<\/method> returns only<\/p>\n *\/\n const StringBag& getTableNames() const SAL_THROW (( ));\n\n \/\/\/ return the intern data source object\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getDataSource() const SAL_THROW (( ));\n\n\n \/\/ ----------------------------------------------------------------\n \/** set a new data source.\n

      Available to selected clients only<\/p>\n *\/\n void setDataSource(\n const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDS\n ,const ::rtl::OUString& _sName\n ,PackageAccessControl\n );\n\n private:\n ODataSource( ); \/\/ never implemented\n };\n\n\/\/.........................................................................\n} \/\/ namespace abp\n\/\/.........................................................................\n\n#endif \/\/ EXTENSIONS_ABP_DATASOURCEHANDLING_HXX\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \"caf\/dictionary.hpp\"\n#include \"caf\/fwd.hpp\"\n#include \"caf\/timestamp.hpp\"\n\nnamespace caf {\nnamespace detail {\n\ntemplate \nstruct type_name_builder_int_size;\n\ntemplate <>\nstruct type_name_builder_int_size<1> {\n inline void operator()(std::string& result) const {\n result += \"8\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<2> {\n inline void operator()(std::string& result) const {\n result += \"16\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<4> {\n inline void operator()(std::string& result) const {\n result += \"32\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<8> {\n inline void operator()(std::string& result) const {\n result += \"64\";\n }\n};\n\ntemplate ::value>\nstruct type_name_builder;\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"boolean\";\n }\n};\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"32-bit real\";\n }\n};\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"64-bit real\";\n }\n};\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"timespan\";\n }\n};\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"string\";\n }\n};\n\ntemplate <>\nstruct type_name_builder {\n inline void operator()(std::string& result) const {\n result += \"atom\";\n }\n};\n\ntemplate \nstruct type_name_builder {\n void operator()(std::string& result) const {\n \/\/ TODO: replace with if constexpr when switching to C++17\n if (!std::is_signed::value)\n result += 'u';\n result += \"int\";\n type_name_builder_int_size g;\n g(result);\n }\n};\n\ntemplate \nstruct type_name_builder, false> {\n void operator()(std::string& result) const {\n result += \"list of \";\n type_name_builder g;\n g(result);\n }\n};\n\ntemplate \nstruct type_name_builder, false> {\n void operator()(std::string& result) const {\n result += \"dictionary of \";\n type_name_builder g;\n g(result);\n }\n};\n\ntemplate \nstd::string type_name() {\n std::string result;\n type_name_builder f;\n f(result);\n return result;\n}\n\n} \/\/ namespace detail\n} \/\/ namespace caf\n\nAdd missing type to type name builder\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \"caf\/dictionary.hpp\"\n#include \"caf\/fwd.hpp\"\n#include \"caf\/timestamp.hpp\"\n\nnamespace caf {\nnamespace detail {\n\ntemplate \nstruct type_name_builder_int_size;\n\ntemplate <>\nstruct type_name_builder_int_size<1> {\n void operator()(std::string& result) const {\n result += \"8\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<2> {\n void operator()(std::string& result) const {\n result += \"16\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<4> {\n void operator()(std::string& result) const {\n result += \"32\";\n }\n};\n\ntemplate <>\nstruct type_name_builder_int_size<8> {\n void operator()(std::string& result) const {\n result += \"64\";\n }\n};\n\ntemplate ::value>\nstruct type_name_builder;\n\ntemplate <>\nstruct type_name_builder {\n void operator()(std::string& result) const {\n result += \"boolean\";\n }\n};\n\n#define CAF_TYPE_NAME_BUILDER_NOINT(class_name, pretty_name) \\\n template <> \\\n struct type_name_builder { \\\n void operator()(std::string& result) const { \\\n result += pretty_name; \\\n } \\\n }\n\nCAF_TYPE_NAME_BUILDER_NOINT(float, \"32-bit real\");\n\nCAF_TYPE_NAME_BUILDER_NOINT(double, \"64-bit real\");\n\nCAF_TYPE_NAME_BUILDER_NOINT(timespan, \"timespan\");\n\nCAF_TYPE_NAME_BUILDER_NOINT(std::string, \"string\");\n\nCAF_TYPE_NAME_BUILDER_NOINT(atom_value, \"atom\");\n\nCAF_TYPE_NAME_BUILDER_NOINT(uri, \"uri\");\n\n#undef CAF_TYPE_NAME_BUILDER\n\ntemplate \nstruct type_name_builder {\n void operator()(std::string& result) const {\n \/\/ TODO: replace with if constexpr when switching to C++17\n if (!std::is_signed::value)\n result += 'u';\n result += \"int\";\n type_name_builder_int_size g;\n g(result);\n }\n};\n\ntemplate \nstruct type_name_builder, false> {\n void operator()(std::string& result) const {\n result += \"list of \";\n type_name_builder g;\n g(result);\n }\n};\n\ntemplate \nstruct type_name_builder, false> {\n void operator()(std::string& result) const {\n result += \"dictionary of \";\n type_name_builder g;\n g(result);\n }\n};\n\ntemplate \nstd::string type_name() {\n std::string result;\n type_name_builder f;\n f(result);\n return result;\n}\n\n} \/\/ namespace detail\n} \/\/ namespace caf\n<|endoftext|>"} {"text":"#ifndef MANIFOLDS_FUNCTIONS_INTEGRAL_POLYNOMIAL_SIMPLIFICATIONS_HH\n#define MANIFOLDS_FUNCTIONS_INTEGRAL_POLYNOMIAL_SIMPLIFICATIONS_HH\n\n#include \"integral_polynomial.hh\"\n#include \"polynomial.hh\"\n#include \"addition.hh\"\n#include \"simplify.hh\"\n#include \"unary_minus.hh\"\n#include \"zero.hh\"\n\nnamespace manifolds {\ntemplate \nstruct Simplification<\n Addition, IntegralPolynomial >,\n \/*add_ip_ip*\/ 0> {\n template struct Extended;\n\n template \n struct Extended,\n std::integer_sequence > {\n typedef std::integer_sequence\n type;\n };\n\n static const int padding1 =\n sizeof...(t1s) < sizeof...(t2s) ? sizeof...(t2s) - sizeof...(t1s) : 0;\n typedef typename Extended<\n std::integer_sequence,\n std::make_integer_sequence >::type padded1;\n\n static const int padding2 =\n sizeof...(t2s) < sizeof...(t1s) ? sizeof...(t1s) - sizeof...(t2s) : 0;\n typedef typename Extended<\n std::integer_sequence,\n std::make_integer_sequence >::type padded2;\n\n template struct Add;\n\n template \n struct Add,\n std::integer_sequence > {\n typedef IntegralPolynomial<(indices1 + indices2)...> type;\n };\n\n typedef typename Add::type type;\n\n static type\n Combine(Addition, IntegralPolynomial >) {\n SIMPLIFY_INFO(\"Simplifying addition of \"\n \"integral_polynomials\\n\");\n return type{};\n }\n};\n\ntemplate \nstruct Simplification<\n Multiplication, IntegralPolynomial >,\n \/*mult_ip_ip*\/ 0> {\n typedef IPInt_t Tr;\n\n typedef std::integer_sequence inputs1;\n typedef std::integer_sequence inputs2;\n\n template struct get_value;\n\n template \n struct get_value<\n i, std::integer_sequence<\n IPInt_t, ts...> > : nth...>::type {};\n\n template struct set_value;\n\n template \n struct set_value > {\n typedef std::integer_sequence values;\n template struct apply;\n\n template \n struct apply,\n std::integer_sequence > {\n typedef std::integer_sequence::value..., t,\n get_value::value...>\n type;\n };\n\n typedef typename apply<\n std::make_integer_sequence,\n std::make_integer_sequence >::type type;\n };\n\n template ::value)>\n struct Add {\n typedef typename set_value::value +\n (Tr)get_value::value *(\n Tr)get_value::value,\n OutSeq>::type type;\n };\n\n template \n struct Add, false> {\n static_assert(i + j == sizeof...(ts), \"Internal error\");\n typedef std::integer_sequence::value *(\n Tr)get_value::value>\n type;\n };\n\n template struct P2Loop {\n typedef typename P2Loop::type>::type\n type;\n };\n\n template struct P2Loop {\n typedef OutSeq type;\n };\n\n template struct P1Loop {\n typedef typename P1Loop<\n i - 1, typename P2Loop::type>::type type;\n };\n\n template \n struct P1Loop<-1, std::integer_sequence > {\n typedef IntegralPolynomial type;\n };\n\n template struct InitOutput;\n\n template struct InitOutput > {\n typedef std::integer_sequence type;\n };\n\n typedef typename P1Loop<\n sizeof...(t1s) - 1,\n typename InitOutput<\n miseq >::type>::type type;\n\n static type Combine(\n Multiplication, IntegralPolynomial >) {\n SIMPLIFY_INFO(\"Simplifying multiplication of \"\n \"integral_polynomials\\n\");\n return type{};\n }\n};\n\ntemplate \nstruct Simplification,\n \/*ip*\/ 0> {\n template using ic = std::integral_constant;\n\n template struct pop {\n template struct apply;\n\n template \n struct apply > {\n typedef std::integer_sequence...>::type::value...> type;\n };\n\n typedef typename apply >::type\n type;\n };\n\n template struct pop_if;\n\n template struct stopping_condition;\n\n template \n struct stopping_condition > {\n static const bool value =\n sizeof...(ts) == 1 || last...>::type::value != 0;\n };\n\n template \n struct pop_if, true> {\n typedef IntegralPolynomial type;\n };\n\n template \n struct pop_if, false> {\n typedef typename pop::type next;\n typedef typename pop_if::value>::type type;\n };\n\n typedef typename pop_if<\n std::integer_sequence,\n stopping_condition >::value>::type\n type;\n\n static type Combine(IntegralPolynomial) {\n SIMPLIFY_INFO(\"Simplifying of integral_polynomial\\n\");\n return type{};\n }\n};\n\ntemplate