text
stringlengths
54
60.6k
<commit_before>7936b88a-2d53-11e5-baeb-247703a38240<commit_msg>793737ba-2d53-11e5-baeb-247703a38240<commit_after>793737ba-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>7f6cf567-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf568-2d15-11e5-af21-0401358ea401<commit_after>7f6cf568-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <iostream> #include <sched.h> #include <stdlib.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <sys/utsname.h> #include <string> #include <cstring> #include <vector> #include <algorithm> #include "container.h" int run(void* arg) { const std::string name = "funny-name"; char **argv = (char**) arg; Container::Builder builder; builder.set_hostname(name); Container container = builder.build(); const std::vector<std::string> args(1); try { container.run_command((const std::string) argv[1], args); } catch (std::exception const &exc) { std::cerr << "Exception caught " << exc.what() << "\n"; } struct utsname uts; std::cout << "This is child" << std::endl; uname(&uts); std::cout << "This is a child's nodename: " << uts.nodename << std::endl; } int main(int argc, char *argv[]) { struct utsname uts; char *stack = (char*) malloc(1024*1024); std::cout << "This is parent" << std::endl; pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv); if (pid == -1) { std::cout << "Creating new namespace failed. Error number: " << errno; } sleep(1); uname(&uts); std::cout << "This is a parent's nodename: " << uts.nodename << std::endl; waitpid(pid, NULL, 0); } <commit_msg>Removing unneded stuff<commit_after>#include <iostream> #include <sched.h> #include <stdlib.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <sys/utsname.h> #include <string> #include <cstring> #include <vector> #include "container.h" Container build_container() { const std::string name = "funny-name"; Container::Builder builder; builder.set_hostname(name); return builder.build(); } int run(void* arg) { char **argv = (char**) arg; const std::vector<std::string> args(1); Container container = build_container(); try { container.run_command((const std::string) argv[1], args); } catch (const std::exception& exc) { std::cerr << "Exception caught " << exc.what() << "\n"; exit(1); } } int main(int argc, char *argv[]) { struct utsname uts; char *stack = (char*) malloc(1024*1024); pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv); if (pid == -1) { std::cerr << "Creating new namespace failed. Error number: " << errno; exit(1); } sleep(1); uname(&uts); std::cout << "This is a parent's nodename: " << uts.nodename << std::endl; waitpid(pid, NULL, 0); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "gettingstartedwelcomepagewidget.h" #include "ui_gettingstartedwelcomepagewidget.h" #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <extensionsystem/pluginmanager.h> #include <help/helpplugin.h> #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtCore/QXmlStreamReader> #include <QtGui/QFont> namespace Qt4ProjectManager { namespace Internal { GettingStartedWelcomePageWidget::GettingStartedWelcomePageWidget(QWidget *parent) : QWidget(parent), ui(new Ui::GettingStartedWelcomePageWidget) { ui->setupUi(this); ui->tutorialsTitleLabel->setStyledText(tr("Tutorials")); ui->demoTitleLabel->setStyledText(tr("Explore Qt Examples")); ui->didYouKnowTextBrowser->viewport()->setAutoFillBackground(false); ui->didYouKnowTitleLabel->setStyledText(tr("Did You Know?")); connect(ui->tutorialTreeWidget, SIGNAL(activated(QString)), SLOT(slotOpenHelpPage(const QString&))); connect(ui->openExampleButton, SIGNAL(clicked()), SLOT(slotOpenExample())); connect(ui->examplesComboBox, SIGNAL(currentIndexChanged(int)), SLOT(slotEnableExampleButton(int))); ui->tutorialTreeWidget->addItem(tr("<b>Qt Creator - A quick tour</b>"), QString("qthelp://com.nokia.qtcreator.%1%2/doc/index.html").arg(IDE_VERSION_MAJOR).arg(IDE_VERSION_MINOR)); ui->tutorialTreeWidget->addItem(tr("Creating an address book"), QLatin1String("qthelp://com.nokia.qtcreator/doc/tutorials-addressbook-sdk.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Understanding widgets"), QLatin1String("qthelp://com.trolltech.qt/qdoc/widgets-tutorial.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Building with qmake"), QLatin1String("qthelp://com.trolltech.qmake/qdoc/qmake-tutorial.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Writing test cases"), QLatin1String("qthelp://com.trolltech.qt/qdoc/qtestlib-tutorial.html?view=split")); srand(QDateTime::currentDateTime().toTime_t()); QStringList tips = tipsOfTheDay(); m_currentTip = rand()%tips.count(); QTextDocument *doc = ui->didYouKnowTextBrowser->document(); doc->setDefaultStyleSheet("a:link {color:black;}"); ui->didYouKnowTextBrowser->setDocument(doc); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); connect(ui->nextTipBtn, SIGNAL(clicked()), this, SLOT(slotNextTip())); connect(ui->prevTipBtn, SIGNAL(clicked()), this, SLOT(slotPrevTip())); } GettingStartedWelcomePageWidget::~GettingStartedWelcomePageWidget() { delete ui; } void GettingStartedWelcomePageWidget::updateExamples(const QString& examplePath, const QString& demosPath, const QString &sourcePath) { QString demoxml = demosPath + "/qtdemo/xml/examples.xml"; if (!QFile::exists(demoxml)) { demoxml = sourcePath + "/demos/qtdemo/xml/examples.xml"; if (!QFile::exists(demoxml)) return; } QFile description(demoxml); if (!description.open(QFile::ReadOnly)) return; ui->examplesComboBox->clear(); ui->examplesComboBox->setEnabled(true); ui->examplesComboBox->addItem(tr("Choose an example...")); QFont f = font(); f.setItalic(true); ui->examplesComboBox->setItemData(0, f, Qt::FontRole); f.setItalic(false); bool inExamples = false; QString dirName; QXmlStreamReader reader(&description); while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::StartElement: if (reader.name() == "category") { QString name = reader.attributes().value(QLatin1String("name")).toString(); if (name.contains("tutorial")) break; dirName = reader.attributes().value(QLatin1String("dirname")).toString(); ui->examplesComboBox->addItem(name); f.setBold(true); ui->examplesComboBox->setItemData(ui->examplesComboBox->count()-1, f, Qt::FontRole); f.setBold(false); inExamples = true; } if (inExamples && reader.name() == "example") { QString name = reader.attributes().value(QLatin1String("name")).toString(); QString fn = reader.attributes().value(QLatin1String("filename")).toString(); QString relativeProPath = '/' + dirName + '/' + fn + '/' + fn + ".pro"; QString fileName = examplePath + relativeProPath; if (!QFile::exists(fileName)) fileName = sourcePath + "/examples" + relativeProPath; QString helpPath = "qthelp://com.trolltech.qt/qdoc/" + dirName.replace("/", "-") + "-" + fn + ".html"; ui->examplesComboBox->addItem(" " + name, fileName); ui->examplesComboBox->setItemData(ui->examplesComboBox->count()-1, helpPath, Qt::UserRole+1); } break; case QXmlStreamReader::EndElement: if (reader.name() == "category") inExamples = false; break; default: break; } } } void GettingStartedWelcomePageWidget::slotEnableExampleButton(int index) { QString fileName = ui->examplesComboBox->itemData(index, Qt::UserRole).toString(); ui->openExampleButton->setEnabled(!fileName.isEmpty()); } void GettingStartedWelcomePageWidget::slotOpenExample() { QComboBox *box = ui->examplesComboBox; QString proFile = box->itemData(box->currentIndex(), Qt::UserRole).toString(); QString helpFile = box->itemData(box->currentIndex(), Qt::UserRole + 1).toString(); QStringList files; QFileInfo fi(proFile); QString tryFile = fi.path() + "/main.cpp"; files << proFile; if(!QFile::exists(tryFile)) tryFile = fi.path() + '/' + fi.baseName() + ".cpp"; if(QFile::exists(tryFile)) files << tryFile; Core::ICore::instance()->openFiles(files); slotOpenContextHelpPage(helpFile); } void GettingStartedWelcomePageWidget::slotOpenHelpPage(const QString& url) { Help::HelpManager *helpManager = ExtensionSystem::PluginManager::instance()->getObject<Help::HelpManager>(); Q_ASSERT(helpManager); helpManager->openHelpPage(url); } void GettingStartedWelcomePageWidget::slotOpenContextHelpPage(const QString& url) { Help::HelpManager *helpManager = ExtensionSystem::PluginManager::instance()->getObject<Help::HelpManager>(); Q_ASSERT(helpManager); helpManager->openContextHelpPage(url); } void GettingStartedWelcomePageWidget::slotNextTip() { QStringList tips = tipsOfTheDay(); m_currentTip = ((m_currentTip+1)%tips.count()); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); } void GettingStartedWelcomePageWidget::slotPrevTip() { QStringList tips = tipsOfTheDay(); m_currentTip = ((m_currentTip-1)+tips.count())%tips.count(); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); } QStringList GettingStartedWelcomePageWidget::tipsOfTheDay() { static QStringList tips; if (tips.isEmpty()) { QString altShortcut = #ifdef Q_WS_MAC tr("Cmd", "Shortcut key"); #else tr("Alt", "Shortcut key"); #endif QString ctrlShortcut = #ifdef Q_WS_MAC tr("Cmd", "Shortcut key"); #else tr("Ctrl", "Shortcut key"); #endif tips.append(tr("You can switch between Qt Creator's modes using <tt>Ctrl+number</tt>:<ul>" "<li>1 - Welcome</li><li>2 - Edit</li><li>3 - Debug</li><li>4 - Projects</li><li>5 - Help</li>" "<li></li><li>6 - Output</li></ul>")); //:%1 gets replaced by Alt (Win/Unix) or Cmd (Mac) tips.append(tr("You can show and hide the side bar using <tt>%1+0<tt>.").arg(altShortcut)); tips.append(tr("You can fine tune the <tt>Find</tt> function by selecting &quot;Whole Words&quot; " "or &quot;Case Sensitive&quot;. Simply click on the icons on the right end of the line edit.")); tips.append(tr("If you add <a href=\"qthelp://com.nokia.qtcreator/doc/creator-external-library-handling.html\"" ">external libraries</a>, Qt Creator will automatically offer syntax highlighting " "and code completion.")); tips.append(tr("The code completion is CamelCase-aware. For example, to complete <tt>namespaceUri</tt> " "you can just type <tt>nU</tt> and hit <tt>Ctrl+Space</tt>.")); tips.append(tr("You can force code completion at any time using <tt>Ctrl+Space</tt>.")); tips.append(tr("You can start Qt Creator with a session by calling <tt>qtcreator &lt;sessionname&gt;</tt>.")); tips.append(tr("You can return to edit mode from any other mode at any time by hitting <tt>Escape</tt>.")); //:%1 gets replaced by Alt (Win/Unix) or Cmd (Mac) tips.append(tr("You can switch between the output pane by hitting <tt>%1+n</tt> where n is the number denoted " "on the buttons at the window bottom:" "<ul><li>1 - Build Issues</li><li>2 - Search Results</li><li>3 - Application Output</li>" "<li>4 - Compile Output</li></ul>").arg(altShortcut)); tips.append(tr("You can quickly search methods, classes, help and more using the " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-navigation.html\">Locator bar</a> (<tt>%1+K</tt>).").arg(ctrlShortcut)); tips.append(tr("You can add custom build steps in the " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-build-settings.html\">build settings</a>.")); tips.append(tr("Within a session, you can add " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-build-settings.html#dependencies\">dependencies</a> between projects.")); tips.append(tr("You can set the preferred editor encoding for every project in <tt>Projects -> Editor Settings -> Default Encoding</tt>.")); tips.append(tr("You can modify the binary that is being executed when you press the <tt>Run</tt> button: Add a <tt>Custom Executable</tt> " "by clicking the <tt>+</tt> button in <tt>Projects -> Run Settings -> Run Configuration</tt> and then select the new " "target in the combo box.")); tips.append(tr("You can use Qt Creator with a number of <a href=\"qthelp://com.nokia.qtcreator/doc/creator-version-control.html\">" "revision control systems</a> such as Subversion, Perforce, CVS and Git.")); tips.append(tr("In the editor, <tt>F2</tt> toggles declaration and definition while <tt>F4</tt> toggles header file and source file.")); } return tips; } } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>Workaround for Linux Distro Qt where examples live in write-protected dirs.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "gettingstartedwelcomepagewidget.h" #include "ui_gettingstartedwelcomepagewidget.h" #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <utils/pathchooser.h> #include <extensionsystem/pluginmanager.h> #include <help/helpplugin.h> #include <QtCore/QDateTime> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtCore/QDebug> #include <QtCore/QUrl> #include <QtCore/QSettings> #include <QtCore/QXmlStreamReader> #include <QtGui/QDialogButtonBox> #include <QtGui/QFont> #include <QtGui/QMessageBox> #include <QtGui/QPushButton> namespace Qt4ProjectManager { namespace Internal { GettingStartedWelcomePageWidget::GettingStartedWelcomePageWidget(QWidget *parent) : QWidget(parent), ui(new Ui::GettingStartedWelcomePageWidget) { ui->setupUi(this); ui->tutorialsTitleLabel->setStyledText(tr("Tutorials")); ui->demoTitleLabel->setStyledText(tr("Explore Qt Examples")); ui->didYouKnowTextBrowser->viewport()->setAutoFillBackground(false); ui->didYouKnowTitleLabel->setStyledText(tr("Did You Know?")); connect(ui->tutorialTreeWidget, SIGNAL(activated(QString)), SLOT(slotOpenHelpPage(const QString&))); connect(ui->openExampleButton, SIGNAL(clicked()), SLOT(slotOpenExample())); connect(ui->examplesComboBox, SIGNAL(currentIndexChanged(int)), SLOT(slotEnableExampleButton(int))); ui->tutorialTreeWidget->addItem(tr("<b>Qt Creator - A quick tour</b>"), QString("qthelp://com.nokia.qtcreator.%1%2/doc/index.html").arg(IDE_VERSION_MAJOR).arg(IDE_VERSION_MINOR)); ui->tutorialTreeWidget->addItem(tr("Creating an address book"), QLatin1String("qthelp://com.nokia.qtcreator/doc/tutorials-addressbook-sdk.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Understanding widgets"), QLatin1String("qthelp://com.trolltech.qt/qdoc/widgets-tutorial.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Building with qmake"), QLatin1String("qthelp://com.trolltech.qmake/qdoc/qmake-tutorial.html?view=split")); ui->tutorialTreeWidget->addItem(tr("Writing test cases"), QLatin1String("qthelp://com.trolltech.qt/qdoc/qtestlib-tutorial.html?view=split")); srand(QDateTime::currentDateTime().toTime_t()); QStringList tips = tipsOfTheDay(); m_currentTip = rand()%tips.count(); QTextDocument *doc = ui->didYouKnowTextBrowser->document(); doc->setDefaultStyleSheet("a:link {color:black;}"); ui->didYouKnowTextBrowser->setDocument(doc); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); connect(ui->nextTipBtn, SIGNAL(clicked()), this, SLOT(slotNextTip())); connect(ui->prevTipBtn, SIGNAL(clicked()), this, SLOT(slotPrevTip())); } GettingStartedWelcomePageWidget::~GettingStartedWelcomePageWidget() { delete ui; } void GettingStartedWelcomePageWidget::updateExamples(const QString& examplePath, const QString& demosPath, const QString &sourcePath) { QString demoxml = demosPath + "/qtdemo/xml/examples.xml"; if (!QFile::exists(demoxml)) { demoxml = sourcePath + "/demos/qtdemo/xml/examples.xml"; if (!QFile::exists(demoxml)) return; } QFile description(demoxml); if (!description.open(QFile::ReadOnly)) return; ui->examplesComboBox->clear(); ui->examplesComboBox->setEnabled(true); ui->examplesComboBox->addItem(tr("Choose an example...")); QFont f = font(); f.setItalic(true); ui->examplesComboBox->setItemData(0, f, Qt::FontRole); f.setItalic(false); bool inExamples = false; QString dirName; QXmlStreamReader reader(&description); while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::StartElement: if (reader.name() == "category") { QString name = reader.attributes().value(QLatin1String("name")).toString(); if (name.contains("tutorial")) break; dirName = reader.attributes().value(QLatin1String("dirname")).toString(); ui->examplesComboBox->addItem(name); f.setBold(true); ui->examplesComboBox->setItemData(ui->examplesComboBox->count()-1, f, Qt::FontRole); f.setBold(false); inExamples = true; } if (inExamples && reader.name() == "example") { QString name = reader.attributes().value(QLatin1String("name")).toString(); QString fn = reader.attributes().value(QLatin1String("filename")).toString(); QString relativeProPath = '/' + dirName + '/' + fn + '/' + fn + ".pro"; QString fileName = examplePath + relativeProPath; if (!QFile::exists(fileName)) fileName = sourcePath + "/examples" + relativeProPath; QString helpPath = "qthelp://com.trolltech.qt/qdoc/" + dirName.replace("/", "-") + "-" + fn + ".html"; ui->examplesComboBox->addItem(" " + name, fileName); ui->examplesComboBox->setItemData(ui->examplesComboBox->count()-1, helpPath, Qt::UserRole+1); } break; case QXmlStreamReader::EndElement: if (reader.name() == "category") inExamples = false; break; default: break; } } } void GettingStartedWelcomePageWidget::slotEnableExampleButton(int index) { QString fileName = ui->examplesComboBox->itemData(index, Qt::UserRole).toString(); ui->openExampleButton->setEnabled(!fileName.isEmpty()); } namespace { void copyRecursive(const QDir& from, const QDir& to, const QString& dir) { QDir dest(to); dest.mkdir(dir); dest.cd(dir); QDir src(from); src.cd(dir); foreach(const QFileInfo& roFile, src.entryInfoList(QDir::Files)) { QFile::copy(roFile.absoluteFilePath(), dest.absolutePath() + '/' + roFile.fileName()); } foreach(const QString& roDir, src.entryList(QDir::NoDotAndDotDot|QDir::Dirs)) { copyRecursive(src, dest, QDir(roDir).dirName()); } } } // namespace void GettingStartedWelcomePageWidget::slotOpenExample() { QComboBox *box = ui->examplesComboBox; QString proFile = box->itemData(box->currentIndex(), Qt::UserRole).toString(); QString helpFile = box->itemData(box->currentIndex(), Qt::UserRole + 1).toString(); QStringList files; QFileInfo proFileInfo(proFile); // If the Qt is a distro Qt on Linux, it will not be writable, hence compilation will fail if (!proFileInfo.isWritable()) { QDialog d; QGridLayout *lay = new QGridLayout(&d); QLabel *descrLbl = new QLabel; d.setWindowTitle(tr("Copy Project to writable Location?")); descrLbl->setTextFormat(Qt::RichText); descrLbl->setWordWrap(true); descrLbl->setText(tr("<p>The project you are about to open is located in the " "write-protected location:</p><blockquote>%1</blockquote>" "<p>Please select a writable location below and click \"Copy Project and Open\" " "to open a modifiable copy of the project or click \"Keep Project and Open\" " "to open the project in location.</p><p><b>Note:</b> You will not " "be able to alter or compile your project in the current location.</p>") .arg(QDir::toNativeSeparators(proFileInfo.dir().absolutePath()))); lay->addWidget(descrLbl, 0, 0, 1, 2); QLabel *txt = new QLabel(tr("&Location:")); Utils::PathChooser *chooser = new Utils::PathChooser; txt->setBuddy(chooser); chooser->setExpectedKind(Utils::PathChooser::Directory); QSettings *settings = Core::ICore::instance()->settings(); chooser->setPath(settings->value( QString::fromLatin1("General/ProjectsFallbackRoot"), QDir::homePath()).toString()); lay->addWidget(txt, 1, 0); lay->addWidget(chooser, 1, 1); QDialogButtonBox *bb = new QDialogButtonBox; connect(bb, SIGNAL(accepted()), &d, SLOT(accept())); connect(bb, SIGNAL(rejected()), &d, SLOT(reject())); QPushButton *copyBtn = bb->addButton(tr("&Copy Project and Open"), QDialogButtonBox::AcceptRole); copyBtn->setDefault(true); bb->addButton(tr("&Keep Project and Open"), QDialogButtonBox::RejectRole); lay->addWidget(bb, 2, 0, 1, 2); connect(chooser, SIGNAL(validChanged(bool)), copyBtn, SLOT(setEnabled(bool))); if (d.exec() == QDialog::Accepted) { QString exampleDirName = proFileInfo.dir().dirName(); QString toDir = chooser->path(); settings->setValue(QString::fromLatin1("General/ProjectsFallbackRoot"), toDir); QDir toDirWithExamplesDir(toDir); if (toDirWithExamplesDir.cd(exampleDirName)) { toDirWithExamplesDir.cdUp(); // step out, just to not be in the way QMessageBox::warning(topLevelWidget(), tr("Warning"), tr("The specified location already exists. " "Please specify a valid location."), QMessageBox::Ok, QMessageBox::NoButton); return; } else { QDir from = proFileInfo.dir(); from.cdUp(); copyRecursive(from, toDir, exampleDirName); // set vars to new location proFileInfo = QFileInfo(toDir + '/'+ exampleDirName + '/' + proFileInfo.fileName()); proFile = proFileInfo.absoluteFilePath(); } } } QString tryFile = proFileInfo.path() + "/main.cpp"; files << proFile; if(!QFile::exists(tryFile)) tryFile = proFileInfo.path() + '/' + proFileInfo.baseName() + ".cpp"; if(QFile::exists(tryFile)) files << tryFile; Core::ICore::instance()->openFiles(files); slotOpenContextHelpPage(helpFile); } void GettingStartedWelcomePageWidget::slotOpenHelpPage(const QString& url) { Help::HelpManager *helpManager = ExtensionSystem::PluginManager::instance()->getObject<Help::HelpManager>(); Q_ASSERT(helpManager); helpManager->openHelpPage(url); } void GettingStartedWelcomePageWidget::slotOpenContextHelpPage(const QString& url) { Help::HelpManager *helpManager = ExtensionSystem::PluginManager::instance()->getObject<Help::HelpManager>(); Q_ASSERT(helpManager); helpManager->openContextHelpPage(url); } void GettingStartedWelcomePageWidget::slotNextTip() { QStringList tips = tipsOfTheDay(); m_currentTip = ((m_currentTip+1)%tips.count()); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); } void GettingStartedWelcomePageWidget::slotPrevTip() { QStringList tips = tipsOfTheDay(); m_currentTip = ((m_currentTip-1)+tips.count())%tips.count(); ui->didYouKnowTextBrowser->setText(tips.at(m_currentTip)); } QStringList GettingStartedWelcomePageWidget::tipsOfTheDay() { static QStringList tips; if (tips.isEmpty()) { QString altShortcut = #ifdef Q_WS_MAC tr("Cmd", "Shortcut key"); #else tr("Alt", "Shortcut key"); #endif QString ctrlShortcut = #ifdef Q_WS_MAC tr("Cmd", "Shortcut key"); #else tr("Ctrl", "Shortcut key"); #endif tips.append(tr("You can switch between Qt Creator's modes using <tt>Ctrl+number</tt>:<ul>" "<li>1 - Welcome</li><li>2 - Edit</li><li>3 - Debug</li><li>4 - Projects</li><li>5 - Help</li>" "<li></li><li>6 - Output</li></ul>")); //:%1 gets replaced by Alt (Win/Unix) or Cmd (Mac) tips.append(tr("You can show and hide the side bar using <tt>%1+0<tt>.").arg(altShortcut)); tips.append(tr("You can fine tune the <tt>Find</tt> function by selecting &quot;Whole Words&quot; " "or &quot;Case Sensitive&quot;. Simply click on the icons on the right end of the line edit.")); tips.append(tr("If you add <a href=\"qthelp://com.nokia.qtcreator/doc/creator-external-library-handling.html\"" ">external libraries</a>, Qt Creator will automatically offer syntax highlighting " "and code completion.")); tips.append(tr("The code completion is CamelCase-aware. For example, to complete <tt>namespaceUri</tt> " "you can just type <tt>nU</tt> and hit <tt>Ctrl+Space</tt>.")); tips.append(tr("You can force code completion at any time using <tt>Ctrl+Space</tt>.")); tips.append(tr("You can start Qt Creator with a session by calling <tt>qtcreator &lt;sessionname&gt;</tt>.")); tips.append(tr("You can return to edit mode from any other mode at any time by hitting <tt>Escape</tt>.")); //:%1 gets replaced by Alt (Win/Unix) or Cmd (Mac) tips.append(tr("You can switch between the output pane by hitting <tt>%1+n</tt> where n is the number denoted " "on the buttons at the window bottom:" "<ul><li>1 - Build Issues</li><li>2 - Search Results</li><li>3 - Application Output</li>" "<li>4 - Compile Output</li></ul>").arg(altShortcut)); tips.append(tr("You can quickly search methods, classes, help and more using the " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-navigation.html\">Locator bar</a> (<tt>%1+K</tt>).").arg(ctrlShortcut)); tips.append(tr("You can add custom build steps in the " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-build-settings.html\">build settings</a>.")); tips.append(tr("Within a session, you can add " "<a href=\"qthelp://com.nokia.qtcreator/doc/creator-build-settings.html#dependencies\">dependencies</a> between projects.")); tips.append(tr("You can set the preferred editor encoding for every project in <tt>Projects -> Editor Settings -> Default Encoding</tt>.")); tips.append(tr("You can modify the binary that is being executed when you press the <tt>Run</tt> button: Add a <tt>Custom Executable</tt> " "by clicking the <tt>+</tt> button in <tt>Projects -> Run Settings -> Run Configuration</tt> and then select the new " "target in the combo box.")); tips.append(tr("You can use Qt Creator with a number of <a href=\"qthelp://com.nokia.qtcreator/doc/creator-version-control.html\">" "revision control systems</a> such as Subversion, Perforce, CVS and Git.")); tips.append(tr("In the editor, <tt>F2</tt> toggles declaration and definition while <tt>F4</tt> toggles header file and source file.")); } return tips; } } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>8fd0494d-2d14-11e5-af21-0401358ea401<commit_msg>8fd0494e-2d14-11e5-af21-0401358ea401<commit_after>8fd0494e-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>98bbc73d-327f-11e5-9abd-9cf387a8033e<commit_msg>98c1e338-327f-11e5-a29e-9cf387a8033e<commit_after>98c1e338-327f-11e5-a29e-9cf387a8033e<|endoftext|>
<commit_before>/* <x0/request.hpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <[email protected]> */ #ifndef x0_http_request_hpp #define x0_http_request_hpp (1) #include <x0/buffer.hpp> #include <x0/header.hpp> #include <x0/fileinfo.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <x0/api.hpp> #include <string> #include <vector> #include <boost/tuple/tuple.hpp> #include <boost/logic/tribool.hpp> namespace x0 { //! \addtogroup core //@{ /** * \brief a client HTTP reuqest object, holding the parsed x0 request data. * * \see header, response, connection, server */ struct request { public: class reader; public: explicit request(x0::connection& connection); /// the TCP/IP connection this request has been sent through x0::connection& connection; public: // request properties /// HTTP request method, e.g. HEAD, GET, POST, PUT, etc. buffer_ref method; /// parsed request uri buffer_ref uri; /// decoded path-part buffer_ref path; /// the final entity to be served, for example the full path to the file on disk. fileinfo_ptr fileinfo; /// decoded query-part buffer_ref query; /// HTTP protocol version major part that this request was formed in int http_version_major; /// HTTP protocol version minor part that this request was formed in int http_version_minor; /// request headers std::vector<x0::request_header> headers; /** retrieve value of a given request header */ buffer_ref header(const std::string& name) const; /// body std::string body; public: // accumulated request data /// username this client has authenticated with. buffer_ref username; /// the document root directory for this request. std::string document_root; // std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified. // std::shared_ptr<range_def> range; //!< parsed "Range" request header public: // utility methods bool supports_protocol(int major, int minor) const; std::string hostid() const; }; /** * \brief implements the HTTP request parser. * * \see request, connection */ class request::reader { public: enum state { method_start, method, uri_start, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3, reading_body }; private: state state_; std::size_t left_; private: static inline bool is_char(int ch); static inline bool is_ctl(int ch); static inline bool is_tspecial(int ch); static inline bool is_digit(int ch); static inline bool url_decode(buffer_ref& url); public: reader(); void reset(); /** parses partial HTTP request. * * \param r request to fill with parsed data * \param data buffer holding the (possibly partial) data of the request to be parsed. * * \retval true request has been fully parsed. * \retval false HTTP request parser error (should result into bad_request if possible.) * \retval indeterminate parsial request parsed successfully but more input is needed to complete parsing. */ inline boost::tribool parse(request& req, const buffer_ref& data); }; // {{{ request impl inline request::request(x0::connection& conn) : connection(conn) { } inline bool request::supports_protocol(int major, int minor) const { if (major == http_version_major && minor <= http_version_minor) return true; if (major < http_version_major) return true; return false; } // }}} // {{{ request::reader impl inline bool request::reader::is_char(int ch) { return ch >= 0 && ch < 127; } inline bool request::reader::is_ctl(int ch) { return (ch >= 0 && ch <= 31) || ch == 127; } inline bool request::reader::is_tspecial(int ch) { switch (ch) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } inline bool request::reader::is_digit(int ch) { return ch >= '0' && ch <= '9'; } inline bool request::reader::url_decode(buffer_ref& url) { std::size_t left = url.offset(); std::size_t right = left + url.size(); std::size_t i = left; // read pos std::size_t d = left; // write pos buffer& value = url.buffer(); while (i != right) { if (value[i] == '%') { if (i + 3 <= right) { int ival; if (hex2int(value.begin() + i + 1, value.begin() + i + 3, ival)) { value[d++] = static_cast<char>(ival); i += 3; } else { return false; } } else { return false; } } else if (value[i] == '+') { value[d++] = ' '; ++i; } else if (d != i) { value[d++] = value[i++]; } else { ++d; ++i; } } url = value.ref(left, d - left); return true; } inline request::reader::reader() : state_(method_start), left_(0) { } inline void request::reader::reset() { state_ = method_start; left_ = 0; } inline boost::tribool request::reader::parse(request& r, const buffer_ref& data) { std::size_t cur = data.offset(); std::size_t count = cur + data.size(); buffer_ref::const_iterator i = data.begin(); for (; cur != count; ++cur) { char input = *i++; switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; state_ = method; break; case method: if (input == ' ') { r.method = data.buffer().ref(left_, cur - left_); state_ = uri; left_ = cur + 1; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; break; case uri_start: if (is_ctl(input)) return false; state_ = uri; break; case uri: if (input == ' ') { r.uri = data.buffer().ref(left_, cur - left_); left_ = cur + 1; if (!url_decode(r.uri)) return false; std::size_t n = r.uri.find("?"); if (n != std::string::npos) { r.path = r.uri.ref(0, n); r.query = r.uri.ref(n + 1); } else { r.path = r.uri; } if (r.path.empty() || r.path[0] != '/' || r.path.find("..") != std::string::npos) return false; state_ = http_version_h; } else if (is_ctl(input)) return false; break; case http_version_h: if (input != 'H') return false; state_ = http_version_t_1; break; case http_version_t_1: if (input != 'T') return false; state_ = http_version_t_2; break; case http_version_t_2: if (input != 'T') return false; state_ = http_version_p; break; case http_version_p: if (input != 'P') return false; state_ = http_version_slash; break; case http_version_slash: if (input != '/') return false; r.http_version_major = 0; r.http_version_minor = 0; state_ = http_version_major_start; break; case http_version_major_start: if (!is_digit(input)) return false; r.http_version_major = r.http_version_major * 10 + input - '0'; state_ = http_version_major; break; case http_version_major: if (input == '.') state_ = http_version_minor_start; else if (is_digit(input)) r.http_version_major = r.http_version_major * 10 + input - '0'; else return false; break; case http_version_minor_start: if (input == '\r') state_ = expecting_newline_1; else if (is_digit(input)) r.http_version_minor = r.http_version_minor * 10 + input - '0'; else return false; break; case expecting_newline_1: if (input != '\n') return false; state_ = header_line_start; break; case header_line_start: if (input == '\r') state_ = expecting_newline_3; else if (!r.headers.empty() && (input == ' ' || input == '\t')) state_ = header_lws; else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; else { r.headers.push_back(x0::request_header()); //r.headers.back().name.push_back(input); r.headers.back().name = data.buffer().ref(cur, 1); state_ = header_name; } break; case header_lws: if (input == '\r') state_ = expecting_newline_2; else if (input != ' ' && input != '\t') { state_ = header_value; r.headers.back().value = data.buffer().ref(cur, 1); } break; case header_name: if (input == ':') state_ = space_before_header_value; else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; else r.headers.back().name.shr(1); break; case space_before_header_value: if (input != ' ') return false; state_ = header_value; break; case header_value: if (input == '\r') state_ = expecting_newline_2; else if (is_ctl(input)) return false; else if (r.headers.back().value.empty()) r.headers.back().value = data.buffer().ref(cur, 1); else r.headers.back().value.shr(1); break; case expecting_newline_2: if (input != '\n') return false; state_ = header_line_start; break; case expecting_newline_3: if (input == '\n') { buffer_ref s(r.header("Content-Length")); if (!s.empty()) { state_ = reading_body; r.body.reserve(std::atoi(s.data())); break; } else { return true; } } else { return false; } case reading_body: r.body.push_back(input); if (r.body.length() < r.body.capacity()) { break; } else { return true; } default: return false; } } // request header parsed partially return boost::indeterminate; } // }}} //@} } // namespace x0 #endif <commit_msg>core: comment-foo<commit_after>/* <x0/request.hpp> * * This file is part of the x0 web server project and is released under LGPL-3. * * (c) 2009 Chrisitan Parpart <[email protected]> */ #ifndef x0_http_request_hpp #define x0_http_request_hpp (1) #include <x0/buffer.hpp> #include <x0/header.hpp> #include <x0/fileinfo.hpp> #include <x0/strutils.hpp> #include <x0/types.hpp> #include <x0/api.hpp> #include <string> #include <vector> #include <boost/tuple/tuple.hpp> #include <boost/logic/tribool.hpp> namespace x0 { //! \addtogroup core //@{ /** * \brief a client HTTP reuqest object, holding the parsed x0 request data. * * \see header, response, connection, server */ struct request { public: class reader; public: explicit request(x0::connection& connection); /// the TCP/IP connection this request has been sent through x0::connection& connection; public: // request properties /// HTTP request method, e.g. HEAD, GET, POST, PUT, etc. buffer_ref method; /// parsed request uri buffer_ref uri; /// decoded path-part buffer_ref path; /// the final entity to be served, for example the full path to the file on disk. fileinfo_ptr fileinfo; /// decoded query-part buffer_ref query; /// HTTP protocol version major part that this request was formed in int http_version_major; /// HTTP protocol version minor part that this request was formed in int http_version_minor; /// request headers std::vector<x0::request_header> headers; /** retrieve value of a given request header */ buffer_ref header(const std::string& name) const; /// body std::string body; public: // accumulated request data /// username this client has authenticated with. buffer_ref username; /// the document root directory for this request. std::string document_root; // std::string if_modified_since; //!< "If-Modified-Since" request header value, if specified. // std::shared_ptr<range_def> range; //!< parsed "Range" request header public: // utility methods bool supports_protocol(int major, int minor) const; std::string hostid() const; }; /** * \brief implements the HTTP request parser. * * \see request, connection */ class request::reader { public: enum state { method_start, method, uri_start, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3, reading_body }; private: state state_; std::size_t left_; private: static inline bool is_char(int ch); static inline bool is_ctl(int ch); static inline bool is_tspecial(int ch); static inline bool is_digit(int ch); static inline bool url_decode(buffer_ref& url); public: reader(); void reset(); /** parses partial HTTP request. * * \param r request to fill with parsed data * \param data buffer holding the (possibly partial) data of the request to be parsed. * * \retval true request has been fully parsed. * \retval false HTTP request parser error (should result into bad_request if possible.) * \retval indeterminate parsial request parsed successfully but more input is needed to complete parsing. */ inline boost::tribool parse(request& req, const buffer_ref& data); }; // {{{ request impl inline request::request(x0::connection& conn) : connection(conn) { } inline bool request::supports_protocol(int major, int minor) const { if (major == http_version_major && minor <= http_version_minor) return true; if (major < http_version_major) return true; return false; } // }}} // {{{ request::reader impl inline bool request::reader::is_char(int ch) { return ch >= 0 && ch < 127; } inline bool request::reader::is_ctl(int ch) { return (ch >= 0 && ch <= 31) || ch == 127; } inline bool request::reader::is_tspecial(int ch) { switch (ch) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } inline bool request::reader::is_digit(int ch) { return ch >= '0' && ch <= '9'; } inline bool request::reader::url_decode(buffer_ref& url) { std::size_t left = url.offset(); std::size_t right = left + url.size(); std::size_t i = left; // read pos std::size_t d = left; // write pos buffer& value = url.buffer(); while (i != right) { if (value[i] == '%') { if (i + 3 <= right) { int ival; if (hex2int(value.begin() + i + 1, value.begin() + i + 3, ival)) { value[d++] = static_cast<char>(ival); i += 3; } else { return false; } } else { return false; } } else if (value[i] == '+') { value[d++] = ' '; ++i; } else if (d != i) { value[d++] = value[i++]; } else { ++d; ++i; } } url = value.ref(left, d - left); return true; } inline request::reader::reader() : state_(method_start), left_(0) { } inline void request::reader::reset() { state_ = method_start; left_ = 0; } inline boost::tribool request::reader::parse(request& r, const buffer_ref& data) { std::size_t cur = data.offset(); std::size_t count = cur + data.size(); buffer_ref::const_iterator i = data.begin(); for (; cur != count; ++cur) { char input = *i++; switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; state_ = method; break; case method: if (input == ' ') { r.method = data.buffer().ref(left_, cur - left_); state_ = uri; left_ = cur + 1; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; break; case uri_start: if (is_ctl(input)) return false; state_ = uri; break; case uri: if (input == ' ') { r.uri = data.buffer().ref(left_, cur - left_); left_ = cur + 1; if (!url_decode(r.uri)) return false; std::size_t n = r.uri.find("?"); if (n != std::string::npos) { r.path = r.uri.ref(0, n); r.query = r.uri.ref(n + 1); } else { r.path = r.uri; } if (r.path.empty() || r.path[0] != '/' || r.path.find("..") != std::string::npos) return false; state_ = http_version_h; } else if (is_ctl(input)) return false; break; case http_version_h: if (input != 'H') return false; state_ = http_version_t_1; break; case http_version_t_1: if (input != 'T') return false; state_ = http_version_t_2; break; case http_version_t_2: if (input != 'T') return false; state_ = http_version_p; break; case http_version_p: if (input != 'P') return false; state_ = http_version_slash; break; case http_version_slash: if (input != '/') return false; r.http_version_major = 0; r.http_version_minor = 0; state_ = http_version_major_start; break; case http_version_major_start: if (!is_digit(input)) return false; r.http_version_major = r.http_version_major * 10 + input - '0'; state_ = http_version_major; break; case http_version_major: if (input == '.') state_ = http_version_minor_start; else if (is_digit(input)) r.http_version_major = r.http_version_major * 10 + input - '0'; else return false; break; case http_version_minor_start: if (input == '\r') state_ = expecting_newline_1; else if (is_digit(input)) r.http_version_minor = r.http_version_minor * 10 + input - '0'; else return false; break; case expecting_newline_1: if (input != '\n') return false; state_ = header_line_start; break; case header_line_start: if (input == '\r') state_ = expecting_newline_3; else if (!r.headers.empty() && (input == ' ' || input == '\t')) state_ = header_lws; // header-value continuation else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; else { r.headers.push_back(x0::request_header()); //r.headers.back().name.push_back(input); r.headers.back().name = data.buffer().ref(cur, 1); state_ = header_name; } break; case header_lws: if (input == '\r') state_ = expecting_newline_2; else if (input != ' ' && input != '\t') { state_ = header_value; r.headers.back().value = data.buffer().ref(cur, 1); } break; case header_name: if (input == ':') state_ = space_before_header_value; else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) return false; else r.headers.back().name.shr(1); break; case space_before_header_value: if (input != ' ') return false; state_ = header_value; break; case header_value: if (input == '\r') state_ = expecting_newline_2; else if (is_ctl(input)) return false; else if (r.headers.back().value.empty()) r.headers.back().value = data.buffer().ref(cur, 1); else r.headers.back().value.shr(1); break; case expecting_newline_2: if (input != '\n') return false; state_ = header_line_start; break; case expecting_newline_3: if (input == '\n') { buffer_ref s(r.header("Content-Length")); if (!s.empty()) { state_ = reading_body; r.body.reserve(std::atoi(s.data())); break; } else { return true; } } else { return false; } case reading_body: r.body.push_back(input); if (r.body.length() < r.body.capacity()) { break; } else { return true; } default: return false; } } // request header parsed partially return boost::indeterminate; } // }}} //@} } // namespace x0 #endif <|endoftext|>
<commit_before>#include "include/udata.h" #include "include/amici_exception.h" #include <cstdio> #include <cstring> #include <algorithm> namespace amici { UserData::UserData(const int np, const int nk, const int nx) : sizex(nx) { // these fields must always be initialized, others are optional or can be set later konst.resize(nk); par.resize(np); unpar.resize(np); qpositivex.assign(nx,1); } UserData::UserData() : sizex(0) { konst.resize(0); par.resize(0); unpar.resize(0); qpositivex.assign(0,1); } UserData::UserData(const UserData &other) : UserData(other.np(), other.nk(), other.nx()) { nmaxevent = other.nmaxevent; qpositivex = other.qpositivex; p_index = other.p_index; par = other.par; unpar = other.unpar; konst = other.konst; pscale = other.pscale; tstart = other.tstart; ts = other.ts; pbar = other.pbar; xbar = other.xbar; sensi = other.sensi; atol = other.atol; rtol = other.rtol; maxsteps = other.maxsteps; quad_atol = other.quad_atol; quad_rtol = other.quad_rtol; maxstepsB = other.maxstepsB; newton_maxsteps = other.newton_maxsteps; newton_maxlinsteps = other.newton_maxlinsteps; newton_preeq = other.newton_preeq; newton_precon = other.newton_precon; ism = other.ism; sensi_meth = other.sensi_meth; linsol = other.linsol; interpType = other.interpType; lmm = other.lmm; iter = other.iter; stldet = other.stldet; x0data = other.x0data; sx0data = other.sx0data; ordering = other.ordering; newton_precon = other.newton_precon; ism = other.ism; } void UserData::unscaleParameters(double *bufferUnscaled) const { /** * unscaleParameters removes parameter scaling according to the parameter * scaling in pscale * * @param[out] bufferUnscaled unscaled parameters are written to the array * @type double * * @return status flag indicating success of execution @type int */ switch (pscale) { case AMICI_SCALING_LOG10: for (int ip = 0; ip < np(); ++ip) { bufferUnscaled[ip] = pow(10, par[ip]); } break; case AMICI_SCALING_LN: for (int ip = 0; ip < np(); ++ip) bufferUnscaled[ip] = exp(par[ip]); break; case AMICI_SCALING_NONE: for (int ip = 0; ip < np(); ++ip) bufferUnscaled[ip] = par[ip]; break; } } void UserData::setTimepoints(const double * timepoints, int numTimepoints) { ts.resize(numTimepoints); memcpy(ts.data(), timepoints, sizeof(double) * numTimepoints); } void UserData::setParameters(const double * parameters) { memcpy(par.data(), parameters, sizeof(double) * np()); unscaleParameters(unpar.data()); } void UserData::setConstants(const double *constants) { memcpy(konst.data(), constants, sizeof(double) * nk()); } void UserData::setPlist(const double *plist, int length) { if(!plist) throw AmiException("Provided plist was a nullptr, please provide a valid pointer."); p_index.resize(length); pbar.resize(nplist()); std::fill(pbar.begin(),pbar.end(),1.0); for (int ip = 0; ip < length; ip++) { p_index[ip] = (int)plist[ip]; } } void UserData::setPlist(const int *plist, int length) { if(!plist) throw AmiException("Provided plist was a nullptr, please provide a valid pointer."); p_index.resize(length); pbar.resize(nplist()); std::fill(pbar.begin(),pbar.end(),1.0); memcpy(p_index.data(), plist, sizeof(int) * length); } void UserData::setPScale(const AMICI_parameter_scaling pscale) { this->pscale = pscale; unscaleParameters(unpar.data()); } const AMICI_parameter_scaling UserData::getPScale() const { return pscale; } void UserData::requireSensitivitiesForAllParameters() { p_index.resize(nplist()); for (int i = 0; i < nplist(); ++i) p_index[i] = i; } void UserData::setPbar(const double *parameterScaling) { if(parameterScaling) { pbar.resize(nplist()); memcpy(pbar.data(), parameterScaling, sizeof(double) * nplist()); } else { pbar.clear(); } } const double *UserData::getPbar() const { return pbar.data(); } void UserData::setXbar(const double *stateScaling) { if(stateScaling){ xbar.resize(nx()); memcpy(xbar.data(), stateScaling, sizeof(double) * nx()); } else { xbar.clear(); } } void UserData::setStateInitialization(const double *stateInitialization) { if(stateInitialization) { x0data.resize(nx()); memcpy(x0data.data(), stateInitialization, sizeof(double) * nx()); } else { x0data.clear(); } } void UserData::setSensitivityInitialization( const double *sensitivityInitialization) { if(sensitivityInitialization) { sx0data.resize(nx() * nplist()); memcpy(sx0data.data(), sensitivityInitialization, sizeof(double) * nx() * nplist()); } else { sx0data.clear(); } } /** * @brief getLinearMultistepMethod * @return lmm */ const LinearMultistepMethod UserData::getLinearMultistepMethod() const{ return lmm; } /** * @brief getNonlinearSolverIteration * @return iter */ const NonlinearSolverIteration UserData::getNonlinearSolverIteration() const{ return iter; } /** * @brief getInterpolationType * @return interType */ const InterpolationType UserData::getInterpolationType() const{ return interpType; } /** * @brief getStateOrdering * @return ordering */ const StateOrdering UserData::getStateOrdering() const{ return ordering; } /** * @brief getStabilityLimitFlag * @return stldet */ const int UserData::getStabilityLimitFlag() const{ return stldet; } UserData::~UserData() { } void UserData::print() const { printf("qpositivex: %p\n", qpositivex.data()); printf("plist: %p\n", p_index.data()); printf("nplist: %d\n", nplist()); printf("nt: %d\n", nt()); printf("nmaxevent: %d\n", nmaxevent); printf("p: %p\n", par.data()); printf("k: %p\n", konst.data()); printf("tstart: %e\n", tstart); printf("ts: %p\n", ts.data()); printf("pbar: %p\n", pbar.data()); printf("xbar: %p\n", xbar.data()); printf("sensi: %d\n", sensi); printf("atol: %e\n", atol); printf("rtol: %e\n", rtol); printf("maxsteps: %d\n", maxsteps); printf("quad_atol: %e\n", quad_atol); printf("quad_rtol: %e\n", quad_rtol); printf("maxstepsB: %d\n", maxstepsB); printf("newton_maxsteps: %d\n", newton_maxsteps); printf("newton_maxlinsteps: %d\n", newton_maxlinsteps); printf("ism: %d\n", ism); printf("sensi_meth: %d\n", sensi_meth); printf("linsol: %d\n", linsol); printf("interpType: %d\n", interpType); printf("lmm: %d\n", lmm); printf("iter: %d\n", iter); printf("stldet: %d\n", stldet); printf("x0data: %p\n", x0data.data()); printf("sx0data: %p\n", sx0data.data()); printf("ordering: %d\n", ordering); } } // namespace amici <commit_msg>moved the setting of default maxstepsB from Matlab to cpp code<commit_after>#include "include/udata.h" #include "include/amici_exception.h" #include <cstdio> #include <cstring> #include <algorithm> namespace amici { UserData::UserData(const int np, const int nk, const int nx) : sizex(nx) { // these fields must always be initialized, others are optional or can be set later konst.resize(nk); par.resize(np); unpar.resize(np); qpositivex.assign(nx,1); } UserData::UserData() : sizex(0) { konst.resize(0); par.resize(0); unpar.resize(0); qpositivex.assign(0,1); } UserData::UserData(const UserData &other) : UserData(other.np(), other.nk(), other.nx()) { nmaxevent = other.nmaxevent; qpositivex = other.qpositivex; p_index = other.p_index; par = other.par; unpar = other.unpar; konst = other.konst; pscale = other.pscale; tstart = other.tstart; ts = other.ts; pbar = other.pbar; xbar = other.xbar; sensi = other.sensi; atol = other.atol; rtol = other.rtol; quad_atol = other.quad_atol; quad_rtol = other.quad_rtol; maxsteps = other.maxsteps; maxstepsB = other.maxstepsB; if (maxstepsB == 0) maxstepsB = 100 * maxsteps; newton_maxsteps = other.newton_maxsteps; newton_maxlinsteps = other.newton_maxlinsteps; newton_preeq = other.newton_preeq; newton_precon = other.newton_precon; ism = other.ism; sensi_meth = other.sensi_meth; linsol = other.linsol; interpType = other.interpType; lmm = other.lmm; iter = other.iter; stldet = other.stldet; x0data = other.x0data; sx0data = other.sx0data; ordering = other.ordering; newton_precon = other.newton_precon; ism = other.ism; } void UserData::unscaleParameters(double *bufferUnscaled) const { /** * unscaleParameters removes parameter scaling according to the parameter * scaling in pscale * * @param[out] bufferUnscaled unscaled parameters are written to the array * @type double * * @return status flag indicating success of execution @type int */ switch (pscale) { case AMICI_SCALING_LOG10: for (int ip = 0; ip < np(); ++ip) { bufferUnscaled[ip] = pow(10, par[ip]); } break; case AMICI_SCALING_LN: for (int ip = 0; ip < np(); ++ip) bufferUnscaled[ip] = exp(par[ip]); break; case AMICI_SCALING_NONE: for (int ip = 0; ip < np(); ++ip) bufferUnscaled[ip] = par[ip]; break; } } void UserData::setTimepoints(const double * timepoints, int numTimepoints) { ts.resize(numTimepoints); memcpy(ts.data(), timepoints, sizeof(double) * numTimepoints); } void UserData::setParameters(const double * parameters) { memcpy(par.data(), parameters, sizeof(double) * np()); unscaleParameters(unpar.data()); } void UserData::setConstants(const double *constants) { memcpy(konst.data(), constants, sizeof(double) * nk()); } void UserData::setPlist(const double *plist, int length) { if(!plist) throw AmiException("Provided plist was a nullptr, please provide a valid pointer."); p_index.resize(length); pbar.resize(nplist()); std::fill(pbar.begin(),pbar.end(),1.0); for (int ip = 0; ip < length; ip++) { p_index[ip] = (int)plist[ip]; } } void UserData::setPlist(const int *plist, int length) { if(!plist) throw AmiException("Provided plist was a nullptr, please provide a valid pointer."); p_index.resize(length); pbar.resize(nplist()); std::fill(pbar.begin(),pbar.end(),1.0); memcpy(p_index.data(), plist, sizeof(int) * length); } void UserData::setPScale(const AMICI_parameter_scaling pscale) { this->pscale = pscale; unscaleParameters(unpar.data()); } const AMICI_parameter_scaling UserData::getPScale() const { return pscale; } void UserData::requireSensitivitiesForAllParameters() { p_index.resize(nplist()); for (int i = 0; i < nplist(); ++i) p_index[i] = i; } void UserData::setPbar(const double *parameterScaling) { if(parameterScaling) { pbar.resize(nplist()); memcpy(pbar.data(), parameterScaling, sizeof(double) * nplist()); } else { pbar.clear(); } } const double *UserData::getPbar() const { return pbar.data(); } void UserData::setXbar(const double *stateScaling) { if(stateScaling){ xbar.resize(nx()); memcpy(xbar.data(), stateScaling, sizeof(double) * nx()); } else { xbar.clear(); } } void UserData::setStateInitialization(const double *stateInitialization) { if(stateInitialization) { x0data.resize(nx()); memcpy(x0data.data(), stateInitialization, sizeof(double) * nx()); } else { x0data.clear(); } } void UserData::setSensitivityInitialization( const double *sensitivityInitialization) { if(sensitivityInitialization) { sx0data.resize(nx() * nplist()); memcpy(sx0data.data(), sensitivityInitialization, sizeof(double) * nx() * nplist()); } else { sx0data.clear(); } } /** * @brief getLinearMultistepMethod * @return lmm */ const LinearMultistepMethod UserData::getLinearMultistepMethod() const{ return lmm; } /** * @brief getNonlinearSolverIteration * @return iter */ const NonlinearSolverIteration UserData::getNonlinearSolverIteration() const{ return iter; } /** * @brief getInterpolationType * @return interType */ const InterpolationType UserData::getInterpolationType() const{ return interpType; } /** * @brief getStateOrdering * @return ordering */ const StateOrdering UserData::getStateOrdering() const{ return ordering; } /** * @brief getStabilityLimitFlag * @return stldet */ const int UserData::getStabilityLimitFlag() const{ return stldet; } UserData::~UserData() { } void UserData::print() const { printf("qpositivex: %p\n", qpositivex.data()); printf("plist: %p\n", p_index.data()); printf("nplist: %d\n", nplist()); printf("nt: %d\n", nt()); printf("nmaxevent: %d\n", nmaxevent); printf("p: %p\n", par.data()); printf("k: %p\n", konst.data()); printf("tstart: %e\n", tstart); printf("ts: %p\n", ts.data()); printf("pbar: %p\n", pbar.data()); printf("xbar: %p\n", xbar.data()); printf("sensi: %d\n", sensi); printf("atol: %e\n", atol); printf("rtol: %e\n", rtol); printf("maxsteps: %d\n", maxsteps); printf("quad_atol: %e\n", quad_atol); printf("quad_rtol: %e\n", quad_rtol); printf("maxstepsB: %d\n", maxstepsB); printf("newton_maxsteps: %d\n", newton_maxsteps); printf("newton_maxlinsteps: %d\n", newton_maxlinsteps); printf("ism: %d\n", ism); printf("sensi_meth: %d\n", sensi_meth); printf("linsol: %d\n", linsol); printf("interpType: %d\n", interpType); printf("lmm: %d\n", lmm); printf("iter: %d\n", iter); printf("stldet: %d\n", stldet); printf("x0data: %p\n", x0data.data()); printf("sx0data: %p\n", sx0data.data()); printf("ordering: %d\n", ordering); } } // namespace amici <|endoftext|>
<commit_before>#include "utils.h" // #include <fstream> // fstream #include <boost/tokenizer.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace std; using namespace boost; using namespace boost::numeric::ublas; std::ostream& operator<<(std::ostream& os, const map<int, double>& int_double_map) { map<int, double>::const_iterator it = int_double_map.begin(); os << "{"; if(it==int_double_map.end()) { os << "}"; return os; } os << it->first << ":" << it->second; it++; for(; it!=int_double_map.end(); it++) { os << ", " << it->first << ":" << it->second; } os << "}"; return os; } std::ostream& operator<<(std::ostream& os, const map<int, int>& int_int_map) { map<int, int>::const_iterator it = int_int_map.begin(); os << "{"; if(it==int_int_map.end()) { os << "}"; return os; } os << it->first << ":" << it->second; it++; for(; it!=int_int_map.end(); it++) { os << ", " << it->first << ":" << it->second; } os << "}"; return os; } string int_to_str(int i) { std::stringstream out; out << i; string s = out.str(); return s; } // FROM runModel_v2.cpp ///////////////////////////////////////////////////////////////////// // expect a csv file of data void LoadData(string file, boost::numeric::ublas::matrix<double>& M) { ifstream in(file.c_str()); if (!in.is_open()) return; typedef tokenizer< char_separator<char> > Tokenizer; char_separator<char> sep(","); string line; int nrows = 0; int ncols = 0; std::vector<string> vec; // get the size first while (std::getline(in,line)) { Tokenizer tok(line, sep); vec.assign(tok.begin(), tok.end()); ncols = vec.end() - vec.begin(); nrows++; } cout << "num rows = "<< nrows << " num cols = " << ncols << endl; // create a matrix to hold data matrix<double> Data(nrows, ncols); // make second pass in.clear(); in.seekg(0); int r = 0; while (std::getline(in,line)) { Tokenizer tok(line, sep); vec.assign(tok.begin(), tok.end()); int i = 0; for(i=0; i < vec.size() ; i++) { Data(r, i) = ::strtod(vec[i].c_str(), 0); } r++; } M = Data; } bool is_almost(double val1, double val2, double precision) { return abs(val1-val2) < precision; } // http://stackoverflow.com/a/11747023/1769715 std::vector<double> linspace(double a, double b, int n) { std::vector<double> array; double step = (b-a) / (n-1); while(a <= b) { array.push_back(a); a += step; } return array; } std::vector<double> log_linspace(double a, double b, int n) { std::vector<double> values = linspace(log(a), log(b), n); std::transform(values.begin(), values.end(), values.begin(), (double (*)(double))exp); return values; } <commit_msg>linspace: change variable name from array to values to avoid confusion with boost arrays<commit_after>#include "utils.h" // #include <fstream> // fstream #include <boost/tokenizer.hpp> #include <boost/numeric/ublas/matrix.hpp> using namespace std; using namespace boost; using namespace boost::numeric::ublas; std::ostream& operator<<(std::ostream& os, const map<int, double>& int_double_map) { map<int, double>::const_iterator it = int_double_map.begin(); os << "{"; if(it==int_double_map.end()) { os << "}"; return os; } os << it->first << ":" << it->second; it++; for(; it!=int_double_map.end(); it++) { os << ", " << it->first << ":" << it->second; } os << "}"; return os; } std::ostream& operator<<(std::ostream& os, const map<int, int>& int_int_map) { map<int, int>::const_iterator it = int_int_map.begin(); os << "{"; if(it==int_int_map.end()) { os << "}"; return os; } os << it->first << ":" << it->second; it++; for(; it!=int_int_map.end(); it++) { os << ", " << it->first << ":" << it->second; } os << "}"; return os; } string int_to_str(int i) { std::stringstream out; out << i; string s = out.str(); return s; } // FROM runModel_v2.cpp ///////////////////////////////////////////////////////////////////// // expect a csv file of data void LoadData(string file, boost::numeric::ublas::matrix<double>& M) { ifstream in(file.c_str()); if (!in.is_open()) return; typedef tokenizer< char_separator<char> > Tokenizer; char_separator<char> sep(","); string line; int nrows = 0; int ncols = 0; std::vector<string> vec; // get the size first while (std::getline(in,line)) { Tokenizer tok(line, sep); vec.assign(tok.begin(), tok.end()); ncols = vec.end() - vec.begin(); nrows++; } cout << "num rows = "<< nrows << " num cols = " << ncols << endl; // create a matrix to hold data matrix<double> Data(nrows, ncols); // make second pass in.clear(); in.seekg(0); int r = 0; while (std::getline(in,line)) { Tokenizer tok(line, sep); vec.assign(tok.begin(), tok.end()); int i = 0; for(i=0; i < vec.size() ; i++) { Data(r, i) = ::strtod(vec[i].c_str(), 0); } r++; } M = Data; } bool is_almost(double val1, double val2, double precision) { return abs(val1-val2) < precision; } // http://stackoverflow.com/a/11747023/1769715 std::vector<double> linspace(double a, double b, int n) { std::vector<double> values; double step = (b-a) / (n-1); while(a <= b) { values.push_back(a); a += step; } return values; } std::vector<double> log_linspace(double a, double b, int n) { std::vector<double> values = linspace(log(a), log(b), n); std::transform(values.begin(), values.end(), values.begin(), (double (*)(double))exp); return values; } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef UTILS_HPP_ #define UTILS_HPP_ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #ifdef VALGRIND #include <valgrind/memcheck.h> #endif // VALGRIND #include <stdexcept> #include <string> #include <vector> #include "containers/printf_buffer.hpp" #include "errors.hpp" #include "config/args.hpp" void run_generic_global_startup_behavior(); struct const_charslice { const char *beg, *end; const_charslice(const char *_beg, const char *_end) : beg(_beg), end(_end) { } const_charslice() : beg(NULL), end(NULL) { } }; typedef uint64_t microtime_t; microtime_t current_microtime(); /* General exception to be thrown when some process is interrupted. It's in `utils.hpp` because I can't think where else to put it */ class interrupted_exc_t : public std::exception { public: const char *what() const throw () { return "interrupted"; } }; /* Pad a value to the size of a cache line to avoid false sharing. * TODO: This is implemented as a struct with subtraction rather than a union * so that it gives an error when trying to pad a value bigger than * CACHE_LINE_SIZE. If that's needed, this may have to be done differently. */ template<typename value_t> struct cache_line_padded_t { value_t value; char padding[CACHE_LINE_SIZE - sizeof(value_t)]; }; void *malloc_aligned(size_t size, size_t alignment = 64); template <class T1, class T2> T1 ceil_aligned(T1 value, T2 alignment) { return value + alignment - (((value + alignment - 1) % alignment) + 1); } template <class T1, class T2> T1 ceil_divide(T1 dividend, T2 alignment) { return (dividend + alignment - 1) / alignment; } template <class T1, class T2> T1 floor_aligned(T1 value, T2 alignment) { return value - (value % alignment); } template <class T1, class T2> T1 ceil_modulo(T1 value, T2 alignment) { T1 x = (value + alignment - 1) % alignment; return value + alignment - ((x < 0 ? x + alignment : x) + 1); } inline bool divides(int64_t x, int64_t y) { return y % x == 0; } int gcd(int x, int y); int64_t round_up_to_power_of_two(int64_t x); timespec clock_monotonic(); timespec clock_realtime(); typedef uint64_t ticks_t; ticks_t secs_to_ticks(time_t secs); ticks_t get_ticks(); time_t get_secs(); double ticks_to_secs(ticks_t ticks); #ifndef NDEBUG #define trace_call(fn, args...) do { \ debugf("%s:%u: %s: entered\n", __FILE__, __LINE__, stringify(fn)); \ fn(args); \ debugf("%s:%u: %s: returned\n", __FILE__, __LINE__, stringify(fn)); \ } while (0) #define TRACEPOINT debugf("%s:%u reached\n", __FILE__, __LINE__) #else #define trace_call(fn, args...) fn(args) // TRACEPOINT is not defined in release, so that TRACEPOINTS do not linger in the code unnecessarily #endif // HEY: Maybe debugf and log_call and TRACEPOINT should be placed in // debugf.hpp (and debugf.cc). /* Debugging printing API (prints current thread in addition to message) */ void debug_print_quoted_string(append_only_printf_buffer_t *buf, const uint8_t *s, size_t n); void debugf_prefix_buf(printf_buffer_t<1000> *buf); void debugf_dump_buf(printf_buffer_t<1000> *buf); // Primitive debug_print declarations. void debug_print(append_only_printf_buffer_t *buf, uint64_t x); void debug_print(append_only_printf_buffer_t *buf, const std::string& s); #ifndef NDEBUG void debugf(const char *msg, ...) __attribute__((format (printf, 1, 2))); template <class T> void debugf_print(const char *msg, const T& obj) { printf_buffer_t<1000> buf; debugf_prefix_buf(&buf); buf.appendf("%s: ", msg); debug_print(&buf, obj); buf.appendf("\n"); debugf_dump_buf(&buf); } #else #define debugf(...) ((void)0) #define debugf_print(...) ((void)0) #endif class debugf_in_dtor_t { public: explicit debugf_in_dtor_t(const char *msg, ...); ~debugf_in_dtor_t(); private: std::string message; }; class rng_t { public: // Returns a random number in [0, n). Is not perfectly uniform; the // bias tends to get worse when RAND_MAX is far from a multiple of n. int randint(int n); explicit rng_t(int seed = -1); private: unsigned short xsubi[3]; DISABLE_COPYING(rng_t); }; // Reads from /dev/urandom. Use this sparingly, please. void get_dev_urandom(void *out, int64_t nbytes); int randint(int n); std::string rand_string(int len); bool begins_with_minus(const char *string); // strtoul() and strtoull() will for some reason not fail if the input begins // with a minus sign. strtou64_strict() does. Also we fix the constness of the // end parameter. int64_t strtoi64_strict(const char *string, const char **end, int base); uint64_t strtou64_strict(const char *string, const char **end, int base); // These functions return false and set the result to 0 if the conversion fails or // does not consume the whole string. MUST_USE bool strtoi64_strict(const std::string &str, int base, int64_t *out_result); MUST_USE bool strtou64_strict(const std::string &str, int base, uint64_t *out_result); std::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); std::string vstrprintf(const char *format, va_list ap); // formatted time: // yyyy-mm-ddThh:mm:ss.nnnnnnnnn (29 characters) const size_t formatted_time_length = 29; // not including null void format_time(struct timespec time, append_only_printf_buffer_t *buf); std::string format_time(struct timespec time); struct timespec parse_time(const std::string &str) THROWS_ONLY(std::runtime_error); /* Printing binary data to stdout in a nice format */ void print_hd(const void *buf, size_t offset, size_t length); // Fast string compare int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2); /* The home thread mixin is a mixin for objects that can only be used on a single thread. Its thread ID is exposed as the `home_thread()` method. Some subclasses of `home_thread_mixin_debug_only_t` can move themselves to another thread, modifying the field real_home_thread. */ #define INVALID_THREAD (-1) class home_thread_mixin_debug_only_t { public: #ifndef NDEBUG void assert_thread() const; #else void assert_thread() const { } #endif protected: explicit home_thread_mixin_debug_only_t(int specified_home_thread); home_thread_mixin_debug_only_t(); virtual ~home_thread_mixin_debug_only_t() { } private: DISABLE_COPYING(home_thread_mixin_debug_only_t); #ifndef NDEBUG int real_home_thread; #endif }; class home_thread_mixin_t { public: int home_thread() const { return real_home_thread; } #ifndef NDEBUG void assert_thread() const; #else void assert_thread() const { } #endif protected: explicit home_thread_mixin_t(int specified_home_thread); home_thread_mixin_t(); virtual ~home_thread_mixin_t() { } int real_home_thread; private: // Things with home threads should not be copyable, since we don't // want to nonchalantly copy their real_home_thread variable. DISABLE_COPYING(home_thread_mixin_t); }; /* `on_thread_t` switches to the given thread in its constructor, then switches back in its destructor. For example: printf("Suppose we are on thread 1.\n"); { on_thread_t thread_switcher(2); printf("Now we are on thread 2.\n"); } printf("And now we are on thread 1 again.\n"); */ class on_thread_t : public home_thread_mixin_t { public: explicit on_thread_t(int thread); ~on_thread_t(); }; template <class InputIterator, class UnaryPredicate> bool all_match_predicate(InputIterator begin, InputIterator end, UnaryPredicate f) { bool res = true; for (; begin != end; begin++) { res &= f(*begin); } return res; } template <class T, class UnaryPredicate> bool all_in_container_match_predicate (const T &container, UnaryPredicate f) { return all_match_predicate(container.begin(), container.end(), f); } bool notf(bool x); /* Translates to and from `0123456789ABCDEF`. */ bool hex_to_int(char c, int *out); char int_to_hex(int i); std::string read_file(const char *path); struct path_t { std::vector<std::string> nodes; bool is_absolute; }; path_t parse_as_path(const std::string &); std::string render_as_path(const path_t &); enum region_join_result_t { REGION_JOIN_OK, REGION_JOIN_BAD_JOIN, REGION_JOIN_BAD_REGION }; template <class T> class assignment_sentry_t { public: assignment_sentry_t(T *v, const T &value) : var(v), old_value(*var) { *var = value; } ~assignment_sentry_t() { *var = old_value; } private: T *var; T old_value; }; std::string sanitize_for_logger(const std::string &s); static inline std::string time2str(const time_t &t) { char timebuf[26]; // I apologize for the magic constant. // ^^ See man 3 ctime_r return ctime_r(&t, timebuf); } std::string errno_string(int errsv); int get_num_db_threads(); template <class T> T valgrind_undefined(T value) { #ifdef VALGRIND VALGRIND_MAKE_MEM_UNDEFINED(&value, sizeof(value)); #endif return value; } #define STR(x) #x #define MSTR(x) STR(x) // Stringify a macro #if defined __clang__ #define COMPILER "CLANG " __clang_version__ #elif defined __GNUC__ #define COMPILER "GCC " MSTR(__GNUC__) "." MSTR(__GNUC_MINOR__) "." MSTR(__GNUC_PATCHLEVEL__) #else #define COMPILER "UNKNOWN COMPILER" #endif #ifndef NDEBUG #define RETHINKDB_VERSION_STR "rethinkdb " RETHINKDB_VERSION " (debug)" " (" COMPILER ")" #else #define RETHINKDB_VERSION_STR "rethinkdb " RETHINKDB_VERSION " (" COMPILER ")" #endif #define NULLPTR (static_cast<void *>(0)) #endif // UTILS_HPP_ <commit_msg>Added unused type portno_t in utils.hpp.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef UTILS_HPP_ #define UTILS_HPP_ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #ifdef VALGRIND #include <valgrind/memcheck.h> #endif // VALGRIND #include <stdexcept> #include <string> #include <vector> #include "containers/printf_buffer.hpp" #include "errors.hpp" #include "config/args.hpp" void run_generic_global_startup_behavior(); struct const_charslice { const char *beg, *end; const_charslice(const char *_beg, const char *_end) : beg(_beg), end(_end) { } const_charslice() : beg(NULL), end(NULL) { } }; typedef uint64_t microtime_t; microtime_t current_microtime(); /* General exception to be thrown when some process is interrupted. It's in `utils.hpp` because I can't think where else to put it */ class interrupted_exc_t : public std::exception { public: const char *what() const throw () { return "interrupted"; } }; /* Pad a value to the size of a cache line to avoid false sharing. * TODO: This is implemented as a struct with subtraction rather than a union * so that it gives an error when trying to pad a value bigger than * CACHE_LINE_SIZE. If that's needed, this may have to be done differently. */ template<typename value_t> struct cache_line_padded_t { value_t value; char padding[CACHE_LINE_SIZE - sizeof(value_t)]; }; void *malloc_aligned(size_t size, size_t alignment = 64); template <class T1, class T2> T1 ceil_aligned(T1 value, T2 alignment) { return value + alignment - (((value + alignment - 1) % alignment) + 1); } template <class T1, class T2> T1 ceil_divide(T1 dividend, T2 alignment) { return (dividend + alignment - 1) / alignment; } template <class T1, class T2> T1 floor_aligned(T1 value, T2 alignment) { return value - (value % alignment); } template <class T1, class T2> T1 ceil_modulo(T1 value, T2 alignment) { T1 x = (value + alignment - 1) % alignment; return value + alignment - ((x < 0 ? x + alignment : x) + 1); } inline bool divides(int64_t x, int64_t y) { return y % x == 0; } int gcd(int x, int y); int64_t round_up_to_power_of_two(int64_t x); timespec clock_monotonic(); timespec clock_realtime(); typedef uint64_t ticks_t; ticks_t secs_to_ticks(time_t secs); ticks_t get_ticks(); time_t get_secs(); double ticks_to_secs(ticks_t ticks); #ifndef NDEBUG #define trace_call(fn, args...) do { \ debugf("%s:%u: %s: entered\n", __FILE__, __LINE__, stringify(fn)); \ fn(args); \ debugf("%s:%u: %s: returned\n", __FILE__, __LINE__, stringify(fn)); \ } while (0) #define TRACEPOINT debugf("%s:%u reached\n", __FILE__, __LINE__) #else #define trace_call(fn, args...) fn(args) // TRACEPOINT is not defined in release, so that TRACEPOINTS do not linger in the code unnecessarily #endif // HEY: Maybe debugf and log_call and TRACEPOINT should be placed in // debugf.hpp (and debugf.cc). /* Debugging printing API (prints current thread in addition to message) */ void debug_print_quoted_string(append_only_printf_buffer_t *buf, const uint8_t *s, size_t n); void debugf_prefix_buf(printf_buffer_t<1000> *buf); void debugf_dump_buf(printf_buffer_t<1000> *buf); // Primitive debug_print declarations. void debug_print(append_only_printf_buffer_t *buf, uint64_t x); void debug_print(append_only_printf_buffer_t *buf, const std::string& s); #ifndef NDEBUG void debugf(const char *msg, ...) __attribute__((format (printf, 1, 2))); template <class T> void debugf_print(const char *msg, const T& obj) { printf_buffer_t<1000> buf; debugf_prefix_buf(&buf); buf.appendf("%s: ", msg); debug_print(&buf, obj); buf.appendf("\n"); debugf_dump_buf(&buf); } #else #define debugf(...) ((void)0) #define debugf_print(...) ((void)0) #endif class debugf_in_dtor_t { public: explicit debugf_in_dtor_t(const char *msg, ...); ~debugf_in_dtor_t(); private: std::string message; }; class rng_t { public: // Returns a random number in [0, n). Is not perfectly uniform; the // bias tends to get worse when RAND_MAX is far from a multiple of n. int randint(int n); explicit rng_t(int seed = -1); private: unsigned short xsubi[3]; DISABLE_COPYING(rng_t); }; // Reads from /dev/urandom. Use this sparingly, please. void get_dev_urandom(void *out, int64_t nbytes); int randint(int n); std::string rand_string(int len); bool begins_with_minus(const char *string); // strtoul() and strtoull() will for some reason not fail if the input begins // with a minus sign. strtou64_strict() does. Also we fix the constness of the // end parameter. int64_t strtoi64_strict(const char *string, const char **end, int base); uint64_t strtou64_strict(const char *string, const char **end, int base); // These functions return false and set the result to 0 if the conversion fails or // does not consume the whole string. MUST_USE bool strtoi64_strict(const std::string &str, int base, int64_t *out_result); MUST_USE bool strtou64_strict(const std::string &str, int base, uint64_t *out_result); std::string strprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); std::string vstrprintf(const char *format, va_list ap); // formatted time: // yyyy-mm-ddThh:mm:ss.nnnnnnnnn (29 characters) const size_t formatted_time_length = 29; // not including null void format_time(struct timespec time, append_only_printf_buffer_t *buf); std::string format_time(struct timespec time); struct timespec parse_time(const std::string &str) THROWS_ONLY(std::runtime_error); /* Printing binary data to stdout in a nice format */ void print_hd(const void *buf, size_t offset, size_t length); // Fast string compare int sized_strcmp(const uint8_t *str1, int len1, const uint8_t *str2, int len2); /* The home thread mixin is a mixin for objects that can only be used on a single thread. Its thread ID is exposed as the `home_thread()` method. Some subclasses of `home_thread_mixin_debug_only_t` can move themselves to another thread, modifying the field real_home_thread. */ #define INVALID_THREAD (-1) class home_thread_mixin_debug_only_t { public: #ifndef NDEBUG void assert_thread() const; #else void assert_thread() const { } #endif protected: explicit home_thread_mixin_debug_only_t(int specified_home_thread); home_thread_mixin_debug_only_t(); virtual ~home_thread_mixin_debug_only_t() { } private: DISABLE_COPYING(home_thread_mixin_debug_only_t); #ifndef NDEBUG int real_home_thread; #endif }; class home_thread_mixin_t { public: int home_thread() const { return real_home_thread; } #ifndef NDEBUG void assert_thread() const; #else void assert_thread() const { } #endif protected: explicit home_thread_mixin_t(int specified_home_thread); home_thread_mixin_t(); virtual ~home_thread_mixin_t() { } int real_home_thread; private: // Things with home threads should not be copyable, since we don't // want to nonchalantly copy their real_home_thread variable. DISABLE_COPYING(home_thread_mixin_t); }; /* `on_thread_t` switches to the given thread in its constructor, then switches back in its destructor. For example: printf("Suppose we are on thread 1.\n"); { on_thread_t thread_switcher(2); printf("Now we are on thread 2.\n"); } printf("And now we are on thread 1 again.\n"); */ class on_thread_t : public home_thread_mixin_t { public: explicit on_thread_t(int thread); ~on_thread_t(); }; template <class InputIterator, class UnaryPredicate> bool all_match_predicate(InputIterator begin, InputIterator end, UnaryPredicate f) { bool res = true; for (; begin != end; begin++) { res &= f(*begin); } return res; } template <class T, class UnaryPredicate> bool all_in_container_match_predicate (const T &container, UnaryPredicate f) { return all_match_predicate(container.begin(), container.end(), f); } bool notf(bool x); /* Translates to and from `0123456789ABCDEF`. */ bool hex_to_int(char c, int *out); char int_to_hex(int i); std::string read_file(const char *path); struct path_t { std::vector<std::string> nodes; bool is_absolute; }; path_t parse_as_path(const std::string &); std::string render_as_path(const path_t &); enum region_join_result_t { REGION_JOIN_OK, REGION_JOIN_BAD_JOIN, REGION_JOIN_BAD_REGION }; template <class T> class assignment_sentry_t { public: assignment_sentry_t(T *v, const T &value) : var(v), old_value(*var) { *var = value; } ~assignment_sentry_t() { *var = old_value; } private: T *var; T old_value; }; std::string sanitize_for_logger(const std::string &s); static inline std::string time2str(const time_t &t) { char timebuf[26]; // I apologize for the magic constant. // ^^ See man 3 ctime_r return ctime_r(&t, timebuf); } std::string errno_string(int errsv); int get_num_db_threads(); template <class T> T valgrind_undefined(T value) { #ifdef VALGRIND VALGRIND_MAKE_MEM_UNDEFINED(&value, sizeof(value)); #endif return value; } // A static type for port number values. class portno_t { public: // Unimplemented constructors to snag attempts to pass things other than uint16_t. explicit portno_t(int portno); explicit portno_t(int16_t portno); explicit portno_t(const uint16_t portno) : portno_(portno) { } uint16_t as_uint16() const { return portno_; } uint16_t as_uint16_with_offset(const int port_offset) const { rassert(port_offset >= 0); if (portno_ == 0) { return 0; } else { int ret = portno_ + port_offset; guarantee(ret < 0x10000); return ret; } } private: uint16_t portno_; }; #define STR(x) #x #define MSTR(x) STR(x) // Stringify a macro #if defined __clang__ #define COMPILER "CLANG " __clang_version__ #elif defined __GNUC__ #define COMPILER "GCC " MSTR(__GNUC__) "." MSTR(__GNUC_MINOR__) "." MSTR(__GNUC_PATCHLEVEL__) #else #define COMPILER "UNKNOWN COMPILER" #endif #ifndef NDEBUG #define RETHINKDB_VERSION_STR "rethinkdb " RETHINKDB_VERSION " (debug)" " (" COMPILER ")" #else #define RETHINKDB_VERSION_STR "rethinkdb " RETHINKDB_VERSION " (" COMPILER ")" #endif #define NULLPTR (static_cast<void *>(0)) #endif // UTILS_HPP_ <|endoftext|>
<commit_before>#include "ed.h" utimer::timer_entry::timer_entry (const utime_t &time, u_long interval, lisp fn, int one_shot_p) : te_time (time + interval * utime_t (UNITS_PER_SEC / 1000)), te_interval (interval), te_fn (fn), te_flags (one_shot_p ? (TE_ONE_SHOT | TE_NEW) : TE_NEW) { } utimer::utimer () : t_hwnd (0), t_timer_on (0), t_in_timer (0) { } utimer::~utimer () { while (!t_entries.empty_p ()) delete t_entries.remove_head (); while (!t_defers.empty_p ()) delete t_defers.remove_head (); } void utimer::stop_timer () { if (t_timer_on) { KillTimer (t_hwnd, TID_USER); t_timer_on = 0; } } void utimer::start_timer (const utime_t &t) { stop_timer (); timer_entry *entry = t_entries.head (); if (entry) { utime_t d = (entry->te_time - t) / (timer_entry::UNITS_PER_SEC / 1000); if (d < 0) d = 0; else if (d >= LONG_MAX) d = LONG_MAX; SetTimer (t_hwnd, TID_USER, UINT (d), 0); t_timer_on = 1; } } void utimer::insert (timer_entry *entry) { for (timer_entry *p = t_entries.head (); p; p = p->next ()) if (entry->te_time < p->te_time) { t_entries.insert_before (entry, p); return; } t_entries.add_tail (entry); } void utimer::timer () { stop_timer (); if (t_in_timer) return; t_in_timer = 1; utime_t t; current_time (t); while (1) { timer_entry *entry = t_entries.head (); if (!entry) break; if (entry->te_time > t) break; lisp fn = entry->te_fn; t_entries.remove (entry); if (entry->te_flags & timer_entry::TE_ONE_SHOT) delete entry; else t_defers.add_tail (entry); try {Ffuncall (fn, Qnil);} catch (nonlocal_jump &) {} } t_in_timer = 0; current_time (t); while (!t_defers.empty_p ()) { timer_entry *entry = t_defers.remove_head (); if (entry->te_flags & timer_entry::TE_NEW) entry->te_flags &= ~timer_entry::TE_NEW; else entry->te_time = t + (entry->te_interval * utime_t (timer_entry::UNITS_PER_SEC / 1000)); insert (entry); } start_timer (t); } void utimer::add (u_long interval, lisp fn, int one_shot_p) { utime_t t; current_time (t); timer_entry *entry = new timer_entry (t, interval, fn, one_shot_p); if (t_in_timer) t_defers.add_tail (entry); else { insert (entry); start_timer (t); } } int utimer::remove (xlist <timer_entry> &list, lisp fn) { for (timer_entry *p = list.head (); p; p = p->next ()) if (p->te_fn == fn) { delete list.remove (p); return 1; } return 0; } int utimer::remove (lisp fn) { if (!remove (t_entries, fn) && !remove (t_defers, fn)) return 0; if (!t_in_timer) { utime_t t; current_time (t); start_timer (t); } return 1; } void utimer::gc_mark (void (*f)(lisp)) { timer_entry *p = t_entries.head (); for (; p; p = p->next ()) (*f)(p->te_fn); for (p = t_defers.head (); p; p = p->next ()) (*f)(p->te_fn); } lisp Fstart_timer (lisp linterval, lisp lfn, lisp lone_shot_p) { double interval (coerce_to_double_float (linterval) * 1000); if (interval < 0 || interval > LONG_MAX) FErange_error (linterval); active_app_frame().user_timer.add (u_long (interval), lfn, lone_shot_p && lone_shot_p != Qnil); return Qt; } lisp Fstop_timer (lisp fn) { return boole (active_app_frame().user_timer.remove (fn)); } <commit_msg>xyzzy.src : fix start-timer.<commit_after>#include "ed.h" utimer::timer_entry::timer_entry (const utime_t &time, u_long interval, lisp fn, int one_shot_p) : te_time (time + interval * utime_t (UNITS_PER_SEC / 1000)), te_interval (interval), te_fn (fn), te_flags (one_shot_p ? (TE_ONE_SHOT | TE_NEW) : TE_NEW) { } utimer::utimer () : t_hwnd (0), t_timer_on (0), t_in_timer (0) { } utimer::~utimer () { while (!t_entries.empty_p ()) delete t_entries.remove_head (); while (!t_defers.empty_p ()) delete t_defers.remove_head (); } void utimer::stop_timer () { if (t_timer_on) { KillTimer (t_hwnd, TID_USER); t_timer_on = 0; } } void utimer::start_timer (const utime_t &t) { stop_timer (); timer_entry *entry = t_entries.head (); if (entry) { utime_t d = (entry->te_time - t) / (timer_entry::UNITS_PER_SEC / 1000); if (d < 0) d = 0; else if (d >= LONG_MAX) d = LONG_MAX; SetTimer (t_hwnd, TID_USER, UINT (d), 0); t_timer_on = 1; } } void utimer::insert (timer_entry *entry) { for (timer_entry *p = t_entries.head (); p; p = p->next ()) if (entry->te_time < p->te_time) { t_entries.insert_before (entry, p); return; } t_entries.add_tail (entry); } void utimer::timer () { stop_timer (); if (t_in_timer) return; t_in_timer = 1; utime_t t; current_time (t); while (1) { timer_entry *entry = t_entries.head (); if (!entry) break; if (entry->te_time > t) break; lisp fn = entry->te_fn; t_entries.remove (entry); if (entry->te_flags & timer_entry::TE_ONE_SHOT) delete entry; else t_defers.add_tail (entry); try {Ffuncall (fn, Qnil);} catch (nonlocal_jump &) {} } t_in_timer = 0; current_time (t); while (!t_defers.empty_p ()) { timer_entry *entry = t_defers.remove_head (); if (entry->te_flags & timer_entry::TE_NEW) entry->te_flags &= ~timer_entry::TE_NEW; entry->te_time = t + (entry->te_interval * utime_t (timer_entry::UNITS_PER_SEC / 1000)); insert (entry); } start_timer (t); } void utimer::add (u_long interval, lisp fn, int one_shot_p) { utime_t t; current_time (t); timer_entry *entry = new timer_entry (t, interval, fn, one_shot_p); if (t_in_timer) t_defers.add_tail (entry); else { insert (entry); start_timer (t); } } int utimer::remove (xlist <timer_entry> &list, lisp fn) { for (timer_entry *p = list.head (); p; p = p->next ()) if (p->te_fn == fn) { delete list.remove (p); return 1; } return 0; } int utimer::remove (lisp fn) { if (!remove (t_entries, fn) && !remove (t_defers, fn)) return 0; if (!t_in_timer) { utime_t t; current_time (t); start_timer (t); } return 1; } void utimer::gc_mark (void (*f)(lisp)) { timer_entry *p = t_entries.head (); for (; p; p = p->next ()) (*f)(p->te_fn); for (p = t_defers.head (); p; p = p->next ()) (*f)(p->te_fn); } lisp Fstart_timer (lisp linterval, lisp lfn, lisp lone_shot_p) { double interval (coerce_to_double_float (linterval) * 1000); if (interval < 0 || interval > LONG_MAX) FErange_error (linterval); active_app_frame().user_timer.add (u_long (interval), lfn, lone_shot_p && lone_shot_p != Qnil); return Qt; } lisp Fstop_timer (lisp fn) { return boole (active_app_frame().user_timer.remove (fn)); } <|endoftext|>
<commit_before>// Copyright (c) 2011, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // STL #include <memory> #include <string> // po6 #include <po6/net/ipaddr.h> #include <po6/net/location.h> // e #include <e/convert.h> #include <e/timer.h> // HyperDex #include <hyperclient/client.h> const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32"}; static int usage(); void handle_put(hyperclient::returncode ret) { if (ret != hyperclient::SUCCESS) { std::cerr << "Put returned " << ret << "." << std::endl; } } void handle_search(size_t* count, const e::buffer& expected_key, hyperclient::returncode ret, const e::buffer& key, const std::vector<e::buffer>& value) { ++*count; if (*count > 1) { std::cerr << "Search returned more than 1 result." << std::endl; } if (expected_key != key) { std::cerr << "Search returned unexpected key: " << expected_key.hex() << " != " << key.hex() << std::endl; } } int main(int argc, char* argv[]) { if (argc != 5) { return usage(); } po6::net::ipaddr ip; uint16_t port; std::string space = argv[3]; uint32_t numbers; try { ip = argv[1]; } catch (std::invalid_argument& e) { std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl; return EXIT_FAILURE; } try { port = e::convert::to_uint16_t(argv[2]); } catch (std::domain_error& e) { std::cerr << "The port number must be an integer." << std::endl; return EXIT_FAILURE; } catch (std::out_of_range& e) { std::cerr << "The port number must be suitably small." << std::endl; return EXIT_FAILURE; } try { numbers = e::convert::to_uint32_t(argv[4]); } catch (std::domain_error& e) { std::cerr << "The number must be an integer." << std::endl; return EXIT_FAILURE; } catch (std::out_of_range& e) { std::cerr << "The number must be suitably small." << std::endl; return EXIT_FAILURE; } try { hyperclient::client cl(po6::net::location(ip, port)); cl.connect(); e::buffer one("one", 3); e::buffer zero("zero", 3); for (uint32_t num = 0; num < numbers; ++num) { e::buffer key; key.pack() << num; std::vector<e::buffer> value; for (size_t i = 0; i < 32; ++i) { value.push_back(e::buffer()); if ((num & (1 << i))) { value.back() = one; } else { value.back() = zero; } } cl.put(space, key, value, handle_put); if (cl.outstanding() > 10000) { cl.flush(-1); } } cl.flush(-1); e::sleep_ms(1, 0); std::cerr << "Starting searches." << std::endl; timespec start; timespec end; clock_gettime(CLOCK_REALTIME, &start); for (uint32_t num = 0; num < numbers; ++num) { e::buffer key; key.pack() << num; std::map<std::string, e::buffer> search; for (size_t i = 0; i < 32; ++i) { if ((num & (1 << i))) { search.insert(std::make_pair(colnames[i], one)); } else { search.insert(std::make_pair(colnames[i], zero)); } } using std::tr1::bind; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; size_t count = 0; cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3)); cl.flush(-1); } clock_gettime(CLOCK_REALTIME, &end); timespec diff; if ((end.tv_nsec < start.tv_nsec) < 0) { diff.tv_sec = end.tv_sec - start.tv_sec - 1; diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; } else { diff.tv_sec = end.tv_sec - start.tv_sec; diff.tv_nsec = end.tv_nsec - start.tv_nsec; } uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec; std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl; } catch (po6::error& e) { std::cerr << "There was a system error: " << e.what(); return EXIT_FAILURE; } catch (std::runtime_error& e) { std::cerr << "There was a runtime error: " << e.what(); return EXIT_FAILURE; } catch (std::bad_alloc& e) { std::cerr << "There was a memory allocation error: " << e.what(); return EXIT_FAILURE; } catch (std::exception& e) { std::cerr << "There was a generic error: " << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } int usage() { std::cerr << "Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\n" << "This will create <numbers> points whose key is a number [0, <numbers>) and " << "then perform searches over the bits of the number. The space should have 32 " << "secondary dimensions so that all bits of a number may be stored." << std::endl; return EXIT_FAILURE; } <commit_msg>Flush every 1000 PUTs in binary-test.cc<commit_after>// Copyright (c) 2011, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // STL #include <memory> #include <string> // po6 #include <po6/net/ipaddr.h> #include <po6/net/location.h> // e #include <e/convert.h> #include <e/timer.h> // HyperDex #include <hyperclient/client.h> const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32"}; static int usage(); void handle_put(hyperclient::returncode ret) { if (ret != hyperclient::SUCCESS) { std::cerr << "Put returned " << ret << "." << std::endl; } } void handle_search(size_t* count, const e::buffer& expected_key, hyperclient::returncode ret, const e::buffer& key, const std::vector<e::buffer>& value) { ++*count; if (*count > 1) { std::cerr << "Search returned more than 1 result." << std::endl; } if (expected_key != key) { std::cerr << "Search returned unexpected key: " << expected_key.hex() << " != " << key.hex() << std::endl; } } int main(int argc, char* argv[]) { if (argc != 5) { return usage(); } po6::net::ipaddr ip; uint16_t port; std::string space = argv[3]; uint32_t numbers; try { ip = argv[1]; } catch (std::invalid_argument& e) { std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl; return EXIT_FAILURE; } try { port = e::convert::to_uint16_t(argv[2]); } catch (std::domain_error& e) { std::cerr << "The port number must be an integer." << std::endl; return EXIT_FAILURE; } catch (std::out_of_range& e) { std::cerr << "The port number must be suitably small." << std::endl; return EXIT_FAILURE; } try { numbers = e::convert::to_uint32_t(argv[4]); } catch (std::domain_error& e) { std::cerr << "The number must be an integer." << std::endl; return EXIT_FAILURE; } catch (std::out_of_range& e) { std::cerr << "The number must be suitably small." << std::endl; return EXIT_FAILURE; } try { hyperclient::client cl(po6::net::location(ip, port)); cl.connect(); e::buffer one("one", 3); e::buffer zero("zero", 3); for (uint32_t num = 0; num < numbers; ++num) { e::buffer key; key.pack() << num; std::vector<e::buffer> value; for (size_t i = 0; i < 32; ++i) { value.push_back(e::buffer()); if ((num & (1 << i))) { value.back() = one; } else { value.back() = zero; } } cl.put(space, key, value, handle_put); if (cl.outstanding() > 1000) { cl.flush(-1); } } cl.flush(-1); e::sleep_ms(1, 0); std::cerr << "Starting searches." << std::endl; timespec start; timespec end; clock_gettime(CLOCK_REALTIME, &start); for (uint32_t num = 0; num < numbers; ++num) { e::buffer key; key.pack() << num; std::map<std::string, e::buffer> search; for (size_t i = 0; i < 32; ++i) { if ((num & (1 << i))) { search.insert(std::make_pair(colnames[i], one)); } else { search.insert(std::make_pair(colnames[i], zero)); } } using std::tr1::bind; using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; size_t count = 0; cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3)); cl.flush(-1); } clock_gettime(CLOCK_REALTIME, &end); timespec diff; if ((end.tv_nsec < start.tv_nsec) < 0) { diff.tv_sec = end.tv_sec - start.tv_sec - 1; diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec; } else { diff.tv_sec = end.tv_sec - start.tv_sec; diff.tv_nsec = end.tv_nsec - start.tv_nsec; } uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec; std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl; } catch (po6::error& e) { std::cerr << "There was a system error: " << e.what(); return EXIT_FAILURE; } catch (std::runtime_error& e) { std::cerr << "There was a runtime error: " << e.what(); return EXIT_FAILURE; } catch (std::bad_alloc& e) { std::cerr << "There was a memory allocation error: " << e.what(); return EXIT_FAILURE; } catch (std::exception& e) { std::cerr << "There was a generic error: " << e.what(); return EXIT_FAILURE; } return EXIT_SUCCESS; } int usage() { std::cerr << "Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\n" << "This will create <numbers> points whose key is a number [0, <numbers>) and " << "then perform searches over the bits of the number. The space should have 32 " << "secondary dimensions so that all bits of a number may be stored." << std::endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <[email protected]> // // Self #include "PluginItemDelegate.h" // Marble #include "RenderPlugin.h" #include "PluginModelItem.h" // Qt #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtGui/QAbstractItemView> #include <QtGui/QStandardItemModel> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QStandardItem> using namespace Marble; PluginItemDelegate::PluginItemDelegate( QAbstractItemView *itemView, QObject * parent ) : QStyledItemDelegate( parent ), m_itemView( itemView ) { connect( itemView, SIGNAL( clicked( QModelIndex ) ), SLOT( handleClickEvent( const QModelIndex& ) ) ); } PluginItemDelegate::~PluginItemDelegate() { } void PluginItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { Q_ASSERT(index.isValid()); // TODO: Do background rendering, implement clicking on buttons, add configure button. QRect rect = option.rect; painter->save(); painter->translate( rect.topLeft() ); // Painting the checkbox QStyleOptionButton checkboxOption; if ( index.data( Qt::CheckStateRole ).toBool() ) checkboxOption.state = option.state | QStyle::State_On; else checkboxOption.state = option.state | QStyle::State_Off; checkboxOption.rect.setTopLeft( QPoint( 0, 0 ) ); checkboxOption.rect.setSize( QSize( rect.height(), rect.height() ) ); painter->save(); QApplication::style()->drawControl( QStyle::CE_CheckBox, &checkboxOption, painter ); painter->restore(); painter->translate( checkboxOption.rect.width(), 0 ); // Painting the Name string QString name = index.data( Qt::DisplayRole ).toString(); QRect nameRect( QPoint( 0, 0 ), QApplication::fontMetrics().size( 0, name ) ); nameRect.setHeight( rect.height() ); QApplication::style()->drawItemText( painter, nameRect, Qt::AlignLeft | Qt::AlignVCenter, option.palette, false, name ); painter->translate( nameRect.width(), 0 ); // Painting the About Button if ( /*index.data( RenderPlugin::AboutDialogAvailable ).toBool()*/ true ) { QStyleOptionButton buttonOption; buttonOption.state = option.state; buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.rect.setTopLeft( QPoint( 0, 0 ) ); buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; buttonOption.text = tr( "About" ); buttonOption.state = option.state; QSize aboutSize = buttonOption.fontMetrics.size( 0, buttonOption.text ) + QSize( 4, 4 ); QSize aboutButtonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &buttonOption, aboutSize ); buttonOption.rect.setWidth( aboutButtonSize.width() ); buttonOption.rect.setHeight( rect.height() ); QApplication::style()->drawControl( QStyle::CE_PushButton, &buttonOption, painter ); painter->translate( aboutButtonSize.width(), 0 ); } painter->restore(); } QSize PluginItemDelegate::sizeHint( const QStyleOptionViewItem& option, const QModelIndex & index ) const { QSize sz = QStyledItemDelegate::sizeHint(option, index) + QSize( 4, 4 ); return sz; } void PluginItemDelegate::handleClickEvent( const QModelIndex& ) { // TODO: Click handling. } #include "PluginItemDelegate.moc" <commit_msg>Removing a not existing header file from the includes of Marble PluginItemDelegate.<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2009 Bastian Holst <[email protected]> // // Self #include "PluginItemDelegate.h" // Marble #include "RenderPlugin.h" // Qt #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtGui/QAbstractItemView> #include <QtGui/QStandardItemModel> #include <QtGui/QApplication> #include <QtGui/QPainter> #include <QtGui/QStandardItem> using namespace Marble; PluginItemDelegate::PluginItemDelegate( QAbstractItemView *itemView, QObject * parent ) : QStyledItemDelegate( parent ), m_itemView( itemView ) { connect( itemView, SIGNAL( clicked( QModelIndex ) ), SLOT( handleClickEvent( const QModelIndex& ) ) ); } PluginItemDelegate::~PluginItemDelegate() { } void PluginItemDelegate::paint( QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const { Q_ASSERT(index.isValid()); // TODO: Do background rendering, implement clicking on buttons, add configure button. QRect rect = option.rect; painter->save(); painter->translate( rect.topLeft() ); // Painting the checkbox QStyleOptionButton checkboxOption; if ( index.data( Qt::CheckStateRole ).toBool() ) checkboxOption.state = option.state | QStyle::State_On; else checkboxOption.state = option.state | QStyle::State_Off; checkboxOption.rect.setTopLeft( QPoint( 0, 0 ) ); checkboxOption.rect.setSize( QSize( rect.height(), rect.height() ) ); painter->save(); QApplication::style()->drawControl( QStyle::CE_CheckBox, &checkboxOption, painter ); painter->restore(); painter->translate( checkboxOption.rect.width(), 0 ); // Painting the Name string QString name = index.data( Qt::DisplayRole ).toString(); QRect nameRect( QPoint( 0, 0 ), QApplication::fontMetrics().size( 0, name ) ); nameRect.setHeight( rect.height() ); QApplication::style()->drawItemText( painter, nameRect, Qt::AlignLeft | Qt::AlignVCenter, option.palette, false, name ); painter->translate( nameRect.width(), 0 ); // Painting the About Button if ( /*index.data( RenderPlugin::AboutDialogAvailable ).toBool()*/ true ) { QStyleOptionButton buttonOption; buttonOption.state = option.state; buttonOption.state &= ~QStyle::State_HasFocus; buttonOption.rect.setTopLeft( QPoint( 0, 0 ) ); buttonOption.palette = option.palette; buttonOption.features = QStyleOptionButton::None; buttonOption.text = tr( "About" ); buttonOption.state = option.state; QSize aboutSize = buttonOption.fontMetrics.size( 0, buttonOption.text ) + QSize( 4, 4 ); QSize aboutButtonSize = QApplication::style()->sizeFromContents( QStyle::CT_PushButton, &buttonOption, aboutSize ); buttonOption.rect.setWidth( aboutButtonSize.width() ); buttonOption.rect.setHeight( rect.height() ); QApplication::style()->drawControl( QStyle::CE_PushButton, &buttonOption, painter ); painter->translate( aboutButtonSize.width(), 0 ); } painter->restore(); } QSize PluginItemDelegate::sizeHint( const QStyleOptionViewItem& option, const QModelIndex & index ) const { QSize sz = QStyledItemDelegate::sizeHint(option, index) + QSize( 4, 4 ); return sz; } void PluginItemDelegate::handleClickEvent( const QModelIndex& ) { // TODO: Click handling. } #include "PluginItemDelegate.moc" <|endoftext|>
<commit_before>/* * Header-only library abstracting some filesystem properties. */ #ifndef MODTOOLS_COMPAT_FS_HPP #define MODTOOLS_COMPAT_FS_HPP #include "modtools_compat/common.hpp" #include "modtools_compat/posix.hpp" #include <string> #include <algorithm> #include <iterator> #include <cassert> #include <cstdlib> #ifndef PATH_MAX # define PATH_MAX 65536 #endif namespace Compat { #ifdef IS_UNIX # define DIR_SEP_MACRO '/' # define DIR_SEP_STR_MACRO "/" #else # define DIR_SEP_MACRO '\\' # define DIR_SEP_STR_MACRO "\\" #endif #if !defined(S_ISDIR) # error "The POSIX macro S_ISDIR is not defined." #endif static const char DIRECTORY_SEPARATOR = DIR_SEP_MACRO; static const char DUAL_DIRECTORY_SEPARATOR = (DIRECTORY_SEPARATOR == '/' ? '\\' : '/'); class Path : public std::string { public: typedef struct stat stat_t; static const char SEPARATOR = DIRECTORY_SEPARATOR; std::string& toString() { return static_cast<std::string&>(*this); } const std::string& toString() const { return static_cast<const std::string&>(*this); } private: static void normalizeDirSeps(std::string& str, size_t offset = 0) { std::string::iterator _begin = str.begin(); std::advance(_begin, offset); std::replace(_begin, str.end(), DUAL_DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); } /* * Skips extra slashes in a normalized string. * Receives begin and end iterators, modifying them * to the actual range. */ static void skip_extra_slashes(std::string::const_iterator& begin, std::string::const_iterator& end) { if(begin == end) return; const size_t len = static_cast<size_t>( std::distance(begin, end) ); const std::string::const_iterator real_end = end; // It points to the last character, for now. end = begin; std::advance(end, len - 1); for(; begin != real_end && *begin == DIRECTORY_SEPARATOR; ++begin); for(; end != begin && *end == DIRECTORY_SEPARATOR; --end); ++end; } int inner_stat(stat_t& buf) const { if(empty()) return -1; return ::stat(this->c_str(), &buf); } size_t get_extension_position() const { const size_t dot_pos = find_last_of('.'); const size_t last_sep_pos = find_last_of(SEPARATOR); if(dot_pos == npos || (last_sep_pos != npos && dot_pos < last_sep_pos)) { return npos; } else { return dot_pos + 1; } } public: bool stat(stat_t& buf) const { if(inner_stat(buf)) { buf = stat_t(); return false; } return true; } stat_t stat() const { stat_t buf; stat(buf); return buf; } bool isDirectory() const { stat_t buf; return stat(buf) && S_ISDIR(buf.st_mode); } /* * Appends a string, preceded by a directory separator if necessary. */ Path& appendPath(std::string str) { if(str.length() == 0) return *this; normalizeDirSeps(str); const size_t old_len = this->length(); if(old_len != 0 || str[0] == DIRECTORY_SEPARATOR) { std::string::append(1, DIRECTORY_SEPARATOR); } std::string::const_iterator _begin, _end; _begin = str.begin(); _end = str.end(); skip_extra_slashes(_begin, _end); std::string::append(_begin, _end); return *this; } Path& assignPath(const std::string& str) { std::string::clear(); return appendPath(str); } Path& operator=(const std::string& str) { return assignPath(str); } Path& operator=(const char *str) { return assignPath(str); } Path& operator=(const Path& p) { std::string::assign(p); return *this; } void makeAbsolute() { #if IS_UNIX char resolved_path[PATH_MAX]; if( realpath(c_str(), resolved_path) != NULL ) { assignPath(resolved_path); } #endif } Path(const std::string& str) : std::string() { *this = str; } Path(const char* str) : std::string() { *this = str; } Path(const Path& p) : std::string() { *this = p; } Path() {} Path copy() const { return Path(*this); } Path& operator+=(const std::string& str) { std::string::append(str); return *this; } Path& operator+=(const char *str) { std::string::append(str); return *this; } Path operator+(const std::string& str) const { return this->copy() += str; } Path operator+(const char *str) const { return this->copy() += str; } Path& operator/=(const std::string& str) { return appendPath(str); } Path& operator/=(const char *str) { return appendPath(str); } Path operator/(const std::string& str) const { return this->copy() /= str; } Path operator/(const char *str) const { return this->copy() /= str; } /* * Splits the path into directory and file parts. * * The "directory part" accounts for everything until the last * separator (not including the separator itself). If no separator * exists, the directory will be ".". * * The directory part DOES NOT include a trailing slash. */ void split(std::string& dir, std::string& base) const { assert( length() > 0 ); const size_t last_sep = find_last_of(DIRECTORY_SEPARATOR); if(last_sep == 0 && length() == 1) { // Root directory (so Unix). dir = "/"; base = "/"; return; } if(last_sep == npos) { dir = "."; base = *this; } else { dir = substr(0, last_sep); base = substr(last_sep + 1); } } Path dirname() const { Path dir, base; split(dir, base); return dir; } // With trailing slash. Path dirnameWithSlash() const { Path p = dirname(); if(p != "/") { p.append(1, DIRECTORY_SEPARATOR); } return p; } Path basename() const { Path dir, base; split(dir, base); return base; } std::string getExtension() const { const size_t start = get_extension_position(); if(start == npos) { return ""; } else { return substr(start); } } Path& replaceExtension(const std::string& newext) { const size_t start = get_extension_position(); if(start == npos) { std::string::append(1, '.'); } else { std::string::erase(start); } std::string::append(newext); return *this; } Path& removeExtension() { const size_t start = get_extension_position(); if(start != npos) { assert( start >= 1 ); std::string::erase(start - 1); } return *this; } bool exists() const { stat_t buf; return inner_stat(buf) == 0; } operator bool() const { return exists(); } /* * If p doesn't exist and *this does, returns true. * Likewise, if *this doesn't exist and p does, returns false. */ bool isNewerThan(const Path& p) const { stat_t mybuf, otherbuf; stat(mybuf); p.stat(otherbuf); if(mybuf.st_mtime > otherbuf.st_mtime) { return true; } else if(mybuf.st_mtime == otherbuf.st_mtime) { // Compares nanoseconds under Unix. #if defined(IS_LINUX) return mybuf.st_mtim.tv_nsec > otherbuf.st_mtim.tv_nsec; #elif defined(IS_MAC) return mybuf.st_mtimespec.tv_nsec > otherbuf.st_mtimespec.tv_nsec; #endif } else { return false; } } bool isOlderThan(const Path& p) const { return p.isNewerThan(*this); } }; } #endif <commit_msg>some more fixes<commit_after>/* * Header-only library abstracting some filesystem properties. */ #ifndef MODTOOLS_COMPAT_FS_HPP #define MODTOOLS_COMPAT_FS_HPP #include "modtools_compat/common.hpp" #include "modtools_compat/posix.hpp" #include <string> #include <algorithm> #include <iterator> #include <cassert> #include <cstdlib> #ifndef PATH_MAX # define PATH_MAX 65536 #endif namespace Compat { #ifdef IS_UNIX # define DIR_SEP_MACRO '/' # define DIR_SEP_STR_MACRO "/" #else # define DIR_SEP_MACRO '\\' # define DIR_SEP_STR_MACRO "\\" #endif #if !defined(S_ISDIR) # error "The POSIX macro S_ISDIR is not defined." #endif static const char DIRECTORY_SEPARATOR = DIR_SEP_MACRO; static const char DUAL_DIRECTORY_SEPARATOR = (DIRECTORY_SEPARATOR == '/' ? '\\' : '/'); class Path : public std::string { public: typedef struct stat stat_t; static const char SEPARATOR = DIRECTORY_SEPARATOR; std::string& toString() { return static_cast<std::string&>(*this); } const std::string& toString() const { return static_cast<const std::string&>(*this); } private: static void normalizeDirSeps(std::string& str, size_t offset = 0) { std::string::iterator _begin = str.begin(); std::advance(_begin, offset); std::replace(_begin, str.end(), DUAL_DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); } /* * Skips extra slashes in a normalized string. * Receives begin and end iterators, modifying them * to the actual range. */ static void skip_extra_slashes(std::string::const_iterator& begin, std::string::const_iterator& end) { if(begin == end) return; const size_t len = static_cast<size_t>( std::distance(begin, end) ); const std::string::const_iterator real_end = end; // It points to the last character, for now. end = begin; std::advance(end, len - 1); for(; begin != real_end && *begin == DIRECTORY_SEPARATOR; ++begin); for(; end != begin && *end == DIRECTORY_SEPARATOR; --end); ++end; } int inner_stat(stat_t& buf) const { if(empty()) return -1; return ::stat(this->c_str(), &buf); } size_t get_extension_position() const { const size_t dot_pos = find_last_of('.'); const size_t last_sep_pos = find_last_of(SEPARATOR); if(dot_pos == npos || (last_sep_pos != npos && dot_pos < last_sep_pos)) { return npos; } else { return dot_pos + 1; } } public: bool stat(stat_t& buf) const { if(inner_stat(buf)) { buf = stat_t(); return false; } return true; } stat_t stat() const { stat_t buf; stat(buf); return buf; } bool isDirectory() const { stat_t buf; return stat(buf) && S_ISDIR(buf.st_mode); } /* * Appends a string, preceded by a directory separator if necessary. */ Path& appendPath(std::string str) { if(str.length() == 0) return *this; normalizeDirSeps(str); const size_t old_len = this->length(); if(old_len != 0 || str[0] == DIRECTORY_SEPARATOR) { std::string::append(1, DIRECTORY_SEPARATOR); } std::string::const_iterator _begin, _end; _begin = str.begin(); _end = str.end(); skip_extra_slashes(_begin, _end); std::string::append(_begin, _end); return *this; } Path& assignPath(const std::string& str) { std::string::clear(); return appendPath(str); } Path& operator=(const std::string& str) { return assignPath(str); } Path& operator=(const char *str) { return assignPath(str); } Path& operator=(const Path& p) { std::string::assign(p); return *this; } void makeAbsolute() { #ifdef IS_UNIX char resolved_path[PATH_MAX]; if( realpath(c_str(), resolved_path) != NULL ) { assignPath(resolved_path); } #endif } Path(const std::string& str) : std::string() { *this = str; } Path(const char* str) : std::string() { *this = str; } Path(const Path& p) : std::string() { *this = p; } Path() {} Path copy() const { return Path(*this); } Path& operator+=(const std::string& str) { std::string::append(str); return *this; } Path& operator+=(const char *str) { std::string::append(str); return *this; } Path operator+(const std::string& str) const { return this->copy() += str; } Path operator+(const char *str) const { return this->copy() += str; } Path& operator/=(const std::string& str) { return appendPath(str); } Path& operator/=(const char *str) { return appendPath(str); } Path operator/(const std::string& str) const { return this->copy() /= str; } Path operator/(const char *str) const { return this->copy() /= str; } /* * Splits the path into directory and file parts. * * The "directory part" accounts for everything until the last * separator (not including the separator itself). If no separator * exists, the directory will be ".". * * The directory part DOES NOT include a trailing slash. */ void split(std::string& dir, std::string& base) const { assert( length() > 0 ); const size_t last_sep = find_last_of(DIRECTORY_SEPARATOR); if(last_sep == 0 && length() == 1) { // Root directory (so Unix). dir = "/"; base = "/"; return; } if(last_sep == npos) { dir = "."; base = *this; } else { dir = substr(0, last_sep); base = substr(last_sep + 1); } } Path dirname() const { Path dir, base; split(dir, base); return dir; } // With trailing slash. Path dirnameWithSlash() const { Path p = dirname(); if(p != "/") { p.append(1, DIRECTORY_SEPARATOR); } return p; } Path basename() const { Path dir, base; split(dir, base); return base; } std::string getExtension() const { const size_t start = get_extension_position(); if(start == npos) { return ""; } else { return substr(start); } } Path& replaceExtension(const std::string& newext) { const size_t start = get_extension_position(); if(start == npos) { std::string::append(1, '.'); } else { std::string::erase(start); } std::string::append(newext); return *this; } Path& removeExtension() { const size_t start = get_extension_position(); if(start != npos) { assert( start >= 1 ); std::string::erase(start - 1); } return *this; } bool exists() const { stat_t buf; return inner_stat(buf) == 0; } operator bool() const { return exists(); } /* * If p doesn't exist and *this does, returns true. * Likewise, if *this doesn't exist and p does, returns false. */ bool isNewerThan(const Path& p) const { stat_t mybuf, otherbuf; stat(mybuf); p.stat(otherbuf); if(mybuf.st_mtime > otherbuf.st_mtime) { return true; } else if(mybuf.st_mtime == otherbuf.st_mtime) { // Compares nanoseconds under Unix. #if defined(IS_LINUX) return mybuf.st_mtim.tv_nsec > otherbuf.st_mtim.tv_nsec; #elif defined(IS_MAC) return mybuf.st_mtimespec.tv_nsec > otherbuf.st_mtimespec.tv_nsec; #endif } else { return false; } } bool isOlderThan(const Path& p) const { return p.isNewerThan(*this); } }; } #endif <|endoftext|>
<commit_before>#pragma once #include <appbase/application.hpp> #include <eos/chain/chain_controller.hpp> #include <eos/chain/key_value_object.hpp> #include <eos/chain/account_object.hpp> #include <eos/types/AbiSerializer.hpp> #include <eos/database_plugin/database_plugin.hpp> namespace fc { class variant; } namespace eos { using eos::chain::chain_controller; using std::unique_ptr; using namespace appbase; using chain::Name; using fc::optional; using chain::uint128_t; namespace chain_apis { struct empty{}; class read_only { const chain_controller& db; const string KEYi64 = "i64"; const string KEYi128i128 = "i128i128"; const string KEYi64i64i64 = "i64i64i64"; const string PRIMARY = "primary"; const string SECONDARY = "secondary"; const string TERTIARY = "tertiary"; public: read_only(const chain_controller& db) : db(db) {} using get_info_params = empty; struct get_info_results { uint32_t head_block_num = 0; uint32_t last_irreversible_block_num = 0; chain::block_id_type head_block_id; fc::time_point_sec head_block_time; types::AccountName head_block_producer; string recent_slots; double participation_rate = 0; }; get_info_results get_info(const get_info_params&) const; struct producer_info { Name name; }; struct get_account_results { Name name; uint64_t eos_balance = 0; uint64_t staked_balance = 0; uint64_t unstaking_balance = 0; fc::time_point_sec last_unstaking_time; optional<producer_info> producer; optional<types::Abi> abi; }; struct get_account_params { Name name; }; get_account_results get_account( const get_account_params& params )const; struct abi_json_to_bin_params { Name code; Name action; fc::variant args; }; struct abi_json_to_bin_result { vector<char> binargs; vector<Name> required_scope; vector<Name> required_auth; }; abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const; struct abi_bin_to_json_params { Name code; Name action; vector<char> binargs; }; struct abi_bin_to_json_result { fc::variant args; vector<Name> required_scope; vector<Name> required_auth; }; abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const; struct get_block_params { string block_num_or_id; }; struct get_block_results : public chain::signed_block { get_block_results( const chain::signed_block& b ) :signed_block(b), id(b.id()), block_num(b.block_num()), refBlockPrefix( id._hash[1] ) {} chain::block_id_type id; uint32_t block_num = 0; uint32_t refBlockPrefix = 0; }; get_block_results get_block(const get_block_params& params) const; struct get_table_rows_params { bool json = false; Name scope; Name code; Name table; string table_type; string table_key; string lower_bound; string upper_bound; uint32_t limit = 10; }; struct get_table_rows_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object bool more; ///< true if last element in data is not the end and sizeof data() < limit }; get_table_rows_result get_table_rows( const get_table_rows_params& params )const; void copy_row(const chain::key_value_object& obj, vector<char>& data)const { data.resize( sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::key128x128_value_object& obj, vector<char>& data)const { data.resize( 2*sizeof(uint128_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint128_t) ); memcpy( data.data()+sizeof(uint128_t), &obj.secondary_key, sizeof(uint128_t) ); memcpy( data.data()+2*sizeof(uint128_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::key64x64x64_value_object& obj, vector<char>& data)const { data.resize( 3*sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), &obj.secondary_key, sizeof(uint64_t) ); memcpy( data.data()+2*sizeof(uint64_t), &obj.tertiary_key, sizeof(uint64_t) ); memcpy( data.data()+3*sizeof(uint64_t), obj.value.data(), obj.value.size() ); } template <typename IndexType, typename Scope> read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p )const { read_only::get_table_rows_result result; const auto& d = db.get_database(); const auto& code_account = d.get<chain::account_object,chain::by_name>( p.code ); types::AbiSerializer abis; if( code_account.abi.size() > 4 ) { /// 4 == packsize of empty Abi eos::types::Abi abi; fc::datastream<const char*> ds( code_account.abi.data(), code_account.abi.size() ); fc::raw::unpack( ds, abi ); abis.setAbi( abi ); } const auto& idx = d.get_index<IndexType, Scope>(); auto lower = idx.lower_bound( boost::make_tuple(p.scope, p.code, p.table, boost::lexical_cast<typename IndexType::value_type::key_type>(p.lower_bound)) ); auto upper = idx.upper_bound( boost::make_tuple(p.scope, p.code, p.table, boost::lexical_cast<typename IndexType::value_type::key_type>(p.upper_bound)) ); vector<char> data; auto start = fc::time_point::now(); auto end = fc::time_point::now() + fc::microseconds( 1000*10 ); /// 10ms max time int count = 0; auto itr = lower; for( itr = lower; itr != upper && itr->table == p.table; ++itr ) { copy_row(*itr, data); if( p.json ) result.rows.emplace_back( abis.binaryToVariant( abis.getTableType(p.table), data ) ); else result.rows.emplace_back( fc::variant(data) ); if( ++count == p.limit || fc::time_point::now() > end ) break; } if( itr != upper ) result.more = true; return result; } }; class read_write { chain_controller& db; uint32_t skip_flags; public: read_write(chain_controller& db, uint32_t skip_flags) : db(db), skip_flags(skip_flags) {} using push_block_params = chain::signed_block; using push_block_results = empty; push_block_results push_block(const push_block_params& params); using push_transaction_params = chain::SignedTransaction; struct push_transaction_results { chain::transaction_id_type transaction_id; fc::variant processed; }; push_transaction_results push_transaction(const push_transaction_params& params); }; } // namespace chain_apis class chain_plugin : public plugin<chain_plugin> { public: APPBASE_PLUGIN_REQUIRES((database_plugin)) chain_plugin(); virtual ~chain_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain()); } chain_apis::read_write get_read_write_api(); bool accept_block(const chain::signed_block& block, bool currently_syncing); void accept_transaction(const chain::SignedTransaction& trx); bool block_is_on_preferred_chain(const chain::block_id_type& block_id); // return true if --skip-transaction-signatures passed to eosd bool is_skipping_transaction_signatures() const; // Only call this after plugin_startup()! chain_controller& chain(); // Only call this after plugin_startup()! const chain_controller& chain() const; void get_chain_id (chain::chain_id_type &cid) const; private: unique_ptr<class chain_plugin_impl> my; }; } FC_REFLECT(eos::chain_apis::empty, ) FC_REFLECT(eos::chain_apis::read_only::get_info_results, (head_block_num)(last_irreversible_block_num)(head_block_id)(head_block_time)(head_block_producer) (recent_slots)(participation_rate)) FC_REFLECT(eos::chain_apis::read_only::get_block_params, (block_num_or_id)) FC_REFLECT_DERIVED( eos::chain_apis::read_only::get_block_results, (eos::chain::signed_block), (id)(block_num)(refBlockPrefix) ); FC_REFLECT( eos::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) ) FC_REFLECT( eos::chain_apis::read_only::get_table_rows_params, (json)(table_type)(table_key)(scope)(code)(table)(lower_bound)(upper_bound)(limit) ) FC_REFLECT( eos::chain_apis::read_only::get_table_rows_result, (rows)(more) ); FC_REFLECT( eos::chain_apis::read_only::get_account_results, (name)(eos_balance)(staked_balance)(unstaking_balance)(last_unstaking_time)(producer)(abi) ) FC_REFLECT( eos::chain_apis::read_only::get_account_params, (name) ) FC_REFLECT( eos::chain_apis::read_only::producer_info, (name) ) FC_REFLECT( eos::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) ) FC_REFLECT( eos::chain_apis::read_only::abi_json_to_bin_result, (binargs)(required_scope)(required_auth) ) FC_REFLECT( eos::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) ) FC_REFLECT( eos::chain_apis::read_only::abi_bin_to_json_result, (args)(required_scope)(required_auth) ) <commit_msg>fix build on OS X by convert lexical cast to variant cast, #250<commit_after>#pragma once #include <appbase/application.hpp> #include <eos/chain/chain_controller.hpp> #include <eos/chain/key_value_object.hpp> #include <eos/chain/account_object.hpp> #include <eos/types/AbiSerializer.hpp> #include <eos/database_plugin/database_plugin.hpp> namespace fc { class variant; } namespace eos { using eos::chain::chain_controller; using std::unique_ptr; using namespace appbase; using chain::Name; using fc::optional; using chain::uint128_t; namespace chain_apis { struct empty{}; class read_only { const chain_controller& db; const string KEYi64 = "i64"; const string KEYi128i128 = "i128i128"; const string KEYi64i64i64 = "i64i64i64"; const string PRIMARY = "primary"; const string SECONDARY = "secondary"; const string TERTIARY = "tertiary"; public: read_only(const chain_controller& db) : db(db) {} using get_info_params = empty; struct get_info_results { uint32_t head_block_num = 0; uint32_t last_irreversible_block_num = 0; chain::block_id_type head_block_id; fc::time_point_sec head_block_time; types::AccountName head_block_producer; string recent_slots; double participation_rate = 0; }; get_info_results get_info(const get_info_params&) const; struct producer_info { Name name; }; struct get_account_results { Name name; uint64_t eos_balance = 0; uint64_t staked_balance = 0; uint64_t unstaking_balance = 0; fc::time_point_sec last_unstaking_time; optional<producer_info> producer; optional<types::Abi> abi; }; struct get_account_params { Name name; }; get_account_results get_account( const get_account_params& params )const; struct abi_json_to_bin_params { Name code; Name action; fc::variant args; }; struct abi_json_to_bin_result { vector<char> binargs; vector<Name> required_scope; vector<Name> required_auth; }; abi_json_to_bin_result abi_json_to_bin( const abi_json_to_bin_params& params )const; struct abi_bin_to_json_params { Name code; Name action; vector<char> binargs; }; struct abi_bin_to_json_result { fc::variant args; vector<Name> required_scope; vector<Name> required_auth; }; abi_bin_to_json_result abi_bin_to_json( const abi_bin_to_json_params& params )const; struct get_block_params { string block_num_or_id; }; struct get_block_results : public chain::signed_block { get_block_results( const chain::signed_block& b ) :signed_block(b), id(b.id()), block_num(b.block_num()), refBlockPrefix( id._hash[1] ) {} chain::block_id_type id; uint32_t block_num = 0; uint32_t refBlockPrefix = 0; }; get_block_results get_block(const get_block_params& params) const; struct get_table_rows_params { bool json = false; Name scope; Name code; Name table; string table_type; string table_key; string lower_bound; string upper_bound; uint32_t limit = 10; }; struct get_table_rows_result { vector<fc::variant> rows; ///< one row per item, either encoded as hex String or JSON object bool more; ///< true if last element in data is not the end and sizeof data() < limit }; get_table_rows_result get_table_rows( const get_table_rows_params& params )const; void copy_row(const chain::key_value_object& obj, vector<char>& data)const { data.resize( sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::key128x128_value_object& obj, vector<char>& data)const { data.resize( 2*sizeof(uint128_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint128_t) ); memcpy( data.data()+sizeof(uint128_t), &obj.secondary_key, sizeof(uint128_t) ); memcpy( data.data()+2*sizeof(uint128_t), obj.value.data(), obj.value.size() ); } void copy_row(const chain::key64x64x64_value_object& obj, vector<char>& data)const { data.resize( 3*sizeof(uint64_t) + obj.value.size() ); memcpy( data.data(), &obj.primary_key, sizeof(uint64_t) ); memcpy( data.data()+sizeof(uint64_t), &obj.secondary_key, sizeof(uint64_t) ); memcpy( data.data()+2*sizeof(uint64_t), &obj.tertiary_key, sizeof(uint64_t) ); memcpy( data.data()+3*sizeof(uint64_t), obj.value.data(), obj.value.size() ); } template <typename IndexType, typename Scope> read_only::get_table_rows_result get_table_rows_ex( const read_only::get_table_rows_params& p )const { read_only::get_table_rows_result result; const auto& d = db.get_database(); const auto& code_account = d.get<chain::account_object,chain::by_name>( p.code ); types::AbiSerializer abis; if( code_account.abi.size() > 4 ) { /// 4 == packsize of empty Abi eos::types::Abi abi; fc::datastream<const char*> ds( code_account.abi.data(), code_account.abi.size() ); fc::raw::unpack( ds, abi ); abis.setAbi( abi ); } const auto& idx = d.get_index<IndexType, Scope>(); auto lower = idx.lower_bound( boost::make_tuple(p.scope, p.code, p.table, fc::variant(p.lower_bound).as<typename IndexType::value_type::key_type>() ) ); auto upper = idx.lower_bound( boost::make_tuple(p.scope, p.code, p.table, fc::variant(p.upper_bound).as<typename IndexType::value_type::key_type>() ) ); // auto upper = idx.upper_bound( boost::make_tuple(p.scope, p.code, p.table, boost::lexical_cast<typename IndexType::value_type::key_type>(p.upper_bound)) ); vector<char> data; auto start = fc::time_point::now(); auto end = fc::time_point::now() + fc::microseconds( 1000*10 ); /// 10ms max time int count = 0; auto itr = lower; for( itr = lower; itr != upper && itr->table == p.table; ++itr ) { copy_row(*itr, data); if( p.json ) result.rows.emplace_back( abis.binaryToVariant( abis.getTableType(p.table), data ) ); else result.rows.emplace_back( fc::variant(data) ); if( ++count == p.limit || fc::time_point::now() > end ) break; } if( itr != upper ) result.more = true; return result; } }; class read_write { chain_controller& db; uint32_t skip_flags; public: read_write(chain_controller& db, uint32_t skip_flags) : db(db), skip_flags(skip_flags) {} using push_block_params = chain::signed_block; using push_block_results = empty; push_block_results push_block(const push_block_params& params); using push_transaction_params = chain::SignedTransaction; struct push_transaction_results { chain::transaction_id_type transaction_id; fc::variant processed; }; push_transaction_results push_transaction(const push_transaction_params& params); }; } // namespace chain_apis class chain_plugin : public plugin<chain_plugin> { public: APPBASE_PLUGIN_REQUIRES((database_plugin)) chain_plugin(); virtual ~chain_plugin(); virtual void set_program_options(options_description& cli, options_description& cfg) override; void plugin_initialize(const variables_map& options); void plugin_startup(); void plugin_shutdown(); chain_apis::read_only get_read_only_api() const { return chain_apis::read_only(chain()); } chain_apis::read_write get_read_write_api(); bool accept_block(const chain::signed_block& block, bool currently_syncing); void accept_transaction(const chain::SignedTransaction& trx); bool block_is_on_preferred_chain(const chain::block_id_type& block_id); // return true if --skip-transaction-signatures passed to eosd bool is_skipping_transaction_signatures() const; // Only call this after plugin_startup()! chain_controller& chain(); // Only call this after plugin_startup()! const chain_controller& chain() const; void get_chain_id (chain::chain_id_type &cid) const; private: unique_ptr<class chain_plugin_impl> my; }; } FC_REFLECT(eos::chain_apis::empty, ) FC_REFLECT(eos::chain_apis::read_only::get_info_results, (head_block_num)(last_irreversible_block_num)(head_block_id)(head_block_time)(head_block_producer) (recent_slots)(participation_rate)) FC_REFLECT(eos::chain_apis::read_only::get_block_params, (block_num_or_id)) FC_REFLECT_DERIVED( eos::chain_apis::read_only::get_block_results, (eos::chain::signed_block), (id)(block_num)(refBlockPrefix) ); FC_REFLECT( eos::chain_apis::read_write::push_transaction_results, (transaction_id)(processed) ) FC_REFLECT( eos::chain_apis::read_only::get_table_rows_params, (json)(table_type)(table_key)(scope)(code)(table)(lower_bound)(upper_bound)(limit) ) FC_REFLECT( eos::chain_apis::read_only::get_table_rows_result, (rows)(more) ); FC_REFLECT( eos::chain_apis::read_only::get_account_results, (name)(eos_balance)(staked_balance)(unstaking_balance)(last_unstaking_time)(producer)(abi) ) FC_REFLECT( eos::chain_apis::read_only::get_account_params, (name) ) FC_REFLECT( eos::chain_apis::read_only::producer_info, (name) ) FC_REFLECT( eos::chain_apis::read_only::abi_json_to_bin_params, (code)(action)(args) ) FC_REFLECT( eos::chain_apis::read_only::abi_json_to_bin_result, (binargs)(required_scope)(required_auth) ) FC_REFLECT( eos::chain_apis::read_only::abi_bin_to_json_params, (code)(action)(binargs) ) FC_REFLECT( eos::chain_apis::read_only::abi_bin_to_json_result, (args)(required_scope)(required_auth) ) <|endoftext|>
<commit_before>#include <configure/bind.hpp> #include <configure/Node.hpp> #include <configure/lua/State.hpp> #include <configure/lua/Type.hpp> #include <boost/filesystem/path.hpp> namespace fs = boost::filesystem; namespace configure { void bind_node(lua::State& state) { /// Node represent a vertex in the build graph. // // @classmod Node lua::Type<Node, NodePtr>(state, "Node") /// True if the node is a virtual node. // @function Node:is_virtual // @treturn bool .def("is_virtual", &Node::is_virtual) /// Path of the node // @function Node:path // @treturn Path absolute path .def("path", &Node::path) /// Name of a virtual node. // @function Node:name // @treturn string .def("name", &Node::name) .def("__tostring", &Node::string) /// Relative path to the node // @tparam Path start Starting point of the relative path // @treturn Path the relative path // @function Node:relative_path .def("relative_path", &Node::relative_path) ; } } <commit_msg>Bind node properties accessor.<commit_after>#include "environ_utils.hpp" #include <configure/bind.hpp> #include <configure/Node.hpp> #include <configure/PropertyMap.hpp> #include <configure/lua/State.hpp> #include <configure/lua/Type.hpp> #include <boost/filesystem/path.hpp> namespace fs = boost::filesystem; namespace configure { static int Node_property(lua_State* state) { NodePtr& self = lua::Converter<NodePtr>::extract(state, 1); Environ& env = self->properties().values(); return utils::env_get(state, env); } static int Node_set_property(lua_State* state) { NodePtr& self = lua::Converter<NodePtr>::extract(state, 1); Environ& env = self->properties().values(); return utils::env_set(state, env); } static int Node_set_property_default(lua_State* state) { NodePtr& self = lua::Converter<NodePtr>::extract(state, 1); Environ& env = self->properties().values(); return utils::env_set_default(state, env); } void bind_node(lua::State& state) { /// Node represent a vertex in the build graph. // // @classmod Node lua::Type<Node, NodePtr>(state, "Node") /// True if the node is a virtual node. // @function Node:is_virtual // @treturn bool .def("is_virtual", &Node::is_virtual) /// Path of the node // @function Node:path // @treturn Path absolute path .def("path", &Node::path) /// Name of a virtual node. // @function Node:name // @treturn string .def("name", &Node::name) .def("__tostring", &Node::string) /// Relative path to the node // @tparam Path start Starting point of the relative path // @treturn Path the relative path // @function Node:relative_path .def("relative_path", &Node::relative_path) /// Retrieve a Node property // @string name The property name // @treturn string|Path|boolean|nil .def("property", &Node_property) /// Set a Node property // @string name The property name // @tparam string|Path|boolean|nil the value to set // @treturn string|Path|boolean|nil .def("set_property", &Node_set_property) /// Set a Node property default value // @string name The property name // @tparam string|Path|boolean|nil the default value to set // @treturn string|Path|boolean|nil .def("set_property_default", &Node_set_property_default) ; } } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "CSVTools.h" #include "ConfigParams.h" #include "LedMeasurement.h" #include "MakeHDKTrackingSystem.h" #include "TrackedBodyTarget.h" #include "newuoa.h" #include <osvr/Util/TimeValue.h> // Library/third-party includes #include <Eigen/Core> #include <Eigen/Geometry> // Standard includes #include <fstream> #include <sstream> using osvr::util::time::TimeValue; static const cv::Size IMAGE_SIZE = {640, 480}; /// Friendlier wrapper around newuoa template <typename Function, typename Vec> inline double ei_newuoa(long npt, Vec &x, std::pair<double, double> rho, long maxfun, Function &&f) { double rhoBeg, rhoEnd; std::tie(rhoBeg, rhoEnd) = rho; if (rhoEnd > rhoBeg) { std::swap(rhoBeg, rhoEnd); } long n = x.size(); auto workingSpaceNeeded = (npt + 13) * (npt + n) + 3 * n * (n + 3) / 2; Eigen::VectorXd workingSpace(workingSpaceNeeded); return newuoa(std::forward<Function>(f), n, npt, x.data(), rhoBeg, rhoEnd, maxfun, workingSpace.data()); } using ParamVec = Eigen::Vector4d; namespace osvr { namespace vbtracker { void updateConfigFromVec(ConfigParams &params, ParamVec const &paramVec) { /// positional noise params.processNoiseAutocorrelation[0] = params.processNoiseAutocorrelation[1] = params.processNoiseAutocorrelation[2] = paramVec[0]; /// rotational noise params.processNoiseAutocorrelation[3] = params.processNoiseAutocorrelation[4] = params.processNoiseAutocorrelation[5] = paramVec[1]; params.beaconProcessNoise = paramVec[2]; params.measurementVarianceScaleFactor = paramVec[3]; } struct TimestampedMeasurements { EIGEN_MAKE_ALIGNED_OPERATOR_NEW TimeValue tv; Eigen::Vector3d xlate; Eigen::Quaterniond rot; LedMeasurementVec measurements; bool ok = false; }; class LoadRow { public: LoadRow(csvtools::FieldParserHelper &helper, TimestampedMeasurements &row) : helper_(helper), row_(row) {} ~LoadRow() { if (!measurementPieces_.empty()) { std::cerr << "Leftover measurement pieces on loadrow " "destruction, suggests a parsing error!" << std::endl; } } bool operator()(std::string const &line, std::size_t beginPos, std::size_t endPos) { field_++; csvtools::StringField strField(line, beginPos, endPos); //std::cout << strField.beginPos() << ":" << strField.virtualEndPos() << std::endl; if (field_ <= 3) { // refx/y/z bool success = false; double val; std::tie(success, val) = helper_.getFieldAs<double>(strField); if (!success) { return false; } row_.xlate[field_] = val; return true; } if (field_ <= 7) { // refqw/qx/qy/qz bool success = false; double val; std::tie(success, val) = helper_.getFieldAs<double>(strField); if (!success) { return false; } switch (field_) { case 4: row_.rot.w() = val; break; case 5: row_.rot.x() = val; break; case 6: row_.rot.y() = val; break; case 7: row_.rot.z() = val; break; } return true; } if (field_ == 8) { // sec auto success = helper_.getField(strField, row_.tv.seconds); return success; } if (field_ == 9) { // usec auto success = helper_.getField(strField, row_.tv.microseconds); if (success) { row_.ok = true; } return success; } // Now, we are looping through x, y, size for every blob. bool success = false; float val; std::tie(success, val) = helper_.getFieldAs<float>(strField); if (!success) { return false; } measurementPieces_.push_back(val); if (measurementPieces_.size() == 3) { // that's a new LED! row_.measurements.emplace_back( measurementPieces_[0], measurementPieces_[1], measurementPieces_[2], IMAGE_SIZE); measurementPieces_.clear(); } return true; } private: csvtools::FieldParserHelper &helper_; TimestampedMeasurements &row_; std::size_t field_ = 0; std::vector<float> measurementPieces_; }; inline std::vector<std::unique_ptr<TimestampedMeasurements>> loadData(std::string const &fn) { std::vector<std::unique_ptr<TimestampedMeasurements>> ret; std::ifstream csvFile(fn); if (!csvFile) { std::cerr << "Could not open csvFile " << fn << std::endl; return ret; } { auto headerRow = csvtools::getCleanLine(csvFile); if (headerRow.empty() || !csvFile) { /// @todo this is pretty crude precondition handling, but /// probably good enough for now. std::cerr << "Header row was empty, that's not a good sign!" << std::endl; return ret; } } csvtools::FieldParserHelper helper; std::string dataLine = csvtools::getCleanLine(csvFile); while (csvFile) { std::unique_ptr<TimestampedMeasurements> newRow( new TimestampedMeasurements); csvtools::iterateFields(LoadRow(helper, *newRow), dataLine); //std::cout << "Done with iterate fields" << std::endl; if (newRow->ok) { std::cout << "Row has " << newRow->measurements.size() << " blobs" << std::endl; ret.emplace_back(std::move(newRow)); } else { std::cerr << "Something went wrong parsing that row: " << dataLine << std::endl; } dataLine = csvtools::getCleanLine(csvFile); } std::cout << "Total of " << ret.size() << " rows" << std::endl; return ret; } ParamVec runOptimizer(std::string const &fn) { // initial values. ParamVec x = {4.14e-6, 1e-2, 0, 5e-2}; auto npt = x.size() * 2; // who knows? auto ret = ei_newuoa( npt, x, {1e-8, 1e-4}, 10, [&](long n, double *x) -> double { using namespace osvr::vbtracker; ConfigParams params; updateConfigFromVec(params, ParamVec::Map(x)); auto system = makeHDKTrackingSystem(params); auto &target = *(system->getBody(BodyId(0)).getTarget(TargetId(0))); /// @todo return 0; }); std::cout << "Optimizer returned " << ret << " and these parameter values:" << std::endl; std::cout << x.transpose() << std::endl; return x; } } } int main() { //osvr::vbtracker::runOptimizer("augmented-blobs.csv"); osvr::vbtracker::loadData("augmented-blobs.csv"); std::cin.ignore(); return 0; } <commit_msg>Load and process the data.<commit_after>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "CSVTools.h" #include "ConfigParams.h" #include "LedMeasurement.h" #include "MakeHDKTrackingSystem.h" #include "TrackedBodyTarget.h" #include "newuoa.h" #include <osvr/Util/EigenFilters.h> #include <osvr/Util/TimeValue.h> // Library/third-party includes #include <Eigen/Core> #include <Eigen/Geometry> // Standard includes #include <fstream> #include <sstream> using osvr::util::time::TimeValue; static const cv::Size IMAGE_SIZE = {640, 480}; /// Friendlier wrapper around newuoa template <typename Function, typename Vec> inline double ei_newuoa(long npt, Vec &x, std::pair<double, double> rho, long maxfun, Function &&f) { double rhoBeg, rhoEnd; std::tie(rhoBeg, rhoEnd) = rho; if (rhoEnd > rhoBeg) { std::swap(rhoBeg, rhoEnd); } long n = x.size(); auto workingSpaceNeeded = (npt + 13) * (npt + n) + 3 * n * (n + 3) / 2; Eigen::VectorXd workingSpace(workingSpaceNeeded); return newuoa(std::forward<Function>(f), n, npt, x.data(), rhoBeg, rhoEnd, maxfun, workingSpace.data()); } using ParamVec = Eigen::Vector4d; namespace osvr { namespace vbtracker { void updateConfigFromVec(ConfigParams &params, ParamVec const &paramVec) { /// positional noise params.processNoiseAutocorrelation[0] = params.processNoiseAutocorrelation[1] = params.processNoiseAutocorrelation[2] = paramVec[0]; /// rotational noise params.processNoiseAutocorrelation[3] = params.processNoiseAutocorrelation[4] = params.processNoiseAutocorrelation[5] = paramVec[1]; params.beaconProcessNoise = paramVec[2]; params.measurementVarianceScaleFactor = paramVec[3]; } struct TimestampedMeasurements { EIGEN_MAKE_ALIGNED_OPERATOR_NEW TimeValue tv; Eigen::Vector3d xlate; Eigen::Quaterniond rot; LedMeasurementVec measurements; bool ok = false; }; class LoadRow { public: LoadRow(csvtools::FieldParserHelper &helper, TimestampedMeasurements &row) : helper_(helper), row_(row) {} ~LoadRow() { if (!measurementPieces_.empty()) { std::cerr << "Leftover measurement pieces on loadrow " "destruction, suggests a parsing error!" << std::endl; } } bool operator()(std::string const &line, std::size_t beginPos, std::size_t endPos) { field_++; csvtools::StringField strField(line, beginPos, endPos); // std::cout << strField.beginPos() << ":" << // strField.virtualEndPos() << std::endl; if (field_ <= 3) { // refx/y/z bool success = false; double val; std::tie(success, val) = helper_.getFieldAs<double>(strField); if (!success) { return false; } row_.xlate[field_] = val; return true; } if (field_ <= 7) { // refqw/qx/qy/qz bool success = false; double val; std::tie(success, val) = helper_.getFieldAs<double>(strField); if (!success) { return false; } switch (field_) { case 4: row_.rot.w() = val; break; case 5: row_.rot.x() = val; break; case 6: row_.rot.y() = val; break; case 7: row_.rot.z() = val; break; } return true; } if (field_ == 8) { // sec auto success = helper_.getField(strField, row_.tv.seconds); return success; } if (field_ == 9) { // usec auto success = helper_.getField(strField, row_.tv.microseconds); if (success) { row_.ok = true; } return success; } // Now, we are looping through x, y, size for every blob. bool success = false; float val; std::tie(success, val) = helper_.getFieldAs<float>(strField); if (!success) { return false; } measurementPieces_.push_back(val); if (measurementPieces_.size() == 3) { // that's a new LED! row_.measurements.emplace_back( measurementPieces_[0], measurementPieces_[1], measurementPieces_[2], IMAGE_SIZE); measurementPieces_.clear(); } return true; } private: csvtools::FieldParserHelper &helper_; TimestampedMeasurements &row_; std::size_t field_ = 0; std::vector<float> measurementPieces_; }; inline std::vector<std::unique_ptr<TimestampedMeasurements>> loadData(std::string const &fn) { std::vector<std::unique_ptr<TimestampedMeasurements>> ret; std::ifstream csvFile(fn); if (!csvFile) { std::cerr << "Could not open csvFile " << fn << std::endl; return ret; } { auto headerRow = csvtools::getCleanLine(csvFile); if (headerRow.empty() || !csvFile) { /// @todo this is pretty crude precondition handling, but /// probably good enough for now. std::cerr << "Header row was empty, that's not a good sign!" << std::endl; return ret; } } csvtools::FieldParserHelper helper; std::string dataLine = csvtools::getCleanLine(csvFile); while (csvFile) { std::unique_ptr<TimestampedMeasurements> newRow( new TimestampedMeasurements); csvtools::iterateFields(LoadRow(helper, *newRow), dataLine); // std::cout << "Done with iterate fields" << std::endl; if (newRow->ok) { std::cout << "Row has " << newRow->measurements.size() << " blobs" << std::endl; ret.emplace_back(std::move(newRow)); } else { std::cerr << "Something went wrong parsing that row: " << dataLine << std::endl; } dataLine = csvtools::getCleanLine(csvFile); } std::cout << "Total of " << ret.size() << " rows" << std::endl; return ret; } ImageOutputDataPtr makeImageOutputDataFromRow(TimestampedMeasurements const &row, CameraParameters const &camParams) { ImageOutputDataPtr ret(new ImageProcessingOutput); ret->tv = row.tv; ret->ledMeasurements = row.measurements; ret->camParams = camParams; return ret; } ParamVec runOptimizer(std::string const &fn) { // initial values. ParamVec x = {4.14e-6, 1e-2, 0, 5e-2}; auto npt = x.size() * 2; // who knows? auto ret = ei_newuoa( npt, x, {1e-8, 1e-4}, 10, [&](long n, double *x) -> double { using namespace osvr::vbtracker; ConfigParams params; updateConfigFromVec(params, ParamVec::Map(x)); auto system = makeHDKTrackingSystem(params); auto &target = *(system->getBody(BodyId(0)).getTarget(TargetId(0))); /// @todo return 0; }); std::cout << "Optimizer returned " << ret << " and these parameter values:" << std::endl; std::cout << x.transpose() << std::endl; return x; } class PoseFilter { public: PoseFilter(util::filters::one_euro::Params const &positionFilterParams = util::filters::one_euro::Params{}, util::filters::one_euro::Params const &oriFilterParams = util::filters::one_euro::Params{}) : m_positionFilter(positionFilterParams), m_orientationFilter(oriFilterParams){}; void filter(double dt, Eigen::Vector3d const &position, Eigen::Quaterniond const &orientation) { if (dt <= 0) { /// Avoid div by 0 dt = 1; } m_positionFilter.filter(dt, position); m_orientationFilter.filter(dt, orientation); } Eigen::Vector3d const &getPosition() const { return m_positionFilter.getState(); } Eigen::Quaterniond const &getOrientation() const { return m_orientationFilter.getState(); } Eigen::Isometry3d getIsometry() const { return Eigen::Translation3d(getPosition()) * Eigen::Isometry3d(getOrientation()); } private: util::filters::OneEuroFilter<Eigen::Vector3d> m_positionFilter; util::filters::OneEuroFilter<Eigen::Quaterniond> m_orientationFilter; }; class MainAlgoUnderStudy { public: void operator()(CameraParameters const &camParams, TrackingSystem &system, TrackedBodyTarget &target, TimestampedMeasurements const &row) { auto indices = system.updateBodiesFromVideoData( std::move(makeImageOutputDataFromRow(row, camParams))); gotPose = target.getBody().hasPoseEstimate(); if (gotPose) { pose = target.getBody().getState().getIsometry(); } } bool havePose() const { return gotPose; } Eigen::Isometry3d const &getPose() const { return pose; } private: bool gotPose = false; Eigen::Isometry3d pose; }; class RansacOneEuro { public: void operator()(CameraParameters const &camParams, TrackingSystem &system, TrackedBodyTarget &target, TimestampedMeasurements const &row) { gotPose = false; Eigen::Vector3d pos; Eigen::Quaterniond quat; auto gotRansac = target.uncalibratedRANSACPoseEstimateFromLeds( camParams, pos, quat); if (gotRansac) { double dt = 1; if (isFirst) { isFirst = false; } else { dt = osvrTimeValueDurationSeconds(&row.tv, &last); } ransacPoseFilter.filter(dt, pos, quat); std::cout << ransacPoseFilter.getPosition().transpose() << std::endl; last = row.tv; gotPose = true; } } bool havePose() const { return gotPose; } Eigen::Isometry3d const &getPose() const { return ransacPoseFilter.getIsometry(); } private: PoseFilter ransacPoseFilter; TimeValue last; bool isFirst = true; bool gotPose = false; }; } } int main() { // osvr::vbtracker::runOptimizer("augmented-blobs.csv"); auto data = osvr::vbtracker::loadData("augmented-blobs.csv"); const auto camParams = osvr::vbtracker::getHDKCameraParameters().createUndistortedVariant(); { using namespace osvr::vbtracker; ConfigParams params; ParamVec x = {4.14e-6, 1e-2, 0, 5e-2}; updateConfigFromVec(params, x); auto system = makeHDKTrackingSystem(params); auto &target = *(system->getBody(BodyId(0)).getTarget(TargetId(0))); MainAlgoUnderStudy mainAlgo; RansacOneEuro ransacOneEuro; for (auto const &rowPtr : data) { mainAlgo(camParams, *system, target, *rowPtr); ransacOneEuro(camParams, *system, target, *rowPtr); } } std::cout << "Press enter to exit." << std::endl; std::cin.ignore(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapScaler.h" #include "SkBitmapFilter.h" #include "SkConvolver.h" #include "SkImageInfo.h" #include "SkPixmap.h" #include "SkRect.h" #include "SkTArray.h" // SkResizeFilter ---------------------------------------------------------------- // Encapsulates computation and storage of the filters required for one complete // resize operation. class SkResizeFilter { public: SkResizeFilter(SkBitmapScaler::ResizeMethod method, int srcFullWidth, int srcFullHeight, float destWidth, float destHeight, const SkRect& destSubset, const SkConvolutionProcs& convolveProcs); ~SkResizeFilter() { delete fBitmapFilter; } // Returns the filled filter values. const SkConvolutionFilter1D& xFilter() { return fXFilter; } const SkConvolutionFilter1D& yFilter() { return fYFilter; } private: SkBitmapFilter* fBitmapFilter; // Computes one set of filters either horizontally or vertically. The caller // will specify the "min" and "max" rather than the bottom/top and // right/bottom so that the same code can be re-used in each dimension. // // |srcDependLo| and |srcDependSize| gives the range for the source // depend rectangle (horizontally or vertically at the caller's discretion // -- see above for what this means). // // Likewise, the range of destination values to compute and the scale factor // for the transform is also specified. void computeFilters(int srcSize, float destSubsetLo, float destSubsetSize, float scale, SkConvolutionFilter1D* output, const SkConvolutionProcs& convolveProcs); SkConvolutionFilter1D fXFilter; SkConvolutionFilter1D fYFilter; }; SkResizeFilter::SkResizeFilter(SkBitmapScaler::ResizeMethod method, int srcFullWidth, int srcFullHeight, float destWidth, float destHeight, const SkRect& destSubset, const SkConvolutionProcs& convolveProcs) { SkASSERT(method >= SkBitmapScaler::RESIZE_FirstMethod && method <= SkBitmapScaler::RESIZE_LastMethod); fBitmapFilter = nullptr; switch(method) { case SkBitmapScaler::RESIZE_BOX: fBitmapFilter = new SkBoxFilter; break; case SkBitmapScaler::RESIZE_TRIANGLE: fBitmapFilter = new SkTriangleFilter; break; case SkBitmapScaler::RESIZE_MITCHELL: fBitmapFilter = new SkMitchellFilter; break; case SkBitmapScaler::RESIZE_HAMMING: fBitmapFilter = new SkHammingFilter; break; case SkBitmapScaler::RESIZE_LANCZOS3: fBitmapFilter = new SkLanczosFilter; break; } float scaleX = destWidth / srcFullWidth; float scaleY = destHeight / srcFullHeight; this->computeFilters(srcFullWidth, destSubset.fLeft, destSubset.width(), scaleX, &fXFilter, convolveProcs); if (srcFullWidth == srcFullHeight && destSubset.fLeft == destSubset.fTop && destSubset.width() == destSubset.height()&& scaleX == scaleY) { fYFilter = fXFilter; } else { this->computeFilters(srcFullHeight, destSubset.fTop, destSubset.height(), scaleY, &fYFilter, convolveProcs); } } // TODO(egouriou): Take advantage of periods in the convolution. // Practical resizing filters are periodic outside of the border area. // For Lanczos, a scaling by a (reduced) factor of p/q (q pixels in the // source become p pixels in the destination) will have a period of p. // A nice consequence is a period of 1 when downscaling by an integral // factor. Downscaling from typical display resolutions is also bound // to produce interesting periods as those are chosen to have multiple // small factors. // Small periods reduce computational load and improve cache usage if // the coefficients can be shared. For periods of 1 we can consider // loading the factors only once outside the borders. void SkResizeFilter::computeFilters(int srcSize, float destSubsetLo, float destSubsetSize, float scale, SkConvolutionFilter1D* output, const SkConvolutionProcs& convolveProcs) { float destSubsetHi = destSubsetLo + destSubsetSize; // [lo, hi) // When we're doing a magnification, the scale will be larger than one. This // means the destination pixels are much smaller than the source pixels, and // that the range covered by the filter won't necessarily cover any source // pixel boundaries. Therefore, we use these clamped values (max of 1) for // some computations. float clampedScale = SkTMin(1.0f, scale); // This is how many source pixels from the center we need to count // to support the filtering function. float srcSupport = fBitmapFilter->width() / clampedScale; float invScale = 1.0f / scale; SkSTArray<64, float, true> filterValuesArray; SkSTArray<64, SkConvolutionFilter1D::ConvolutionFixed, true> fixedFilterValuesArray; // Loop over all pixels in the output range. We will generate one set of // filter values for each one. Those values will tell us how to blend the // source pixels to compute the destination pixel. // This is the pixel in the source directly under the pixel in the dest. // Note that we base computations on the "center" of the pixels. To see // why, observe that the destination pixel at coordinates (0, 0) in a 5.0x // downscale should "cover" the pixels around the pixel with *its center* // at coordinates (2.5, 2.5) in the source, not those around (0, 0). // Hence we need to scale coordinates (0.5, 0.5), not (0, 0). destSubsetLo = SkScalarFloorToScalar(destSubsetLo); destSubsetHi = SkScalarCeilToScalar(destSubsetHi); float srcPixel = (destSubsetLo + 0.5f) * invScale; int destLimit = SkScalarTruncToInt(destSubsetHi - destSubsetLo); output->reserveAdditional(destLimit, SkScalarCeilToInt(destLimit * srcSupport * 2)); for (int destI = 0; destI < destLimit; srcPixel += invScale, destI++) { // Compute the (inclusive) range of source pixels the filter covers. float srcBegin = SkTMax(0.f, SkScalarFloorToScalar(srcPixel - srcSupport)); float srcEnd = SkTMin(srcSize - 1.f, SkScalarCeilToScalar(srcPixel + srcSupport)); // Compute the unnormalized filter value at each location of the source // it covers. // Sum of the filter values for normalizing. // Distance from the center of the filter, this is the filter coordinate // in source space. We also need to consider the center of the pixel // when comparing distance against 'srcPixel'. In the 5x downscale // example used above the distance from the center of the filter to // the pixel with coordinates (2, 2) should be 0, because its center // is at (2.5, 2.5). float destFilterDist = (srcBegin + 0.5f - srcPixel) * clampedScale; int filterCount = SkScalarTruncToInt(srcEnd - srcBegin) + 1; SkASSERT(filterCount > 0); filterValuesArray.reset(filterCount); float filterSum = fBitmapFilter->evaluate_n(destFilterDist, clampedScale, filterCount, filterValuesArray.begin()); // The filter must be normalized so that we don't affect the brightness of // the image. Convert to normalized fixed point. int fixedSum = 0; fixedFilterValuesArray.reset(filterCount); const float* filterValues = filterValuesArray.begin(); SkConvolutionFilter1D::ConvolutionFixed* fixedFilterValues = fixedFilterValuesArray.begin(); float invFilterSum = 1 / filterSum; for (int fixedI = 0; fixedI < filterCount; fixedI++) { int curFixed = SkConvolutionFilter1D::FloatToFixed(filterValues[fixedI] * invFilterSum); fixedSum += curFixed; fixedFilterValues[fixedI] = SkToS16(curFixed); } SkASSERT(fixedSum <= 0x7FFF); // The conversion to fixed point will leave some rounding errors, which // we add back in to avoid affecting the brightness of the image. We // arbitrarily add this to the center of the filter array (this won't always // be the center of the filter function since it could get clipped on the // edges, but it doesn't matter enough to worry about that case). int leftovers = SkConvolutionFilter1D::FloatToFixed(1) - fixedSum; fixedFilterValues[filterCount / 2] += leftovers; // Now it's ready to go. output->AddFilter(SkScalarFloorToInt(srcBegin), fixedFilterValues, filterCount); } if (convolveProcs.fApplySIMDPadding) { convolveProcs.fApplySIMDPadding(output); } } /////////////////////////////////////////////////////////////////////////////////////////////////// static bool valid_for_resize(const SkPixmap& source, int dstW, int dstH) { // TODO: Seems like we shouldn't care about the swizzle of source, just that it's 8888 return source.addr() && source.colorType() == kN32_SkColorType && source.width() >= 1 && source.height() >= 1 && dstW >= 1 && dstH >= 1; } bool SkBitmapScaler::Resize(const SkPixmap& result, const SkPixmap& source, ResizeMethod method) { if (!valid_for_resize(source, result.width(), result.height())) { return false; } if (!result.addr() || result.colorType() != source.colorType()) { return false; } SkConvolutionProcs convolveProcs= { 0, nullptr, nullptr, nullptr, nullptr }; PlatformConvolutionProcs(&convolveProcs); SkRect destSubset = SkRect::MakeIWH(result.width(), result.height()); SkResizeFilter filter(method, source.width(), source.height(), result.width(), result.height(), destSubset, convolveProcs); // Get a subset encompassing this touched area. We construct the // offsets and row strides such that it looks like a new bitmap, while // referring to the old data. const uint8_t* sourceSubset = reinterpret_cast<const uint8_t*>(source.addr()); return BGRAConvolve2D(sourceSubset, static_cast<int>(source.rowBytes()), !source.isOpaque(), filter.xFilter(), filter.yFilter(), static_cast<int>(result.rowBytes()), static_cast<unsigned char*>(result.writable_addr()), convolveProcs, true); } bool SkBitmapScaler::Resize(SkBitmap* resultPtr, const SkPixmap& source, ResizeMethod method, int destWidth, int destHeight, SkBitmap::Allocator* allocator) { // Preflight some of the checks, to avoid allocating the result if we don't need it. if (!valid_for_resize(source, destWidth, destHeight)) { return false; } SkBitmap result; result.setInfo(SkImageInfo::MakeN32(destWidth, destHeight, source.alphaType())); result.allocPixels(allocator, nullptr); SkPixmap resultPM; if (!result.peekPixels(&resultPM) || !Resize(resultPM, source, method)) { return false; } *resultPtr = result; resultPtr->lockPixels(); SkASSERT(resultPtr->getPixels()); return true; } <commit_msg>exit computeFilters if filter width is zero<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmapScaler.h" #include "SkBitmapFilter.h" #include "SkConvolver.h" #include "SkImageInfo.h" #include "SkPixmap.h" #include "SkRect.h" #include "SkTArray.h" // SkResizeFilter ---------------------------------------------------------------- // Encapsulates computation and storage of the filters required for one complete // resize operation. class SkResizeFilter { public: SkResizeFilter(SkBitmapScaler::ResizeMethod method, int srcFullWidth, int srcFullHeight, float destWidth, float destHeight, const SkRect& destSubset, const SkConvolutionProcs& convolveProcs); ~SkResizeFilter() { delete fBitmapFilter; } // Returns the filled filter values. const SkConvolutionFilter1D& xFilter() { return fXFilter; } const SkConvolutionFilter1D& yFilter() { return fYFilter; } private: SkBitmapFilter* fBitmapFilter; // Computes one set of filters either horizontally or vertically. The caller // will specify the "min" and "max" rather than the bottom/top and // right/bottom so that the same code can be re-used in each dimension. // // |srcDependLo| and |srcDependSize| gives the range for the source // depend rectangle (horizontally or vertically at the caller's discretion // -- see above for what this means). // // Likewise, the range of destination values to compute and the scale factor // for the transform is also specified. void computeFilters(int srcSize, float destSubsetLo, float destSubsetSize, float scale, SkConvolutionFilter1D* output, const SkConvolutionProcs& convolveProcs); SkConvolutionFilter1D fXFilter; SkConvolutionFilter1D fYFilter; }; SkResizeFilter::SkResizeFilter(SkBitmapScaler::ResizeMethod method, int srcFullWidth, int srcFullHeight, float destWidth, float destHeight, const SkRect& destSubset, const SkConvolutionProcs& convolveProcs) { SkASSERT(method >= SkBitmapScaler::RESIZE_FirstMethod && method <= SkBitmapScaler::RESIZE_LastMethod); fBitmapFilter = nullptr; switch(method) { case SkBitmapScaler::RESIZE_BOX: fBitmapFilter = new SkBoxFilter; break; case SkBitmapScaler::RESIZE_TRIANGLE: fBitmapFilter = new SkTriangleFilter; break; case SkBitmapScaler::RESIZE_MITCHELL: fBitmapFilter = new SkMitchellFilter; break; case SkBitmapScaler::RESIZE_HAMMING: fBitmapFilter = new SkHammingFilter; break; case SkBitmapScaler::RESIZE_LANCZOS3: fBitmapFilter = new SkLanczosFilter; break; } float scaleX = destWidth / srcFullWidth; float scaleY = destHeight / srcFullHeight; this->computeFilters(srcFullWidth, destSubset.fLeft, destSubset.width(), scaleX, &fXFilter, convolveProcs); if (srcFullWidth == srcFullHeight && destSubset.fLeft == destSubset.fTop && destSubset.width() == destSubset.height()&& scaleX == scaleY) { fYFilter = fXFilter; } else { this->computeFilters(srcFullHeight, destSubset.fTop, destSubset.height(), scaleY, &fYFilter, convolveProcs); } } // TODO(egouriou): Take advantage of periods in the convolution. // Practical resizing filters are periodic outside of the border area. // For Lanczos, a scaling by a (reduced) factor of p/q (q pixels in the // source become p pixels in the destination) will have a period of p. // A nice consequence is a period of 1 when downscaling by an integral // factor. Downscaling from typical display resolutions is also bound // to produce interesting periods as those are chosen to have multiple // small factors. // Small periods reduce computational load and improve cache usage if // the coefficients can be shared. For periods of 1 we can consider // loading the factors only once outside the borders. void SkResizeFilter::computeFilters(int srcSize, float destSubsetLo, float destSubsetSize, float scale, SkConvolutionFilter1D* output, const SkConvolutionProcs& convolveProcs) { float destSubsetHi = destSubsetLo + destSubsetSize; // [lo, hi) // When we're doing a magnification, the scale will be larger than one. This // means the destination pixels are much smaller than the source pixels, and // that the range covered by the filter won't necessarily cover any source // pixel boundaries. Therefore, we use these clamped values (max of 1) for // some computations. float clampedScale = SkTMin(1.0f, scale); // This is how many source pixels from the center we need to count // to support the filtering function. float srcSupport = fBitmapFilter->width() / clampedScale; float invScale = 1.0f / scale; SkSTArray<64, float, true> filterValuesArray; SkSTArray<64, SkConvolutionFilter1D::ConvolutionFixed, true> fixedFilterValuesArray; // Loop over all pixels in the output range. We will generate one set of // filter values for each one. Those values will tell us how to blend the // source pixels to compute the destination pixel. // This is the pixel in the source directly under the pixel in the dest. // Note that we base computations on the "center" of the pixels. To see // why, observe that the destination pixel at coordinates (0, 0) in a 5.0x // downscale should "cover" the pixels around the pixel with *its center* // at coordinates (2.5, 2.5) in the source, not those around (0, 0). // Hence we need to scale coordinates (0.5, 0.5), not (0, 0). destSubsetLo = SkScalarFloorToScalar(destSubsetLo); destSubsetHi = SkScalarCeilToScalar(destSubsetHi); float srcPixel = (destSubsetLo + 0.5f) * invScale; int destLimit = SkScalarTruncToInt(destSubsetHi - destSubsetLo); output->reserveAdditional(destLimit, SkScalarCeilToInt(destLimit * srcSupport * 2)); for (int destI = 0; destI < destLimit; srcPixel += invScale, destI++) { // Compute the (inclusive) range of source pixels the filter covers. float srcBegin = SkTMax(0.f, SkScalarFloorToScalar(srcPixel - srcSupport)); float srcEnd = SkTMin(srcSize - 1.f, SkScalarCeilToScalar(srcPixel + srcSupport)); // Compute the unnormalized filter value at each location of the source // it covers. // Sum of the filter values for normalizing. // Distance from the center of the filter, this is the filter coordinate // in source space. We also need to consider the center of the pixel // when comparing distance against 'srcPixel'. In the 5x downscale // example used above the distance from the center of the filter to // the pixel with coordinates (2, 2) should be 0, because its center // is at (2.5, 2.5). float destFilterDist = (srcBegin + 0.5f - srcPixel) * clampedScale; int filterCount = SkScalarTruncToInt(srcEnd - srcBegin) + 1; if (filterCount <= 0) { // true when srcSize is equal to srcPixel - srcSupport; this may be a bug return; } filterValuesArray.reset(filterCount); float filterSum = fBitmapFilter->evaluate_n(destFilterDist, clampedScale, filterCount, filterValuesArray.begin()); // The filter must be normalized so that we don't affect the brightness of // the image. Convert to normalized fixed point. int fixedSum = 0; fixedFilterValuesArray.reset(filterCount); const float* filterValues = filterValuesArray.begin(); SkConvolutionFilter1D::ConvolutionFixed* fixedFilterValues = fixedFilterValuesArray.begin(); float invFilterSum = 1 / filterSum; for (int fixedI = 0; fixedI < filterCount; fixedI++) { int curFixed = SkConvolutionFilter1D::FloatToFixed(filterValues[fixedI] * invFilterSum); fixedSum += curFixed; fixedFilterValues[fixedI] = SkToS16(curFixed); } SkASSERT(fixedSum <= 0x7FFF); // The conversion to fixed point will leave some rounding errors, which // we add back in to avoid affecting the brightness of the image. We // arbitrarily add this to the center of the filter array (this won't always // be the center of the filter function since it could get clipped on the // edges, but it doesn't matter enough to worry about that case). int leftovers = SkConvolutionFilter1D::FloatToFixed(1) - fixedSum; fixedFilterValues[filterCount / 2] += leftovers; // Now it's ready to go. output->AddFilter(SkScalarFloorToInt(srcBegin), fixedFilterValues, filterCount); } if (convolveProcs.fApplySIMDPadding) { convolveProcs.fApplySIMDPadding(output); } } /////////////////////////////////////////////////////////////////////////////////////////////////// static bool valid_for_resize(const SkPixmap& source, int dstW, int dstH) { // TODO: Seems like we shouldn't care about the swizzle of source, just that it's 8888 return source.addr() && source.colorType() == kN32_SkColorType && source.width() >= 1 && source.height() >= 1 && dstW >= 1 && dstH >= 1; } bool SkBitmapScaler::Resize(const SkPixmap& result, const SkPixmap& source, ResizeMethod method) { if (!valid_for_resize(source, result.width(), result.height())) { return false; } if (!result.addr() || result.colorType() != source.colorType()) { return false; } SkConvolutionProcs convolveProcs= { 0, nullptr, nullptr, nullptr, nullptr }; PlatformConvolutionProcs(&convolveProcs); SkRect destSubset = SkRect::MakeIWH(result.width(), result.height()); SkResizeFilter filter(method, source.width(), source.height(), result.width(), result.height(), destSubset, convolveProcs); // Get a subset encompassing this touched area. We construct the // offsets and row strides such that it looks like a new bitmap, while // referring to the old data. const uint8_t* sourceSubset = reinterpret_cast<const uint8_t*>(source.addr()); return BGRAConvolve2D(sourceSubset, static_cast<int>(source.rowBytes()), !source.isOpaque(), filter.xFilter(), filter.yFilter(), static_cast<int>(result.rowBytes()), static_cast<unsigned char*>(result.writable_addr()), convolveProcs, true); } bool SkBitmapScaler::Resize(SkBitmap* resultPtr, const SkPixmap& source, ResizeMethod method, int destWidth, int destHeight, SkBitmap::Allocator* allocator) { // Preflight some of the checks, to avoid allocating the result if we don't need it. if (!valid_for_resize(source, destWidth, destHeight)) { return false; } SkBitmap result; result.setInfo(SkImageInfo::MakeN32(destWidth, destHeight, source.alphaType())); result.allocPixels(allocator, nullptr); SkPixmap resultPM; if (!result.peekPixels(&resultPM) || !Resize(resultPM, source, method)) { return false; } *resultPtr = result; resultPtr->lockPixels(); SkASSERT(resultPtr->getPixels()); return true; } <|endoftext|>
<commit_before>// #undef UNICODE // #include <sstream> #include "logconsole.h" std::ostream& Core::Color::operator<<(std::ostream& os, Core::Color::CodeFG code) { #ifndef _WIN32 return os << "\033[1;" << static_cast<int>(code) << "m"; #else return os; #endif } std::ostream& Core::Color::operator<<(std::ostream& os, Core::Color::CodeBG code) { #ifndef _WIN32 return os << "\033[" << static_cast<int>(code) << "m"; #else return os; #endif } namespace Core { spdlog::level::level_enum CLog::level_ = spdlog::level::notice; void CLog::SetLevel(spdlog::level::level_enum _level) { level_ = _level; std::ostringstream format; format << "[%H:%M:%S.%e %z] [%L]"; if (level_ <= spdlog::level::debug) format << " [thread %t]"; format << " [%n]" << " %v "; spdlog::set_pattern(format.str()); } std::weak_ptr<spdlog::logger> CLog::GetLogger( log_type _type) { std::weak_ptr<spdlog::logger> logger; try { switch (_type) { case log_type::NETWORK: logger = spdlog::get("net"); break; case log_type::DATABASE: logger = spdlog::get("db"); break; case log_type::GENERAL: default: logger = spdlog::get("server"); break; } if (logger.expired()) { std::ostringstream format; format << "[%H:%M:%S.%e %z] [%L]"; if (level_ <= spdlog::level::debug) format << " [thread %t]"; format << " [%n]" << " %v "; size_t q_size = 1048576; spdlog::set_async_mode(q_size, spdlog::async_overflow_policy::discard_log_msg, nullptr, std::chrono::seconds(30)); std::string path, name; switch (_type) { case log_type::NETWORK: { path = "logs/network"; name = "net"; break; } case log_type::DATABASE: { path = "logs/database"; name = "db"; break; } case log_type::GENERAL: default: { path = "logs/server"; name = "server"; break; } } std::vector<spdlog::sink_ptr> net_sink; // auto console_out = spdlog::sinks::stdout_sink_mt::instance(); #ifdef _WIN32 auto console_out = spdlog::sinks::stdout_sink_st::instance(); auto console_sink = std::make_shared<spdlog::sinks::wincolor_sink_mt>(console_out); #else auto console_out = spdlog::sinks::stdout_sink_mt::instance(); auto console_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(console_out); #endif // auto daily_sink = std::make_shared<spdlog::sinks::daily_file_sink_mt>( // path.c_str(), "txt", 23, 59); net_sink.push_back(console_sink); // net_sink.push_back(daily_sink); auto net_logger = std::make_shared<spdlog::logger>( name.c_str(), begin(net_sink), end(net_sink)); net_logger->set_level(level_); net_logger->set_pattern(format.str()); spdlog::register_logger(net_logger); return net_logger; } } catch (const spdlog::spdlog_ex& ex) { std::cout << "Log failed: " << ex.what() << std::endl; } return logger; } } <commit_msg>Added microseconds to the log output<commit_after>// #undef UNICODE // #include <sstream> #include "logconsole.h" std::ostream& Core::Color::operator<<(std::ostream& os, Core::Color::CodeFG code) { #ifndef _WIN32 return os << "\033[1;" << static_cast<int>(code) << "m"; #else return os; #endif } std::ostream& Core::Color::operator<<(std::ostream& os, Core::Color::CodeBG code) { #ifndef _WIN32 return os << "\033[" << static_cast<int>(code) << "m"; #else return os; #endif } namespace Core { spdlog::level::level_enum CLog::level_ = spdlog::level::notice; void CLog::SetLevel(spdlog::level::level_enum _level) { level_ = _level; std::ostringstream format; format << "[%H:%M:%S.%e %z] [%L]"; if (level_ <= spdlog::level::debug) format << " [thread %t]"; format << " [%n]" << " %v "; spdlog::set_pattern(format.str()); } std::weak_ptr<spdlog::logger> CLog::GetLogger( log_type _type) { std::weak_ptr<spdlog::logger> logger; try { switch (_type) { case log_type::NETWORK: logger = spdlog::get("net"); break; case log_type::DATABASE: logger = spdlog::get("db"); break; case log_type::GENERAL: default: logger = spdlog::get("server"); break; } if (logger.expired()) { std::ostringstream format; format << "[%H:%M:%S.%e.%f %z] [%L]"; if (level_ <= spdlog::level::debug) format << " [thread %t]"; format << " [%n]" << " %v "; size_t q_size = 1048576; spdlog::set_async_mode(q_size, spdlog::async_overflow_policy::discard_log_msg, nullptr, std::chrono::seconds(30)); std::string path, name; switch (_type) { case log_type::NETWORK: { path = "logs/network"; name = "net"; break; } case log_type::DATABASE: { path = "logs/database"; name = "db"; break; } case log_type::GENERAL: default: { path = "logs/server"; name = "server"; break; } } std::vector<spdlog::sink_ptr> net_sink; // auto console_out = spdlog::sinks::stdout_sink_mt::instance(); #ifdef _WIN32 auto console_out = spdlog::sinks::stdout_sink_st::instance(); auto console_sink = std::make_shared<spdlog::sinks::wincolor_sink_mt>(console_out); #else auto console_out = spdlog::sinks::stdout_sink_mt::instance(); auto console_sink = std::make_shared<spdlog::sinks::ansicolor_sink>(console_out); #endif // auto daily_sink = std::make_shared<spdlog::sinks::daily_file_sink_mt>( // path.c_str(), "txt", 23, 59); net_sink.push_back(console_sink); // net_sink.push_back(daily_sink); auto net_logger = std::make_shared<spdlog::logger>( name.c_str(), begin(net_sink), end(net_sink)); net_logger->set_level(level_); net_logger->set_pattern(format.str()); spdlog::register_logger(net_logger); return net_logger; } } catch (const spdlog::spdlog_ex& ex) { std::cout << "Log failed: " << ex.what() << std::endl; } return logger; } } <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "strigithread.h" #include "strigi_thread.h" #include "strigilogging.h" #include <string> #include <cstring> #include <errno.h> #include <signal.h> #include <vector> #include <stdlib.h> #include <unistd.h> #include <sys/resource.h> #include <sys/syscall.h> // define two enums and a constant for use of ioprio enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE, }; enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER, }; #define IOPRIO_CLASS_SHIFT 13 using namespace std; vector<StrigiThread*> threads; void StrigiThread::stopThreads() { vector<StrigiThread*>::const_iterator i; for (i=threads.begin(); i!=threads.end(); ++i) { STRIGI_LOG_INFO ("strigi.daemon", string("stopping thread ") + (*i)->name); (*i)->stop(); STRIGI_LOG_INFO ("strigi.daemon", "stopped another thread "); } } extern "C" void quit_daemon(int signum) { STRIGI_LOG_INFO("strigi.daemon", "quit_daemon"); static int interruptcount = 0; vector<StrigiThread*>::const_iterator i; switch (++interruptcount) { case 1: STRIGI_LOG_INFO ("strigi.daemon", "stopping threads "); StrigiThread::stopThreads(); break; case 2: STRIGI_LOG_INFO ("strigi.daemon", "terminating threads "); for (i=threads.begin(); i!=threads.end(); ++i) { (*i)->terminate(); } break; case 3: default: STRIGI_LOG_FATAL ("strigi.daemon", "calling exit(1)") exit(1); } } struct sigaction quitaction; void set_quit_on_signal(int signum) { quitaction.sa_handler = quit_daemon; sigaction(signum, &quitaction, 0); } struct sigaction dummyaction; extern "C" void nothing(int) {} void set_wakeup_on_signal(int signum) { dummyaction.sa_handler = nothing; sigaction(signum, &dummyaction, 0); } extern "C" void* threadstarter(void *d) { // give this thread job batch job priority struct sched_param param; memset(&param, 0, sizeof(param)); param.sched_priority = 0; StrigiThread* thread = static_cast<StrigiThread*>(d); #ifndef __APPLE__ if (thread->getPriority() > 0) { #ifndef SCHED_BATCH #define SCHED_BATCH 3 #endif // renice the thread int r = setpriority(PRIO_PROCESS, 0, thread->getPriority()); if (r != 0) { STRIGI_LOG_ERROR (string("strigi.daemon.") + thread->name + ".threadstarter", string("error setting priority: ") + strerror(errno)); } r = sched_setscheduler(0, SCHED_BATCH, &param); if (r != 0) { STRIGI_LOG_INFO (string("strigi.daemon.") + thread->name + ".threadstarter", string("error setting to batch: ") + strerror(errno)); } #ifdef SYS_ioprio_set if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE<<IOPRIO_CLASS_SHIFT ) < 0 ) { fprintf(stderr, "cannot set io scheduling to idle (%s). " "Trying best effort.\n", strerror( errno )); if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, 7|IOPRIO_CLASS_BE<<IOPRIO_CLASS_SHIFT ) < 0 ) { fprintf( stderr, "cannot set io scheduling to best effort.\n"); } } #endif } #endif // start the actual work thread->run(0); STRIGI_LOG_DEBUG(string("strigi.daemon.") + thread->name + ".threadstarter", "end of thread"); STRIGI_THREAD_EXIT(0); return 0; } StrigiThread::StrigiThread(const char* n) :state(Idling),thread(0), name(n) { priority = 0; STRIGI_MUTEX_INIT(&lock); } StrigiThread::~StrigiThread() { STRIGI_MUTEX_DESTROY(&lock); } void StrigiThread::setState(State s) { STRIGI_MUTEX_LOCK(&lock); state = s; STRIGI_MUTEX_UNLOCK(&lock); } StrigiThread::State StrigiThread::getState() { State s; STRIGI_MUTEX_LOCK(&lock); s = state; STRIGI_MUTEX_UNLOCK(&lock); return s; } std::string StrigiThread::getStringState() { State s = getState(); std::string str; switch (s) { case Idling: str = "idling"; break; case Working: str = "working"; break; case Stopping: str = "stopping"; break; } return str; } int StrigiThread::start(int prio) { // set up signal handling set_quit_on_signal(SIGINT); set_quit_on_signal(SIGQUIT); set_quit_on_signal(SIGTERM); set_wakeup_on_signal(SIGALRM); threads.push_back(this); priority = prio; // start the indexer thread int r = STRIGI_THREAD_CREATE(&thread, threadstarter, this); if (r < 0) { STRIGI_LOG_ERROR ("strigi.daemon." + string(name), "cannot create thread"); return 1; } return 0; } void StrigiThread::stop() { state = Stopping; stopThread(); if (thread) { // signal the thread to wake up pthread_kill(thread, SIGALRM); // wait for the thread to finish STRIGI_THREAD_JOIN(thread); } thread = 0; } void StrigiThread::terminate() { // TODO } <commit_msg>SVN_SILENT remove extra ','<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "strigithread.h" #include "strigi_thread.h" #include "strigilogging.h" #include <string> #include <cstring> #include <errno.h> #include <signal.h> #include <vector> #include <stdlib.h> #include <unistd.h> #include <sys/resource.h> #include <sys/syscall.h> // define two enums and a constant for use of ioprio enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE }; enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER }; #define IOPRIO_CLASS_SHIFT 13 using namespace std; vector<StrigiThread*> threads; void StrigiThread::stopThreads() { vector<StrigiThread*>::const_iterator i; for (i=threads.begin(); i!=threads.end(); ++i) { STRIGI_LOG_INFO ("strigi.daemon", string("stopping thread ") + (*i)->name); (*i)->stop(); STRIGI_LOG_INFO ("strigi.daemon", "stopped another thread "); } } extern "C" void quit_daemon(int signum) { STRIGI_LOG_INFO("strigi.daemon", "quit_daemon"); static int interruptcount = 0; vector<StrigiThread*>::const_iterator i; switch (++interruptcount) { case 1: STRIGI_LOG_INFO ("strigi.daemon", "stopping threads "); StrigiThread::stopThreads(); break; case 2: STRIGI_LOG_INFO ("strigi.daemon", "terminating threads "); for (i=threads.begin(); i!=threads.end(); ++i) { (*i)->terminate(); } break; case 3: default: STRIGI_LOG_FATAL ("strigi.daemon", "calling exit(1)") exit(1); } } struct sigaction quitaction; void set_quit_on_signal(int signum) { quitaction.sa_handler = quit_daemon; sigaction(signum, &quitaction, 0); } struct sigaction dummyaction; extern "C" void nothing(int) {} void set_wakeup_on_signal(int signum) { dummyaction.sa_handler = nothing; sigaction(signum, &dummyaction, 0); } extern "C" void* threadstarter(void *d) { // give this thread job batch job priority struct sched_param param; memset(&param, 0, sizeof(param)); param.sched_priority = 0; StrigiThread* thread = static_cast<StrigiThread*>(d); #ifndef __APPLE__ if (thread->getPriority() > 0) { #ifndef SCHED_BATCH #define SCHED_BATCH 3 #endif // renice the thread int r = setpriority(PRIO_PROCESS, 0, thread->getPriority()); if (r != 0) { STRIGI_LOG_ERROR (string("strigi.daemon.") + thread->name + ".threadstarter", string("error setting priority: ") + strerror(errno)); } r = sched_setscheduler(0, SCHED_BATCH, &param); if (r != 0) { STRIGI_LOG_INFO (string("strigi.daemon.") + thread->name + ".threadstarter", string("error setting to batch: ") + strerror(errno)); } #ifdef SYS_ioprio_set if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, IOPRIO_CLASS_IDLE<<IOPRIO_CLASS_SHIFT ) < 0 ) { fprintf(stderr, "cannot set io scheduling to idle (%s). " "Trying best effort.\n", strerror( errno )); if (syscall(SYS_ioprio_set, IOPRIO_WHO_PROCESS, 0, 7|IOPRIO_CLASS_BE<<IOPRIO_CLASS_SHIFT ) < 0 ) { fprintf( stderr, "cannot set io scheduling to best effort.\n"); } } #endif } #endif // start the actual work thread->run(0); STRIGI_LOG_DEBUG(string("strigi.daemon.") + thread->name + ".threadstarter", "end of thread"); STRIGI_THREAD_EXIT(0); return 0; } StrigiThread::StrigiThread(const char* n) :state(Idling),thread(0), name(n) { priority = 0; STRIGI_MUTEX_INIT(&lock); } StrigiThread::~StrigiThread() { STRIGI_MUTEX_DESTROY(&lock); } void StrigiThread::setState(State s) { STRIGI_MUTEX_LOCK(&lock); state = s; STRIGI_MUTEX_UNLOCK(&lock); } StrigiThread::State StrigiThread::getState() { State s; STRIGI_MUTEX_LOCK(&lock); s = state; STRIGI_MUTEX_UNLOCK(&lock); return s; } std::string StrigiThread::getStringState() { State s = getState(); std::string str; switch (s) { case Idling: str = "idling"; break; case Working: str = "working"; break; case Stopping: str = "stopping"; break; } return str; } int StrigiThread::start(int prio) { // set up signal handling set_quit_on_signal(SIGINT); set_quit_on_signal(SIGQUIT); set_quit_on_signal(SIGTERM); set_wakeup_on_signal(SIGALRM); threads.push_back(this); priority = prio; // start the indexer thread int r = STRIGI_THREAD_CREATE(&thread, threadstarter, this); if (r < 0) { STRIGI_LOG_ERROR ("strigi.daemon." + string(name), "cannot create thread"); return 1; } return 0; } void StrigiThread::stop() { state = Stopping; stopThread(); if (thread) { // signal the thread to wake up pthread_kill(thread, SIGALRM); // wait for the thread to finish STRIGI_THREAD_JOIN(thread); } thread = 0; } void StrigiThread::terminate() { // TODO } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TableGrantCtrl.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: oj $ $Date: 2001-06-20 06:59:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_TABLEGRANTCONTROL_HXX #define DBAUI_TABLEGRANTCONTROL_HXX #ifndef _SVX_DBBROWSE_HXX #include <svx/dbbrowse.hxx> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif class Edit; namespace dbaui { class OTableGrantControl : public DbBrowseBox { DECLARE_STL_USTRINGACCESS_MAP(sal_Int32,TTablePrivilegeMap); ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUsers; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xTables; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xORB; ::com::sun::star::uno::Sequence< ::rtl::OUString> m_aTableNames; TTablePrivilegeMap m_aPrivMap; ::rtl::OUString m_sUserName; DbCheckBoxCtrl* m_pCheckCell; Edit* m_pEdit; long m_nDataPos; BOOL m_bEnable; public: OTableGrantControl( Window* pParent,const ResId& _RsId); virtual ~OTableGrantControl(); void UpdateTables(); void setUserName(const ::rtl::OUString _sUserName); void setTablesSupplier(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier >& _xTablesSup); void setORB(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _xORB); virtual void Init(); protected: virtual void Resize(); virtual long PreParentNotify(NotifyEvent& rNEvt ); virtual BOOL IsTabAllowed(BOOL bForward) const; virtual void InitController( DbCellControllerRef& rController, long nRow, USHORT nCol ); virtual DbCellController* GetController( long nRow, USHORT nCol ); virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, USHORT nColId ) const; virtual BOOL SeekRow( long nRow ); virtual BOOL SaveModified(); virtual String GetCellText( long nRow, USHORT nColId ); virtual void CellModified(); private: ULONG m_nDeActivateEvent; DECL_LINK( AsynchActivate, void* ); DECL_LINK( AsynchDeactivate, void* ); sal_Bool isAllowed(USHORT _nColumnId,sal_Int32 _nPrivilege) const; sal_Int32 fillPrivilege(sal_Int32 _nRow); }; } #endif // DBAUI_TABLEGRANTCONTROL_HXX<commit_msg>#87576# missing \n at end of file inserted<commit_after>/************************************************************************* * * $RCSfile: TableGrantCtrl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2001-06-20 11:25:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_TABLEGRANTCONTROL_HXX #define DBAUI_TABLEGRANTCONTROL_HXX #ifndef _SVX_DBBROWSE_HXX #include <svx/dbbrowse.hxx> #endif #ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_ #include <com/sun/star/sdbcx/XTablesSupplier.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif class Edit; namespace dbaui { class OTableGrantControl : public DbBrowseBox { DECLARE_STL_USTRINGACCESS_MAP(sal_Int32,TTablePrivilegeMap); ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUsers; ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xTables; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xORB; ::com::sun::star::uno::Sequence< ::rtl::OUString> m_aTableNames; TTablePrivilegeMap m_aPrivMap; ::rtl::OUString m_sUserName; DbCheckBoxCtrl* m_pCheckCell; Edit* m_pEdit; long m_nDataPos; BOOL m_bEnable; public: OTableGrantControl( Window* pParent,const ResId& _RsId); virtual ~OTableGrantControl(); void UpdateTables(); void setUserName(const ::rtl::OUString _sUserName); void setTablesSupplier(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier >& _xTablesSup); void setORB(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _xORB); virtual void Init(); protected: virtual void Resize(); virtual long PreParentNotify(NotifyEvent& rNEvt ); virtual BOOL IsTabAllowed(BOOL bForward) const; virtual void InitController( DbCellControllerRef& rController, long nRow, USHORT nCol ); virtual DbCellController* GetController( long nRow, USHORT nCol ); virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, USHORT nColId ) const; virtual BOOL SeekRow( long nRow ); virtual BOOL SaveModified(); virtual String GetCellText( long nRow, USHORT nColId ); virtual void CellModified(); private: ULONG m_nDeActivateEvent; DECL_LINK( AsynchActivate, void* ); DECL_LINK( AsynchDeactivate, void* ); sal_Bool isAllowed(USHORT _nColumnId,sal_Int32 _nPrivilege) const; sal_Int32 fillPrivilege(sal_Int32 _nRow); }; } #endif // DBAUI_TABLEGRANTCONTROL_HXX <|endoftext|>
<commit_before>// doosabin_regression.cpp // Includes #include <algorithm> #include <cstdio> #include <fstream> #include <iostream> #include <memory> #include <string> #include <streambuf> #include <utility> #include "ceres/ceres.h" #include "gflags/gflags.h" #include "glog/logging.h" #include <Eigen/Dense> #include "rapidjson/document.h" #include "rapidjson/filestream.h" #include "rapidjson/prettywriter.h" #include "Math/linalg.h" #include "Ceres/compose_cost_functions.h" #include "doosabin.h" #include "ceres_surface.h" #include "surface.h" // DooSabinSurface class DooSabinSurface : public Surface { public: typedef doosabin::Surface<double> Surface; explicit DooSabinSurface(const Surface* surface) : surface_(surface) {} #define EVALUATE(M, SIZE) \ virtual void M(double* r, const int p, const double* u, \ const double* const* X) const { \ const Eigen::Map<const Eigen::Vector2d> _u(u); \ const linalg::MatrixOfColumnPointers<double> _X( \ X, 3, surface_->patch_vertex_indices(p).size()); \ Eigen::Map<Eigen::VectorXd> _r(r, SIZE); \ surface_->M(p, _u, _X, &_r); \ } #define SIZE_JACOBIAN_X (3 * 3 * surface_->patch_vertex_indices(p).size()) EVALUATE(M, 3); EVALUATE(Mu, 3); EVALUATE(Mv, 3); EVALUATE(Muu, 3); EVALUATE(Muv, 3); EVALUATE(Mvv, 3); EVALUATE(Mx, SIZE_JACOBIAN_X); EVALUATE(Mux, SIZE_JACOBIAN_X); EVALUATE(Mvx, SIZE_JACOBIAN_X); #undef EVALUATE #undef SIZE_JACOBIAN_X virtual int number_of_vertices() const { return surface_->number_of_vertices(); } virtual int number_of_faces() const { return surface_->number_of_faces(); } virtual int number_of_patches() const { return surface_->number_of_patches(); } virtual const std::vector<int>& patch_vertex_indices(const int p) const { return surface_->patch_vertex_indices(p); } virtual const std::vector<int>& adjacent_patch_indices(const int p) const { return surface_->adjacent_patch_indices(p); } private: const Surface* surface_; }; // PositionErrorFunctor class PositionErrorFunctor { public: template <typename M> PositionErrorFunctor(const M& m0, const double& sqrt_w = 1.0) : m0_(m0), sqrt_w_(sqrt_w) {} template <typename T> bool operator()(const T* m, T* e) const { e[0] = T(sqrt_w_) * (T(m0_[0]) - m[0]); e[1] = T(sqrt_w_) * (T(m0_[1]) - m[1]); e[2] = T(sqrt_w_) * (T(m0_[2]) - m[2]); return true; } private: Eigen::Vector3d m0_; const double sqrt_w_; }; // PairwiseErrorFunctor class PairwiseErrorFunctor { public: PairwiseErrorFunctor(const double& sqrt_w = 1.0) : sqrt_w_(sqrt_w) {} template <typename T> bool operator()(const T* x0, const T* x1, T* e) const { e[0] = T(sqrt_w_) * (x1[0] - x0[0]); e[1] = T(sqrt_w_) * (x1[1] - x0[1]); e[2] = T(sqrt_w_) * (x1[2] - x0[2]); return true; } private: const double sqrt_w_; }; // ReadFileIntoDocument bool ReadFileIntoDocument(const std::string& input_path, rapidjson::Document* document) { std::ifstream input(input_path, std::ios::binary); if (!input) { LOG(ERROR) << "File \"" << input_path << "\" not found."; return false; } std::string input_string; input.seekg(0, std::ios::end); input_string.reserve(input.tellg()); input.seekg(0, std::ios::beg); input_string.assign((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>()); if (document->Parse<0>(input_string.c_str()).HasParseError()) { LOG(ERROR) << "Failed to parse input."; return false; } return true; } // LoadProblemFromFile bool LoadProblemFromFile(const std::string& input_path, Eigen::MatrixXd* Y, std::vector<int>* raw_face_array, Eigen::MatrixXd* X, Eigen::VectorXi* p, Eigen::MatrixXd* U) { rapidjson::Document document; if (!ReadFileIntoDocument(input_path, &document)) { return false; } #define LOAD_MATRIXD(SRC, DST, DIM) { \ CHECK(document.HasMember(#SRC)); \ auto& v = document[#SRC]; \ CHECK(v.IsArray()); \ DST->resize(DIM, v.Size() / DIM); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsDouble()); \ (*DST)(i % DIM, i / DIM) = v[i].GetDouble(); \ } \ } #define LOAD_VECTORI(SRC, DST) { \ CHECK(document.HasMember(#SRC)); \ auto& v = document[#SRC]; \ CHECK(v.IsArray()); \ DST->resize(v.Size()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsInt()); \ (*DST)[i] = v[i].GetInt(); \ } \ } LOAD_MATRIXD(Y, Y, 3); LOAD_VECTORI(raw_face_array, raw_face_array); LOAD_MATRIXD(X, X, 3); LOAD_VECTORI(p, p); LOAD_MATRIXD(U, U, 2); #undef LOAD_MATRIXD #undef LOAD_VECTORI return true; } // UpdateProblemToFile bool UpdateProblemToFile(const std::string& input_path, const std::string& output_path, const Eigen::MatrixXd& X, const Eigen::VectorXi& p, const Eigen::MatrixXd& U) { rapidjson::Document document; if (!ReadFileIntoDocument(input_path, &document)) { return false; } #define SAVE_MATRIXD(SRC, DST) { \ CHECK(document.HasMember(#DST)); \ auto& v = document[#DST]; \ CHECK(v.IsArray()); \ CHECK_EQ(v.Size(), SRC.rows() * SRC.cols()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsDouble()); \ v[i] = SRC(i % SRC.rows(), i / SRC.rows()); \ } \ } #define SAVE_VECTORI(SRC, DST) { \ CHECK(document.HasMember(#DST)); \ auto& v = document[#DST]; \ CHECK(v.IsArray()); \ CHECK_EQ(v.Size(), SRC.size()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsInt()); \ v[i] = SRC[i]; \ } \ } SAVE_MATRIXD(X, X); SAVE_VECTORI(p, p); SAVE_MATRIXD(U, U); // Use `fopen` instead of streams for `rapidjson::FileStream`. FILE* output_handle = fopen(output_path.c_str(), "wb"); if (output_handle == nullptr) { LOG(ERROR) << "Unable to open \"" << output_path << "\""; } rapidjson::FileStream output(output_handle); rapidjson::PrettyWriter<rapidjson::FileStream> writer(output); document.Accept(writer); fclose(output_handle); return true; } // main DEFINE_int32(max_num_iterations, 1000, "Maximum number of iterations."); DEFINE_double(function_tolerance, 0.0, "Minimizer terminates when " "(new_cost - old_cost) < function_tolerance * old_cost"); DEFINE_double(gradient_tolerance, 0.0, "Minimizer terminates when " "max_i |gradient_i| < gradient_tolerance * max_i|initial_gradient_i|"); DEFINE_double(parameter_tolerance, 0.0, "Minimizer terminates when " "|step|_2 <= parameter_tolerance * ( |x|_2 + parameter_tolerance)"); DEFINE_double(min_trust_region_radius, 1e-9, "Minimizer terminates when the trust region radius becomes smaller than " "this value"); DEFINE_int32(num_threads, 1, "Number of threads to use for Jacobian evaluation."); DEFINE_int32(num_linear_solver_threads, 1, "Number of threads to use for the linear solver."); int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (argc < 4) { LOG(ERROR) << "Usage: " << argv[0] << " input_path lambda output_path"; return -1; } // Load the problem data ... Eigen::MatrixXd Y; std::vector<int> raw_face_array; Eigen::MatrixXd X; Eigen::VectorXi p; Eigen::MatrixXd U; if (!LoadProblemFromFile(argv[1], &Y, &raw_face_array, &X, &p, &U)) { return -1; } // ... and check consistency of dimensions. typedef Eigen::DenseIndex Index; const Index num_data_points = Y.cols(); CHECK_GT(num_data_points, 0); CHECK_EQ(num_data_points, p.size()); CHECK_EQ(num_data_points, U.cols()); doosabin::GeneralMesh T(std::move(raw_face_array)); CHECK_GT(T.number_of_faces(), 0); doosabin::Surface<double> surface(T); DooSabinSurface doosabin_surface(&surface); CHECK_EQ(surface.number_of_vertices(), X.cols()); // `lambda` is the regularisation weight. const double lambda = atof(argv[2]); // Setup `problem`. ceres::Problem problem; // Encode patch indices into the preimage positions. for (Index i = 0; i < num_data_points; ++i) { EncodePatchIndexInPlace(U.data() + 2 * i, p[i]); } // Add error residuals. std::vector<double*> parameter_blocks; parameter_blocks.reserve(1 + surface.number_of_vertices()); parameter_blocks.push_back(nullptr); // `u`. for (Index i = 0; i < X.cols(); ++i) { parameter_blocks.push_back(X.data() + 3 * i); } std::unique_ptr<ceres::CostFunction> surface_position( new SurfacePositionCostFunction(&doosabin_surface)); for (Index i = 0; i < num_data_points; ++i) { parameter_blocks[0] = U.data() + 2 * i; auto position_error = new ceres_utility::GeneralCostFunctionComposition( new ceres::AutoDiffCostFunction<PositionErrorFunctor, 3, 3>( new PositionErrorFunctor(Y.col(i), 1.0 / sqrt(num_data_points)))); position_error->AddInputCostFunction(surface_position.get(), parameter_blocks, false); position_error->Finalise(); problem.AddResidualBlock(position_error, nullptr, parameter_blocks); } // Add regularisation residuals. // Note: `problem` takes ownership of `pairwise_error`. auto pairwise_error = new ceres::AutoDiffCostFunction<PairwiseErrorFunctor, 3, 3, 3>( new PairwiseErrorFunctor(sqrt(lambda))); std::set<std::pair<int, int>> full_edges; for (std::pair<int, int> e : T.iterate_half_edges()) { if (e.first > e.second) { std::swap(e.first, e.second); } if (!full_edges.count(e)) { problem.AddResidualBlock(pairwise_error, nullptr, X.data() + 3 * e.first, X.data() + 3 * e.second); full_edges.insert(e); } } // Set preimage parameterisations so that they are updated using // `doosabin::SurfaceWalker<double>` and NOT Euclidean addition. // Note: `problem` takes ownership of `local_parameterisation`. typedef doosabin::SurfaceWalker<double> DooSabinWalker; DooSabinWalker walker(&surface); auto local_parameterisation = new PreimageLocalParameterisation<DooSabinWalker, Eigen::MatrixXd>( &walker, &X); for (Index i = 0; i < num_data_points; ++i) { problem.SetParameterization(U.data() + 2 * i, local_parameterisation); } // Initialise the solver options. std::cout << "Solver options:" << std::endl; ceres::Solver::Options options; options.num_threads = FLAGS_num_threads; options.num_linear_solver_threads = FLAGS_num_linear_solver_threads; // Disable auto-scaling and set LM to be additive (instead of multiplicative). options.min_lm_diagonal = 1.0; options.max_lm_diagonal = 1.0; options.jacobi_scaling = false; options.minimizer_progress_to_stdout = FLAGS_v >= 1; // Termination criteria. options.max_num_iterations = FLAGS_max_num_iterations; std::cout << " max_num_iterations: " << options.max_num_iterations << std::endl; options.max_num_consecutive_invalid_steps = FLAGS_max_num_iterations; options.function_tolerance = FLAGS_function_tolerance; options.gradient_tolerance = FLAGS_gradient_tolerance; options.parameter_tolerance = FLAGS_parameter_tolerance; options.min_trust_region_radius = FLAGS_min_trust_region_radius; // Solver selection. options.dynamic_sparsity = true; // `update_state_every_iteration` is required by // `PreimageLocalParameterisation` instances. options.update_state_every_iteration = true; // Solve. std::cout << "Solving ..." << std::endl; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << std::endl; // Decode patch indices. for (Index i = 0; i < num_data_points; ++i) { p[i] = DecodePatchIndexInPlace(U.data() + 2 * i); } // Save. if (!UpdateProblemToFile(argv[1], argv[3], X, p, U)) { return -1; } std::cout << "Output: " << argv[3] << std::endl; return 0; } <commit_msg>Minor improvement to `ReadFileIntoDocument` in src/doosabin_regression.cpp<commit_after>// doosabin_regression.cpp // Includes #include <algorithm> #include <cstdio> #include <fstream> #include <iostream> #include <memory> #include <string> #include <sstream> #include <utility> #include "ceres/ceres.h" #include "gflags/gflags.h" #include "glog/logging.h" #include <Eigen/Dense> #include "rapidjson/document.h" #include "rapidjson/filestream.h" #include "rapidjson/prettywriter.h" #include "Math/linalg.h" #include "Ceres/compose_cost_functions.h" #include "doosabin.h" #include "ceres_surface.h" #include "surface.h" // DooSabinSurface class DooSabinSurface : public Surface { public: typedef doosabin::Surface<double> Surface; explicit DooSabinSurface(const Surface* surface) : surface_(surface) {} #define EVALUATE(M, SIZE) \ virtual void M(double* r, const int p, const double* u, \ const double* const* X) const { \ const Eigen::Map<const Eigen::Vector2d> _u(u); \ const linalg::MatrixOfColumnPointers<double> _X( \ X, 3, surface_->patch_vertex_indices(p).size()); \ Eigen::Map<Eigen::VectorXd> _r(r, SIZE); \ surface_->M(p, _u, _X, &_r); \ } #define SIZE_JACOBIAN_X (3 * 3 * surface_->patch_vertex_indices(p).size()) EVALUATE(M, 3); EVALUATE(Mu, 3); EVALUATE(Mv, 3); EVALUATE(Muu, 3); EVALUATE(Muv, 3); EVALUATE(Mvv, 3); EVALUATE(Mx, SIZE_JACOBIAN_X); EVALUATE(Mux, SIZE_JACOBIAN_X); EVALUATE(Mvx, SIZE_JACOBIAN_X); #undef EVALUATE #undef SIZE_JACOBIAN_X virtual int number_of_vertices() const { return surface_->number_of_vertices(); } virtual int number_of_faces() const { return surface_->number_of_faces(); } virtual int number_of_patches() const { return surface_->number_of_patches(); } virtual const std::vector<int>& patch_vertex_indices(const int p) const { return surface_->patch_vertex_indices(p); } virtual const std::vector<int>& adjacent_patch_indices(const int p) const { return surface_->adjacent_patch_indices(p); } private: const Surface* surface_; }; // PositionErrorFunctor class PositionErrorFunctor { public: template <typename M> PositionErrorFunctor(const M& m0, const double& sqrt_w = 1.0) : m0_(m0), sqrt_w_(sqrt_w) {} template <typename T> bool operator()(const T* m, T* e) const { e[0] = T(sqrt_w_) * (T(m0_[0]) - m[0]); e[1] = T(sqrt_w_) * (T(m0_[1]) - m[1]); e[2] = T(sqrt_w_) * (T(m0_[2]) - m[2]); return true; } private: Eigen::Vector3d m0_; const double sqrt_w_; }; // PairwiseErrorFunctor class PairwiseErrorFunctor { public: PairwiseErrorFunctor(const double& sqrt_w = 1.0) : sqrt_w_(sqrt_w) {} template <typename T> bool operator()(const T* x0, const T* x1, T* e) const { e[0] = T(sqrt_w_) * (x1[0] - x0[0]); e[1] = T(sqrt_w_) * (x1[1] - x0[1]); e[2] = T(sqrt_w_) * (x1[2] - x0[2]); return true; } private: const double sqrt_w_; }; // ReadFileIntoDocument bool ReadFileIntoDocument(const std::string& input_path, rapidjson::Document* document) { std::ifstream input(input_path, std::ios::binary); if (!input) { LOG(ERROR) << "File \"" << input_path << "\" not found."; return false; } std::stringstream input_ss; input_ss << input.rdbuf(); if (document->Parse<0>(input_ss.str().c_str()).HasParseError()) { LOG(ERROR) << "Failed to parse input."; return false; } return true; } // LoadProblemFromFile bool LoadProblemFromFile(const std::string& input_path, Eigen::MatrixXd* Y, std::vector<int>* raw_face_array, Eigen::MatrixXd* X, Eigen::VectorXi* p, Eigen::MatrixXd* U) { rapidjson::Document document; if (!ReadFileIntoDocument(input_path, &document)) { return false; } #define LOAD_MATRIXD(SRC, DST, DIM) { \ CHECK(document.HasMember(#SRC)); \ auto& v = document[#SRC]; \ CHECK(v.IsArray()); \ DST->resize(DIM, v.Size() / DIM); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsDouble()); \ (*DST)(i % DIM, i / DIM) = v[i].GetDouble(); \ } \ } #define LOAD_VECTORI(SRC, DST) { \ CHECK(document.HasMember(#SRC)); \ auto& v = document[#SRC]; \ CHECK(v.IsArray()); \ DST->resize(v.Size()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsInt()); \ (*DST)[i] = v[i].GetInt(); \ } \ } LOAD_MATRIXD(Y, Y, 3); LOAD_VECTORI(raw_face_array, raw_face_array); LOAD_MATRIXD(X, X, 3); LOAD_VECTORI(p, p); LOAD_MATRIXD(U, U, 2); #undef LOAD_MATRIXD #undef LOAD_VECTORI return true; } // UpdateProblemToFile bool UpdateProblemToFile(const std::string& input_path, const std::string& output_path, const Eigen::MatrixXd& X, const Eigen::VectorXi& p, const Eigen::MatrixXd& U) { rapidjson::Document document; if (!ReadFileIntoDocument(input_path, &document)) { return false; } #define SAVE_MATRIXD(SRC, DST) { \ CHECK(document.HasMember(#DST)); \ auto& v = document[#DST]; \ CHECK(v.IsArray()); \ CHECK_EQ(v.Size(), SRC.rows() * SRC.cols()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsDouble()); \ v[i] = SRC(i % SRC.rows(), i / SRC.rows()); \ } \ } #define SAVE_VECTORI(SRC, DST) { \ CHECK(document.HasMember(#DST)); \ auto& v = document[#DST]; \ CHECK(v.IsArray()); \ CHECK_EQ(v.Size(), SRC.size()); \ for (rapidjson::SizeType i = 0; i < v.Size(); ++i) { \ CHECK(v[i].IsInt()); \ v[i] = SRC[i]; \ } \ } SAVE_MATRIXD(X, X); SAVE_VECTORI(p, p); SAVE_MATRIXD(U, U); // Use `fopen` instead of streams for `rapidjson::FileStream`. FILE* output_handle = fopen(output_path.c_str(), "wb"); if (output_handle == nullptr) { LOG(ERROR) << "Unable to open \"" << output_path << "\""; } rapidjson::FileStream output(output_handle); rapidjson::PrettyWriter<rapidjson::FileStream> writer(output); document.Accept(writer); fclose(output_handle); return true; } // main DEFINE_int32(max_num_iterations, 1000, "Maximum number of iterations."); DEFINE_double(function_tolerance, 0.0, "Minimizer terminates when " "(new_cost - old_cost) < function_tolerance * old_cost"); DEFINE_double(gradient_tolerance, 0.0, "Minimizer terminates when " "max_i |gradient_i| < gradient_tolerance * max_i|initial_gradient_i|"); DEFINE_double(parameter_tolerance, 0.0, "Minimizer terminates when " "|step|_2 <= parameter_tolerance * ( |x|_2 + parameter_tolerance)"); DEFINE_double(min_trust_region_radius, 1e-9, "Minimizer terminates when the trust region radius becomes smaller than " "this value"); DEFINE_int32(num_threads, 1, "Number of threads to use for Jacobian evaluation."); DEFINE_int32(num_linear_solver_threads, 1, "Number of threads to use for the linear solver."); int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (argc < 4) { LOG(ERROR) << "Usage: " << argv[0] << " input_path lambda output_path"; return -1; } // Load the problem data ... Eigen::MatrixXd Y; std::vector<int> raw_face_array; Eigen::MatrixXd X; Eigen::VectorXi p; Eigen::MatrixXd U; if (!LoadProblemFromFile(argv[1], &Y, &raw_face_array, &X, &p, &U)) { return -1; } // ... and check consistency of dimensions. typedef Eigen::DenseIndex Index; const Index num_data_points = Y.cols(); CHECK_GT(num_data_points, 0); CHECK_EQ(num_data_points, p.size()); CHECK_EQ(num_data_points, U.cols()); doosabin::GeneralMesh T(std::move(raw_face_array)); CHECK_GT(T.number_of_faces(), 0); doosabin::Surface<double> surface(T); DooSabinSurface doosabin_surface(&surface); CHECK_EQ(surface.number_of_vertices(), X.cols()); // `lambda` is the regularisation weight. const double lambda = atof(argv[2]); // Setup `problem`. ceres::Problem problem; // Encode patch indices into the preimage positions. for (Index i = 0; i < num_data_points; ++i) { EncodePatchIndexInPlace(U.data() + 2 * i, p[i]); } // Add error residuals. std::vector<double*> parameter_blocks; parameter_blocks.reserve(1 + surface.number_of_vertices()); parameter_blocks.push_back(nullptr); // `u`. for (Index i = 0; i < X.cols(); ++i) { parameter_blocks.push_back(X.data() + 3 * i); } std::unique_ptr<ceres::CostFunction> surface_position( new SurfacePositionCostFunction(&doosabin_surface)); for (Index i = 0; i < num_data_points; ++i) { parameter_blocks[0] = U.data() + 2 * i; auto position_error = new ceres_utility::GeneralCostFunctionComposition( new ceres::AutoDiffCostFunction<PositionErrorFunctor, 3, 3>( new PositionErrorFunctor(Y.col(i), 1.0 / sqrt(num_data_points)))); position_error->AddInputCostFunction(surface_position.get(), parameter_blocks, false); position_error->Finalise(); problem.AddResidualBlock(position_error, nullptr, parameter_blocks); } // Add regularisation residuals. // Note: `problem` takes ownership of `pairwise_error`. auto pairwise_error = new ceres::AutoDiffCostFunction<PairwiseErrorFunctor, 3, 3, 3>( new PairwiseErrorFunctor(sqrt(lambda))); std::set<std::pair<int, int>> full_edges; for (std::pair<int, int> e : T.iterate_half_edges()) { if (e.first > e.second) { std::swap(e.first, e.second); } if (!full_edges.count(e)) { problem.AddResidualBlock(pairwise_error, nullptr, X.data() + 3 * e.first, X.data() + 3 * e.second); full_edges.insert(e); } } // Set preimage parameterisations so that they are updated using // `doosabin::SurfaceWalker<double>` and NOT Euclidean addition. // Note: `problem` takes ownership of `local_parameterisation`. typedef doosabin::SurfaceWalker<double> DooSabinWalker; DooSabinWalker walker(&surface); auto local_parameterisation = new PreimageLocalParameterisation<DooSabinWalker, Eigen::MatrixXd>( &walker, &X); for (Index i = 0; i < num_data_points; ++i) { problem.SetParameterization(U.data() + 2 * i, local_parameterisation); } // Initialise the solver options. std::cout << "Solver options:" << std::endl; ceres::Solver::Options options; options.num_threads = FLAGS_num_threads; options.num_linear_solver_threads = FLAGS_num_linear_solver_threads; // Disable auto-scaling and set LM to be additive (instead of multiplicative). options.min_lm_diagonal = 1.0; options.max_lm_diagonal = 1.0; options.jacobi_scaling = false; options.minimizer_progress_to_stdout = FLAGS_v >= 1; // Termination criteria. options.max_num_iterations = FLAGS_max_num_iterations; std::cout << " max_num_iterations: " << options.max_num_iterations << std::endl; options.max_num_consecutive_invalid_steps = FLAGS_max_num_iterations; options.function_tolerance = FLAGS_function_tolerance; options.gradient_tolerance = FLAGS_gradient_tolerance; options.parameter_tolerance = FLAGS_parameter_tolerance; options.min_trust_region_radius = FLAGS_min_trust_region_radius; // Solver selection. options.dynamic_sparsity = true; // `update_state_every_iteration` is required by // `PreimageLocalParameterisation` instances. options.update_state_every_iteration = true; // Solve. std::cout << "Solving ..." << std::endl; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << std::endl; // Decode patch indices. for (Index i = 0; i < num_data_points; ++i) { p[i] = DecodePatchIndexInPlace(U.data() + 2 * i); } // Save. if (!UpdateProblemToFile(argv[1], argv[3], X, p, U)) { return -1; } std::cout << "Output: " << argv[3] << std::endl; return 0; } <|endoftext|>
<commit_before>#include <stdexcept> #include <iostream> #include <csignal> #include <boost/program_options.hpp> #include "cppkafka/consumer.h" #include "cppkafka/configuration.h" using std::string; using std::exception; using std::cout; using std::endl; using cppkafka::Consumer; using cppkafka::Configuration; using cppkafka::Message; namespace po = boost::program_options; bool running = true; int main(int argc, char* argv[]) { string brokers; string topic_name; string group_id; po::options_description options("Options"); options.add_options() ("help,h", "produce this help message") ("brokers", po::value<string>(&brokers)->required(), "the kafka broker list") ("topic", po::value<string>(&topic_name)->required(), "the topic in which to write to") ("group-id", po::value<string>(&group_id)->required(), "the consumer group id") ; po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(options).run(), vm); po::notify(vm); } catch (exception& ex) { cout << "Error parsing options: " << ex.what() << endl; cout << endl; cout << options << endl; return 1; } // Stop processing on SIGINT signal(SIGINT, [](int) { running = false; }); // Construct the configuration Configuration config; config.set("metadata.broker.list", brokers); config.set("group.id", group_id); // Disable auto commit config.set("enable.auto.commit", false); // Create the consumer Consumer consumer(config); // Subscribe to the topic consumer.subscribe({ topic_name }); cout << "Consuming messages from topic " << topic_name << endl; // Now read lines and write them into kafka while (running) { // Try to consume a message Message msg = consumer.poll(); if (msg) { // If we managed to get a message if (msg.has_error()) { if (msg.get_error() != RD_KAFKA_RESP_ERR__PARTITION_EOF) { cout << "[+] Received error notification: " << msg.get_error_string() << endl; } } else { // Print the key (if any) if (msg.get_key()) { cout << msg.get_key() << " -> "; } // Print the payload cout << msg.get_payload() << endl; // Now commit the message consumer.commit(msg); } } } } <commit_msg>Print assigned and revoked partitions on consumer example<commit_after>#include <stdexcept> #include <iostream> #include <csignal> #include <boost/program_options.hpp> #include "cppkafka/consumer.h" #include "cppkafka/configuration.h" using std::string; using std::exception; using std::cout; using std::endl; using cppkafka::Consumer; using cppkafka::Configuration; using cppkafka::Message; using cppkafka::TopicPartitionList; namespace po = boost::program_options; bool running = true; int main(int argc, char* argv[]) { string brokers; string topic_name; string group_id; po::options_description options("Options"); options.add_options() ("help,h", "produce this help message") ("brokers", po::value<string>(&brokers)->required(), "the kafka broker list") ("topic", po::value<string>(&topic_name)->required(), "the topic in which to write to") ("group-id", po::value<string>(&group_id)->required(), "the consumer group id") ; po::variables_map vm; try { po::store(po::command_line_parser(argc, argv).options(options).run(), vm); po::notify(vm); } catch (exception& ex) { cout << "Error parsing options: " << ex.what() << endl; cout << endl; cout << options << endl; return 1; } // Stop processing on SIGINT signal(SIGINT, [](int) { running = false; }); // Construct the configuration Configuration config; config.set("metadata.broker.list", brokers); config.set("group.id", group_id); // Disable auto commit config.set("enable.auto.commit", false); // Create the consumer Consumer consumer(config); // Print the assigned partitions on assignment consumer.set_assignment_callback([](const TopicPartitionList& partitions) { cout << "Got assigned: " << partitions << endl; }); // Print the revoked partitions on revocation consumer.set_revocation_callback([](const TopicPartitionList& partitions) { cout << "Got revoked: " << partitions << endl; }); // Subscribe to the topic consumer.subscribe({ topic_name }); cout << "Consuming messages from topic " << topic_name << endl; // Now read lines and write them into kafka while (running) { // Try to consume a message Message msg = consumer.poll(); if (msg) { // If we managed to get a message if (msg.has_error()) { if (msg.get_error() != RD_KAFKA_RESP_ERR__PARTITION_EOF) { cout << "[+] Received error notification: " << msg.get_error_string() << endl; } } else { // Print the key (if any) if (msg.get_key()) { cout << msg.get_key() << " -> "; } // Print the payload cout << msg.get_payload() << endl; // Now commit the message consumer.commit(msg); } } } } <|endoftext|>
<commit_before>#include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <leveldb/db.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/imgproc/imgproc.hpp> #include <stdint.h> #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" namespace caffe { using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; close(fd); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; ZeroCopyInputStream* raw_input = new FileInputStream(fd); CodedInputStream* coded_input = new CodedInputStream(raw_input); coded_input->SetTotalBytesLimit(1073741824, 536870912); bool success = proto->ParseFromCodedStream(coded_input); delete coded_input; delete raw_input; close(fd); return success; } void WriteProtoToBinaryFile(const Message& proto, const char* filename) { fstream output(filename, ios::out | ios::trunc | ios::binary); CHECK(proto.SerializeToOstream(&output)); } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, const bool is_color, Datum* datum) { cv::Mat cv_img; int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag); if (!cv_img_origin.data) { LOG(ERROR) << "Could not open or find file " << filename; return false; } if (height > 0 && width > 0) { cv::resize(cv_img_origin, cv_img, cv::Size(width, height)); } else { cv_img = cv_img_origin; } int num_channels = (is_color ? 3 : 1); datum->set_channels(num_channels); datum->set_height(cv_img.rows); datum->set_width(cv_img.cols); datum->set_label(label); datum->clear_data(); datum->clear_float_data(); string* datum_string = datum->mutable_data(); if (is_color) { for (int c = 0; c < num_channels; ++c) { for (int h = 0; h < cv_img.rows; ++h) { for (int w = 0; w < cv_img.cols; ++w) { datum_string->push_back( static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c])); } } } } else { // Faster than repeatedly testing is_color for each pixel w/i loop for (int h = 0; h < cv_img.rows; ++h) { for (int w = 0; w < cv_img.cols; ++w) { datum_string->push_back( static_cast<char>(cv_img.at<uchar>(h, w))); } } } return true; } leveldb::Options GetLevelDBOptions() { // In default, we will return the leveldb option and set the max open files // in order to avoid using up the operating system's limit. leveldb::Options options; options.max_open_files = 100; return options; } // Verifies format of data stored in HDF5 file and reshapes blob accordingly. template <typename Dtype> void hdf5_load_nd_dataset_helper( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob) { // Verify that the number of dimensions is in the accepted range. herr_t status; int ndims; status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims); CHECK_GE(status, 0) << "Failed to get dataset ndims for " << dataset_name_; CHECK_GE(ndims, min_dim); CHECK_LE(ndims, max_dim); // Verify that the data format is what we expect: float or double. std::vector<hsize_t> dims(ndims); H5T_class_t class_; status = H5LTget_dataset_info( file_id, dataset_name_, dims.data(), &class_, NULL); CHECK_GE(status, 0) << "Failed to get dataset info for " << dataset_name_; CHECK_EQ(class_, H5T_FLOAT) << "Expected float or double data"; blob->Reshape( dims[0], (dims.size() > 1) ? dims[1] : 1, (dims.size() > 2) ? dims[2] : 1, (dims.size() > 3) ? dims[3] : 1); } template <> void hdf5_load_nd_dataset<float>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<float>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_float( file_id, dataset_name_, blob->mutable_cpu_data()); CHECK_GE(status, 0) << "Failed to read float dataset " << dataset_name_; } template <> void hdf5_load_nd_dataset<double>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<double>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_double( file_id, dataset_name_, blob->mutable_cpu_data()); CHECK_GE(status, 0) << "Failed to read double dataset " << dataset_name_; } template <> void hdf5_save_nd_dataset<float>( const hid_t file_id, const string dataset_name, const Blob<float>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_float( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make float dataset " << dataset_name; } template <> void hdf5_save_nd_dataset<double>( const hid_t file_id, const string dataset_name, const Blob<double>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_double( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make double dataset " << dataset_name; } } // namespace caffe <commit_msg>hdf5_load_nd_dataset_helper: check that dataset exists first<commit_after>#include <fcntl.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <leveldb/db.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/highgui/highgui_c.h> #include <opencv2/imgproc/imgproc.hpp> #include <stdint.h> #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <string> #include <vector> #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" namespace caffe { using google::protobuf::io::FileInputStream; using google::protobuf::io::FileOutputStream; using google::protobuf::io::ZeroCopyInputStream; using google::protobuf::io::CodedInputStream; using google::protobuf::io::ZeroCopyOutputStream; using google::protobuf::io::CodedOutputStream; using google::protobuf::Message; bool ReadProtoFromTextFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; FileInputStream* input = new FileInputStream(fd); bool success = google::protobuf::TextFormat::Parse(input, proto); delete input; close(fd); return success; } void WriteProtoToTextFile(const Message& proto, const char* filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); FileOutputStream* output = new FileOutputStream(fd); CHECK(google::protobuf::TextFormat::Print(proto, output)); delete output; close(fd); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto) { int fd = open(filename, O_RDONLY); CHECK_NE(fd, -1) << "File not found: " << filename; ZeroCopyInputStream* raw_input = new FileInputStream(fd); CodedInputStream* coded_input = new CodedInputStream(raw_input); coded_input->SetTotalBytesLimit(1073741824, 536870912); bool success = proto->ParseFromCodedStream(coded_input); delete coded_input; delete raw_input; close(fd); return success; } void WriteProtoToBinaryFile(const Message& proto, const char* filename) { fstream output(filename, ios::out | ios::trunc | ios::binary); CHECK(proto.SerializeToOstream(&output)); } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, const bool is_color, Datum* datum) { cv::Mat cv_img; int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag); if (!cv_img_origin.data) { LOG(ERROR) << "Could not open or find file " << filename; return false; } if (height > 0 && width > 0) { cv::resize(cv_img_origin, cv_img, cv::Size(width, height)); } else { cv_img = cv_img_origin; } int num_channels = (is_color ? 3 : 1); datum->set_channels(num_channels); datum->set_height(cv_img.rows); datum->set_width(cv_img.cols); datum->set_label(label); datum->clear_data(); datum->clear_float_data(); string* datum_string = datum->mutable_data(); if (is_color) { for (int c = 0; c < num_channels; ++c) { for (int h = 0; h < cv_img.rows; ++h) { for (int w = 0; w < cv_img.cols; ++w) { datum_string->push_back( static_cast<char>(cv_img.at<cv::Vec3b>(h, w)[c])); } } } } else { // Faster than repeatedly testing is_color for each pixel w/i loop for (int h = 0; h < cv_img.rows; ++h) { for (int w = 0; w < cv_img.cols; ++w) { datum_string->push_back( static_cast<char>(cv_img.at<uchar>(h, w))); } } } return true; } leveldb::Options GetLevelDBOptions() { // In default, we will return the leveldb option and set the max open files // in order to avoid using up the operating system's limit. leveldb::Options options; options.max_open_files = 100; return options; } // Verifies format of data stored in HDF5 file and reshapes blob accordingly. template <typename Dtype> void hdf5_load_nd_dataset_helper( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob) { // Verify that the dataset exists. CHECK(H5LTfind_dataset(file_id, dataset_name_)) << "Failed to find HDF5 dataset " << dataset_name_; // Verify that the number of dimensions is in the accepted range. herr_t status; int ndims; status = H5LTget_dataset_ndims(file_id, dataset_name_, &ndims); CHECK_GE(status, 0) << "Failed to get dataset ndims for " << dataset_name_; CHECK_GE(ndims, min_dim); CHECK_LE(ndims, max_dim); // Verify that the data format is what we expect: float or double. std::vector<hsize_t> dims(ndims); H5T_class_t class_; status = H5LTget_dataset_info( file_id, dataset_name_, dims.data(), &class_, NULL); CHECK_GE(status, 0) << "Failed to get dataset info for " << dataset_name_; CHECK_EQ(class_, H5T_FLOAT) << "Expected float or double data"; blob->Reshape( dims[0], (dims.size() > 1) ? dims[1] : 1, (dims.size() > 2) ? dims[2] : 1, (dims.size() > 3) ? dims[3] : 1); } template <> void hdf5_load_nd_dataset<float>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<float>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_float( file_id, dataset_name_, blob->mutable_cpu_data()); CHECK_GE(status, 0) << "Failed to read float dataset " << dataset_name_; } template <> void hdf5_load_nd_dataset<double>(hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<double>* blob) { hdf5_load_nd_dataset_helper(file_id, dataset_name_, min_dim, max_dim, blob); herr_t status = H5LTread_dataset_double( file_id, dataset_name_, blob->mutable_cpu_data()); CHECK_GE(status, 0) << "Failed to read double dataset " << dataset_name_; } template <> void hdf5_save_nd_dataset<float>( const hid_t file_id, const string dataset_name, const Blob<float>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_float( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make float dataset " << dataset_name; } template <> void hdf5_save_nd_dataset<double>( const hid_t file_id, const string dataset_name, const Blob<double>& blob) { hsize_t dims[HDF5_NUM_DIMS]; dims[0] = blob.num(); dims[1] = blob.channels(); dims[2] = blob.height(); dims[3] = blob.width(); herr_t status = H5LTmake_dataset_double( file_id, dataset_name.c_str(), HDF5_NUM_DIMS, dims, blob.cpu_data()); CHECK_GE(status, 0) << "Failed to make double dataset " << dataset_name; } } // namespace caffe <|endoftext|>
<commit_before>/* This file is part of KXForms. Copyright (c) 2006 Cornelius Schumacher <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "formcreator.h" #include "xmlbuilder.h" #include <QDebug> using namespace KXForms; FormCreator::FormCreator() { } QString FormCreator::create( const Schema::Document &schemaDocument ) { qDebug() << "---FormCreator::create()"; mDocument = schemaDocument; mCollapsedForms.clear(); XmlBuilder xml( "kxforms" ); createForm( &xml, schemaDocument.startElement() ); foreach ( Schema::Element element, schemaDocument.usedElements() ) { if ( element.identifier() != schemaDocument.startElement().identifier() ) { createForm( &xml, element ); } } qDebug() << "---FormCreator::create() done"; return xml.print(); } void FormCreator::createForm( XmlBuilder *xml, const Schema::Element &element ) { if ( mCollapsedForms.contains( element.name() ) ) return; qDebug() << "ELEMENT" << element.name(); XmlBuilder *form = xml->tag( "form" )->attribute( "ref", element.name() ); form->tag( "xf:label", humanizeString( element.name() ) ); parseAttributes( element, form ); parseElement( element, form ); } void FormCreator::parseAttributes( const Schema::Element &element, XmlBuilder *xml ) { foreach( Schema::Relation r, element.attributeRelations() ) { Schema::Attribute a = mDocument.attribute( r ); qDebug() << " ATTRIBUTE: " << a.identifier(); if ( a.type() == Schema::Attribute::String ) { XmlBuilder *input = xml->tag( "xf:input" ); input->attribute( "ref", a.ref() ); createLabel( input, a ); } else if ( a.type() == Schema::Attribute::Enumeration ) { XmlBuilder *select1 = xml->tag( "xf:select1" ); select1->attribute( "ref", a.ref() ); createLabel( select1, a ); foreach( QString value, a.enumerationValues() ) { XmlBuilder *item = select1->tag( "xf:item" ); QString itemLabel; Hint hint = mHints.hint( element.identifier() + '/' + a.ref() ); if ( hint.isValid() ) itemLabel = hint.enumValue( value ); if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value ); item->tag( "xf:label", itemLabel ); item->tag( "xf:value", value ); } } else { qDebug() << "Unsupported type: " << a.type(); } } } void FormCreator::parseElement( const Schema::Element &element, XmlBuilder *xml ) { if ( element.type() == Schema::Node::String ) { XmlBuilder *textArea = xml->tag( "xf:textarea" ); textArea->attribute( "ref", "." ); createLabel( textArea, element ); } else if ( element.type() == Schema::Node::NormalizedString || element.type() == Schema::Node::Token ) { XmlBuilder *input = xml->tag( "xf:input" ); input->attribute( "ref", "." ); createLabel( input, element ); } else if ( element.type() == Schema::Node::ComplexType ) { parseComplexType( element, xml, true ); } else { qDebug() << "Unsupported type: " << element.type(); } } void FormCreator::parseComplexType( const Schema::Element &element, XmlBuilder *xml, bool topLevel ) { QString currentChoice; XmlBuilder *section; bool choiceOnly = true; foreach( Schema::Relation r, element.elementRelations() ) { if( r.choice().isEmpty() ) choiceOnly = false; } if( !topLevel && !element.mixed() && !choiceOnly ) { section = xml->tag( "kxf:section" ); createLabel( section, element ); } /*else if( !topLevel && element.type() == ) { section = xml->tag( "kxf:section" ); createLabel( section, element ); } */else { section = xml; } XmlBuilder *list = 0; XmlBuilder *choice = 0; foreach( Schema::Relation r, element.elementRelations() ) { qDebug() << " CHILD ELEMENT" << r.target(); qDebug() << " CHOICE" << r.choice(); if ( r.isList() ) { bool isMixedList = r.choice().contains( "+" ); if ( !list || r.choice().isEmpty() || currentChoice != r.choice() ) { list = section->tag( "list" ); QString label; if ( isMixedList ) { label = "Item"; } else { label = getLabel( element.identifier() + '[' + r.target() + ']' ); if ( label.isEmpty() ) { label = humanizeString( r.target(), true ); } } list->tag( "xf:label", label ); } XmlBuilder *item = list->tag( "itemclass" ); item->attribute( "ref", r.target() ); QString itemLabel; itemLabel = getLabel( element.identifier() + '/' + r.target() ); Schema::Element itemElement = mDocument.element( r ); if ( itemLabel.isEmpty() ) { // Try to guess a suitable item label. foreach( Schema::Relation r2, itemElement.attributeRelations() ) { if ( r2.target() == "name" ) { if ( isMixedList ) { itemLabel = humanizeString( itemElement.name() ) + ": "; } itemLabel += "<arg ref=\"@name\"/>"; break; } } } if ( itemLabel.isEmpty() ) { if ( itemElement.type() == Schema::Node::String ) { itemLabel += "<arg ref=\".\" truncate=\"40\"/>"; } else if ( itemElement.type() == Schema::Node::NormalizedString || itemElement.type() == Schema::Node::Token ) { itemLabel += "<arg ref=\".\"/>"; } } if ( itemLabel.isEmpty() ) itemLabel = humanizeString( r.target() ); item->tag( "itemlabel", itemLabel ); currentChoice = r.choice(); } else if( !r.choice().isEmpty() ) { if( !choice ) { choice = section->tag( "xf:select1" ); choice->tag( "xf:label", humanizeString( element.name() ) ); } Schema::Element choiceElement = mDocument.element( r ); XmlBuilder *item = choice->tag( "xf:item" ); QString value = choiceElement.name(); QString itemLabel; Hint hint = mHints.hint( element.identifier() + '/' + choiceElement.ref() ); if ( hint.isValid() ) itemLabel = hint.enumValue( value ); if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value ); item->tag( "xf:label", itemLabel ); item->tag( "xf:value", value ); } else{ Schema::Element textElement = mDocument.element( r.target() ); if( textElement.type() == Schema::Node::ComplexType && !textElement.mixed() ) { parseComplexType( textElement, section, false ); } else { XmlBuilder *textInput = 0; if ( textElement.type() == Schema::Node::NormalizedString ) { textInput = section->tag( "xf:input" ); } else { textInput = section->tag( "xf:textarea" ); } textInput->attribute( "ref", textElement.name() ); createLabel( textInput, textElement ); mCollapsedForms.append( r.target() ); } } } } QString FormCreator::humanizeString( const QString &str, bool pluralize ) { if ( str.isEmpty() ) return str; QString result = str[0].toUpper() + str.mid( 1 ); if ( pluralize ) { if ( result.endsWith( "y" ) ) { result = result.left( str.length() - 1 ) + "ies"; } else { result += 's'; } } return result; } void FormCreator::setHints( const Hints &hints ) { mHints = hints; } void FormCreator::mergeHints( const Hints &hints ) { foreach( Hint h, hints.hints() ) { mHints.insertHint( h ); } } void FormCreator::createLabel( XmlBuilder *parent, const Schema::Node &node ) { parent->tag( "xf:label", getLabel( node.identifier(), node.name() ) ); } QString FormCreator::getLabel( const QString &ref, const QString &fallback, bool pluralize ) { // qDebug() << "GETLABEL: " << ref; QString label; Hint hint = mHints.hint( ref ); if ( hint.isValid() ) label = hint.label(); if ( label.isEmpty() ) label = humanizeString( fallback, pluralize ); return label; } Hints FormCreator::hints() const { return mHints; } <commit_msg>Apply hints on choice elements. Create a textarea element if a complextype has no elementrelation.<commit_after>/* This file is part of KXForms. Copyright (c) 2006 Cornelius Schumacher <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "formcreator.h" #include "xmlbuilder.h" #include <QDebug> using namespace KXForms; FormCreator::FormCreator() { } QString FormCreator::create( const Schema::Document &schemaDocument ) { qDebug() << "---FormCreator::create()"; mDocument = schemaDocument; mCollapsedForms.clear(); XmlBuilder xml( "kxforms" ); createForm( &xml, schemaDocument.startElement() ); foreach ( Schema::Element element, schemaDocument.usedElements() ) { if ( element.identifier() != schemaDocument.startElement().identifier() ) { createForm( &xml, element ); } } qDebug() << "---FormCreator::create() done"; return xml.print(); } void FormCreator::createForm( XmlBuilder *xml, const Schema::Element &element ) { if ( mCollapsedForms.contains( element.name() ) ) return; qDebug() << "ELEMENT" << element.name(); XmlBuilder *form = xml->tag( "form" )->attribute( "ref", element.name() ); form->tag( "xf:label", humanizeString( element.name() ) ); parseAttributes( element, form ); parseElement( element, form ); } void FormCreator::parseAttributes( const Schema::Element &element, XmlBuilder *xml ) { foreach( Schema::Relation r, element.attributeRelations() ) { Schema::Attribute a = mDocument.attribute( r ); qDebug() << " ATTRIBUTE: " << a.identifier(); if ( a.type() == Schema::Attribute::String ) { XmlBuilder *input = xml->tag( "xf:input" ); input->attribute( "ref", a.ref() ); createLabel( input, a ); } else if ( a.type() == Schema::Attribute::Enumeration ) { XmlBuilder *select1 = xml->tag( "xf:select1" ); select1->attribute( "ref", a.ref() ); createLabel( select1, a ); foreach( QString value, a.enumerationValues() ) { XmlBuilder *item = select1->tag( "xf:item" ); QString itemLabel; Hint hint = mHints.hint( element.identifier() + '/' + a.ref() ); if ( hint.isValid() ) itemLabel = hint.enumValue( value ); if ( itemLabel.isEmpty() ) itemLabel = humanizeString( value ); item->tag( "xf:label", itemLabel ); item->tag( "xf:value", value ); } } else { qDebug() << "Unsupported type: " << a.type(); } } } void FormCreator::parseElement( const Schema::Element &element, XmlBuilder *xml ) { if ( element.type() == Schema::Node::String ) { XmlBuilder *textArea = xml->tag( "xf:textarea" ); textArea->attribute( "ref", "." ); createLabel( textArea, element ); } else if ( element.type() == Schema::Node::NormalizedString || element.type() == Schema::Node::Token ) { XmlBuilder *input = xml->tag( "xf:input" ); input->attribute( "ref", "." ); createLabel( input, element ); } else if ( element.type() == Schema::Node::ComplexType ) { parseComplexType( element, xml, true ); } else { qDebug() << "Unsupported type: " << element.type(); } } void FormCreator::parseComplexType( const Schema::Element &element, XmlBuilder *xml, bool topLevel ) { QString currentChoice; XmlBuilder *section; bool choiceOnly = true; foreach( Schema::Relation r, element.elementRelations() ) { if( r.choice().isEmpty() ) choiceOnly = false; } if( !topLevel && !element.mixed() && !choiceOnly && element.elementRelations().size() > 1 ) { section = xml->tag( "kxf:section" ); createLabel( section, element ); } /*else if( !topLevel && element.type() == ) { section = xml->tag( "kxf:section" ); createLabel( section, element ); } */else { section = xml; } XmlBuilder *list = 0; XmlBuilder *choice = 0; foreach( Schema::Relation r, element.elementRelations() ) { qDebug() << " CHILD ELEMENT" << r.target(); qDebug() << " CHOICE" << r.choice(); if ( r.isList() ) { bool isMixedList = r.choice().contains( "+" ); if ( !list || r.choice().isEmpty() || currentChoice != r.choice() ) { list = section->tag( "list" ); QString label; if ( isMixedList ) { label = "Item"; } else { label = getLabel( element.identifier() + '[' + r.target() + ']' ); if ( label.isEmpty() ) { label = humanizeString( r.target(), true ); } } list->tag( "xf:label", label ); } XmlBuilder *item = list->tag( "itemclass" ); item->attribute( "ref", r.target() ); QString itemLabel; itemLabel = getLabel( element.identifier() + '/' + r.target() ); Schema::Element itemElement = mDocument.element( r ); if ( itemLabel.isEmpty() ) { // Try to guess a suitable item label. foreach( Schema::Relation r2, itemElement.attributeRelations() ) { if ( r2.target() == "name" ) { if ( isMixedList ) { itemLabel = humanizeString( itemElement.name() ) + ": "; } itemLabel += "<arg ref=\"@name\"/>"; break; } } } if ( itemLabel.isEmpty() ) { if ( itemElement.type() == Schema::Node::String ) { itemLabel += "<arg ref=\".\" truncate=\"40\"/>"; } else if ( itemElement.type() == Schema::Node::NormalizedString || itemElement.type() == Schema::Node::Token ) { itemLabel += "<arg ref=\".\"/>"; } } if ( itemLabel.isEmpty() ) itemLabel = humanizeString( r.target() ); item->tag( "itemlabel", itemLabel ); currentChoice = r.choice(); } else if( !r.choice().isEmpty() ) { if( !choice ) { choice = section->tag( "xf:select1" ); choice->tag( "xf:label", getLabel( element.ref(), element.name() ) ); } Schema::Element choiceElement = mDocument.element( r ); XmlBuilder *item = choice->tag( "xf:item" ); QString value = choiceElement.name(); QString itemLabel = getLabel( choiceElement.ref(), choiceElement.name() ); item->tag( "xf:label", itemLabel ); item->tag( "xf:value", value ); } else{ Schema::Element textElement = mDocument.element( r.target() ); if( textElement.type() == Schema::Node::ComplexType && !textElement.mixed() ) { parseComplexType( textElement, section, false ); } else { XmlBuilder *textInput = 0; if ( textElement.type() == Schema::Node::NormalizedString ) { textInput = section->tag( "xf:input" ); } else { textInput = section->tag( "xf:textarea" ); } textInput->attribute( "ref", textElement.name() ); createLabel( textInput, textElement ); mCollapsedForms.append( r.target() ); } } } if( element.elementRelations().size() == 0 ) { XmlBuilder *textInput = 0; textInput = section->tag( "xf:textarea" ); textInput->attribute( "ref", element.name() ); createLabel( textInput, element ); } } QString FormCreator::humanizeString( const QString &str, bool pluralize ) { if ( str.isEmpty() ) return str; QString result = str[0].toUpper() + str.mid( 1 ); if ( pluralize ) { if ( result.endsWith( "y" ) ) { result = result.left( str.length() - 1 ) + "ies"; } else { result += 's'; } } return result; } void FormCreator::setHints( const Hints &hints ) { mHints = hints; } void FormCreator::mergeHints( const Hints &hints ) { foreach( Hint h, hints.hints() ) { mHints.insertHint( h ); } } void FormCreator::createLabel( XmlBuilder *parent, const Schema::Node &node ) { parent->tag( "xf:label", getLabel( node.identifier(), node.name() ) ); } QString FormCreator::getLabel( const QString &ref, const QString &fallback, bool pluralize ) { // qDebug() << "GETLABEL: " << ref; QString label; Hint hint = mHints.hint( ref ); if ( hint.isValid() ) label = hint.label(); if ( label.isEmpty() ) label = humanizeString( fallback, pluralize ); return label; } Hints FormCreator::hints() const { return mHints; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbAtmosphericCorrectionParameters.h" #include <fstream> #include "otbAeronetFileReader.h" #include "otbSpectralSensitivityReader.h" #include "otbAeronetData.h" namespace otb { AtmosphericCorrectionParameters ::AtmosphericCorrectionParameters() { m_AtmosphericPressure = 1030.; m_WaterVaporAmount = 2.5; m_OzoneAmount = 0.28; m_AerosolModel = CONTINENTAL; m_AerosolOptical = 0.2; m_AeronetFileName = ""; m_Day = 1; m_Month = 1; } /** Get data from aeronet file*/ void AtmosphericCorrectionParameters ::UpdateAeronetData(const std::string& file, int year, int month, int day, int hour, int minute, double epsi) { if (file == "") itkExceptionMacro(<< "No Aeronet filename specified."); AeronetFileReader::Pointer reader = AeronetFileReader::New(); reader->SetFileName(file); reader->SetDay(day); reader->SetMonth(month); reader->SetYear(year); reader->SetHour(hour); reader->SetMinute(minute); reader->SetEpsilon(epsi); reader->Update(); m_AerosolOptical = reader->GetOutput()->GetAerosolOpticalThickness(); m_WaterVaporAmount = reader->GetOutput()->GetWater(); } /**PrintSelf method */ void AtmosphericCorrectionParameters ::PrintSelf(std::ostream& os, itk::Indent indent) const { os << "Atmospheric pressure : " << m_AtmosphericPressure << std::endl; os << "Water vapor amount : " << m_WaterVaporAmount << std::endl; os << "Ozone amount : " << m_OzoneAmount << std::endl; os << "Aerosol model : " << m_AerosolModel << std::endl; os << "Aerosol optical : " << m_AerosolOptical << std::endl; } } // end namespace otb <commit_msg>ENH: follow ITK guidelines and add indentation in PrintSelf method<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbAtmosphericCorrectionParameters.h" #include <fstream> #include "otbAeronetFileReader.h" #include "otbSpectralSensitivityReader.h" #include "otbAeronetData.h" namespace otb { AtmosphericCorrectionParameters ::AtmosphericCorrectionParameters() { m_AtmosphericPressure = 1030.; m_WaterVaporAmount = 2.5; m_OzoneAmount = 0.28; m_AerosolModel = CONTINENTAL; m_AerosolOptical = 0.2; m_AeronetFileName = ""; m_Day = 1; m_Month = 1; } /** Get data from aeronet file*/ void AtmosphericCorrectionParameters ::UpdateAeronetData(const std::string& file, int year, int month, int day, int hour, int minute, double epsi) { if (file == "") itkExceptionMacro(<< "No Aeronet filename specified."); AeronetFileReader::Pointer reader = AeronetFileReader::New(); reader->SetFileName(file); reader->SetDay(day); reader->SetMonth(month); reader->SetYear(year); reader->SetHour(hour); reader->SetMinute(minute); reader->SetEpsilon(epsi); reader->Update(); m_AerosolOptical = reader->GetOutput()->GetAerosolOpticalThickness(); m_WaterVaporAmount = reader->GetOutput()->GetWater(); } /**PrintSelf method */ void AtmosphericCorrectionParameters ::PrintSelf(std::ostream& os, itk::Indent indent) const { os << indent << "Atmospheric pressure : " << m_AtmosphericPressure << std::endl; os << indent << "Water vapor amount : " << m_WaterVaporAmount << std::endl; os << indent << "Ozone amount : " << m_OzoneAmount << std::endl; os << indent << "Aerosol model : " << m_AerosolModel << std::endl; os << indent << "Aerosol optical : " << m_AerosolOptical << std::endl; } } // end namespace otb <|endoftext|>
<commit_before>#include <blackhole/formatter/string.hpp> #include <blackhole/log.hpp> #include <blackhole/repository.hpp> #include <blackhole/sink/files.hpp> using namespace blackhole; enum class level { debug, info, warning, error }; void init() { repository_t<level>::instance().configure< sink::files_t< sink::files::boost_backend_t, sink::rotator_t< sink::files::boost_backend_t, sink::rotation::watcher::size_t > >, formatter::string_t >(); formatter_config_t formatter("string"); formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s"; sink_config_t sink("files"); sink["path"] = "blackhole.log"; sink["autoflush"] = true; sink["rotation"]["pattern"] = "blackhole.log.%N"; sink["rotation"]["backups"] = std::uint16_t(5); sink["rotation"]["size"] = std::uint64_t(1024); frontend_config_t frontend = { formatter, sink }; log_config_t config{ "root", { frontend } }; repository_t<level>::instance().init(config); } int main(int, char**) { init(); verbose_logger_t<level> log = repository_t<level>::instance().root(); for (int i = 0; i < 10; ++i) { BH_LOG(log, level::debug, "[%d] %s - done", 0, "debug"); BH_LOG(log, level::info, "[%d] %s - done", 1, "info"); BH_LOG(log, level::warning, "[%d] %s - done", 2, "warning"); BH_LOG(log, level::error, "[%d] %s - done", 3, "error"); } return 0; } <commit_msg>Reduced rotation rate for files example with rotation.<commit_after>#include <blackhole/formatter/string.hpp> #include <blackhole/log.hpp> #include <blackhole/repository.hpp> #include <blackhole/sink/files.hpp> using namespace blackhole; enum class level { debug, info, warning, error }; void init() { repository_t<level>::instance().configure< sink::files_t< sink::files::boost_backend_t, sink::rotator_t< sink::files::boost_backend_t, sink::rotation::watcher::size_t > >, formatter::string_t >(); formatter_config_t formatter("string"); formatter["pattern"] = "[%(timestamp)s] [%(severity)s]: %(message)s"; sink_config_t sink("files"); sink["path"] = "blackhole.log"; sink["autoflush"] = true; sink["rotation"]["pattern"] = "blackhole.log.%N"; sink["rotation"]["backups"] = std::uint16_t(10); sink["rotation"]["size"] = std::uint64_t(100 * 1024); frontend_config_t frontend = { formatter, sink }; log_config_t config{ "root", { frontend } }; repository_t<level>::instance().init(config); } int main(int, char**) { init(); verbose_logger_t<level> log = repository_t<level>::instance().root(); for (int i = 0; i < 32; ++i) { BH_LOG(log, level::debug, "[%d] %s - done", 0, "debug"); BH_LOG(log, level::info, "[%d] %s - done", 1, "info"); BH_LOG(log, level::warning, "[%d] %s - done", 2, "warning"); BH_LOG(log, level::error, "[%d] %s - done", 3, "error"); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("PolishCoin - Satoshi"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "c99dac5" #define GIT_COMMIT_DATE "Sat, 4 Jul 2015 20:17:16 +1000" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif #ifndef BUILD_DATE #ifdef GIT_COMMIT_DATE #define BUILD_DATE GIT_COMMIT_DATE #else #define BUILD_DATE __DATE__ ", " __TIME__ #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); } <commit_msg>Version<commit_after>// Copyright (c) 2012-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both bitcoind and bitcoin-core, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("PolishCoin"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID "c99dac5" #define GIT_COMMIT_DATE "Sat, 4 Jul 2015 20:17:16 +1000" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif #ifndef BUILD_DATE #ifdef GIT_COMMIT_DATE #define BUILD_DATE GIT_COMMIT_DATE #else #define BUILD_DATE __DATE__ ", " __TIME__ #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); } <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQMathMatrixWidget.h" #include "copasi.h" #include "qtUtilities.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CModel.h" #include "function/CExpression.h" //activate display of test of symbolic derivatives //#define _DERIV_TEST_ /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent) : CopasiWidget(parent) { setupUi(this); CColorScaleSimple * tcs = new CColorScaleSimple(); mpArrayWidget1->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget1->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget2->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget2->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget3->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget3->setColorScalingAutomatic(false); #ifdef _DERIV_TEST_ connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed())); #else if (mpTabWidget->count()) mpTabWidget->removeTab(mpTabWidget->count() - 1); #endif } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mpArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mpArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mpArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mpArrayWidget1->setArrayAnnotation(NULL); mpArrayWidget2->setArrayAnnotation(NULL); mpArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { clearArrays(); return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enterProtected() { loadMatrices(); return true; } #include <qtablewidget.h> void CQMathMatrixWidget::slotDerivButtonPressed() { #ifdef _DERIV_TEST_ std::cout << "Deriv" << std::endl; CModel* pModel = &CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[0], pModel->getMetabolites()[0], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[0], pModel->getMetabolites()[0], true); //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); mpMML->setBaseFontPointSize(qApp->font().pointSize()); mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML->setContent(tmpstring.c_str()); mpMML2->setBaseFontPointSize(qApp->font().pointSize()); mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML2->setContent(tmpstring2.c_str()); QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size()); pTable->show(); int i, imax = pModel->getMetabolites().size(); int j, jmax = pModel->getReactions().size(); for (i = 0; i < imax; ++i) for (j = 0; j < jmax; ++j) { //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j], // pModel->getMetabolites()[i], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(pModel->getReactions()[j], pModel->getMetabolites()[i], true); //evaluate CExpression * tmpExp = new CExpression("tmp expr", pModel); tmpExp->setRoot(tmpnode2); tmpExp->compile(); std::cout << tmpExp->calcValue() << std::endl; //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; //std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); QtMmlWidget* tmpmml = new QtMmlWidget(); tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2); tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); tmpmml->setContent(tmpstring2.c_str()); pTable->setCellWidget(j, i, tmpmml); //tmpmml = new QtMmlWidget(); //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2); //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); //tmpmml->setContent(tmpstring.c_str()); //pTable->setCellWidget(i, 1, tmpmml); } pTable->resizeColumnsToContents(); pTable->resizeRowsToContents(); #endif } <commit_msg>make the test code for derivatives compile again<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "CQMathMatrixWidget.h" #include "copasi.h" #include "qtUtilities.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "model/CModel.h" #include "function/CExpression.h" //activate display of test of symbolic derivatives //#define _DERIV_TEST_ /** * Constructs a CQMathMatrixWidget which is a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent) : CopasiWidget(parent) { setupUi(this); CColorScaleSimple * tcs = new CColorScaleSimple(); mpArrayWidget1->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget1->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget2->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget2->setColorScalingAutomatic(false); tcs = new CColorScaleSimple(); mpArrayWidget3->setColorCoding(tcs); tcs->setMinMax(-1.5, 1.5); mpArrayWidget3->setColorScalingAutomatic(false); #ifdef _DERIV_TEST_ connect(mpDerivButton, SIGNAL(clicked()), this, SLOT(slotDerivButtonPressed())); #else if (mpTabWidget->count()) mpTabWidget->removeTab(mpTabWidget->count() - 1); #endif } /* * Destroys the object and frees any allocated resources */ CQMathMatrixWidget::~CQMathMatrixWidget() {} void CQMathMatrixWidget::loadMatrices() { assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); mpArrayWidget1->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)"))); mpArrayWidget2->setArrayAnnotation(tmp); tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)"))); mpArrayWidget3->setArrayAnnotation(tmp); } void CQMathMatrixWidget::clearArrays() { mpArrayWidget1->setArrayAnnotation(NULL); mpArrayWidget2->setArrayAnnotation(NULL); mpArrayWidget3->setArrayAnnotation(NULL); } //************************************* bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { clearArrays(); return true; } bool CQMathMatrixWidget::leave() { return true; } bool CQMathMatrixWidget::enterProtected() { loadMatrices(); return true; } #include <qtablewidget.h> void CQMathMatrixWidget::slotDerivButtonPressed() { #ifdef _DERIV_TEST_ std::cout << "Deriv" << std::endl; CModel* pModel = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel(); CEvaluationNode* tmpnode = pModel->prepareElasticity(&pModel->getReactions()[0], &pModel->getMetabolites()[0], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[0], &pModel->getMetabolites()[0], true); //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); mpMML->setBaseFontPointSize(qApp->font().pointSize()); mpMML->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML->setContent(tmpstring.c_str()); mpMML2->setBaseFontPointSize(qApp->font().pointSize()); mpMML2->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); mpMML2->setContent(tmpstring2.c_str()); QTableWidget * pTable = new QTableWidget(pModel->getReactions().size(), pModel->getMetabolites().size()); pTable->show(); int i, imax = pModel->getMetabolites().size(); int j, jmax = pModel->getReactions().size(); for (i = 0; i < imax; ++i) for (j = 0; j < jmax; ++j) { //CEvaluationNode* tmpnode = pModel->prepareElasticity(pModel->getReactions()[j], // pModel->getMetabolites()[i], false); CEvaluationNode* tmpnode2 = pModel->prepareElasticity(&pModel->getReactions()[j], &pModel->getMetabolites()[i], true); //evaluate CExpression * tmpExp = new CExpression("tmp expr", pModel); tmpExp->setRoot(tmpnode2); tmpExp->compile(); std::cout << tmpExp->calcValue() << std::endl; //create empty environment. Variable nodes should not occur in an expression std::vector<std::vector<std::string> > env; //std::string tmpstring = tmpnode->buildMMLString(false, env); std::string tmpstring2 = tmpnode2->buildMMLString(false, env); QtMmlWidget* tmpmml = new QtMmlWidget(); tmpmml->setBaseFontPointSize(qApp->font().pointSize() - 2); tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); tmpmml->setContent(tmpstring2.c_str()); pTable->setCellWidget(j, i, tmpmml); //tmpmml = new QtMmlWidget(); //tmpmml->setBaseFontPointSize(qApp->font().pointSize()-2); //tmpmml->setFontName(QtMmlWidget::NormalFont, qApp->font().family()); //tmpmml->setContent(tmpstring.c_str()); //pTable->setCellWidget(i, 1, tmpmml); } pTable->resizeColumnsToContents(); pTable->resizeRowsToContents(); #endif } <|endoftext|>
<commit_before>// CChemEqElement // // A class describing an element of a chemical equation // (C) Stefan Hoops 2001 // #include "copasi.h" #include "CChemEq.h" CChemEq::CChemEq(){}; CChemEq::CChemEq(const CChemEq & src) { mChemicalEquation = src.mChemicalEquation; mChemicalEquationConverted = src.mChemicalEquationConverted; mSubstrates = src.mSubstrates; mProducts = src.mProducts; mBalances = src.mBalances; } CChemEq::~CChemEq(){cleanup();} void CChemEq::cleanup() { mSubstrates.cleanup(); mProducts.cleanup(); mBalances.cleanup(); } void CChemEq::compile(CCopasiVectorN < CCompartment > & compartments) { compileChemEqElements(mSubstrates, compartments); compileChemEqElements(mProducts, compartments); compileChemEqElements(mBalances, compartments); } void CChemEq::setChemicalEquation(const string & chemicalEquation) { string Substrates, Products; mChemicalEquation = chemicalEquation; splitChemEq(Substrates, Products); setChemEqElements(mSubstrates, Substrates); setChemEqElements(mProducts, Products); setChemEqElements(mBalances, Substrates, CChemEq::SUBSTRATE); setChemEqElements(mBalances, Products); writeChemicalEquation(); writeChemicalEquationConverted(); } const string & CChemEq::getChemicalEquation() const {return mChemicalEquation;} const string & CChemEq::getChemicalEquationConverted() const {return mChemicalEquationConverted;} const CCopasiVector < CChemEqElement > & CChemEq::getSubstrates() {return mSubstrates;} const CCopasiVector < CChemEqElement > & CChemEq::getProducts() {return mProducts;} const CCopasiVector < CChemEqElement > & CChemEq::getBalances() {return mBalances;} CChemEqElement CChemEq::extractElement(const string & input, string::size_type & pos) const { CChemEqElement Element; string Value; string::size_type Start = input.find_first_not_of(" ", pos); string::size_type End = input.find("+", Start); string::size_type Multiplier = input.find("*", Start); string::size_type NameStart; string::size_type NameEnd; if (Multiplier == string::npos || Multiplier > End) { NameStart = Start; Element.setMultiplicity(1.0); } else { NameStart = input.find_first_not_of(" ",Multiplier+1); Value = input.substr(Start, Multiplier - Start); Element.setMultiplicity(atof(Value.c_str())); } NameEnd = input.find_first_of(" +", NameStart); if (NameStart != string::npos) Element.setMetaboliteName(input.substr(NameStart, NameEnd - NameStart)); pos = (End == string::npos) ? End: End+1; return Element; } void CChemEq::addElement(CCopasiVector < CChemEqElement > & structure, const CChemEqElement & element, CChemEq::MetaboliteRole role) { unsigned C_INT32 i; string Name = element.getMetaboliteName(); for (i=0; i < structure.size(); i++) if (Name == structure[i]->getMetaboliteName()) break; if (i >= structure.size()) { CChemEqElement * Element = new CChemEqElement(element); if (role == CChemEq::SUBSTRATE) Element->setMultiplicity(- Element->getMultiplicity()); structure.add(Element); } else if (role == CChemEq::SUBSTRATE) structure[i]->addToMultiplicity(- element.getMultiplicity()); else structure[i]->addToMultiplicity(element.getMultiplicity()); } void CChemEq::setChemEqElements(CCopasiVector < CChemEqElement > & elements, const string & reaction, CChemEq::MetaboliteRole role) { string::size_type pos = 0; while (pos != string::npos) addElement(elements, extractElement(reaction, pos), role); } #ifdef XXXX void CChemEq::cleanupChemEqElements(vector < CChemEqElement * > & elements) { for (unsigned C_INT32 i=0; i<elements.size(); i++) free(elements[i]); elements.clear(); } #endif // XXXX void CChemEq::splitChemEq(string & left, string & right) const { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0; while (*Separator != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); right = mChemicalEquation.substr(equal+(Separator[--i].length())); left = mChemicalEquation.substr(0,equal); return; } void CChemEq::compileChemEqElements(CCopasiVector < CChemEqElement > & elements, CCopasiVectorN < CCompartment > & compartments) { unsigned C_INT32 i, imax = elements.size(); for (i=0; i<imax; i++) elements[i]->compile(compartments); } void CChemEq::writeChemicalEquation() { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0, j; while (Separator[i] != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); mChemicalEquation.erase(); for (j=0; j<mSubstrates.size(); j++) { if (j) mChemicalEquation += " + "; mChemicalEquation += mSubstrates[j]->writeElement(); } mChemicalEquation += " " + Separator[--i] + " "; for (j=0; j<mProducts.size(); j++) { if (j) mChemicalEquation += " + "; mChemicalEquation += mProducts[j]->writeElement(); } } void CChemEq::writeChemicalEquationConverted() { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0, j, k, kmax; while (Separator[i] != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); mChemicalEquationConverted.erase(); for (j=0; j<mSubstrates.size(); j++) { if (j) mChemicalEquationConverted += " + "; kmax = (unsigned C_INT32) mSubstrates[j]->getMultiplicity(); for (k=0; k<kmax; k++) { if (k) mChemicalEquationConverted += " + "; mChemicalEquationConverted += mSubstrates[j]->getMetaboliteName(); } } mChemicalEquationConverted += " " + Separator[--i] + " "; for (j=0; j<mProducts.size(); j++) { if (j) mChemicalEquation += " + "; kmax = (unsigned C_INT32) mProducts[j]->getMultiplicity(); for (k=0; k<kmax; k++) { if (k) mChemicalEquationConverted += " + "; mChemicalEquationConverted += mProducts[j]->getMetaboliteName(); } } } <commit_msg>Fixed error in writeChemicalEquationConverted<commit_after>// CChemEqElement // // A class describing an element of a chemical equation // (C) Stefan Hoops 2001 // #include "copasi.h" #include "CChemEq.h" CChemEq::CChemEq(){}; CChemEq::CChemEq(const CChemEq & src) { mChemicalEquation = src.mChemicalEquation; mChemicalEquationConverted = src.mChemicalEquationConverted; mSubstrates = src.mSubstrates; mProducts = src.mProducts; mBalances = src.mBalances; } CChemEq::~CChemEq(){cleanup();} void CChemEq::cleanup() { mSubstrates.cleanup(); mProducts.cleanup(); mBalances.cleanup(); } void CChemEq::compile(CCopasiVectorN < CCompartment > & compartments) { compileChemEqElements(mSubstrates, compartments); compileChemEqElements(mProducts, compartments); compileChemEqElements(mBalances, compartments); } void CChemEq::setChemicalEquation(const string & chemicalEquation) { string Substrates, Products; mChemicalEquation = chemicalEquation; splitChemEq(Substrates, Products); setChemEqElements(mSubstrates, Substrates); setChemEqElements(mProducts, Products); setChemEqElements(mBalances, Substrates, CChemEq::SUBSTRATE); setChemEqElements(mBalances, Products); writeChemicalEquation(); writeChemicalEquationConverted(); } const string & CChemEq::getChemicalEquation() const {return mChemicalEquation;} const string & CChemEq::getChemicalEquationConverted() const {return mChemicalEquationConverted;} const CCopasiVector < CChemEqElement > & CChemEq::getSubstrates() {return mSubstrates;} const CCopasiVector < CChemEqElement > & CChemEq::getProducts() {return mProducts;} const CCopasiVector < CChemEqElement > & CChemEq::getBalances() {return mBalances;} CChemEqElement CChemEq::extractElement(const string & input, string::size_type & pos) const { CChemEqElement Element; string Value; string::size_type Start = input.find_first_not_of(" ", pos); string::size_type End = input.find("+", Start); string::size_type Multiplier = input.find("*", Start); string::size_type NameStart; string::size_type NameEnd; if (Multiplier == string::npos || Multiplier > End) { NameStart = Start; Element.setMultiplicity(1.0); } else { NameStart = input.find_first_not_of(" ",Multiplier+1); Value = input.substr(Start, Multiplier - Start); Element.setMultiplicity(atof(Value.c_str())); } NameEnd = input.find_first_of(" +", NameStart); if (NameStart != string::npos) Element.setMetaboliteName(input.substr(NameStart, NameEnd - NameStart)); pos = (End == string::npos) ? End: End+1; return Element; } void CChemEq::addElement(CCopasiVector < CChemEqElement > & structure, const CChemEqElement & element, CChemEq::MetaboliteRole role) { unsigned C_INT32 i; string Name = element.getMetaboliteName(); for (i=0; i < structure.size(); i++) if (Name == structure[i]->getMetaboliteName()) break; if (i >= structure.size()) { CChemEqElement * Element = new CChemEqElement(element); if (role == CChemEq::SUBSTRATE) Element->setMultiplicity(- Element->getMultiplicity()); structure.add(Element); } else if (role == CChemEq::SUBSTRATE) structure[i]->addToMultiplicity(- element.getMultiplicity()); else structure[i]->addToMultiplicity(element.getMultiplicity()); } void CChemEq::setChemEqElements(CCopasiVector < CChemEqElement > & elements, const string & reaction, CChemEq::MetaboliteRole role) { string::size_type pos = 0; while (pos != string::npos) addElement(elements, extractElement(reaction, pos), role); } #ifdef XXXX void CChemEq::cleanupChemEqElements(vector < CChemEqElement * > & elements) { for (unsigned C_INT32 i=0; i<elements.size(); i++) free(elements[i]); elements.clear(); } #endif // XXXX void CChemEq::splitChemEq(string & left, string & right) const { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0; while (*Separator != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); right = mChemicalEquation.substr(equal+(Separator[--i].length())); left = mChemicalEquation.substr(0,equal); return; } void CChemEq::compileChemEqElements(CCopasiVector < CChemEqElement > & elements, CCopasiVectorN < CCompartment > & compartments) { unsigned C_INT32 i, imax = elements.size(); for (i=0; i<imax; i++) elements[i]->compile(compartments); } void CChemEq::writeChemicalEquation() { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0, j; while (Separator[i] != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); mChemicalEquation.erase(); for (j=0; j<mSubstrates.size(); j++) { if (j) mChemicalEquation += " + "; mChemicalEquation += mSubstrates[j]->writeElement(); } mChemicalEquation += " " + Separator[--i] + " "; for (j=0; j<mProducts.size(); j++) { if (j) mChemicalEquation += " + "; mChemicalEquation += mProducts[j]->writeElement(); } } void CChemEq::writeChemicalEquationConverted() { string::size_type equal = string::npos; string Separator[] = {"->", "=>", "=", ""}; unsigned C_INT32 i=0, j, k, kmax; while (Separator[i] != "" && equal == string::npos) equal = mChemicalEquation.find(Separator[i++]); if (equal == string::npos) fatalError(); mChemicalEquationConverted.erase(); for (j=0; j<mSubstrates.size(); j++) { if (j) mChemicalEquationConverted += " + "; kmax = (unsigned C_INT32) mSubstrates[j]->getMultiplicity(); for (k=0; k<kmax; k++) { if (k) mChemicalEquationConverted += " + "; mChemicalEquationConverted += mSubstrates[j]->getMetaboliteName(); } } mChemicalEquationConverted += " " + Separator[--i] + " "; for (j=0; j<mProducts.size(); j++) { if (j) mChemicalEquationConverted += " + "; kmax = (unsigned C_INT32) mProducts[j]->getMultiplicity(); for (k=0; k<kmax; k++) { if (k) mChemicalEquationConverted += " + "; mChemicalEquationConverted += mProducts[j]->getMetaboliteName(); } } } <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "writingtotemporary.h" #include "Utils.h" #include "checkmanager.h" #include "StringUtils.h" #include <clang/AST/AST.h> #include <clang/Lex/Lexer.h> using namespace clang; using namespace std; WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci) : CheckBase(name, ci) , m_widenCriteria(isOptionSet("widen-criteria")) { } std::vector<string> WritingToTemporary::filesToIgnore() const { static const vector<string> files = { "qstring.h" }; return files; } vector<string> WritingToTemporary::supportedOptions() const { static const vector<string> options = { "widen-criteria" }; return options; } static bool isDisallowedClass(const string &className) { static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement", "QScriptValue", "QTextLine", "QTextBlock", "QDomNode" }; return clazy_std::contains(disallowed, className); } static bool isKnownType(const string &className) { static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet", "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList", "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D" , "QVector4D", "QSize", "QSizeF", "QSizePolicy" }; return clazy_std::contains(types, className); } void WritingToTemporary::VisitStmt(clang::Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (!callExpr) return; // For a chain like getFoo().setBar(), returns {setBar(), getFoo()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar() FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee(); if (!secondFunc) return; CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc); if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic()) return; CXXRecordDecl *record = secondMethod->getParent(); if (!record) return; if (isDisallowedClass(record->getNameAsString())) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType()) return; qt = secondFunc->getReturnType(); const Type *secondFuncReturnType = qt.getTypePtrOrNull(); if (!secondFuncReturnType || !secondFuncReturnType->isVoidType()) return; if (!isKnownType(record->getNameAsString()) && !stringStartsWith(secondFunc->getNameAsString(), "set") && !m_widenCriteria) return; emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + secondFunc->getQualifiedNameAsString()); } REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0) <commit_msg>writing-to-temporary: Add QPoint and QPointF<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "writingtotemporary.h" #include "Utils.h" #include "checkmanager.h" #include "StringUtils.h" #include <clang/AST/AST.h> #include <clang/Lex/Lexer.h> using namespace clang; using namespace std; WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci) : CheckBase(name, ci) , m_widenCriteria(isOptionSet("widen-criteria")) { } std::vector<string> WritingToTemporary::filesToIgnore() const { static const vector<string> files = { "qstring.h" }; return files; } vector<string> WritingToTemporary::supportedOptions() const { static const vector<string> options = { "widen-criteria" }; return options; } static bool isDisallowedClass(const string &className) { static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement", "QScriptValue", "QTextLine", "QTextBlock", "QDomNode" }; return clazy_std::contains(disallowed, className); } static bool isKnownType(const string &className) { static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet", "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList", "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D", "QVector4D", "QSize", "QSizeF", "QSizePolicy", "QPoint", "QPointF" }; return clazy_std::contains(types, className); } void WritingToTemporary::VisitStmt(clang::Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (!callExpr) return; // For a chain like getFoo().setBar(), returns {setBar(), getFoo()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar() FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee(); if (!secondFunc) return; CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc); if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic()) return; CXXRecordDecl *record = secondMethod->getParent(); if (!record) return; if (isDisallowedClass(record->getNameAsString())) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType()) return; qt = secondFunc->getReturnType(); const Type *secondFuncReturnType = qt.getTypePtrOrNull(); if (!secondFuncReturnType || !secondFuncReturnType->isVoidType()) return; if (!isKnownType(record->getNameAsString()) && !stringStartsWith(secondFunc->getNameAsString(), "set") && !m_widenCriteria) return; emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + secondFunc->getQualifiedNameAsString()); } REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0) <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/thread/FixedSizeThreadPool.h" #include "fnord-base/wallclock.h" #include "fnord-base/VFS.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/VFSFileServlet.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-sstable/SSTableServlet.h" #include "fnord-logtable/LogTableServlet.h" #include "fnord-logtable/TableRepository.h" #include "fnord-logtable/TableJanitor.h" #include "fnord-logtable/TableReplication.h" #include "fnord-logtable/ArtifactReplication.h" #include "fnord-logtable/ArtifactIndexReplication.h" #include "fnord-logtable/NumericBoundsSummary.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-tsdb/TSDBNode.h" #include "fnord-tsdb/TSDBServlet.h" #include "common.h" #include "schemas.h" #include "ModelReplication.h" using namespace fnord; std::atomic<bool> shutdown_sig; fnord::thread::EventLoop ev; void quit(int n) { shutdown_sig = true; fnord::logInfo("cm.chunkserver", "Shutting down..."); // FIXPAUL: wait for http server stop... ev.shutdown(); } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ shutdown_sig = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "http_port", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the public http server on this port", "<port>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "datadir path", "<path>"); flags.defineFlag( "replicate_to", cli::FlagParser::T_STRING, false, NULL, NULL, "url", "<url>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* args */ auto dir = flags.getString("datadir"); auto repl_targets = flags.getStrings("replicate_to"); /* start http server and worker pools */ fnord::thread::ThreadPool tpool; http::HTTPConnectionPool http(&ev); fnord::http::HTTPRouter http_router; fnord::http::HTTPServer http_server(&http_router, &ev); http_server.listen(flags.getInt("http_port")); auto repl_scheme = mkRef(new dht::FixedReplicationScheme()); for (const auto& r : repl_targets) { repl_scheme->addHost(r); } tsdb::TSDBNode tsdb_node(dir + "/tsdb", repl_scheme.get(), &http); tsdb::StreamProperties config(new msg::MessageSchema(joinedSessionsSchema())); config.max_datafile_size = 1024 * 1024 * 512; config.chunk_size = Duration(3600 * 4 * kMicrosPerSecond); config.compaction_interval = Duration(3 * kMicrosPerSecond); tsdb_node.configurePrefix("joined_sessions.", config); tsdb::TSDBServlet tsdb_servlet(&tsdb_node); http_router.addRouteByPrefixMatch("/tsdb", &tsdb_servlet, &tpool); tsdb_node.start(); ev.run(); tsdb_node.stop(); fnord::logInfo("cm.chunkserver", "Exiting..."); exit(0); } <commit_msg>30s commit interval<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/thread/FixedSizeThreadPool.h" #include "fnord-base/wallclock.h" #include "fnord-base/VFS.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/VFSFileServlet.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-sstable/SSTableServlet.h" #include "fnord-logtable/LogTableServlet.h" #include "fnord-logtable/TableRepository.h" #include "fnord-logtable/TableJanitor.h" #include "fnord-logtable/TableReplication.h" #include "fnord-logtable/ArtifactReplication.h" #include "fnord-logtable/ArtifactIndexReplication.h" #include "fnord-logtable/NumericBoundsSummary.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-tsdb/TSDBNode.h" #include "fnord-tsdb/TSDBServlet.h" #include "common.h" #include "schemas.h" #include "ModelReplication.h" using namespace fnord; std::atomic<bool> shutdown_sig; fnord::thread::EventLoop ev; void quit(int n) { shutdown_sig = true; fnord::logInfo("cm.chunkserver", "Shutting down..."); // FIXPAUL: wait for http server stop... ev.shutdown(); } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ shutdown_sig = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "http_port", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the public http server on this port", "<port>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "datadir path", "<path>"); flags.defineFlag( "replicate_to", cli::FlagParser::T_STRING, false, NULL, NULL, "url", "<url>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* args */ auto dir = flags.getString("datadir"); auto repl_targets = flags.getStrings("replicate_to"); /* start http server and worker pools */ fnord::thread::ThreadPool tpool; http::HTTPConnectionPool http(&ev); fnord::http::HTTPRouter http_router; fnord::http::HTTPServer http_server(&http_router, &ev); http_server.listen(flags.getInt("http_port")); auto repl_scheme = mkRef(new dht::FixedReplicationScheme()); for (const auto& r : repl_targets) { repl_scheme->addHost(r); } tsdb::TSDBNode tsdb_node(dir + "/tsdb", repl_scheme.get(), &http); tsdb::StreamProperties config(new msg::MessageSchema(joinedSessionsSchema())); config.max_datafile_size = 1024 * 1024 * 512; config.chunk_size = Duration(3600 * 4 * kMicrosPerSecond); config.compaction_interval = Duration(30 * kMicrosPerSecond); tsdb_node.configurePrefix("joined_sessions.", config); tsdb::TSDBServlet tsdb_servlet(&tsdb_node); http_router.addRouteByPrefixMatch("/tsdb", &tsdb_servlet, &tpool); tsdb_node.start(); ev.run(); tsdb_node.stop(); fnord::logInfo("cm.chunkserver", "Exiting..."); exit(0); } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/UInt16ColumnReader.h" #include "fnord-cstable/UInt16ColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsQuery.h" #include "analytics/CTRByPositionQuery.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt16ColumnWriter jq_page_col(1, 1); /* query item level */ cstable::UInt16ColumnWriter position_col(2, 2); cstable::UInt16ColumnWriter clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (const cm::JoinedSession& sess) { ++n; for (const auto& q : sess.queries) { auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } if (q.items.size() == 0) { if (r==0) ++debug_z; position_col.addNull(r, 1); clicked_col.addNull(r, 1); } for (const auto& i : q.items) { ++debug_n; if (r==0) ++debug_z; position_col.addDatum(r, 2, i.position); clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ auto sstables = flags.getArgv(); int row_idx = 0; for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) { const auto& sstable = sstables[tbl_idx]; fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$1/$2] [$0%] Reading sstable... rows=$3", (size_t) ((cursor->position() / (double) body_size) * 100), tbl_idx + 1, sstables.size(), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); } if (sstables.size() > 0) { cstable::CSTableWriter writer("fnord.cstable", n); writer.addColumn("queries.items.position", &position_col); writer.addColumn("queries.items.clicked", &clicked_col); writer.commit(); } cstable::CSTableReader reader("fnord.cstable"); auto t0 = WallClock::unixMicros(); cm::AnalyticsQuery aq; cm::CTRByPositionQuery q(&aq); aq.scanTable(&reader); auto t1 = WallClock::unixMicros(); fnord::iputs("scanned $0 rows in $1 ms", q.rowsScanned(), (t1 - t0) / 1000.0f); for (const auto& p : q.results()) { fnord::iputs( "pos: $0, views: $1, clicks: $2, ctr: $3", p.first, p.second.num_views, p.second.num_clicks, p.second.num_clicks / (double) p.second.num_views); } return 0; } <commit_msg>CTRByPositionQueryResult<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <algorithm> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/cli/flagparser.h" #include "fnord-base/util/SimpleRateLimit.h" #include "fnord-base/InternMap.h" #include "fnord-json/json.h" #include "fnord-mdb/MDB.h" #include "fnord-mdb/MDBUtil.h" #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/UInt16ColumnReader.h" #include "fnord-cstable/UInt16ColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "common.h" #include "CustomerNamespace.h" #include "FeatureSchema.h" #include "JoinedQuery.h" #include "CTRCounter.h" #include "analytics/AnalyticsQuery.h" #include "analytics/CTRByPositionQuery.h" using namespace fnord; int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); fnord::cli::FlagParser flags; flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); size_t debug_n = 0; size_t debug_z = 0; /* query level */ cstable::UInt16ColumnWriter jq_page_col(1, 1); /* query item level */ cstable::UInt16ColumnWriter position_col(2, 2); cstable::UInt16ColumnWriter clicked_col(2, 2); uint64_t r = 0; uint64_t n = 0; auto add_session = [&] (const cm::JoinedSession& sess) { ++n; for (const auto& q : sess.queries) { auto pg_str = cm::extractAttr(q.attrs, "pg"); if (pg_str.isEmpty()) { jq_page_col.addNull(r, 1); } else { jq_page_col.addDatum(r, 1, std::stoul(pg_str.get())); } if (q.items.size() == 0) { if (r==0) ++debug_z; position_col.addNull(r, 1); clicked_col.addNull(r, 1); } for (const auto& i : q.items) { ++debug_n; if (r==0) ++debug_z; position_col.addDatum(r, 2, i.position); clicked_col.addDatum(r, 2, i.clicked); r = 2; } r = 1; } r = 0; }; /* read input tables */ auto sstables = flags.getArgv(); int row_idx = 0; for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) { const auto& sstable = sstables[tbl_idx]; fnord::logInfo("cm.jqcolumnize", "Importing sstable: $0", sstable); /* read sstable header */ sstable::SSTableReader reader(File::openFile(sstable, File::O_READ)); if (reader.bodySize() == 0) { fnord::logCritical("cm.jqcolumnize", "unfinished sstable: $0", sstable); exit(1); } /* get sstable cursor */ auto cursor = reader.getCursor(); auto body_size = reader.bodySize(); /* status line */ util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () { fnord::logInfo( "cm.jqcolumnize", "[$1/$2] [$0%] Reading sstable... rows=$3", (size_t) ((cursor->position() / (double) body_size) * 100), tbl_idx + 1, sstables.size(), row_idx); }); /* read sstable rows */ for (; cursor->valid(); ++row_idx) { status_line.runMaybe(); auto key = cursor->getKeyString(); auto val = cursor->getDataBuffer(); Option<cm::JoinedQuery> q; try { q = Some(json::fromJSON<cm::JoinedQuery>(val)); } catch (const Exception& e) { fnord::logWarning("cm.jqcolumnize", e, "invalid json: $0", val.toString()); } if (!q.isEmpty()) { cm::JoinedSession s; s.queries.emplace_back(q.get()); add_session(s); } if (!cursor->next()) { break; } } status_line.runForce(); } if (sstables.size() > 0) { cstable::CSTableWriter writer("fnord.cstable", n); writer.addColumn("queries.items.position", &position_col); writer.addColumn("queries.items.clicked", &clicked_col); writer.commit(); } cstable::CSTableReader reader("fnord.cstable"); auto t0 = WallClock::unixMicros(); cm::AnalyticsQuery aq; cm::CTRByPositionQueryResult res; cm::CTRByPositionQuery q(&aq, &res); aq.scanTable(&reader); auto t1 = WallClock::unixMicros(); fnord::iputs("scanned $0 rows in $1 ms", res.rows_scanned, (t1 - t0) / 1000.0f); for (const auto& p : res.counters) { fnord::iputs( "pos: $0, views: $1, clicks: $2, ctr: $3", p.first, p.second.num_views, p.second.num_clicks, p.second.num_clicks / (double) p.second.num_views); } return 0; } <|endoftext|>
<commit_before>#include "game_object_factory.hpp" using namespace mindscape; engine::GameObject* GameObjectFactory::fabricate( GameObjectFactory::Options option, std::pair<int, int> coordinates, int priority){ switch(option){ case(GameObjectFactory::LITTLE_GIRL): return fabricate_little_girl(); case(GameObjectFactory::FOOTER): return fabricate_footer(); case(GameObjectFactory::FOX): return fabricate_fox(); case(GameObjectFactory::PLATFORM): return fabricate_platform(); case(GameObjectFactory::BUTTON): return fabricate_button(); case(GameObjectFactory::BACKGROUND): return fabricate_background(); case(GameObjectFactory::SELECT_ARROW): return fabricate_select_arrow(); default: return NULL; } } engine::GameObject* GameObjectFactory::fabricate_footer(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_platform(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_background(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_button(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_select_arrow(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_fox(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_little_girl(){ engine::Game& game = engine::Game::get_instance(); std::pair<int, int> place (416, -500); //Creating running right animation engine::Animation* running_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_running_right.png", false, std::make_pair(0, 0), 1,1,9,0.9,true,"RIGHT" ); running_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating running right animation engine::Animation* running_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_running_left.png", false, std::make_pair(0, 0), 1,1,9,0.9,true,"LEFT" ); running_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating idle right animation engine::Animation* idle_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_idle_right.png", true, std::make_pair(0, 0), 1,1,10,1.5,"RIGHT" ); idle_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating idle left animation engine::Animation* idle_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_idle_left.png", false, std::make_pair(0, 0), 1,1,10,1.5,true,"LEFT" ); idle_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating jumping right animation engine::Animation* jumping_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_jumping_right.png", false, std::make_pair(0, 0), 1,1,5,1.5,true,"RIGHT" ); jumping_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating jumping left animation engine::Animation* jumping_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_jumping_left.png", false, std::make_pair(0, 0), 1,1,5,1.5,true,"LEFT" ); jumping_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); engine::GameObject* little_girl = new engine::LittleGirl("little_girl", place, 3); engine::Hitbox* hitbox= new engine::Hitbox("hitbox", little_girl->get_position(), std::make_pair(60, 180), std::make_pair(50,5), game.get_renderer()); little_girl->collidable = true; little_girl->add_animation("running_right_animation",running_right_animation); little_girl->add_animation("running_left_animation",running_left_animation); little_girl->add_animation("idle_right_animation",idle_right_animation); little_girl->add_animation("idle_left_animation",idle_left_animation); little_girl->add_animation("jumping_right_animation",jumping_right_animation); little_girl->add_animation("jumping_left_animation",jumping_left_animation); little_girl->set_actual_animation(idle_right_animation); little_girl->add_component(hitbox); return little_girl; } <commit_msg>Created basic enemy attack<commit_after>#include "game_object_factory.hpp" using namespace mindscape; engine::GameObject* GameObjectFactory::fabricate( GameObjectFactory::Options option, std::pair<int, int> coordinates, int priority){ switch(option){ case(GameObjectFactory::LITTLE_GIRL): return fabricate_little_girl(); case(GameObjectFactory::FOOTER): return fabricate_footer(); case(GameObjectFactory::FOX): return fabricate_fox(); case(GameObjectFactory::PLATFORM): return fabricate_platform(); case(GameObjectFactory::BUTTON): return fabricate_button(); case(GameObjectFactory::BACKGROUND): return fabricate_background(); case(GameObjectFactory::SELECT_ARROW): return fabricate_select_arrow(); default: return NULL; } } engine::GameObject* GameObjectFactory::fabricate_footer(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_platform(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_background(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_button(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_select_arrow(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_fox(){ std::cout << "NOT IMPLEMENTED YET" << std::endl; return NULL; } engine::GameObject* GameObjectFactory::fabricate_little_girl(){ engine::Game& game = engine::Game::get_instance(); std::pair<int, int> place (416, -500); //Creating running right animation engine::Animation* running_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_running_right.png", false, std::make_pair(0, 0), 1,1,9,0.9,true,"RIGHT" ); running_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating running right animation engine::Animation* running_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_running_left.png", false, std::make_pair(0, 0), 1,1,9,0.9,true,"LEFT" ); running_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating idle right animation engine::Animation* idle_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_idle_right.png", true, std::make_pair(0, 0), 1,1,10,1.5,"RIGHT" ); idle_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating idle left animation engine::Animation* idle_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_idle_left.png", false, std::make_pair(0, 0), 1,1,10,1.5,true,"LEFT" ); idle_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating jumping right animation engine::Animation* jumping_right_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_jumping_right.png", false, std::make_pair(0, 0), 1,1,5,1.5,true,"RIGHT" ); jumping_right_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); //Creating jumping left animation engine::Animation* jumping_left_animation = new engine::Animation( game.get_renderer(), "../assets/images/sprites/little_girl/little_girl_jumping_left.png", false, std::make_pair(0, 0), 1,1,5,1.5,true,"LEFT" ); jumping_left_animation->set_values( std::make_pair(192, 192), std::make_pair(192, 192), std::make_pair(0, 0) ); engine::GameObject* little_girl = new engine::LittleGirl("little_girl", place, 52); engine::Hitbox* hitbox= new engine::Hitbox("hitbox", little_girl->get_position(), std::make_pair(60, 45), std::make_pair(50,140), game.get_renderer()); little_girl->collidable = true; little_girl->add_animation("running_right_animation",running_right_animation); little_girl->add_animation("running_left_animation",running_left_animation); little_girl->add_animation("idle_right_animation",idle_right_animation); little_girl->add_animation("idle_left_animation",idle_left_animation); little_girl->add_animation("jumping_right_animation",jumping_right_animation); little_girl->add_animation("jumping_left_animation",jumping_left_animation); little_girl->set_actual_animation(idle_right_animation); little_girl->add_component(hitbox); return little_girl; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "Erzaehlmirnix.h" #include <QDebug> #include <QRegularExpression> #include <QRegularExpressionMatch> Erzaehlmirnix::Erzaehlmirnix(QObject *parent) : Comic(parent) { m_info.id = QString("erzaehlmirnix"); m_info.name = QString("Erzaehlmirnix"); m_info.color = QColor(188, 197, 192); m_info.authors = QStringList("Nadja Hermann"); m_info.homepage = QUrl("https://erzaehlmirnix.wordpress.com/"); m_info.country = QLocale::Germany; m_info.language = QLocale::German; m_info.endDate = QDate::currentDate(); m_info.stripSourceUrl = QUrl("https://erzaehlmirnix.wordpress.com/"); } QUrl Erzaehlmirnix::extractStripImageUrl(QByteArray data) { QString html(data); QRegularExpression reg("<img[^>]*src=\"([^\"]*erzaehlmirnix.files.wordpress.com[^\"]*)\""); QRegularExpressionMatch match = reg.match(html); if (!match.hasMatch()) { return QUrl(); } QString src = match.captured(1); return QUrl(src); } <commit_msg>fix Erzaehlmirnix comic<commit_after>/** * Copyright (c) 2015 Damien Tardy-Panis * * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. **/ #include "Erzaehlmirnix.h" #include <QDebug> #include <QRegularExpression> #include <QRegularExpressionMatch> #include <QRegularExpressionMatchIterator> Erzaehlmirnix::Erzaehlmirnix(QObject *parent) : Comic(parent) { m_info.id = QString("erzaehlmirnix"); m_info.name = QString("Erzaehlmirnix"); m_info.color = QColor(188, 197, 192); m_info.authors = QStringList("Nadja Hermann"); m_info.homepage = QUrl("https://erzaehlmirnix.wordpress.com/"); m_info.country = QLocale::Germany; m_info.language = QLocale::German; m_info.endDate = QDate::currentDate(); m_info.stripSourceUrl = QUrl("https://erzaehlmirnix.wordpress.com/"); } QUrl Erzaehlmirnix::extractStripImageUrl(QByteArray data) { QString html(data); QRegularExpression reg("<img[^>]*src=\"([^\"]*erzaehlmirnix.files.wordpress.com[^\"]*)\""); QRegularExpressionMatchIterator matchIterator = reg.globalMatch(html); if (!matchIterator.hasNext()) return QUrl(); matchIterator.next(); if (!matchIterator.hasNext()) return QUrl(); QRegularExpressionMatch match = matchIterator.next(); QString src = match.captured(1); return QUrl(src); } <|endoftext|>
<commit_before>#include <Core/Tasks/TaskQueue.hpp> #include <Core/Tasks/Task.hpp> #include <stack> #include <iostream> namespace Ra { namespace Core { TaskQueue::TaskQueue( uint numThreads ) : m_processingTasks( 0 ), m_shuttingDown( false ) { CORE_ASSERT( numThreads > 0, " You need at least one thread" ); m_workerThreads.reserve( numThreads ); for ( uint i = 0 ; i < numThreads; ++i ) { m_workerThreads.emplace_back( std::thread( &TaskQueue::runThread, this, i ) ); } } TaskQueue::~TaskQueue() { flushTaskQueue(); m_shuttingDown = true; m_threadNotifier.notify_all(); for ( auto& t : m_workerThreads ) { t.join(); } } TaskQueue::TaskId TaskQueue::registerTask( Task* task ) { m_tasks.emplace_back( std::unique_ptr<Task> ( task ) ); m_dependencies.push_back( std::vector<TaskId>() ); m_remainingDependencies.push_back( 0 ); TimerData tdata; tdata.taskName = task->getName(); m_timerData.push_back( tdata ); CORE_ASSERT( m_tasks.size() == m_dependencies.size(), "Inconsistent task list" ); CORE_ASSERT( m_tasks.size() == m_remainingDependencies.size(), "Inconsistent task list" ); CORE_ASSERT( m_tasks.size() == m_timerData.size(), "Inconsistent task list" ); return TaskId( m_tasks.size() - 1 ); } void TaskQueue::addDependency( TaskQueue::TaskId predecessor, TaskQueue::TaskId successor ) { CORE_ASSERT( ( predecessor != InvalidTaskId ) && ( predecessor < m_tasks.size() ), "Invalid predecessor task" ); CORE_ASSERT( ( successor != InvalidTaskId ) && ( successor < m_tasks.size() ), "Invalid successor task" ); CORE_ASSERT( predecessor != successor, "Cannot add self-dependency" ); m_dependencies[predecessor].push_back( successor ); ++m_remainingDependencies[successor]; } bool TaskQueue::addDependency(const std::string &predecessors, TaskQueue::TaskId successor) { bool added = false; for (uint i = 0; i < m_tasks.size(); ++i) { if (m_tasks[i]->getName() == predecessors ) { added = true; addDependency( i, successor); } } return added; } bool TaskQueue::addDependency(TaskQueue::TaskId predecessor, const std::string &successors) { bool added = false; for (uint i = 0; i < m_tasks.size(); ++i) { if (m_tasks[i]->getName() == successors ) { added = true; addDependency( predecessor, i ); } } return added; } void TaskQueue::addPendingDependency(const std::string &predecessors, TaskQueue::TaskId successor) { m_pendingDepsSucc.push_back(std::make_pair(predecessors, successor)); } void TaskQueue::addPendingDependency( TaskId predecessor, const std::string& successors) { m_pendingDepsPre.push_back(std::make_pair(predecessor, successors)); } void TaskQueue::resolveDependencies() { for ( const auto& pre : m_pendingDepsPre ) { bool result = addDependency( pre.first, pre.second ); CORE_ASSERT( result, "Pending dependency unresolved"); } for ( const auto& pre : m_pendingDepsSucc ) { bool result = addDependency( pre.first, pre.second ); CORE_ASSERT( result, "Pending dependency unresolved"); } m_pendingDepsPre.clear(); m_pendingDepsSucc.clear(); } void TaskQueue::queueTask( TaskQueue::TaskId task ) { CORE_ASSERT( m_remainingDependencies[task] == 0, " Task has unsatisfied dependencies" ); m_taskQueue.push_front( task ); } void TaskQueue::detectCycles() { #if defined (CORE_DEBUG) // Do a depth-first search of the nodes. std::vector<bool> visited( m_tasks.size(), false ); std::stack<TaskId> pending; for (TaskId id = 0; id < m_tasks.size(); ++id) { if ( m_dependencies[id].size() == 0 ) { pending.push(id); } } // If you hit this assert, there are tasks in the list but // all tasks have dependencies so no task can start. CORE_ASSERT( m_tasks.empty() || !pending.empty(), "No free tasks."); while (! pending.empty()) { TaskId id = pending.top(); pending.pop(); // The task has already been visited. It means there is a cycle in the task graph. CORE_ASSERT( !(visited[id]), "Cycle detected in tasks !"); visited[id] = true; for ( const auto& dep : m_dependencies[id]) { pending.push( dep ); } } #endif } void TaskQueue::startTasks() { // Add pending dependencies. resolveDependencies(); // Do a debug check detectCycles(); // Enqueue all tasks with no dependencies. for ( uint t = 0; t < m_tasks.size(); ++t ) { if ( m_remainingDependencies[t] == 0 ) { queueTask( t ); } } // Wake up all threads. m_threadNotifier.notify_all(); } void TaskQueue::waitForTasks() { bool isFinished = false; while ( !isFinished ) { // TODO : use a notifier for task queue empty. m_taskQueueMutex.lock(); isFinished = ( m_taskQueue.empty() && m_processingTasks == 0 ); m_taskQueueMutex.unlock(); if ( !isFinished ) { std::this_thread::yield(); } } } const std::vector<TaskQueue::TimerData>& TaskQueue::getTimerData() { return m_timerData; } void TaskQueue::flushTaskQueue() { CORE_ASSERT( m_processingTasks == 0, "You have tasks still in process" ); CORE_ASSERT( m_taskQueue.empty(), " You have unprocessed tasks " ); m_tasks.clear(); m_dependencies.clear(); m_timerData.clear(); m_remainingDependencies.clear(); } void TaskQueue::runThread( uint id ) { while ( true ) { TaskId task = InvalidTaskId; // Acquire mutex. { std::unique_lock<std::mutex> lock( m_taskQueueMutex ); // Wait for a new task // TODO : use the second form of wait() while ( !m_shuttingDown && m_taskQueue.empty() ) { m_threadNotifier.wait( lock ); } // If the task queue is shutting down we quit, releasing // the lock. if ( m_shuttingDown ) { return; } // If we are here it means we got a task task = m_taskQueue.back(); m_taskQueue.pop_back(); ++m_processingTasks; CORE_ASSERT( task != InvalidTaskId && task < m_tasks.size(), "Invalid task" ); } // Release mutex. // Run task m_timerData[task].start = Timer::Clock::now(); m_tasks[task]->process(); m_timerData[task].end = Timer::Clock::now(); // Critical section : mark task as finished and en-queue dependencies. uint newTasks = 0; { std::unique_lock<std::mutex> lock( m_taskQueueMutex ); for ( auto t : m_dependencies[task] ) { uint& nDepends = m_remainingDependencies[t]; CORE_ASSERT( nDepends > 0, "Inconsistency in dependencies" ); --nDepends; if ( nDepends == 0 ) { queueTask( t ); ++newTasks; } // TODO :Easy optimization : grab one of the new task and process it immediately. } --m_processingTasks; } // If we added new tasks, we wake up one thread to execute it. if ( newTasks > 0 ) { m_threadNotifier.notify_one(); } } // End of while(true) } } } <commit_msg>Debug check adding duplicate task dependency<commit_after>#include <Core/Tasks/TaskQueue.hpp> #include <Core/Tasks/Task.hpp> #include <stack> #include <iostream> namespace Ra { namespace Core { TaskQueue::TaskQueue( uint numThreads ) : m_processingTasks( 0 ), m_shuttingDown( false ) { CORE_ASSERT( numThreads > 0, " You need at least one thread" ); m_workerThreads.reserve( numThreads ); for ( uint i = 0 ; i < numThreads; ++i ) { m_workerThreads.emplace_back( std::thread( &TaskQueue::runThread, this, i ) ); } } TaskQueue::~TaskQueue() { flushTaskQueue(); m_shuttingDown = true; m_threadNotifier.notify_all(); for ( auto& t : m_workerThreads ) { t.join(); } } TaskQueue::TaskId TaskQueue::registerTask( Task* task ) { m_tasks.emplace_back( std::unique_ptr<Task> ( task ) ); m_dependencies.push_back( std::vector<TaskId>() ); m_remainingDependencies.push_back( 0 ); TimerData tdata; tdata.taskName = task->getName(); m_timerData.push_back( tdata ); CORE_ASSERT( m_tasks.size() == m_dependencies.size(), "Inconsistent task list" ); CORE_ASSERT( m_tasks.size() == m_remainingDependencies.size(), "Inconsistent task list" ); CORE_ASSERT( m_tasks.size() == m_timerData.size(), "Inconsistent task list" ); return TaskId( m_tasks.size() - 1 ); } void TaskQueue::addDependency( TaskQueue::TaskId predecessor, TaskQueue::TaskId successor ) { CORE_ASSERT( ( predecessor != InvalidTaskId ) && ( predecessor < m_tasks.size() ), "Invalid predecessor task" ); CORE_ASSERT( ( successor != InvalidTaskId ) && ( successor < m_tasks.size() ), "Invalid successor task" ); CORE_ASSERT( predecessor != successor, "Cannot add self-dependency" ); CORE_ASSERT( m_dependencies[predecessor].find(successor) == m_dependencies[predecessor].end(), "Cannot add a dependency twice" ); m_dependencies[predecessor].push_back( successor ); ++m_remainingDependencies[successor]; } bool TaskQueue::addDependency(const std::string &predecessors, TaskQueue::TaskId successor) { bool added = false; for (uint i = 0; i < m_tasks.size(); ++i) { if (m_tasks[i]->getName() == predecessors ) { added = true; addDependency( i, successor); } } return added; } bool TaskQueue::addDependency(TaskQueue::TaskId predecessor, const std::string &successors) { bool added = false; for (uint i = 0; i < m_tasks.size(); ++i) { if (m_tasks[i]->getName() == successors ) { added = true; addDependency( predecessor, i ); } } return added; } void TaskQueue::addPendingDependency(const std::string &predecessors, TaskQueue::TaskId successor) { m_pendingDepsSucc.push_back(std::make_pair(predecessors, successor)); } void TaskQueue::addPendingDependency( TaskId predecessor, const std::string& successors) { m_pendingDepsPre.push_back(std::make_pair(predecessor, successors)); } void TaskQueue::resolveDependencies() { for ( const auto& pre : m_pendingDepsPre ) { bool result = addDependency( pre.first, pre.second ); CORE_ASSERT( result, "Pending dependency unresolved"); } for ( const auto& pre : m_pendingDepsSucc ) { bool result = addDependency( pre.first, pre.second ); CORE_ASSERT( result, "Pending dependency unresolved"); } m_pendingDepsPre.clear(); m_pendingDepsSucc.clear(); } void TaskQueue::queueTask( TaskQueue::TaskId task ) { CORE_ASSERT( m_remainingDependencies[task] == 0, " Task has unsatisfied dependencies" ); m_taskQueue.push_front( task ); } void TaskQueue::detectCycles() { #if defined (CORE_DEBUG) // Do a depth-first search of the nodes. std::vector<bool> visited( m_tasks.size(), false ); std::stack<TaskId> pending; for (TaskId id = 0; id < m_tasks.size(); ++id) { if ( m_dependencies[id].size() == 0 ) { pending.push(id); } } // If you hit this assert, there are tasks in the list but // all tasks have dependencies so no task can start. CORE_ASSERT( m_tasks.empty() || !pending.empty(), "No free tasks."); while (! pending.empty()) { TaskId id = pending.top(); pending.pop(); // The task has already been visited. It means there is a cycle in the task graph. CORE_ASSERT( !(visited[id]), "Cycle detected in tasks !"); visited[id] = true; for ( const auto& dep : m_dependencies[id]) { pending.push( dep ); } } #endif } void TaskQueue::startTasks() { // Add pending dependencies. resolveDependencies(); // Do a debug check detectCycles(); // Enqueue all tasks with no dependencies. for ( uint t = 0; t < m_tasks.size(); ++t ) { if ( m_remainingDependencies[t] == 0 ) { queueTask( t ); } } // Wake up all threads. m_threadNotifier.notify_all(); } void TaskQueue::waitForTasks() { bool isFinished = false; while ( !isFinished ) { // TODO : use a notifier for task queue empty. m_taskQueueMutex.lock(); isFinished = ( m_taskQueue.empty() && m_processingTasks == 0 ); m_taskQueueMutex.unlock(); if ( !isFinished ) { std::this_thread::yield(); } } } const std::vector<TaskQueue::TimerData>& TaskQueue::getTimerData() { return m_timerData; } void TaskQueue::flushTaskQueue() { CORE_ASSERT( m_processingTasks == 0, "You have tasks still in process" ); CORE_ASSERT( m_taskQueue.empty(), " You have unprocessed tasks " ); m_tasks.clear(); m_dependencies.clear(); m_timerData.clear(); m_remainingDependencies.clear(); } void TaskQueue::runThread( uint id ) { while ( true ) { TaskId task = InvalidTaskId; // Acquire mutex. { std::unique_lock<std::mutex> lock( m_taskQueueMutex ); // Wait for a new task // TODO : use the second form of wait() while ( !m_shuttingDown && m_taskQueue.empty() ) { m_threadNotifier.wait( lock ); } // If the task queue is shutting down we quit, releasing // the lock. if ( m_shuttingDown ) { return; } // If we are here it means we got a task task = m_taskQueue.back(); m_taskQueue.pop_back(); ++m_processingTasks; CORE_ASSERT( task != InvalidTaskId && task < m_tasks.size(), "Invalid task" ); } // Release mutex. // Run task m_timerData[task].start = Timer::Clock::now(); m_tasks[task]->process(); m_timerData[task].end = Timer::Clock::now(); // Critical section : mark task as finished and en-queue dependencies. uint newTasks = 0; { std::unique_lock<std::mutex> lock( m_taskQueueMutex ); for ( auto t : m_dependencies[task] ) { uint& nDepends = m_remainingDependencies[t]; CORE_ASSERT( nDepends > 0, "Inconsistency in dependencies" ); --nDepends; if ( nDepends == 0 ) { queueTask( t ); ++newTasks; } // TODO :Easy optimization : grab one of the new task and process it immediately. } --m_processingTasks; } // If we added new tasks, we wake up one thread to execute it. if ( newTasks > 0 ) { m_threadNotifier.notify_one(); } } // End of while(true) } } } <|endoftext|>
<commit_before>#include <ctime> #include <json/json.h> #include <fstream> #include <iostream> #include <utils.h> #include "CommandHandler.h" static bool valid_resp(const std::string &resp, std::string &err); CustomCommandHandler::CustomCommandHandler(commandMap *defaultCmds, TimerManager *tm, const std::string &wheelCmd, const std::string &name, const std::string &channel) : m_cmp(defaultCmds), m_tmp(tm), m_wheelCmd(wheelCmd), m_name(name), m_channel(channel) { if (!(m_active = utils::readJSON("customcmds.json", m_commands))) { std::cerr << "Could not read customcmds.json."; return; } if (!m_commands.isMember("commands") || !m_commands["commands"].isArray()) { m_active = false; std::cerr << "customcmds.json is improperly configured"; return; } if (!cmdcheck()) std::cerr << "\nCustom commands disabled." << std::endl; } CustomCommandHandler::~CustomCommandHandler() {} bool CustomCommandHandler::isActive() { return m_active; } /* addCom: add a new custom command cmd with response and cooldown */ bool CustomCommandHandler::addcom(const std::string &cmd, const std::string &response, const std::string &nick, time_t cooldown) { time_t t; if (!validName(cmd)) { m_error = "invalid command name: $" + cmd; return false; } if (!valid_resp(response, m_error)) return false; Json::Value command; command["active"] = true; command["cmd"] = cmd; command["response"] = response; command["cooldown"] = (Json::Int64)cooldown; command["ctime"] = (Json::Int64)(t = time(nullptr)); command["mtime"] = (Json::Int64)t; command["creator"] = nick; command["uses"] = 0; m_commands["commands"].append(command); m_tmp->add(cmd, cooldown); write(); return true; } /* delCom: delete command cmd if it exists */ bool CustomCommandHandler::delcom(const std::string &cmd) { Json::ArrayIndex ind = 0; Json::Value def, rem; while (ind < m_commands["commands"].size()) { Json::Value val = m_commands["commands"].get(ind, def); if (val["cmd"] == cmd) break; ++ind; } if (ind == m_commands["commands"].size()) return false; m_commands["commands"].removeIndex(ind, &rem); m_tmp->remove(cmd); write(); return true; } /* editCom: modify the command cmd with newResp and newcd */ bool CustomCommandHandler::editcom(const std::string &cmd, const std::string &newResp, time_t newcd) { auto *com = getcom(cmd); if (com->empty()) { m_error = "not a command: $" + cmd; return false; } if (!valid_resp(newResp, m_error)) return false; if (!newResp.empty()) (*com)["response"] = newResp; if (newcd != -1) { (*com)["cooldown"] = (Json::Int64)newcd; m_tmp->remove(cmd); m_tmp->add(cmd, newcd); } (*com)["mtime"] = (Json::Int64)time(nullptr); write(); return true; } /* activate: activate the command cmd */ bool CustomCommandHandler::activate(const std::string &cmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } if (!valid_resp((*com)["response"].asString(), m_error)) return false; (*com)["active"] = true; write(); return true; } /* deactivate: deactivate the command cmd */ bool CustomCommandHandler::deactivate(const std::string &cmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } (*com)["active"] = false; write(); return true; } /* rename: rename custom command cmd to newcmd */ bool CustomCommandHandler::rename(const std::string &cmd, const std::string &newcmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } (*com)["cmd"] = newcmd; (*com)["mtime"] = (Json::Int64)time(nullptr); m_tmp->remove(cmd); m_tmp->add(newcmd, (*com)["cooldown"].asInt64()); write(); return true; } /* getcom: return command value if it exists, empty value otherwise */ Json::Value *CustomCommandHandler::getcom(const std::string &cmd) { for (auto &val : m_commands["commands"]) { if (val["cmd"] == cmd) return &val; } /* returns an empty value if the command is not found */ return &m_emptyVal; } const Json::Value *CustomCommandHandler::commands() { return &m_commands; } /* write: write all commands to file */ void CustomCommandHandler::write() { utils::writeJSON("customcmds.json", m_commands); } /* validName: check if cmd is a valid command name */ bool CustomCommandHandler::validName(const std::string &cmd, bool loading) { /* if CCH is loading commands from file (in constructor) */ /* it doesn't need to check against its stored commands */ return m_cmp->find(cmd) == m_cmp->end() && cmd != m_wheelCmd && cmd.length() < 20 && (loading ? true : getcom(cmd)->empty()); } std::string CustomCommandHandler::error() const { return m_error; } /* format: format a response for cmd */ std::string CustomCommandHandler::format(const Json::Value *cmd, const std::string &nick) const { size_t ind; std::string out, ins; char c; ind = 0; out = (*cmd)["response"].asString(); while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + nick + ","; break; case 'b': ins = m_name; break; case 'c': ins = m_channel; break; case 'n': ins = nick; break; case 'u': ins = utils::formatInteger((*cmd)["uses"].asString()); break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* cmdcheck: check the validity of a command and add missing fields */ bool CustomCommandHandler::cmdcheck() { time_t t; bool added; t = time(nullptr); added = false; for (Json::Value &val : m_commands["commands"]) { /* add new values to old commands */ if (!val.isMember("ctime")) { val["ctime"] = (Json::Int64)t; added = true; } if (!val.isMember("mtime")) { val["mtime"] = (Json::Int64)t; added = true; } if (!val.isMember("creator")) { val["creator"] = "unknown"; added = true; } if (!val.isMember("uses")) { val["uses"] = 0; added = true; } if (!val.isMember("active")) { val["active"] = true; added = true; } if (!(val.isMember("cmd") && val.isMember("response") && val.isMember("cooldown"))) { m_active = false; std::cerr << "customcmds.json is improperly configured"; return false; } if (!validName(val["cmd"].asString(), true)) { m_active = false; std::cerr << val["cmd"].asString() << " is an invalid command name - change " "or remove it"; return false; } if (val["cooldown"].asInt() < 0) { m_active = false; std::cerr << "command \"" << val["cmd"].asString() << "\" has a negative cooldown - change " "or remove it"; return false; } /* check validity of response */ if (!valid_resp(val["response"].asString(), m_error)) { std::cerr << "Custom command " << val["cmd"].asString() << ": " << m_error << std::endl; val["active"] = false; added = true; } if (added) write(); m_tmp->add(val["cmd"].asString(), val["cooldown"].asInt64()); } return true; } /* valid_resp: check if a response has valid format characters */ static bool valid_resp(const std::string &resp, std::string &err) { static const std::string fmt_c = "%Nbcnu"; size_t ind; int c; ind = -1; while ((ind = resp.find('%', ind + 1)) != std::string::npos) { if (ind == resp.length() - 1) { err = "unexpected end of line after '%' in response"; return false; } c = resp[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format sequence '%"; err += (char)c; err += "' in response"; return false; } if (c == '%') ++ind; } return true; } <commit_msg>Check valid name on editcom rename<commit_after>#include <ctime> #include <json/json.h> #include <fstream> #include <iostream> #include <utils.h> #include "CommandHandler.h" static bool valid_resp(const std::string &resp, std::string &err); CustomCommandHandler::CustomCommandHandler(commandMap *defaultCmds, TimerManager *tm, const std::string &wheelCmd, const std::string &name, const std::string &channel) : m_cmp(defaultCmds), m_tmp(tm), m_wheelCmd(wheelCmd), m_name(name), m_channel(channel) { if (!(m_active = utils::readJSON("customcmds.json", m_commands))) { std::cerr << "Could not read customcmds.json."; return; } if (!m_commands.isMember("commands") || !m_commands["commands"].isArray()) { m_active = false; std::cerr << "customcmds.json is improperly configured"; return; } if (!cmdcheck()) std::cerr << "\nCustom commands disabled." << std::endl; } CustomCommandHandler::~CustomCommandHandler() {} bool CustomCommandHandler::isActive() { return m_active; } /* addCom: add a new custom command cmd with response and cooldown */ bool CustomCommandHandler::addcom(const std::string &cmd, const std::string &response, const std::string &nick, time_t cooldown) { time_t t; if (!validName(cmd)) { m_error = "invalid command name: $" + cmd; return false; } if (!valid_resp(response, m_error)) return false; Json::Value command; command["active"] = true; command["cmd"] = cmd; command["response"] = response; command["cooldown"] = (Json::Int64)cooldown; command["ctime"] = (Json::Int64)(t = time(nullptr)); command["mtime"] = (Json::Int64)t; command["creator"] = nick; command["uses"] = 0; m_commands["commands"].append(command); m_tmp->add(cmd, cooldown); write(); return true; } /* delCom: delete command cmd if it exists */ bool CustomCommandHandler::delcom(const std::string &cmd) { Json::ArrayIndex ind = 0; Json::Value def, rem; while (ind < m_commands["commands"].size()) { Json::Value val = m_commands["commands"].get(ind, def); if (val["cmd"] == cmd) break; ++ind; } if (ind == m_commands["commands"].size()) return false; m_commands["commands"].removeIndex(ind, &rem); m_tmp->remove(cmd); write(); return true; } /* editCom: modify the command cmd with newResp and newcd */ bool CustomCommandHandler::editcom(const std::string &cmd, const std::string &newResp, time_t newcd) { auto *com = getcom(cmd); if (com->empty()) { m_error = "not a command: $" + cmd; return false; } if (!valid_resp(newResp, m_error)) return false; if (!newResp.empty()) (*com)["response"] = newResp; if (newcd != -1) { (*com)["cooldown"] = (Json::Int64)newcd; m_tmp->remove(cmd); m_tmp->add(cmd, newcd); } (*com)["mtime"] = (Json::Int64)time(nullptr); write(); return true; } /* activate: activate the command cmd */ bool CustomCommandHandler::activate(const std::string &cmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } if (!valid_resp((*com)["response"].asString(), m_error)) return false; (*com)["active"] = true; write(); return true; } /* deactivate: deactivate the command cmd */ bool CustomCommandHandler::deactivate(const std::string &cmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } (*com)["active"] = false; write(); return true; } /* rename: rename custom command cmd to newcmd */ bool CustomCommandHandler::rename(const std::string &cmd, const std::string &newcmd) { Json::Value *com; if ((com = getcom(cmd))->empty()) { m_error = "not a command: $" + cmd; return false; } if (!validName(newcmd)) { m_error = "invalid command name: $" + newcmd; return false; } (*com)["cmd"] = newcmd; (*com)["mtime"] = (Json::Int64)time(nullptr); m_tmp->remove(cmd); m_tmp->add(newcmd, (*com)["cooldown"].asInt64()); write(); return true; } /* getcom: return command value if it exists, empty value otherwise */ Json::Value *CustomCommandHandler::getcom(const std::string &cmd) { for (auto &val : m_commands["commands"]) { if (val["cmd"] == cmd) return &val; } /* returns an empty value if the command is not found */ return &m_emptyVal; } const Json::Value *CustomCommandHandler::commands() { return &m_commands; } /* write: write all commands to file */ void CustomCommandHandler::write() { utils::writeJSON("customcmds.json", m_commands); } /* validName: check if cmd is a valid command name */ bool CustomCommandHandler::validName(const std::string &cmd, bool loading) { /* if CCH is loading commands from file (in constructor) */ /* it doesn't need to check against its stored commands */ return m_cmp->find(cmd) == m_cmp->end() && cmd != m_wheelCmd && cmd.length() < 20 && (loading ? true : getcom(cmd)->empty()); } std::string CustomCommandHandler::error() const { return m_error; } /* format: format a response for cmd */ std::string CustomCommandHandler::format(const Json::Value *cmd, const std::string &nick) const { size_t ind; std::string out, ins; char c; ind = 0; out = (*cmd)["response"].asString(); while ((ind = out.find('%', ind)) != std::string::npos) { c = out[ind + 1]; out.erase(ind, 2); switch (c) { case '%': ins = "%"; break; case 'N': ins = "@" + nick + ","; break; case 'b': ins = m_name; break; case 'c': ins = m_channel; break; case 'n': ins = nick; break; case 'u': ins = utils::formatInteger((*cmd)["uses"].asString()); break; default: break; } out.insert(ind, ins); ind += ins.length(); } return out; } /* cmdcheck: check the validity of a command and add missing fields */ bool CustomCommandHandler::cmdcheck() { time_t t; bool added; t = time(nullptr); added = false; for (Json::Value &val : m_commands["commands"]) { /* add new values to old commands */ if (!val.isMember("ctime")) { val["ctime"] = (Json::Int64)t; added = true; } if (!val.isMember("mtime")) { val["mtime"] = (Json::Int64)t; added = true; } if (!val.isMember("creator")) { val["creator"] = "unknown"; added = true; } if (!val.isMember("uses")) { val["uses"] = 0; added = true; } if (!val.isMember("active")) { val["active"] = true; added = true; } if (!(val.isMember("cmd") && val.isMember("response") && val.isMember("cooldown"))) { m_active = false; std::cerr << "customcmds.json is improperly configured"; return false; } if (!validName(val["cmd"].asString(), true)) { m_active = false; std::cerr << val["cmd"].asString() << " is an invalid command name - change " "or remove it"; return false; } if (val["cooldown"].asInt() < 0) { m_active = false; std::cerr << "command \"" << val["cmd"].asString() << "\" has a negative cooldown - change " "or remove it"; return false; } /* check validity of response */ if (!valid_resp(val["response"].asString(), m_error)) { std::cerr << "Custom command " << val["cmd"].asString() << ": " << m_error << std::endl; val["active"] = false; added = true; } if (added) write(); m_tmp->add(val["cmd"].asString(), val["cooldown"].asInt64()); } return true; } /* valid_resp: check if a response has valid format characters */ static bool valid_resp(const std::string &resp, std::string &err) { static const std::string fmt_c = "%Nbcnu"; size_t ind; int c; ind = -1; while ((ind = resp.find('%', ind + 1)) != std::string::npos) { if (ind == resp.length() - 1) { err = "unexpected end of line after '%' in response"; return false; } c = resp[ind + 1]; if (fmt_c.find(c) == std::string::npos) { err = "invalid format sequence '%"; err += (char)c; err += "' in response"; return false; } if (c == '%') ++ind; } return true; } <|endoftext|>
<commit_before>#ifndef TATUM_COMMON_ANALYSIS_VISITOR_HPP #define TATUM_COMMON_ANALYSIS_VISITOR_HPP #include "tatum_error.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "TimingTags.hpp" namespace tatum { namespace detail { /** \file * * Common analysis functionality for both setup and hold analysis. */ /** \class CommonAnalysisVisitor * * A class satisfying the GraphVisitor concept, which contains common * node and edge processing code used by both setup and hold analysis. * * \see GraphVisitor * * \tparam AnalysisOps a class defining the setup/hold specific operations * \see SetupAnalysisOps * \see HoldAnalysisOps */ template<class AnalysisOps> class CommonAnalysisVisitor { public: CommonAnalysisVisitor(size_t num_tags) : ops_(num_tags) { } void do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id); void do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id); template<class DelayCalc> void do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id); template<class DelayCalc> void do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id); void reset() { ops_.reset(); } protected: AnalysisOps ops_; private: template<class DelayCalc> void do_arrival_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id); template<class DelayCalc> void do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id); }; /* * Pre-traversal */ template<class AnalysisOps> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) { //Logical Input TATUM_ASSERT_MSG(tg.node_in_edges(node_id).size() == 0, "Logical input has input edges: timing graph not levelized."); NodeType node_type = tg.node_type(node_id); //We don't propagate any tags from constant generators, //since they do not effect the dynamic timing behaviour of the //system if(tc.node_is_constant_generator(node_id)) return; if(tc.node_is_clock_source(node_id)) { //Generate the appropriate clock tag //Note that we assume that edge counting has set the effective period constraint assuming a //launch edge at time zero. This means we don't need to do anything special for clocks //with rising edges after time zero. TATUM_ASSERT_MSG(ops_.get_clock_tags(node_id).num_tags() == 0, "Clock source already has clock tags"); //Find it's domain DomainId domain_id = tc.node_clock_domain(node_id); TATUM_ASSERT(domain_id); //Initialize a clock tag with zero arrival, invalid required time TimingTag clock_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id); //Add the tag ops_.get_clock_tags(node_id).add_tag(clock_tag); } else { TATUM_ASSERT(node_type == NodeType::SOURCE); //A standard primary input, generate the appropriate data tag //We assume input delays are on the arc from INPAD_SOURCE to INPAD_OPIN, //so we do not need to account for it directly in the arrival time of INPAD_SOURCES TATUM_ASSERT_MSG(ops_.get_data_tags(node_id).num_tags() == 0, "Primary input already has data tags"); DomainId domain_id = tc.node_clock_domain(node_id); TATUM_ASSERT(domain_id); //Initialize a data tag with zero arrival, invalid required time TimingTag input_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id); ops_.get_data_tags(node_id).add_tag(input_tag); } } template<class AnalysisOps> void CommonAnalysisVisitor<AnalysisOps>::do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) { TimingTags& node_data_tags = ops_.get_data_tags(node_id); TimingTags& node_clock_tags = ops_.get_clock_tags(node_id); /* * Calculate required times */ auto node_type = tg.node_type(node_id); TATUM_ASSERT(node_type == NodeType::SINK); //Sinks corresponding to FF sinks will have propagated clock tags, //while those corresponding to outpads will not. if(node_clock_tags.empty()) { //Initialize the outpad's clock tags based on the specified constraints. auto output_constraints = tc.output_constraints(node_id); if(output_constraints.empty()) { //throw tatum::Error("Output unconstrained"); std::cerr << "Warning: Timing graph " << node_id << " " << node_type << " has no incomming clock tags, and no output constraint. No required time will be calculated\n"; #if 1 //Debug trace-back //TODO: remove debug code! if(node_type == NodeType::FF_SINK) { std::cerr << "\tClock path:\n"; int i = 0; NodeId curr_node = node_id; while(tg.node_type(curr_node) != NodeType::INPAD_SOURCE && tg.node_type(curr_node) != NodeType::CLOCK_SOURCE && tg.node_type(curr_node) != NodeType::CONSTANT_GEN_SOURCE && i < 100) { //Look throught the fanin for a clock or other node to follow // //Typically the first hop from node_id will be to either the IPIN or CLOCK pin //the following preferentially prefers the CLOCK pin to show the clock path EdgeId best_edge; for(auto edge_id : tg.node_in_edges(curr_node)) { if(!best_edge) { best_edge = edge_id; } NodeId src_node = tg.edge_src_node(edge_id); auto src_node_type = tg.node_type(src_node); if(src_node_type == NodeType::FF_CLOCK) { best_edge = edge_id; } } //Step back curr_node = tg.edge_src_node(best_edge); auto curr_node_type = tg.node_type(curr_node); std::cerr << "\tNode " << curr_node << " Type: " << curr_node_type << "\n"; if(++i >= 100) { std::cerr << "\tStopping backtrace\n"; } } } #endif } else { for(auto constraint : output_constraints) { //TODO: use real constraint value when output delay no-longer on edges TimingTag constraint_tag = TimingTag(Time(0.), Time(NAN), constraint.second.domain, node_id); node_clock_tags.add_tag(constraint_tag); } } } //At this stage both FF and outpad sinks now have the relevant clock //tags and we can process them equivalently //Determine the required time at this sink // //We need to generate a required time for each clock domain for which there is a data //arrival time at this node, while considering all possible clocks that could drive //this node (i.e. take the most restrictive constraint accross all clock tags at this //node) for(TimingTag& node_data_tag : node_data_tags) { for(const TimingTag& node_clock_tag : node_clock_tags) { //Should we be analyzing paths between these two domains? if(tc.should_analyze(node_data_tag.clock_domain(), node_clock_tag.clock_domain())) { //We only set a required time if the source domain actually reaches this sink //domain. This is indicated by having a valid arrival time. if(node_data_tag.arr_time().valid()) { float clock_constraint = ops_.clock_constraint(tc, node_data_tag.clock_domain(), node_clock_tag.clock_domain()); //Update the required time. This will keep the most restrictive constraint. ops_.merge_req_tag(node_data_tag, node_clock_tag.arr_time() + Time(clock_constraint), node_data_tag); } } } } } /* * Arrival Time Operations */ template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, NodeId node_id) { //Do not propagate arrival tags through constant generators if(tc.node_is_constant_generator(node_id)) return; //Pull from upstream sources to current node for(EdgeId edge_id : tg.node_in_edges(node_id)) { do_arrival_traverse_edge(tg, dc, node_id, edge_id); } } template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) { //We must use the tags by reference so we don't accidentally wipe-out any //existing tags TimingTags& node_data_tags = ops_.get_data_tags(node_id); TimingTags& node_clock_tags = ops_.get_clock_tags(node_id); //Pulling values from upstream source node NodeId src_node_id = tg.edge_src_node(edge_id); const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id); const TimingTags& src_clk_tags = ops_.get_clock_tags(src_node_id); const TimingTags& src_data_tags = ops_.get_data_tags(src_node_id); /* * Clock tags */ if(src_data_tags.empty()) { //Propagate the clock tags through the clock network for(const TimingTag& src_clk_tag : src_clk_tags) { //Standard propagation through the clock network ops_.merge_arr_tags(node_clock_tags, src_clk_tag.arr_time() + edge_delay, src_clk_tag); if(tg.node_type(node_id) == NodeType::FF_SOURCE) { //FIXME: Should be any source type //We are traversing a clock to data launch edge. // //We convert the clock arrival time to a data //arrival time at this node (since the clock //arrival launches the data). //Make a copy of the tag TimingTag launch_tag = src_clk_tag; //Update the launch node, since the data is //launching from this node launch_tag.set_launch_node(node_id); //Mark propagated launch time as a DATA tag ops_.merge_arr_tags(node_data_tags, launch_tag.arr_time() + edge_delay, launch_tag); } } } /* * Data tags */ for(const TimingTag& src_data_tag : src_data_tags) { //Standard data-path propagation ops_.merge_arr_tags(node_data_tags, src_data_tag.arr_time() + edge_delay, src_data_tag); } } /* * Required Time Operations */ template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id) { //Do not propagate required tags through constant generators if(tc.node_is_constant_generator(node_id)) return; //Pull from downstream sinks to current node for(EdgeId edge_id : tg.node_out_edges(node_id)) { do_required_traverse_edge(tg, dc, node_id, edge_id); } } template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) { //We must use the tags by reference so we don't accidentally wipe-out any //existing tags TimingTags& node_data_tags = ops_.get_data_tags(node_id); //Pulling values from downstream sink node NodeId sink_node_id = tg.edge_sink_node(edge_id); const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id); const TimingTags& sink_data_tags = ops_.get_data_tags(sink_node_id); for(const TimingTag& sink_tag : sink_data_tags) { //We only propogate the required time if we have a valid arrival time auto matched_tag_iter = node_data_tags.find_tag_by_clock_domain(sink_tag.clock_domain()); if(matched_tag_iter != node_data_tags.end() && matched_tag_iter->arr_time().valid()) { //Valid arrival, update required ops_.merge_req_tag(*matched_tag_iter, sink_tag.req_time() - edge_delay, sink_tag); } } } }} //namepsace #endif <commit_msg>Factor out clock to data edge detection into function<commit_after>#ifndef TATUM_COMMON_ANALYSIS_VISITOR_HPP #define TATUM_COMMON_ANALYSIS_VISITOR_HPP #include "tatum_error.hpp" #include "TimingGraph.hpp" #include "TimingConstraints.hpp" #include "TimingTags.hpp" namespace tatum { namespace detail { /** \file * * Common analysis functionality for both setup and hold analysis. */ /** \class CommonAnalysisVisitor * * A class satisfying the GraphVisitor concept, which contains common * node and edge processing code used by both setup and hold analysis. * * \see GraphVisitor * * \tparam AnalysisOps a class defining the setup/hold specific operations * \see SetupAnalysisOps * \see HoldAnalysisOps */ template<class AnalysisOps> class CommonAnalysisVisitor { public: CommonAnalysisVisitor(size_t num_tags) : ops_(num_tags) { } void do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id); void do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id); template<class DelayCalc> void do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id); template<class DelayCalc> void do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id); void reset() { ops_.reset(); } protected: AnalysisOps ops_; private: template<class DelayCalc> void do_arrival_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id); template<class DelayCalc> void do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id); bool is_clock_to_data_edge(const TimingGraph& tg, const NodeId src_node_id, const NodeId node_id) const; }; /* * Pre-traversal */ template<class AnalysisOps> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) { //Logical Input TATUM_ASSERT_MSG(tg.node_in_edges(node_id).size() == 0, "Logical input has input edges: timing graph not levelized."); NodeType node_type = tg.node_type(node_id); //We don't propagate any tags from constant generators, //since they do not effect the dynamic timing behaviour of the //system if(tc.node_is_constant_generator(node_id)) return; if(tc.node_is_clock_source(node_id)) { //Generate the appropriate clock tag //Note that we assume that edge counting has set the effective period constraint assuming a //launch edge at time zero. This means we don't need to do anything special for clocks //with rising edges after time zero. TATUM_ASSERT_MSG(ops_.get_clock_tags(node_id).num_tags() == 0, "Clock source already has clock tags"); //Find it's domain DomainId domain_id = tc.node_clock_domain(node_id); TATUM_ASSERT(domain_id); //Initialize a clock tag with zero arrival, invalid required time TimingTag clock_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id); //Add the tag ops_.get_clock_tags(node_id).add_tag(clock_tag); } else { TATUM_ASSERT(node_type == NodeType::SOURCE); //A standard primary input, generate the appropriate data tag //We assume input delays are on the arc from INPAD_SOURCE to INPAD_OPIN, //so we do not need to account for it directly in the arrival time of INPAD_SOURCES TATUM_ASSERT_MSG(ops_.get_data_tags(node_id).num_tags() == 0, "Primary input already has data tags"); DomainId domain_id = tc.node_clock_domain(node_id); TATUM_ASSERT(domain_id); //Initialize a data tag with zero arrival, invalid required time TimingTag input_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id); ops_.get_data_tags(node_id).add_tag(input_tag); } } template<class AnalysisOps> void CommonAnalysisVisitor<AnalysisOps>::do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) { TimingTags& node_data_tags = ops_.get_data_tags(node_id); TimingTags& node_clock_tags = ops_.get_clock_tags(node_id); /* * Calculate required times */ auto node_type = tg.node_type(node_id); TATUM_ASSERT(node_type == NodeType::SINK); //Sinks corresponding to FF sinks will have propagated clock tags, //while those corresponding to outpads will not. if(node_clock_tags.empty()) { //Initialize the outpad's clock tags based on the specified constraints. auto output_constraints = tc.output_constraints(node_id); if(output_constraints.empty()) { //throw tatum::Error("Output unconstrained"); std::cerr << "Warning: Timing graph " << node_id << " " << node_type << " has no incomming clock tags, and no output constraint. No required time will be calculated\n"; #if 1 //Debug trace-back //TODO: remove debug code! if(node_type == NodeType::FF_SINK) { std::cerr << "\tClock path:\n"; int i = 0; NodeId curr_node = node_id; while(tg.node_type(curr_node) != NodeType::INPAD_SOURCE && tg.node_type(curr_node) != NodeType::CLOCK_SOURCE && tg.node_type(curr_node) != NodeType::CONSTANT_GEN_SOURCE && i < 100) { //Look throught the fanin for a clock or other node to follow // //Typically the first hop from node_id will be to either the IPIN or CLOCK pin //the following preferentially prefers the CLOCK pin to show the clock path EdgeId best_edge; for(auto edge_id : tg.node_in_edges(curr_node)) { if(!best_edge) { best_edge = edge_id; } NodeId src_node = tg.edge_src_node(edge_id); auto src_node_type = tg.node_type(src_node); if(src_node_type == NodeType::FF_CLOCK) { best_edge = edge_id; } } //Step back curr_node = tg.edge_src_node(best_edge); auto curr_node_type = tg.node_type(curr_node); std::cerr << "\tNode " << curr_node << " Type: " << curr_node_type << "\n"; if(++i >= 100) { std::cerr << "\tStopping backtrace\n"; } } } #endif } else { for(auto constraint : output_constraints) { //TODO: use real constraint value when output delay no-longer on edges TimingTag constraint_tag = TimingTag(Time(0.), Time(NAN), constraint.second.domain, node_id); node_clock_tags.add_tag(constraint_tag); } } } //At this stage both FF and outpad sinks now have the relevant clock //tags and we can process them equivalently //Determine the required time at this sink // //We need to generate a required time for each clock domain for which there is a data //arrival time at this node, while considering all possible clocks that could drive //this node (i.e. take the most restrictive constraint accross all clock tags at this //node) for(TimingTag& node_data_tag : node_data_tags) { for(const TimingTag& node_clock_tag : node_clock_tags) { //Should we be analyzing paths between these two domains? if(tc.should_analyze(node_data_tag.clock_domain(), node_clock_tag.clock_domain())) { //We only set a required time if the source domain actually reaches this sink //domain. This is indicated by having a valid arrival time. if(node_data_tag.arr_time().valid()) { float clock_constraint = ops_.clock_constraint(tc, node_data_tag.clock_domain(), node_clock_tag.clock_domain()); //Update the required time. This will keep the most restrictive constraint. ops_.merge_req_tag(node_data_tag, node_clock_tag.arr_time() + Time(clock_constraint), node_data_tag); } } } } } /* * Arrival Time Operations */ template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, NodeId node_id) { //Do not propagate arrival tags through constant generators if(tc.node_is_constant_generator(node_id)) return; //Pull from upstream sources to current node for(EdgeId edge_id : tg.node_in_edges(node_id)) { do_arrival_traverse_edge(tg, dc, node_id, edge_id); } } template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) { //We must use the tags by reference so we don't accidentally wipe-out any //existing tags TimingTags& node_data_tags = ops_.get_data_tags(node_id); TimingTags& node_clock_tags = ops_.get_clock_tags(node_id); //Pulling values from upstream source node NodeId src_node_id = tg.edge_src_node(edge_id); const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id); const TimingTags& src_clk_tags = ops_.get_clock_tags(src_node_id); const TimingTags& src_data_tags = ops_.get_data_tags(src_node_id); /* * Clock tags */ if(src_data_tags.empty()) { //Propagate the clock tags through the clock network for(const TimingTag& src_clk_tag : src_clk_tags) { //Standard propagation through the clock network ops_.merge_arr_tags(node_clock_tags, src_clk_tag.arr_time() + edge_delay, src_clk_tag); if(is_clock_to_data_edge(tg, src_node_id, node_id)) { //We convert the clock arrival time to a data //arrival time at this node (since the clock //arrival launches the data). //Make a copy of the tag TimingTag launch_tag = src_clk_tag; //Update the launch node, since the data is //launching from this node launch_tag.set_launch_node(node_id); //Mark propagated launch time as a DATA tag ops_.merge_arr_tags(node_data_tags, launch_tag.arr_time() + edge_delay, launch_tag); } } } /* * Data tags */ for(const TimingTag& src_data_tag : src_data_tags) { //Standard data-path propagation ops_.merge_arr_tags(node_data_tags, src_data_tag.arr_time() + edge_delay, src_data_tag); } } /* * Required Time Operations */ template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id) { //Do not propagate required tags through constant generators if(tc.node_is_constant_generator(node_id)) return; //Pull from downstream sinks to current node for(EdgeId edge_id : tg.node_out_edges(node_id)) { do_required_traverse_edge(tg, dc, node_id, edge_id); } } template<class AnalysisOps> template<class DelayCalc> void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) { //We must use the tags by reference so we don't accidentally wipe-out any //existing tags TimingTags& node_data_tags = ops_.get_data_tags(node_id); //Pulling values from downstream sink node NodeId sink_node_id = tg.edge_sink_node(edge_id); const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id); const TimingTags& sink_data_tags = ops_.get_data_tags(sink_node_id); for(const TimingTag& sink_tag : sink_data_tags) { //We only propogate the required time if we have a valid arrival time auto matched_tag_iter = node_data_tags.find_tag_by_clock_domain(sink_tag.clock_domain()); if(matched_tag_iter != node_data_tags.end() && matched_tag_iter->arr_time().valid()) { //Valid arrival, update required ops_.merge_req_tag(*matched_tag_iter, sink_tag.req_time() - edge_delay, sink_tag); } } } template<class AnalysisOps> bool CommonAnalysisVisitor<AnalysisOps>::is_clock_to_data_edge(const TimingGraph& tg, const NodeId /*src_node_id*/, const NodeId node_id) const { if(tg.node_type(node_id) == NodeType::FF_SOURCE) return true; return false; } }} //namepsace #endif <|endoftext|>
<commit_before>/***************************************************************************//** * FILE : cmiss_set.hpp * * Template class derived from STL set which handles reference counting and * maintains connections between sets of related objects to safely and * efficiently manage changing the identifier i.e. sort key of the objects. */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #if !defined (CMISS_SET_HPP) #define CMISS_SET_HPP #include <set> /* Local types ----------- */ template<class Key, class Compare > class Cmiss_set : private std::set<Key,Compare> { private: typedef std::set<Key,Compare> Base_class; mutable Cmiss_set *next, *prev; // linked list of related sets Key temp_removed_object; // removed while changing identifier int access_count; Cmiss_set() : next(this), prev(this), temp_removed_object(0), access_count(1) { } /** copy constructor */ Cmiss_set(const Cmiss_set& source) : Base_class(source), next(source.next), prev(&source), temp_removed_object(0), access_count(1) { for (iterator iter = begin(); iter != end(); ++iter) { (*iter)->access(); } source.next = this; next->prev = this; } /** creates a set with the same manager, not a copy constructor */ Cmiss_set(const Cmiss_set *source) : Base_class(), next(source->next), prev(const_cast<Cmiss_set *>(source)), temp_removed_object(0), access_count(1) { source->next = this; next->prev = this; } public: ~Cmiss_set() { clear(); prev->next = next; next->prev = prev; } typedef typename Base_class::iterator iterator; typedef typename Base_class::const_iterator const_iterator; typedef typename Base_class::size_type size_type; static Cmiss_set *create_independent() { return new Cmiss_set(); } Cmiss_set *create_related() const { return new Cmiss_set(this); } Cmiss_set *create_copy() { return new Cmiss_set(*this); } Cmiss_set& operator=(const Cmiss_set& source) { if (&source == this) return *this; const Cmiss_set *related_set = this->next; while (related_set != this) { if (related_set == &source) { break; } related_set = related_set->next; } Base_class::operator=(source); if (related_set == this) { // copy from unrelated set: switch linked-lists this->next->prev = this->prev; this->prev->next = this->next; this->prev = const_cast<Cmiss_set *>(&source); this->next = source.next; source.next->prev = this; source.next = this; } return *this; } inline Cmiss_set *access() { ++access_count; return this; } static inline int deaccess(Cmiss_set **set_address) { if (set_address && *set_address) { if (0 >= (--(*set_address)->access_count)) { delete *set_address; } *set_address = 0; return 1; } return 0; } size_type erase(Key object) { size_type count = Base_class::erase(object); if (count) { object->deaccess(&object); } return count; } void erase(iterator iter) { Key object = *iter; Base_class::erase(iter); object->deaccess(&object); } std::pair<iterator,bool> insert(Key object) { std::pair<iterator,bool> result = Base_class::insert(object); if (result.second) object->access(); return result; } void clear() { for (iterator iter = begin(); iter != end(); ++iter) { Key tmp = *iter; tmp->deaccess(&tmp); } Base_class::clear(); } size_type size() const { return Base_class::size(); } const_iterator find(const Key &object) const { return Base_class::find(object); } iterator find(const Key &object) { return Base_class::find(object); } iterator begin() { return Base_class::begin(); } const_iterator begin() const { return Base_class::begin(); } iterator end() { return Base_class::end(); } const_iterator end() const { return Base_class::end(); } bool begin_identifier_change(Key object) { Cmiss_set *related_set = this; do { iterator iter = related_set->find(object); if (iter != related_set->end()) { related_set->temp_removed_object = (*iter)->access(); related_set->erase(iter); } else { related_set->temp_removed_object = 0; } related_set = related_set->next; } while (related_set != this); return true; } void end_identifier_change() { Cmiss_set *related_set = this; do { if (related_set->temp_removed_object) { related_set->insert(related_set->temp_removed_object); // check success? related_set->temp_removed_object->deaccess(&related_set->temp_removed_object); } related_set = related_set->next; } while (related_set != this); } /** * A specialised iterator class which wraps a reference to a container and an * iterator in it, suitable for use from external API because the container * cannot be destroyed before the iterator. */ struct ext_iterator { Cmiss_set *container; iterator iter; ext_iterator(Cmiss_set *container) : container(container->access()), iter(container->begin()) { } ~ext_iterator() { // the container may be destroyed immediately before the iterator; // hopefully not a problem container->deaccess(&container); } Key next() { if (iter != container->end()) { Key object = *iter; ++iter; return object->access(); } return 0; } Key next_non_access() { if (iter != container->end()) { Key object = *iter; ++iter; return object; } return 0; } }; }; #endif /* !defined (CMISS_SET_HPP) */ <commit_msg>Fixed Cmiss_set assignment operator to handle access_count. https://tracker.physiomeproject.org/show_bug.cgi?id=1451<commit_after>/***************************************************************************//** * FILE : cmiss_set.hpp * * Template class derived from STL set which handles reference counting and * maintains connections between sets of related objects to safely and * efficiently manage changing the identifier i.e. sort key of the objects. */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #if !defined (CMISS_SET_HPP) #define CMISS_SET_HPP #include <set> /* Local types ----------- */ template<class Key, class Compare > class Cmiss_set : private std::set<Key,Compare> { private: typedef std::set<Key,Compare> Base_class; mutable Cmiss_set *next, *prev; // linked list of related sets Key temp_removed_object; // removed while changing identifier int access_count; Cmiss_set() : next(this), prev(this), temp_removed_object(0), access_count(1) { } /** copy constructor */ Cmiss_set(const Cmiss_set& source) : Base_class(source), next(source.next), prev(&source), temp_removed_object(0), access_count(1) { for (iterator iter = begin(); iter != end(); ++iter) { (*iter)->access(); } source.next = this; next->prev = this; } /** creates a set with the same manager, not a copy constructor */ Cmiss_set(const Cmiss_set *source) : Base_class(), next(source->next), prev(const_cast<Cmiss_set *>(source)), temp_removed_object(0), access_count(1) { source->next = this; next->prev = this; } public: ~Cmiss_set() { clear(); prev->next = next; next->prev = prev; } typedef typename Base_class::iterator iterator; typedef typename Base_class::const_iterator const_iterator; typedef typename Base_class::size_type size_type; static Cmiss_set *create_independent() { return new Cmiss_set(); } Cmiss_set *create_related() const { return new Cmiss_set(this); } Cmiss_set *create_copy() { return new Cmiss_set(*this); } Cmiss_set& operator=(const Cmiss_set& source) { if (&source == this) return *this; const Cmiss_set *related_set = this->next; while (related_set != this) { if (related_set == &source) { break; } related_set = related_set->next; } for (iterator iter = begin(); iter != end(); ++iter) { Key object = *iter; object->deaccess(&object); } Base_class::operator=(source); for (iterator iter = begin(); iter != end(); ++iter) { (*iter)->access(); } if (related_set == this) { // copy from unrelated set: switch linked-lists this->next->prev = this->prev; this->prev->next = this->next; this->prev = const_cast<Cmiss_set *>(&source); this->next = source.next; source.next->prev = this; source.next = this; } return *this; } inline Cmiss_set *access() { ++access_count; return this; } static inline int deaccess(Cmiss_set **set_address) { if (set_address && *set_address) { if (0 >= (--(*set_address)->access_count)) { delete *set_address; } *set_address = 0; return 1; } return 0; } size_type erase(Key object) { size_type count = Base_class::erase(object); if (count) { object->deaccess(&object); } return count; } void erase(iterator iter) { Key object = *iter; Base_class::erase(iter); object->deaccess(&object); } std::pair<iterator,bool> insert(Key object) { std::pair<iterator,bool> result = Base_class::insert(object); if (result.second) object->access(); return result; } void clear() { for (iterator iter = begin(); iter != end(); ++iter) { Key tmp = *iter; tmp->deaccess(&tmp); } Base_class::clear(); } size_type size() const { return Base_class::size(); } const_iterator find(const Key &object) const { return Base_class::find(object); } iterator find(const Key &object) { return Base_class::find(object); } iterator begin() { return Base_class::begin(); } const_iterator begin() const { return Base_class::begin(); } iterator end() { return Base_class::end(); } const_iterator end() const { return Base_class::end(); } bool begin_identifier_change(Key object) { Cmiss_set *related_set = this; do { iterator iter = related_set->find(object); if (iter != related_set->end()) { related_set->temp_removed_object = (*iter)->access(); related_set->erase(iter); } else { related_set->temp_removed_object = 0; } related_set = related_set->next; } while (related_set != this); return true; } void end_identifier_change() { Cmiss_set *related_set = this; do { if (related_set->temp_removed_object) { related_set->insert(related_set->temp_removed_object); // check success? related_set->temp_removed_object->deaccess(&related_set->temp_removed_object); } related_set = related_set->next; } while (related_set != this); } /** * A specialised iterator class which wraps a reference to a container and an * iterator in it, suitable for use from external API because the container * cannot be destroyed before the iterator. */ struct ext_iterator { Cmiss_set *container; iterator iter; ext_iterator(Cmiss_set *container) : container(container->access()), iter(container->begin()) { } ~ext_iterator() { // the container may be destroyed immediately before the iterator; // hopefully not a problem container->deaccess(&container); } Key next() { if (iter != container->end()) { Key object = *iter; ++iter; return object->access(); } return 0; } Key next_non_access() { if (iter != container->end()) { Key object = *iter; ++iter; return object; } return 0; } }; }; #endif /* !defined (CMISS_SET_HPP) */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mythes.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-08-03 12:31:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include "license.readme" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "mythes.hxx" MyThes::MyThes(const char* idxpath, const char * datpath) { nw = 0; encoding = NULL; list = NULL; offst = NULL; if (thInitialize(idxpath, datpath) != 1) { fprintf(stderr,"Error - can't open %s or %s\n",idxpath, datpath); fflush(stderr); thCleanup(); // did not initialize properly - throw exception? } } MyThes::~MyThes() { thCleanup(); } int MyThes::thInitialize(const char* idxpath, const char* datpath) { // open the index file FILE * pifile = fopen(idxpath,"r"); if (!pifile) { return 0; } // parse in encoding and index size */ char * wrd; wrd = (char *)calloc(1, MAX_WD_LEN); if (!wrd) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } int len = readLine(pifile,wrd,MAX_WD_LEN); encoding = mystrdup(wrd); len = readLine(pifile,wrd,MAX_WD_LEN); int idxsz = atoi(wrd); // now allocate list, offst for the given size list = (char**) calloc(idxsz,sizeof(char*)); offst = (unsigned int*) calloc(idxsz,sizeof(unsigned int)); if ( (!(list)) || (!(offst)) ) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } // now parse the remaining lines of the index len = readLine(pifile,wrd,MAX_WD_LEN); while (len > 0) { int np = mystr_indexOfChar(wrd,'|'); if (nw < idxsz) { if (np >= 0) { *(wrd+np) = '\0'; list[nw] = (char *)calloc(1,(np+1)); if (!list[nw]) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } memcpy((list[nw]),wrd,np); offst[nw] = atoi(wrd+np+1); nw++; } } len = readLine(pifile,wrd,MAX_WD_LEN); } free((void *)wrd); fclose(pifile); /* next open the data file */ pdfile = fopen(datpath,"r"); if (!pdfile) { return 0; } return 1; } void MyThes::thCleanup() { /* first close the data file */ if (pdfile) { fclose(pdfile); pdfile=NULL; } if (list) { /* now free up all the allocated strings on the list */ for (int i=0; i < nw; i++) { if (list[i]) { free(list[i]); list[i] = 0; } } free((void*)list); } if (encoding) free((void*)encoding); if (offst) free((void*)offst); encoding = NULL; list = NULL; offst = NULL; nw = 0; } // lookup text in index and count of meanings and a list of meaning entries // with each entry having a synonym count and pointer to an // array of char * (i.e the synonyms) // // note: calling routine should call CleanUpAfterLookup with the original // meaning point and count to properly deallocate memory int MyThes::Lookup(const char * pText, int len, mentry** pme) { *pme = NULL; // handle the case of missing file or file related errors if (! pdfile) return 0; long offset = 0; /* copy search word and make sure null terminated */ char * wrd = (char *) calloc(1,(len+1)); memcpy(wrd,pText,len); /* find it in the list */ int idx = nw > 0 ? binsearch(wrd,list,nw) : -1; free(wrd); if (idx < 0) return 0; // now seek to the offset offset = (long) offst[idx]; int rc = fseek(pdfile,offset,SEEK_SET); if (rc) { return 0; } // grab the count of the number of meanings // and allocate a list of meaning entries char * buf = NULL; buf = (char *) malloc( MAX_LN_LEN ); if (!buf) return 0; readLine(pdfile, buf, (MAX_LN_LEN-1)); int np = mystr_indexOfChar(buf,'|'); if (np < 0) { free(buf); return 0; } int nmeanings = atoi(buf+np+1); *pme = (mentry*) malloc( nmeanings * sizeof(mentry) ); if (!(*pme)) { free(buf); return 0; } // now read in each meaning and parse it to get defn, count and synonym lists mentry* pm = *(pme); char dfn[MAX_WD_LEN]; for (int j = 0; j < nmeanings; j++) { readLine(pdfile, buf, (MAX_LN_LEN-1)); pm->count = 0; pm->psyns = NULL; pm->defn = NULL; // store away the part of speech for later use char * p = buf; char * pos = NULL; np = mystr_indexOfChar(p,'|'); if (np >= 0) { *(buf+np) = '\0'; pos = mystrdup(p); p = p + np + 1; } else { pos = mystrdup(""); } // count the number of fields in the remaining line int nf = 1; char * d = p; np = mystr_indexOfChar(d,'|'); while ( np >= 0 ) { nf++; d = d + np + 1; np = mystr_indexOfChar(d,'|'); } pm->count = nf; pm->psyns = (char **) malloc(nf*sizeof(char*)); // fill in the synonym list d = p; for (int jj = 0; jj < nf; jj++) { np = mystr_indexOfChar(d,'|'); if (np > 0) { *(d+np) = '\0'; pm->psyns[jj] = mystrdup(d); d = d + np + 1; } else { pm->psyns[jj] = mystrdup(d); } } // add pos to first synonym to create the definition int k = strlen(pos); int m = strlen(pm->psyns[0]); if ((k+m) < (MAX_WD_LEN - 1)) { strncpy(dfn,pos,k); *(dfn+k) = ' '; strncpy((dfn+k+1),(pm->psyns[0]),m+1); pm->defn = mystrdup(dfn); } else { pm->defn = mystrdup(pm->psyns[0]); } free(pos); pm++; } free(buf); return nmeanings; } void MyThes::CleanUpAfterLookup(mentry ** pme, int nmeanings) { if (nmeanings == 0) return; if ((*pme) == NULL) return; mentry * pm = *pme; for (int i = 0; i < nmeanings; i++) { int count = pm->count; for (int j = 0; j < count; j++) { if (pm->psyns[j]) free(pm->psyns[j]); pm->psyns[j] = NULL; } if (pm->psyns) free(pm->psyns); pm->psyns = NULL; if (pm->defn) free(pm->defn); pm->defn = NULL; pm->count = 0; pm++; } pm = *pme; free(pm); *pme = NULL; return; } // read a line of text from a text file stripping // off the line terminator and replacing it with // a null string terminator. // returns: -1 on error or the number of characters in // in the returning string // A maximum of nc characters will be returned int MyThes::readLine(FILE * pf, char * buf, int nc) { if (fgets(buf,nc,pf)) { mychomp(buf); return strlen(buf); } return -1; } // performs a binary search on null terminated character // strings // // returns: -1 on not found // index of wrd in the list[] int MyThes::binsearch(char * sw, char* _list[], int nlst) { int lp, up, mp, j, indx; lp = 0; up = nlst-1; indx = -1; if (strcmp(sw,_list[lp]) < 0) return -1; if (strcmp(sw,_list[up]) > 0) return -1; while (indx < 0 ) { mp = (int)((lp+up) >> 1); j = strcmp(sw,_list[mp]); if ( j > 0) { lp = mp + 1; } else if (j < 0 ) { up = mp - 1; } else { indx = mp; } if (lp > up) return -1; } return indx; } char * MyThes::get_th_encoding() { if (encoding) return encoding; return NULL; } // string duplication routine char * MyThes::mystrdup(const char * p) { int sl = strlen(p) + 1; char * d = (char *)malloc(sl); if (d) { memcpy(d,p,sl); return d; } return NULL; } // remove cross-platform text line end characters void MyThes::mychomp(char * s) { int k = strlen(s); if ((k > 0) && ((*(s+k-1)=='\r') || (*(s+k-1)=='\n'))) *(s+k-1) = '\0'; if ((k > 1) && (*(s+k-2) == '\r')) *(s+k-2) = '\0'; } // return index of char in string int MyThes::mystr_indexOfChar(const char * d, int c) { char * p = strchr((char *)d,c); if (p) return (int)(p-d); return -1; } <commit_msg>INTEGRATION: CWS changefileheader (1.8.56); FILE MERGED 2008/03/31 16:25:06 rt 1.8.56.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mythes.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include "license.readme" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "mythes.hxx" MyThes::MyThes(const char* idxpath, const char * datpath) { nw = 0; encoding = NULL; list = NULL; offst = NULL; if (thInitialize(idxpath, datpath) != 1) { fprintf(stderr,"Error - can't open %s or %s\n",idxpath, datpath); fflush(stderr); thCleanup(); // did not initialize properly - throw exception? } } MyThes::~MyThes() { thCleanup(); } int MyThes::thInitialize(const char* idxpath, const char* datpath) { // open the index file FILE * pifile = fopen(idxpath,"r"); if (!pifile) { return 0; } // parse in encoding and index size */ char * wrd; wrd = (char *)calloc(1, MAX_WD_LEN); if (!wrd) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } int len = readLine(pifile,wrd,MAX_WD_LEN); encoding = mystrdup(wrd); len = readLine(pifile,wrd,MAX_WD_LEN); int idxsz = atoi(wrd); // now allocate list, offst for the given size list = (char**) calloc(idxsz,sizeof(char*)); offst = (unsigned int*) calloc(idxsz,sizeof(unsigned int)); if ( (!(list)) || (!(offst)) ) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } // now parse the remaining lines of the index len = readLine(pifile,wrd,MAX_WD_LEN); while (len > 0) { int np = mystr_indexOfChar(wrd,'|'); if (nw < idxsz) { if (np >= 0) { *(wrd+np) = '\0'; list[nw] = (char *)calloc(1,(np+1)); if (!list[nw]) { fprintf(stderr,"Error - bad memory allocation\n"); fflush(stderr); fclose(pifile); return 0; } memcpy((list[nw]),wrd,np); offst[nw] = atoi(wrd+np+1); nw++; } } len = readLine(pifile,wrd,MAX_WD_LEN); } free((void *)wrd); fclose(pifile); /* next open the data file */ pdfile = fopen(datpath,"r"); if (!pdfile) { return 0; } return 1; } void MyThes::thCleanup() { /* first close the data file */ if (pdfile) { fclose(pdfile); pdfile=NULL; } if (list) { /* now free up all the allocated strings on the list */ for (int i=0; i < nw; i++) { if (list[i]) { free(list[i]); list[i] = 0; } } free((void*)list); } if (encoding) free((void*)encoding); if (offst) free((void*)offst); encoding = NULL; list = NULL; offst = NULL; nw = 0; } // lookup text in index and count of meanings and a list of meaning entries // with each entry having a synonym count and pointer to an // array of char * (i.e the synonyms) // // note: calling routine should call CleanUpAfterLookup with the original // meaning point and count to properly deallocate memory int MyThes::Lookup(const char * pText, int len, mentry** pme) { *pme = NULL; // handle the case of missing file or file related errors if (! pdfile) return 0; long offset = 0; /* copy search word and make sure null terminated */ char * wrd = (char *) calloc(1,(len+1)); memcpy(wrd,pText,len); /* find it in the list */ int idx = nw > 0 ? binsearch(wrd,list,nw) : -1; free(wrd); if (idx < 0) return 0; // now seek to the offset offset = (long) offst[idx]; int rc = fseek(pdfile,offset,SEEK_SET); if (rc) { return 0; } // grab the count of the number of meanings // and allocate a list of meaning entries char * buf = NULL; buf = (char *) malloc( MAX_LN_LEN ); if (!buf) return 0; readLine(pdfile, buf, (MAX_LN_LEN-1)); int np = mystr_indexOfChar(buf,'|'); if (np < 0) { free(buf); return 0; } int nmeanings = atoi(buf+np+1); *pme = (mentry*) malloc( nmeanings * sizeof(mentry) ); if (!(*pme)) { free(buf); return 0; } // now read in each meaning and parse it to get defn, count and synonym lists mentry* pm = *(pme); char dfn[MAX_WD_LEN]; for (int j = 0; j < nmeanings; j++) { readLine(pdfile, buf, (MAX_LN_LEN-1)); pm->count = 0; pm->psyns = NULL; pm->defn = NULL; // store away the part of speech for later use char * p = buf; char * pos = NULL; np = mystr_indexOfChar(p,'|'); if (np >= 0) { *(buf+np) = '\0'; pos = mystrdup(p); p = p + np + 1; } else { pos = mystrdup(""); } // count the number of fields in the remaining line int nf = 1; char * d = p; np = mystr_indexOfChar(d,'|'); while ( np >= 0 ) { nf++; d = d + np + 1; np = mystr_indexOfChar(d,'|'); } pm->count = nf; pm->psyns = (char **) malloc(nf*sizeof(char*)); // fill in the synonym list d = p; for (int jj = 0; jj < nf; jj++) { np = mystr_indexOfChar(d,'|'); if (np > 0) { *(d+np) = '\0'; pm->psyns[jj] = mystrdup(d); d = d + np + 1; } else { pm->psyns[jj] = mystrdup(d); } } // add pos to first synonym to create the definition int k = strlen(pos); int m = strlen(pm->psyns[0]); if ((k+m) < (MAX_WD_LEN - 1)) { strncpy(dfn,pos,k); *(dfn+k) = ' '; strncpy((dfn+k+1),(pm->psyns[0]),m+1); pm->defn = mystrdup(dfn); } else { pm->defn = mystrdup(pm->psyns[0]); } free(pos); pm++; } free(buf); return nmeanings; } void MyThes::CleanUpAfterLookup(mentry ** pme, int nmeanings) { if (nmeanings == 0) return; if ((*pme) == NULL) return; mentry * pm = *pme; for (int i = 0; i < nmeanings; i++) { int count = pm->count; for (int j = 0; j < count; j++) { if (pm->psyns[j]) free(pm->psyns[j]); pm->psyns[j] = NULL; } if (pm->psyns) free(pm->psyns); pm->psyns = NULL; if (pm->defn) free(pm->defn); pm->defn = NULL; pm->count = 0; pm++; } pm = *pme; free(pm); *pme = NULL; return; } // read a line of text from a text file stripping // off the line terminator and replacing it with // a null string terminator. // returns: -1 on error or the number of characters in // in the returning string // A maximum of nc characters will be returned int MyThes::readLine(FILE * pf, char * buf, int nc) { if (fgets(buf,nc,pf)) { mychomp(buf); return strlen(buf); } return -1; } // performs a binary search on null terminated character // strings // // returns: -1 on not found // index of wrd in the list[] int MyThes::binsearch(char * sw, char* _list[], int nlst) { int lp, up, mp, j, indx; lp = 0; up = nlst-1; indx = -1; if (strcmp(sw,_list[lp]) < 0) return -1; if (strcmp(sw,_list[up]) > 0) return -1; while (indx < 0 ) { mp = (int)((lp+up) >> 1); j = strcmp(sw,_list[mp]); if ( j > 0) { lp = mp + 1; } else if (j < 0 ) { up = mp - 1; } else { indx = mp; } if (lp > up) return -1; } return indx; } char * MyThes::get_th_encoding() { if (encoding) return encoding; return NULL; } // string duplication routine char * MyThes::mystrdup(const char * p) { int sl = strlen(p) + 1; char * d = (char *)malloc(sl); if (d) { memcpy(d,p,sl); return d; } return NULL; } // remove cross-platform text line end characters void MyThes::mychomp(char * s) { int k = strlen(s); if ((k > 0) && ((*(s+k-1)=='\r') || (*(s+k-1)=='\n'))) *(s+k-1) = '\0'; if ((k > 1) && (*(s+k-2) == '\r')) *(s+k-2) = '\0'; } // return index of char in string int MyThes::mystr_indexOfChar(const char * d, int c) { char * p = strchr((char *)d,c); if (p) return (int)(p-d); return -1; } <|endoftext|>
<commit_before>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; size_t n = 100; auto int_ready = agency::detail::make_ready_future(0); auto void_ready = agency::detail::make_ready_future(); auto vector_ready = agency::detail::make_ready_future(std::vector<int>(n)); auto futures = std::make_tuple(std::move(int_ready), std::move(void_ready), std::move(vector_ready)); std::mutex mut; executor_type exec; std::future<agency::detail::tuple<std::vector<int>,int>> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<2,0>(exec, [&mut](size_t idx, int& x, std::vector<int>& vec) { mut.lock(); x += 1; mut.unlock(); vec[idx] = 13; }, n, std::move(futures)); auto got = fut.get(); assert(std::get<0>(got) == std::vector<int>(n, 13)); assert(std::get<1>(got) == n); assert(exec.valid()); } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_with_shared_inits_executor>(); test<when_all_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); test<multi_agent_async_execute_returning_void_executor>(); test<multi_agent_execute_with_shared_inits_returning_user_defined_container_executor>(); std::cout << "OK" << std::endl; return 0; } <commit_msg>Test multi_agent_execute_with_shared_inits_returning_default_container_executor with test_multi_agent_when_all_execute_and_select.cpp.<commit_after>#include <agency/future.hpp> #include <agency/new_executor_traits.hpp> #include <iostream> #include <cassert> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; size_t n = 100; auto int_ready = agency::detail::make_ready_future(0); auto void_ready = agency::detail::make_ready_future(); auto vector_ready = agency::detail::make_ready_future(std::vector<int>(n)); auto futures = std::make_tuple(std::move(int_ready), std::move(void_ready), std::move(vector_ready)); std::mutex mut; executor_type exec; std::future<agency::detail::tuple<std::vector<int>,int>> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<2,0>(exec, [&mut](size_t idx, int& x, std::vector<int>& vec) { mut.lock(); x += 1; mut.unlock(); vec[idx] = 13; }, n, std::move(futures)); auto got = fut.get(); assert(std::get<0>(got) == std::vector<int>(n, 13)); assert(std::get<1>(got) == n); assert(exec.valid()); } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_with_shared_inits_executor>(); test<when_all_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); test<multi_agent_async_execute_returning_default_container_executor>(); test<multi_agent_async_execute_returning_void_executor>(); test<multi_agent_execute_with_shared_inits_returning_user_defined_container_executor>(); test<multi_agent_execute_with_shared_inits_returning_default_container_executor>(); std::cout << "OK" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp> #include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp> #include <xercesc/util/Base64.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(MemoryManager* const manager) :AbstractStringValidator(0, 0, 0, DatatypeValidator::Base64Binary, manager) {} Base64BinaryDatatypeValidator::~Base64BinaryDatatypeValidator() {} Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager) :AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::Base64Binary, manager) { init(enums, manager); } DatatypeValidator* Base64BinaryDatatypeValidator::newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager ) { return (DatatypeValidator*) new (manager) Base64BinaryDatatypeValidator(this, facets, enums, finalSet, manager); } // --------------------------------------------------------------------------- // Utilities // --------------------------------------------------------------------------- void Base64BinaryDatatypeValidator::checkValueSpace(const XMLCh* const content , MemoryManager* const manager) { if (getLength(content, manager) < 0) { ThrowXMLwithMemMgr1(InvalidDatatypeValueException , XMLExcepts::VALUE_Not_Base64 , content , manager); } } int Base64BinaryDatatypeValidator::getLength(const XMLCh* const content , MemoryManager* const manager) const { return Base64::getDataLength(content, manager, Base64::Conf_Schema); } void Base64BinaryDatatypeValidator::normalizeEnumeration(MemoryManager* const manager) { int enumLength = getEnumeration()->size(); for ( int i=0; i < enumLength; i++) { XMLString::removeWS(getEnumeration()->elementAt(i), manager); } } void Base64BinaryDatatypeValidator::normalizeContent(XMLCh* const content , MemoryManager* const manager) const { XMLString::removeWS(content, manager); } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(Base64BinaryDatatypeValidator) void Base64BinaryDatatypeValidator::serialize(XSerializeEngine& serEng) { AbstractStringValidator::serialize(serEng); } XERCES_CPP_NAMESPACE_END /** * End of file Base64BinaryDatatypeValidator.cpp */ <commit_msg>Empty content for Base64Binary should be allowed.<commit_after>/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp> #include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp> #include <xercesc/util/Base64.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(MemoryManager* const manager) :AbstractStringValidator(0, 0, 0, DatatypeValidator::Base64Binary, manager) {} Base64BinaryDatatypeValidator::~Base64BinaryDatatypeValidator() {} Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager) :AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::Base64Binary, manager) { init(enums, manager); } DatatypeValidator* Base64BinaryDatatypeValidator::newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager ) { return (DatatypeValidator*) new (manager) Base64BinaryDatatypeValidator(this, facets, enums, finalSet, manager); } // --------------------------------------------------------------------------- // Utilities // --------------------------------------------------------------------------- void Base64BinaryDatatypeValidator::checkValueSpace(const XMLCh* const content , MemoryManager* const manager) { if (!content || !*content) return; if (getLength(content, manager) < 0) { ThrowXMLwithMemMgr1(InvalidDatatypeValueException , XMLExcepts::VALUE_Not_Base64 , content , manager); } } int Base64BinaryDatatypeValidator::getLength(const XMLCh* const content , MemoryManager* const manager) const { if (!content || !*content) return 0; return Base64::getDataLength(content, manager, Base64::Conf_Schema); } void Base64BinaryDatatypeValidator::normalizeEnumeration(MemoryManager* const manager) { int enumLength = getEnumeration()->size(); for ( int i=0; i < enumLength; i++) { XMLString::removeWS(getEnumeration()->elementAt(i), manager); } } void Base64BinaryDatatypeValidator::normalizeContent(XMLCh* const content , MemoryManager* const manager) const { XMLString::removeWS(content, manager); } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(Base64BinaryDatatypeValidator) void Base64BinaryDatatypeValidator::serialize(XSerializeEngine& serEng) { AbstractStringValidator::serialize(serEng); } XERCES_CPP_NAMESPACE_END /** * End of file Base64BinaryDatatypeValidator.cpp */ <|endoftext|>
<commit_before>#include "autocompletebasictest.h" #include <QUrl> #include <QFileInfo> #include <QStringList> #include "integrationtestbase.h" #include "signalwaiter.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "../../xpiks-qt/Models/artitemsmodel.h" #include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h" #include "../../xpiks-qt/Models/artworkmetadata.h" #include "../../xpiks-qt/Models/settingsmodel.h" #include "../../xpiks-qt/AutoComplete/autocompleteservice.h" #include "../../xpiks-qt/AutoComplete/autocompletemodel.h" QString AutoCompleteBasicTest::testName() { return QLatin1String("AutoCompleteBasicTest"); } void AutoCompleteBasicTest::setup() { Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel(); settingsModel->setUseAutoComplete(true); } int AutoCompleteBasicTest::doTest() { Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel(); QList<QUrl> files; files << QUrl::fromLocalFile(QFileInfo("images-for-tests/vector/026.jpg").absoluteFilePath()); int addedCount = artItemsModel->addLocalArtworks(files); VERIFY(addedCount == files.length(), "Failed to add file"); MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator(); SignalWaiter waiter; QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished())); ioCoordinator->continueReading(true); if (!waiter.wait(20)) { VERIFY(false, "Timeout exceeded for reading metadata."); } VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading"); Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0); SignalWaiter completionWaiter; QObject::connect(metadata, SIGNAL(completionsAvailable()), &completionWaiter, SIGNAL(finished())); AutoComplete::AutoCompleteService *acService = m_CommandManager->getAutoCompleteService(); AutoComplete::AutoCompleteModel *acModel = acService->getAutoCompleteModel(); VERIFY(acModel->getCount() == 0, "AC model was not empty"); m_CommandManager->autoCompleteKeyword("tes", metadata); if (!completionWaiter.wait(10)) { VERIFY(false, "Timeout while waiting for the completion"); } VERIFY(acModel->getCount() > 0, "AC model didn't receive the completions"); VERIFY(acModel->containsWord("test"), "AC model has irrelevant results"); return 0; } <commit_msg>Fixes for connections of signals<commit_after>#include "autocompletebasictest.h" #include <QUrl> #include <QFileInfo> #include <QStringList> #include "integrationtestbase.h" #include "signalwaiter.h" #include "../../xpiks-qt/Commands/commandmanager.h" #include "../../xpiks-qt/Models/artitemsmodel.h" #include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h" #include "../../xpiks-qt/Models/artworkmetadata.h" #include "../../xpiks-qt/Models/settingsmodel.h" #include "../../xpiks-qt/AutoComplete/autocompleteservice.h" #include "../../xpiks-qt/AutoComplete/autocompletemodel.h" QString AutoCompleteBasicTest::testName() { return QLatin1String("AutoCompleteBasicTest"); } void AutoCompleteBasicTest::setup() { Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel(); settingsModel->setUseAutoComplete(true); } int AutoCompleteBasicTest::doTest() { Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel(); QList<QUrl> files; files << QUrl::fromLocalFile(QFileInfo("images-for-tests/vector/026.jpg").absoluteFilePath()); int addedCount = artItemsModel->addLocalArtworks(files); VERIFY(addedCount == files.length(), "Failed to add file"); MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator(); SignalWaiter waiter; QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished())); ioCoordinator->continueReading(true); if (!waiter.wait(20)) { VERIFY(false, "Timeout exceeded for reading metadata."); } VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading"); Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0); SignalWaiter completionWaiter; QObject::connect(metadata->getKeywordsModel(), SIGNAL(completionsAvailable()), &completionWaiter, SIGNAL(finished())); AutoComplete::AutoCompleteService *acService = m_CommandManager->getAutoCompleteService(); AutoComplete::AutoCompleteModel *acModel = acService->getAutoCompleteModel(); VERIFY(acModel->getCount() == 0, "AC model was not empty"); m_CommandManager->autoCompleteKeyword("tes", metadata); if (!completionWaiter.wait(10)) { VERIFY(false, "Timeout while waiting for the completion"); } VERIFY(acModel->getCount() > 0, "AC model didn't receive the completions"); VERIFY(acModel->containsWord("test"), "AC model has irrelevant results"); return 0; } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_state_handler.h" #include <vespa/vespalib/data/slime/slime.h> namespace vespalib { namespace { vespalib::string url_escape(const vespalib::string &item) { return item; } class Url { private: vespalib::string _url; void append(const vespalib::string &item) { if (*_url.rbegin() != '/') { _url.append('/'); } _url.append(url_escape(item)); } public: Url(const vespalib::string &host, const std::vector<vespalib::string> &items) : _url("http://") { _url.append(host); _url.append('/'); for (const auto &item: items) { append(item); } } Url(const Url &parent, const vespalib::string &item) : _url(parent._url) { append(item); } const vespalib::string &get() const { return _url; } }; std::vector<vespalib::string> split_path(const vespalib::string &path) { vespalib::string tmp; std::vector<vespalib::string> items; for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) { if (path[i] == '/') { if (!tmp.empty()) { items.push_back(tmp); tmp.clear(); } } else { tmp.push_back(path[i]); } } if (!tmp.empty()) { items.push_back(tmp); } return items; } bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) { if (root.size() > full.size()) { return false; } for (size_t i = 0; i < root.size(); ++i) { if (root[i] != full[i]) { return false; } } return true; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self); Slime child_state(const StateExplorer &state, const Url &url) { Slime child_state; state.get_state(slime::SlimeInserter(child_state), false); if (child_state.get().type().getId() == slime::NIX::ID) { inject_children(state, url, child_state.setObject()); } else { child_state.get().setString("url", url.get()); } return child_state; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self) { std::vector<vespalib::string> children_names = state.get_children_names(); for (const vespalib::string &child_name: children_names) { std::unique_ptr<StateExplorer> child = state.get_child(child_name); if (child) { Slime fragment = child_state(*child, Url(url, child_name)); slime::inject(fragment.get(), slime::ObjectInserter(self, child_name)); } } } vespalib::string render(const StateExplorer &state, const Url &url) { Slime top; state.get_state(slime::SlimeInserter(top), true); if (top.get().type().getId() == slime::NIX::ID) { top.setObject(); } inject_children(state, url, top.get()); slime::SimpleBuffer buf; slime::JsonFormat::encode(top, buf, true); return buf.get().make_string(); } vespalib::string explore(const StateExplorer &state, const vespalib::string &host, const std::vector<vespalib::string> &items, size_t pos) { if (pos == items.size()) { return render(state, Url(host, items)); } std::unique_ptr<StateExplorer> child = state.get_child(items[pos]); if (!child) { return ""; } return explore(*child, host, items, pos + 1); } } // namespace vespalib::<unnamed> GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state) : _root(split_path(root_path)), _state(state) { } vespalib::string GenericStateHandler::get(const vespalib::string &host, const vespalib::string &path, const std::map<vespalib::string,vespalib::string> &) const { std::vector<vespalib::string> items = split_path(path); if (!is_prefix(_root, items)) { return ""; } return explore(_state, host, items, _root.size()); } } // namespace vespalib <commit_msg>actually escape URL components<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_state_handler.h" #include <vespa/vespalib/data/slime/slime.h> namespace vespalib { namespace { // escape a path component in the URL // (needed to avoid java.net.URI throwing an exception) vespalib::string url_escape(const vespalib::string &item) { static const char hexdigits[] = "0123456789ABCDEF"; vespalib::string r; r.reserve(item.size()); for (const char c : item) { if ( ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || (c == '_') || (c == '-')) { r.append(c); } else { r.append('%'); r.append(hexdigits[0xF & (c >> 4)]); r.append(hexdigits[0xF & c]); } } return r; } class Url { private: vespalib::string _url; void append(const vespalib::string &item) { if (*_url.rbegin() != '/') { _url.append('/'); } _url.append(url_escape(item)); } public: Url(const vespalib::string &host, const std::vector<vespalib::string> &items) : _url("http://") { _url.append(host); _url.append('/'); for (const auto &item: items) { append(item); } } Url(const Url &parent, const vespalib::string &item) : _url(parent._url) { append(item); } const vespalib::string &get() const { return _url; } }; std::vector<vespalib::string> split_path(const vespalib::string &path) { vespalib::string tmp; std::vector<vespalib::string> items; for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) { if (path[i] == '/') { if (!tmp.empty()) { items.push_back(tmp); tmp.clear(); } } else { tmp.push_back(path[i]); } } if (!tmp.empty()) { items.push_back(tmp); } return items; } bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) { if (root.size() > full.size()) { return false; } for (size_t i = 0; i < root.size(); ++i) { if (root[i] != full[i]) { return false; } } return true; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self); Slime child_state(const StateExplorer &state, const Url &url) { Slime child_state; state.get_state(slime::SlimeInserter(child_state), false); if (child_state.get().type().getId() == slime::NIX::ID) { inject_children(state, url, child_state.setObject()); } else { child_state.get().setString("url", url.get()); } return child_state; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self) { std::vector<vespalib::string> children_names = state.get_children_names(); for (const vespalib::string &child_name: children_names) { std::unique_ptr<StateExplorer> child = state.get_child(child_name); if (child) { Slime fragment = child_state(*child, Url(url, child_name)); slime::inject(fragment.get(), slime::ObjectInserter(self, child_name)); } } } vespalib::string render(const StateExplorer &state, const Url &url) { Slime top; state.get_state(slime::SlimeInserter(top), true); if (top.get().type().getId() == slime::NIX::ID) { top.setObject(); } inject_children(state, url, top.get()); slime::SimpleBuffer buf; slime::JsonFormat::encode(top, buf, true); return buf.get().make_string(); } vespalib::string explore(const StateExplorer &state, const vespalib::string &host, const std::vector<vespalib::string> &items, size_t pos) { if (pos == items.size()) { return render(state, Url(host, items)); } std::unique_ptr<StateExplorer> child = state.get_child(items[pos]); if (!child) { return ""; } return explore(*child, host, items, pos + 1); } } // namespace vespalib::<unnamed> GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state) : _root(split_path(root_path)), _state(state) { } vespalib::string GenericStateHandler::get(const vespalib::string &host, const vespalib::string &path, const std::map<vespalib::string,vespalib::string> &) const { std::vector<vespalib::string> items = split_path(path); if (!is_prefix(_root, items)) { return ""; } return explore(_state, host, items, _root.size()); } } // namespace vespalib <|endoftext|>
<commit_before>/* $Id$ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "support/EtchQueuedPool.h" #include "capu/os/Thread.h" #include "capu/util/ThreadPool.h" #include "capu/os/Memory.h" #include "capu/util/Runnable.h" class EtchQueuedPoolRunnable : public capu::Runnable { public: /** * Create a new instance of EtchFreePoolRunnable class. */ EtchQueuedPoolRunnable(EtchQueuedPool* pool, capu::SmartPointer<EtchPoolRunnable> runnable) : mPool(pool), mRunnable(runnable) { } /** * Destructor */ virtual ~EtchQueuedPoolRunnable() { } /** * Runnable */ void run() { if(mRunnable.get() != NULL) { if(ETCH_OK != mRunnable->run()) { //TODO: Log exception if(mRunnable->hasException()) { capu::SmartPointer<EtchException> exception; mRunnable->getException(&exception); mRunnable->exception(exception); } } } } private: EtchQueuedPool* mPool; capu::SmartPointer<EtchPoolRunnable> mRunnable; }; const EtchObjectType* EtchQueuedPool::TYPE() { const static EtchObjectType TYPE(EOTID_QUEUEDPOOL, NULL); return &TYPE; } EtchQueuedPool::EtchQueuedPool(capu::int32_t size) : mSizeMax(size), mIsOpen(true) { addObjectType(TYPE()); mPool = new capu::ThreadPool(1); } EtchQueuedPool::~EtchQueuedPool() { delete mPool; } status_t EtchQueuedPool::close() { mIsOpen = false; return ETCH_OK; } status_t EtchQueuedPool::join() { mPool->join(); return ETCH_OK; } status_t EtchQueuedPool::add(capu::SmartPointer<EtchPoolRunnable> runnable) { if(!mIsOpen) { return ETCH_EINVAL; } EtchQueuedPoolRunnable* pr = new EtchQueuedPoolRunnable(this, runnable); //TODO: check max Size before adding a new Runnable capu::status_t status = mPool->add(pr); if(status != capu::CAPU_OK) { return ETCH_ERROR; } return ETCH_OK; } <commit_msg>ETCH-244 Fixing QueuedPool todo<commit_after>/* $Id$ * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "support/EtchQueuedPool.h" #include "capu/os/Thread.h" #include "capu/util/ThreadPool.h" #include "capu/os/Memory.h" #include "capu/util/Runnable.h" class EtchQueuedPoolRunnable : public capu::Runnable { public: /** * Create a new instance of EtchFreePoolRunnable class. */ EtchQueuedPoolRunnable(EtchQueuedPool* pool, capu::SmartPointer<EtchPoolRunnable> runnable) : mPool(pool), mRunnable(runnable) { } /** * Destructor */ virtual ~EtchQueuedPoolRunnable() { } /** * Runnable */ void run() { if(mRunnable.get() != NULL) { if(ETCH_OK != mRunnable->run()) { //TODO: Log exception if(mRunnable->hasException()) { capu::SmartPointer<EtchException> exception; mRunnable->getException(&exception); mRunnable->exception(exception); } } } } private: EtchQueuedPool* mPool; capu::SmartPointer<EtchPoolRunnable> mRunnable; }; const EtchObjectType* EtchQueuedPool::TYPE() { const static EtchObjectType TYPE(EOTID_QUEUEDPOOL, NULL); return &TYPE; } EtchQueuedPool::EtchQueuedPool(capu::int32_t size) : mSizeMax(size), mIsOpen(true) { addObjectType(TYPE()); mPool = new capu::ThreadPool(1); } EtchQueuedPool::~EtchQueuedPool() { delete mPool; } status_t EtchQueuedPool::close() { mIsOpen = false; return ETCH_OK; } status_t EtchQueuedPool::join() { mPool->join(); return ETCH_OK; } status_t EtchQueuedPool::add(capu::SmartPointer<EtchPoolRunnable> runnable) { if(!mIsOpen) { return ETCH_EINVAL; } if(mPool->getSize() + 1 > mSizeMax) return ETCH_ENOT_SUPPORTED; EtchQueuedPoolRunnable* pr = new EtchQueuedPoolRunnable(this, runnable); capu::status_t status = mPool->add(pr); if(status != capu::CAPU_OK) { return ETCH_ERROR; } return ETCH_OK; } <|endoftext|>
<commit_before>#pragma once #include <map> #include <typeinfo> #include "../Scene/Scene.hpp" namespace Component { class SuperComponent; } /// %Entity containing various components. class Entity { public: /// Create new entity. /** * @param scene The scene in which the entity is contained. */ Entity(Scene* scene); /// Destructor. ~Entity(); /// Adds component with type T. /** * @return The created component. */ template<typename T> T* AddComponent(); private: Scene* scene; std::map<const std::type_info*, Component::SuperComponent*> components; }; template <typename T> T* Entity::AddComponent() { const std::type_info* componentType = &typeid(T*); if (components.find(componentType) != components.end()) return nullptr; T* component = new T(this); components[componentType] = component; scene->AddComponent(component, componentType); return component; } <commit_msg>Method to get an entity's component.<commit_after>#pragma once #include <map> #include <typeinfo> #include "../Scene/Scene.hpp" namespace Component { class SuperComponent; } /// %Entity containing various components. class Entity { public: /// Create new entity. /** * @param scene The scene in which the entity is contained. */ Entity(Scene* scene); /// Destructor. ~Entity(); /// Adds component with type T. /** * @return The created component. */ template<typename T> T* AddComponent(); /// Gets component with type T. /** * @return The requested component (or nullptr). */ template<typename T> T* GetComponent(); private: Scene* scene; std::map<const std::type_info*, Component::SuperComponent*> components; }; template<typename T> T* Entity::AddComponent() { const std::type_info* componentType = &typeid(T*); if (components.find(componentType) != components.end()) return nullptr; T* component = new T(this); components[componentType] = component; scene->AddComponent(component, componentType); return component; } template<typename T> T* Entity::GetComponent() { if (components.count(&typeid(T*)) != 0) { return static_cast<T*>(components[&typeid(T*)]); } else { return nullptr; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:38:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_stoc.hxx" #include "UriSchemeParser_vndDOTsunDOTstarDOTscript.hxx" #include "UriReference.hxx" #include "supportsService.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uri/XUriReference.hpp" #include "com/sun/star/uri/XUriSchemeParser.hpp" #include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp" #include "cppuhelper/implbase1.hxx" #include "cppuhelper/implbase2.hxx" #include "cppuhelper/weak.hxx" #include "osl/mutex.hxx" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" #include "sal/types.h" #include <new> namespace css = com::sun::star; namespace { int getHexWeight(sal_Unicode c) { return c >= '0' && c <= '9' ? static_cast< int >(c - '0') : c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10) : c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10) : -1; } int parseEscaped(rtl::OUString const & part, sal_Int32 * index) { if (part.getLength() - *index < 3 || part[*index] != '%') { return -1; } int n1 = getHexWeight(part[*index + 1]); int n2 = getHexWeight(part[*index + 2]); if (n1 < 0 || n2 < 0) { return -1; } *index += 3; return (n1 << 4) | n2; } rtl::OUString parsePart( rtl::OUString const & part, bool namePart, sal_Int32 * index) { rtl::OUStringBuffer buf; while (*index < part.getLength()) { sal_Unicode c = part[*index]; if (namePart ? c == '?' : c == '&' || c == '=') { break; } else if (c == '%') { sal_Int32 i = *index; int n = parseEscaped(part, &i); if (n >= 0 && n <= 0x7F) { buf.append(static_cast< sal_Unicode >(n)); } else if (n >= 0xC0 && n <= 0xFC) { sal_Int32 encoded; int shift; sal_Int32 min; if (n <= 0xDF) { encoded = (n & 0x1F) << 6; shift = 0; min = 0x80; } else if (n <= 0xEF) { encoded = (n & 0x0F) << 12; shift = 6; min = 0x800; } else if (n <= 0xF7) { encoded = (n & 0x07) << 18; shift = 12; min = 0x10000; } else if (n <= 0xFB) { encoded = (n & 0x03) << 24; shift = 18; min = 0x200000; } else { encoded = 0; shift = 24; min = 0x4000000; } bool utf8 = true; for (; shift >= 0; shift -= 6) { n = parseEscaped(part, &i); if (n < 0x80 || n > 0xBF) { utf8 = false; break; } encoded |= (n & 0x3F) << shift; } if (!utf8 || encoded < min || encoded >= 0xD800 && encoded <= 0xDFFF || encoded > 0x10FFFF) { break; } if (encoded <= 0xFFFF) { buf.append(static_cast< sal_Unicode >(encoded)); } else { buf.append(static_cast< sal_Unicode >( (encoded >> 10) | 0xD800)); buf.append(static_cast< sal_Unicode >( (encoded & 0x3FF) | 0xDC00)); } } else { break; } *index = i; } else { buf.append(c); ++*index; } } return buf.makeStringAndClear(); } bool parseSchemeSpecificPart(rtl::OUString const & part) { sal_Int32 len = part.getLength(); sal_Int32 i = 0; if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') { return false; } if (i == len) { return true; } for (;;) { ++i; // skip '?' or '&' if (parsePart(part, false, &i).getLength() == 0 || i == len || part[i] != '=') { return false; } ++i; parsePart(part, false, &i); if (i == len) { return true; } if (part[i] != '&') { return false; } } } class UrlReference: public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference > { public: UrlReference(rtl::OUString const & scheme, rtl::OUString const & path): m_base( scheme, false, false, rtl::OUString(), path, false, rtl::OUString()) {} virtual rtl::OUString SAL_CALL getUriReference() throw (com::sun::star::uno::RuntimeException) { return m_base.getUriReference(); } virtual sal_Bool SAL_CALL isAbsolute() throw (com::sun::star::uno::RuntimeException) { return m_base.isAbsolute(); } virtual rtl::OUString SAL_CALL getScheme() throw (com::sun::star::uno::RuntimeException) { return m_base.getScheme(); } virtual rtl::OUString SAL_CALL getSchemeSpecificPart() throw (com::sun::star::uno::RuntimeException) { return m_base.getSchemeSpecificPart(); } virtual sal_Bool SAL_CALL isHierarchical() throw (com::sun::star::uno::RuntimeException) { return m_base.isHierarchical(); } virtual sal_Bool SAL_CALL hasAuthority() throw (com::sun::star::uno::RuntimeException) { return m_base.hasAuthority(); } virtual rtl::OUString SAL_CALL getAuthority() throw (com::sun::star::uno::RuntimeException) { return m_base.getAuthority(); } virtual rtl::OUString SAL_CALL getPath() throw (com::sun::star::uno::RuntimeException) { return m_base.getPath(); } virtual sal_Bool SAL_CALL hasRelativePath() throw (com::sun::star::uno::RuntimeException) { return m_base.hasRelativePath(); } virtual sal_Int32 SAL_CALL getPathSegmentCount() throw (com::sun::star::uno::RuntimeException) { return m_base.getPathSegmentCount(); } virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index) throw (com::sun::star::uno::RuntimeException) { return m_base.getPathSegment(index); } virtual sal_Bool SAL_CALL hasQuery() throw (com::sun::star::uno::RuntimeException) { return m_base.hasQuery(); } virtual rtl::OUString SAL_CALL getQuery() throw (com::sun::star::uno::RuntimeException) { return m_base.getQuery(); } virtual sal_Bool SAL_CALL hasFragment() throw (com::sun::star::uno::RuntimeException) { return m_base.hasFragment(); } virtual rtl::OUString SAL_CALL getFragment() throw (com::sun::star::uno::RuntimeException) { return m_base.getFragment(); } virtual void SAL_CALL setFragment(rtl::OUString const & fragment) throw (com::sun::star::uno::RuntimeException) { m_base.setFragment(fragment); } virtual void SAL_CALL clearFragment() throw (com::sun::star::uno::RuntimeException) { m_base.clearFragment(); } virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key) throw (css::uno::RuntimeException); virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key) throw (css::uno::RuntimeException); private: UrlReference(UrlReference &); // not implemented void operator =(UrlReference); // not implemented virtual ~UrlReference() {} sal_Int32 findParameter(rtl::OUString const & key); stoc::uriproc::UriReference m_base; }; rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); sal_Int32 i = 0; return parsePart(m_base.m_path, true, &i); } sal_Bool UrlReference::hasParameter(rtl::OUString const & key) throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); return findParameter(key) >= 0; } rtl::OUString UrlReference::getParameter(rtl::OUString const & key) throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); sal_Int32 i = findParameter(key); return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString(); } sal_Int32 UrlReference::findParameter(rtl::OUString const & key) { sal_Int32 i = 0; parsePart(m_base.m_path, true, &i); // skip name for (;;) { if (i == m_base.m_path.getLength()) { return -1; } ++i; // skip '?' or '&' rtl::OUString k = parsePart(m_base.m_path, false, &i); ++i; // skip '=' if (k == key) { return i; } parsePart(m_base.m_path, false, &i); // skip value } } class Parser: public cppu::WeakImplHelper2< css::lang::XServiceInfo, css::uri::XUriSchemeParser > { public: Parser() {} virtual rtl::OUString SAL_CALL getImplementationName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException); virtual css::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (css::uno::RuntimeException); virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL parse( rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart) throw (css::uno::RuntimeException); private: Parser(Parser &); // not implemented void operator =(Parser); // not implemented virtual ~Parser() {} }; rtl::OUString Parser::getImplementationName() throw (css::uno::RuntimeException) { return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript:: getImplementationName(); } sal_Bool Parser::supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException) { return stoc::uriproc::supportsService( getSupportedServiceNames(), serviceName); } css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames() throw (css::uno::RuntimeException) { return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript:: getSupportedServiceNames(); } css::uno::Reference< css::uri::XUriReference > Parser::parse( rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart) throw (css::uno::RuntimeException) { if (!parseSchemeSpecificPart(schemeSpecificPart)) { return 0; } try { return new UrlReference(scheme, schemeSpecificPart); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } } namespace stoc { namespace uriproc { namespace UriSchemeParser_vndDOTsunDOTstarDOTscript { css::uno::Reference< css::uno::XInterface > create( css::uno::Reference< css::uno::XComponentContext > const &) SAL_THROW((css::uno::Exception)) { //TODO: single instance try { return static_cast< cppu::OWeakObject * >(new Parser); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } rtl::OUString getImplementationName() { return rtl::OUString::createFromAscii( "com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript"); } css::uno::Sequence< rtl::OUString > getSupportedServiceNames() { css::uno::Sequence< rtl::OUString > s(1); s[0] = rtl::OUString::createFromAscii( "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript"); return s; } } } } <commit_msg>INTEGRATION: CWS sb76 (1.5.46); FILE MERGED 2007/08/31 11:01:56 sb 1.5.46.1: #i77885# Consolidate stoc libraries; patch by jnavrati.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-09-27 13:06:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_stoc.hxx" #include "stocservices.hxx" #include "UriReference.hxx" #include "supportsService.hxx" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uri/XUriReference.hpp" #include "com/sun/star/uri/XUriSchemeParser.hpp" #include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp" #include "cppuhelper/implbase1.hxx" #include "cppuhelper/implbase2.hxx" #include "cppuhelper/weak.hxx" #include "osl/mutex.hxx" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.hxx" #include "sal/types.h" #include <new> namespace css = com::sun::star; namespace { int getHexWeight(sal_Unicode c) { return c >= '0' && c <= '9' ? static_cast< int >(c - '0') : c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10) : c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10) : -1; } int parseEscaped(rtl::OUString const & part, sal_Int32 * index) { if (part.getLength() - *index < 3 || part[*index] != '%') { return -1; } int n1 = getHexWeight(part[*index + 1]); int n2 = getHexWeight(part[*index + 2]); if (n1 < 0 || n2 < 0) { return -1; } *index += 3; return (n1 << 4) | n2; } rtl::OUString parsePart( rtl::OUString const & part, bool namePart, sal_Int32 * index) { rtl::OUStringBuffer buf; while (*index < part.getLength()) { sal_Unicode c = part[*index]; if (namePart ? c == '?' : c == '&' || c == '=') { break; } else if (c == '%') { sal_Int32 i = *index; int n = parseEscaped(part, &i); if (n >= 0 && n <= 0x7F) { buf.append(static_cast< sal_Unicode >(n)); } else if (n >= 0xC0 && n <= 0xFC) { sal_Int32 encoded; int shift; sal_Int32 min; if (n <= 0xDF) { encoded = (n & 0x1F) << 6; shift = 0; min = 0x80; } else if (n <= 0xEF) { encoded = (n & 0x0F) << 12; shift = 6; min = 0x800; } else if (n <= 0xF7) { encoded = (n & 0x07) << 18; shift = 12; min = 0x10000; } else if (n <= 0xFB) { encoded = (n & 0x03) << 24; shift = 18; min = 0x200000; } else { encoded = 0; shift = 24; min = 0x4000000; } bool utf8 = true; for (; shift >= 0; shift -= 6) { n = parseEscaped(part, &i); if (n < 0x80 || n > 0xBF) { utf8 = false; break; } encoded |= (n & 0x3F) << shift; } if (!utf8 || encoded < min || encoded >= 0xD800 && encoded <= 0xDFFF || encoded > 0x10FFFF) { break; } if (encoded <= 0xFFFF) { buf.append(static_cast< sal_Unicode >(encoded)); } else { buf.append(static_cast< sal_Unicode >( (encoded >> 10) | 0xD800)); buf.append(static_cast< sal_Unicode >( (encoded & 0x3FF) | 0xDC00)); } } else { break; } *index = i; } else { buf.append(c); ++*index; } } return buf.makeStringAndClear(); } bool parseSchemeSpecificPart(rtl::OUString const & part) { sal_Int32 len = part.getLength(); sal_Int32 i = 0; if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') { return false; } if (i == len) { return true; } for (;;) { ++i; // skip '?' or '&' if (parsePart(part, false, &i).getLength() == 0 || i == len || part[i] != '=') { return false; } ++i; parsePart(part, false, &i); if (i == len) { return true; } if (part[i] != '&') { return false; } } } class UrlReference: public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference > { public: UrlReference(rtl::OUString const & scheme, rtl::OUString const & path): m_base( scheme, false, false, rtl::OUString(), path, false, rtl::OUString()) {} virtual rtl::OUString SAL_CALL getUriReference() throw (com::sun::star::uno::RuntimeException) { return m_base.getUriReference(); } virtual sal_Bool SAL_CALL isAbsolute() throw (com::sun::star::uno::RuntimeException) { return m_base.isAbsolute(); } virtual rtl::OUString SAL_CALL getScheme() throw (com::sun::star::uno::RuntimeException) { return m_base.getScheme(); } virtual rtl::OUString SAL_CALL getSchemeSpecificPart() throw (com::sun::star::uno::RuntimeException) { return m_base.getSchemeSpecificPart(); } virtual sal_Bool SAL_CALL isHierarchical() throw (com::sun::star::uno::RuntimeException) { return m_base.isHierarchical(); } virtual sal_Bool SAL_CALL hasAuthority() throw (com::sun::star::uno::RuntimeException) { return m_base.hasAuthority(); } virtual rtl::OUString SAL_CALL getAuthority() throw (com::sun::star::uno::RuntimeException) { return m_base.getAuthority(); } virtual rtl::OUString SAL_CALL getPath() throw (com::sun::star::uno::RuntimeException) { return m_base.getPath(); } virtual sal_Bool SAL_CALL hasRelativePath() throw (com::sun::star::uno::RuntimeException) { return m_base.hasRelativePath(); } virtual sal_Int32 SAL_CALL getPathSegmentCount() throw (com::sun::star::uno::RuntimeException) { return m_base.getPathSegmentCount(); } virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index) throw (com::sun::star::uno::RuntimeException) { return m_base.getPathSegment(index); } virtual sal_Bool SAL_CALL hasQuery() throw (com::sun::star::uno::RuntimeException) { return m_base.hasQuery(); } virtual rtl::OUString SAL_CALL getQuery() throw (com::sun::star::uno::RuntimeException) { return m_base.getQuery(); } virtual sal_Bool SAL_CALL hasFragment() throw (com::sun::star::uno::RuntimeException) { return m_base.hasFragment(); } virtual rtl::OUString SAL_CALL getFragment() throw (com::sun::star::uno::RuntimeException) { return m_base.getFragment(); } virtual void SAL_CALL setFragment(rtl::OUString const & fragment) throw (com::sun::star::uno::RuntimeException) { m_base.setFragment(fragment); } virtual void SAL_CALL clearFragment() throw (com::sun::star::uno::RuntimeException) { m_base.clearFragment(); } virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key) throw (css::uno::RuntimeException); virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key) throw (css::uno::RuntimeException); private: UrlReference(UrlReference &); // not implemented void operator =(UrlReference); // not implemented virtual ~UrlReference() {} sal_Int32 findParameter(rtl::OUString const & key); stoc::uriproc::UriReference m_base; }; rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); sal_Int32 i = 0; return parsePart(m_base.m_path, true, &i); } sal_Bool UrlReference::hasParameter(rtl::OUString const & key) throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); return findParameter(key) >= 0; } rtl::OUString UrlReference::getParameter(rtl::OUString const & key) throw (css::uno::RuntimeException) { osl::MutexGuard g(m_base.m_mutex); sal_Int32 i = findParameter(key); return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString(); } sal_Int32 UrlReference::findParameter(rtl::OUString const & key) { sal_Int32 i = 0; parsePart(m_base.m_path, true, &i); // skip name for (;;) { if (i == m_base.m_path.getLength()) { return -1; } ++i; // skip '?' or '&' rtl::OUString k = parsePart(m_base.m_path, false, &i); ++i; // skip '=' if (k == key) { return i; } parsePart(m_base.m_path, false, &i); // skip value } } class Parser: public cppu::WeakImplHelper2< css::lang::XServiceInfo, css::uri::XUriSchemeParser > { public: Parser() {} virtual rtl::OUString SAL_CALL getImplementationName() throw (css::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException); virtual css::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (css::uno::RuntimeException); virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL parse( rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart) throw (css::uno::RuntimeException); private: Parser(Parser &); // not implemented void operator =(Parser); // not implemented virtual ~Parser() {} }; rtl::OUString Parser::getImplementationName() throw (css::uno::RuntimeException) { return stoc_services::UriSchemeParser_vndDOTsunDOTstarDOTscript:: getImplementationName(); } sal_Bool Parser::supportsService(rtl::OUString const & serviceName) throw (css::uno::RuntimeException) { return stoc::uriproc::supportsService( getSupportedServiceNames(), serviceName); } css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames() throw (css::uno::RuntimeException) { return stoc_services::UriSchemeParser_vndDOTsunDOTstarDOTscript:: getSupportedServiceNames(); } css::uno::Reference< css::uri::XUriReference > Parser::parse( rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart) throw (css::uno::RuntimeException) { if (!parseSchemeSpecificPart(schemeSpecificPart)) { return 0; } try { return new UrlReference(scheme, schemeSpecificPart); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } } namespace stoc_services { namespace UriSchemeParser_vndDOTsunDOTstarDOTscript { css::uno::Reference< css::uno::XInterface > create( css::uno::Reference< css::uno::XComponentContext > const &) SAL_THROW((css::uno::Exception)) { //TODO: single instance try { return static_cast< cppu::OWeakObject * >(new Parser); } catch (std::bad_alloc &) { throw css::uno::RuntimeException( rtl::OUString::createFromAscii("std::bad_alloc"), 0); } } rtl::OUString getImplementationName() { return rtl::OUString::createFromAscii( "com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript"); } css::uno::Sequence< rtl::OUString > getSupportedServiceNames() { css::uno::Sequence< rtl::OUString > s(1); s[0] = rtl::OUString::createFromAscii( "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript"); return s; } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <commit_msg>add interfaceForMode<commit_after>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include "qsysteminfo.h" Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus); Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode); class tst_QSystemNetworkInfo : public QObject { Q_OBJECT private slots: void initTestCase(); void tst_networkStatus(); void tst_networkSignalStrength_data(); void tst_networkSignalStrength(); void tst_cellId(); void tst_locationAreaCode(); void tst_currentMobileCountryCode(); // Mobile Country Code void tst_currentMobileNetworkCode(); // Mobile Network Code void tst_homeMobileCountryCode(); void tst_homeMobileNetworkCode(); void tst_networkName(); void tst_macAddress_data(); void tst_macAddress(); void tst_interfaceForMode(); }; //signal todo: // void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus); void tst_QSystemNetworkInfo::initTestCase() { qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus"); qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode"); } void tst_QSystemNetworkInfo::tst_networkStatus() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode); QVERIFY( status == QSystemNetworkInfo::UndefinedStatus || status == QSystemNetworkInfo::NoNetworkAvailable || status == QSystemNetworkInfo::EmergencyOnly || status == QSystemNetworkInfo::Searching || status == QSystemNetworkInfo::Busy || status == QSystemNetworkInfo::Connected || status == QSystemNetworkInfo::HomeNetwork || status == QSystemNetworkInfo::Denied || status == QSystemNetworkInfo::Roaming); } } void tst_QSystemNetworkInfo::tst_networkSignalStrength_data() { QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode"); QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode; QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode; QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode; QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode; QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode; QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode; QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode; } void tst_QSystemNetworkInfo::tst_networkSignalStrength() { { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; qint32 strength = ni.networkSignalStrength(mode); QVERIFY( strength > -2 && strength < 101); } } void tst_QSystemNetworkInfo::tst_cellId() { QSystemNetworkInfo ni; qint32 id = ni.cellId(); QVERIFY(id > -2); } void tst_QSystemNetworkInfo::tst_locationAreaCode() { QSystemNetworkInfo ni; qint32 lac = ni.locationAreaCode(); QVERIFY(lac > -2); } void tst_QSystemNetworkInfo::tst_currentMobileCountryCode() { QSystemNetworkInfo ni; QVERIFY(!ni.currentMobileCountryCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_currentMobileNetworkCode() { QSystemNetworkInfo ni; QVERIFY(!ni.currentMobileNetworkCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_homeMobileCountryCode() { QSystemNetworkInfo ni; QVERIFY(!ni.homeMobileCountryCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_homeMobileNetworkCode() { QSystemNetworkInfo ni; QVERIFY(!ni.homeMobileNetworkCode().isEmpty()); } void tst_QSystemNetworkInfo::tst_networkName() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.networkName(mode).isEmpty()); } } void tst_QSystemNetworkInfo::tst_macAddress_data() { tst_networkSignalStrength_data(); } void tst_QSystemNetworkInfo::tst_macAddress() { QFETCH(QSystemNetworkInfo::NetworkMode, mode); QSystemNetworkInfo ni; QString mac = ni.macAddress(mode); if (!mac.isEmpty()) { QVERIFY(mac.length() == 17); QVERIFY(mac.contains(":")); } } void tst_QSystemNetworkInfo::tst_interfaceForMode() { QSystemNetworkInfo ni; QList<QSystemNetworkInfo::NetworkMode> modeList; modeList << QSystemNetworkInfo::GsmMode; modeList << QSystemNetworkInfo::CdmaMode; modeList << QSystemNetworkInfo::WcdmaMode; modeList << QSystemNetworkInfo::WlanMode; modeList << QSystemNetworkInfo::EthernetMode; modeList << QSystemNetworkInfo::BluetoothMode; modeList << QSystemNetworkInfo::WimaxMode; foreach(QSystemNetworkInfo::NetworkMode mode, modeList) { QVERIFY(!ni.interfaceForMode(mode).name().isEmpty()); } } QTEST_MAIN(tst_QSystemNetworkInfo) #include "tst_qsystemnetworkinfo.moc" <|endoftext|>
<commit_before> #include "test.h" #include <GLFW/glfw3.h> #include <bgfx.h> #include <common.h> #include <bgfx_utils.h> #include <bgfxplatform.h> #include <bx/string.h> #include <bx/readerwriter.h> #include "file.h" #include "utilities.h" #include "rendercontext.h" video_test::video_test( void ) { se_type = 0; } struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl PosColorVertex::ms_decl; static PosColorVertex s_cubeVertices[8] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath) { if (0 == bx::open(_reader, _filePath) ) { uint32_t size = (uint32_t)bx::getSize(_reader); const bgfx::Memory* mem = bgfx::alloc(size+1); bx::read(_reader, mem->data, size); bx::close(_reader); mem->data[mem->size-1] = '\0'; return mem; } return NULL; } void video_test::start( void ) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; if (!glfwInit()) exit(EXIT_FAILURE); GLFWwindow* window = glfwCreateWindow(1280, 720, "My Title", NULL, NULL); glfwMakeContextCurrent(window); bgfx::glfwSetWindow( window ); bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. PosColorVertex::init(); // Create static vertex buffer. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosColorVertex::ms_decl ); crap::VertexDeclaration vb_decl; crap::VertexAttribute vb_attr[2]; crap::setVertexAttribute( vb_attr[0], crap::Attribute::position, 3, crap::AttributeType::flt32 ); crap::setVertexAttribute( vb_attr[1], crap::Attribute::color0, 4, crap::AttributeType::uint8, true ); crap::setVertexDeclarationAttributes( vb_decl, vb_attr, 2 ); crap::RenderHandle vb_buffer = crap::createStaticVertexBuffer( s_cubeVertices, sizeof(s_cubeVertices), &vb_decl ); crap::file_t* vs_file = crap::openFile( "../../../data/vs_instancing.bin", CRAP_FILE_READBINARY ); uint32_t vs_size = crap::fileSize("../../../data/vs_instancing.bin"); char vs_memory[ vs_size ]; crap::readFromFile( vs_file, vs_memory, vs_size ); crap::RenderHandle vs_handle = crap::createShader( vs_memory, vs_size ); crap::file_t* fs_file = crap::openFile( "../../../data/fs_instancing.bin", CRAP_FILE_READBINARY ); uint32_t fs_size = crap::fileSize("../../../data/fs_instancing.bin"); char fs_memory[ fs_size ]; crap::readFromFile( fs_file, fs_memory, fs_size ); crap::RenderHandle fs_handle = crap::createShader( fs_memory, fs_size ); crap::RenderHandle pr_handle = crap::createProgram( vs_handle, fs_handle ); // Create static index buffer. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); float at[3] = { 50.0f, 50.0f, 0.0f }; float eye[3] = { 50.0f, 50.0f, -100.0f }; int64_t timeOffset = bx::getHPCounter(); uint32_t key = 0; key |= ( 1 << 6 ) | ( 1 << 7 ) | ( 1 << 8 ); uint32_t keys[100]; uint32_t levels[100]; for( uint32_t u=0; u< 100; ++u ) { keys[u] = rand(); levels[u] = rand() % 9; } bgfx::setViewSeq(0, true); while ( glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS ) { float view[16]; float proj[16]; bx::mtxLookAt(view, eye, at); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 1000.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) ); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); bgfx::dbgTextPrintf(0, 4, 0x6f, "Press ESC to close window and exit."); const uint16_t instanceStride = 80; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(100, instanceStride); if( idb != 0 ) { uint8_t* data = idb->data; for( uint32_t y=0; y<100; ++y ) { float* mtx = (float*)data; bx::mtxRotateXY(mtx, 0, 0); keyToCoords( mtx[12], mtx[13], mtx[14], keys[y], levels[y] ); bx::mtxScale(mtx, 10, 10, 10); float* color = (float*)&data[64]; color[0] = sin(time+float(y)/11.0f)*0.5f+0.5f; color[1] = cos(time+float(y)/11.0f)*0.5f+0.5f; color[2] = sin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } // Set vertex and fragment shaders. //bgfx::setProgram(program); crap::setProgram( pr_handle ); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); //crap::setVertexBuffer( vb_buffer ); bgfx::setIndexBuffer(ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); glfwPollEvents(); } // Shutdown bgfx. bgfx::shutdown(); glfwDestroyWindow(window); glfwTerminate(); } <commit_msg>update<commit_after> #include "test.h" #include <GLFW/glfw3.h> #include <bgfx.h> #include <common.h> #include <bgfx_utils.h> #include <bgfxplatform.h> #include <bx/string.h> #include <bx/readerwriter.h> #include "file.h" #include "utilities.h" #include "rendercontext.h" video_test::video_test( void ) { se_type = 0; } struct PosColorVertex { float m_x; float m_y; float m_z; uint32_t m_abgr; static void init() { ms_decl .begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true) .end(); }; static bgfx::VertexDecl ms_decl; }; bgfx::VertexDecl PosColorVertex::ms_decl; static PosColorVertex s_cubeVertices[8] = { {-1.0f, 1.0f, 1.0f, 0xff000000 }, { 1.0f, 1.0f, 1.0f, 0xff0000ff }, {-1.0f, -1.0f, 1.0f, 0xff00ff00 }, { 1.0f, -1.0f, 1.0f, 0xff00ffff }, {-1.0f, 1.0f, -1.0f, 0xffff0000 }, { 1.0f, 1.0f, -1.0f, 0xffff00ff }, {-1.0f, -1.0f, -1.0f, 0xffffff00 }, { 1.0f, -1.0f, -1.0f, 0xffffffff }, }; static const uint16_t s_cubeIndices[36] = { 0, 1, 2, // 0 1, 3, 2, 4, 6, 5, // 2 5, 6, 7, 0, 2, 4, // 4 4, 2, 6, 1, 5, 3, // 6 5, 7, 3, 0, 4, 1, // 8 4, 5, 1, 2, 3, 6, // 10 6, 3, 7, }; static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath) { if (0 == bx::open(_reader, _filePath) ) { uint32_t size = (uint32_t)bx::getSize(_reader); const bgfx::Memory* mem = bgfx::alloc(size+1); bx::read(_reader, mem->data, size); bx::close(_reader); mem->data[mem->size-1] = '\0'; return mem; } return NULL; } void video_test::start( void ) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; if (!glfwInit()) exit(EXIT_FAILURE); GLFWwindow* window = glfwCreateWindow(1280, 720, "My Title", NULL, NULL); glfwMakeContextCurrent(window); bgfx::glfwSetWindow( window ); bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. PosColorVertex::init(); // Create static vertex buffer. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosColorVertex::ms_decl ); crap::VertexDeclaration vb_decl; crap::VertexAttribute vb_attr[2]; crap::setVertexAttribute( vb_attr[0], crap::Attribute::position, 3, crap::AttributeType::flt32 ); crap::setVertexAttribute( vb_attr[1], crap::Attribute::color0, 4, crap::AttributeType::uint8, true ); crap::setVertexDeclarationAttributes( vb_decl, vb_attr, 2 ); crap::RenderHandle vb_buffer = crap::createStaticVertexBuffer( s_cubeVertices, sizeof(s_cubeVertices), &vb_decl ); crap::file_t* vs_file = crap::openFile( "../../../data/vs_instancing.bin", CRAP_FILE_READBINARY ); uint32_t vs_size = crap::fileSize("../../../data/vs_instancing.bin"); char vs_memory[ vs_size ]; crap::readFromFile( vs_file, vs_memory, vs_size ); crap::RenderHandle vs_handle = crap::createShader( vs_memory, vs_size ); crap::file_t* fs_file = crap::openFile( "../../../data/fs_instancing.bin", CRAP_FILE_READBINARY ); uint32_t fs_size = crap::fileSize("../../../data/fs_instancing.bin"); char fs_memory[ fs_size ]; crap::readFromFile( fs_file, fs_memory, fs_size ); crap::RenderHandle fs_handle = crap::createShader( fs_memory, fs_size ); crap::RenderHandle pr_handle = crap::createProgram( vs_handle, fs_handle ); // Create static index buffer. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); float at[3] = { 50.0f, 50.0f, 0.0f }; float eye[3] = { 50.0f, 50.0f, -100.0f }; int64_t timeOffset = bx::getHPCounter(); uint32_t key = 0; key |= ( 1 << 6 ) | ( 1 << 7 ) | ( 1 << 8 ); uint32_t keys[100]; uint32_t levels[100]; for( uint32_t u=0; u< 100; ++u ) { keys[u] = rand(); levels[u] = rand() % 9; } bgfx::setViewSeq(0, true); while ( glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS ) { float view[16]; float proj[16]; bx::mtxLookAt(view, eye, at); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 1000.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) ); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); bgfx::dbgTextPrintf(0, 4, 0x6f, "Press ESC to close window and exit."); const uint16_t instanceStride = 80; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(100, instanceStride); if( idb != 0 ) { uint8_t* data = idb->data; for( uint32_t y=0; y<100; ++y ) { float* mtx = (float*)data; bx::mtxRotateXY(mtx, 0, 0); keyToCoords( mtx[12], mtx[13], mtx[14], keys[y], levels[y] ); bx::mtxScale(mtx, 10, 10, 10); float* color = (float*)&data[64]; color[0] = sin(time+float(y)/11.0f)*0.5f+0.5f; color[1] = cos(time+float(y)/11.0f)*0.5f+0.5f; color[2] = sin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } // Set vertex and fragment shaders. //bgfx::setProgram(program); crap::setProgram( pr_handle ); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); //crap::setVertexBuffer( vb_buffer ); bgfx::setIndexBuffer(ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); glfwPollEvents(); } // Shutdown bgfx. bgfx::shutdown(); glfwDestroyWindow(window); glfwTerminate(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dp_ucb.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-08-12 12:09:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dp_misc.hrc" #include "dp_misc.h" #include "dp_ucb.h" #include "rtl/uri.hxx" #include "rtl/ustrbuf.hxx" #include "ucbhelper/content.hxx" #include "xmlscript/xml_helper.hxx" #include "com/sun/star/io/XInputStream.hpp" #include "com/sun/star/ucb/CommandFailedException.hpp" #include "com/sun/star/ucb/XContentCreator.hpp" #include "com/sun/star/ucb/ContentInfo.hpp" #include "com/sun/star/ucb/ContentInfoAttribute.hpp" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using ::rtl::OUString; namespace dp_misc { //============================================================================== bool create_ucb_content( ::ucb::Content * ret_ucbContent, OUString const & url, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { try { // dilemma: no chance to use the given iahandler here, because it would // raise no such file dialogs, else no interaction for // passwords, ...? xxx todo ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() ); if (! ucbContent.isFolder()) ucbContent.openStream()->closeInput(); if (ret_ucbContent != 0) *ret_ucbContent = ::ucb::Content( url, xCmdEnv ); return true; } catch (RuntimeException &) { throw; } catch (Exception &) { if (throw_exc) throw; } return false; } //============================================================================== bool create_folder( ::ucb::Content * ret_ucb_content, OUString const & url_, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { ::ucb::Content ucb_content; if (create_ucb_content( &ucb_content, url_, xCmdEnv, false /* no throw */ )) { if (ucb_content.isFolder()) { if (ret_ucb_content != 0) *ret_ucb_content = ucb_content; return true; } } OUString url( url_ ); // xxx todo: find parent sal_Int32 slash = url.lastIndexOf( '/' ); if (slash < 0) { // fallback: url = expand_url( url ); slash = url.lastIndexOf( '/' ); } ::ucb::Content parentContent; if (! create_folder( &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc )) return false; Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY ); if (xCreator.is()) { OUString strTitle( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ); Any title( makeAny( ::rtl::Uri::decode( url.copy( slash + 1 ), rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ) ) ); Sequence<ContentInfo> infos( xCreator->queryCreatableContentsInfo() ); for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos ) { // look KIND_FOLDER: ContentInfo const & info = infos[ pos ]; if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0) { // make sure the only required bootstrap property is "Title": Sequence<beans::Property> const & rProps = info.Properties; if (rProps.getLength() != 1 || !rProps[ 0 ].Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("Title") )) continue; try { if (parentContent.insertNewContent( info.Type, Sequence<OUString>( &strTitle, 1 ), Sequence<Any>( &title, 1 ), ucb_content )) { if (ret_ucb_content != 0) *ret_ucb_content = ucb_content; return true; } } catch (RuntimeException &) { throw; } catch (CommandFailedException &) { // Interaction Handler already handled the error // that has occured... } catch (Exception &) { if (throw_exc) throw; return false; } } } } if (throw_exc) throw ContentCreationException( OUSTR("Cannot create folder: ") + url, Reference<XInterface>(), ContentCreationError_UNKNOWN ); return false; } //============================================================================== bool erase_path( OUString const & url, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { ::ucb::Content ucb_content; if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ )) { try { ucb_content.executeCommand( OUSTR("delete"), makeAny( true /* delete physically */ ) ); } catch (RuntimeException &) { throw; } catch (Exception &) { if (throw_exc) throw; return false; } } return true; } //============================================================================== ::rtl::ByteSequence readFile( ::ucb::Content & ucb_content ) { ::rtl::ByteSequence bytes; Reference<io::XOutputStream> xStream( ::xmlscript::createOutputStream( &bytes ) ); if (! ucb_content.openStream( xStream )) throw RuntimeException( OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 ); return bytes; } //============================================================================== bool readLine( OUString * res, OUString const & startingWith, ::ucb::Content & ucb_content, rtl_TextEncoding textenc ) { // read whole file: ::rtl::ByteSequence bytes( readFile( ucb_content ) ); OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()), bytes.getLength(), textenc ); sal_Int32 pos = 0; for (;;) { if (file.match( startingWith, pos )) { ::rtl::OUStringBuffer buf; sal_Int32 start = pos; pos += startingWith.getLength(); for (;;) { pos = file.indexOf( LF, pos ); if (pos < 0) { // EOF buf.append( file.copy( start ) ); } else { if (pos > 0 && file[ pos - 1 ] == CR) { // consume extra CR buf.append( file.copy( start, pos - start - 1 ) ); ++pos; } else buf.append( file.copy( start, pos - start ) ); ++pos; // consume LF // check next line: if (pos < file.getLength() && (file[ pos ] == ' ' || file[ pos ] == '\t')) { buf.append( static_cast<sal_Unicode>(' ') ); ++pos; start = pos; continue; } } break; } *res = buf.makeStringAndClear(); return true; } // next line: sal_Int32 next_lf = file.indexOf( LF, pos ); if (next_lf < 0) // EOF break; pos = next_lf + 1; } return false; } } <commit_msg>INTEGRATION: CWS jl13 (1.4.12); FILE MERGED 2004/10/15 12:48:58 dbo 1.4.12.3: #i35536##i34555##i34149# - rc files without vnd.sun.star.expand urls - export file picker filter - reinstall cleans xlc files - minor improvements Issue number: Submitted by: Reviewed by: 2004/09/30 16:53:54 dbo 1.4.12.2: #i34555# correct double checked locking, misc cleanup 2004/09/14 15:31:44 dbo 1.4.12.1: #i34149##i33982# modified makeURL(), misc fixes<commit_after>/************************************************************************* * * $RCSfile: dp_ucb.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2004-11-09 14:10:17 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "dp_misc.hrc" #include "dp_misc.h" #include "dp_ucb.h" #include "rtl/uri.hxx" #include "rtl/ustrbuf.hxx" #include "ucbhelper/content.hxx" #include "xmlscript/xml_helper.hxx" #include "com/sun/star/io/XInputStream.hpp" #include "com/sun/star/ucb/CommandFailedException.hpp" #include "com/sun/star/ucb/XContentCreator.hpp" #include "com/sun/star/ucb/ContentInfo.hpp" #include "com/sun/star/ucb/ContentInfoAttribute.hpp" using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using ::rtl::OUString; namespace dp_misc { //============================================================================== bool create_ucb_content( ::ucb::Content * ret_ucbContent, OUString const & url, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { try { // dilemma: no chance to use the given iahandler here, because it would // raise no such file dialogs, else no interaction for // passwords, ...? xxx todo ::ucb::Content ucbContent( url, Reference<XCommandEnvironment>() ); if (! ucbContent.isFolder()) ucbContent.openStream()->closeInput(); if (ret_ucbContent != 0) *ret_ucbContent = ::ucb::Content( url, xCmdEnv ); return true; } catch (RuntimeException &) { throw; } catch (Exception &) { if (throw_exc) throw; } return false; } //============================================================================== bool create_folder( ::ucb::Content * ret_ucb_content, OUString const & url_, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { ::ucb::Content ucb_content; if (create_ucb_content( &ucb_content, url_, xCmdEnv, false /* no throw */ )) { if (ucb_content.isFolder()) { if (ret_ucb_content != 0) *ret_ucb_content = ucb_content; return true; } } OUString url( url_ ); // xxx todo: find parent sal_Int32 slash = url.lastIndexOf( '/' ); if (slash < 0) { // fallback: url = expandUnoRcUrl( url ); slash = url.lastIndexOf( '/' ); } ::ucb::Content parentContent; if (! create_folder( &parentContent, url.copy( 0, slash ), xCmdEnv, throw_exc )) return false; Reference<XContentCreator> xCreator( parentContent.get(), UNO_QUERY ); if (xCreator.is()) { Any title( makeAny( ::rtl::Uri::decode( url.copy( slash + 1 ), rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 ) ) ); Sequence<ContentInfo> infos( xCreator->queryCreatableContentsInfo() ); for ( sal_Int32 pos = 0; pos < infos.getLength(); ++pos ) { // look KIND_FOLDER: ContentInfo const & info = infos[ pos ]; if ((info.Attributes & ContentInfoAttribute::KIND_FOLDER) != 0) { // make sure the only required bootstrap property is "Title": Sequence<beans::Property> const & rProps = info.Properties; if (rProps.getLength() != 1 || !rProps[ 0 ].Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("Title") )) continue; try { if (parentContent.insertNewContent( info.Type, Sequence<OUString>( &StrTitle::get(), 1 ), Sequence<Any>( &title, 1 ), ucb_content )) { if (ret_ucb_content != 0) *ret_ucb_content = ucb_content; return true; } } catch (RuntimeException &) { throw; } catch (CommandFailedException &) { // Interaction Handler already handled the error // that has occured... } catch (Exception &) { if (throw_exc) throw; return false; } } } } if (throw_exc) throw ContentCreationException( OUSTR("Cannot create folder: ") + url, Reference<XInterface>(), ContentCreationError_UNKNOWN ); return false; } //============================================================================== bool erase_path( OUString const & url, Reference<XCommandEnvironment> const & xCmdEnv, bool throw_exc ) { ::ucb::Content ucb_content; if (create_ucb_content( &ucb_content, url, xCmdEnv, false /* no throw */ )) { try { ucb_content.executeCommand( OUSTR("delete"), makeAny( true /* delete physically */ ) ); } catch (RuntimeException &) { throw; } catch (Exception &) { if (throw_exc) throw; return false; } } return true; } //============================================================================== ::rtl::ByteSequence readFile( ::ucb::Content & ucb_content ) { ::rtl::ByteSequence bytes; Reference<io::XOutputStream> xStream( ::xmlscript::createOutputStream( &bytes ) ); if (! ucb_content.openStream( xStream )) throw RuntimeException( OUSTR("::ucb::Content::openStream( XOutputStream ) failed!"), 0 ); return bytes; } //============================================================================== bool readLine( OUString * res, OUString const & startingWith, ::ucb::Content & ucb_content, rtl_TextEncoding textenc ) { // read whole file: ::rtl::ByteSequence bytes( readFile( ucb_content ) ); OUString file( reinterpret_cast<sal_Char const *>(bytes.getConstArray()), bytes.getLength(), textenc ); sal_Int32 pos = 0; for (;;) { if (file.match( startingWith, pos )) { ::rtl::OUStringBuffer buf; sal_Int32 start = pos; pos += startingWith.getLength(); for (;;) { pos = file.indexOf( LF, pos ); if (pos < 0) { // EOF buf.append( file.copy( start ) ); } else { if (pos > 0 && file[ pos - 1 ] == CR) { // consume extra CR buf.append( file.copy( start, pos - start - 1 ) ); ++pos; } else buf.append( file.copy( start, pos - start ) ); ++pos; // consume LF // check next line: if (pos < file.getLength() && (file[ pos ] == ' ' || file[ pos ] == '\t')) { buf.append( static_cast<sal_Unicode>(' ') ); ++pos; start = pos; continue; } } break; } *res = buf.makeStringAndClear(); return true; } // next line: sal_Int32 next_lf = file.indexOf( LF, pos ); if (next_lf < 0) // EOF break; pos = next_lf + 1; } return false; } } <|endoftext|>
<commit_before>/** * \author John Szwast * \year 2014-2016 * \copyright MIT */ #pragma once #include <mutex> #include <type_traits> #include <utility> /** * \brief MemoizedMember is a C++ class that caches the result of a computation. * * \details * If your class `A` has an attribute `b` with a value you want to memoize: * * 1. Write a `private`, `const` computation method, `type compute_b() const`. * * 2. Add a `MemoizedMember` member using the computation method. * * 3. Write a `public` getter for the `MemoizedMember`, `type get_b() const`. * * Here is an example memoizing an `int` type attribute. * * class A * { * public: * int get_b() const {return b;} * private: * int compute_b() const; * MemoizedMember<int, A, &A::compute_b> b{*this}; * }; */ template<typename Key, class Class, Key (Class::*evaluate) () const> class MemoizedMember { public: /** * \brief "Default" constructor * \param[in] instance The Class instance in which *this is a member * \remarks We require a reference to the Class of which we are a member. */ MemoizedMember (Class const& instance) noexcept (std::is_nothrow_default_constructible<Key>::value) : m_instance (instance) { } /** * \brief "Copy" constructor * \param[in] instance The Class instance in which *this is a member * \param[in] r The source of the copy * \remarks We require a reference to the Class of which we are a member. * We do not want to copy the reference to the class of which `r` is a member. */ MemoizedMember (Class const& instance, const MemoizedMember& r) noexcept (std::is_nothrow_copy_constructible<Key>::value) : m_instance (instance) , m_value (r.m_value) , m_valid (r.m_valid) { } /** * \brief "Move" constructor * \param[in] instance The Class instance in which *this is a member * \param[in] r The source of the copy * \remarks We require a reference to the Class of which we are a member. * We do not want to copy the reference to the class of which `r` is a member. */ MemoizedMember (Class const& instance, MemoizedMember && r) noexcept (std::is_nothrow_move_constructible<Key>::value) : m_instance (instance) , m_value (std::move (r.m_value)) , m_valid (r.m_valid) { } MemoizedMember(const MemoizedMember&) = delete; MemoizedMember(MemoizedMember&&) = delete; ~MemoizedMember() = default; /** * A memoized member should be affiliated with an object. If that object is being * assigned we want to copy the memoization state, but m_instance shouldn't change. * * Basic exception guarantee: if copying the memoized value throws, then the memoization * will be cleared and recalculated on the next request. */ MemoizedMember& operator= (const MemoizedMember& r) { std::lock_guard<std::mutex> guard(m_lock); m_valid = false; m_value = r.m_value; m_valid = r.m_valid; return *this; } /** * A memoized member should be affiliated with an object. If that object is being * (move) assigned we want to move the memoization state, but m_instance shouldn't change. * * Basic exception guarantee: if moving the memoized value throws, then the memoization * will be cleared and recalculated on the next request. */ MemoizedMember& operator= (const MemoizedMember && r) { std::lock_guard<std::mutex> guard(m_lock); m_valid = false; m_value = std::move (r.m_value); m_valid = r.m_valid; return *this; } /** * \brief Key conversion operator. * * \details * This is the meat of this class. This is how the MemoizedMember behaves like a Key object. * If the value has not yet been calculated, then calculate it. * * \returns The memoized value. * * \remarks * Strong exception guarantee: If the calculation of the value to be memoized fails, then * it will be reattempted next time. */ operator Key() const { std::lock_guard<std::mutex> guard(m_lock); if (!m_valid) { m_value = (m_instance.*evaluate) (); m_valid = true; } return m_value; } /** * If the owning object is mutated in a way that should change the value of the memoized * member, then reset() it. After reset(), a re-computation will occur the next time the value * of the member is requested. */ void reset() noexcept { m_valid = false; } private: Class const& m_instance; mutable Key m_value {}; mutable bool m_valid {false}; mutable std::mutex m_lock; }; <commit_msg>Fixes #5. Make the mutex type a template parameter.<commit_after>/** * \author John Szwast * \year 2014-2016 * \copyright MIT */ #pragma once #include <mutex> #include <type_traits> #include <utility> /** * \brief MemoizedMember is a C++ class that caches the result of a computation. * * \details * If your class `A` has an attribute `b` with a value you want to memoize: * * 1. Write a `private`, `const` computation method, `type compute_b() const`. * * 2. Add a `MemoizedMember` member using the computation method. * * 3. Write a `public` getter for the `MemoizedMember`, `type get_b() const`. * * Here is an example memoizing an `int` type attribute. * * class A * { * public: * int get_b() const {return b;} * private: * int compute_b() const; * MemoizedMember<int, A, &A::compute_b> b{*this}; * }; */ template<typename Key, class Class, Key (Class::*evaluate) () const, typename Mutex = std::mutex> class MemoizedMember { public: /** * \brief "Default" constructor * \param[in] instance The Class instance in which *this is a member * \remarks We require a reference to the Class of which we are a member. */ MemoizedMember (Class const& instance) noexcept (std::is_nothrow_default_constructible<Key>::value) : m_instance (instance) { } /** * \brief "Copy" constructor * \param[in] instance The Class instance in which *this is a member * \param[in] r The source of the copy * \remarks We require a reference to the Class of which we are a member. * We do not want to copy the reference to the class of which `r` is a member. */ MemoizedMember (Class const& instance, const MemoizedMember& r) noexcept (std::is_nothrow_copy_constructible<Key>::value) : m_instance (instance) , m_value (r.m_value) , m_valid (r.m_valid) { } /** * \brief "Move" constructor * \param[in] instance The Class instance in which *this is a member * \param[in] r The source of the copy * \remarks We require a reference to the Class of which we are a member. * We do not want to copy the reference to the class of which `r` is a member. */ MemoizedMember (Class const& instance, MemoizedMember && r) noexcept (std::is_nothrow_move_constructible<Key>::value) : m_instance (instance) , m_value (std::move (r.m_value)) , m_valid (r.m_valid) { } MemoizedMember(const MemoizedMember&) = delete; MemoizedMember(MemoizedMember&&) = delete; ~MemoizedMember() = default; /** * A memoized member should be affiliated with an object. If that object is being * assigned we want to copy the memoization state, but m_instance shouldn't change. * * Basic exception guarantee: if copying the memoized value throws, then the memoization * will be cleared and recalculated on the next request. */ MemoizedMember& operator= (const MemoizedMember& r) { std::lock_guard<Mutex> guard(m_lock); m_valid = false; m_value = r.m_value; m_valid = r.m_valid; return *this; } /** * A memoized member should be affiliated with an object. If that object is being * (move) assigned we want to move the memoization state, but m_instance shouldn't change. * * Basic exception guarantee: if moving the memoized value throws, then the memoization * will be cleared and recalculated on the next request. */ MemoizedMember& operator= (const MemoizedMember && r) { std::lock_guard<Mutex> guard(m_lock); m_valid = false; m_value = std::move (r.m_value); m_valid = r.m_valid; return *this; } /** * \brief Key conversion operator. * * \details * This is the meat of this class. This is how the MemoizedMember behaves like a Key object. * If the value has not yet been calculated, then calculate it. * * \returns The memoized value. * * \remarks * Strong exception guarantee: If the calculation of the value to be memoized fails, then * it will be reattempted next time. */ operator Key() const { std::lock_guard<Mutex> guard(m_lock); if (!m_valid) { m_value = (m_instance.*evaluate) (); m_valid = true; } return m_value; } /** * If the owning object is mutated in a way that should change the value of the memoized * member, then reset() it. After reset(), a re-computation will occur the next time the value * of the member is requested. */ void reset() noexcept { m_valid = false; } private: Class const& m_instance; mutable Key m_value {}; mutable bool m_valid {false}; mutable Mutex m_lock; }; <|endoftext|>
<commit_before>#include <boost/algorithm/string.hpp> #include <functional> #include <string> #include <vector> #include <map> #include "collectfunctions.h" #include "vvvptreehelper.hpp" #include "myparamnames.hpp" using namespace clang; std::string getDoxyBrief(const ASTContext& ctx, const RawComment* comment) { return comment ? comment->getBriefText(ctx) : ""; } /** * Return strings of doxygen comment without comment opening and closing. * From eahch line also removed decoration * from begining if exist */ std::vector<std::string> removeDecorations(const std::string& str) { using namespace boost::algorithm; std::vector<std::string> ret; auto docstring = erase_tail_copy(erase_head_copy(str,3), 2); split(ret, docstring, is_any_of("\n"), token_compress_on); std::transform( ret.begin(), ret.end(), ret.begin(), [](const auto& str) { return boost::algorithm::trim_copy(str);} ); std::transform( ret.begin(), ret.end(), ret.begin(), [](const auto& str) { return str[0]=='*' ? erase_head_copy(str,1) : str; } ); return ret; } std::vector<std::string> splitToTrimmedWords(const std::string& str) { using namespace boost::algorithm; std::vector<std::string> splited; split(splited, str, is_any_of(" \t"), token_compress_on ); return filter(splited, [](const auto& str) {return !str.empty();}); } /** * Function join elements from 'c' using sep omitting n first elements. * @param c container * @param n number of head elements to exclude * @param sep separator to insert */ template<class T, typename S> auto joinTail(const T& c, size_t n, const S& sep) { const auto& tail = std::vector<std::string>(c.begin() + n, c.end()); const auto& comment = boost::algorithm::join(tail, sep); return comment; } std::map<std::string, std::string> getDoxyParams(const ASTContext& ctx, const RawComment* rawcomment) { using namespace boost::algorithm; std::map<std::string, std::string> ret; if(rawcomment == nullptr) return ret; const SourceManager& sm = ctx.getSourceManager(); const auto& text = rawcomment->getRawText(sm).str(); const auto& lines = removeDecorations(text); static const auto paramTags = {"@param", "\\param"}; static const auto returnTags = {"@return", "\\return"}; for(const auto& l: lines) { const auto words = splitToTrimmedWords(l); const size_t splitedsize = words.size(); if(splitedsize < 2) continue; const auto& Tag = words[0]; if(contain(paramTags, Tag) && splitedsize>2) { const auto& paramName = words[1]; const auto& comment = joinTail(words, 2, " "); ret[paramName] = comment; } else if(contain(returnTags, Tag)) { const auto& comment = joinTail(words, 1, " "); ret["return"] = comment; } } return ret; } void printFunctionDecls(clang::ASTContext& Context, boost::property_tree::ptree& tree, const printFunctionsParam& params) { const auto declsInMain = contain(params, PARAM_NAME_MAIN_ONLY) ? getMainFileDeclarations(Context) : getNonSystemDeclarations(Context); const auto functionsDecls = filterFunctions(declsInMain); using boost::property_tree::ptree; for(const auto& d: functionsDecls) { using namespace std; const auto& fs = getFunctionParams( d ); ptree functiondesc; ptree params; const RawComment* rc = Context.getRawCommentForDeclNoCache(d); const auto& brief = getDoxyBrief(Context, rc); auto paramsComments = getDoxyParams(Context, rc); for(const auto& f: fs) { const auto& name = f->getNameAsString(); const auto& t = f->getType().getAsString(); //const auto& comment = getComment((Decl*)f); ptree param; ptree_add_value(param, "param", name); ptree_add_value(param, "type", t); const std::string& comment = paramsComments.count(name) ? paramsComments[name] : ""; ptree_add_value(param, "comment", comment); ptree_array_add_node(params, param); } const auto functionName = d->getName().str(); ptree_add_value(functiondesc, "name", functionName); ptree_add_value(functiondesc, "retval", d->getReturnType().getAsString() ); ptree_add_value(functiondesc, "retcomment", paramsComments["return"]); ptree_add_value(functiondesc, "comment", brief); if(!fs.empty()) ptree_add_subnode(functiondesc, "params", params); ptree_array_add_node(tree, functiondesc); } } <commit_msg>refactoring<commit_after>#include <boost/algorithm/string.hpp> #include <functional> #include <string> #include <vector> #include <map> #include "collectfunctions.h" #include "vvvptreehelper.hpp" #include "myparamnames.hpp" using namespace clang; std::string getDoxyBrief(const ASTContext& ctx, const RawComment* comment) { return comment ? comment->getBriefText(ctx) : ""; } /** * Return strings of doxygen comment without comment opening and closing. * From eahch line also removed decoration * from begining if exist */ std::vector<std::string> removeDecorations(const std::string& str) { using namespace boost::algorithm; std::vector<std::string> ret; auto docstring = erase_tail_copy(erase_head_copy(str,3), 2); split(ret, docstring, is_any_of("\n"), token_compress_on); std::transform( ret.begin(), ret.end(), ret.begin(), [](const auto& str) { return boost::algorithm::trim_copy(str);} ); std::transform( ret.begin(), ret.end(), ret.begin(), [](const auto& str) { return str[0]=='*' ? erase_head_copy(str,1) : str; } ); return ret; } std::vector<std::string> splitToTrimmedWords(const std::string& str) { using namespace boost::algorithm; std::vector<std::string> splited; split(splited, str, is_any_of(" \t"), token_compress_on ); return filter(splited, [](const auto& str) {return !str.empty();}); } /** * Function join elements from 'c' using sep omitting n first elements. * @param c container * @param n number of head elements to exclude * @param sep separator to insert */ template<class T, typename S> auto joinTail(const T& c, size_t n, const S& sep) { const auto& tail = std::vector<std::string>(c.begin() + n, c.end()); const auto& comment = boost::algorithm::join(tail, sep); return comment; } std::map<std::string, std::string> getDoxyParams(const ASTContext& ctx, const RawComment* rawcomment) { using namespace boost::algorithm; std::map<std::string, std::string> ret; if(rawcomment == nullptr) return ret; const SourceManager& sm = ctx.getSourceManager(); const auto& text = rawcomment->getRawText(sm).str(); const auto& lines = removeDecorations(text); static const auto paramTags = {"@param", "\\param"}; static const auto returnTags = {"@return", "\\return"}; for(const auto& l: lines) { const auto words = splitToTrimmedWords(l); const size_t splitedsize = words.size(); if(splitedsize < 2) continue; const auto& Tag = words[0]; if(contain(paramTags, Tag) && splitedsize>2) { const auto& paramName = words[1]; const auto& comment = joinTail(words, 2, " "); ret[paramName] = comment; } else if(contain(returnTags, Tag)) { const auto& comment = joinTail(words, 1, " "); ret["return"] = comment; } } return ret; } void printFunctionDecls(clang::ASTContext& Context, boost::property_tree::ptree& tree, const printFunctionsParam& params) { const auto declsInMain = contain(params, PARAM_NAME_MAIN_ONLY) ? getMainFileDeclarations(Context) : getNonSystemDeclarations(Context); const auto functionsDecls = filterFunctions(declsInMain); using boost::property_tree::ptree; for(const auto& d: functionsDecls) { using namespace std; ptree functiondesc; ptree params; const RawComment* rc = Context.getRawCommentForDeclNoCache(d); const auto& brief = getDoxyBrief(Context, rc); auto paramsComments = getDoxyParams(Context, rc); const auto& paramDecls = getFunctionParams( d ); for(const auto& f: paramDecls) { const auto& name = f->getNameAsString(); const auto& t = f->getType().getAsString(); ptree param; ptree_add_value(param, "param", name); ptree_add_value(param, "type", t); const std::string& comment = paramsComments.count(name) ? paramsComments[name] : ""; ptree_add_value(param, "comment", comment); ptree_array_add_node(params, param); } const auto functionName = d->getName().str(); ptree_add_value(functiondesc, "name", functionName); ptree_add_value(functiondesc, "retval", d->getReturnType().getAsString() ); ptree_add_value(functiondesc, "retcomment", paramsComments["return"]); ptree_add_value(functiondesc, "comment", brief); if(!paramDecls.empty()) ptree_add_subnode(functiondesc, "params", params); ptree_array_add_node(tree, functiondesc); } } <|endoftext|>
<commit_before>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" #include "../lcd/LcdDisplay.h" #include "MockScannerView.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "/var/run/scannerd.STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); fflush(stdout); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop); fflush(stdout); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; static ScannerView *getDisplayInstance() { ScannerView *view = nullptr; #ifdef HAVE_LCD_DISPLAY LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance(); lcd->init(); view = lcd; #else view = new MockScannerView(); #endif } /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); for(int n = 0; n < argc; n ++) { printf(" argv[%d] = %s\n", n, argv[n]); } fflush(stdout); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672", false, "tcp://localhost:5672", "string", cmd); TCLAP::ValueArg<std::string> destinationName("t", "destinationName", "Specify the name of the destination on the message broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 1, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply", "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1", false, -1, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::SwitchArg generateTestData("T", "generateTestData", "Indicate that test data should be generated", false); TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect", "Don't try to reconnect to the broker on failure, just exit", false); TCLAP::SwitchArg batteryTestMode("", "batteryTestMode", "Simply monitor the raw heartbeat beacon events and publish them to the destinationName", false); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); cmd.add(generateTestData); cmd.add(noBrokerReconnect); cmd.add(batteryTestMode); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue()); command.setUseQueues(useQueues.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); command.setGenerateTestData(generateTestData.getValue()); command.setBatteryTestMode(batteryTestMode.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } shared_ptr<ScannerView> lcd(getDisplayInstance()); parserLogic.setScannerView(lcd); char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); fflush(stdout); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); fflush(stdout); return 0; } <commit_msg> Install default terminate handler to make sure we exit with non-zero status<commit_after>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <execinfo.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" #include "../lcd/LcdDisplay.h" #include "MockScannerView.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "/var/run/scannerd.STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); fflush(stdout); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #ifdef PRINT_DEBUG printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop); fflush(stdout); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; static ScannerView *getDisplayInstance() { ScannerView *view = nullptr; #ifdef HAVE_LCD_DISPLAY LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance(); lcd->init(); view = lcd; #else view = new MockScannerView(); #endif } void printStacktrace() { void *array[20]; int size = backtrace(array, sizeof(array) / sizeof(array[0])); backtrace_symbols_fd(array, size, STDERR_FILENO); } static void terminateHandler() { std::exception_ptr exptr = std::current_exception(); if (exptr != nullptr) { // the only useful feature of std::exception_ptr is that it can be rethrown... try { std::rethrow_exception(exptr); } catch (std::exception &ex) { std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what()); } catch (...) { std::fprintf(stderr, "Terminated due to unknown exception\n"); } } else { std::fprintf(stderr, "Terminated due to unknown reason :(\n"); } printStacktrace(); exit(100); } /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); for(int n = 0; n < argc; n ++) { printf(" argv[%d] = %s\n", n, argv[n]); } fflush(stdout); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672", false, "tcp://localhost:5672", "string", cmd); TCLAP::ValueArg<std::string> destinationName("t", "destinationName", "Specify the name of the destination on the message broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 1, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply", "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1", false, -1, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::SwitchArg generateTestData("T", "generateTestData", "Indicate that test data should be generated", false); TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect", "Don't try to reconnect to the broker on failure, just exit", false); TCLAP::SwitchArg batteryTestMode("", "batteryTestMode", "Simply monitor the raw heartbeat beacon events and publish them to the destinationName", false); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); cmd.add(generateTestData); cmd.add(noBrokerReconnect); cmd.add(batteryTestMode); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue()); command.setUseQueues(useQueues.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); command.setGenerateTestData(generateTestData.getValue()); command.setBatteryTestMode(batteryTestMode.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } // Install default terminate handler to make sure we exit with non-zero status std::set_terminate(terminateHandler); shared_ptr<ScannerView> lcd(getDisplayInstance()); parserLogic.setScannerView(lcd); char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); fflush(stdout); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); fflush(stdout); return 0; } <|endoftext|>
<commit_before>/* * author: Max Kellermann <[email protected]> */ #ifndef EXPANDABLE_STRING_LIST_HXX #define EXPANDABLE_STRING_LIST_HXX #include "util/ShallowCopy.hxx" #include <inline/compiler.h> #include <iterator> struct pool; class MatchInfo; class Error; template<typename T> struct ConstBuffer; class ExpandableStringList final { struct Item { Item *next = nullptr; const char *value; bool expandable; Item(const char *_value, bool _expandable) :value(_value), expandable(_expandable) {} }; Item *head = nullptr; public: ExpandableStringList() = default; ExpandableStringList(ExpandableStringList &&) = default; ExpandableStringList &operator=(ExpandableStringList &&src) = default; constexpr ExpandableStringList(ShallowCopy, const ExpandableStringList &src) :head(src.head) {} ExpandableStringList(struct pool &pool, const ExpandableStringList &src); gcc_pure bool IsEmpty() const { return head == nullptr; } class const_iterator final : public std::iterator<std::forward_iterator_tag, const char *> { const Item *cursor; public: const_iterator(const Item *_cursor):cursor(_cursor) {} bool operator!=(const const_iterator &other) const { return cursor != other.cursor; } const char *operator*() const { return cursor->value; } const_iterator &operator++() { cursor = cursor->next; return *this; } }; const_iterator begin() const { return {head}; } const_iterator end() const { return {nullptr}; } gcc_pure bool IsExpandable() const; bool Expand(struct pool *pool, const MatchInfo &match_info, Error &error_r); class Builder final { ExpandableStringList *list; Item **tail_r; Item *last; public: Builder() = default; Builder(ExpandableStringList &_list) :list(&_list), tail_r(&_list.head), last(nullptr) {} void Add(struct pool &pool, const char *value, bool expandable); bool CanSetExpand() const { return last != nullptr && !last->expandable; } void SetExpand(const char *value) const { last->value = value; last->expandable = true; } }; ConstBuffer<const char *> ToArray(struct pool &pool) const; }; #endif <commit_msg>ExpandableStringList: add Builder::Add() documentation<commit_after>/* * author: Max Kellermann <[email protected]> */ #ifndef EXPANDABLE_STRING_LIST_HXX #define EXPANDABLE_STRING_LIST_HXX #include "util/ShallowCopy.hxx" #include <inline/compiler.h> #include <iterator> struct pool; class MatchInfo; class Error; template<typename T> struct ConstBuffer; class ExpandableStringList final { struct Item { Item *next = nullptr; const char *value; bool expandable; Item(const char *_value, bool _expandable) :value(_value), expandable(_expandable) {} }; Item *head = nullptr; public: ExpandableStringList() = default; ExpandableStringList(ExpandableStringList &&) = default; ExpandableStringList &operator=(ExpandableStringList &&src) = default; constexpr ExpandableStringList(ShallowCopy, const ExpandableStringList &src) :head(src.head) {} ExpandableStringList(struct pool &pool, const ExpandableStringList &src); gcc_pure bool IsEmpty() const { return head == nullptr; } class const_iterator final : public std::iterator<std::forward_iterator_tag, const char *> { const Item *cursor; public: const_iterator(const Item *_cursor):cursor(_cursor) {} bool operator!=(const const_iterator &other) const { return cursor != other.cursor; } const char *operator*() const { return cursor->value; } const_iterator &operator++() { cursor = cursor->next; return *this; } }; const_iterator begin() const { return {head}; } const_iterator end() const { return {nullptr}; } gcc_pure bool IsExpandable() const; bool Expand(struct pool *pool, const MatchInfo &match_info, Error &error_r); class Builder final { ExpandableStringList *list; Item **tail_r; Item *last; public: Builder() = default; Builder(ExpandableStringList &_list) :list(&_list), tail_r(&_list.head), last(nullptr) {} /** * Add a new item to the end of the list. The pool is only * used to allocate the item structure, it does not copy the * string. */ void Add(struct pool &pool, const char *value, bool expandable); bool CanSetExpand() const { return last != nullptr && !last->expandable; } void SetExpand(const char *value) const { last->value = value; last->expandable = true; } }; ConstBuffer<const char *> ToArray(struct pool &pool) const; }; #endif <|endoftext|>
<commit_before>#include "Globals.h" #include "Application.h" #include "PhysBody3D.h" #include "ModuleCamera3D.h" ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled) { name = "Camera3D"; CalculateViewMatrix(); X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); Position = vec3(0.0f, 0.0f, 5.0f); Reference = vec3(0.0f, 0.0f, 0.0f); } ModuleCamera3D::~ModuleCamera3D() {} // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { LOG("Setting up the camera"); bool ret = true; return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { LOG("Cleaning camera"); return true; } // ----------------------------------------------------------------- update_status ModuleCamera3D::Update(float dt) { vec3 newPos(0,0,0); float speed = 3.0f * dt; if(App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT) speed = 8.0f * dt; if(App->input->GetKey(SDL_SCANCODE_R) == KEY_REPEAT) newPos.y += speed; if(App->input->GetKey(SDL_SCANCODE_F) == KEY_REPEAT) newPos.y -= speed; if(App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed; if(App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed; if(App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed; if(App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed; Position += newPos; Reference += newPos; // Mouse motion ---------------- if(App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { int dx = -App->input->GetMouseXMotion(); int dy = -App->input->GetMouseYMotion(); float Sensitivity = 0.25f; if(dx != 0) { float DeltaX = (float)dx * Sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if(dy != 0) { float DeltaY = (float)dy * Sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); if(Y.y < 0.0f) { Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f); Y = cross(Z, X); } } //Position = Reference + Z * length(Position); } // Recalculate matrix ------------- CalculateViewMatrix(); return UPDATE_CONTINUE; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if(!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt( const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- float* ModuleCamera3D::GetViewMatrix() { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); }<commit_msg>Right Click activates WASD - fps like movement<commit_after>#include "Globals.h" #include "Application.h" #include "PhysBody3D.h" #include "ModuleCamera3D.h" ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, start_enabled) { name = "Camera3D"; CalculateViewMatrix(); X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); Position = vec3(0.0f, 0.0f, 5.0f); Reference = vec3(0.0f, 0.0f, 0.0f); } ModuleCamera3D::~ModuleCamera3D() {} // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { LOG("Setting up the camera"); bool ret = true; return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { LOG("Cleaning camera"); return true; } // ----------------------------------------------------------------- update_status ModuleCamera3D::Update(float dt) { // Mouse motion ---------------- if(App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { vec3 newPos(0, 0, 0); float speed = 3.0f * dt; if (App->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_REPEAT) speed = 8.0f * dt; if (App->input->GetKey(SDL_SCANCODE_R) == KEY_REPEAT) newPos.y += speed; if (App->input->GetKey(SDL_SCANCODE_F) == KEY_REPEAT) newPos.y -= speed; if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) newPos -= Z * speed; if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) newPos += Z * speed; if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) newPos -= X * speed; if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) newPos += X * speed; Position += newPos; Reference += newPos; int dx = -App->input->GetMouseXMotion(); int dy = -App->input->GetMouseYMotion(); float Sensitivity = 0.25f; if(dx != 0) { float DeltaX = (float)dx * Sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if(dy != 0) { float DeltaY = (float)dy * Sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); if(Y.y < 0.0f) { Z = vec3(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f); Y = cross(Z, X); } } //Position = Reference + Z * length(Position); } // Recalculate matrix ------------- CalculateViewMatrix(); return UPDATE_CONTINUE; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if(!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt( const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- float* ModuleCamera3D::GetViewMatrix() { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cancelcommandexecution.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:36:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandFailedException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_ #include <com/sun/star/ucb/XCommandEnvironment.hpp> #endif #ifndef _UCBHELPER_INTERACTIONREQUEST_HXX #include <ucbhelper/interactionrequest.hxx> #endif #ifndef _UCBHELPER_CANCELCOMMANDEXECUTION_HXX_ #include <ucbhelper/cancelcommandexecution.hxx> #endif #ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX #include <ucbhelper/simpleioerrorrequest.hxx> #endif using namespace com::sun::star; namespace ucbhelper { //========================================================================= void cancelCommandExecution( const uno::Any & rException, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( uno::Exception ) { if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { rtl::Reference< ucbhelper::InteractionRequest > xRequest = new ucbhelper::InteractionRequest( rException ); uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations( 1 ); aContinuations[ 0 ] = new ucbhelper::InteractionAbort( xRequest.get() ); xRequest->setContinuations( aContinuations ); xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), uno::Reference< uno::XInterface >(), rException ); } } cppu::throwException( rException ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } #if SUPD < 641 //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const rtl::OUString & rArg, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { uno::Sequence< uno::Any > aArgs( 1 ); aArgs[ 0 ] <<= rArg; rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, aArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const rtl::OUString & rArg1, const rtl::OUString & rArg2, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { uno::Sequence< uno::Any > aArgs( 2 ); aArgs[ 0 ] <<= rArg1; aArgs[ 1 ] <<= rArg2; rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, aArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } #endif // SUPD, 641 //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const uno::Sequence< uno::Any > & rArgs, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, rArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } } <commit_msg>INTEGRATION: CWS pchfix02 (1.11.34); FILE MERGED 2006/09/01 17:56:06 kaib 1.11.34.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cancelcommandexecution.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:20:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_ucbhelper.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _CPPUHELPER_EXC_HLP_HXX_ #include <cppuhelper/exc_hlp.hxx> #endif #ifndef _COM_SUN_STAR_UCB_COMMANDFAILEDEXCEPTION_HPP_ #include <com/sun/star/ucb/CommandFailedException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_ #include <com/sun/star/ucb/XCommandEnvironment.hpp> #endif #ifndef _UCBHELPER_INTERACTIONREQUEST_HXX #include <ucbhelper/interactionrequest.hxx> #endif #ifndef _UCBHELPER_CANCELCOMMANDEXECUTION_HXX_ #include <ucbhelper/cancelcommandexecution.hxx> #endif #ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX #include <ucbhelper/simpleioerrorrequest.hxx> #endif using namespace com::sun::star; namespace ucbhelper { //========================================================================= void cancelCommandExecution( const uno::Any & rException, const uno::Reference< ucb::XCommandEnvironment > & xEnv ) throw( uno::Exception ) { if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { rtl::Reference< ucbhelper::InteractionRequest > xRequest = new ucbhelper::InteractionRequest( rException ); uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations( 1 ); aContinuations[ 0 ] = new ucbhelper::InteractionAbort( xRequest.get() ); xRequest->setContinuations( aContinuations ); xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), uno::Reference< uno::XInterface >(), rException ); } } cppu::throwException( rException ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } #if SUPD < 641 //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const rtl::OUString & rArg, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { uno::Sequence< uno::Any > aArgs( 1 ); aArgs[ 0 ] <<= rArg; rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, aArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const rtl::OUString & rArg1, const rtl::OUString & rArg2, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { uno::Sequence< uno::Any > aArgs( 2 ); aArgs[ 0 ] <<= rArg1; aArgs[ 1 ] <<= rArg2; rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, aArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } #endif // SUPD, 641 //========================================================================= void cancelCommandExecution( const ucb::IOErrorCode eError, const uno::Sequence< uno::Any > & rArgs, const uno::Reference< ucb::XCommandEnvironment > & xEnv, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) throw( uno::Exception ) { rtl::Reference< ucbhelper::SimpleIOErrorRequest > xRequest = new ucbhelper::SimpleIOErrorRequest( eError, rArgs, rMessage, xContext ); if ( xEnv.is() ) { uno::Reference< task::XInteractionHandler > xIH = xEnv->getInteractionHandler(); if ( xIH.is() ) { xIH->handle( xRequest.get() ); rtl::Reference< ucbhelper::InteractionContinuation > xSelection = xRequest->getSelection(); if ( xSelection.is() ) throw ucb::CommandFailedException( rtl::OUString(), xContext, xRequest->getRequest() ); } } cppu::throwException( xRequest->getRequest() ); OSL_ENSURE( sal_False, "Return from cppu::throwException call!!!" ); throw uno::RuntimeException(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: VectorConfidenceConnected.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the confidence connected concept // applied to images with vector pixel types. The confidence connected // algorithm is implemented for vector images in the class // \doxygen{VectorConfidenceConnected}. The basic difference between the // scalar and vector version is that the vector version uses the covariance // matrix instead of a variance, and a vector mean instead of a scalar mean. // The membership of a vector pixel value to the region is measured using the // Mahalanobis distance as implemented in the class // \subdoxygen{Statistics}{MahalanobisDistanceThresholdImageFunction}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkVectorConfidenceConnectedImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRGBPixel.h" int main( int argc, char *argv[] ) { if( argc < 7 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage outputImage seedX seedY multiplier iterations" << std::endl; return 1; } // Software Guide : BeginLatex // // We now define the image type using a particular pixel type and // dimension. In this case the \code{float} type is used for the pixels // due to the requirements of the smoothing filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char PixelComponentType; typedef itk::RGBPixel< PixelComponentType > InputPixelType; const unsigned int Dimension = 2; typedef itk::Image< InputPixelType, Dimension > InputImageType; // Software Guide : EndCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // We instantiate reader and writer types // typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); // Software Guide : BeginLatex // // We now declare the type of the region growing filter. In this case it // is the \doxygen{VectorConfidenceConnectedImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::VectorConfidenceConnectedImageFilter< InputImageType, OutputImageType > ConnectedFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, we construct one filter of this class using the \code{New()} // method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we create a simple, linear data processing pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetInput( reader->GetOutput() ); writer->SetInput( confidenceConnected->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The VectorConfidenceConnectedImageFilter requires specifying two // parameters. First, the multiplier factor $f$ defines how large the // range of intensities will be. Small values of the multiplier will // restrict the inclusion of pixels to those having similar intensities to // those already in the current region. Larger values of the multiplier // relax the accepting condition and result in more generous growth of the // region. Values that are too large will cause the region to grow into // neighboring regions that may actually belong to separate anatomical // structures. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetMultiplier()} // // Software Guide : EndLatex const double multiplier = atof( argv[5] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetMultiplier( multiplier ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The number of iterations is typically determined based on the // homogeneity of the image intensity representing the anatomical // structure to be segmented. Highly homogeneous regions may only require // a couple of iterations. Regions with ramp effects, like MRI images with // inhomogenous fields, may require more iterations. In practice, it seems // to be more relevant to carefully select the multiplier factor than the // number of iterations. However, keep in mind that there is no reason to // assume that this algorithm should converge to a stable region. It is // possible that by letting the algorithm run for more iterations the // region will end up engulfing the entire image. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetNumberOfIterations()} // // Software Guide : EndLatex const unsigned int iterations = atoi( argv[6] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetNumberOfIterations( iterations ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output of this filter is a binary image with zero-value pixels // everywhere except on the extracted region. The intensity value to be // put inside the region is selected with the method // \code{SetReplaceValue()} // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetReplaceValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetReplaceValue( 255 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The initialization of the algorithm requires the user to provide a seed // point. This point should be placed in a \emph{typical} region of the // anatomical structure to be segmented. A small neighborhood around the // seed point will be used to compute the initial mean and standard // deviation for the inclusion criterion. The seed is passed in the form // of a \doxygen{Index} to the \code{SetSeed()} method. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetSeed()} // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetInitialNeighborhoodRadius()} // // Software Guide : EndLatex InputImageType::IndexType index; index[0] = atoi( argv[3] ); index[1] = atoi( argv[4] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetSeed( index ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The size of the initial neighborhood around the seed is defined with the // method \code{SetInitialNeighborhoodRadius()}. The neighborhood will be // defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on // the side, where $r$ is the value passed as initial neighborhood radius. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetInitialNeighborhoodRadius( 3 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is usually wise to put update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now let's run this example using as input the image // \code{VisibleWomanEyeSlice.png} provided in the directory // \code{Examples/Data}. We can easily segment the major anatomical // structures by providing seeds in the appropriate locations. For example, // // \begin{center} // \begin{tabular}{|l|c|c|c|c|} // \hline // Structure & Seed Index & Multiplier & Iterations & Output Image \\ \hline // Rectum & $(70,120)$ & 7 & 1 & Second from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // Rectum & $(23, 93)$ & 7 & 1 & Third from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // Vitreo & $(66, 66)$ & 3 & 1 & Fourth from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // \end{tabular} // \end{center} // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{VisibleWomanEyeSlice.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput1.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput2.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput3.eps} // \itkcaption[VectorConfidenceConnected segmentation results]{Segmentation results of // the VectorConfidenceConnected filter for various seed points.} // \label{fig:VectorConfidenceConnectedOutput} // \end{figure} // // The coloration of muscular tissue makes it easy to distinguish them from // the surrounding anatomical strucures. The optic vitrea on the other hand // has a coloration that is not very homogeneous inside the eyeball and // does not allow to generate a full segmentation based only on color. // // Software Guide : EndLatex return 0; } <commit_msg>ENH: Print out of the mean vector and covariance matrix added.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: VectorConfidenceConnected.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the confidence connected concept // applied to images with vector pixel types. The confidence connected // algorithm is implemented for vector images in the class // \doxygen{VectorConfidenceConnected}. The basic difference between the // scalar and vector version is that the vector version uses the covariance // matrix instead of a variance, and a vector mean instead of a scalar mean. // The membership of a vector pixel value to the region is measured using the // Mahalanobis distance as implemented in the class // \subdoxygen{Statistics}{MahalanobisDistanceThresholdImageFunction}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkVectorConfidenceConnectedImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRGBPixel.h" int main( int argc, char *argv[] ) { if( argc < 7 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " inputImage outputImage seedX seedY multiplier iterations" << std::endl; return 1; } // Software Guide : BeginLatex // // We now define the image type using a particular pixel type and // dimension. In this case the \code{float} type is used for the pixels // due to the requirements of the smoothing filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char PixelComponentType; typedef itk::RGBPixel< PixelComponentType > InputPixelType; const unsigned int Dimension = 2; typedef itk::Image< InputPixelType, Dimension > InputImageType; // Software Guide : EndCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; // We instantiate reader and writer types // typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName( argv[1] ); writer->SetFileName( argv[2] ); // Software Guide : BeginLatex // // We now declare the type of the region growing filter. In this case it // is the \doxygen{VectorConfidenceConnectedImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::VectorConfidenceConnectedImageFilter< InputImageType, OutputImageType > ConnectedFilterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, we construct one filter of this class using the \code{New()} // method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ConnectedFilterType::Pointer confidenceConnected = ConnectedFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next we create a simple, linear data processing pipeline. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetInput( reader->GetOutput() ); writer->SetInput( confidenceConnected->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The VectorConfidenceConnectedImageFilter requires specifying two // parameters. First, the multiplier factor $f$ defines how large the // range of intensities will be. Small values of the multiplier will // restrict the inclusion of pixels to those having similar intensities to // those already in the current region. Larger values of the multiplier // relax the accepting condition and result in more generous growth of the // region. Values that are too large will cause the region to grow into // neighboring regions that may actually belong to separate anatomical // structures. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetMultiplier()} // // Software Guide : EndLatex const double multiplier = atof( argv[5] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetMultiplier( multiplier ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The number of iterations is typically determined based on the // homogeneity of the image intensity representing the anatomical // structure to be segmented. Highly homogeneous regions may only require // a couple of iterations. Regions with ramp effects, like MRI images with // inhomogenous fields, may require more iterations. In practice, it seems // to be more relevant to carefully select the multiplier factor than the // number of iterations. However, keep in mind that there is no reason to // assume that this algorithm should converge to a stable region. It is // possible that by letting the algorithm run for more iterations the // region will end up engulfing the entire image. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetNumberOfIterations()} // // Software Guide : EndLatex const unsigned int iterations = atoi( argv[6] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetNumberOfIterations( iterations ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output of this filter is a binary image with zero-value pixels // everywhere except on the extracted region. The intensity value to be // put inside the region is selected with the method // \code{SetReplaceValue()} // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetReplaceValue()} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetReplaceValue( 255 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The initialization of the algorithm requires the user to provide a seed // point. This point should be placed in a \emph{typical} region of the // anatomical structure to be segmented. A small neighborhood around the // seed point will be used to compute the initial mean and standard // deviation for the inclusion criterion. The seed is passed in the form // of a \doxygen{Index} to the \code{SetSeed()} method. // // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetSeed()} // \index{itk::Vector\-Confidence\-Connected\-Image\-Filter!SetInitialNeighborhoodRadius()} // // Software Guide : EndLatex InputImageType::IndexType index; index[0] = atoi( argv[3] ); index[1] = atoi( argv[4] ); // Software Guide : BeginCodeSnippet confidenceConnected->SetSeed( index ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The size of the initial neighborhood around the seed is defined with the // method \code{SetInitialNeighborhoodRadius()}. The neighborhood will be // defined as an $N$-Dimensional rectangular region with $2r+1$ pixels on // the side, where $r$ is the value passed as initial neighborhood radius. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet confidenceConnected->SetInitialNeighborhoodRadius( 3 ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is usually wise to put update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now let's run this example using as input the image // \code{VisibleWomanEyeSlice.png} provided in the directory // \code{Examples/Data}. We can easily segment the major anatomical // structures by providing seeds in the appropriate locations. For example, // // \begin{center} // \begin{tabular}{|l|c|c|c|c|} // \hline // Structure & Seed Index & Multiplier & Iterations & Output Image \\ \hline // Rectum & $(70,120)$ & 7 & 1 & Second from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // Rectum & $(23, 93)$ & 7 & 1 & Third from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // Vitreo & $(66, 66)$ & 3 & 1 & Fourth from left in Figure \ref{fig:VectorConfidenceConnectedOutput} \\ \hline // \end{tabular} // \end{center} // // \begin{figure} \center // \includegraphics[width=0.24\textwidth]{VisibleWomanEyeSlice.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput1.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput2.eps} // \includegraphics[width=0.24\textwidth]{VectorConfidenceConnectedOutput3.eps} // \itkcaption[VectorConfidenceConnected segmentation results]{Segmentation results of // the VectorConfidenceConnected filter for various seed points.} // \label{fig:VectorConfidenceConnectedOutput} // \end{figure} // // The coloration of muscular tissue makes it easy to distinguish them from // the surrounding anatomical strucures. The optic vitrea on the other hand // has a coloration that is not very homogeneous inside the eyeball and // does not allow to generate a full segmentation based only on color. // // Software Guide : EndLatex // Software Guide : BeginLatex // // The values of the final mean vector and covariance matrix used for the // last iteration can be queried using the methods \code{GetMean()} and // \code{GetCovariance()}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef ConnectedFilterType::MeanVectorType MeanVectorType; const MeanVectorType & mean = confidenceConnected->GetMean(); std::cout << "Mean vector = " << std::endl; std::cout << mean << std::endl; typedef ConnectedFilterType::CovarianceMatrixType CovarianceMatrixType; const CovarianceMatrixType & covariance = confidenceConnected->GetCovariance(); std::cout << "Covariance matrix = " << std::endl; std::cout << covariance << std::endl; // Software Guide : EndCodeSnippet return 0; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning(4:4786) #endif // interface header #include "Bundle.h" // system headers #include <fstream> #include <stdio.h> // local implementation headers #include "StateDatabase.h" #include "AnsiCodes.h" Bundle::Bundle(const Bundle *pBundle) { if (pBundle == NULL) return; mappings = pBundle->mappings; } void Bundle::load(const std::string &path) { std::string untranslated; std::string translated; char buffer[1024]; std::ifstream poStrm(path.c_str()); if (!poStrm.good()) return; poStrm.getline(buffer,1024); while (poStrm.good()) { std::string line = buffer; std::string data; TLineType type = parseLine(line, data); if (type == tMSGID) { if (untranslated.length() > 0) { mappings.erase(untranslated); ensureNormalText(translated); mappings.insert(std::pair<std::string,std::string>(untranslated, translated)); } untranslated = data; translated.resize(0); } else if (type == tMSGSTR) { if (untranslated.length() > 0) translated = data; } else if (type == tAPPEND) { if (untranslated.length() > 0) translated += data; } else if (type == tERROR) { } poStrm.getline(buffer,1024); } if ((untranslated.length() > 0) && (translated.length() > 0)) { mappings.erase(untranslated); ensureNormalText(translated); mappings.insert(std::pair<std::string,std::string>(untranslated, translated)); } } Bundle::TLineType Bundle::parseLine(const std::string &line, std::string &data) const { int startPos, endPos; TLineType type; data.resize(0); startPos = line.find_first_not_of("\t \r\n"); if ((startPos < 0) || (line.at(startPos) == '#')) return tCOMMENT; else if (line.at(startPos) == '"') { endPos = line.find_first_of('"', startPos+1); if (endPos < 0) endPos = line.length(); data = line.substr(startPos+1, endPos-startPos-1); return tAPPEND; } endPos = line.find_first_of("\t \r\n\""); if (endPos < 0) endPos = line.length(); std::string key = line.substr(startPos, endPos-startPos); if (key == "msgid") type = tMSGID; else if (key == "msgstr") type = tMSGSTR; else return tERROR; startPos = line.find_first_of('"', endPos + 1); if (startPos >= 0) { startPos++; endPos = line.find_first_of('"', startPos); if (endPos < 0) endPos = line.length(); data = line.substr( startPos, endPos-startPos); } return type; } #include <set> static std::set<std::string> unmapped; std::string Bundle::getLocalString(const std::string &key) const { if (key == "") return key; BundleStringMap::const_iterator it = mappings.find(key); if (it != mappings.end()) { return it->second; } else { if (BZDB.getDebug()) { if (unmapped.find( key ) == unmapped.end( )) { unmapped.insert( key ); std::string stripped = stripAnsiCodes (key); std::string debugStr = "Unmapped Locale String: " + stripped + "\n"; DEBUG1("%s", debugStr.c_str()); } } return key; } } void Bundle::ensureNormalText(std::string &msg) { // This is an ugly hack. If you don't like it fix it. // BZFlag's font bitmaps don't contain letters with accents, so strip them here // Would be nice if some kind sole added them. for (std::string::size_type i = 0; i < msg.length(); i++) { char c = msg.at(i); switch (c) { case '': case '': case '': case '': case '': case '': msg[i] = 'a'; break; case '': msg[i] = 'a'; i++; msg.insert(i, 1, 'a'); break; case '': case '': msg[i] = 'a'; i++; msg.insert(i, 1, 'e'); break; case '': case '': case '': msg[i] = 'A'; break; case '': case '': msg[i] = 'A'; i++; msg.insert(i, 1, 'e'); break; case '': msg[i] = 'A'; i++; msg.insert(i, 1, 'a'); break; case '': msg[i] = 'c'; break; case '': case '': case '': case '': msg[i] = 'e'; break; case '': case '': case '': case '': msg[i] = 'i'; break; case '': case '': case '': case '': msg[i] = 'o'; break; case '': case '': msg[i] = 'o'; i++; msg.insert(i, 1, 'e'); break; case '': msg[i] = 'O'; break; case '': case '': msg[i] = 'O'; i++; msg.insert(i, 1, 'e'); break; case '': case '': case '': msg[i] = 'u'; break; case '': msg[i] = 'u'; i++; msg.insert(i, 1, 'e'); break; case '': msg[i] = 'U'; i++; msg.insert(i, 1, 'e'); break; case '': msg[i] = 'n'; break; case '': msg[i] = 'Y'; break; case '': msg[i] = 's'; i++; msg.insert(i, 1, 's'); break; case '': case '': msg[i] = ' '; break; default: // A temporary patch, to catch untranslated chars.. To be removed eventually if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) || (c == '}') || (c == '{') || (c == ' ') || (c == ':') || (c == '/') || (c == '-') || (c == ',') || (c == '&') || (c == '?') || (c == '<') || (c == '>') || (c == '.') || (c == '(') || (c == ')') || (c == '%') || (c == '!') || (c == '+') || (c == '-') || (c == '$') || (c == ';') || (c == '@') || (c == '[') || (c == ']') || (c == '=') || (c == '\'')) ; else { msg = std::string("unsupported char:") + c; return; } break; } } } std::string Bundle::formatMessage(const std::string &key, const std::vector<std::string> *parms) const { std::string messageIn = getLocalString(key); std::string messageOut; if (!parms || (parms->size() == 0)) return messageIn; int parmCnt = parms->size(); int startPos = 0; int lCurlyPos = messageIn.find_first_of("{"); while (lCurlyPos >= 0) { messageOut += messageIn.substr( startPos, lCurlyPos - startPos); int rCurlyPos = messageIn.find_first_of("}", lCurlyPos++); if (rCurlyPos < 0) { messageOut += messageIn.substr(lCurlyPos); return messageOut; } std::string numStr = messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos); int num; if (sscanf(numStr.c_str(), "%d", &num) != 1) messageOut += messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos); else { num--; if ((num >= 0) && (num < parmCnt)) messageOut += (*parms)[num]; } startPos = rCurlyPos+1; lCurlyPos = messageIn.find_first_of("{", startPos); } messageOut += messageIn.substr(startPos); return messageOut; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>utf8<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _MSC_VER #pragma warning(4:4786) #endif // interface header #include "Bundle.h" // system headers #include <fstream> #include <stdio.h> // local implementation headers #include "StateDatabase.h" #include "AnsiCodes.h" Bundle::Bundle(const Bundle *pBundle) { if (pBundle == NULL) return; mappings = pBundle->mappings; } void Bundle::load(const std::string &path) { std::string untranslated; std::string translated; char buffer[1024]; std::ifstream poStrm(path.c_str()); if (!poStrm.good()) return; poStrm.getline(buffer,1024); while (poStrm.good()) { std::string line = buffer; std::string data; TLineType type = parseLine(line, data); if (type == tMSGID) { if (untranslated.length() > 0) { mappings.erase(untranslated); ensureNormalText(translated); mappings.insert(std::pair<std::string,std::string>(untranslated, translated)); } untranslated = data; translated.resize(0); } else if (type == tMSGSTR) { if (untranslated.length() > 0) translated = data; } else if (type == tAPPEND) { if (untranslated.length() > 0) translated += data; } else if (type == tERROR) { } poStrm.getline(buffer,1024); } if ((untranslated.length() > 0) && (translated.length() > 0)) { mappings.erase(untranslated); ensureNormalText(translated); mappings.insert(std::pair<std::string,std::string>(untranslated, translated)); } } Bundle::TLineType Bundle::parseLine(const std::string &line, std::string &data) const { int startPos, endPos; TLineType type; data.resize(0); startPos = line.find_first_not_of("\t \r\n"); if ((startPos < 0) || (line.at(startPos) == '#')) return tCOMMENT; else if (line.at(startPos) == '"') { endPos = line.find_first_of('"', startPos+1); if (endPos < 0) endPos = line.length(); data = line.substr(startPos+1, endPos-startPos-1); return tAPPEND; } endPos = line.find_first_of("\t \r\n\""); if (endPos < 0) endPos = line.length(); std::string key = line.substr(startPos, endPos-startPos); if (key == "msgid") type = tMSGID; else if (key == "msgstr") type = tMSGSTR; else return tERROR; startPos = line.find_first_of('"', endPos + 1); if (startPos >= 0) { startPos++; endPos = line.find_first_of('"', startPos); if (endPos < 0) endPos = line.length(); data = line.substr( startPos, endPos-startPos); } return type; } #include <set> static std::set<std::string> unmapped; std::string Bundle::getLocalString(const std::string &key) const { if (key == "") return key; BundleStringMap::const_iterator it = mappings.find(key); if (it != mappings.end()) { return it->second; } else { if (BZDB.getDebug()) { if (unmapped.find( key ) == unmapped.end( )) { unmapped.insert( key ); std::string stripped = stripAnsiCodes (key); std::string debugStr = "Unmapped Locale String: " + stripped + "\n"; DEBUG1("%s", debugStr.c_str()); } } return key; } } const char utf8bytes[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,5,5,5,5,6,6,6,6 }; #if 0 // TODO: find the utf-8 values for these switch (c) { case 'Œ': case 'Š': msg[i] = 'a'; break; case '': case '€': msg[i] = 'A'; break; case '†': msg[i] = 'i'; break; case 'š': msg[i] = 'o'; break; case '…': msg[i] = 'O'; break; case 'Ÿ': msg[i] = 'Y'; break; } #endif // TODO: sort this and bsearch it. perhaps divided by utf8 length const char *translationTable[][2] = { {"â", "a"}, {"à", "a"}, {"á", "a"}, {"ã", "a"}, {"å", "aa"}, {"ä", "ae"}, {"æ", "ae"}, {"Â", "A"}, {"Ä", "AE"}, {"Æ", "AE"}, {"Å", "AA"}, {"ç", "c"}, {"é", "e"}, {"è", "e"}, {"ê", "e"}, {"ë", "e"}, {"î", "i"}, {"ï", "i"}, {"í", "i"}, {"ô", "o"}, {"ó", "o"}, {"õ", "o"}, {"ö", "oe"}, {"ø", "oe"}, {"Ö", "OE"}, {"Ø", "OE"}, {"û", "u"}, {"ù", "u"}, {"ú", "u"}, {"ü", "ue"}, {"Ü", "UE"}, {"ñ", "n"}, {"ß", "ss"}, {"¿", "?"}, {"¡", "!"}, }; void Bundle::ensureNormalText(std::string &msg) { // BZFlag's font system only supports ascii // convert msg to ascii // If you don't like it fix it. for (std::string::size_type i = 0; i < msg.length(); i++) { unsigned char c = msg.at(i); if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) || (c == '}') || (c == '{') || (c == ' ') || (c == ':') || (c == '/') || (c == '-') || (c == ',') || (c == '&') || (c == '?') || (c == '<') || (c == '>') || (c == '.') || (c == '(') || (c == ')') || (c == '%') || (c == '!') || (c == '+') || (c == '-') || (c == '$') || (c == ';') || (c == '@') || (c == '[') || (c == ']') || (c == '=') || (c == '\'')) { ; // this char's ok by me } else { std::string replacement = "0x"; unsigned int trans; // TODO: optimize this for (trans = 0; trans < sizeof(translationTable) / sizeof (char *) / 2; trans++) { if (!strncmp(translationTable[trans][0],&(msg.c_str()[i]),utf8bytes[(int)c])) { replacement = translationTable[trans][1]; break; } } if (trans == sizeof(translationTable) / sizeof (char *) / 2) { // didn't find a match for (int j = 0; j < utf8bytes[(int)c]; j++) { //for (int j = 0; j < 1; j++) { char hexchar[30]; sprintf(hexchar, "%2X", (unsigned char)msg.at(i+j)); replacement += hexchar; } } msg.replace(i,utf8bytes[(int)c],replacement); i += replacement.length() - 1; } } //std::cout << "\"" + msg + "\"\n"; } std::string Bundle::formatMessage(const std::string &key, const std::vector<std::string> *parms) const { std::string messageIn = getLocalString(key); std::string messageOut; if (!parms || (parms->size() == 0)) return messageIn; int parmCnt = parms->size(); int startPos = 0; int lCurlyPos = messageIn.find_first_of("{"); while (lCurlyPos >= 0) { messageOut += messageIn.substr( startPos, lCurlyPos - startPos); int rCurlyPos = messageIn.find_first_of("}", lCurlyPos++); if (rCurlyPos < 0) { messageOut += messageIn.substr(lCurlyPos); return messageOut; } std::string numStr = messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos); int num; if (sscanf(numStr.c_str(), "%d", &num) != 1) messageOut += messageIn.substr(lCurlyPos, rCurlyPos-lCurlyPos); else { num--; if ((num >= 0) && (num < parmCnt)) messageOut += (*parms)[num]; } startPos = rCurlyPos+1; lCurlyPos = messageIn.find_first_of("{", startPos); } messageOut += messageIn.substr(startPos); return messageOut; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#ifndef PIXELBOOST_DISABLE_GRAPHICS #include <algorithm> #include <set> #include "pixelboost/graphics/camera/camera.h" #include "pixelboost/graphics/camera/viewport.h" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/effect/effect.h" #include "pixelboost/graphics/effect/manager.h" #include "pixelboost/graphics/renderer/common/irenderer.h" #include "pixelboost/graphics/renderer/common/renderable.h" #include "pixelboost/graphics/renderer/common/renderer.h" using namespace pb; Renderer* Renderer::Renderer::_Instance = 0; Renderer::Renderer() { _Instance = this; _EffectManager = new EffectManager(); } Renderer::~Renderer() { _Instance = 0; } Renderer* Renderer::Instance() { return _Instance; } void Renderer::Render() { for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it) { (*it)->Render(); FlushBuffer(*it); } } EffectManager* Renderer::GetEffectManager() { return _EffectManager; } void Renderer::AttachRenderable(Renderable* renderable) { _Renderables[renderable->GetLayer()].push_back(renderable); } void Renderer::AddViewport(Viewport* viewport) { _Viewports.push_back(viewport); } void Renderer::RemoveViewport(Viewport* viewport) { for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it) { if (*it == viewport) { _Viewports.erase(it); return; } } } void Renderer::SetHandler(int renderableType, IRenderer* renderer) { _RenderableHandlers[renderableType] = renderer; } bool RenderableSorter(const Renderable* a, const Renderable* b) { return a->GetMVP()[3][2] < b->GetMVP()[3][2]; } void Renderer::FlushBuffer(Viewport* viewport) { for (int i=0; i<16; i++) { RenderableList& renderables = _Renderables[i]; if (!renderables.size()) continue; for (RenderableList::iterator it = renderables.begin(); it != renderables.end(); ++it) { (*it)->CalculateMVP(viewport); } std::stable_sort(renderables.begin(), renderables.end(), &RenderableSorter); Uid type = renderables[0]->GetRenderableType(); Effect* effect = renderables[0]->GetEffect(); int start = 0; int count = 0; for (int i=0; i < renderables.size(); i++) { Uid newType = renderables[i]->GetRenderableType(); Effect* newEffect = renderables[i]->GetEffect(); if (type == newType && effect == newEffect) { count++; } else { RenderBatch(viewport, count, &renderables[start], effect); start = i; count = 1; type = newType; effect = newEffect; } } if (count > 0) { RenderBatch(viewport, count, &renderables[start], effect); } } _Renderables.clear(); } void Renderer::RenderBatch(Viewport* viewport, int count, Renderable** renderable, Effect* effect) { if (!effect) return; RenderableHandlerMap::iterator it = _RenderableHandlers.find(renderable[0]->GetRenderableType()); if (it != _RenderableHandlers.end()) { EffectTechnique* technique = effect->GetTechnique(viewport->GetRenderScheme()); if (!technique) { for (int i=0; i < count; i++) { technique = viewport->GetTechnique(renderable[i], effect); if (technique) { for (int j=0; j<technique->GetNumPasses(); j++) { EffectPass* pass = technique->GetPass(j); pass->Bind(); it->second->Render(1, &renderable[i], viewport, pass); } } } } else { for (int i=0; i<technique->GetNumPasses(); i++) { EffectPass* pass = technique->GetPass(i); pass->Bind(); it->second->Render(count, renderable, viewport, pass); } } } } #endif <commit_msg>Reverse depth sort<commit_after>#ifndef PIXELBOOST_DISABLE_GRAPHICS #include <algorithm> #include <set> #include "pixelboost/graphics/camera/camera.h" #include "pixelboost/graphics/camera/viewport.h" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/effect/effect.h" #include "pixelboost/graphics/effect/manager.h" #include "pixelboost/graphics/renderer/common/irenderer.h" #include "pixelboost/graphics/renderer/common/renderable.h" #include "pixelboost/graphics/renderer/common/renderer.h" using namespace pb; Renderer* Renderer::Renderer::_Instance = 0; Renderer::Renderer() { _Instance = this; _EffectManager = new EffectManager(); } Renderer::~Renderer() { _Instance = 0; } Renderer* Renderer::Instance() { return _Instance; } void Renderer::Render() { for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it) { (*it)->Render(); FlushBuffer(*it); } } EffectManager* Renderer::GetEffectManager() { return _EffectManager; } void Renderer::AttachRenderable(Renderable* renderable) { _Renderables[renderable->GetLayer()].push_back(renderable); } void Renderer::AddViewport(Viewport* viewport) { _Viewports.push_back(viewport); } void Renderer::RemoveViewport(Viewport* viewport) { for (ViewportList::iterator it = _Viewports.begin(); it != _Viewports.end(); ++it) { if (*it == viewport) { _Viewports.erase(it); return; } } } void Renderer::SetHandler(int renderableType, IRenderer* renderer) { _RenderableHandlers[renderableType] = renderer; } bool RenderableBackToFrontSorter(const Renderable* a, const Renderable* b) { return a->GetMVP()[3][2] > b->GetMVP()[3][2]; } void Renderer::FlushBuffer(Viewport* viewport) { for (int i=0; i<16; i++) { RenderableList& renderables = _Renderables[i]; if (!renderables.size()) continue; for (RenderableList::iterator it = renderables.begin(); it != renderables.end(); ++it) { (*it)->CalculateMVP(viewport); } std::stable_sort(renderables.begin(), renderables.end(), &RenderableBackToFrontSorter); Uid type = renderables[0]->GetRenderableType(); Effect* effect = renderables[0]->GetEffect(); int start = 0; int count = 0; for (int i=0; i < renderables.size(); i++) { Uid newType = renderables[i]->GetRenderableType(); Effect* newEffect = renderables[i]->GetEffect(); if (type == newType && effect == newEffect) { count++; } else { RenderBatch(viewport, count, &renderables[start], effect); start = i; count = 1; type = newType; effect = newEffect; } } if (count > 0) { RenderBatch(viewport, count, &renderables[start], effect); } } _Renderables.clear(); } void Renderer::RenderBatch(Viewport* viewport, int count, Renderable** renderable, Effect* effect) { if (!effect) return; RenderableHandlerMap::iterator it = _RenderableHandlers.find(renderable[0]->GetRenderableType()); if (it != _RenderableHandlers.end()) { EffectTechnique* technique = effect->GetTechnique(viewport->GetRenderScheme()); if (!technique) { for (int i=0; i < count; i++) { technique = viewport->GetTechnique(renderable[i], effect); if (technique) { for (int j=0; j<technique->GetNumPasses(); j++) { EffectPass* pass = technique->GetPass(j); pass->Bind(); it->second->Render(1, &renderable[i], viewport, pass); } } } } else { for (int i=0; i<technique->GetNumPasses(); i++) { EffectPass* pass = technique->GetPass(i); pass->Bind(); it->second->Render(count, renderable, viewport, pass); } } } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_ui_manager.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/stl_util-inl.h" #include "chrome/browser/notifications/balloon_collection.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" // A class which represents a notification waiting to be shown. class QueuedNotification { public: QueuedNotification(const Notification& notification, Profile* profile) : notification_(notification), profile_(profile) { } const Notification& notification() const { return notification_; } Profile* profile() const { return profile_; } void Replace(const Notification& new_notification) { notification_ = new_notification; } private: // The notification to be shown. Notification notification_; // Non owned pointer to the user's profile. Profile* profile_; DISALLOW_COPY_AND_ASSIGN(QueuedNotification); }; NotificationUIManager::NotificationUIManager() : balloon_collection_(NULL) { registrar_.Add(this, NotificationType::APP_TERMINATING, NotificationService::AllSources()); } NotificationUIManager::~NotificationUIManager() { STLDeleteElements(&show_queue_); } // static NotificationUIManager* NotificationUIManager::Create() { BalloonCollection* balloons = BalloonCollection::Create(); NotificationUIManager* instance = new NotificationUIManager(); instance->Initialize(balloons); balloons->set_space_change_listener(instance); return instance; } void NotificationUIManager::Add(const Notification& notification, Profile* profile) { if (TryReplacement(notification)) { return; } VLOG(1) << "Added notification. URL: " << notification.content_url().spec(); show_queue_.push_back( new QueuedNotification(notification, profile)); CheckAndShowNotifications(); } bool NotificationUIManager::CancelById(const std::string& id) { // See if this ID hasn't been shown yet. NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end(); ++iter) { if ((*iter)->notification().notification_id() == id) { show_queue_.erase(iter); return true; } } // If it has been shown, remove it from the balloon collections. return balloon_collection_->RemoveById(id); } bool NotificationUIManager::CancelAllBySourceOrigin(const GURL& source) { // Same pattern as CancelById, but more complicated than the above // because there may be multiple notifications from the same source. bool removed = false; NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end(); ++iter) { if ((*iter)->notification().origin_url() == source) { iter = show_queue_.erase(iter); removed = true; } else { ++iter; } } return balloon_collection_->RemoveBySourceOrigin(source) || removed; } void NotificationUIManager::CancelAll() { STLDeleteElements(&show_queue_); balloon_collection_->RemoveAll(); } void NotificationUIManager::CheckAndShowNotifications() { // TODO(johnnyg): http://crbug.com/25061 - Check for user idle/presentation. ShowNotifications(); } void NotificationUIManager::ShowNotifications() { while (!show_queue_.empty() && balloon_collection_->HasSpace()) { scoped_ptr<QueuedNotification> queued_notification(show_queue_.front()); show_queue_.pop_front(); balloon_collection_->Add(queued_notification->notification(), queued_notification->profile()); } } void NotificationUIManager::OnBalloonSpaceChanged() { CheckAndShowNotifications(); } bool NotificationUIManager::TryReplacement(const Notification& notification) { const GURL& origin = notification.origin_url(); const string16& replace_id = notification.replace_id(); if (replace_id.empty()) return false; // First check the queue of pending notifications for replacement. // Then check the list of notifications already being shown. NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end(); ++iter) { if (origin == (*iter)->notification().origin_url() && replace_id == (*iter)->notification().replace_id()) { (*iter)->Replace(notification); return true; } } BalloonCollection::Balloons::iterator balloon_iter; BalloonCollection::Balloons balloons = balloon_collection_->GetActiveBalloons(); for (balloon_iter = balloons.begin(); balloon_iter != balloons.end(); ++balloon_iter) { if (origin == (*balloon_iter)->notification().origin_url() && replace_id == (*balloon_iter)->notification().replace_id()) { (*balloon_iter)->Update(notification); return true; } } return false; } void NotificationUIManager::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::APP_TERMINATING) CancelAll(); else NOTREACHED(); } <commit_msg>Stray ++ causes crashes. Don't walk off the end of the array.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/notification_ui_manager.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/stl_util-inl.h" #include "chrome/browser/notifications/balloon_collection.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" // A class which represents a notification waiting to be shown. class QueuedNotification { public: QueuedNotification(const Notification& notification, Profile* profile) : notification_(notification), profile_(profile) { } const Notification& notification() const { return notification_; } Profile* profile() const { return profile_; } void Replace(const Notification& new_notification) { notification_ = new_notification; } private: // The notification to be shown. Notification notification_; // Non owned pointer to the user's profile. Profile* profile_; DISALLOW_COPY_AND_ASSIGN(QueuedNotification); }; NotificationUIManager::NotificationUIManager() : balloon_collection_(NULL) { registrar_.Add(this, NotificationType::APP_TERMINATING, NotificationService::AllSources()); } NotificationUIManager::~NotificationUIManager() { STLDeleteElements(&show_queue_); } // static NotificationUIManager* NotificationUIManager::Create() { BalloonCollection* balloons = BalloonCollection::Create(); NotificationUIManager* instance = new NotificationUIManager(); instance->Initialize(balloons); balloons->set_space_change_listener(instance); return instance; } void NotificationUIManager::Add(const Notification& notification, Profile* profile) { if (TryReplacement(notification)) { return; } VLOG(1) << "Added notification. URL: " << notification.content_url().spec(); show_queue_.push_back( new QueuedNotification(notification, profile)); CheckAndShowNotifications(); } bool NotificationUIManager::CancelById(const std::string& id) { // See if this ID hasn't been shown yet. NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end(); ++iter) { if ((*iter)->notification().notification_id() == id) { show_queue_.erase(iter); return true; } } // If it has been shown, remove it from the balloon collections. return balloon_collection_->RemoveById(id); } bool NotificationUIManager::CancelAllBySourceOrigin(const GURL& source) { // Same pattern as CancelById, but more complicated than the above // because there may be multiple notifications from the same source. bool removed = false; NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end();) { if ((*iter)->notification().origin_url() == source) { iter = show_queue_.erase(iter); removed = true; } else { ++iter; } } return balloon_collection_->RemoveBySourceOrigin(source) || removed; } void NotificationUIManager::CancelAll() { STLDeleteElements(&show_queue_); balloon_collection_->RemoveAll(); } void NotificationUIManager::CheckAndShowNotifications() { // TODO(johnnyg): http://crbug.com/25061 - Check for user idle/presentation. ShowNotifications(); } void NotificationUIManager::ShowNotifications() { while (!show_queue_.empty() && balloon_collection_->HasSpace()) { scoped_ptr<QueuedNotification> queued_notification(show_queue_.front()); show_queue_.pop_front(); balloon_collection_->Add(queued_notification->notification(), queued_notification->profile()); } } void NotificationUIManager::OnBalloonSpaceChanged() { CheckAndShowNotifications(); } bool NotificationUIManager::TryReplacement(const Notification& notification) { const GURL& origin = notification.origin_url(); const string16& replace_id = notification.replace_id(); if (replace_id.empty()) return false; // First check the queue of pending notifications for replacement. // Then check the list of notifications already being shown. NotificationDeque::iterator iter; for (iter = show_queue_.begin(); iter != show_queue_.end(); ++iter) { if (origin == (*iter)->notification().origin_url() && replace_id == (*iter)->notification().replace_id()) { (*iter)->Replace(notification); return true; } } BalloonCollection::Balloons::iterator balloon_iter; BalloonCollection::Balloons balloons = balloon_collection_->GetActiveBalloons(); for (balloon_iter = balloons.begin(); balloon_iter != balloons.end(); ++balloon_iter) { if (origin == (*balloon_iter)->notification().origin_url() && replace_id == (*balloon_iter)->notification().replace_id()) { (*balloon_iter)->Update(notification); return true; } } return false; } void NotificationUIManager::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::APP_TERMINATING) CancelAll(); else NOTREACHED(); } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved." #ident "$Id$" // Test to make sure nothing crashes if the backup source directory has unreadable permissions. #include <errno.h> #include "backup_test_helpers.h" volatile bool saw_error = false; static void expect_eacces_error_fun(int error_number, const char *error_string, void *backup_extra __attribute__((unused))) { fprintf(stderr, "EXPECT ERROR %d: %d (%s)\n", EACCES, error_number, error_string); check(error_number==EACCES); saw_error = true; } int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) { char *src = get_src(); char *dst = get_dst(); { int r = systemf("chmod ugo+rwx %s", src); check(r==0); } setup_source(); setup_destination(); setup_dirs(); { int r = systemf("chmod ugo-r %s", src); check(r==0); } { const char *srcs[1] = {src}; const char *dsts[1] = {dst}; int r = tokubackup_create_backup(srcs, dsts, 1, simple_poll_fun, NULL, expect_eacces_error_fun, NULL); check(r==EACCES); check(saw_error); } { int r = systemf("chmod ugo+rwx %s", src); check(r==0); } cleanup_dirs(); free(src); free(dst); return 0; } <commit_msg>#19 still messing with permissions<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2012-2013 Tokutek Inc. All rights reserved." #ident "$Id$" // Test to make sure nothing crashes if the backup source directory has unreadable permissions. #include <errno.h> #include "backup_test_helpers.h" volatile bool saw_error = false; static void expect_eacces_error_fun(int error_number, const char *error_string, void *backup_extra __attribute__((unused))) { fprintf(stderr, "EXPECT ERROR %d: %d (%s)\n", EACCES, error_number, error_string); check(error_number==EACCES); saw_error = true; } int test_main(int argc __attribute__((__unused__)), const char *argv[] __attribute__((__unused__))) { char *src = get_src(); char *dst = get_dst(); { int r = systemf("chmod ugo+rwx %s 2> /dev/null", src); ignore(r); } setup_source(); setup_destination(); setup_dirs(); { int r = systemf("chmod ugo-r %s", src); check(r==0); } { const char *srcs[1] = {src}; const char *dsts[1] = {dst}; int r = tokubackup_create_backup(srcs, dsts, 1, simple_poll_fun, NULL, expect_eacces_error_fun, NULL); check(r==EACCES); check(saw_error); } { int r = systemf("chmod ugo+rwx %s", src); check(r==0); } cleanup_dirs(); free(src); free(dst); return 0; } <|endoftext|>
<commit_before>#include <QtTest> #include <timing/calendartiming.h> class TestCalendarTiming : public QObject { Q_OBJECT private slots: void constructors() { CalendarTiming timing; QCOMPARE(timing.type(), QLatin1String("calendar")); } }; QTEST_MAIN(TestCalendarTiming) #include "tst_calendartiming.moc" <commit_msg>Unittests for calendarTiming<commit_after>#include <QtTest> #include <timing/calendartiming.h> class TestCalendarTiming : public QObject { Q_OBJECT private slots: void constructors() { CalendarTiming timing; QCOMPARE(timing.type(), QLatin1String("calendar")); } void nextRuns() { QTime time = QTime::currentTime(); time = QTime(time.hour(), time.minute(), time.second()); QDateTime now = QDateTime::currentDateTime(); now.setTime(time); QDateTime start = QDateTime::currentDateTime(); QDateTime end; QList<quint8> months = QList<quint8>()<<1<<2<<3<<4<<5<<6<<7<<8<<9<<10<<11<<12; QList<quint8> daysOfWeek = QList<quint8>()<<1<<2<<3<<4<<5<<6<<7; QList<quint8> daysOfMonth; QList<quint8> hours; QList<quint8> minutes; QList<quint8> seconds; for(int i=1; i<32; i++) { daysOfMonth<<i; } for(int i=0; i<24; i++) { hours<<i; } for(int i=0; i<60; i++) { minutes<<i; seconds<<i; } // start now CalendarTiming nowTiming(start, end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time now"); QCOMPARE(nowTiming.nextRun(), now); // start time in the future CalendarTiming futureTiming(start.addDays(1), end, months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("start time one day in the future"); QCOMPARE(futureTiming.nextRun(), now.addDays(1)); // end time already reached CalendarTiming pastTiming(start.addDays(1), start.addDays(-1), months, daysOfWeek, daysOfMonth, hours, minutes, seconds); qDebug("end time already reached"); QCOMPARE(pastTiming.nextRun(), QDateTime()); // start tomorrow because hour already passed today (not true before 4 am) CalendarTiming tomorrowTiming(start, end, months, daysOfWeek, daysOfMonth, QList<quint8>()<<4, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 am)"); QDateTime tomorrowTime = now.addDays(1); tomorrowTime.setTime(QTime(4,0,0)); QCOMPARE(tomorrowTiming.nextRun(), tomorrowTime); // start tomorrow because hour already passed today (not true before 4 am [2]) CalendarTiming tomorrowTiming2(start, end, months, daysOfWeek, daysOfMonth, QList<quint8>()<<4<<5, minutes, seconds); qDebug("nextRun tomorrow because hour already passed today (4 and 5 am)"); QCOMPARE(tomorrowTiming2.nextRun(), tomorrowTime); // start next month because day already passed this month (not true on 1st of month) CalendarTiming nextMonthTiming(start, end, months, daysOfWeek, QList<quint8>()<<1, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st)"); QDateTime nextMonthTime = now.addMonths(1); nextMonthTime.setTime(QTime(0,0,0)); nextMonthTime.setDate(QDate(nextMonthTime.date().year(), nextMonthTime.date().month(), 1)); QCOMPARE(nextMonthTiming.nextRun(), nextMonthTime); // start next month because day already passed this month (not true on 1st or 2nd of month) CalendarTiming nextMonthTiming2(start, end, months, daysOfWeek, QList<quint8>()<<1<<2, hours, minutes, seconds); qDebug("nextRun next month because day already passed this month (1st and 2nd)"); QCOMPARE(nextMonthTiming2.nextRun(), nextMonthTime); // no nextRun because of invalid Timing (February 30th) CalendarTiming februaryTiming(start, end, QList<quint8>()<<2, daysOfWeek, QList<quint8>()<<30, hours, minutes, seconds); qDebug("no nextRun because invalid Timing (30.02)"); QCOMPARE(februaryTiming.nextRun(), QDateTime()); // start next year because day already passed this year (not true on January 1st) CalendarTiming yearTiming(start, end, QList<quint8>()<<1, daysOfWeek, QList<quint8>()<<1, hours, minutes, seconds); qDebug("nextRun on January 1st"); QCOMPARE(yearTiming.nextRun(), QDateTime(QDate(now.date().year()+1, 1, 1), QTime(0,0,0))); } }; QTEST_MAIN(TestCalendarTiming) #include "tst_calendartiming.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifdef _WIN32 #include <sdkddkver.h> #endif #include <dom.hpp> #include <http/http.hpp> #include <http/server.hpp> #include <ssdp/ssdp.hpp> #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; inline void push() {} template <typename T, typename... Args> inline void push(T && arg, Args && ... rest) { std::cerr << arg; push(std::forward<Args>(rest)...); } template <typename... Args> void help(Args&& ... args) { std::cerr << "svcc 1.0 -- SSDP service compiler.\n"; push(std::forward<Args>(args)...); if (sizeof...(args) > 0) std::cerr << "\n"; std::cerr << "\nusage:\n" " ssvc INFILE OUTFILE\n" "e.g.\n" " ssvc service.xml service.idl\n" " ssvc service.idl service.hpp\n" ; } inline bool is_file(const fs::path& p) { return fs::is_regular_file(p) || fs::is_symlink(p); } int main(int argc, char* argv []) { try { std::cout << fs::current_path().string() << std::endl; if (argc != 3) { help("File name missing."); return 1; } fs::path in(argv[1]); fs::path out(argv[2]); if (is_file(in) && is_file(out) && fs::last_write_time(in) < fs::last_write_time(out)) return 0; fs::ifstream in_f(in); if (!in_f) { help("File `", in, "` could not be read."); return 1; } std::cout << in.filename().string() << std::endl; auto doc = dom::XmlDocument::fromDataSource([&](void* buffer, size_t size) { return (size_t)in_f.read((char*)buffer, size).gcount(); }); if (doc) { // try XML -> IDL } else { // try IDL -> HPP } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <commit_msg>Crude IDL printing<commit_after>/* * Copyright (C) 2013 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifdef _WIN32 #include <sdkddkver.h> #endif #include <dom.hpp> #include <http/http.hpp> #include <http/server.hpp> #include <ssdp/ssdp.hpp> #include <boost/filesystem.hpp> #include <iostream> namespace fs = boost::filesystem; inline void push() {} template <typename T, typename... Args> inline void push(T && arg, Args && ... rest) { std::cerr << arg; push(std::forward<Args>(rest)...); } template <typename... Args> void help(Args&& ... args) { std::cerr << "svcc 1.0 -- SSDP service compiler.\n"; push(std::forward<Args>(args)...); if (sizeof...(args) > 0) std::cerr << "\n"; std::cerr << "\nusage:\n" " ssvc INFILE OUTFILE\n" "e.g.\n" " ssvc service.xml service.idl\n" " ssvc service.idl service.hpp\n" ; } inline bool is_file(const fs::path& p) { return fs::is_regular_file(p) || fs::is_symlink(p); } struct state_variable { bool m_event; std::string m_name; std::string m_type; std::vector<std::string> m_values; std::string getType() const { return m_values.empty() ? m_type : m_event ? m_name + "_Values" : m_name; } }; struct action_arg { bool m_input; std::string m_name; std::string m_type_ref; std::string getType(const std::vector<state_variable>& refs) const { for (auto&& ref : refs) { if (m_type_ref == ref.m_name) return ref.getType(); } return m_type_ref; } }; struct action { std::string m_name; std::vector<action_arg> m_args; }; inline std::string find_string(const dom::XmlNodePtr& node, const std::string& xpath) { auto tmp = node->find(xpath); if (tmp) return tmp->stringValue(); return std::string(); } inline std::string find_string(const dom::XmlNodePtr& node, const std::string& xpath, dom::Namespaces ns) { auto tmp = node->find(xpath, ns); if (tmp) return tmp->stringValue(); return std::string(); } int main(int argc, char* argv []) { try { std::cout << fs::current_path().string() << std::endl; if (argc != 3) { help("File name missing."); return 1; } fs::path in(argv[1]); fs::path out(argv[2]); if (is_file(in) && is_file(out) && fs::last_write_time(in) < fs::last_write_time(out)) return 0; fs::ifstream in_f(in); if (!in_f) { help("File `", in, "` could not be read."); return 1; } std::cout << in.filename().string() << std::endl; auto doc = dom::XmlDocument::fromDataSource([&](void* buffer, size_t size) { return (size_t)in_f.read((char*)buffer, size).gcount(); }); if (doc) { std::vector<state_variable> types_variables; std::vector<action> actions; int spec_major = 0, spec_minor = 0; // try XML -> IDL dom::NSData ns[] = { {"svc", "urn:schemas-upnp-org:service-1-0"} }; auto version = doc->find("/svc:scpd/svc:specVersion", ns); if (version) { auto major = find_string(version, "svc:major", ns); auto minor = find_string(version, "svc:minor", ns); { std::istringstream i(major); i >> spec_major; } { std::istringstream i(minor); i >> spec_minor; } } auto action_list = doc->findall("/svc:scpd/svc:actionList/svc:action", ns); for (auto&& act : action_list) { action action; action.m_name = find_string(act, "svc:name", ns); auto args = act->findall("svc:argumentList/svc:argument", ns); for (auto&& arg : args) { action_arg action_arg; action_arg.m_input = find_string(arg, "svc:direction", ns) == "out"; action_arg.m_name = find_string(arg, "svc:name", ns); action_arg.m_type_ref = find_string(arg, "svc:relatedStateVariable", ns); action.m_args.push_back(action_arg); } actions.push_back(action); } auto variables = doc->findall("/svc:scpd/svc:serviceStateTable/svc:stateVariable", ns); for (auto&& variable : variables) { auto sendEvent = find_string(variable, "@sendEvents"); state_variable var; var.m_event = sendEvent == "1" || sendEvent == "yes"; var.m_name = find_string(variable, "svc:name", ns); var.m_type = find_string(variable, "svc:dataType", ns); auto allowedValues = variable->findall("svc:allowedValueList/svc:allowedValue", ns); for (auto&& value : allowedValues) var.m_values.push_back(value->stringValue()); types_variables.push_back(var); } size_t events = 0; for (auto&& var : types_variables) { if (var.m_values.empty()) { ++events; continue; } std::cout << "enum " << var.getType() << " { // " << var.m_type << "\n"; for (auto&& val : var.m_values) { std::cout << " " << val << ";\n"; } std::cout << "};\n\n"; } std::cout << "[version(" << spec_major << "." << spec_minor << ")] interface <name missing> {\n"; for (auto&& action : actions) { bool first = true; std::cout << " void " << action.m_name << "("; size_t out_count = 0; for (auto&& arg : action.m_args) { if (!arg.m_input) ++out_count; } for (auto&& arg : action.m_args) { if (first) first = false; else std::cout << ", "; std::cout << (arg.m_input ? "[in] " : out_count == 1 ? "[retval] " : "[out] ") << arg.getType(types_variables) << " " << arg.m_name; } std::cout << ");\n"; } if (!types_variables.empty() && events > 0) std::cout << "\n"; for (auto && var : types_variables) { if (!var.m_event) continue; std::cout << " "; std::cout << var.getType() << " " << var.m_name << ";\n"; } std::cout << "};\n"; } else { // try IDL -> HPP } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>#include "remote_control/resource_allocation_manager_impl.h" #include "application_manager/application.h" #include "application_manager/message_helper.h" #include "remote_control/rc_module_constants.h" #include "json/json.h" #include "utils/helpers.h" #include "utils/make_shared.h" #include "remote_control/message_helper.h" namespace remote_control { CREATE_LOGGERPTR_GLOBAL(logger_, "RemoteControlModule") ResourceAllocationManagerImpl::ResourceAllocationManagerImpl( RemotePluginInterface& rc_plugin) : current_access_mode_(hmi_apis::Common_RCAccessMode::AUTO_ALLOW) , rc_plugin_(rc_plugin) {} ResourceAllocationManagerImpl::~ResourceAllocationManagerImpl() {} AcquireResult::eType ResourceAllocationManagerImpl::AcquireResource( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); const application_manager::ApplicationSharedPtr acquiring_app = rc_plugin_.service()->GetApplication(app_id); if (!acquiring_app) { LOG4CXX_WARN(logger_, "App with app_id: " << app_id << "does not exist!"); return AcquireResult::IN_USE; } const AllocatedResources::const_iterator allocated_it = allocated_resources_.find(module_type); if (allocated_resources_.end() == allocated_it) { allocated_resources_[module_type] = app_id; LOG4CXX_DEBUG(logger_, "Resource is not acquired yet. " << "App: " << app_id << " is allowed to acquire " << module_type); return AcquireResult::ALLOWED; } if (app_id == allocated_resources_[module_type]) { LOG4CXX_DEBUG(logger_, "App: " << app_id << " is already acquired resource " << module_type); return AcquireResult::ALLOWED; } if (IsModuleTypeRejected(module_type, app_id)) { LOG4CXX_DEBUG(logger_, "Driver disallowed app: " << app_id << " to acquire " << module_type); return AcquireResult::REJECTED; } const mobile_apis::HMILevel::eType acquiring_app_hmi_level = acquiring_app->hmi_level(); if (mobile_apis::HMILevel::HMI_FULL != acquiring_app_hmi_level) { LOG4CXX_DEBUG( logger_, "Aquiring resources is not allowed in HMI level: " << application_manager::MessageHelper::StringifiedHMILevel( acquiring_app_hmi_level) << ". App: " << app_id << " is disallowed to acquire " << module_type); return AcquireResult::REJECTED; } switch (current_access_mode_) { case hmi_apis::Common_RCAccessMode::AUTO_DENY: { LOG4CXX_DEBUG(logger_, "Current access_mode is AUTO_DENY. " << "App: " << app_id << " is disallowed to acquire " << module_type); return AcquireResult::IN_USE; } case hmi_apis::Common_RCAccessMode::ASK_DRIVER: { LOG4CXX_DEBUG(logger_, "Current access_mode is ASK_DRIVER. " "Driver confirmation is required for app: " << app_id << " to acquire " << module_type); return AcquireResult::ASK_DRIVER; } case hmi_apis::Common_RCAccessMode::AUTO_ALLOW: { LOG4CXX_DEBUG(logger_, "Current access_mode is AUTO_ALLOW. " << "App: " << app_id << " is allowed to acquire " << module_type); allocated_resources_[module_type] = app_id; return AcquireResult::ALLOWED; } default: { DCHECK_OR_RETURN(false, AcquireResult::IN_USE); } } } void ResourceAllocationManagerImpl::SetResourceState( const std::string& module_type, const uint32_t app_id, const ResourceState::eType state) { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Setting state for " << module_type << " by app_id " << app_id << " to state " << state); const AllocatedResources::const_iterator allocated_it = allocated_resources_.find(module_type); const std::string status = allocated_resources_.end() != allocated_it ? " acquired " : " not acquired "; LOG4CXX_DEBUG(logger_, "Resource " << module_type << " is " << status << " Owner application id is " << allocated_it->second << " Changing application id is " << app_id); resources_state_[module_type] = state; LOG4CXX_DEBUG(logger_, "Resource " << module_type << " got state " << state); } bool ResourceAllocationManagerImpl::IsResourceFree( const std::string& module_type) const { LOG4CXX_AUTO_TRACE(logger_); const ResourcesState::const_iterator resource = resources_state_.find(module_type); if (resources_state_.end() == resource) { LOG4CXX_DEBUG(logger_, "Resource " << module_type << " is free."); return true; } LOG4CXX_DEBUG(logger_, "Resource " << module_type << " state is " << resource->second); return ResourceState::FREE == resource->second; } void ResourceAllocationManagerImpl::SetAccessMode( const hmi_apis::Common_RCAccessMode::eType access_mode) { if (hmi_apis::Common_RCAccessMode::ASK_DRIVER != access_mode) { rejected_resources_for_application_.clear(); } current_access_mode_ = access_mode; } void ResourceAllocationManagerImpl::ForceAcquireResource( const std::string& module_type, const uint32_t app_id) { LOG4CXX_DEBUG(logger_, "Force " << app_id << " acquiring " << module_type); allocated_resources_[module_type] = app_id; } bool ResourceAllocationManagerImpl::IsModuleTypeRejected( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); RejectedResources::iterator it = rejected_resources_for_application_.find(app_id); if (rejected_resources_for_application_.end() == it) { return false; } const std::vector<std::string>& list_of_rejected_resources = rejected_resources_for_application_[app_id]; return helpers::in_range(list_of_rejected_resources, module_type); } void ResourceAllocationManagerImpl::OnDriverDisallowed( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); RejectedResources::iterator it = rejected_resources_for_application_.find(app_id); if (rejected_resources_for_application_.end() == it) { rejected_resources_for_application_[app_id] = std::vector<std::string>(); } std::vector<std::string>& list_of_rejected_resources = rejected_resources_for_application_[app_id]; list_of_rejected_resources.push_back(module_type); } void ResourceAllocationManagerImpl::OnUnregisterApplication( const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); rejected_resources_for_application_.erase(app_id); for (AllocatedResources::const_iterator it = allocated_resources_.begin(); it != allocated_resources_.end();) { if (app_id == it->second) { LOG4CXX_INFO(logger_, "Application " << app_id << " is unregistered. Releasing resource " << it->first); resources_state_.erase(it->first); it = allocated_resources_.erase(it); } else { ++it; } } } void ResourceAllocationManagerImpl::ResetAllAllocations() { LOG4CXX_AUTO_TRACE(logger_); allocated_resources_.clear(); rejected_resources_for_application_.clear(); resources_state_.clear(); } } // namespace remote_control <commit_msg>Mark variable as unused to avoid build fail without logs<commit_after>#include "remote_control/resource_allocation_manager_impl.h" #include "application_manager/application.h" #include "application_manager/message_helper.h" #include "remote_control/rc_module_constants.h" #include "json/json.h" #include "utils/helpers.h" #include "utils/make_shared.h" #include "remote_control/message_helper.h" namespace remote_control { CREATE_LOGGERPTR_GLOBAL(logger_, "RemoteControlModule") ResourceAllocationManagerImpl::ResourceAllocationManagerImpl( RemotePluginInterface& rc_plugin) : current_access_mode_(hmi_apis::Common_RCAccessMode::AUTO_ALLOW) , rc_plugin_(rc_plugin) {} ResourceAllocationManagerImpl::~ResourceAllocationManagerImpl() {} AcquireResult::eType ResourceAllocationManagerImpl::AcquireResource( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); const application_manager::ApplicationSharedPtr acquiring_app = rc_plugin_.service()->GetApplication(app_id); if (!acquiring_app) { LOG4CXX_WARN(logger_, "App with app_id: " << app_id << "does not exist!"); return AcquireResult::IN_USE; } const AllocatedResources::const_iterator allocated_it = allocated_resources_.find(module_type); if (allocated_resources_.end() == allocated_it) { allocated_resources_[module_type] = app_id; LOG4CXX_DEBUG(logger_, "Resource is not acquired yet. " << "App: " << app_id << " is allowed to acquire " << module_type); return AcquireResult::ALLOWED; } if (app_id == allocated_resources_[module_type]) { LOG4CXX_DEBUG(logger_, "App: " << app_id << " is already acquired resource " << module_type); return AcquireResult::ALLOWED; } if (IsModuleTypeRejected(module_type, app_id)) { LOG4CXX_DEBUG(logger_, "Driver disallowed app: " << app_id << " to acquire " << module_type); return AcquireResult::REJECTED; } const mobile_apis::HMILevel::eType acquiring_app_hmi_level = acquiring_app->hmi_level(); if (mobile_apis::HMILevel::HMI_FULL != acquiring_app_hmi_level) { LOG4CXX_DEBUG( logger_, "Aquiring resources is not allowed in HMI level: " << application_manager::MessageHelper::StringifiedHMILevel( acquiring_app_hmi_level) << ". App: " << app_id << " is disallowed to acquire " << module_type); return AcquireResult::REJECTED; } switch (current_access_mode_) { case hmi_apis::Common_RCAccessMode::AUTO_DENY: { LOG4CXX_DEBUG(logger_, "Current access_mode is AUTO_DENY. " << "App: " << app_id << " is disallowed to acquire " << module_type); return AcquireResult::IN_USE; } case hmi_apis::Common_RCAccessMode::ASK_DRIVER: { LOG4CXX_DEBUG(logger_, "Current access_mode is ASK_DRIVER. " "Driver confirmation is required for app: " << app_id << " to acquire " << module_type); return AcquireResult::ASK_DRIVER; } case hmi_apis::Common_RCAccessMode::AUTO_ALLOW: { LOG4CXX_DEBUG(logger_, "Current access_mode is AUTO_ALLOW. " << "App: " << app_id << " is allowed to acquire " << module_type); allocated_resources_[module_type] = app_id; return AcquireResult::ALLOWED; } default: { DCHECK_OR_RETURN(false, AcquireResult::IN_USE); } } } void ResourceAllocationManagerImpl::SetResourceState( const std::string& module_type, const uint32_t app_id, const ResourceState::eType state) { LOG4CXX_AUTO_TRACE(logger_); LOG4CXX_DEBUG(logger_, "Setting state for " << module_type << " by app_id " << app_id << " to state " << state); const AllocatedResources::const_iterator allocated_it = allocated_resources_.find(module_type); const std::string status = allocated_resources_.end() != allocated_it ? " acquired " : " not acquired "; UNUSED(status); LOG4CXX_DEBUG(logger_, "Resource " << module_type << " is " << status << " Owner application id is " << allocated_it->second << " Changing application id is " << app_id); resources_state_[module_type] = state; LOG4CXX_DEBUG(logger_, "Resource " << module_type << " got state " << state); } bool ResourceAllocationManagerImpl::IsResourceFree( const std::string& module_type) const { LOG4CXX_AUTO_TRACE(logger_); const ResourcesState::const_iterator resource = resources_state_.find(module_type); if (resources_state_.end() == resource) { LOG4CXX_DEBUG(logger_, "Resource " << module_type << " is free."); return true; } LOG4CXX_DEBUG(logger_, "Resource " << module_type << " state is " << resource->second); return ResourceState::FREE == resource->second; } void ResourceAllocationManagerImpl::SetAccessMode( const hmi_apis::Common_RCAccessMode::eType access_mode) { if (hmi_apis::Common_RCAccessMode::ASK_DRIVER != access_mode) { rejected_resources_for_application_.clear(); } current_access_mode_ = access_mode; } void ResourceAllocationManagerImpl::ForceAcquireResource( const std::string& module_type, const uint32_t app_id) { LOG4CXX_DEBUG(logger_, "Force " << app_id << " acquiring " << module_type); allocated_resources_[module_type] = app_id; } bool ResourceAllocationManagerImpl::IsModuleTypeRejected( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); RejectedResources::iterator it = rejected_resources_for_application_.find(app_id); if (rejected_resources_for_application_.end() == it) { return false; } const std::vector<std::string>& list_of_rejected_resources = rejected_resources_for_application_[app_id]; return helpers::in_range(list_of_rejected_resources, module_type); } void ResourceAllocationManagerImpl::OnDriverDisallowed( const std::string& module_type, const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); RejectedResources::iterator it = rejected_resources_for_application_.find(app_id); if (rejected_resources_for_application_.end() == it) { rejected_resources_for_application_[app_id] = std::vector<std::string>(); } std::vector<std::string>& list_of_rejected_resources = rejected_resources_for_application_[app_id]; list_of_rejected_resources.push_back(module_type); } void ResourceAllocationManagerImpl::OnUnregisterApplication( const uint32_t app_id) { LOG4CXX_AUTO_TRACE(logger_); rejected_resources_for_application_.erase(app_id); for (AllocatedResources::const_iterator it = allocated_resources_.begin(); it != allocated_resources_.end();) { if (app_id == it->second) { LOG4CXX_INFO(logger_, "Application " << app_id << " is unregistered. Releasing resource " << it->first); resources_state_.erase(it->first); it = allocated_resources_.erase(it); } else { ++it; } } } void ResourceAllocationManagerImpl::ResetAllAllocations() { LOG4CXX_AUTO_TRACE(logger_); allocated_resources_.clear(); rejected_resources_for_application_.clear(); resources_state_.clear(); } } // namespace remote_control <|endoftext|>
<commit_before>#include "I2PEndian.h" #include "CryptoConst.h" #include "Tunnel.h" #include "NetDb.h" #include "Timestamp.h" #include "Garlic.h" #include "TunnelPool.h" namespace i2p { namespace tunnel { TunnelPool::TunnelPool (i2p::garlic::GarlicDestination& localDestination, int numInboundHops, int numOutboundHops, int numTunnels): m_LocalDestination (localDestination), m_NumInboundHops (numInboundHops), m_NumOutboundHops (numOutboundHops), m_NumTunnels (numTunnels), m_IsActive (true) { } TunnelPool::~TunnelPool () { DetachTunnels (); } void TunnelPool::DetachTunnels () { { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it: m_InboundTunnels) it->SetTunnelPool (nullptr); m_InboundTunnels.clear (); } { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); for (auto it: m_OutboundTunnels) it->SetTunnelPool (nullptr); m_OutboundTunnels.clear (); } m_Tests.clear (); } void TunnelPool::TunnelCreated (InboundTunnel * createdTunnel) { if (!m_IsActive) return; { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.insert (createdTunnel); } m_LocalDestination.SetLeaseSetUpdated (); } void TunnelPool::TunnelExpired (InboundTunnel * expiredTunnel) { if (expiredTunnel) { expiredTunnel->SetTunnelPool (nullptr); for (auto it: m_Tests) if (it.second.second == expiredTunnel) it.second.second = nullptr; RecreateInboundTunnel (expiredTunnel); std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.erase (expiredTunnel); } } void TunnelPool::TunnelCreated (OutboundTunnel * createdTunnel) { if (!m_IsActive) return; std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.insert (createdTunnel); } void TunnelPool::TunnelExpired (OutboundTunnel * expiredTunnel) { if (expiredTunnel) { expiredTunnel->SetTunnelPool (nullptr); for (auto it: m_Tests) if (it.second.first == expiredTunnel) it.second.first = nullptr; RecreateOutboundTunnel (expiredTunnel); std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.erase (expiredTunnel); } } std::vector<InboundTunnel *> TunnelPool::GetInboundTunnels (int num) const { std::vector<InboundTunnel *> v; int i = 0; std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it : m_InboundTunnels) { if (i >= num) break; if (it->IsEstablished ()) { v.push_back (it); i++; } } return v; } OutboundTunnel * TunnelPool::GetNextOutboundTunnel (OutboundTunnel * suggested) const { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); return GetNextTunnel (m_OutboundTunnels, suggested); } InboundTunnel * TunnelPool::GetNextInboundTunnel (InboundTunnel * suggested) const { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); return GetNextTunnel (m_InboundTunnels, suggested); } template<class TTunnels> typename TTunnels::value_type TunnelPool::GetNextTunnel (TTunnels& tunnels, typename TTunnels::value_type suggested) const { if (tunnels.empty ()) return nullptr; if (suggested && tunnels.count (suggested) > 0 && suggested->IsEstablished ()) return suggested; CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator (); uint32_t ind = rnd.GenerateWord32 (0, tunnels.size ()/2), i = 0; typename TTunnels::value_type tunnel = nullptr; for (auto it: tunnels) { if (it->IsEstablished ()) { tunnel = it; i++; } if (i > ind && tunnel) break; } return tunnel; } void TunnelPool::CreateTunnels () { int num = 0; { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it : m_InboundTunnels) if (it->IsEstablished ()) num++; } for (int i = num; i < m_NumTunnels; i++) CreateInboundTunnel (); num = 0; { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); for (auto it : m_OutboundTunnels) if (it->IsEstablished ()) num++; } for (int i = num; i < m_NumTunnels; i++) CreateOutboundTunnel (); } void TunnelPool::TestTunnels () { auto& rnd = i2p::context.GetRandomNumberGenerator (); for (auto it: m_Tests) { LogPrint ("Tunnel test ", (int)it.first, " failed"); // if test failed again with another tunnel we consider it failed if (it.second.first) { if (it.second.first->GetState () == eTunnelStateTestFailed) { it.second.first->SetState (eTunnelStateFailed); std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.erase (it.second.first); } else it.second.first->SetState (eTunnelStateTestFailed); } if (it.second.second) { if (it.second.second->GetState () == eTunnelStateTestFailed) { it.second.second->SetState (eTunnelStateFailed); { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.erase (it.second.second); } m_LocalDestination.SetLeaseSetUpdated (); } else it.second.second->SetState (eTunnelStateTestFailed); } } m_Tests.clear (); // new tests auto it1 = m_OutboundTunnels.begin (); auto it2 = m_InboundTunnels.begin (); while (it1 != m_OutboundTunnels.end () && it2 != m_InboundTunnels.end ()) { bool failed = false; if ((*it1)->IsFailed ()) { failed = true; it1++; } if ((*it2)->IsFailed ()) { failed = true; it2++; } if (!failed) { uint32_t msgID = rnd.GenerateWord32 (); m_Tests[msgID] = std::make_pair (*it1, *it2); (*it1)->SendTunnelDataMsg ((*it2)->GetNextIdentHash (), (*it2)->GetNextTunnelID (), CreateDeliveryStatusMsg (msgID)); it1++; it2++; } } } void TunnelPool::ProcessDeliveryStatus (I2NPMessage * msg) { I2NPDeliveryStatusMsg * deliveryStatus = (I2NPDeliveryStatusMsg *)msg->GetPayload (); auto it = m_Tests.find (be32toh (deliveryStatus->msgID)); if (it != m_Tests.end ()) { // restore from test failed state if any if (it->second.first->GetState () == eTunnelStateTestFailed) it->second.first->SetState (eTunnelStateEstablished); if (it->second.second->GetState () == eTunnelStateTestFailed) it->second.second->SetState (eTunnelStateEstablished); LogPrint ("Tunnel test ", it->first, " successive. ", i2p::util::GetMillisecondsSinceEpoch () - be64toh (deliveryStatus->timestamp), " milliseconds"); m_Tests.erase (it); DeleteI2NPMessage (msg); } else m_LocalDestination.ProcessDeliveryStatusMessage (msg); } std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop) const { bool isExploratory = (&m_LocalDestination == &i2p::context); // TODO: implement it better auto hop = isExploratory ? i2p::data::netdb.GetRandomRouter (prevHop): i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop); if (!hop) hop = i2p::data::netdb.GetRandomRouter (); return hop; } void TunnelPool::CreateInboundTunnel () { OutboundTunnel * outboundTunnel = GetNextOutboundTunnel (); if (!outboundTunnel) outboundTunnel = tunnels.GetNextOutboundTunnel (); LogPrint ("Creating destination inbound tunnel..."); auto prevHop = i2p::context.GetSharedRouterInfo (); std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops; int numHops = m_NumInboundHops; if (outboundTunnel) { // last hop auto hop = outboundTunnel->GetTunnelConfig ()->GetFirstHop ()->router; if (hop->GetIdentHash () != i2p::context.GetIdentHash ()) // outbound shouldn't be zero-hop tunnel { prevHop = hop; hops.push_back (prevHop); numHops--; } } for (int i = 0; i < numHops; i++) { auto hop = SelectNextHop (prevHop); prevHop = hop; hops.push_back (hop); } std::reverse (hops.begin (), hops.end ()); auto * tunnel = tunnels.CreateTunnel<InboundTunnel> (new TunnelConfig (hops), outboundTunnel); tunnel->SetTunnelPool (this); } void TunnelPool::RecreateInboundTunnel (InboundTunnel * tunnel) { OutboundTunnel * outboundTunnel = GetNextOutboundTunnel (); if (!outboundTunnel) outboundTunnel = tunnels.GetNextOutboundTunnel (); LogPrint ("Re-creating destination inbound tunnel..."); auto * newTunnel = tunnels.CreateTunnel<InboundTunnel> (tunnel->GetTunnelConfig ()->Clone (), outboundTunnel); newTunnel->SetTunnelPool (this); } void TunnelPool::CreateOutboundTunnel () { InboundTunnel * inboundTunnel = GetNextInboundTunnel (); if (!inboundTunnel) inboundTunnel = tunnels.GetNextInboundTunnel (); if (inboundTunnel) { LogPrint ("Creating destination outbound tunnel..."); auto prevHop = i2p::context.GetSharedRouterInfo (); std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops; for (int i = 0; i < m_NumOutboundHops; i++) { auto hop = SelectNextHop (prevHop); prevHop = hop; hops.push_back (hop); } auto * tunnel = tunnels.CreateTunnel<OutboundTunnel> ( new TunnelConfig (hops, inboundTunnel->GetTunnelConfig ())); tunnel->SetTunnelPool (this); } else LogPrint ("Can't create outbound tunnel. No inbound tunnels found"); } void TunnelPool::RecreateOutboundTunnel (OutboundTunnel * tunnel) { InboundTunnel * inboundTunnel = GetNextInboundTunnel (); if (!inboundTunnel) inboundTunnel = tunnels.GetNextInboundTunnel (); if (inboundTunnel) { LogPrint ("Re-creating destination outbound tunnel..."); auto * newTunnel = tunnels.CreateTunnel<OutboundTunnel> ( tunnel->GetTunnelConfig ()->Clone (inboundTunnel->GetTunnelConfig ())); newTunnel->SetTunnelPool (this); } else LogPrint ("Can't re-create outbound tunnel. No inbound tunnels found"); } } } <commit_msg>enale tunnl test encryption back<commit_after>#include "I2PEndian.h" #include "CryptoConst.h" #include "Tunnel.h" #include "NetDb.h" #include "Timestamp.h" #include "Garlic.h" #include "TunnelPool.h" namespace i2p { namespace tunnel { TunnelPool::TunnelPool (i2p::garlic::GarlicDestination& localDestination, int numInboundHops, int numOutboundHops, int numTunnels): m_LocalDestination (localDestination), m_NumInboundHops (numInboundHops), m_NumOutboundHops (numOutboundHops), m_NumTunnels (numTunnels), m_IsActive (true) { } TunnelPool::~TunnelPool () { DetachTunnels (); } void TunnelPool::DetachTunnels () { { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it: m_InboundTunnels) it->SetTunnelPool (nullptr); m_InboundTunnels.clear (); } { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); for (auto it: m_OutboundTunnels) it->SetTunnelPool (nullptr); m_OutboundTunnels.clear (); } m_Tests.clear (); } void TunnelPool::TunnelCreated (InboundTunnel * createdTunnel) { if (!m_IsActive) return; { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.insert (createdTunnel); } m_LocalDestination.SetLeaseSetUpdated (); } void TunnelPool::TunnelExpired (InboundTunnel * expiredTunnel) { if (expiredTunnel) { expiredTunnel->SetTunnelPool (nullptr); for (auto it: m_Tests) if (it.second.second == expiredTunnel) it.second.second = nullptr; RecreateInboundTunnel (expiredTunnel); std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.erase (expiredTunnel); } } void TunnelPool::TunnelCreated (OutboundTunnel * createdTunnel) { if (!m_IsActive) return; std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.insert (createdTunnel); } void TunnelPool::TunnelExpired (OutboundTunnel * expiredTunnel) { if (expiredTunnel) { expiredTunnel->SetTunnelPool (nullptr); for (auto it: m_Tests) if (it.second.first == expiredTunnel) it.second.first = nullptr; RecreateOutboundTunnel (expiredTunnel); std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.erase (expiredTunnel); } } std::vector<InboundTunnel *> TunnelPool::GetInboundTunnels (int num) const { std::vector<InboundTunnel *> v; int i = 0; std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it : m_InboundTunnels) { if (i >= num) break; if (it->IsEstablished ()) { v.push_back (it); i++; } } return v; } OutboundTunnel * TunnelPool::GetNextOutboundTunnel (OutboundTunnel * suggested) const { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); return GetNextTunnel (m_OutboundTunnels, suggested); } InboundTunnel * TunnelPool::GetNextInboundTunnel (InboundTunnel * suggested) const { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); return GetNextTunnel (m_InboundTunnels, suggested); } template<class TTunnels> typename TTunnels::value_type TunnelPool::GetNextTunnel (TTunnels& tunnels, typename TTunnels::value_type suggested) const { if (tunnels.empty ()) return nullptr; if (suggested && tunnels.count (suggested) > 0 && suggested->IsEstablished ()) return suggested; CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator (); uint32_t ind = rnd.GenerateWord32 (0, tunnels.size ()/2), i = 0; typename TTunnels::value_type tunnel = nullptr; for (auto it: tunnels) { if (it->IsEstablished ()) { tunnel = it; i++; } if (i > ind && tunnel) break; } return tunnel; } void TunnelPool::CreateTunnels () { int num = 0; { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); for (auto it : m_InboundTunnels) if (it->IsEstablished ()) num++; } for (int i = num; i < m_NumTunnels; i++) CreateInboundTunnel (); num = 0; { std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); for (auto it : m_OutboundTunnels) if (it->IsEstablished ()) num++; } for (int i = num; i < m_NumTunnels; i++) CreateOutboundTunnel (); } void TunnelPool::TestTunnels () { auto& rnd = i2p::context.GetRandomNumberGenerator (); for (auto it: m_Tests) { LogPrint ("Tunnel test ", (int)it.first, " failed"); // if test failed again with another tunnel we consider it failed if (it.second.first) { if (it.second.first->GetState () == eTunnelStateTestFailed) { it.second.first->SetState (eTunnelStateFailed); std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex); m_OutboundTunnels.erase (it.second.first); } else it.second.first->SetState (eTunnelStateTestFailed); } if (it.second.second) { if (it.second.second->GetState () == eTunnelStateTestFailed) { it.second.second->SetState (eTunnelStateFailed); { std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); m_InboundTunnels.erase (it.second.second); } m_LocalDestination.SetLeaseSetUpdated (); } else it.second.second->SetState (eTunnelStateTestFailed); } } m_Tests.clear (); // new tests auto it1 = m_OutboundTunnels.begin (); auto it2 = m_InboundTunnels.begin (); while (it1 != m_OutboundTunnels.end () && it2 != m_InboundTunnels.end ()) { bool failed = false; if ((*it1)->IsFailed ()) { failed = true; it1++; } if ((*it2)->IsFailed ()) { failed = true; it2++; } if (!failed) { uint8_t key[32], tag[32]; rnd.GenerateBlock (key, 32); // random session key rnd.GenerateBlock (tag, 32); // random session tag m_LocalDestination.SubmitSessionKey (key, tag); i2p::garlic::GarlicRoutingSession garlic (key, tag); uint32_t msgID = rnd.GenerateWord32 (); m_Tests[msgID] = std::make_pair (*it1, *it2); (*it1)->SendTunnelDataMsg ((*it2)->GetNextIdentHash (), (*it2)->GetNextTunnelID (), garlic.WrapSingleMessage (CreateDeliveryStatusMsg (msgID))); it1++; it2++; } } } void TunnelPool::ProcessDeliveryStatus (I2NPMessage * msg) { I2NPDeliveryStatusMsg * deliveryStatus = (I2NPDeliveryStatusMsg *)msg->GetPayload (); auto it = m_Tests.find (be32toh (deliveryStatus->msgID)); if (it != m_Tests.end ()) { // restore from test failed state if any if (it->second.first->GetState () == eTunnelStateTestFailed) it->second.first->SetState (eTunnelStateEstablished); if (it->second.second->GetState () == eTunnelStateTestFailed) it->second.second->SetState (eTunnelStateEstablished); LogPrint ("Tunnel test ", it->first, " successive. ", i2p::util::GetMillisecondsSinceEpoch () - be64toh (deliveryStatus->timestamp), " milliseconds"); m_Tests.erase (it); DeleteI2NPMessage (msg); } else m_LocalDestination.ProcessDeliveryStatusMessage (msg); } std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop) const { bool isExploratory = (&m_LocalDestination == &i2p::context); // TODO: implement it better auto hop = isExploratory ? i2p::data::netdb.GetRandomRouter (prevHop): i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop); if (!hop) hop = i2p::data::netdb.GetRandomRouter (); return hop; } void TunnelPool::CreateInboundTunnel () { OutboundTunnel * outboundTunnel = GetNextOutboundTunnel (); if (!outboundTunnel) outboundTunnel = tunnels.GetNextOutboundTunnel (); LogPrint ("Creating destination inbound tunnel..."); auto prevHop = i2p::context.GetSharedRouterInfo (); std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops; int numHops = m_NumInboundHops; if (outboundTunnel) { // last hop auto hop = outboundTunnel->GetTunnelConfig ()->GetFirstHop ()->router; if (hop->GetIdentHash () != i2p::context.GetIdentHash ()) // outbound shouldn't be zero-hop tunnel { prevHop = hop; hops.push_back (prevHop); numHops--; } } for (int i = 0; i < numHops; i++) { auto hop = SelectNextHop (prevHop); prevHop = hop; hops.push_back (hop); } std::reverse (hops.begin (), hops.end ()); auto * tunnel = tunnels.CreateTunnel<InboundTunnel> (new TunnelConfig (hops), outboundTunnel); tunnel->SetTunnelPool (this); } void TunnelPool::RecreateInboundTunnel (InboundTunnel * tunnel) { OutboundTunnel * outboundTunnel = GetNextOutboundTunnel (); if (!outboundTunnel) outboundTunnel = tunnels.GetNextOutboundTunnel (); LogPrint ("Re-creating destination inbound tunnel..."); auto * newTunnel = tunnels.CreateTunnel<InboundTunnel> (tunnel->GetTunnelConfig ()->Clone (), outboundTunnel); newTunnel->SetTunnelPool (this); } void TunnelPool::CreateOutboundTunnel () { InboundTunnel * inboundTunnel = GetNextInboundTunnel (); if (!inboundTunnel) inboundTunnel = tunnels.GetNextInboundTunnel (); if (inboundTunnel) { LogPrint ("Creating destination outbound tunnel..."); auto prevHop = i2p::context.GetSharedRouterInfo (); std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops; for (int i = 0; i < m_NumOutboundHops; i++) { auto hop = SelectNextHop (prevHop); prevHop = hop; hops.push_back (hop); } auto * tunnel = tunnels.CreateTunnel<OutboundTunnel> ( new TunnelConfig (hops, inboundTunnel->GetTunnelConfig ())); tunnel->SetTunnelPool (this); } else LogPrint ("Can't create outbound tunnel. No inbound tunnels found"); } void TunnelPool::RecreateOutboundTunnel (OutboundTunnel * tunnel) { InboundTunnel * inboundTunnel = GetNextInboundTunnel (); if (!inboundTunnel) inboundTunnel = tunnels.GetNextInboundTunnel (); if (inboundTunnel) { LogPrint ("Re-creating destination outbound tunnel..."); auto * newTunnel = tunnels.CreateTunnel<OutboundTunnel> ( tunnel->GetTunnelConfig ()->Clone (inboundTunnel->GetTunnelConfig ())); newTunnel->SetTunnelPool (this); } else LogPrint ("Can't re-create outbound tunnel. No inbound tunnels found"); } } } <|endoftext|>
<commit_before> #include <stdio.h> #include "Common.hpp" #include <Lumino/Base/Logger.hpp> #ifdef __EMSCRIPTEN__ #include <emscripten.h> static volatile bool g_ioDione = false; extern "C" void setIODone() { printf("called setIODone()\n"); g_ioDione = true; } void pre1(void *arg) { EM_ASM( //create your directory where we keep our persistent data FS.mkdir('/persistent_data'); //mount persistent directory as IDBFS FS.mount(IDBFS,{},'/persistent_data'); Module.print("start file sync.."); //flag to check when data are synchronized Module.syncdone = 0; //populate persistent_data directory with existing persistent source data //stored with Indexed Db //first parameter = "true" mean synchronize from Indexed Db to //Emscripten file system, // "false" mean synchronize from Emscripten file system to Indexed Db //second parameter = function called when data are synchronized FS.syncfs(true, function(err) { assert(!err); Module.print("end file sync.."); Module.syncdone = 1; //Module.ccall('setIODone', ""); }); ); printf("waiting\n"); //while (!g_ioDione) { //} printf("wait end\n"); } static void ems_loop() { static int count = 0; if (count == 10) { { FILE* fp = fopen("/persistent_data/out.txt", "r"); if (fp) { printf("open file."); char str[256]; fgets(str, 256, fp); printf(str); } else { printf("no file."); } } FILE* fp = fopen("/persistent_data/out.txt", "w"); if (!fp) { printf("failed fp."); return; } printf("fp:%p\n", fp); fprintf(fp, "test"); fclose(fp); //persist Emscripten current data to Indexed Db EM_ASM( Module.print("Start File sync.."); Module.syncdone = 0; FS.syncfs(false, function(err) { assert(!err); Module.print("End File sync.."); Module.syncdone = 1; }); ); } if (count == 50) { { FILE* fp = fopen("/persistent_data/out.txt", "r"); if (fp) { printf("open file.\n"); char str[256]; fgets(str, 256, fp); printf(str); } else { printf("no file.\n"); } } } if (count == 60) { emscripten_cancel_main_loop(); } printf("count:%d\n", count); count++; } static void main_loop() { static int init = 0; if (!init) { init = 1; char* testArgs[] = { "", "--gtest_break_on_failure", "--gtest_filter=Test_IO_FileSystem.*" }; int argc = sizeof(testArgs) / sizeof(char*); testing::InitGoogleTest(&argc, (char**)testArgs); RUN_ALL_TESTS(); } } int main(int argc, char** argv) { setlocale(LC_ALL, ""); printf("Running test.\n"); emscripten_set_main_loop(main_loop, 1, true); return 0; } #else bool testProcess(int argc, char** argv, int* outExitCode) { if (argc >= 2) { if (strcmp(argv[1], "proctest1") == 0) { *outExitCode = 2; return true; } else if (strcmp(argv[1], "proctest2") == 0) { char str[256]; scanf("%s", &str); printf("[%s]", str); // [ ] をつけて出力 fprintf(stderr, "err:%s", str); // err:をつけて出力 *outExitCode = 0; return true; } else if (strcmp(argv[1], "proctest3") == 0) { unsigned char str[4] = { 0xE3, 0x81, 0x82, 0x00 }; // UTF8 'あ' printf((char*)str); *outExitCode = 0; return true; } } return false; } bool myErrorHandler(Exception& e) { ln::detail::printError(e); return true; } int main(int argc, char** argv) { ln::Exception::setNotificationHandler(myErrorHandler); { int exitCode; if (testProcess(argc, argv, &exitCode)) { return exitCode; } } #ifdef _WIN32 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif setlocale(LC_ALL, ""); #ifdef __EMSCRIPTEN__ { emscripten_push_main_loop_blocker(pre1, (void*)123); emscripten_set_main_loop(ems_loop, 60, true); } #endif TestHelper::setAssetsDirPath(LN_LOCALFILE("TestData")); TestHelper::setTempDirPath(_T("TestTemp")); GlobalLogger::addStdErrAdapter(); LN_LOG_INFO << "Running test."; char* testArgs[] = { argv[0], "--gtest_break_on_failure", //"--gtest_filter=Test_IO_FileSystem.LastModifiedTime" }; argc = sizeof(testArgs) / sizeof(char*); testing::InitGoogleTest(&argc, (char**)testArgs); return RUN_ALL_TESTS(); } #endif <commit_msg>link lib<commit_after> #include <stdio.h> #include "Common.hpp" #include <LuminoCore.hpp> #ifdef __EMSCRIPTEN__ #include <emscripten.h> static volatile bool g_ioDione = false; extern "C" void setIODone() { printf("called setIODone()\n"); g_ioDione = true; } void pre1(void *arg) { EM_ASM( //create your directory where we keep our persistent data FS.mkdir('/persistent_data'); //mount persistent directory as IDBFS FS.mount(IDBFS,{},'/persistent_data'); Module.print("start file sync.."); //flag to check when data are synchronized Module.syncdone = 0; //populate persistent_data directory with existing persistent source data //stored with Indexed Db //first parameter = "true" mean synchronize from Indexed Db to //Emscripten file system, // "false" mean synchronize from Emscripten file system to Indexed Db //second parameter = function called when data are synchronized FS.syncfs(true, function(err) { assert(!err); Module.print("end file sync.."); Module.syncdone = 1; //Module.ccall('setIODone', ""); }); ); printf("waiting\n"); //while (!g_ioDione) { //} printf("wait end\n"); } static void ems_loop() { static int count = 0; if (count == 10) { { FILE* fp = fopen("/persistent_data/out.txt", "r"); if (fp) { printf("open file."); char str[256]; fgets(str, 256, fp); printf(str); } else { printf("no file."); } } FILE* fp = fopen("/persistent_data/out.txt", "w"); if (!fp) { printf("failed fp."); return; } printf("fp:%p\n", fp); fprintf(fp, "test"); fclose(fp); //persist Emscripten current data to Indexed Db EM_ASM( Module.print("Start File sync.."); Module.syncdone = 0; FS.syncfs(false, function(err) { assert(!err); Module.print("End File sync.."); Module.syncdone = 1; }); ); } if (count == 50) { { FILE* fp = fopen("/persistent_data/out.txt", "r"); if (fp) { printf("open file.\n"); char str[256]; fgets(str, 256, fp); printf(str); } else { printf("no file.\n"); } } } if (count == 60) { emscripten_cancel_main_loop(); } printf("count:%d\n", count); count++; } static void main_loop() { static int init = 0; if (!init) { init = 1; char* testArgs[] = { "", "--gtest_break_on_failure", "--gtest_filter=Test_IO_FileSystem.*" }; int argc = sizeof(testArgs) / sizeof(char*); testing::InitGoogleTest(&argc, (char**)testArgs); RUN_ALL_TESTS(); } } int main(int argc, char** argv) { setlocale(LC_ALL, ""); printf("Running test.\n"); emscripten_set_main_loop(main_loop, 1, true); return 0; } #else bool testProcess(int argc, char** argv, int* outExitCode) { if (argc >= 2) { if (strcmp(argv[1], "proctest1") == 0) { *outExitCode = 2; return true; } else if (strcmp(argv[1], "proctest2") == 0) { char str[256]; scanf("%s", &str); printf("[%s]", str); // [ ] をつけて出力 fprintf(stderr, "err:%s", str); // err:をつけて出力 *outExitCode = 0; return true; } else if (strcmp(argv[1], "proctest3") == 0) { unsigned char str[4] = { 0xE3, 0x81, 0x82, 0x00 }; // UTF8 'あ' printf((char*)str); *outExitCode = 0; return true; } } return false; } bool myErrorHandler(Exception& e) { ln::detail::printError(e); return true; } int main(int argc, char** argv) { ln::Exception::setNotificationHandler(myErrorHandler); { int exitCode; if (testProcess(argc, argv, &exitCode)) { return exitCode; } } #ifdef _WIN32 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif setlocale(LC_ALL, ""); #ifdef __EMSCRIPTEN__ { emscripten_push_main_loop_blocker(pre1, (void*)123); emscripten_set_main_loop(ems_loop, 60, true); } #endif TestHelper::setAssetsDirPath(LN_LOCALFILE("TestData")); TestHelper::setTempDirPath(_T("TestTemp")); GlobalLogger::addStdErrAdapter(); LN_LOG_INFO << "Running test."; char* testArgs[] = { argv[0], "--gtest_break_on_failure", //"--gtest_filter=Test_IO_FileSystem.LastModifiedTime" }; argc = sizeof(testArgs) / sizeof(char*); testing::InitGoogleTest(&argc, (char**)testArgs); return RUN_ALL_TESTS(); } #endif <|endoftext|>
<commit_before>#include "McMaker/TpcEffFitter.h" #include "Common.h" // ROOT #include "TGraphAsymmErrors.h" #include "TFile.h" #include "Logger.h" #include "Reporter.h" #include "RooPlotLib.h" using namespace jdb; TpcEffFitter::TpcEffFitter( XmlConfig * _cfg, string _nodePath ){ DEBUG( "( " << _cfg << ", " << _nodePath << " )" ) cfg = _cfg; nodePath = _nodePath; outputPath = cfg->getString( nodePath + "output:path", "" ); book = unique_ptr<HistoBook>( new HistoBook( outputPath + cfg->getString( nodePath + "output.data", "TpcEff.root" ), cfg, "", "" ) ); } void TpcEffFitter::make(){ DEBUG("") gStyle->SetOptFit( 111 ); string params_file = cfg->getString( nodePath + "output.params" ); if ( "" == params_file ){ ERROR( "Specifiy an output params file for the parameters" ) return; } ofstream out( params_file.c_str() ); out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; out << "<config>" << endl; vector<string> labels = cfg->getStringVector( nodePath + "CentralityLabels" ); vector< int> cbins = cfg->getIntVector( nodePath + "CentralityBins" ); Reporter rp( cfg, nodePath + "Reporter." ); DEBUG( "Starting plc loop" ) for ( string plc : Common::species ){ if ( "E" == plc || "D" == plc ) continue; for ( string c : Common::sCharges ){ out << "\t<" << plc << "_" << c << ">" << endl; string fnMc = cfg->getString( nodePath + "input:url" ) + "TpcEff_" + plc + "_" + c + "_mc" + ".root"; TFile * fmc = new TFile( fnMc.c_str(), "READ" ); string fnRc = cfg->getString( nodePath + "input:url" ) + "TpcEff_" + plc + "_" + c + "_rc" + ".root"; TFile * frc = new TFile( fnRc.c_str(), "READ" ); DEBUG( "Mc File = " << fmc ) DEBUG( "Rc File = " << frc ) if ( !fmc->IsOpen() || !frc->IsOpen() ) continue; // build an efficiency for each centrality for ( int b : cbins ){ TH1 * hMc = (TH1*)fmc->Get( ("inclusive/pt_" + ts( b ) + "_" + c ).c_str() ); TH1 * hRc = (TH1*)frc->Get( ("inclusive/pt_" + ts( b ) + "_" + c ).c_str() ); INFO( tag, "N bins MC = " << hMc->GetNbinsX() ); INFO( tag, "N bins RC = " << hRc->GetNbinsX() ); for ( int i = 0; i <= hMc->GetNbinsX() + 1; i++ ){ if ( hMc->GetBinContent( i ) < hRc->GetBinContent( i ) ){ // set to 100% if ( i > 5 ) hMc->SetBinContent( i, hRc->GetBinContent( i ) ); else{ hRc->SetBinContent( i, 0 ); hMc->SetBinContent( i, 0 ); } } } hMc->Sumw2(); hRc->Sumw2(); TGraphAsymmErrors g; g.SetName( (plc + "_" + c + "_" + ts(b)).c_str() ); g.BayesDivide( hRc, hMc ); book->add( plc + "_" + c + "_" + ts(b), &g ); // do the fit TF1 * fitFunc = new TF1( "effFitFunc", "[0] * exp( - pow( [1] / x, [2] ) )", 0.0, 5.0 ); fitFunc->SetParameters( .85, 0.05, 5.0, -0.05 ); fitFunc->SetParLimits( 0, 0.5, 1.0 ); fitFunc->SetParLimits( 1, 0.0, 0.5 ); fitFunc->SetParLimits( 2, 0.0, 100000 ); // fist fit shape TFitResultPtr fitPointer = g.Fit( fitFunc, "RSWW" ); // fitFunc->FixParameter( 1, fitFunc->GetParameter( 1 ) ); // fitFunc->FixParameter( 2, fitFunc->GetParameter( 2 ) ); fitPointer = g.Fit( fitFunc, "RS" ); // fitFunc->ReleaseParameter( 1 ); // fitFunc->ReleaseParameter( 2 ); INFO( tag, "FitPointer = " << fitPointer ); TGraphErrors * band = Common::choleskyBands( fitPointer, fitFunc, 5000, 200, &rp ); RooPlotLib rpl; rp.newPage(); rpl.style( &g ).set( "title", Common::plc_label( plc, c ) + " : " + labels[ b ] + ", 68%CL (Red)" ).set( "yr", 0, 1.1 ).set( "optfit", 111 ) .set( "xr", 0, 4.5 ) .set("y", "Efficiency x Acceptance").set( "x", "p_{T}^{MC} [GeV/c]" ).draw(); gStyle->SetStatY( 0.5 ); gStyle->SetStatX( 0.85 ); fitFunc->SetLineColor( kRed ); fitFunc->Draw("same"); // TH1 * band2 = Common::fitCL( fitFunc, "bands", 0.95 ); // band2->SetFillColorAlpha( kBlue, 0.5 ); band->SetFillColorAlpha( kRed, 0.5 ); // band2->Draw( "same e3" ); band->Draw( "same e3" ); rp.savePage(); exportParams( b, fitFunc, fitPointer, out ); } // loop centrality bins out << "\t</" << plc << "_" << c << ">" << endl; } } out << "</config>" << endl; out.close(); } void TpcEffFitter::exportParams( int bin, TF1 * f, TFitResultPtr result, ofstream &out ){ INFO( tag, "(bin=" << bin << ", f=" << f << ", fPtr=" << result << " )" ) out << "\t\t<TpcEffParams bin=\"" << bin << "\" "; out << Common::toXml( f, result ); out << "/>" << endl; }<commit_msg>tpc eff fitter<commit_after>#include "McMaker/TpcEffFitter.h" #include "Common.h" // ROOT #include "TGraphAsymmErrors.h" #include "TFile.h" #include "Logger.h" #include "Reporter.h" #include "RooPlotLib.h" using namespace jdb; TpcEffFitter::TpcEffFitter( XmlConfig * _cfg, string _nodePath ){ DEBUG( "( " << _cfg << ", " << _nodePath << " )" ) cfg = _cfg; nodePath = _nodePath; outputPath = cfg->getString( nodePath + "output:path", "" ); book = unique_ptr<HistoBook>( new HistoBook( outputPath + cfg->getString( nodePath + "output.data", "TpcEff.root" ), cfg, "", "" ) ); } void TpcEffFitter::make(){ DEBUG("") gStyle->SetOptFit( 111 ); string params_file = cfg->getString( nodePath + "output.params" ); if ( "" == params_file ){ ERROR( "Specifiy an output params file for the parameters" ) return; } ofstream out( params_file.c_str() ); out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl; out << "<config>" << endl; vector<string> labels = cfg->getStringVector( nodePath + "CentralityLabels" ); vector< int> cbins = cfg->getIntVector( nodePath + "CentralityBins" ); Reporter rp( cfg, nodePath + "Reporter." ); DEBUG( "Starting plc loop" ) for ( string plc : Common::species ){ if ( "E" == plc || "D" == plc ) continue; for ( string c : Common::sCharges ){ out << "\t<" << plc << "_" << c << ">" << endl; string fnMc = cfg->getString( nodePath + "input:url" ) + "TpcEff_" + plc + "_" + c + "_mc" + ".root"; TFile * fmc = new TFile( fnMc.c_str(), "READ" ); string fnRc = cfg->getString( nodePath + "input:url" ) + "TpcEff_" + plc + "_" + c + "_rc" + ".root"; TFile * frc = new TFile( fnRc.c_str(), "READ" ); DEBUG( "Mc File = " << fmc ) DEBUG( "Rc File = " << frc ) if ( !fmc->IsOpen() || !frc->IsOpen() ) continue; // build an efficiency for each centrality for ( int b : cbins ){ TH1 * hMc = (TH1*)fmc->Get( ("inclusive/pt_" + ts( b ) + "_" + c ).c_str() ); TH1 * hRc = (TH1*)frc->Get( ("inclusive/pt_" + ts( b ) + "_" + c ).c_str() ); INFO( tag, "N bins MC = " << hMc->GetNbinsX() ); INFO( tag, "N bins RC = " << hRc->GetNbinsX() ); for ( int i = 0; i <= hMc->GetNbinsX() + 1; i++ ){ if ( hMc->GetBinContent( i ) < hRc->GetBinContent( i ) ){ // set to 100% if ( i > 5 ) hMc->SetBinContent( i, hRc->GetBinContent( i ) ); else{ hRc->SetBinContent( i, 0 ); hMc->SetBinContent( i, 0 ); } } } hMc->Sumw2(); hRc->Sumw2(); TGraphAsymmErrors g; g.SetName( (plc + "_" + c + "_" + ts(b)).c_str() ); g.BayesDivide( hRc, hMc ); book->add( plc + "_" + c + "_" + ts(b), &g ); // do the fit TF1 * fitFunc = new TF1( "effFitFunc", "[0] * exp( - pow( [1] / x, [2] ) )", 0.0, 5.0 ); fitFunc->SetParameters( .85, 0.05, 5.0, -0.05 ); fitFunc->SetParLimits( 0, 0.5, 1.0 ); fitFunc->SetParLimits( 1, 0.0, 0.5 ); fitFunc->SetParLimits( 2, 0.0, 100000 ); // fist fit shape TFitResultPtr fitPointer = g.Fit( fitFunc, "RSWW" ); // fitFunc->FixParameter( 1, fitFunc->GetParameter( 1 ) ); // fitFunc->FixParameter( 2, fitFunc->GetParameter( 2 ) ); fitPointer = g.Fit( fitFunc, "RS" ); // fitFunc->ReleaseParameter( 1 ); // fitFunc->ReleaseParameter( 2 ); INFO( tag, "FitPointer = " << fitPointer ); TGraphErrors * band = Common::choleskyBands( fitPointer, fitFunc, 5000, 200, &rp ); RooPlotLib rpl; rp.newPage(); rpl.style( &g ).set( "title", Common::plc_label( plc, c ) + " : " + labels[ b ] + ", 68%CL (Red)" ).set( "yr", 0, 1.1 ).set( "optfit", 111 ) .set( "xr", 0, 4.5 ) .set("y", "Efficiency x Acceptance").set( "x", "p_{T}^{MC} [GeV/c]" ).draw(); INFO( tag, "Stat Box" ); gStyle->SetStatY( 0.5 ); gStyle->SetStatX( 0.85 ); fitFunc->SetLineColor( kRed ); fitFunc->Draw("same"); INFO( tag, "Drawing CL band" ); // TH1 * band2 = Common::fitCL( fitFunc, "bands", 0.95 ); // band2->SetFillColorAlpha( kBlue, 0.5 ); band->SetFillColorAlpha( kRed, 0.5 ); // band2->Draw( "same e3" ); band->Draw( "same e3" ); rp.savePage(); INFO( tag, "Exporting Params" ); exportParams( b, fitFunc, fitPointer, out ); } // loop centrality bins out << "\t</" << plc << "_" << c << ">" << endl; } } out << "</config>" << endl; out.close(); } void TpcEffFitter::exportParams( int bin, TF1 * f, TFitResultPtr result, ofstream &out ){ INFO( tag, "(bin=" << bin << ", f=" << f << ", fPtr=" << result << " )" ) out << "\t\t<TpcEffParams bin=\"" << bin << "\" "; out << Common::toXml( f, result ); out << "/>" << endl; }<|endoftext|>
<commit_before>/** Count Vowels program - Enter some text and the program automatically counts the vowels and returns the total. * Copyrights (c) Frédéric Charette - 2016 * * for some reason; the code does not prompt for text on mobile... */ #include <iostream> #include <string> #include <cstdlib> using namespace std; void ProgHeader(){ cout << "Welcome to the Count Vowel Program. This program will take your input on a text and return the amount of vowels in the text... \n\n"; } int main() { char cTxt; int iCountVowels = 0; int iCountAs = 0; int iCountEs = 0; int iCountIs = 0; int iCountOs = 0; int iCountUs = 0; int iCountYs = 0; string sTextToCheck; ProgHeader(); cout << "Please enter the text to count vowels from:"; getline(cin, sTextToCheck); cout << endl << endl; for (int i = 0; i < sTextToCheck.size(); i++){ cTxt = sTextToCheck[i]; cTxt = toupper(cTxt); switch(cTxt){ case 'A': iCountAs++; iCountVowels++; break; case 'E': iCountEs++; iCountVowels++; break; case 'I': iCountIs++; iCountVowels++; break; case 'O': iCountOs++; iCountVowels++; break; case 'U': iCountUs++; iCountVowels++; break; case 'Y': iCountYs++; iCountVowels++; break; default : //not a vowels break; } } cout << "There are " << iCountVowels << " vowels in this text." << endl; cout << "There are " << iCountAs << " \"A\"s in this text." << endl; cout << "There are " << iCountEs << " \"E\"s in this text." << endl; cout << "There are " << iCountIs << " \"I\"s in this text." << endl; cout << "There are " << iCountOs << " \"O\"s in this text." << endl; cout << "There are " << iCountUs << " \"U\"s in this text." << endl; cout << "There are " << iCountYs << " \"Y\"s in this text." << endl; return 0; } <commit_msg>Update VowelCount.cpp<commit_after>/** Count Vowels program - Enter some text and the program automatically counts the vowels and returns the total. * Copyrights (c) Frédéric Charette - 2016 * https://github.com/rain79/CPP_Source * */ #include <iostream> #include <string> #include <cstdlib> #include <fstream> using namespace std; double iCountVowels = 0; double iCountAs = 0; double iCountEs = 0; double iCountIs = 0; double iCountOs = 0; double iCountUs = 0; double iCountYs = 0; string ProgMenu(){ string sSelection; char cSelect; cout << "Let's begin by making a selection from the following menu: \n"; cout << "Enter a (F)ile Name (include the full path if the file is not in the same directory).\n"; cout << "Enter the (T)ext directly in the console.\n"; cout << "(Q)uit\n\n\n"; cout << "Please make your selection now:"; cin >> cSelect; cin.ignore(); cin.clear(); sSelection = toupper(cSelect); if(sSelection == "F" || sSelection == "T" || sSelection =="Q"){ return sSelection; } else { ProgMenu(); } } void CountVowels (string sTextToCheck){ char cTxt; for (int i = 0; i < sTextToCheck.size()+1; i++){ //cout << cTxt << endl; cTxt = sTextToCheck[i]; cTxt = toupper(cTxt); switch(cTxt){ case 'A': iCountAs++; iCountVowels++; break; case 'E': iCountEs++; iCountVowels++; break; case 'I': iCountIs++; iCountVowels++; break; case 'O': iCountOs++; iCountVowels++; break; case 'U': iCountUs++; iCountVowels++; break; case 'Y': iCountYs++; iCountVowels++; break; default : //not a vowels break; } } } void OpenFile(){ string sFileName; string sReadLine; cout << "Please enter the name of the file you wish to work with: "; getline(cin, sFileName); cout << endl; ifstream MyFile(sFileName.c_str()); if(!MyFile.is_open()){ cout << "There was an error opening this file. Please try again\n\n"; cout << "If the file is not in the same path as this application,\n"; cout << "Be sure to specify the full path.\n" OpenFile(); } else { while (getline (MyFile, sReadLine) ) { CountVowels(sReadLine); } MyFile.close(); } } int main() { string sSelect; string sReadLine; cout << "Welcome to the Count Vowel Program!\n"; cout << "This program will take a text and return the amount of vowels in the text... \n\n"; sSelect = ProgMenu(); cout << sSelect; if (sSelect == "F"){ OpenFile(); } else if (sSelect == "T"){ cout << "Please enter the text below. (Press enter to analyze the text...)\n"; getline(cin, sReadLine); CountVowels(sReadLine); } else if (sSelect == "Q"){ return 0; } else { cout << "An error has occured... Please try again."; return 0; } cout << "There are " << iCountVowels << " vowels in this text." << endl; cout << "There are " << iCountAs << " \"A\"s in this text." << endl; cout << "There are " << iCountEs << " \"E\"s in this text." << endl; cout << "There are " << iCountIs << " \"I\"s in this text." << endl; cout << "There are " << iCountOs << " \"O\"s in this text." << endl; cout << "There are " << iCountUs << " \"U\"s in this text." << endl; cout << "There are " << iCountYs << " \"Y\"s in this text." << endl; return 0; } <|endoftext|>
<commit_before>//===- TableGen.cpp - Top-Level TableGen implementation for Clang ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the main function for Clang's TableGen. // //===----------------------------------------------------------------------===// #include "TableGenBackends.h" // Declares all backends. #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" using namespace llvm; using namespace clang; enum ActionType { GenClangAttrClasses, GenClangAttrParserStringSwitches, GenClangAttrImpl, GenClangAttrList, GenClangAttrPCHRead, GenClangAttrPCHWrite, GenClangAttrHasAttributeImpl, GenClangAttrSpellingListIndex, GenClangAttrASTVisitor, GenClangAttrTemplateInstantiate, GenClangAttrParsedAttrList, GenClangAttrParsedAttrImpl, GenClangAttrParsedAttrKinds, GenClangAttrDump, GenClangDiagsDefs, GenClangDiagGroups, GenClangDiagsIndexName, GenClangCommentNodes, GenClangDeclNodes, GenClangStmtNodes, GenClangSACheckers, GenClangCommentHTMLTags, GenClangCommentHTMLTagsProperties, GenClangCommentHTMLNamedCharacterReferences, GenClangCommentCommandInfo, GenClangCommentCommandList, GenArmNeon, GenArmNeonSema, GenArmNeonTest, GenAttrDocs }; namespace { cl::opt<ActionType> Action( cl::desc("Action to perform:"), cl::values( clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes", "Generate clang attribute clases"), clEnumValN(GenClangAttrParserStringSwitches, "gen-clang-attr-parser-string-switches", "Generate all parser-related attribute string switches"), clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl", "Generate clang attribute implementations"), clEnumValN(GenClangAttrList, "gen-clang-attr-list", "Generate a clang attribute list"), clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read", "Generate clang PCH attribute reader"), clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write", "Generate clang PCH attribute writer"), clEnumValN(GenClangAttrHasAttributeImpl, "gen-clang-attr-has-attribute-impl", "Generate a clang attribute spelling list"), clEnumValN(GenClangAttrSpellingListIndex, "gen-clang-attr-spelling-index", "Generate a clang attribute spelling index"), clEnumValN(GenClangAttrASTVisitor, "gen-clang-attr-ast-visitor", "Generate a recursive AST visitor for clang attributes"), clEnumValN(GenClangAttrTemplateInstantiate, "gen-clang-attr-template-instantiate", "Generate a clang template instantiate code"), clEnumValN(GenClangAttrParsedAttrList, "gen-clang-attr-parsed-attr-list", "Generate a clang parsed attribute list"), clEnumValN(GenClangAttrParsedAttrImpl, "gen-clang-attr-parsed-attr-impl", "Generate the clang parsed attribute helpers"), clEnumValN(GenClangAttrParsedAttrKinds, "gen-clang-attr-parsed-attr-kinds", "Generate a clang parsed attribute kinds"), clEnumValN(GenClangAttrDump, "gen-clang-attr-dump", "Generate clang attribute dumper"), clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs", "Generate Clang diagnostics definitions"), clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups", "Generate Clang diagnostic groups"), clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name", "Generate Clang diagnostic name index"), clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes", "Generate Clang AST comment nodes"), clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes", "Generate Clang AST declaration nodes"), clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes", "Generate Clang AST statement nodes"), clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers", "Generate Clang Static Analyzer checkers"), clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags", "Generate efficient matchers for HTML tag " "names that are used in documentation comments"), clEnumValN(GenClangCommentHTMLTagsProperties, "gen-clang-comment-html-tags-properties", "Generate efficient matchers for HTML tag " "properties"), clEnumValN(GenClangCommentHTMLNamedCharacterReferences, "gen-clang-comment-html-named-character-references", "Generate function to translate named character " "references to UTF-8 sequences"), clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info", "Generate command properties for commands that " "are used in documentation comments"), clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list", "Generate list of commands that are used in " "documentation comments"), clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"), clEnumValN(GenArmNeonSema, "gen-arm-neon-sema", "Generate ARM NEON sema support for clang"), clEnumValN(GenArmNeonTest, "gen-arm-neon-test", "Generate ARM NEON tests for clang"), clEnumValN(GenAttrDocs, "gen-attr-docs", "Generate attribute documentation"), clEnumValEnd)); cl::opt<std::string> ClangComponent("clang-component", cl::desc("Only use warnings from specified component"), cl::value_desc("component"), cl::Hidden); bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) { switch (Action) { case GenClangAttrClasses: EmitClangAttrClass(Records, OS); break; case GenClangAttrParserStringSwitches: EmitClangAttrParserStringSwitches(Records, OS); break; case GenClangAttrImpl: EmitClangAttrImpl(Records, OS); break; case GenClangAttrList: EmitClangAttrList(Records, OS); break; case GenClangAttrPCHRead: EmitClangAttrPCHRead(Records, OS); break; case GenClangAttrPCHWrite: EmitClangAttrPCHWrite(Records, OS); break; case GenClangAttrHasAttributeImpl: EmitClangAttrHasAttrImpl(Records, OS); break; case GenClangAttrSpellingListIndex: EmitClangAttrSpellingListIndex(Records, OS); break; case GenClangAttrASTVisitor: EmitClangAttrASTVisitor(Records, OS); break; case GenClangAttrTemplateInstantiate: EmitClangAttrTemplateInstantiate(Records, OS); break; case GenClangAttrParsedAttrList: EmitClangAttrParsedAttrList(Records, OS); break; case GenClangAttrParsedAttrImpl: EmitClangAttrParsedAttrImpl(Records, OS); break; case GenClangAttrParsedAttrKinds: EmitClangAttrParsedAttrKinds(Records, OS); break; case GenClangAttrDump: EmitClangAttrDump(Records, OS); break; case GenClangDiagsDefs: EmitClangDiagsDefs(Records, OS, ClangComponent); break; case GenClangDiagGroups: EmitClangDiagGroups(Records, OS); break; case GenClangDiagsIndexName: EmitClangDiagsIndexName(Records, OS); break; case GenClangCommentNodes: EmitClangASTNodes(Records, OS, "Comment", ""); break; case GenClangDeclNodes: EmitClangASTNodes(Records, OS, "Decl", "Decl"); EmitClangDeclContext(Records, OS); break; case GenClangStmtNodes: EmitClangASTNodes(Records, OS, "Stmt", ""); break; case GenClangSACheckers: EmitClangSACheckers(Records, OS); break; case GenClangCommentHTMLTags: EmitClangCommentHTMLTags(Records, OS); break; case GenClangCommentHTMLTagsProperties: EmitClangCommentHTMLTagsProperties(Records, OS); break; case GenClangCommentHTMLNamedCharacterReferences: EmitClangCommentHTMLNamedCharacterReferences(Records, OS); break; case GenClangCommentCommandInfo: EmitClangCommentCommandInfo(Records, OS); break; case GenClangCommentCommandList: EmitClangCommentCommandList(Records, OS); break; case GenArmNeon: EmitNeon(Records, OS); break; case GenArmNeonSema: EmitNeonSema(Records, OS); break; case GenArmNeonTest: EmitNeonTest(Records, OS); break; case GenAttrDocs: EmitClangAttrDocs(Records, OS); break; } return false; } } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); llvm_shutdown_obj Y; return TableGenMain(argv[0], &ClangTableGenMain); } #ifdef __has_feature #if __has_feature(address_sanitizer) #include <sanitizer/lsan_interface.h> // Disable LeakSanitizer for this binary as it has too many leaks that are not // very interesting to fix. See compiler-rt/include/sanitizer/lsan_interface.h . int __lsan_is_turned_off() { return 1; } #endif // __has_feature(address_sanitizer) #endif // defined(__has_feature) <commit_msg>[clang-tblgen] Remove unused #include (NFC)<commit_after>//===- TableGen.cpp - Top-Level TableGen implementation for Clang ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the main function for Clang's TableGen. // //===----------------------------------------------------------------------===// #include "TableGenBackends.h" // Declares all backends. #include "llvm/Support/CommandLine.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Main.h" #include "llvm/TableGen/Record.h" using namespace llvm; using namespace clang; enum ActionType { GenClangAttrClasses, GenClangAttrParserStringSwitches, GenClangAttrImpl, GenClangAttrList, GenClangAttrPCHRead, GenClangAttrPCHWrite, GenClangAttrHasAttributeImpl, GenClangAttrSpellingListIndex, GenClangAttrASTVisitor, GenClangAttrTemplateInstantiate, GenClangAttrParsedAttrList, GenClangAttrParsedAttrImpl, GenClangAttrParsedAttrKinds, GenClangAttrDump, GenClangDiagsDefs, GenClangDiagGroups, GenClangDiagsIndexName, GenClangCommentNodes, GenClangDeclNodes, GenClangStmtNodes, GenClangSACheckers, GenClangCommentHTMLTags, GenClangCommentHTMLTagsProperties, GenClangCommentHTMLNamedCharacterReferences, GenClangCommentCommandInfo, GenClangCommentCommandList, GenArmNeon, GenArmNeonSema, GenArmNeonTest, GenAttrDocs }; namespace { cl::opt<ActionType> Action( cl::desc("Action to perform:"), cl::values( clEnumValN(GenClangAttrClasses, "gen-clang-attr-classes", "Generate clang attribute clases"), clEnumValN(GenClangAttrParserStringSwitches, "gen-clang-attr-parser-string-switches", "Generate all parser-related attribute string switches"), clEnumValN(GenClangAttrImpl, "gen-clang-attr-impl", "Generate clang attribute implementations"), clEnumValN(GenClangAttrList, "gen-clang-attr-list", "Generate a clang attribute list"), clEnumValN(GenClangAttrPCHRead, "gen-clang-attr-pch-read", "Generate clang PCH attribute reader"), clEnumValN(GenClangAttrPCHWrite, "gen-clang-attr-pch-write", "Generate clang PCH attribute writer"), clEnumValN(GenClangAttrHasAttributeImpl, "gen-clang-attr-has-attribute-impl", "Generate a clang attribute spelling list"), clEnumValN(GenClangAttrSpellingListIndex, "gen-clang-attr-spelling-index", "Generate a clang attribute spelling index"), clEnumValN(GenClangAttrASTVisitor, "gen-clang-attr-ast-visitor", "Generate a recursive AST visitor for clang attributes"), clEnumValN(GenClangAttrTemplateInstantiate, "gen-clang-attr-template-instantiate", "Generate a clang template instantiate code"), clEnumValN(GenClangAttrParsedAttrList, "gen-clang-attr-parsed-attr-list", "Generate a clang parsed attribute list"), clEnumValN(GenClangAttrParsedAttrImpl, "gen-clang-attr-parsed-attr-impl", "Generate the clang parsed attribute helpers"), clEnumValN(GenClangAttrParsedAttrKinds, "gen-clang-attr-parsed-attr-kinds", "Generate a clang parsed attribute kinds"), clEnumValN(GenClangAttrDump, "gen-clang-attr-dump", "Generate clang attribute dumper"), clEnumValN(GenClangDiagsDefs, "gen-clang-diags-defs", "Generate Clang diagnostics definitions"), clEnumValN(GenClangDiagGroups, "gen-clang-diag-groups", "Generate Clang diagnostic groups"), clEnumValN(GenClangDiagsIndexName, "gen-clang-diags-index-name", "Generate Clang diagnostic name index"), clEnumValN(GenClangCommentNodes, "gen-clang-comment-nodes", "Generate Clang AST comment nodes"), clEnumValN(GenClangDeclNodes, "gen-clang-decl-nodes", "Generate Clang AST declaration nodes"), clEnumValN(GenClangStmtNodes, "gen-clang-stmt-nodes", "Generate Clang AST statement nodes"), clEnumValN(GenClangSACheckers, "gen-clang-sa-checkers", "Generate Clang Static Analyzer checkers"), clEnumValN(GenClangCommentHTMLTags, "gen-clang-comment-html-tags", "Generate efficient matchers for HTML tag " "names that are used in documentation comments"), clEnumValN(GenClangCommentHTMLTagsProperties, "gen-clang-comment-html-tags-properties", "Generate efficient matchers for HTML tag " "properties"), clEnumValN(GenClangCommentHTMLNamedCharacterReferences, "gen-clang-comment-html-named-character-references", "Generate function to translate named character " "references to UTF-8 sequences"), clEnumValN(GenClangCommentCommandInfo, "gen-clang-comment-command-info", "Generate command properties for commands that " "are used in documentation comments"), clEnumValN(GenClangCommentCommandList, "gen-clang-comment-command-list", "Generate list of commands that are used in " "documentation comments"), clEnumValN(GenArmNeon, "gen-arm-neon", "Generate arm_neon.h for clang"), clEnumValN(GenArmNeonSema, "gen-arm-neon-sema", "Generate ARM NEON sema support for clang"), clEnumValN(GenArmNeonTest, "gen-arm-neon-test", "Generate ARM NEON tests for clang"), clEnumValN(GenAttrDocs, "gen-attr-docs", "Generate attribute documentation"), clEnumValEnd)); cl::opt<std::string> ClangComponent("clang-component", cl::desc("Only use warnings from specified component"), cl::value_desc("component"), cl::Hidden); bool ClangTableGenMain(raw_ostream &OS, RecordKeeper &Records) { switch (Action) { case GenClangAttrClasses: EmitClangAttrClass(Records, OS); break; case GenClangAttrParserStringSwitches: EmitClangAttrParserStringSwitches(Records, OS); break; case GenClangAttrImpl: EmitClangAttrImpl(Records, OS); break; case GenClangAttrList: EmitClangAttrList(Records, OS); break; case GenClangAttrPCHRead: EmitClangAttrPCHRead(Records, OS); break; case GenClangAttrPCHWrite: EmitClangAttrPCHWrite(Records, OS); break; case GenClangAttrHasAttributeImpl: EmitClangAttrHasAttrImpl(Records, OS); break; case GenClangAttrSpellingListIndex: EmitClangAttrSpellingListIndex(Records, OS); break; case GenClangAttrASTVisitor: EmitClangAttrASTVisitor(Records, OS); break; case GenClangAttrTemplateInstantiate: EmitClangAttrTemplateInstantiate(Records, OS); break; case GenClangAttrParsedAttrList: EmitClangAttrParsedAttrList(Records, OS); break; case GenClangAttrParsedAttrImpl: EmitClangAttrParsedAttrImpl(Records, OS); break; case GenClangAttrParsedAttrKinds: EmitClangAttrParsedAttrKinds(Records, OS); break; case GenClangAttrDump: EmitClangAttrDump(Records, OS); break; case GenClangDiagsDefs: EmitClangDiagsDefs(Records, OS, ClangComponent); break; case GenClangDiagGroups: EmitClangDiagGroups(Records, OS); break; case GenClangDiagsIndexName: EmitClangDiagsIndexName(Records, OS); break; case GenClangCommentNodes: EmitClangASTNodes(Records, OS, "Comment", ""); break; case GenClangDeclNodes: EmitClangASTNodes(Records, OS, "Decl", "Decl"); EmitClangDeclContext(Records, OS); break; case GenClangStmtNodes: EmitClangASTNodes(Records, OS, "Stmt", ""); break; case GenClangSACheckers: EmitClangSACheckers(Records, OS); break; case GenClangCommentHTMLTags: EmitClangCommentHTMLTags(Records, OS); break; case GenClangCommentHTMLTagsProperties: EmitClangCommentHTMLTagsProperties(Records, OS); break; case GenClangCommentHTMLNamedCharacterReferences: EmitClangCommentHTMLNamedCharacterReferences(Records, OS); break; case GenClangCommentCommandInfo: EmitClangCommentCommandInfo(Records, OS); break; case GenClangCommentCommandList: EmitClangCommentCommandList(Records, OS); break; case GenArmNeon: EmitNeon(Records, OS); break; case GenArmNeonSema: EmitNeonSema(Records, OS); break; case GenArmNeonTest: EmitNeonTest(Records, OS); break; case GenAttrDocs: EmitClangAttrDocs(Records, OS); break; } return false; } } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); llvm_shutdown_obj Y; return TableGenMain(argv[0], &ClangTableGenMain); } #ifdef __has_feature #if __has_feature(address_sanitizer) #include <sanitizer/lsan_interface.h> // Disable LeakSanitizer for this binary as it has too many leaks that are not // very interesting to fix. See compiler-rt/include/sanitizer/lsan_interface.h . int __lsan_is_turned_off() { return 1; } #endif // __has_feature(address_sanitizer) #endif // defined(__has_feature) <|endoftext|>
<commit_before>/* Copyright (c) 2011 Arduino. All right reserved. Copyright (c) 2015 Intel Corporation. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA CDC-ACM class for Arduino 101 - Aug 2015 <[email protected]> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "Arduino.h" #include "portable.h" #include "CDCSerialClass.h" #include "wiring_constants.h" #include "wiring_digital.h" #include "variant.h" extern void CDCSerial_Handler(void); extern void serialEventRun1(void) __attribute__((weak)); extern void serialEvent1(void) __attribute__((weak)); // Constructors //////////////////////////////////////////////////////////////// CDCSerialClass::CDCSerialClass(uart_init_info *info) { this->info = info; } // Public Methods ////////////////////////////////////////////////////////////// void CDCSerialClass::setSharedData(struct cdc_acm_shared_data *cdc_acm_shared_data) { this->_shared_data = cdc_acm_shared_data; this->_rx_buffer = cdc_acm_shared_data->rx_buffer; this->_tx_buffer = cdc_acm_shared_data->tx_buffer; } void CDCSerialClass::begin(const uint32_t dwBaudRate) { begin(dwBaudRate, (uint8_t)SERIAL_8N1 ); } void CDCSerialClass::begin(const uint32_t dwBaudRate, const uint8_t config) { init(dwBaudRate, config ); } void CDCSerialClass::init(const uint32_t dwBaudRate, const uint8_t modeReg) { /* Set a per-byte write delay approximately equal to the time it would * take to clock out a byte on a standard UART at this baud rate */ _writeDelayUsec = 8000000 / dwBaudRate; /* Make sure both ring buffers are initialized back to empty. * Empty the Rx buffer but don't touch Tx buffer: it is drained by the * LMT one way or another */ _rx_buffer->tail = _rx_buffer->head; _shared_data->device_open = true; } void CDCSerialClass::end( void ) { _shared_data->device_open = false; } int CDCSerialClass::available( void ) { #define SBS SERIAL_BUFFER_SIZE return (int)(SBS + _rx_buffer->head - _rx_buffer->tail) % SBS; } int CDCSerialClass::availableForWrite(void) { if (!_shared_data->device_open || !_shared_data->host_open) return(0); int head = _tx_buffer->head; int tail = _tx_buffer->tail; if (head >= tail) return SERIAL_BUFFER_SIZE - head + tail - 1; return tail - head - 1; } int CDCSerialClass::peek(void) { if ( _rx_buffer->head == _rx_buffer->tail ) return -1; return _rx_buffer->data[_rx_buffer->tail]; } int CDCSerialClass::read( void ) { if ( _rx_buffer->head == _rx_buffer->tail ) return -1; uint8_t uc = _rx_buffer->data[_rx_buffer->tail]; _rx_buffer->tail = (_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return uc; } void CDCSerialClass::flush( void ) { while (_tx_buffer->tail != _tx_buffer->head) { /* This infinite loop is intentional and requested by design */ delayMicroseconds(1); } } size_t CDCSerialClass::write( const uint8_t uc_data ) { uint32_t retries = 1; if (!_shared_data->device_open || !_shared_data->host_open) return(0); do { int i = (uint32_t)(_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != _tx_buffer->tail) { _tx_buffer->data[_tx_buffer->head] = uc_data; _tx_buffer->head = i; // Mimick the throughput of a typical UART by throttling the data // flow according to the configured baud rate delayMicroseconds(_writeDelayUsec); break; } } while (retries--); return 1; } <commit_msg>Jira-462: Call Available() after calling end() indicated data available.<commit_after>/* Copyright (c) 2011 Arduino. All right reserved. Copyright (c) 2015 Intel Corporation. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA CDC-ACM class for Arduino 101 - Aug 2015 <[email protected]> */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "Arduino.h" #include "portable.h" #include "CDCSerialClass.h" #include "wiring_constants.h" #include "wiring_digital.h" #include "variant.h" extern void CDCSerial_Handler(void); extern void serialEventRun1(void) __attribute__((weak)); extern void serialEvent1(void) __attribute__((weak)); // Constructors //////////////////////////////////////////////////////////////// CDCSerialClass::CDCSerialClass(uart_init_info *info) { this->info = info; } // Public Methods ////////////////////////////////////////////////////////////// void CDCSerialClass::setSharedData(struct cdc_acm_shared_data *cdc_acm_shared_data) { this->_shared_data = cdc_acm_shared_data; this->_rx_buffer = cdc_acm_shared_data->rx_buffer; this->_tx_buffer = cdc_acm_shared_data->tx_buffer; } void CDCSerialClass::begin(const uint32_t dwBaudRate) { begin(dwBaudRate, (uint8_t)SERIAL_8N1 ); } void CDCSerialClass::begin(const uint32_t dwBaudRate, const uint8_t config) { init(dwBaudRate, config ); } void CDCSerialClass::init(const uint32_t dwBaudRate, const uint8_t modeReg) { /* Set a per-byte write delay approximately equal to the time it would * take to clock out a byte on a standard UART at this baud rate */ _writeDelayUsec = 8000000 / dwBaudRate; /* Make sure both ring buffers are initialized back to empty. * Empty the Rx buffer but don't touch Tx buffer: it is drained by the * LMT one way or another */ _rx_buffer->tail = _rx_buffer->head; _shared_data->device_open = true; } void CDCSerialClass::end( void ) { _shared_data->device_open = false; } int CDCSerialClass::available( void ) { #define SBS SERIAL_BUFFER_SIZE if (!_shared_data->device_open) return (0); else return (int)(SBS + _rx_buffer->head - _rx_buffer->tail) % SBS; } int CDCSerialClass::availableForWrite(void) { if (!_shared_data->device_open || !_shared_data->host_open) return(0); int head = _tx_buffer->head; int tail = _tx_buffer->tail; if (head >= tail) return SERIAL_BUFFER_SIZE - head + tail - 1; return tail - head - 1; } int CDCSerialClass::peek(void) { if ((!_shared_data->device_open) || ( _rx_buffer->head == _rx_buffer->tail )) return -1; return _rx_buffer->data[_rx_buffer->tail]; } int CDCSerialClass::read( void ) { if ((!_shared_data->device_open) || ( _rx_buffer->head == _rx_buffer->tail )) return -1; uint8_t uc = _rx_buffer->data[_rx_buffer->tail]; _rx_buffer->tail = (_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return uc; } void CDCSerialClass::flush( void ) { while (_tx_buffer->tail != _tx_buffer->head) { /* This infinite loop is intentional and requested by design */ delayMicroseconds(1); } } size_t CDCSerialClass::write( const uint8_t uc_data ) { uint32_t retries = 1; if (!_shared_data->device_open || !_shared_data->host_open) return(0); do { int i = (uint32_t)(_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != _tx_buffer->tail) { _tx_buffer->data[_tx_buffer->head] = uc_data; _tx_buffer->head = i; // Mimick the throughput of a typical UART by throttling the data // flow according to the configured baud rate delayMicroseconds(_writeDelayUsec); break; } } while (retries--); return 1; } <|endoftext|>
<commit_before>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which head is the index of the location // to which to write the next incoming character and tail is the index of the // location from which to read. #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer tx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; ring_buffer tx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8535 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_USART0_RECV) && defined(UDR0) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } #elif defined(SIG_UART0_RECV) && defined(UDR0) SIGNAL(SIG_UART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } //#elif defined(SIG_USART_RECV) #elif defined(USART0_RX_vect) // fixed by Mark Sproul this is on the 644/644p //SIGNAL(SIG_USART_RECV) SIGNAL(USART0_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8, atmega32 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_UART_RECV) // this is for atmega8 SIGNAL(SIG_UART_RECV) { #if defined(UDR0) unsigned char c = UDR0; // atmega645 #elif defined(UDR) unsigned char c = UDR; // atmega8 #endif store_char(c, &rx_buffer); } #elif defined(USBCON) #warning No interrupt handler for usart 0 #warning Serial(0) is on USB interface #else #error No interrupt handler for usart 0 #endif //#if defined(SIG_USART1_RECV) #if defined(USART1_RX_vect) //SIGNAL(SIG_USART1_RECV) SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) #error Don't know what the Data Register Empty vector is called for the first UART #else #if defined(UART0_UDRE_vect) ISR(UART0_UDRE_vect) #elif defined(UART_UDRE_vect) ISR(UART_UDRE_vect) #elif defined(USART0_UDRE_vect) ISR(USART0_UDRE_vect) #elif defined(USART_UDRE_vect) ISR(USART_UDRE_vect) #endif { if (tx_buffer.head == tx_buffer.tail) { // Buffer empty, so disable interrupts #if defined(UCSR0B) cbi(UCSR0B, UDRIE0); #else cbi(UCSRB, UDRIE); #endif } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer.buffer[tx_buffer.tail]; tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE; #if defined(UDR0) UDR0 = c; #elif defined(UDR) UDR = c; #else #error UDR not defined #endif } } #endif #ifdef USART1_UDRE_vect ISR(USART1_UDRE_vect) { if (tx_buffer1.head == tx_buffer1.tail) { // Buffer empty, so disable interrupts cbi(UCSR1B, UDRIE1); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer1.buffer[tx_buffer1.tail]; tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE; UDR1 = c; } } #endif #ifdef USART2_UDRE_vect ISR(USART2_UDRE_vect) { if (tx_buffer2.head == tx_buffer2.tail) { // Buffer empty, so disable interrupts cbi(UCSR2B, UDRIE2); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer2.buffer[tx_buffer2.tail]; tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE; UDR2 = c; } } #endif #ifdef USART3_UDRE_vect ISR(USART3_UDRE_vect) { if (tx_buffer3.head == tx_buffer3.tail) { // Buffer empty, so disable interrupts cbi(UCSR3B, UDRIE3); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer3.buffer[tx_buffer3.tail]; tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE; UDR3 = c; } } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x) { _rx_buffer = rx_buffer; _tx_buffer = tx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udrie = udrie; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail) ; cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); // clear any received data _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer->tail) ; _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; sbi(*_ucsrb, _udrie); } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3); #endif #endif // whole file <commit_msg>Changing Serial.flush() to write outgoing data, not drop incoming data.<commit_after>/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 28 September 2010 by Mark Sproul */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "Arduino.h" #include "wiring_private.h" // this next line disables the entire HardwareSerial.cpp, // this is so I can support Attiny series and any other chip without a uart #if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which head is the index of the location // to which to write the next incoming character and tail is the index of the // location from which to read. #if (RAMEND < 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif struct ring_buffer { unsigned char buffer[SERIAL_BUFFER_SIZE]; volatile int head; volatile int tail; }; #if defined(UBRRH) || defined(UBRR0H) ring_buffer rx_buffer = { { 0 }, 0, 0 }; ring_buffer tx_buffer = { { 0 }, 0, 0 }; #endif #if defined(UBRR1H) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer tx_buffer1 = { { 0 }, 0, 0 }; #endif #if defined(UBRR2H) ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer tx_buffer2 = { { 0 }, 0, 0 }; #endif #if defined(UBRR3H) ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; ring_buffer tx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *buffer) { int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer->tail) { buffer->buffer[buffer->head] = c; buffer->head = i; } } #if defined(USART_RX_vect) SIGNAL(USART_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8535 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_USART0_RECV) && defined(UDR0) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } #elif defined(SIG_UART0_RECV) && defined(UDR0) SIGNAL(SIG_UART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } //#elif defined(SIG_USART_RECV) #elif defined(USART0_RX_vect) // fixed by Mark Sproul this is on the 644/644p //SIGNAL(SIG_USART_RECV) SIGNAL(USART0_RX_vect) { #if defined(UDR0) unsigned char c = UDR0; #elif defined(UDR) unsigned char c = UDR; // atmega8, atmega32 #else #error UDR not defined #endif store_char(c, &rx_buffer); } #elif defined(SIG_UART_RECV) // this is for atmega8 SIGNAL(SIG_UART_RECV) { #if defined(UDR0) unsigned char c = UDR0; // atmega645 #elif defined(UDR) unsigned char c = UDR; // atmega8 #endif store_char(c, &rx_buffer); } #elif defined(USBCON) #warning No interrupt handler for usart 0 #warning Serial(0) is on USB interface #else #error No interrupt handler for usart 0 #endif //#if defined(SIG_USART1_RECV) #if defined(USART1_RX_vect) //SIGNAL(SIG_USART1_RECV) SIGNAL(USART1_RX_vect) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } #elif defined(SIG_USART1_RECV) #error SIG_USART1_RECV #endif #if defined(USART2_RX_vect) && defined(UDR2) SIGNAL(USART2_RX_vect) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } #elif defined(SIG_USART2_RECV) #error SIG_USART2_RECV #endif #if defined(USART3_RX_vect) && defined(UDR3) SIGNAL(USART3_RX_vect) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #elif defined(SIG_USART3_RECV) #error SIG_USART3_RECV #endif #if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect) #error Don't know what the Data Register Empty vector is called for the first UART #else #if defined(UART0_UDRE_vect) ISR(UART0_UDRE_vect) #elif defined(UART_UDRE_vect) ISR(UART_UDRE_vect) #elif defined(USART0_UDRE_vect) ISR(USART0_UDRE_vect) #elif defined(USART_UDRE_vect) ISR(USART_UDRE_vect) #endif { if (tx_buffer.head == tx_buffer.tail) { // Buffer empty, so disable interrupts #if defined(UCSR0B) cbi(UCSR0B, UDRIE0); #else cbi(UCSRB, UDRIE); #endif } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer.buffer[tx_buffer.tail]; tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE; #if defined(UDR0) UDR0 = c; #elif defined(UDR) UDR = c; #else #error UDR not defined #endif } } #endif #ifdef USART1_UDRE_vect ISR(USART1_UDRE_vect) { if (tx_buffer1.head == tx_buffer1.tail) { // Buffer empty, so disable interrupts cbi(UCSR1B, UDRIE1); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer1.buffer[tx_buffer1.tail]; tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE; UDR1 = c; } } #endif #ifdef USART2_UDRE_vect ISR(USART2_UDRE_vect) { if (tx_buffer2.head == tx_buffer2.tail) { // Buffer empty, so disable interrupts cbi(UCSR2B, UDRIE2); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer2.buffer[tx_buffer2.tail]; tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE; UDR2 = c; } } #endif #ifdef USART3_UDRE_vect ISR(USART3_UDRE_vect) { if (tx_buffer3.head == tx_buffer3.tail) { // Buffer empty, so disable interrupts cbi(UCSR3B, UDRIE3); } else { // There is more data in the output buffer. Send the next byte unsigned char c = tx_buffer3.buffer[tx_buffer3.tail]; tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE; UDR3 = c; } } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x) { _rx_buffer = rx_buffer; _tx_buffer = tx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udrie = udrie; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x = true; #if F_CPU == 16000000UL // hardcoded exception for compatibility with the bootloader shipped // with the Duemilanove and previous boards and the firmware on the 8U2 // on the Uno and Mega 2560. if (baud == 57600) { use_u2x = false; } #endif if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); } void HardwareSerial::end() { // wait for transmission of outgoing data while (_tx_buffer->head != _tx_buffer->tail) ; cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); cbi(*_ucsrb, _udrie); // clear any received data _rx_buffer->head = _rx_buffer->tail; } int HardwareSerial::available(void) { return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { while (_tx_buffer->head != _tx_buffer->tail) ; } void HardwareSerial::write(uint8_t c) { int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE; // If the output buffer is full, there's nothing for it other than to // wait for the interrupt handler to empty it a bit while (i == _tx_buffer->tail) ; _tx_buffer->buffer[_tx_buffer->head] = c; _tx_buffer->head = i; sbi(*_ucsrb, _udrie); } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X); #elif defined(UBRR0H) && defined(UBRR0L) HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0); #elif defined(USBCON) #warning no serial port defined (port 0) #else #error no serial port defined (port 0) #endif #if defined(UBRR1H) HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1); #endif #if defined(UBRR2H) HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2); #endif #if defined(UBRR3H) HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3); #endif #endif // whole file <|endoftext|>
<commit_before>/** * Eval.cpp * * This file holds the implementation for the Php::eval() function * * @author andot <https://github.com/andot> */ /** * Dependencies */ #include "includes.h" /** * Open PHP namespace */ namespace Php { /** * Evaluate a PHP string * @param phpCode The PHP code to evaluate * @return Value The result of the evaluation */ Value eval(const std::string &phpCode) { // we need the tsrm_ls variable TSRMLS_FETCH(); // the current exception zval* oldException = EG(exception); // the return zval zval* retval = nullptr; if (zend_eval_stringl_ex((char *)phpCode.c_str(), (int32_t)phpCode.length(), retval, (char *)"", 1 TSRMLS_CC) != SUCCESS) { // Do we want to throw an exception here? The original author of this code // did, but there are some reasons not to: // // 1. the PHP eval() function also does not throw exceptions. // // 2. the zend_eval_string() function already triggers a // 'PHP parse error' when an error occurs, which also has // to be handled. If we also throw an exception here, the // user will have to write two error checks: for the error // and the exception. // // if we _do_ want to throw an exception, we will first have to // prevent the original zend_error to occur, and then turn it // into an exception. An exception would be nicer from a C++ // point of view, but because of the extra complexity, we do not // this for now. return nullptr; } else { // was an exception thrown inside the eval()'ed code? In that case we // throw a C++ new exception to give the C++ code the chance to catch it if (oldException != EG(exception) && EG(exception)) throw OrigException(EG(exception) TSRMLS_CC); // no (additional) exception was thrown return retval ? Value(retval) : nullptr; } } /** * Include a file * @param filename * @return Value */ Value include(const std::string &filename) { // we can simply execute a file return File(filename).execute(); } /** * Include a file only once * @param filename * @return Value */ Value include_once(const std::string &filename) { // we can simply execute a file return File(filename).execute(); } /** * Require a file * This causes a fatal error if the file does not exist * @param filename * @return Value */ Value require(const std::string &filename) { // create the file File file(filename); // execute if it exists if (file.exists()) return file.execute(); // trigger fatal error error << filename << " does not exist" << std::flush; // unreachable return nullptr; } /** * Require a file only once * This causes a fatal error if the file does not exist * @param filename * @return Value */ Value require_once(const std::string &filename) { // create the file File file(filename); // execute if it exists if (file.exists()) return file.once(); // trigger fatal error error << filename << " does not exist" << std::flush; // unreachable return nullptr; } /** * End of namespace */ } <commit_msg>fixed return value problem in the Php::eval() function (also solved in issue #129)<commit_after>/** * Eval.cpp * * This file holds the implementation for the Php::eval() function * * @author andot <https://github.com/andot> */ /** * Dependencies */ #include "includes.h" /** * Open PHP namespace */ namespace Php { /** * Evaluate a PHP string * @param phpCode The PHP code to evaluate * @return Value The result of the evaluation */ Value eval(const std::string &phpCode) { // we need the tsrm_ls variable TSRMLS_FETCH(); // the current exception zval* oldException = EG(exception); // the return va zval *retval = nullptr; MAKE_STD_ZVAL(retval); // evaluate the string if (zend_eval_stringl_ex((char *)phpCode.c_str(), (int32_t)phpCode.length(), retval, (char *)"", 1 TSRMLS_CC) != SUCCESS) { // Do we want to throw an exception here? The original author of this code // did, but there are some reasons not to: // // 1. the PHP eval() function also does not throw exceptions. // // 2. the zend_eval_string() function already triggers a // 'PHP parse error' when an error occurs, which also has // to be handled. If we also throw an exception here, the // user will have to write two error checks: for the error // and the exception. // // if we _do_ want to throw an exception, we will first have to // prevent the original zend_error to occur, and then turn it // into an exception. An exception would be nicer from a C++ // point of view, but because of the extra complexity, we do not // this for now. return nullptr; } else { // was an exception thrown inside the eval()'ed code? In that case we // throw a C++ new exception to give the C++ code the chance to catch it if (oldException != EG(exception) && EG(exception)) throw OrigException(EG(exception) TSRMLS_CC); // wrap the return value in a value object Value result(retval); // the retval should now have two references: the value object and the // retval itselves, so we can remove one of it (the zval_ptr_dtor only // decrements refcount and won't destruct anything because there still // is one reference left inside the Value object) zval_ptr_dtor(&retval); // done return result; } } /** * Include a file * @param filename * @return Value */ Value include(const std::string &filename) { // we can simply execute a file return File(filename).execute(); } /** * Include a file only once * @param filename * @return Value */ Value include_once(const std::string &filename) { // we can simply execute a file return File(filename).execute(); } /** * Require a file * This causes a fatal error if the file does not exist * @param filename * @return Value */ Value require(const std::string &filename) { // create the file File file(filename); // execute if it exists if (file.exists()) return file.execute(); // trigger fatal error error << filename << " does not exist" << std::flush; // unreachable return nullptr; } /** * Require a file only once * This causes a fatal error if the file does not exist * @param filename * @return Value */ Value require_once(const std::string &filename) { // create the file File file(filename); // execute if it exists if (file.exists()) return file.once(); // trigger fatal error error << filename << " does not exist" << std::flush; // unreachable return nullptr; } /** * End of namespace */ } <|endoftext|>
<commit_before>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_archive " << "difference_archive output_archive\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", FileUtil::GetLastPathComponent(reader->getPath())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_archive) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_archive + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_archive + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_archive(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_archive(FileUtil::MakeAbsolutePath(argv[3])); if (input_archive == difference_archive or input_archive == output_archive or difference_archive == output_archive) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; Archive::UnpackArchive(difference_archive, difference_archive); const auto directory_name(output_archive); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_archive, &input_archive_members); GetDirectoryContentsWithRelativepath(difference_archive, &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_archive); if (not keep_intermediate_files and not FileUtil::RemoveDirectory(difference_archive)) LOG_ERROR("failed to remove directory: \"" + difference_archive + "\"!"); return EXIT_SUCCESS; } <commit_msg>Re-introduce .tar.gz name handling for the difference archive.<commit_after>/** \file apply_differential_update.cc * \brief A tool for applying a differential update to a complete MARC dump. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2018 Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <stdexcept> #include <unordered_set> #include <cassert> #include <cstdlib> #include <cstring> #include "unistd.h" #include "Archive.h" #include "BSZUtil.h" #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--min-log-level=log_level] [--keep-intermediate-files] input_archive " << "difference_archive output_archive\n" << " Log levels are DEBUG, INFO, WARNING and ERROR with INFO being the default.\n\n"; std::exit(EXIT_FAILURE); } void CopyAndCollectPPNs(MARC::Reader * const reader, MARC::Writer * const writer, std::unordered_set<std::string> * const previously_seen_ppns) { while (auto record = reader->read()) { if (previously_seen_ppns->find(record.getControlNumber()) == previously_seen_ppns->end()) { previously_seen_ppns->emplace(record.getControlNumber()); if (record.getFirstField("ORI") == record.end()) record.appendField("ORI", FileUtil::GetLastPathComponent(reader->getPath())); writer->write(record); } } } void CopySelectedTypes(const std::vector<std::string> &archive_members, MARC::Writer * const writer, const std::set<BSZUtil::ArchiveType> &selected_types, std::unordered_set<std::string> * const previously_seen_ppns) { for (const auto &archive_member : archive_members) { if (selected_types.find(BSZUtil::GetArchiveType(archive_member)) != selected_types.cend()) { const auto reader(MARC::Reader::Factory(archive_member, MARC::FileType::BINARY)); CopyAndCollectPPNs(reader.get(), writer, previously_seen_ppns); } } } void PatchArchiveMembersAndCreateOutputArchive(const std::vector<std::string> &input_archive_members, const std::vector<std::string> &difference_archive_members, const std::string &output_archive) { if (input_archive_members.empty()) LOG_ERROR("no input archive members!"); if (difference_archive_members.empty()) LOG_WARNING("no difference archive members!"); // // We process title data first and combine all inferior and superior records. // const auto title_writer(MARC::Writer::Factory(output_archive + "/tit.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_title_ppns; CopySelectedTypes(difference_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); CopySelectedTypes(input_archive_members, title_writer.get(), { BSZUtil::TITLE_RECORDS, BSZUtil::SUPERIOR_TITLES }, &previously_seen_title_ppns); const auto authority_writer(MARC::Writer::Factory(output_archive + "/aut.mrc", MARC::FileType::BINARY)); std::unordered_set<std::string> previously_seen_authority_ppns; CopySelectedTypes(difference_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); CopySelectedTypes(input_archive_members, authority_writer.get(), { BSZUtil::AUTHORITY_RECORDS }, &previously_seen_authority_ppns); } void GetDirectoryContentsWithRelativepath(const std::string &archive_name, std::vector<std::string> * const archive_members) { const std::string directory_name(archive_name); FileUtil::GetFileNameList(".(raw|mrc)$", archive_members, directory_name); for (auto &archive_member : *archive_members) archive_member = directory_name + "/" + archive_member; } std::string RemoveSuffix(const std::string &s, const std::string &suffix) { if (unlikely(not StringUtil::EndsWith(s, suffix))) LOG_ERROR("\"" + s + "\" does not end w/ \"" + suffix + "\"!"); return s.substr(0, s.length() - suffix.length()); } inline std::string StripTarGz(const std::string &archive_filename) { return RemoveSuffix(archive_filename, ".tar.gz"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 4) Usage(); bool keep_intermediate_files(false); if (std::strcmp(argv[1], "--keep-intermediate-files") == 0) { keep_intermediate_files = true; --argc, ++argv; } if (argc != 4) Usage(); const std::string input_archive(FileUtil::MakeAbsolutePath(argv[1])); const std::string difference_archive(FileUtil::MakeAbsolutePath(argv[2])); const std::string output_archive(FileUtil::MakeAbsolutePath(argv[3])); if (input_archive == difference_archive or input_archive == output_archive or difference_archive == output_archive) LOG_ERROR("all archive names must be distinct!"); std::unique_ptr<FileUtil::AutoTempDirectory> working_directory; Archive::UnpackArchive(difference_archive, StripTarGz(difference_archive)); const auto directory_name(output_archive); if (not FileUtil::MakeDirectory(directory_name)) LOG_ERROR("failed to create directory: \"" + directory_name + "\"!"); std::vector<std::string> input_archive_members, difference_archive_members; GetDirectoryContentsWithRelativepath(input_archive, &input_archive_members); GetDirectoryContentsWithRelativepath(StripTarGz(difference_archive), &difference_archive_members); PatchArchiveMembersAndCreateOutputArchive(input_archive_members, difference_archive_members, output_archive); if (not keep_intermediate_files and not FileUtil::RemoveDirectory(difference_archive)) LOG_ERROR("failed to remove directory: \"" + difference_archive + "\"!"); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 by Robert Schmidtke, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include <gtest/gtest.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <fstream> #include <stdio.h> #include <string> #include "libxtreemfs/client.h" #include "libxtreemfs/client_implementation.h" #include "libxtreemfs/options.h" #include "pbrpc/RPC.pb.h" #include "util/logging.h" using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { namespace rpc { class ExternalService { public: ExternalService( std::string config_file_name) : config_file_name_(config_file_name) { char *java_home = getenv("JAVA_HOME"); if (java_home == NULL || (java_home_ = strdup(java_home)).empty()) { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "JAVA_HOME is empty." << std::endl; } } if (!boost::algorithm::ends_with(java_home_, "/")) { java_home_ += "/"; } classpath_ = "java/servers/dist/XtreemFS.jar"; classpath_ += ":java/foundation/dist/Foundation.jar"; classpath_ += ":java/flease/dist/Flease.jar"; classpath_ += ":java/lib/*"; service_pid_ = -1; } void Start(std::string service_class) { char *argv[] = { strdup((java_home_ + "bin/java").c_str()), strdup("-ea"), strdup("-cp"), strdup(classpath_.c_str()), strdup(service_class.c_str()), strdup(config_file_name_.c_str()), NULL }; char *envp[] = { NULL }; service_pid_ = fork(); if (service_pid_ == 0) { // Executed by the child. execve((java_home_ + "bin/java").c_str(), argv, envp); exit(EXIT_SUCCESS); } } void Shutdown() { if (service_pid_ > 0) { // Executed by the parent. kill(service_pid_, 2); waitpid(service_pid_, NULL, 0); service_pid_ = -1; } } private: std::string config_file_name_; std::string java_home_; std::string classpath_; pid_t service_pid_; }; class ExternalDIR : public ExternalService { public: ExternalDIR(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.dir.DIR"); } }; class ExternalMRC : public ExternalService { public: ExternalMRC(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.mrc.MRC"); } }; class ExternalOSD : public ExternalService { public: ExternalOSD(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.osd.OSD"); } }; class ClientTest : public ::testing::Test { protected: virtual void SetUp() { initialize_logger(options_.log_level_string, options_.log_file_path, LEVEL_WARN); external_dir_.reset(new ExternalDIR(dir_config_file_)); external_dir_->Start(); external_mrc_.reset(new ExternalMRC(mrc_config_file_)); external_mrc_->Start(); external_osd_.reset(new ExternalOSD(osd_config_file_)); external_osd_->Start(); auth_.set_auth_type(AUTH_NONE); user_credentials_.set_username("client_ssl_test"); user_credentials_.add_groups("client_ssl_test"); options_.retry_delay_s = 5; mrc_url_.ParseURL(kMRC); dir_url_.ParseURL(kDIR); client_.reset(xtreemfs::Client::CreateClient(dir_url_.service_addresses, user_credentials_, options_.GenerateSSLOptions(), options_)); client_->Start(); } virtual void TearDown() { client_->Shutdown(); external_osd_->Shutdown(); external_mrc_->Shutdown(); external_dir_->Shutdown(); } void CreateOpenDeleteVolume(std::string volume_name) { client_->CreateVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); client_->OpenVolume(volume_name, options_.GenerateSSLOptions(), options_); client_->DeleteVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); } size_t count_occurrences_in_file(std::string file_path, std::string s) { std::ifstream in(file_path.c_str(), std::ios_base::in); size_t occurences = 0; while (!in.eof()) { std::string line; std::getline(in, line); occurences += line.find(s) == std::string::npos ? 0 : 1; } in.close(); return occurences; } boost::scoped_ptr<ExternalDIR> external_dir_; boost::scoped_ptr<ExternalMRC> external_mrc_; boost::scoped_ptr<ExternalOSD> external_osd_; boost::scoped_ptr<xtreemfs::Client> client_; xtreemfs::Options options_; xtreemfs::Options dir_url_; xtreemfs::Options mrc_url_; std::string dir_config_file_; std::string mrc_config_file_; std::string osd_config_file_; xtreemfs::pbrpc::Auth auth_; xtreemfs::pbrpc::UserCredentials user_credentials_; }; class ClientNoSSLTest : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = "tests/configs/dirconfig_nossl.test"; mrc_config_file_ = "tests/configs/mrcconfig_nossl.test"; osd_config_file_ = "tests/configs/osdconfig_nossl.test"; dir_url_.xtreemfs_url = "pbrpc://localhost:42638/"; mrc_url_.xtreemfs_url = "pbrpc://localhost:42636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_no_ssl"; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); } }; class ClientSSLTest : public ClientTest { protected: virtual void SetUp() { // All service certificates are signed with Leaf CA, which is signed with // Intermediate CA, which is signed with Root CA. The keystore contains // only the Leaf CA. dir_config_file_ = "tests/configs/dirconfig_ssl.test"; mrc_config_file_ = "tests/configs/mrcconfig_ssl.test"; osd_config_file_ = "tests/configs/osdconfig_ssl.test"; dir_url_.xtreemfs_url = "pbrpcs://localhost:42638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:42636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_with_chain"; // Client certificate is signed with Leaf CA. Contains the entire chain // as additional certificates. options_.ssl_pkcs12_path = "tests/certs/client_ssl_test/Client_Leaf_Chain.p12"; options_.ssl_verify_certificates = true; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); } }; TEST_F(ClientNoSSLTest, TestNoSSL) { CreateOpenDeleteVolume("test_no_ssl"); ASSERT_EQ(0, count_occurrences_in_file(options_.log_file_path, "SSL")); } TEST_F(ClientSSLTest, TestSSLWithChain) { CreateOpenDeleteVolume("test_ssl"); // Once for MRC and once for DIR. ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support activated")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PKCS#12 file " "tests/certs/client_ssl_test/Client_Leaf_Chain.p12")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Writing 3 verification certificates to /tmp/ca")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Root CA' " "was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Intermediate " "CA' was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Leaf CA' was " "successful.")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=MRC (Leaf)' " "was successful")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=DIR (Leaf)' " "was successful.")); } } // namespace rpc } // namespace xtreemfs <commit_msg>cpp: libxtreemfs: added short ssl chain verificationt test<commit_after>/* * Copyright (c) 2014 by Robert Schmidtke, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ #include <gtest/gtest.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/scoped_ptr.hpp> #include <boost/thread.hpp> #include <fstream> #include <stdio.h> #include <string> #include "libxtreemfs/client.h" #include "libxtreemfs/client_implementation.h" #include "libxtreemfs/options.h" #include "pbrpc/RPC.pb.h" #include "util/logging.h" using namespace xtreemfs::pbrpc; using namespace xtreemfs::util; namespace xtreemfs { namespace rpc { class ExternalService { public: ExternalService( std::string config_file_name) : config_file_name_(config_file_name) { char *java_home = getenv("JAVA_HOME"); if (java_home == NULL || (java_home_ = strdup(java_home)).empty()) { if (Logging::log->loggingActive(LEVEL_WARN)) { Logging::log->getLog(LEVEL_WARN) << "JAVA_HOME is empty." << std::endl; } } if (!boost::algorithm::ends_with(java_home_, "/")) { java_home_ += "/"; } classpath_ = "java/servers/dist/XtreemFS.jar"; classpath_ += ":java/foundation/dist/Foundation.jar"; classpath_ += ":java/flease/dist/Flease.jar"; classpath_ += ":java/lib/*"; service_pid_ = -1; } void Start(std::string service_class) { char *argv[] = { strdup((java_home_ + "bin/java").c_str()), strdup("-ea"), strdup("-cp"), strdup(classpath_.c_str()), strdup(service_class.c_str()), strdup(config_file_name_.c_str()), NULL }; char *envp[] = { NULL }; service_pid_ = fork(); if (service_pid_ == 0) { // Executed by the child. execve((java_home_ + "bin/java").c_str(), argv, envp); exit(EXIT_SUCCESS); } } void Shutdown() { if (service_pid_ > 0) { // Executed by the parent. kill(service_pid_, 2); waitpid(service_pid_, NULL, 0); service_pid_ = -1; } } private: std::string config_file_name_; std::string java_home_; std::string classpath_; pid_t service_pid_; }; class ExternalDIR : public ExternalService { public: ExternalDIR(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.dir.DIR"); } }; class ExternalMRC : public ExternalService { public: ExternalMRC(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.mrc.MRC"); } }; class ExternalOSD : public ExternalService { public: ExternalOSD(std::string config_file_name) : ExternalService(config_file_name) {} void Start() { ExternalService::Start("org.xtreemfs.osd.OSD"); } }; class ClientTest : public ::testing::Test { protected: virtual void SetUp() { initialize_logger(options_.log_level_string, options_.log_file_path, LEVEL_WARN); external_dir_.reset(new ExternalDIR(dir_config_file_)); external_dir_->Start(); external_mrc_.reset(new ExternalMRC(mrc_config_file_)); external_mrc_->Start(); external_osd_.reset(new ExternalOSD(osd_config_file_)); external_osd_->Start(); auth_.set_auth_type(AUTH_NONE); user_credentials_.set_username("client_ssl_test"); user_credentials_.add_groups("client_ssl_test"); options_.retry_delay_s = 5; mrc_url_.ParseURL(kMRC); dir_url_.ParseURL(kDIR); client_.reset(xtreemfs::Client::CreateClient(dir_url_.service_addresses, user_credentials_, options_.GenerateSSLOptions(), options_)); client_->Start(); } virtual void TearDown() { client_->Shutdown(); external_osd_->Shutdown(); external_mrc_->Shutdown(); external_dir_->Shutdown(); } void CreateOpenDeleteVolume(std::string volume_name) { client_->CreateVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); client_->OpenVolume(volume_name, options_.GenerateSSLOptions(), options_); client_->DeleteVolume(mrc_url_.service_addresses, auth_, user_credentials_, volume_name); } size_t count_occurrences_in_file(std::string file_path, std::string s) { std::ifstream in(file_path.c_str(), std::ios_base::in); size_t occurences = 0; while (!in.eof()) { std::string line; std::getline(in, line); occurences += line.find(s) == std::string::npos ? 0 : 1; } in.close(); return occurences; } boost::scoped_ptr<ExternalDIR> external_dir_; boost::scoped_ptr<ExternalMRC> external_mrc_; boost::scoped_ptr<ExternalOSD> external_osd_; boost::scoped_ptr<xtreemfs::Client> client_; xtreemfs::Options options_; xtreemfs::Options dir_url_; xtreemfs::Options mrc_url_; std::string dir_config_file_; std::string mrc_config_file_; std::string osd_config_file_; xtreemfs::pbrpc::Auth auth_; xtreemfs::pbrpc::UserCredentials user_credentials_; }; class ClientNoSSLTest : public ClientTest { protected: virtual void SetUp() { dir_config_file_ = "tests/configs/dirconfig_nossl.test"; mrc_config_file_ = "tests/configs/mrcconfig_nossl.test"; osd_config_file_ = "tests/configs/osdconfig_nossl.test"; dir_url_.xtreemfs_url = "pbrpc://localhost:42638/"; mrc_url_.xtreemfs_url = "pbrpc://localhost:42636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_no_ssl"; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); } }; class ClientSSLTestShortChain : public ClientTest { protected: virtual void SetUp() { // Root signed, root trusted dir_config_file_ = "tests/configs/dirconfig_ssl_short_chain.test"; mrc_config_file_ = "tests/configs/mrcconfig_ssl_short_chain.test"; osd_config_file_ = "tests/configs/osdconfig_ssl_short_chain.test"; dir_url_.xtreemfs_url = "pbrpcs://localhost:42638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:42636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_short_chain"; // Root signed, only root as additional certificate. options_.ssl_pkcs12_path = "tests/certs/client_ssl_test/Client_Root_Root.p12"; options_.ssl_verify_certificates = true; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); } }; class ClientSSLTestLongChain : public ClientTest { protected: virtual void SetUp() { // All service certificates are signed with Leaf CA, which is signed with // Intermediate CA, which is signed with Root CA. The keystore contains // only the Leaf CA. dir_config_file_ = "tests/configs/dirconfig_ssl.test"; mrc_config_file_ = "tests/configs/mrcconfig_ssl.test"; osd_config_file_ = "tests/configs/osdconfig_ssl.test"; dir_url_.xtreemfs_url = "pbrpcs://localhost:42638/"; mrc_url_.xtreemfs_url = "pbrpcs://localhost:42636/"; options_.log_level_string = "DEBUG"; options_.log_file_path = "/tmp/xtreemfs_client_ssl_test_with_chain"; // Client certificate is signed with Leaf CA. Contains the entire chain // as additional certificates. options_.ssl_pkcs12_path = "tests/certs/client_ssl_test/Client_Leaf_Chain.p12"; options_.ssl_verify_certificates = true; ClientTest::SetUp(); } virtual void TearDown() { ClientTest::TearDown(); unlink(options_.log_file_path.c_str()); } }; TEST_F(ClientNoSSLTest, TestNoSSL) { CreateOpenDeleteVolume("test_no_ssl"); ASSERT_EQ(0, count_occurrences_in_file(options_.log_file_path, "SSL")); } TEST_F(ClientSSLTestShortChain, TestVerifyShortChain) { CreateOpenDeleteVolume("test_ssl_short_chain"); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support activated")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PKCS#12 file " "tests/certs/client_ssl_test/Client_Root_Root.p12")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Writing 1 verification certificates to /tmp/ca")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Root CA' " "was successful.")); ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Intermediate CA")); ASSERT_EQ(0, count_occurrences_in_file( options_.log_file_path, "/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Leaf CA")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=MRC (Root)' " "was successful")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=DIR (Root)' " "was successful.")); } TEST_F(ClientSSLTestLongChain, TestVerifyLongChain) { CreateOpenDeleteVolume("test_ssl_long_chain"); // Once for MRC and once for DIR. ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support activated")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "SSL support using PKCS#12 file " "tests/certs/client_ssl_test/Client_Leaf_Chain.p12")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Writing 3 verification certificates to /tmp/ca")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Root CA' " "was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Intermediate " "CA' was successful.")); ASSERT_EQ(2, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=Leaf CA' was " "successful.")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=MRC (Leaf)' " "was successful")); ASSERT_EQ(1, count_occurrences_in_file( options_.log_file_path, "Verification of subject '/C=DE/ST=Berlin/L=Berlin/O=ZIB/CN=DIR (Leaf)' " "was successful.")); } } // namespace rpc } // namespace xtreemfs <|endoftext|>
<commit_before>/** * Copyright (C) 2015 Topology LP * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef CPPCODEC_DETAIL_STREAM_CODEC #define CPPCODEC_DETAIL_STREAM_CODEC #include <stdlib.h> // for abort() #include <stdint.h> #include "../parse_error.hpp" namespace cppcodec { namespace detail { template <typename Codec, typename CodecVariant> class stream_codec { public: template <typename Result, typename ResultState> static void encode( Result& encoded_result, ResultState&, const uint8_t* binary, size_t binary_size); template <typename Result, typename ResultState> static void decode( Result& binary_result, ResultState&, const char* encoded, size_t encoded_size); static constexpr size_t encoded_size(size_t binary_size) noexcept; static constexpr size_t decoded_max_size(size_t encoded_size) noexcept; }; template <typename Codec, typename CodecVariant> template <typename Result, typename ResultState> inline void stream_codec<Codec, CodecVariant>::encode( Result& encoded_result, ResultState& state, const uint8_t* src, size_t src_size) { const uint8_t* src_end = src + src_size; if (src_size >= Codec::binary_block_size()) { src_end -= Codec::binary_block_size(); for (; src <= src_end; src += Codec::binary_block_size()) { Codec::encode_block(encoded_result, state, src); } src_end += Codec::binary_block_size(); } if (src_end > src) { auto remaining_src_len = src_end - src; if (!remaining_src_len || remaining_src_len >= Codec::binary_block_size()) { abort(); return; } Codec::encode_tail(encoded_result, state, src, remaining_src_len); Codec::pad(encoded_result, state, remaining_src_len); } } template <typename Codec, typename CodecVariant> template <typename Result, typename ResultState> inline void stream_codec<Codec, CodecVariant>::decode( Result& binary_result, ResultState& state, const char* src_encoded, size_t src_size) { const char* src = src_encoded; const char* src_end = src + src_size; uint8_t idx[Codec::encoded_block_size()] = {}; uint8_t last_value_idx = 0; while (src < src_end) { if (CodecVariant::should_ignore(idx[last_value_idx] = CodecVariant::index_of(*(src++)))) { continue; } if (CodecVariant::is_special_character(idx[last_value_idx])) { break; } ++last_value_idx; if (last_value_idx == Codec::encoded_block_size()) { Codec::decode_block(binary_result, state, idx); last_value_idx = 0; } } uint8_t last_idx = last_value_idx; if (CodecVariant::is_padding_symbol(idx[last_idx])) { // We're in here because we just read a (first) padding character. Try to read more. ++last_idx; while (src < src_end) { if (CodecVariant::is_eof(idx[last_idx] = CodecVariant::index_of(*(src++)))) { break; } if (!CodecVariant::is_padding_symbol(idx[last_idx])) { throw padding_error(); } ++last_idx; if (last_idx > Codec::encoded_block_size()) { throw padding_error(); } } } if (last_idx) { if (CodecVariant::requires_padding() && last_idx != Codec::encoded_block_size()) { // If the input is not a multiple of the block size then the input is incorrect. throw padding_error(); } if (last_value_idx >= Codec::encoded_block_size()) { abort(); return; } Codec::decode_tail(binary_result, state, idx, last_value_idx); } } template <typename Codec, typename CodecVariant> inline constexpr size_t stream_codec<Codec, CodecVariant>::encoded_size(size_t binary_size) noexcept { using C = Codec; // constexpr rules make this a lot harder to read than it actually is. return CodecVariant::generates_padding() // With padding, the encoded size is a multiple of the encoded block size. // To calculate that, round the binary size up to multiple of the binary block size, // then convert to encoded by multiplying with { base32: 8/5, base64: 4/3 }. ? (binary_size + (C::binary_block_size() - 1) - ((binary_size + (C::binary_block_size() - 1)) % C::binary_block_size())) * C::encoded_block_size() / C::binary_block_size() // No padding: only pad to the next multiple of 5 bits, i.e. at most a single extra byte. : (binary_size * C::encoded_block_size() / C::binary_block_size()) + (((binary_size * C::encoded_block_size()) % C::binary_block_size()) ? 1 : 0); } template <typename Codec, typename CodecVariant> inline constexpr size_t stream_codec<Codec, CodecVariant>::decoded_max_size(size_t encoded_size) noexcept { using C = Codec; return CodecVariant::requires_padding() ? encoded_size * C::binary_block_size() / C::encoded_block_size() : (encoded_size * C::binary_block_size() / C::encoded_block_size()) + (((encoded_size * C::binary_block_size()) % C::encoded_block_size()) ? 1 : 0); } } // namespace detail } // namespace cppcodec #endif // CPPCODEC_DETAIL_STREAM_CODEC <commit_msg>Fix decoded_max_size() for unpadded stream codecs.<commit_after>/** * Copyright (C) 2015 Topology LP * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef CPPCODEC_DETAIL_STREAM_CODEC #define CPPCODEC_DETAIL_STREAM_CODEC #include <stdlib.h> // for abort() #include <stdint.h> #include "../parse_error.hpp" namespace cppcodec { namespace detail { template <typename Codec, typename CodecVariant> class stream_codec { public: template <typename Result, typename ResultState> static void encode( Result& encoded_result, ResultState&, const uint8_t* binary, size_t binary_size); template <typename Result, typename ResultState> static void decode( Result& binary_result, ResultState&, const char* encoded, size_t encoded_size); static constexpr size_t encoded_size(size_t binary_size) noexcept; static constexpr size_t decoded_max_size(size_t encoded_size) noexcept; }; template <typename Codec, typename CodecVariant> template <typename Result, typename ResultState> inline void stream_codec<Codec, CodecVariant>::encode( Result& encoded_result, ResultState& state, const uint8_t* src, size_t src_size) { const uint8_t* src_end = src + src_size; if (src_size >= Codec::binary_block_size()) { src_end -= Codec::binary_block_size(); for (; src <= src_end; src += Codec::binary_block_size()) { Codec::encode_block(encoded_result, state, src); } src_end += Codec::binary_block_size(); } if (src_end > src) { auto remaining_src_len = src_end - src; if (!remaining_src_len || remaining_src_len >= Codec::binary_block_size()) { abort(); return; } Codec::encode_tail(encoded_result, state, src, remaining_src_len); Codec::pad(encoded_result, state, remaining_src_len); } } template <typename Codec, typename CodecVariant> template <typename Result, typename ResultState> inline void stream_codec<Codec, CodecVariant>::decode( Result& binary_result, ResultState& state, const char* src_encoded, size_t src_size) { const char* src = src_encoded; const char* src_end = src + src_size; uint8_t idx[Codec::encoded_block_size()] = {}; uint8_t last_value_idx = 0; while (src < src_end) { if (CodecVariant::should_ignore(idx[last_value_idx] = CodecVariant::index_of(*(src++)))) { continue; } if (CodecVariant::is_special_character(idx[last_value_idx])) { break; } ++last_value_idx; if (last_value_idx == Codec::encoded_block_size()) { Codec::decode_block(binary_result, state, idx); last_value_idx = 0; } } uint8_t last_idx = last_value_idx; if (CodecVariant::is_padding_symbol(idx[last_idx])) { // We're in here because we just read a (first) padding character. Try to read more. ++last_idx; while (src < src_end) { if (CodecVariant::is_eof(idx[last_idx] = CodecVariant::index_of(*(src++)))) { break; } if (!CodecVariant::is_padding_symbol(idx[last_idx])) { throw padding_error(); } ++last_idx; if (last_idx > Codec::encoded_block_size()) { throw padding_error(); } } } if (last_idx) { if (CodecVariant::requires_padding() && last_idx != Codec::encoded_block_size()) { // If the input is not a multiple of the block size then the input is incorrect. throw padding_error(); } if (last_value_idx >= Codec::encoded_block_size()) { abort(); return; } Codec::decode_tail(binary_result, state, idx, last_value_idx); } } template <typename Codec, typename CodecVariant> inline constexpr size_t stream_codec<Codec, CodecVariant>::encoded_size(size_t binary_size) noexcept { using C = Codec; // constexpr rules make this a lot harder to read than it actually is. return CodecVariant::generates_padding() // With padding, the encoded size is a multiple of the encoded block size. // To calculate that, round the binary size up to multiple of the binary block size, // then convert to encoded by multiplying with { base32: 8/5, base64: 4/3 }. ? (binary_size + (C::binary_block_size() - 1) - ((binary_size + (C::binary_block_size() - 1)) % C::binary_block_size())) * C::encoded_block_size() / C::binary_block_size() // No padding: only pad to the next multiple of 5 bits, i.e. at most a single extra byte. : (binary_size * C::encoded_block_size() / C::binary_block_size()) + (((binary_size * C::encoded_block_size()) % C::binary_block_size()) ? 1 : 0); } template <typename Codec, typename CodecVariant> inline constexpr size_t stream_codec<Codec, CodecVariant>::decoded_max_size(size_t encoded_size) noexcept { using C = Codec; return CodecVariant::requires_padding() ? (encoded_size / C::encoded_block_size() * C::binary_block_size()) : (encoded_size / C::encoded_block_size() * C::binary_block_size()) + ((encoded_size % C::encoded_block_size()) * C::binary_block_size() / C::encoded_block_size()); } } // namespace detail } // namespace cppcodec #endif // CPPCODEC_DETAIL_STREAM_CODEC <|endoftext|>
<commit_before>#include "RaZ/Render/Mesh.hpp" namespace Raz { Mesh::Mesh(const Triangle& triangle) : Mesh() { // TODO: check if vertices are defined counterclockwise const Vec3f& firstPos = triangle.getFirstPos(); const Vec3f& secondPos = triangle.getSecondPos(); const Vec3f& thirdPos = triangle.getThirdPos(); Vertex firstVert {}; firstVert.position = firstPos; firstVert.texcoords = Vec2f({ 0.f, 0.f }); Vertex secondVert {}; secondVert.position = secondPos; secondVert.texcoords = Vec2f({ 0.5f, 1.f }); Vertex thirdVert {}; thirdVert.position = thirdPos; thirdVert.texcoords = Vec2f({ 1.f, 0.f }); // Computing normals firstVert.normal = (firstPos - secondPos).cross(firstPos - thirdPos).normalize(); secondVert.normal = (secondPos - thirdPos).cross(secondPos - firstPos).normalize(); thirdVert.normal = (thirdPos - firstPos).cross(thirdPos - secondPos).normalize(); std::vector<Vertex>& vertices = m_submeshes.front()->getVbo().getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getEbo().getIndices(); vertices.resize(3); indices.resize(3); vertices[0] = firstVert; vertices[1] = secondVert; vertices[2] = thirdVert; indices[0] = 1; indices[1] = 0; indices[2] = 2; load(); } Mesh::Mesh(const Quad& quad) : Mesh() { const Vec3f& leftTopPos = quad.getLeftTopPos(); const Vec3f& rightTopPos = quad.getRightTopPos(); const Vec3f& rightBottomPos = quad.getRightBottomPos(); const Vec3f& leftBottomPos = quad.getLeftBottomPos(); Vertex leftTop {}; leftTop.position = leftTopPos; leftTop.texcoords = Vec2f({ 0.f, 1.f }); Vertex rightTop {}; rightTop.position = rightTopPos; rightTop.texcoords = Vec2f({ 1.f, 1.f }); Vertex rightBottom {}; rightBottom.position = rightBottomPos; rightBottom.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftBottom {}; leftBottom.position = leftBottomPos; leftBottom.texcoords = Vec2f({ 0.f, 0.f }); // Computing normals // TODO: normals should not be computed (or even exist) for simple display quads like a framebuffer leftTop.normal = (leftTopPos - rightTopPos).cross(leftTopPos - leftBottomPos).normalize(); rightTop.normal = (rightTopPos - rightBottomPos).cross(rightTopPos - leftTopPos).normalize(); rightBottom.normal = (rightBottomPos - leftBottomPos).cross(rightBottomPos - rightTopPos).normalize(); leftBottom.normal = (leftBottomPos - leftTopPos).cross(leftBottomPos - rightBottomPos).normalize(); std::vector<Vertex>& vertices = m_submeshes.front()->getVbo().getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getEbo().getIndices(); vertices.resize(4); indices.resize(6); vertices[0] = leftTop; vertices[1] = leftBottom; vertices[2] = rightBottom; vertices[3] = rightTop; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; load(); } Mesh::Mesh(const AABB& box) : Mesh() { const Vec3f& rightTopFrontPos = box.getRightTopFrontPos(); const Vec3f& leftBottomBackPos = box.getLeftBottomBackPos(); const float rightPos = rightTopFrontPos[0]; const float leftPos = leftBottomBackPos[0]; const float topPos = rightTopFrontPos[1]; const float bottomPos = leftBottomBackPos[1]; const float frontPos = rightTopFrontPos[2]; const float backPos = leftBottomBackPos[2]; // TODO: texcoords should not exist for simple display cubes like a skybox Vertex rightTopBack {}; rightTopBack.position = Vec3f({ rightPos, topPos, backPos }); rightTopBack.texcoords = Vec2f({ 0.f, 1.f }); Vertex rightTopFront {}; rightTopFront.position = rightTopFrontPos; rightTopFront.texcoords = Vec2f({ 1.f, 1.f }); Vertex rightBottomBack {}; rightBottomBack.position = Vec3f({ rightPos, bottomPos, backPos }); rightBottomBack.texcoords = Vec2f({ 0.f, 0.f }); Vertex rightBottomFront {}; rightBottomFront.position = Vec3f({ rightPos, bottomPos, frontPos }); rightBottomFront.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftTopBack {}; leftTopBack.position = Vec3f({ leftPos, topPos, backPos }); leftTopBack.texcoords = Vec2f({ 1.f, 1.f }); Vertex leftTopFront {}; leftTopFront.position = Vec3f({ leftPos, topPos, frontPos }); leftTopFront.texcoords = Vec2f({ 0.f, 1.f }); Vertex leftBottomBack {}; leftBottomBack.position = leftBottomBackPos; leftBottomBack.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftBottomFront {}; leftBottomFront.position = Vec3f({ leftPos, bottomPos, frontPos }); leftBottomFront.texcoords = Vec2f({ 0.f, 0.f }); // Computing normals // TODO: normals should not be computed (or even exist) for simple display cubes like a skybox // TODO: compute normals std::vector<Vertex>& vertices = m_submeshes.front()->getVbo().getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getEbo().getIndices(); vertices.resize(8); indices.resize(36); vertices[0] = rightTopBack; vertices[1] = rightTopFront; vertices[2] = rightBottomBack; vertices[3] = rightBottomFront; vertices[4] = leftTopBack; vertices[5] = leftTopFront; vertices[6] = leftBottomBack; vertices[7] = leftBottomFront; // Right face indices[0] = 1; indices[1] = 0; indices[2] = 2; indices[3] = 1; indices[4] = 2; indices[5] = 3; // Left face indices[6] = 4; indices[7] = 5; indices[8] = 7; indices[9] = 4; indices[10] = 7; indices[11] = 6; // Top face indices[12] = 4; indices[13] = 0; indices[14] = 1; indices[15] = 4; indices[16] = 1; indices[17] = 5; // Bottom face indices[18] = 7; indices[19] = 3; indices[20] = 2; indices[21] = 7; indices[22] = 2; indices[23] = 6; // Front face indices[24] = 5; indices[25] = 1; indices[26] = 3; indices[27] = 5; indices[28] = 3; indices[29] = 7; // Back face indices[30] = 0; indices[31] = 4; indices[32] = 6; indices[33] = 0; indices[34] = 6; indices[35] = 2; load(); } } // namespace Raz <commit_msg>[Render/MeshShape] MeshShape's funcs don't use getVbo()/getEbo() anymore<commit_after>#include "RaZ/Render/Mesh.hpp" namespace Raz { Mesh::Mesh(const Triangle& triangle) : Mesh() { // TODO: check if vertices are defined counterclockwise const Vec3f& firstPos = triangle.getFirstPos(); const Vec3f& secondPos = triangle.getSecondPos(); const Vec3f& thirdPos = triangle.getThirdPos(); Vertex firstVert {}; firstVert.position = firstPos; firstVert.texcoords = Vec2f({ 0.f, 0.f }); Vertex secondVert {}; secondVert.position = secondPos; secondVert.texcoords = Vec2f({ 0.5f, 1.f }); Vertex thirdVert {}; thirdVert.position = thirdPos; thirdVert.texcoords = Vec2f({ 1.f, 0.f }); // Computing normals firstVert.normal = (firstPos - secondPos).cross(firstPos - thirdPos).normalize(); secondVert.normal = (secondPos - thirdPos).cross(secondPos - firstPos).normalize(); thirdVert.normal = (thirdPos - firstPos).cross(thirdPos - secondPos).normalize(); std::vector<Vertex>& vertices = m_submeshes.front()->getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getIndices(); vertices.resize(3); indices.resize(3); vertices[0] = firstVert; vertices[1] = secondVert; vertices[2] = thirdVert; indices[0] = 1; indices[1] = 0; indices[2] = 2; load(); } Mesh::Mesh(const Quad& quad) : Mesh() { const Vec3f& leftTopPos = quad.getLeftTopPos(); const Vec3f& rightTopPos = quad.getRightTopPos(); const Vec3f& rightBottomPos = quad.getRightBottomPos(); const Vec3f& leftBottomPos = quad.getLeftBottomPos(); Vertex leftTop {}; leftTop.position = leftTopPos; leftTop.texcoords = Vec2f({ 0.f, 1.f }); Vertex rightTop {}; rightTop.position = rightTopPos; rightTop.texcoords = Vec2f({ 1.f, 1.f }); Vertex rightBottom {}; rightBottom.position = rightBottomPos; rightBottom.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftBottom {}; leftBottom.position = leftBottomPos; leftBottom.texcoords = Vec2f({ 0.f, 0.f }); // Computing normals // TODO: normals should not be computed (or even exist) for simple display quads like a framebuffer leftTop.normal = (leftTopPos - rightTopPos).cross(leftTopPos - leftBottomPos).normalize(); rightTop.normal = (rightTopPos - rightBottomPos).cross(rightTopPos - leftTopPos).normalize(); rightBottom.normal = (rightBottomPos - leftBottomPos).cross(rightBottomPos - rightTopPos).normalize(); leftBottom.normal = (leftBottomPos - leftTopPos).cross(leftBottomPos - rightBottomPos).normalize(); std::vector<Vertex>& vertices = m_submeshes.front()->getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getIndices(); vertices.resize(4); indices.resize(6); vertices[0] = leftTop; vertices[1] = leftBottom; vertices[2] = rightBottom; vertices[3] = rightTop; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; load(); } Mesh::Mesh(const AABB& box) : Mesh() { const Vec3f& rightTopFrontPos = box.getRightTopFrontPos(); const Vec3f& leftBottomBackPos = box.getLeftBottomBackPos(); const float rightPos = rightTopFrontPos[0]; const float leftPos = leftBottomBackPos[0]; const float topPos = rightTopFrontPos[1]; const float bottomPos = leftBottomBackPos[1]; const float frontPos = rightTopFrontPos[2]; const float backPos = leftBottomBackPos[2]; // TODO: texcoords should not exist for simple display cubes like a skybox Vertex rightTopBack {}; rightTopBack.position = Vec3f({ rightPos, topPos, backPos }); rightTopBack.texcoords = Vec2f({ 0.f, 1.f }); Vertex rightTopFront {}; rightTopFront.position = rightTopFrontPos; rightTopFront.texcoords = Vec2f({ 1.f, 1.f }); Vertex rightBottomBack {}; rightBottomBack.position = Vec3f({ rightPos, bottomPos, backPos }); rightBottomBack.texcoords = Vec2f({ 0.f, 0.f }); Vertex rightBottomFront {}; rightBottomFront.position = Vec3f({ rightPos, bottomPos, frontPos }); rightBottomFront.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftTopBack {}; leftTopBack.position = Vec3f({ leftPos, topPos, backPos }); leftTopBack.texcoords = Vec2f({ 1.f, 1.f }); Vertex leftTopFront {}; leftTopFront.position = Vec3f({ leftPos, topPos, frontPos }); leftTopFront.texcoords = Vec2f({ 0.f, 1.f }); Vertex leftBottomBack {}; leftBottomBack.position = leftBottomBackPos; leftBottomBack.texcoords = Vec2f({ 1.f, 0.f }); Vertex leftBottomFront {}; leftBottomFront.position = Vec3f({ leftPos, bottomPos, frontPos }); leftBottomFront.texcoords = Vec2f({ 0.f, 0.f }); // Computing normals // TODO: normals should not be computed (or even exist) for simple display cubes like a skybox // TODO: compute normals std::vector<Vertex>& vertices = m_submeshes.front()->getVertices(); std::vector<unsigned int>& indices = m_submeshes.front()->getIndices(); vertices.resize(8); indices.resize(36); vertices[0] = rightTopBack; vertices[1] = rightTopFront; vertices[2] = rightBottomBack; vertices[3] = rightBottomFront; vertices[4] = leftTopBack; vertices[5] = leftTopFront; vertices[6] = leftBottomBack; vertices[7] = leftBottomFront; // Right face indices[0] = 1; indices[1] = 0; indices[2] = 2; indices[3] = 1; indices[4] = 2; indices[5] = 3; // Left face indices[6] = 4; indices[7] = 5; indices[8] = 7; indices[9] = 4; indices[10] = 7; indices[11] = 6; // Top face indices[12] = 4; indices[13] = 0; indices[14] = 1; indices[15] = 4; indices[16] = 1; indices[17] = 5; // Bottom face indices[18] = 7; indices[19] = 3; indices[20] = 2; indices[21] = 7; indices[22] = 2; indices[23] = 6; // Front face indices[24] = 5; indices[25] = 1; indices[26] = 3; indices[27] = 5; indices[28] = 3; indices[29] = 7; // Back face indices[30] = 0; indices[31] = 4; indices[32] = 6; indices[33] = 0; indices[34] = 6; indices[35] = 2; load(); } } // namespace Raz <|endoftext|>
<commit_before>// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================== #include <dlfcn.h> #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "tensorflow/compiler/xla/python/tpu_driver/client/c_api.h" #include "tensorflow/compiler/xla/python/tpu_driver/tpu_driver.h" #include "tensorflow/compiler/xla/python/tpu_driver/tpu_driver.pb.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace tpu_driver { namespace { class ExternalTpuDriver; class ExternalEvent : public Event { public: explicit ExternalEvent(::TpuDriverFn* driver_fn, ::TpuEvent* event) : driver_fn_(driver_fn), event_(event) {} ~ExternalEvent() override { driver_fn_->TpuDriver_FreeEvent(event_); } xla::Status Await() override { auto tpu_status = driver_fn_->TpuDriver_EventAwait(event_, -1); auto ret = xla::Status(tensorflow::error::Code(tpu_status->code), absl::StrFormat("%s", tpu_status->msg)); driver_fn_->TpuDriver_FreeStatus(tpu_status); return ret; } absl::optional<xla::Status> AwaitWithTimeout( absl::Duration duration) override { auto tpu_status_or = driver_fn_->TpuDriver_EventAwait( event_, absl::ToInt64Microseconds(duration)); if (tpu_status_or == nullptr) { return absl::nullopt; } else { auto ret = xla::Status(tensorflow::error::Code(tpu_status_or->code), absl::StrFormat("%s", tpu_status_or->msg)); driver_fn_->TpuDriver_FreeStatus(tpu_status_or); return ret; } } void AddCallback(std::function<void(xla::Status)> callback) override { // We have to create a new copy of the fn on the heap to make it persist. std::function<void(xla::Status)>* callback_addr = new std::function<void(xla::Status)>(callback); // Using the callback_addr instead of capturing because C++11 lambdas with // variable captures cannot be converted to C function pointers. driver_fn_->TpuDriver_EventAddCallback( event_, [](struct TpuStatus* status, void* additional_info) { auto callback_addr = static_cast<std::function<void(xla::Status)>*>(additional_info); auto xla_status = xla::Status(tensorflow::error::Code(status->code), absl::StrFormat("%s", status->msg)); (*callback_addr)(xla_status); delete callback_addr; }, callback_addr); } private: ::TpuDriverFn* driver_fn_; ::TpuEvent* event_; friend ExternalTpuDriver; }; class ExternalBufferHandle : public BufferHandle { public: explicit ExternalBufferHandle(::TpuDriverFn* driver_fn, ::TpuBufferHandle* handle) : handle_(handle), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { return handle_->size_in_bytes; } absl::optional<xla::ShapeProto> shape() override { LOG(FATAL) << "Unimplemented."; return absl::nullopt; } private: ::TpuBufferHandle* handle_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalCompiledProgramHandle : public CompiledProgramHandle { public: explicit ExternalCompiledProgramHandle(::TpuDriverFn* driver_fn, ::TpuCompiledProgramHandle* handle) : handle_(handle), driver_fn_(driver_fn), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { LOG(FATAL) << "Unimplemented."; return 0; } xla::Status program_shape(xla::ProgramShapeProto* program_shape) override { struct CompiledProgramShape* shape = driver_fn_->TpuDriver_GetCompiledProgramShape(handle_); program_shape->ParseFromArray(shape->bytes, shape->size); auto status = xla::Status(tensorflow::error::Code(shape->status->code), absl::StrFormat("%s", shape->status->msg)); driver_fn_->TpuDriver_FreeCompiledProgramShape(shape); return status; } private: ::TpuCompiledProgramHandle* handle_; ::TpuDriverFn* driver_fn_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalLoadedProgramHandle : public LoadedProgramHandle { public: explicit ExternalLoadedProgramHandle(::TpuDriverFn* driver_fn, ::TpuLoadedProgramHandle* handle) : handle_(handle), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { LOG(FATAL) << "Unimplemented."; return 0; } private: ::TpuLoadedProgramHandle* handle_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalTpuDriver : public TpuDriver { public: explicit ExternalTpuDriver(const std::string& so_path) { void* handle; handle = dlopen(so_path.c_str(), RTLD_NOW); if (!handle) { LOG(FATAL) << "Unable to load shared library: " << dlerror(); } PrototypeTpuDriver_Initialize* initialize_fn; *reinterpret_cast<void**>(&initialize_fn) = dlsym(handle, "TpuDriver_Initialize"); initialize_fn(&driver_fn_); driver_ = driver_fn_.TpuDriver_Open("local://"); } ~ExternalTpuDriver() override {} void QuerySystemInfo(SystemInfo* system_info) override { LOG(FATAL) << "Unimplemented."; } xla::Status Reset() override { LOG(FATAL) << "Unimplemented."; } std::unique_ptr<BufferHandle> Allocate( int32_t core_id, MemoryRegion region, int64_t num_bytes, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto bh = absl::make_unique<ExternalBufferHandle>( &driver_fn_, driver_fn_.TpuDriver_Allocate(driver_, core_id, region, num_bytes, wait_for.size(), tpu_events)); delete tpu_events; return bh; } std::unique_ptr<BufferHandle> Allocate( int32_t core_id, MemoryRegion region, const xla::ShapeProto& shape, absl::Span<Event* const> wait_for) override { LOG(FATAL) << "Unimplemented."; return nullptr; } std::unique_ptr<BufferHandle> AllocateTuple( int32_t core_id, MemoryRegion region, absl::Span<BufferHandle* const> children, absl::Span<Event* const> wait_for) override { LOG(FATAL) << "Unimplemented."; return nullptr; } std::shared_ptr<Event> Deallocate( std::unique_ptr<BufferHandle> handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_Deallocate( driver_, static_cast<ExternalBufferHandle*>(handle.get())->handle_, wait_for.size(), tpu_events)); delete tpu_events; return event; } std::shared_ptr<Event> TransferToDevice( const void* src, BufferHandle* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferToDevice( driver_, src, static_cast<ExternalBufferHandle*>(dst)->handle_, wait_for.size(), tpu_events)); delete tpu_events; return event; } std::shared_ptr<Event> TransferFromDevice( const BufferHandle* src, void* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferFromDevice( driver_, static_cast<const ExternalBufferHandle*>(src)->handle_, dst, wait_for.size(), tpu_events)); delete tpu_events; return event; } std::shared_ptr<Event> TransferFromDeviceToDevice( const BufferHandle* src, BufferHandle* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferFromDeviceToDevice( driver_, static_cast<const ExternalBufferHandle*>(src)->handle_, static_cast<ExternalBufferHandle*>(dst)->handle_, wait_for.size(), tpu_events)); delete tpu_events; return event; } std::unique_ptr<CompiledProgramHandle> CompileProgram( const xla::HloProto& source, int32_t num_replicas, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); struct HloProto hlo; hlo.size = source.ByteSizeLong(); hlo.buffer = malloc(hlo.size); if (!source.SerializeToArray(hlo.buffer, hlo.size)) { LOG(ERROR) << "Unable to serialize HLO to array."; return nullptr; } auto handle = absl::make_unique<ExternalCompiledProgramHandle>( &driver_fn_, driver_fn_.TpuDriver_CompileProgram(driver_, hlo, num_replicas, wait_for.size(), tpu_events)); free(hlo.buffer); delete tpu_events; return handle; } std::unique_ptr<LoadedProgramHandle> LoadProgram( int32_t core_id, const CompiledProgramHandle* handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto loaded_handle = absl::make_unique<ExternalLoadedProgramHandle>( &driver_fn_, driver_fn_.TpuDriver_LoadProgram( driver_, core_id, static_cast<const ExternalCompiledProgramHandle*>(handle)->handle_, wait_for.size(), tpu_events)); delete tpu_events; return loaded_handle; } std::shared_ptr<Event> UnloadProgram( std::unique_ptr<LoadedProgramHandle> handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_UnloadProgram( driver_, static_cast<ExternalLoadedProgramHandle*>(handle.get())->handle_, wait_for.size(), tpu_events)); delete tpu_events; return event; } std::shared_ptr<Event> ExecuteProgram( LoadedProgramHandle* program, absl::Span<BufferHandle* const> inputs, absl::Span<BufferHandle* const> outputs, const xla::DeviceAssignmentProto& device_assignment, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); std::vector<::TpuBufferHandle*> inputv; inputv.reserve(inputs.size()); for (int i = 0; i < inputs.size(); i++) { inputv.push_back( static_cast<ExternalBufferHandle* const>(inputs[i])->handle_); } std::vector<::TpuBufferHandle*> outputv; outputv.reserve(outputs.size()); for (int i = 0; i < outputs.size(); i++) { outputv.push_back( static_cast<ExternalBufferHandle* const>(outputs[i])->handle_); } struct DeviceAssignment da = {device_assignment.replica_count(), device_assignment.computation_count()}; auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_ExecuteProgram( driver_, static_cast<ExternalLoadedProgramHandle*>(program)->handle_, inputs.size(), inputv.data(), outputs.size(), outputv.data(), da, wait_for.size(), tpu_events)); return event; } std::unique_ptr<TpuLinearizer> GetLinearizer() override { return nullptr; } private: ::TpuDriverFn driver_fn_; ::TpuDriver* driver_; ::TpuEvent** MakeEventArray(absl::Span<Event* const> wait_for) { if (wait_for.empty()) return nullptr; ::TpuEvent** ret = new ::TpuEvent*[wait_for.size()]; for (int i = 0; i < wait_for.size(); i++) { ret[i] = static_cast<ExternalEvent* const>(wait_for[i])->event_; } return ret; } }; xla::StatusOr<std::unique_ptr<TpuDriver>> RegisterExternalTpuDriver( const TpuDriverConfig& config) { std::string shared_lib = config.worker().substr(strlen("external://")); return xla::StatusOr<std::unique_ptr<TpuDriver>>( absl::make_unique<ExternalTpuDriver>(shared_lib)); } REGISTER_TPU_DRIVER("external://", RegisterExternalTpuDriver); } // namespace } // namespace tpu_driver <commit_msg>Add implementation for AllocateTuple to external TPU driver<commit_after>// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================== #include <dlfcn.h> #include "absl/strings/str_format.h" #include "absl/time/time.h" #include "tensorflow/compiler/xla/python/tpu_driver/client/c_api.h" #include "tensorflow/compiler/xla/python/tpu_driver/tpu_driver.h" #include "tensorflow/compiler/xla/python/tpu_driver/tpu_driver.pb.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace tpu_driver { namespace { class ExternalTpuDriver; class ExternalEvent : public Event { public: explicit ExternalEvent(::TpuDriverFn* driver_fn, ::TpuEvent* event) : driver_fn_(driver_fn), event_(event) {} ~ExternalEvent() override { driver_fn_->TpuDriver_FreeEvent(event_); } xla::Status Await() override { auto tpu_status = driver_fn_->TpuDriver_EventAwait(event_, -1); auto ret = xla::Status(tensorflow::error::Code(tpu_status->code), absl::StrFormat("%s", tpu_status->msg)); driver_fn_->TpuDriver_FreeStatus(tpu_status); return ret; } absl::optional<xla::Status> AwaitWithTimeout( absl::Duration duration) override { auto tpu_status_or = driver_fn_->TpuDriver_EventAwait( event_, absl::ToInt64Microseconds(duration)); if (tpu_status_or == nullptr) { return absl::nullopt; } else { auto ret = xla::Status(tensorflow::error::Code(tpu_status_or->code), absl::StrFormat("%s", tpu_status_or->msg)); driver_fn_->TpuDriver_FreeStatus(tpu_status_or); return ret; } } void AddCallback(std::function<void(xla::Status)> callback) override { // We have to create a new copy of the fn on the heap to make it persist. std::function<void(xla::Status)>* callback_addr = new std::function<void(xla::Status)>(callback); // Using the callback_addr instead of capturing because C++11 lambdas with // variable captures cannot be converted to C function pointers. driver_fn_->TpuDriver_EventAddCallback( event_, [](struct TpuStatus* status, void* additional_info) { auto callback_addr = static_cast<std::function<void(xla::Status)>*>(additional_info); auto xla_status = xla::Status(tensorflow::error::Code(status->code), absl::StrFormat("%s", status->msg)); (*callback_addr)(xla_status); delete callback_addr; }, callback_addr); } private: ::TpuDriverFn* driver_fn_; ::TpuEvent* event_; friend ExternalTpuDriver; }; class ExternalBufferHandle : public BufferHandle { public: explicit ExternalBufferHandle(::TpuDriverFn* driver_fn, ::TpuBufferHandle* handle) : handle_(handle), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { return handle_->size_in_bytes; } absl::optional<xla::ShapeProto> shape() override { LOG(FATAL) << "Unimplemented."; return absl::nullopt; } private: ::TpuBufferHandle* handle_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalCompiledProgramHandle : public CompiledProgramHandle { public: explicit ExternalCompiledProgramHandle(::TpuDriverFn* driver_fn, ::TpuCompiledProgramHandle* handle) : handle_(handle), driver_fn_(driver_fn), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { LOG(FATAL) << "Unimplemented."; return 0; } xla::Status program_shape(xla::ProgramShapeProto* program_shape) override { struct CompiledProgramShape* shape = driver_fn_->TpuDriver_GetCompiledProgramShape(handle_); program_shape->ParseFromArray(shape->bytes, shape->size); auto status = xla::Status(tensorflow::error::Code(shape->status->code), absl::StrFormat("%s", shape->status->msg)); driver_fn_->TpuDriver_FreeCompiledProgramShape(shape); return status; } private: ::TpuCompiledProgramHandle* handle_; ::TpuDriverFn* driver_fn_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalLoadedProgramHandle : public LoadedProgramHandle { public: explicit ExternalLoadedProgramHandle(::TpuDriverFn* driver_fn, ::TpuLoadedProgramHandle* handle) : handle_(handle), event_(new ExternalEvent(driver_fn, handle->event)) {} std::shared_ptr<Event> OnReady() override { return event_; } int64_t size_in_bytes() override { LOG(FATAL) << "Unimplemented."; return 0; } private: ::TpuLoadedProgramHandle* handle_; std::shared_ptr<ExternalEvent> event_; friend ExternalTpuDriver; }; class ExternalTpuDriver : public TpuDriver { public: explicit ExternalTpuDriver(const std::string& so_path) { void* handle; handle = dlopen(so_path.c_str(), RTLD_NOW); if (!handle) { LOG(FATAL) << "Unable to load shared library: " << dlerror(); } PrototypeTpuDriver_Initialize* initialize_fn; *reinterpret_cast<void**>(&initialize_fn) = dlsym(handle, "TpuDriver_Initialize"); initialize_fn(&driver_fn_); driver_ = driver_fn_.TpuDriver_Open("local://"); } ~ExternalTpuDriver() override {} void QuerySystemInfo(SystemInfo* system_info) override { LOG(FATAL) << "Unimplemented."; } xla::Status Reset() override { LOG(FATAL) << "Unimplemented."; } std::unique_ptr<BufferHandle> Allocate( int32_t core_id, MemoryRegion region, int64_t num_bytes, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto bh = absl::make_unique<ExternalBufferHandle>( &driver_fn_, driver_fn_.TpuDriver_Allocate(driver_, core_id, region, num_bytes, wait_for.size(), tpu_events)); delete[] tpu_events; return bh; } std::unique_ptr<BufferHandle> Allocate( int32_t core_id, MemoryRegion region, const xla::ShapeProto& shape, absl::Span<Event* const> wait_for) override { LOG(FATAL) << "Unimplemented."; return nullptr; } std::unique_ptr<BufferHandle> AllocateTuple( int32_t core_id, MemoryRegion region, absl::Span<BufferHandle* const> children, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); ::TpuBufferHandle** childbuf = new ::TpuBufferHandle*[children.size()]; for (int i = 0; i < children.size(); i++) { childbuf[i] = static_cast<ExternalBufferHandle* const>(children[i])->handle_; } auto bh = absl::make_unique<ExternalBufferHandle>( &driver_fn_, driver_fn_.TpuDriver_AllocateTuple( driver_, core_id, region, children.size(), childbuf, wait_for.size(), tpu_events)); delete[] tpu_events; delete[] childbuf; return bh; } std::shared_ptr<Event> Deallocate( std::unique_ptr<BufferHandle> handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_Deallocate( driver_, static_cast<ExternalBufferHandle*>(handle.get())->handle_, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::shared_ptr<Event> TransferToDevice( const void* src, BufferHandle* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferToDevice( driver_, src, static_cast<ExternalBufferHandle*>(dst)->handle_, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::shared_ptr<Event> TransferFromDevice( const BufferHandle* src, void* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferFromDevice( driver_, static_cast<const ExternalBufferHandle*>(src)->handle_, dst, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::shared_ptr<Event> TransferFromDeviceToDevice( const BufferHandle* src, BufferHandle* dst, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_TransferFromDeviceToDevice( driver_, static_cast<const ExternalBufferHandle*>(src)->handle_, static_cast<ExternalBufferHandle*>(dst)->handle_, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::unique_ptr<CompiledProgramHandle> CompileProgram( const xla::HloProto& source, int32_t num_replicas, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); struct HloProto hlo; hlo.size = source.ByteSizeLong(); hlo.buffer = malloc(hlo.size); if (!source.SerializeToArray(hlo.buffer, hlo.size)) { LOG(ERROR) << "Unable to serialize HLO to array."; return nullptr; } auto handle = absl::make_unique<ExternalCompiledProgramHandle>( &driver_fn_, driver_fn_.TpuDriver_CompileProgram(driver_, hlo, num_replicas, wait_for.size(), tpu_events)); free(hlo.buffer); delete[] tpu_events; return handle; } std::unique_ptr<LoadedProgramHandle> LoadProgram( int32_t core_id, const CompiledProgramHandle* handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto loaded_handle = absl::make_unique<ExternalLoadedProgramHandle>( &driver_fn_, driver_fn_.TpuDriver_LoadProgram( driver_, core_id, static_cast<const ExternalCompiledProgramHandle*>(handle)->handle_, wait_for.size(), tpu_events)); delete[] tpu_events; return loaded_handle; } std::shared_ptr<Event> UnloadProgram( std::unique_ptr<LoadedProgramHandle> handle, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_UnloadProgram( driver_, static_cast<ExternalLoadedProgramHandle*>(handle.get())->handle_, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::shared_ptr<Event> ExecuteProgram( LoadedProgramHandle* program, absl::Span<BufferHandle* const> inputs, absl::Span<BufferHandle* const> outputs, const xla::DeviceAssignmentProto& device_assignment, absl::Span<Event* const> wait_for) override { auto tpu_events = MakeEventArray(wait_for); std::vector<::TpuBufferHandle*> inputv; inputv.reserve(inputs.size()); for (int i = 0; i < inputs.size(); i++) { inputv.push_back( static_cast<ExternalBufferHandle* const>(inputs[i])->handle_); } std::vector<::TpuBufferHandle*> outputv; outputv.reserve(outputs.size()); for (int i = 0; i < outputs.size(); i++) { outputv.push_back( static_cast<ExternalBufferHandle* const>(outputs[i])->handle_); } struct DeviceAssignment da = {device_assignment.replica_count(), device_assignment.computation_count()}; auto event = std::make_shared<ExternalEvent>( &driver_fn_, driver_fn_.TpuDriver_ExecuteProgram( driver_, static_cast<ExternalLoadedProgramHandle*>(program)->handle_, inputs.size(), inputv.data(), outputs.size(), outputv.data(), da, wait_for.size(), tpu_events)); delete[] tpu_events; return event; } std::unique_ptr<TpuLinearizer> GetLinearizer() override { return nullptr; } private: ::TpuDriverFn driver_fn_; ::TpuDriver* driver_; ::TpuEvent** MakeEventArray(absl::Span<Event* const> wait_for) { if (wait_for.empty()) return nullptr; ::TpuEvent** ret = new ::TpuEvent*[wait_for.size()]; for (int i = 0; i < wait_for.size(); i++) { ret[i] = static_cast<ExternalEvent* const>(wait_for[i])->event_; } return ret; } }; xla::StatusOr<std::unique_ptr<TpuDriver>> RegisterExternalTpuDriver( const TpuDriverConfig& config) { std::string shared_lib = config.worker().substr(strlen("external://")); return xla::StatusOr<std::unique_ptr<TpuDriver>>( absl::make_unique<ExternalTpuDriver>(shared_lib)); } REGISTER_TPU_DRIVER("external://", RegisterExternalTpuDriver); } // namespace } // namespace tpu_driver <|endoftext|>
<commit_before>#include "game.h" #define LOOKAHEAD 4 #define SACRIFICE_OPTIONS 5 #define OPPONENT_MOVES 5 using namespace std; // globals int sacrificeCombinations = factorial(SACRIFICE_OPTIONS) / (factorial(SACRIFICE_OPTIONS - 2) * factorial(2)); stringstream token; char botId; char state[16][18]; int roundNum, timebank, myLiveCells, theirLiveCells; // this just for logging time TODO: remove auto t = chrono::steady_clock::now(); void game() { string line, command; while (getline(cin, line)) { token.clear(); token.str(line); token >> command; if (command == "action") processAction(); if (command == "update") processUpdate(); if (command == "settings") processSettings(); } } void processAction() { string type, time; token >> type; token >> time; if (type == "move") { t = chrono::steady_clock::now(); // TODO: remove timebank = stoi(time); makeMove(); chrono::duration<double> diff = chrono::steady_clock::now() - t; // TODO: remove cerr << diff.count() * 1000 << "ms used\n"; // TODO: remove } else cerr << "action type: " << type << " not expected\n"; } void processUpdate() { string target, field, value; token >> target; token >> field; token >> value; if (target == "game") { if (field == "round") { roundNum = stoi(value); } if (field == "field") { parseState(value); } } else if (target == "player0" or target == "player1") { if (field == "living_cells") { if (target[6] == botId) myLiveCells = stoi(value); else theirLiveCells = stoi(value); } else if (field != "move") cerr << "update playerX field: " << field << " not expected\n"; } else cerr << "update target: " << target << " not expected\n"; } void processSettings() { string field, value; token >> field; token >> value; if (field == "player_names") { if (value != "player0,player1") cerr << "settings player_names value: " << value << " not expected\n"; } else if (field == "your_bot") { if (value != "player0" and value != "player1") cerr << "settings your_bot value: " << value << " not expected\n"; } else if (field == "timebank") { if (value == "10000") timebank = stoi(value); else cerr << "settings timebank value: " << value << " not expected\n"; } else if (field == "time_per_move") { if (value != "100") cerr << "settings time_per_move value: " << value << " not expected\n"; } else if (field == "field_width") { if (value != "18") cerr << "settings field_width value: " << value << " not expected\n"; } else if (field == "field_height") { if (value != "16") cerr << "settings field_height value: " << value << " not expected\n"; } else if (field == "max_rounds") { if (value != "100") cerr << "settings max_rounds value: " << value << " not expected\n"; } else if (field == "your_botid") { if (value == "0" or value == "1") botId = value[0]; else cerr << "settings your_botid value: " << value << " not expected\n"; } else cerr << "settings field: " << field << " not expected\n"; } void parseState(const string &value) { int row = 0; int col = 0; for (const char& c : value) { if (c != ',') { state[row][col] = c; if (col == 17) { col = 0; row++; } else { col++; } } } } void makeMove() { int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells)); // TODO: handle less then n of my cells alive for birthing calcs node nodes[numMoves]; addKillNodes(nodes); node bestKillNodes[SACRIFICE_OPTIONS]; findBestKillNodes(nodes, bestKillNodes); addPassNode(nodes); addBirthNodes(nodes, bestKillNodes); // TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those // sort then slice, then 2nd round heuristic, then sort then first sort(nodes, nodes + numMoves, nodeCompare); // node bestNode = findBestNode(nodes, numMoves); node bestNode = nodes[0]; sendMove(bestNode); } void addKillNodes(node nodes[]) { int i = 0; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (state[r][c] != '.') { node n; n.value = state[r][c]; n.type = 'k'; n.target = r * 18 + c; copyState(n.state); n.state[r][c] = '.'; calculateNextState(n); calculateHeuristic(n); nodes[i++] = n; } } } } void findBestKillNodes(node nodes[], node bestKillNodes[]) { sort(nodes, nodes + myLiveCells + theirLiveCells, nodeCompare); int killNodeCount = 0; for (int i = 0; i < myLiveCells + theirLiveCells; i++) { node n = nodes[i]; if (n.value == botId) { bestKillNodes[killNodeCount] = n; killNodeCount++; if (killNodeCount == SACRIFICE_OPTIONS) { break; } } } } void addPassNode(node nodes[]) { node n; n.type = 'p'; copyState(n.state); calculateNextState(n); calculateHeuristic(n); nodes[myLiveCells + theirLiveCells] = n; } void addBirthNodes(node nodes[], const node bestKillNodes[]) { int i = myLiveCells + theirLiveCells + 1; for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) { for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) { for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (state[r][c] == '.') { node n; n.type = 'b'; n.target = r * 18 + c; n.sacrifice1 = bestKillNodes[x].target; n.sacrifice2 = bestKillNodes[y].target; copyState(n.state); n.state[r][c] = botId; n.state[n.sacrifice1 / 18][n.sacrifice1 % 18] = '.'; n.state[n.sacrifice2 / 18][n.sacrifice2 % 18] = '.'; calculateNextState(n); calculateHeuristic(n); nodes[i++] = n; } } } } } } node findBestNode(const node nodes[], int nodeCount) { int topHeuristic = -288; int topHeuristicIdx = 0; for (int i = 0; i < nodeCount; i++) { if (nodes[i].heuristicValue > topHeuristic) { topHeuristic = nodes[topHeuristicIdx].heuristicValue; topHeuristicIdx = i; } } return nodes[topHeuristicIdx]; } void sendMove(const node &n) { if (n.type == 'p') { cout << "pass\n"; } else if (n.type == 'k') { cout << "kill " << coords(n.target) << "\n"; } else if (n.type == 'b') { cout << "birth " << coords(n.target) << " " << coords(n.sacrifice1) << " " << coords(n.sacrifice2) << "\n"; } } void calculateNextState(node &n) { for (int l = 0; l < LOOKAHEAD; l++) { int neighbours0[16][18]; int neighbours1[16][18]; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { neighbours0[r][c] = 0; neighbours1[r][c] = 0; } } for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (n.state[r][c] == '0') { if (c > 0) { neighbours0[r][c - 1]++; if (r > 0) neighbours0[r - 1][c - 1]++; if (r < 15) neighbours0[r + 1][c - 1]++; } if (c < 17) { neighbours0[r][c + 1]++; if (r > 0) neighbours0[r - 1][c + 1]++; if (r < 15) neighbours0[r + 1][c + 1]++; } if (r > 0) neighbours0[r - 1][c]++; if (r < 15) neighbours0[r + 1][c]++; } if (n.state[r][c] == '1') { if (c > 0) { neighbours1[r][c - 1]++; if (r > 0) neighbours1[r - 1][c - 1]++; if (r < 15) neighbours1[r + 1][c - 1]++; } if (c < 17) { neighbours1[r][c + 1]++; if (r > 0) neighbours1[r - 1][c + 1]++; if (r < 15) neighbours1[r + 1][c + 1]++; } if (r > 0) neighbours1[r - 1][c]++; if (r < 15) neighbours1[r + 1][c]++; } } } int neighbours; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { neighbours = neighbours0[r][c] + neighbours1[r][c]; if (n.state[r][c] == '.' and neighbours == 3) { n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1'; } else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) { n.state[r][c] = '.'; } } } } } void calculateHeuristic(node &n) { int cellCount0 = 0; int cellCount1 = 0; // TODO: consider the number of opponent cells alive to increase aggression when they are low for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (n.state[r][c] == '0') { cellCount0++; } else if (n.state[r][c] == '1') { cellCount1++; } } } if (botId == '0') { if (cellCount0 == 0) { n.heuristicValue = -288; } else if (cellCount1 == 0) { n.heuristicValue = 288; } else { n.heuristicValue = cellCount0 - cellCount1; } } else if (botId == '1') { if (cellCount1 == 0) { n.heuristicValue = -288; } else if (cellCount0 == 0) { n.heuristicValue = 288; } else { n.heuristicValue = cellCount1 - cellCount0; } } } // utility functions int factorial(int x, int result) { return (x == 1) ? result : factorial(x - 1, x * result); } string coords(int cellIdx) { stringstream ss; ss << (cellIdx % 18) << "," << cellIdx / 18; return ss.str(); } void copyState(const char source[][18], char target[][18]) { for (int r = 0; r < 16; r++) { for (int c = 0; c < 18; c++) { target[r][c] = source[r][c]; } } } bool nodeCompare(node lhs, node rhs) { // sort descending return lhs.heuristicValue > rhs.heuristicValue; } // debug functions void setBotId(const char id) { botId = id; } <commit_msg>calculateNextState takes lookahead as an arg<commit_after>#include "game.h" #define LOOKAHEAD 4 #define SACRIFICE_OPTIONS 5 #define OPPONENT_MOVES 5 using namespace std; // globals int sacrificeCombinations = factorial(SACRIFICE_OPTIONS) / (factorial(SACRIFICE_OPTIONS - 2) * factorial(2)); stringstream token; char botId; char state[16][18]; int roundNum, timebank, myLiveCells, theirLiveCells; // this just for logging time TODO: remove auto t = chrono::steady_clock::now(); void game() { string line, command; while (getline(cin, line)) { token.clear(); token.str(line); token >> command; if (command == "action") processAction(); if (command == "update") processUpdate(); if (command == "settings") processSettings(); } } void processAction() { string type, time; token >> type; token >> time; if (type == "move") { t = chrono::steady_clock::now(); // TODO: remove timebank = stoi(time); makeMove(); chrono::duration<double> diff = chrono::steady_clock::now() - t; // TODO: remove cerr << diff.count() * 1000 << "ms used\n"; // TODO: remove } else cerr << "action type: " << type << " not expected\n"; } void processUpdate() { string target, field, value; token >> target; token >> field; token >> value; if (target == "game") { if (field == "round") { roundNum = stoi(value); } if (field == "field") { parseState(value); } } else if (target == "player0" or target == "player1") { if (field == "living_cells") { if (target[6] == botId) myLiveCells = stoi(value); else theirLiveCells = stoi(value); } else if (field != "move") cerr << "update playerX field: " << field << " not expected\n"; } else cerr << "update target: " << target << " not expected\n"; } void processSettings() { string field, value; token >> field; token >> value; if (field == "player_names") { if (value != "player0,player1") cerr << "settings player_names value: " << value << " not expected\n"; } else if (field == "your_bot") { if (value != "player0" and value != "player1") cerr << "settings your_bot value: " << value << " not expected\n"; } else if (field == "timebank") { if (value == "10000") timebank = stoi(value); else cerr << "settings timebank value: " << value << " not expected\n"; } else if (field == "time_per_move") { if (value != "100") cerr << "settings time_per_move value: " << value << " not expected\n"; } else if (field == "field_width") { if (value != "18") cerr << "settings field_width value: " << value << " not expected\n"; } else if (field == "field_height") { if (value != "16") cerr << "settings field_height value: " << value << " not expected\n"; } else if (field == "max_rounds") { if (value != "100") cerr << "settings max_rounds value: " << value << " not expected\n"; } else if (field == "your_botid") { if (value == "0" or value == "1") botId = value[0]; else cerr << "settings your_botid value: " << value << " not expected\n"; } else cerr << "settings field: " << field << " not expected\n"; } void parseState(const string &value) { int row = 0; int col = 0; for (const char& c : value) { if (c != ',') { state[row][col] = c; if (col == 17) { col = 0; row++; } else { col++; } } } } void makeMove() { int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells)); // TODO: handle less then n of my cells alive for birthing calcs node nodes[numMoves]; addKillNodes(nodes); node bestKillNodes[SACRIFICE_OPTIONS]; findBestKillNodes(nodes, bestKillNodes); addPassNode(nodes); addBirthNodes(nodes, bestKillNodes); // TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those // sort then slice, then 2nd round heuristic, then sort then first sort(nodes, nodes + numMoves, nodeCompare); // node bestNode = findBestNode(nodes, numMoves); node bestNode = nodes[0]; sendMove(bestNode); } void addKillNodes(node nodes[]) { int i = 0; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (state[r][c] != '.') { node n; n.value = state[r][c]; n.type = 'k'; n.target = r * 18 + c; copyState(n.state); n.state[r][c] = '.'; calculateNextState(n); calculateHeuristic(n); nodes[i++] = n; } } } } void findBestKillNodes(node nodes[], node bestKillNodes[]) { sort(nodes, nodes + myLiveCells + theirLiveCells, nodeCompare); int killNodeCount = 0; for (int i = 0; i < myLiveCells + theirLiveCells; i++) { node n = nodes[i]; if (n.value == botId) { bestKillNodes[killNodeCount] = n; killNodeCount++; if (killNodeCount == SACRIFICE_OPTIONS) { break; } } } } void addPassNode(node nodes[]) { node n; n.type = 'p'; copyState(n.state); calculateNextState(n); calculateHeuristic(n); nodes[myLiveCells + theirLiveCells] = n; } void addBirthNodes(node nodes[], const node bestKillNodes[]) { int i = myLiveCells + theirLiveCells + 1; for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) { for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) { for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (state[r][c] == '.') { node n; n.type = 'b'; n.target = r * 18 + c; n.sacrifice1 = bestKillNodes[x].target; n.sacrifice2 = bestKillNodes[y].target; copyState(n.state); n.state[r][c] = botId; n.state[n.sacrifice1 / 18][n.sacrifice1 % 18] = '.'; n.state[n.sacrifice2 / 18][n.sacrifice2 % 18] = '.'; calculateNextState(n); calculateHeuristic(n); nodes[i++] = n; } } } } } } node findBestNode(const node nodes[], int nodeCount) { int topHeuristic = -288; int topHeuristicIdx = 0; for (int i = 0; i < nodeCount; i++) { if (nodes[i].heuristicValue > topHeuristic) { topHeuristic = nodes[topHeuristicIdx].heuristicValue; topHeuristicIdx = i; } } return nodes[topHeuristicIdx]; } void sendMove(const node &n) { if (n.type == 'p') { cout << "pass\n"; } else if (n.type == 'k') { cout << "kill " << coords(n.target) << "\n"; } else if (n.type == 'b') { cout << "birth " << coords(n.target) << " " << coords(n.sacrifice1) << " " << coords(n.sacrifice2) << "\n"; } } void calculateNextState(node &n, int lookahead) { for (int l = 0; l < lookahead; l++) { int neighbours0[16][18]; int neighbours1[16][18]; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { neighbours0[r][c] = 0; neighbours1[r][c] = 0; } } for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (n.state[r][c] == '0') { if (c > 0) { neighbours0[r][c - 1]++; if (r > 0) neighbours0[r - 1][c - 1]++; if (r < 15) neighbours0[r + 1][c - 1]++; } if (c < 17) { neighbours0[r][c + 1]++; if (r > 0) neighbours0[r - 1][c + 1]++; if (r < 15) neighbours0[r + 1][c + 1]++; } if (r > 0) neighbours0[r - 1][c]++; if (r < 15) neighbours0[r + 1][c]++; } if (n.state[r][c] == '1') { if (c > 0) { neighbours1[r][c - 1]++; if (r > 0) neighbours1[r - 1][c - 1]++; if (r < 15) neighbours1[r + 1][c - 1]++; } if (c < 17) { neighbours1[r][c + 1]++; if (r > 0) neighbours1[r - 1][c + 1]++; if (r < 15) neighbours1[r + 1][c + 1]++; } if (r > 0) neighbours1[r - 1][c]++; if (r < 15) neighbours1[r + 1][c]++; } } } int neighbours; for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { neighbours = neighbours0[r][c] + neighbours1[r][c]; if (n.state[r][c] == '.' and neighbours == 3) { n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1'; } else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) { n.state[r][c] = '.'; } } } } } void calculateHeuristic(node &n) { int cellCount0 = 0; int cellCount1 = 0; // TODO: consider the number of opponent cells alive to increase aggression when they are low for (int c = 0; c < 18; c++) { for (int r = 0; r < 16; r++) { if (n.state[r][c] == '0') { cellCount0++; } else if (n.state[r][c] == '1') { cellCount1++; } } } if (botId == '0') { if (cellCount0 == 0) { n.heuristicValue = -288; } else if (cellCount1 == 0) { n.heuristicValue = 288; } else { n.heuristicValue = cellCount0 - cellCount1; } } else if (botId == '1') { if (cellCount1 == 0) { n.heuristicValue = -288; } else if (cellCount0 == 0) { n.heuristicValue = 288; } else { n.heuristicValue = cellCount1 - cellCount0; } } } // utility functions int factorial(int x, int result) { return (x == 1) ? result : factorial(x - 1, x * result); } string coords(int cellIdx) { stringstream ss; ss << (cellIdx % 18) << "," << cellIdx / 18; return ss.str(); } void copyState(const char source[][18], char target[][18]) { for (int r = 0; r < 16; r++) { for (int c = 0; c < 18; c++) { target[r][c] = source[r][c]; } } } bool nodeCompare(node lhs, node rhs) { // sort descending return lhs.heuristicValue > rhs.heuristicValue; } // debug functions void setBotId(const char id) { botId = id; } <|endoftext|>
<commit_before>#include "core/settings.hpp" #include "core/tz_glad/glad_context.hpp" #include "core/debug/assert.hpp" namespace tz { void RenderSettings::enable_wireframe_mode(bool wireframe) const { if(wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth(1.0f); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } RenderSettings::CullTarget RenderSettings::get_culling() const { tz::RenderSettings::CullTarget cull; GLint val; glGetIntegerv(GL_CULL_FACE, &val); if(val == GL_FALSE) { cull = tz::RenderSettings::CullTarget::Nothing; } else { glGetIntegerv(GL_CULL_FACE_MODE, &val); switch(val) { case GL_BACK: cull = tz::RenderSettings::CullTarget::BackFaces; break; case GL_FRONT: cull = tz::RenderSettings::CullTarget::FrontFaces; break; case GL_FRONT_AND_BACK: cull = tz::RenderSettings::CullTarget::Both; break; default: topaz_assert(false, "Could not retrieve current culling mode. Perhaps this needs to be updated?"); break; } } return cull; } void RenderSettings::set_culling(tz::RenderSettings::CullTarget culling) const { if(culling == tz::RenderSettings::CullTarget::Nothing) { glDisable(GL_CULL_FACE); return; } glEnable(GL_CULL_FACE); switch(culling) { case tz::RenderSettings::CullTarget::BackFaces: glCullFace(GL_BACK); break; case tz::RenderSettings::CullTarget::FrontFaces: glCullFace(GL_FRONT); break; case tz::RenderSettings::CullTarget::Both: glCullFace(GL_FRONT_AND_BACK); break; default: topaz_assert(false, "tz::RenderSettings::set_culling(CullTarget): Unknown CullTarget. Garbage enum value?"); break; } } RenderSettings::DepthTesting RenderSettings::get_depth_testing() const { GLint val; glGetIntegerv(GL_DEPTH_TEST, &val); if(val == GL_FALSE) { return DepthTesting::AlwaysPass; } glGetIntegerv(GL_DEPTH_FUNC, &val); switch(val) { case GL_NEVER: return DepthTesting::NeverPass; break; case GL_LESS: return DepthTesting::PassIfLess; break; case GL_EQUAL: return DepthTesting::PassIfEqual; break; case GL_LEQUAL: return DepthTesting::PassIfLequal; break; case GL_GREATER: return DepthTesting::PassIfGreater; break; case GL_NOTEQUAL: return DepthTesting::PassIfNequal; break; case GL_GEQUAL: return DepthTesting::PassIfGequal; break; case GL_ALWAYS: return DepthTesting::AlwaysPass; break; default: topaz_assert(false, "tz::RenderSettings::get_depth_testing(): Unexpected state. Returning default of DepthTesting::PassIfLess."); return DepthTesting::PassIfLess; break; } } void RenderSettings::set_depth_testing(DepthTesting depth_testing) { if(depth_testing == DepthTesting::AlwaysPass) { glDisable(GL_DEPTH_TEST); } else { glEnable(GL_DEPTH_TEST); switch(depth_testing) { case DepthTesting::NeverPass: glDepthFunc(GL_NEVER); break; case DepthTesting::PassIfLess: glDepthFunc(GL_LESS); break; case DepthTesting::PassIfEqual: glDepthFunc(GL_EQUAL); break; case DepthTesting::PassIfLequal: glDepthFunc(GL_LEQUAL); break; case DepthTesting::PassIfGreater: glDepthFunc(GL_GREATER); break; case DepthTesting::PassIfNequal: glDepthFunc(GL_NOTEQUAL); break; case DepthTesting::PassIfGequal: glDepthFunc(GL_GEQUAL); break; case DepthTesting::AlwaysPass: glDepthFunc(GL_ALWAYS); break; default: topaz_assert(false, "tz::RenderSettings::set_depth_testing(DepthTesting): Invalid state. Using default of DepthTesting::PassIfLess."); glDepthFunc(GL_LESS); break; } } } }<commit_msg>* Fixed wrong include path in core/settings.cpp. This was actually found by github actions yay!<commit_after>#include "core/settings.hpp" #include "ext/tz_glad/glad_context.hpp" #include "core/debug/assert.hpp" namespace tz { void RenderSettings::enable_wireframe_mode(bool wireframe) const { if(wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glLineWidth(1.0f); } else { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } RenderSettings::CullTarget RenderSettings::get_culling() const { tz::RenderSettings::CullTarget cull; GLint val; glGetIntegerv(GL_CULL_FACE, &val); if(val == GL_FALSE) { cull = tz::RenderSettings::CullTarget::Nothing; } else { glGetIntegerv(GL_CULL_FACE_MODE, &val); switch(val) { case GL_BACK: cull = tz::RenderSettings::CullTarget::BackFaces; break; case GL_FRONT: cull = tz::RenderSettings::CullTarget::FrontFaces; break; case GL_FRONT_AND_BACK: cull = tz::RenderSettings::CullTarget::Both; break; default: topaz_assert(false, "Could not retrieve current culling mode. Perhaps this needs to be updated?"); break; } } return cull; } void RenderSettings::set_culling(tz::RenderSettings::CullTarget culling) const { if(culling == tz::RenderSettings::CullTarget::Nothing) { glDisable(GL_CULL_FACE); return; } glEnable(GL_CULL_FACE); switch(culling) { case tz::RenderSettings::CullTarget::BackFaces: glCullFace(GL_BACK); break; case tz::RenderSettings::CullTarget::FrontFaces: glCullFace(GL_FRONT); break; case tz::RenderSettings::CullTarget::Both: glCullFace(GL_FRONT_AND_BACK); break; default: topaz_assert(false, "tz::RenderSettings::set_culling(CullTarget): Unknown CullTarget. Garbage enum value?"); break; } } RenderSettings::DepthTesting RenderSettings::get_depth_testing() const { GLint val; glGetIntegerv(GL_DEPTH_TEST, &val); if(val == GL_FALSE) { return DepthTesting::AlwaysPass; } glGetIntegerv(GL_DEPTH_FUNC, &val); switch(val) { case GL_NEVER: return DepthTesting::NeverPass; break; case GL_LESS: return DepthTesting::PassIfLess; break; case GL_EQUAL: return DepthTesting::PassIfEqual; break; case GL_LEQUAL: return DepthTesting::PassIfLequal; break; case GL_GREATER: return DepthTesting::PassIfGreater; break; case GL_NOTEQUAL: return DepthTesting::PassIfNequal; break; case GL_GEQUAL: return DepthTesting::PassIfGequal; break; case GL_ALWAYS: return DepthTesting::AlwaysPass; break; default: topaz_assert(false, "tz::RenderSettings::get_depth_testing(): Unexpected state. Returning default of DepthTesting::PassIfLess."); return DepthTesting::PassIfLess; break; } } void RenderSettings::set_depth_testing(DepthTesting depth_testing) { if(depth_testing == DepthTesting::AlwaysPass) { glDisable(GL_DEPTH_TEST); } else { glEnable(GL_DEPTH_TEST); switch(depth_testing) { case DepthTesting::NeverPass: glDepthFunc(GL_NEVER); break; case DepthTesting::PassIfLess: glDepthFunc(GL_LESS); break; case DepthTesting::PassIfEqual: glDepthFunc(GL_EQUAL); break; case DepthTesting::PassIfLequal: glDepthFunc(GL_LEQUAL); break; case DepthTesting::PassIfGreater: glDepthFunc(GL_GREATER); break; case DepthTesting::PassIfNequal: glDepthFunc(GL_NOTEQUAL); break; case DepthTesting::PassIfGequal: glDepthFunc(GL_GEQUAL); break; case DepthTesting::AlwaysPass: glDepthFunc(GL_ALWAYS); break; default: topaz_assert(false, "tz::RenderSettings::set_depth_testing(DepthTesting): Invalid state. Using default of DepthTesting::PassIfLess."); glDepthFunc(GL_LESS); break; } } } }<|endoftext|>
<commit_before>#include "archive.hh" #include "fs-accessor.hh" #include "store-api.hh" namespace nix { struct LocalStoreAccessor : public FSAccessor { ref<Store> store; LocalStoreAccessor(ref<Store> store) : store(store) { } void assertStore(const Path & path) { Path storePath = toStorePath(path); if (!store->isValidPath(storePath)) throw Error(format("path ‘%1%’ is not a valid store path") % storePath); } FSAccessor::Stat stat(const Path & path) override { assertStore(path); struct stat st; if (lstat(path.c_str(), &st)) { if (errno == ENOENT) return {Type::tMissing, 0, false}; throw SysError(format("getting status of ‘%1%’") % path); } if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode)) throw Error(format("file ‘%1%’ has unsupported type") % path); return { S_ISREG(st.st_mode) ? Type::tRegular : S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory, S_ISREG(st.st_mode) ? (uint64_t) st.st_size : 0, S_ISREG(st.st_mode) && st.st_mode & S_IXUSR}; } StringSet readDirectory(const Path & path) override { assertStore(path); auto entries = nix::readDirectory(path); StringSet res; for (auto & entry : entries) res.insert(entry.name); return res; } std::string readFile(const Path & path) override { assertStore(path); return nix::readFile(path); } std::string readLink(const Path & path) override { assertStore(path); return nix::readLink(path); } }; ref<FSAccessor> LocalFSStore::getFSAccessor() { return make_ref<LocalStoreAccessor>(ref<Store>(shared_from_this())); } void LocalFSStore::narFromPath(const Path & path, Sink & sink) { if (!isValidPath(path)) throw Error(format("path ‘%s’ is not valid") % path); dumpPath(path, sink); } } <commit_msg>LocalStoreAccessor::stat: Handle ENOTDIR<commit_after>#include "archive.hh" #include "fs-accessor.hh" #include "store-api.hh" namespace nix { struct LocalStoreAccessor : public FSAccessor { ref<Store> store; LocalStoreAccessor(ref<Store> store) : store(store) { } void assertStore(const Path & path) { Path storePath = toStorePath(path); if (!store->isValidPath(storePath)) throw Error(format("path ‘%1%’ is not a valid store path") % storePath); } FSAccessor::Stat stat(const Path & path) override { assertStore(path); struct stat st; if (lstat(path.c_str(), &st)) { if (errno == ENOENT || errno == ENOTDIR) return {Type::tMissing, 0, false}; throw SysError(format("getting status of ‘%1%’") % path); } if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode)) throw Error(format("file ‘%1%’ has unsupported type") % path); return { S_ISREG(st.st_mode) ? Type::tRegular : S_ISLNK(st.st_mode) ? Type::tSymlink : Type::tDirectory, S_ISREG(st.st_mode) ? (uint64_t) st.st_size : 0, S_ISREG(st.st_mode) && st.st_mode & S_IXUSR}; } StringSet readDirectory(const Path & path) override { assertStore(path); auto entries = nix::readDirectory(path); StringSet res; for (auto & entry : entries) res.insert(entry.name); return res; } std::string readFile(const Path & path) override { assertStore(path); return nix::readFile(path); } std::string readLink(const Path & path) override { assertStore(path); return nix::readLink(path); } }; ref<FSAccessor> LocalFSStore::getFSAccessor() { return make_ref<LocalStoreAccessor>(ref<Store>(shared_from_this())); } void LocalFSStore::narFromPath(const Path & path, Sink & sink) { if (!isValidPath(path)) throw Error(format("path ‘%s’ is not valid") % path); dumpPath(path, sink); } } <|endoftext|>
<commit_before>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <fftw3.h> #include "crosscorrelate.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif namespace votca { namespace tools { /** \todo clean implementation!!! */ void CrossCorrelate::AutoCorrelate(DataCollection<double>::selection *data, bool average) { #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorrelate is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = (*data)[0].size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &(*data)[0][0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); /*double m=0; for(int i=0; i<N; i++) { _corrfunc[i] = 0; m+=(*data)[0][i]; } m=m/(double)N; for(int i=0;i<N; i++) for(int j=0; j<N-i-1; j++) _corrfunc[i]+=((*data)[0][j]-m)*((*data)[0][(i+j)]-m); */ double d = _corrfunc[0]; for(int i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; //cout << *data << endl; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } void CrossCorrelate::AutoFourier(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoFourier is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } // copy the real component of temp to the _corrfunc vector for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::FFTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::FFTOnly is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); // copy the real component of temp to the _corrfunc vector for(int i=0; i<N/2+1; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::DCTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::DCTOnly is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // store results for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCosine(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCosing is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // compute autocorrelation tmp[0] = 0; for(int i=1; i<N; i++) { tmp[i] = tmp[i]*tmp[i]; } // store results for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCorr(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorr is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); double d = _corrfunc[0]; for(int i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } }} <commit_msg>crosscorrelate.cc: put include <fftw3.h> in ifdef<commit_after>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "crosscorrelate.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifndef NOFFTW #include <fftw3.h> #endif namespace votca { namespace tools { /** \todo clean implementation!!! */ void CrossCorrelate::AutoCorrelate(DataCollection<double>::selection *data, bool average) { #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorrelate is not compiled-in due to disabling of FFTW - recompile libtools with '--with-ffw'"); #else size_t N = (*data)[0].size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &(*data)[0][0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); /*double m=0; for(int i=0; i<N; i++) { _corrfunc[i] = 0; m+=(*data)[0][i]; } m=m/(double)N; for(int i=0;i<N; i++) for(int j=0; j<N-i-1; j++) _corrfunc[i]+=((*data)[0][j]-m)*((*data)[0][(i+j)]-m); */ double d = _corrfunc[0]; for(int i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; //cout << *data << endl; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } void CrossCorrelate::AutoFourier(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoFourier is not compiled-in due to disabling of FFTW - recompile libtools with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } // copy the real component of temp to the _corrfunc vector for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::FFTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::FFTOnly is not compiled-in due to disabling of FFTW - recompile libtools with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); // copy the real component of temp to the _corrfunc vector for(int i=0; i<N/2+1; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::DCTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::DCTOnly is not compiled-in due to disabling of FFTW - recompile libtools with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // store results for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCosine(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCosing is not compiled-in due to disabling of FFTW - recompile libtools with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // compute autocorrelation tmp[0] = 0; for(int i=1; i<N; i++) { tmp[i] = tmp[i]*tmp[i]; } // store results for(int i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCorr(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorr is not compiled-in due to disabling of FFTW - recompile libtool with '--with-ffw'"); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(int i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); double d = _corrfunc[0]; for(int i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } }} <|endoftext|>
<commit_before>#include <tensorflow/core/common_runtime/constant_folding.h> #include <tensorflow/core/graph/graph_constructor.h> #include <tensorflow/core/graph/node_builder.h> #include <tensorflow/core/graph/subgraph.h> #include <tensorflow/core/platform/init_main.h> #include <tensorflow/core/public/session.h> #include <tensorflow/core/util/command_line_flags.h> #include <tensorflow/tools/graph_transforms/transform_utils.h> namespace tensorflow { namespace graph_transforms { // Remove control depdencies in preparation for inference. // In the tensorflow graph, control dependencies are represented as extra // inputs which are referenced with "^tensor_name". // See node_def.proto for more details. Status RemoveControlDependencies(const GraphDef& input_graph_def, const TransformFuncContext& context, GraphDef* output_graph_def) { output_graph_def->Clear(); for (const NodeDef& node : input_graph_def.node()) { NodeDef* new_node = output_graph_def->mutable_node()->Add(); *new_node = node; new_node->clear_input(); for (const auto& input : node.input()) { if (input[0] != '^') { new_node->add_input(input); } } } return Status::OK(); } REGISTER_GRAPH_TRANSFORM("remove_control_dependencies", RemoveControlDependencies); } // namespace graph_transforms } // namespace tensorflow <commit_msg>remove unnecessary includes<commit_after>#include <tensorflow/core/graph/graph_constructor.h> #include <tensorflow/core/graph/node_builder.h> #include <tensorflow/tools/graph_transforms/transform_utils.h> namespace tensorflow { namespace graph_transforms { // Remove control depdencies in preparation for inference. // In the tensorflow graph, control dependencies are represented as extra // inputs which are referenced with "^tensor_name". // See node_def.proto for more details. Status RemoveControlDependencies(const GraphDef& input_graph_def, const TransformFuncContext& context, GraphDef* output_graph_def) { output_graph_def->Clear(); for (const NodeDef& node : input_graph_def.node()) { NodeDef* new_node = output_graph_def->mutable_node()->Add(); *new_node = node; new_node->clear_input(); for (const auto& input : node.input()) { if (input[0] != '^') { new_node->add_input(input); } } } return Status::OK(); } REGISTER_GRAPH_TRANSFORM("remove_control_dependencies", RemoveControlDependencies); } // namespace graph_transforms } // namespace tensorflow <|endoftext|>
<commit_before>#include "breakpoint.h" #include <windows.h> #include <tlhelp32.h> #include <algorithm> #include <iostream> const char HWBreakpoint::m_originalOpcode[8] = { 0x48, 0x83, 0xEC, 0x48, 0x4C, 0x8B, 0xC9, 0x48 }; HWBreakpoint::HWBreakpoint() { ZeroMemory(m_address, sizeof(m_address)); m_countActive = 0; BuildTrampoline(); m_workerSignal = CreateEvent(NULL, FALSE, FALSE, NULL); m_workerDone = CreateEvent(NULL, FALSE, FALSE, NULL); m_workerThread = CreateThread(NULL, 0, WorkerThreadProc, this, 0, NULL); WaitForSingleObject(m_workerDone, INFINITE); } HWBreakpoint::~HWBreakpoint() { CriticalSection::Scope lock(m_cs); { ZeroMemory(m_address, sizeof(m_address)); SetForThreads(); } m_pendingThread.tid = -1; SetEvent(m_workerSignal); WaitForSingleObject(m_workerThread, INFINITE); CloseHandle(m_workerDone); CloseHandle(m_workerSignal); CloseHandle(m_workerThread); } bool HWBreakpoint::Set(void* address, int len, Condition when) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); for (int index = 0; index < 4; ++index) if (bp.m_address[index] == nullptr) { bp.m_address[index] = address; bp.m_len[index] = len; bp.m_when[index] = when; if (bp.m_countActive++ == 0) bp.ToggleThreadHook(true); bp.SetForThreads(); return true; } } return false; } bool HWBreakpoint::Clear(void* address) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); for (int index = 0; index < 4; ++index) if (bp.m_address[index] == address) { bp.m_address[index] = nullptr; if (--bp.m_countActive == 0) bp.ToggleThreadHook(false); bp.SetForThreads(); return true; } } return false; } void HWBreakpoint::ToggleThread(DWORD tid, bool enableBP) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); bp.m_pendingThread.tid = tid; bp.m_pendingThread.enable = enableBP; SetEvent(bp.m_workerSignal); WaitForSingleObject(bp.m_workerDone, INFINITE); } } void HWBreakpoint::BuildTrampoline() { DWORD64* rtlThreadStartAddress = (DWORD64*)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlUserThreadStart"); SYSTEM_INFO si; GetSystemInfo(&si); DWORD64 gMinAddress = (DWORD64)si.lpMinimumApplicationAddress; DWORD64 gMaxAddress = (DWORD64)si.lpMaximumApplicationAddress; DWORD64 minAddr = std::max<DWORD64>(gMinAddress, (DWORD64)rtlThreadStartAddress - 0x20000000); DWORD64 maxAddr = std::min<DWORD64>(gMaxAddress, (DWORD64)rtlThreadStartAddress + 0x20000000); const size_t BlockSize = 0x10000; intptr_t min = minAddr / BlockSize; intptr_t max = maxAddr / BlockSize; int rel = 0; m_trampoline = nullptr; MEMORY_BASIC_INFORMATION mi = { 0 }; for (int i = 0; i < (max - min + 1); ++i) { rel = -rel + (i & 1); void* pQuery = reinterpret_cast<void*>(((min + max) / 2 + rel) * BlockSize); VirtualQuery(pQuery, &mi, sizeof(mi)); if (mi.State == MEM_FREE) { m_trampoline = (unsigned char*)VirtualAlloc(pQuery, BlockSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (m_trampoline != nullptr) break; } } if (!m_trampoline) return; *(unsigned char*) &m_trampoline[0] = 0x51; // push rcx *(unsigned char*) &m_trampoline[1] = 0x52; // push rdx *(unsigned short*) &m_trampoline[2] = 0x15FF; // call *(DWORD*) &m_trampoline[4] = 0x00000017; // ThreadDeutor *(unsigned char*) &m_trampoline[8] = 0x5A; // pop rdx *(unsigned char*) &m_trampoline[9] = 0x59; // pop rcx *(DWORD*) &m_trampoline[10] = 0x48EC8348; // sub rsp, 0x48 (2 instruction from prologe of target hook) *(unsigned short*) &m_trampoline[14] = 0x8B4C; // mov r9, *(unsigned char*) &m_trampoline[16] = 0xC9; // rcx *(short*) &m_trampoline[17] = 0x25FF; // jmp *(DWORD*) &m_trampoline[19] = 0x00000000; // address data for call & jump *(DWORD64*) &m_trampoline[23] = (DWORD64)((unsigned char*)rtlThreadStartAddress + 7); *(DWORD64*) &m_trampoline[31] = (DWORD64)ThreadDeutor; } void HWBreakpoint::ToggleThreadHook(bool set) { DWORD oldProtect; DWORD64* rtlThreadStartAddress = (DWORD64*)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlUserThreadStart"); if (m_trampoline && set) { VirtualProtect(rtlThreadStartAddress, 5, PAGE_EXECUTE_READWRITE, &oldProtect); unsigned char* b = (unsigned char*)rtlThreadStartAddress; // TODO: replace with one atomic operation b[0] = 0xE9; *(DWORD*)&b[1] = (DWORD)m_trampoline - (DWORD)b - 5; VirtualProtect(rtlThreadStartAddress, 5, oldProtect, &oldProtect); } else if (*rtlThreadStartAddress != *(DWORD64*)m_originalOpcode) { VirtualProtect(rtlThreadStartAddress, 5, PAGE_EXECUTE_READWRITE, &oldProtect); *rtlThreadStartAddress = *(DWORD64*)m_originalOpcode; VirtualProtect(rtlThreadStartAddress, 5, oldProtect, &oldProtect); } } void HWBreakpoint::ThreadDeutor() { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); { bp.m_pendingThread.tid = GetCurrentThreadId(); bp.m_pendingThread.enable = true; SetEvent(bp.m_workerSignal); WaitForSingleObject(bp.m_workerDone, INFINITE); } } } void HWBreakpoint::SetForThreads() { const DWORD pid = GetCurrentProcessId(); HANDLE hThreadSnap = INVALID_HANDLE_VALUE; THREADENTRY32 te32; hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) return; te32.dwSize = sizeof(THREADENTRY32); if(!Thread32First(hThreadSnap, &te32)) { CloseHandle(hThreadSnap); return; } do { if(te32.th32OwnerProcessID == pid) { CriticalSection::Scope lock(m_cs); { m_pendingThread.tid = te32.th32ThreadID; m_pendingThread.enable = true; SetEvent(m_workerSignal); WaitForSingleObject(m_workerDone, INFINITE); } } } while(Thread32Next(hThreadSnap, &te32)); } void HWBreakpoint::SetThread(DWORD tid, bool enableBP) { // this function supposed to be called only from worker thread if (GetCurrentThreadId() == tid) return; HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, FALSE, tid); if (!hThread) return; CONTEXT cxt; cxt.ContextFlags = CONTEXT_DEBUG_REGISTERS; if (SuspendThread(hThread) == -1) goto Final; if (!GetThreadContext(hThread, &cxt)) goto Final; for (int index = 0; index < 4; ++index) { const bool isSet = m_address[index] != nullptr; SetBits(cxt.Dr7, index*2, 1, isSet); if (isSet) { switch (index) { case 0: cxt.Dr0 = (DWORD_PTR) m_address[index]; break; case 1: cxt.Dr1 = (DWORD_PTR) m_address[index]; break; case 2: cxt.Dr2 = (DWORD_PTR) m_address[index]; break; case 3: cxt.Dr3 = (DWORD_PTR) m_address[index]; break; } SetBits(cxt.Dr7, 16 + (index*4), 2, m_when[index]); SetBits(cxt.Dr7, 18 + (index*4), 2, m_len[index]); } } if (!SetThreadContext(hThread, &cxt)) goto Final; if (ResumeThread(hThread) == -1) goto Final; std::cout << "Set BP for Thread: " << tid << std::endl; Final: CloseHandle(hThread); } DWORD HWBreakpoint::WorkerThreadProc(LPVOID lpParameter) { HWBreakpoint& bp = *(HWBreakpoint*)lpParameter; SetEvent(bp.m_workerDone); while (WaitForSingleObject(bp.m_workerSignal, INFINITE) == WAIT_OBJECT_0) { // signal for abort if (bp.m_pendingThread.tid == -1) return 0; bp.SetThread(bp.m_pendingThread.tid, bp.m_pendingThread.enable); SetEvent(bp.m_workerDone); } return 0; }<commit_msg>fix release build<commit_after>#include "breakpoint.h" #include <windows.h> #include <tlhelp32.h> #include <algorithm> #include <iostream> const char HWBreakpoint::m_originalOpcode[8] = { 0x48, 0x83, 0xEC, 0x48, 0x4C, 0x8B, 0xC9, 0x48 }; HWBreakpoint::HWBreakpoint() { ZeroMemory(m_address, sizeof(m_address)); m_countActive = 0; BuildTrampoline(); m_workerSignal = CreateEvent(NULL, FALSE, FALSE, NULL); m_workerDone = CreateEvent(NULL, FALSE, FALSE, NULL); m_workerThread = CreateThread(NULL, 0, WorkerThreadProc, this, 0, NULL); WaitForSingleObject(m_workerDone, INFINITE); } HWBreakpoint::~HWBreakpoint() { CriticalSection::Scope lock(m_cs); { ZeroMemory(m_address, sizeof(m_address)); SetForThreads(); } m_pendingThread.tid = -1; SetEvent(m_workerSignal); WaitForSingleObject(m_workerThread, INFINITE); CloseHandle(m_workerDone); CloseHandle(m_workerSignal); CloseHandle(m_workerThread); } bool HWBreakpoint::Set(void* address, int len, Condition when) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); for (int index = 0; index < 4; ++index) if (bp.m_address[index] == nullptr) { bp.m_address[index] = address; bp.m_len[index] = len; bp.m_when[index] = when; if (bp.m_countActive++ == 0) bp.ToggleThreadHook(true); bp.SetForThreads(); return true; } } return false; } bool HWBreakpoint::Clear(void* address) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); for (int index = 0; index < 4; ++index) if (bp.m_address[index] == address) { bp.m_address[index] = nullptr; if (--bp.m_countActive == 0) bp.ToggleThreadHook(false); bp.SetForThreads(); return true; } } return false; } void HWBreakpoint::ToggleThread(DWORD tid, bool enableBP) { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); bp.m_pendingThread.tid = tid; bp.m_pendingThread.enable = enableBP; SetEvent(bp.m_workerSignal); WaitForSingleObject(bp.m_workerDone, INFINITE); } } void HWBreakpoint::BuildTrampoline() { DWORD64* rtlThreadStartAddress = (DWORD64*)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlUserThreadStart"); SYSTEM_INFO si; GetSystemInfo(&si); DWORD64 gMinAddress = (DWORD64)si.lpMinimumApplicationAddress; DWORD64 gMaxAddress = (DWORD64)si.lpMaximumApplicationAddress; DWORD64 minAddr = std::max<DWORD64>(gMinAddress, (DWORD64)rtlThreadStartAddress - 0x20000000); DWORD64 maxAddr = std::min<DWORD64>(gMaxAddress, (DWORD64)rtlThreadStartAddress + 0x20000000); const size_t BlockSize = 0x10000; intptr_t min = minAddr / BlockSize; intptr_t max = maxAddr / BlockSize; int rel = 0; m_trampoline = nullptr; MEMORY_BASIC_INFORMATION mi = { 0 }; for (int i = 0; i < (max - min + 1); ++i) { rel = -rel + (i & 1); void* pQuery = reinterpret_cast<void*>(((min + max) / 2 + rel) * BlockSize); VirtualQuery(pQuery, &mi, sizeof(mi)); if (mi.State == MEM_FREE) { m_trampoline = (unsigned char*)VirtualAlloc(pQuery, BlockSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (m_trampoline != nullptr) break; } } if (!m_trampoline) return; *(unsigned char*) &m_trampoline[0] = 0x51; // push rcx *(unsigned char*) &m_trampoline[1] = 0x52; // push rdx *(unsigned char*) &m_trampoline[2] = 0x52; // push rdx *(unsigned short*) &m_trampoline[3] = 0x15FF; // call *(DWORD*) &m_trampoline[5] = 0x00000018; // ThreadDeutor *(unsigned char*) &m_trampoline[9] = 0x5A; // pop rdx *(unsigned char*) &m_trampoline[10] = 0x5A; // pop rdx *(unsigned char*) &m_trampoline[11] = 0x59; // pop rcx *(DWORD*) &m_trampoline[12] = 0x48EC8348; // sub rsp, 0x48 (2 instruction from prologe of target hook) *(unsigned short*) &m_trampoline[16] = 0x8B4C; // mov r9, *(unsigned char*) &m_trampoline[18] = 0xC9; // rcx *(short*) &m_trampoline[19] = 0x25FF; // jmp *(DWORD*) &m_trampoline[21] = 0x00000000; // rtlThreadStartAddress + 7 // address data for call & jump *(DWORD64*) &m_trampoline[25] = (DWORD64)((unsigned char*)rtlThreadStartAddress + 7); *(DWORD64*) &m_trampoline[33] = (DWORD64)ThreadDeutor; } void HWBreakpoint::ToggleThreadHook(bool set) { DWORD oldProtect; DWORD64* rtlThreadStartAddress = (DWORD64*)GetProcAddress(GetModuleHandle("ntdll.dll"), "RtlUserThreadStart"); if (m_trampoline && set) { VirtualProtect(rtlThreadStartAddress, 5, PAGE_EXECUTE_READWRITE, &oldProtect); unsigned char* b = (unsigned char*)rtlThreadStartAddress; // TODO: replace with one atomic operation b[0] = 0xE9; *(DWORD*)&b[1] = (DWORD)m_trampoline - (DWORD)b - 5; VirtualProtect(rtlThreadStartAddress, 5, oldProtect, &oldProtect); } else if (*rtlThreadStartAddress != *(DWORD64*)m_originalOpcode) { VirtualProtect(rtlThreadStartAddress, 5, PAGE_EXECUTE_READWRITE, &oldProtect); *rtlThreadStartAddress = *(DWORD64*)m_originalOpcode; VirtualProtect(rtlThreadStartAddress, 5, oldProtect, &oldProtect); } } void HWBreakpoint::ThreadDeutor() { HWBreakpoint& bp = GetInstance(); { CriticalSection::Scope lock(bp.m_cs); { bp.m_pendingThread.tid = GetCurrentThreadId(); bp.m_pendingThread.enable = true; SetEvent(bp.m_workerSignal); WaitForSingleObject(bp.m_workerDone, INFINITE); } } } void HWBreakpoint::SetForThreads() { const DWORD pid = GetCurrentProcessId(); HANDLE hThreadSnap = INVALID_HANDLE_VALUE; THREADENTRY32 te32; hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) return; te32.dwSize = sizeof(THREADENTRY32); if(!Thread32First(hThreadSnap, &te32)) { CloseHandle(hThreadSnap); return; } do { if(te32.th32OwnerProcessID == pid) { CriticalSection::Scope lock(m_cs); { m_pendingThread.tid = te32.th32ThreadID; m_pendingThread.enable = true; SetEvent(m_workerSignal); WaitForSingleObject(m_workerDone, INFINITE); } } } while(Thread32Next(hThreadSnap, &te32)); } void HWBreakpoint::SetThread(DWORD tid, bool enableBP) { // this function supposed to be called only from worker thread if (GetCurrentThreadId() == tid) return; HANDLE hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, FALSE, tid); if (!hThread) return; CONTEXT cxt; cxt.ContextFlags = CONTEXT_DEBUG_REGISTERS; if (SuspendThread(hThread) == -1) goto Final; if (!GetThreadContext(hThread, &cxt)) goto Final; for (int index = 0; index < 4; ++index) { const bool isSet = m_address[index] != nullptr; SetBits(cxt.Dr7, index*2, 1, isSet); if (isSet) { switch (index) { case 0: cxt.Dr0 = (DWORD_PTR) m_address[index]; break; case 1: cxt.Dr1 = (DWORD_PTR) m_address[index]; break; case 2: cxt.Dr2 = (DWORD_PTR) m_address[index]; break; case 3: cxt.Dr3 = (DWORD_PTR) m_address[index]; break; } SetBits(cxt.Dr7, 16 + (index*4), 2, m_when[index]); SetBits(cxt.Dr7, 18 + (index*4), 2, m_len[index]); } } if (!SetThreadContext(hThread, &cxt)) goto Final; if (ResumeThread(hThread) == -1) goto Final; std::cout << "Set BP for Thread: " << tid << std::endl; Final: CloseHandle(hThread); } DWORD HWBreakpoint::WorkerThreadProc(LPVOID lpParameter) { HWBreakpoint& bp = *(HWBreakpoint*)lpParameter; SetEvent(bp.m_workerDone); while (WaitForSingleObject(bp.m_workerSignal, INFINITE) == WAIT_OBJECT_0) { // signal for abort if (bp.m_pendingThread.tid == -1) return 0; bp.SetThread(bp.m_pendingThread.tid, bp.m_pendingThread.enable); SetEvent(bp.m_workerDone); } return 0; }<|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2021 Intel Corporation #include <algorithm> #include <sstream> #include "streaming/onevpl/engine/decode/decode_engine_legacy.hpp" #include "streaming/onevpl/engine/transcode/transcode_engine_legacy.hpp" #include "streaming/onevpl/accelerators/accel_policy_dx11.hpp" #include "streaming/onevpl/accelerators/accel_policy_cpu.hpp" #include "streaming/onevpl/accelerators/accel_policy_va_api.hpp" #include "streaming/onevpl/utils.hpp" #include "streaming/onevpl/cfg_params_parser.hpp" #include "streaming/onevpl/data_provider_defines.hpp" #include "streaming/onevpl/source_priv.hpp" #include "logger.hpp" #ifndef HAVE_ONEVPL namespace cv { namespace gapi { namespace wip { namespace onevpl { bool GSource::Priv::pull(cv::gapi::wip::Data&) { return true; } GMetaArg GSource::Priv::descr_of() const { return {}; } } // namespace onevpl } // namespace wip } // namespace gapi } // namespace cv #else // HAVE_ONEVPL // TODO global variable move it into Source after CloneSession issue resolving mfxLoader mfx_handle = MFXLoad(); int impl_number = 0; namespace cv { namespace gapi { namespace wip { namespace onevpl { enum { VPL_NEW_API_MAJOR_VERSION = 2, VPL_NEW_API_MINOR_VERSION = 2 }; GSource::Priv::Priv() : // mfx_handle(MFXLoad()), mfx_impl_description(), mfx_handle_configs(), cfg_params(), mfx_session(), description(), description_is_valid(false), engine(), consumed_frames_count() { GAPI_LOG_INFO(nullptr, "Initialized MFX handle: " << mfx_handle); } GSource::Priv::Priv(std::shared_ptr<IDataProvider> provider, const std::vector<CfgParam>& params, std::shared_ptr<IDeviceSelector> device_selector) : GSource::Priv() { // Enable Config if (params.empty()) { GAPI_LOG_INFO(nullptr, "No special cfg params requested - use default"); this->cfg_params = getDefaultCfgParams(); } else { this->cfg_params = params; } GAPI_LOG_DEBUG(nullptr, "Requested cfg params count: " << cfg_params.size()); this->mfx_handle_configs.resize(cfg_params.size()); // Build VPL handle config from major input params // VPL dispatcher then uses this config handle to look up for all existing VPL impl // satisfying major input params and available in the system GAPI_LOG_INFO(nullptr, "Creating VPL config from input params"); auto cfg_param_it = cfg_params.begin(); for (mfxConfig& cfg_inst : mfx_handle_configs) { cfg_inst = MFXCreateConfig(mfx_handle); GAPI_Assert(cfg_inst && "MFXCreateConfig failed"); if (!cfg_param_it->is_major()) { GAPI_LOG_DEBUG(nullptr, "Skip not major param: " << cfg_param_it->to_string()); ++cfg_param_it; continue; } GAPI_LOG_DEBUG(nullptr, "Apply major param: " << cfg_param_it->to_string()); mfxVariant mfx_param = cfg_param_to_mfx_variant(*cfg_param_it); mfxStatus sts = MFXSetConfigFilterProperty(cfg_inst, (mfxU8 *)cfg_param_it->get_name().c_str(), mfx_param); if (sts != MFX_ERR_NONE ) { GAPI_LOG_WARNING(nullptr, "MFXSetConfigFilterProperty failed, error: " << mfxstatus_to_string(sts) << " - for \"" << cfg_param_it->get_name() << "\""); GAPI_Assert(false && "MFXSetConfigFilterProperty failed"); } mfx_param.Type = MFX_VARIANT_TYPE_U32; mfx_param.Data.U32 = MFX_EXTBUFF_VPP_SCALING; sts = MFXSetConfigFilterProperty(cfg_inst, (mfxU8 *)"mfxImplDescription.mfxVPPDescription.filter.FilterFourCC", mfx_param); if (sts != MFX_ERR_NONE ) { GAPI_LOG_WARNING(nullptr, "MFXSetConfigFilterProperty failed, error: " << mfxstatus_to_string(sts) << " - for \"mfxImplDescription.mfxVPPDescription.filter.FilterFourCC\""); GAPI_Assert(false && "MFXSetConfigFilterProperty failed"); } ++cfg_param_it; } // collect optional-preferred input parameters from input params // which may (optionally) or may not be used to choose the most preferable // VPL implementation (for example, specific API version or Debug/Release VPL build) std::vector<CfgParam> preferred_params; std::copy_if(cfg_params.begin(), cfg_params.end(), std::back_inserter(preferred_params), [] (const CfgParam& param) { return !param.is_major(); }); std::sort(preferred_params.begin(), preferred_params.end()); GAPI_LOG_DEBUG(nullptr, "Find MFX better implementation from handle: " << mfx_handle << " is satisfying preferable params count: " << preferred_params.size()); int i = 0; mfxImplDescription *idesc = nullptr; std::vector<mfxImplDescription*> available_impl_descriptions; std::map<size_t/*matches count*/, int /*impl index*/> matches_count; while (MFX_ERR_NONE == MFXEnumImplementations(mfx_handle, i, MFX_IMPLCAPS_IMPLDESCSTRUCTURE, reinterpret_cast<mfxHDL *>(&idesc))) { available_impl_descriptions.push_back(idesc); std::stringstream ss; mfxHDL hImplPath = nullptr; if (MFX_ERR_NONE == MFXEnumImplementations(mfx_handle, i, MFX_IMPLCAPS_IMPLPATH, &hImplPath)) { if (hImplPath) { ss << "Implementation path: " << reinterpret_cast<mfxChar *>(hImplPath) << std::endl; MFXDispReleaseImplDescription(mfx_handle, hImplPath); } } ss << *idesc << std::endl; GAPI_LOG_INFO(nullptr, "Implementation index: " << i << "\n" << ss.str()); // Only one VPL implementation is required for GSource here. // Let's find intersection params from available impl with preferable input params // to find best match. // An available VPL implementation with max matching count std::vector<CfgParam> impl_params = get_params_from_string<CfgParam>(ss.str()); std::sort(impl_params.begin(), impl_params.end()); GAPI_LOG_DEBUG(nullptr, "Find implementation cfg params count: " << impl_params.size()); std::vector<CfgParam> matched_params; std::set_intersection(impl_params.begin(), impl_params.end(), preferred_params.begin(), preferred_params.end(), std::back_inserter(matched_params)); if (preferred_params.empty()) { // in case of no input preferrance we consider all params are matched // for the first available VPL implementation. It will be a chosen one matches_count.emplace(impl_params.size(), i++); GAPI_LOG_DEBUG(nullptr, "No preferable params, use the first one implementation"); break; } else { GAPI_LOG_DEBUG(nullptr, "Equal param intersection count: " << matched_params.size()); matches_count.emplace(matches_count.size(), i++); } } // Extract the most suitable VPL implementation by max score auto max_match_it = matches_count.rbegin(); if (max_match_it == matches_count.rend()) { std::stringstream ss; for (const auto &p : cfg_params) { ss << p.to_string() << std::endl; } GAPI_LOG_WARNING(nullptr, "No one suitable MFX implementation is found, requested params:\n" << ss.str()); throw std::runtime_error("Cannot find any suitable MFX implementation for requested configuration"); } // TODO impl_number is global for now impl_number = max_match_it->second; GAPI_LOG_INFO(nullptr, "Chosen implementation index: " << impl_number); // release unusable impl available_impl_descriptions std::swap(mfx_impl_description, available_impl_descriptions[impl_number]); for (mfxImplDescription* unusable_impl_descr : available_impl_descriptions) { if (unusable_impl_descr) { MFXDispReleaseImplDescription(mfx_handle, unusable_impl_descr); } } available_impl_descriptions.clear(); // create session for implementation mfxStatus sts = MFXCreateSession(mfx_handle, impl_number, &mfx_session); if (MFX_ERR_NONE != sts) { GAPI_LOG_WARNING(nullptr, "Cannot create MFX Session for implementation index:" << std::to_string(impl_number) << ", error: " << mfxstatus_to_string(sts)); } GAPI_LOG_INFO(nullptr, "Initialized MFX session: " << mfx_session); // create session driving engine if required if (!engine) { std::unique_ptr<VPLAccelerationPolicy> acceleration = initializeHWAccel(device_selector); // TODO Add factory static method in ProcessingEngineBase if (mfx_impl_description->ApiVersion.Major >= VPL_NEW_API_MAJOR_VERSION) { GAPI_Assert(false && "GSource mfx_impl_description->ApiVersion.Major >= VPL_NEW_API_MAJOR_VERSION" " - is not implemented"); } else { const auto& transcode_params = VPLLegacyTranscodeEngine::get_vpp_params(preferred_params); if (!transcode_params.empty()) { engine.reset(new VPLLegacyTranscodeEngine(std::move(acceleration))); } else { engine.reset(new VPLLegacyDecodeEngine(std::move(acceleration))); } } } // create engine session for processing mfx session pipeline auto engine_session_ptr = engine->initialize_session(mfx_session, cfg_params, provider); const mfxFrameInfo& video_param = engine_session_ptr->get_video_param(); // set valid description description.size = cv::Size { video_param.Width, video_param.Height}; switch(video_param.FourCC) { case MFX_FOURCC_I420: throw std::runtime_error("Cannot parse GMetaArg description: MediaFrame doesn't support I420 type"); case MFX_FOURCC_NV12: description.fmt = cv::MediaFormat::NV12; break; default: throw std::runtime_error("Cannot parse GMetaArg description: MediaFrame unknown 'fmt' type: " + std::to_string(video_param.FourCC)); } description_is_valid = true; //prepare session for processing engine->process(mfx_session); } GSource::Priv::~Priv() { engine.reset(); GAPI_LOG_INFO(nullptr, "consumed frames count: " << consumed_frames_count); GAPI_LOG_INFO(nullptr, "Unload MFX implementation description: " << mfx_impl_description); MFXDispReleaseImplDescription(mfx_handle, mfx_impl_description); GAPI_LOG_INFO(nullptr, "Unload MFX handle: " << mfx_handle); //MFXUnload(mfx_handle); } std::unique_ptr<VPLAccelerationPolicy> GSource::Priv::initializeHWAccel(std::shared_ptr<IDeviceSelector> selector) { std::unique_ptr<VPLAccelerationPolicy> ret; auto accel_mode_it = std::find_if(cfg_params.begin(), cfg_params.end(), [] (const CfgParam& value) { return value.get_name() == CfgParam::acceleration_mode_name(); }); if (accel_mode_it == cfg_params.end()) { GAPI_LOG_DEBUG(nullptr, "No HW Accel requested. Use CPU"); ret.reset(new VPLCPUAccelerationPolicy(selector)); return ret; } GAPI_LOG_DEBUG(nullptr, "Add HW acceleration support"); mfxVariant accel_mode = cfg_param_to_mfx_variant(*accel_mode_it); switch(accel_mode.Data.U32) { case MFX_ACCEL_MODE_VIA_D3D11: { std::unique_ptr<VPLDX11AccelerationPolicy> cand(new VPLDX11AccelerationPolicy(selector)); ret = std::move(cand); break; } case MFX_ACCEL_MODE_VIA_VAAPI: { std::unique_ptr<VPLVAAPIAccelerationPolicy> cand(new VPLVAAPIAccelerationPolicy(selector)); ret = std::move(cand); break; } case MFX_ACCEL_MODE_NA: { std::unique_ptr<VPLCPUAccelerationPolicy> cand(new VPLCPUAccelerationPolicy(selector)); ret = std::move(cand); break; } default: { GAPI_LOG_WARNING(nullptr, "Cannot initialize HW Accel: " "invalid accelerator type: " << std::to_string(accel_mode.Data.U32)); GAPI_Assert(false && "Cannot initialize HW Accel"); } } return ret; } const std::vector<CfgParam>& GSource::Priv::getDefaultCfgParams() { #ifdef __WIN32__ static const std::vector<CfgParam> def_params = get_params_from_string<CfgParam>( "mfxImplDescription.Impl: MFX_IMPL_TYPE_HARDWARE\n" "mfxImplDescription.AccelerationMode: MFX_ACCEL_MODE_VIA_D3D11\n"); #else static const std::vector<CfgParam> def_params = get_params_from_string<CfgParam>( "mfxImplDescription.Impl: MFX_IMPL_TYPE_HARDWARE\n"); #endif return def_params; } const std::vector<CfgParam>& GSource::Priv::getCfgParams() const { return cfg_params; } bool GSource::Priv::pull(cv::gapi::wip::Data& data) { ProcessingEngineBase::ExecutionStatus status = ProcessingEngineBase::ExecutionStatus::Continue; while (0 == engine->get_ready_frames_count() && status == ProcessingEngineBase::ExecutionStatus::Continue) { status = engine->process(mfx_session); } if (engine->get_ready_frames_count()) { engine->get_frame(data); consumed_frames_count++; return true; } else { return false; } } GMetaArg GSource::Priv::descr_of() const { GAPI_Assert(description_is_valid); GMetaArg arg(description); return arg; } } // namespace onevpl } // namespace wip } // namespace gapi } // namespace cv #endif // HAVE_ONEVPL <commit_msg>Replace MFX major version assertion to warning<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2021 Intel Corporation #include <algorithm> #include <sstream> #include "streaming/onevpl/engine/decode/decode_engine_legacy.hpp" #include "streaming/onevpl/engine/transcode/transcode_engine_legacy.hpp" #include "streaming/onevpl/accelerators/accel_policy_dx11.hpp" #include "streaming/onevpl/accelerators/accel_policy_cpu.hpp" #include "streaming/onevpl/accelerators/accel_policy_va_api.hpp" #include "streaming/onevpl/utils.hpp" #include "streaming/onevpl/cfg_params_parser.hpp" #include "streaming/onevpl/data_provider_defines.hpp" #include "streaming/onevpl/source_priv.hpp" #include "logger.hpp" #ifndef HAVE_ONEVPL namespace cv { namespace gapi { namespace wip { namespace onevpl { bool GSource::Priv::pull(cv::gapi::wip::Data&) { return true; } GMetaArg GSource::Priv::descr_of() const { return {}; } } // namespace onevpl } // namespace wip } // namespace gapi } // namespace cv #else // HAVE_ONEVPL // TODO global variable move it into Source after CloneSession issue resolving mfxLoader mfx_handle = MFXLoad(); int impl_number = 0; namespace cv { namespace gapi { namespace wip { namespace onevpl { enum { VPL_NEW_API_MAJOR_VERSION = 2, VPL_NEW_API_MINOR_VERSION = 2 }; GSource::Priv::Priv() : // mfx_handle(MFXLoad()), mfx_impl_description(), mfx_handle_configs(), cfg_params(), mfx_session(), description(), description_is_valid(false), engine(), consumed_frames_count() { GAPI_LOG_INFO(nullptr, "Initialized MFX handle: " << mfx_handle); } GSource::Priv::Priv(std::shared_ptr<IDataProvider> provider, const std::vector<CfgParam>& params, std::shared_ptr<IDeviceSelector> device_selector) : GSource::Priv() { // Enable Config if (params.empty()) { GAPI_LOG_INFO(nullptr, "No special cfg params requested - use default"); this->cfg_params = getDefaultCfgParams(); } else { this->cfg_params = params; } GAPI_LOG_DEBUG(nullptr, "Requested cfg params count: " << cfg_params.size()); this->mfx_handle_configs.resize(cfg_params.size()); // Build VPL handle config from major input params // VPL dispatcher then uses this config handle to look up for all existing VPL impl // satisfying major input params and available in the system GAPI_LOG_INFO(nullptr, "Creating VPL config from input params"); auto cfg_param_it = cfg_params.begin(); for (mfxConfig& cfg_inst : mfx_handle_configs) { cfg_inst = MFXCreateConfig(mfx_handle); GAPI_Assert(cfg_inst && "MFXCreateConfig failed"); if (!cfg_param_it->is_major()) { GAPI_LOG_DEBUG(nullptr, "Skip not major param: " << cfg_param_it->to_string()); ++cfg_param_it; continue; } GAPI_LOG_DEBUG(nullptr, "Apply major param: " << cfg_param_it->to_string()); mfxVariant mfx_param = cfg_param_to_mfx_variant(*cfg_param_it); mfxStatus sts = MFXSetConfigFilterProperty(cfg_inst, (mfxU8 *)cfg_param_it->get_name().c_str(), mfx_param); if (sts != MFX_ERR_NONE ) { GAPI_LOG_WARNING(nullptr, "MFXSetConfigFilterProperty failed, error: " << mfxstatus_to_string(sts) << " - for \"" << cfg_param_it->get_name() << "\""); GAPI_Assert(false && "MFXSetConfigFilterProperty failed"); } mfx_param.Type = MFX_VARIANT_TYPE_U32; mfx_param.Data.U32 = MFX_EXTBUFF_VPP_SCALING; sts = MFXSetConfigFilterProperty(cfg_inst, (mfxU8 *)"mfxImplDescription.mfxVPPDescription.filter.FilterFourCC", mfx_param); if (sts != MFX_ERR_NONE ) { GAPI_LOG_WARNING(nullptr, "MFXSetConfigFilterProperty failed, error: " << mfxstatus_to_string(sts) << " - for \"mfxImplDescription.mfxVPPDescription.filter.FilterFourCC\""); GAPI_Assert(false && "MFXSetConfigFilterProperty failed"); } ++cfg_param_it; } // collect optional-preferred input parameters from input params // which may (optionally) or may not be used to choose the most preferable // VPL implementation (for example, specific API version or Debug/Release VPL build) std::vector<CfgParam> preferred_params; std::copy_if(cfg_params.begin(), cfg_params.end(), std::back_inserter(preferred_params), [] (const CfgParam& param) { return !param.is_major(); }); std::sort(preferred_params.begin(), preferred_params.end()); GAPI_LOG_DEBUG(nullptr, "Find MFX better implementation from handle: " << mfx_handle << " is satisfying preferable params count: " << preferred_params.size()); int i = 0; mfxImplDescription *idesc = nullptr; std::vector<mfxImplDescription*> available_impl_descriptions; std::map<size_t/*matches count*/, int /*impl index*/> matches_count; while (MFX_ERR_NONE == MFXEnumImplementations(mfx_handle, i, MFX_IMPLCAPS_IMPLDESCSTRUCTURE, reinterpret_cast<mfxHDL *>(&idesc))) { available_impl_descriptions.push_back(idesc); std::stringstream ss; mfxHDL hImplPath = nullptr; if (MFX_ERR_NONE == MFXEnumImplementations(mfx_handle, i, MFX_IMPLCAPS_IMPLPATH, &hImplPath)) { if (hImplPath) { ss << "Implementation path: " << reinterpret_cast<mfxChar *>(hImplPath) << std::endl; MFXDispReleaseImplDescription(mfx_handle, hImplPath); } } ss << *idesc << std::endl; GAPI_LOG_INFO(nullptr, "Implementation index: " << i << "\n" << ss.str()); // Only one VPL implementation is required for GSource here. // Let's find intersection params from available impl with preferable input params // to find best match. // An available VPL implementation with max matching count std::vector<CfgParam> impl_params = get_params_from_string<CfgParam>(ss.str()); std::sort(impl_params.begin(), impl_params.end()); GAPI_LOG_DEBUG(nullptr, "Find implementation cfg params count: " << impl_params.size()); std::vector<CfgParam> matched_params; std::set_intersection(impl_params.begin(), impl_params.end(), preferred_params.begin(), preferred_params.end(), std::back_inserter(matched_params)); if (preferred_params.empty()) { // in case of no input preferrance we consider all params are matched // for the first available VPL implementation. It will be a chosen one matches_count.emplace(impl_params.size(), i++); GAPI_LOG_DEBUG(nullptr, "No preferable params, use the first one implementation"); break; } else { GAPI_LOG_DEBUG(nullptr, "Equal param intersection count: " << matched_params.size()); matches_count.emplace(matches_count.size(), i++); } } // Extract the most suitable VPL implementation by max score auto max_match_it = matches_count.rbegin(); if (max_match_it == matches_count.rend()) { std::stringstream ss; for (const auto &p : cfg_params) { ss << p.to_string() << std::endl; } GAPI_LOG_WARNING(nullptr, "No one suitable MFX implementation is found, requested params:\n" << ss.str()); throw std::runtime_error("Cannot find any suitable MFX implementation for requested configuration"); } // TODO impl_number is global for now impl_number = max_match_it->second; GAPI_LOG_INFO(nullptr, "Chosen implementation index: " << impl_number); // release unusable impl available_impl_descriptions std::swap(mfx_impl_description, available_impl_descriptions[impl_number]); for (mfxImplDescription* unusable_impl_descr : available_impl_descriptions) { if (unusable_impl_descr) { MFXDispReleaseImplDescription(mfx_handle, unusable_impl_descr); } } available_impl_descriptions.clear(); // create session for implementation mfxStatus sts = MFXCreateSession(mfx_handle, impl_number, &mfx_session); if (MFX_ERR_NONE != sts) { GAPI_LOG_WARNING(nullptr, "Cannot create MFX Session for implementation index:" << std::to_string(impl_number) << ", error: " << mfxstatus_to_string(sts)); } GAPI_LOG_INFO(nullptr, "Initialized MFX session: " << mfx_session); // create session driving engine if required if (!engine) { std::unique_ptr<VPLAccelerationPolicy> acceleration = initializeHWAccel(device_selector); // TODO Add factory static method in ProcessingEngineBase if (mfx_impl_description->ApiVersion.Major >= VPL_NEW_API_MAJOR_VERSION) { GAPI_LOG_WARNING(NULL, "GSource mfx_impl_description->ApiVersion.Major >= VPL_NEW_API_MAJOR_VERSION" " - is not implemented. G-API only supports an older version of OneVPL API."); } const auto& transcode_params = VPLLegacyTranscodeEngine::get_vpp_params(preferred_params); if (!transcode_params.empty()) { engine.reset(new VPLLegacyTranscodeEngine(std::move(acceleration))); } else { engine.reset(new VPLLegacyDecodeEngine(std::move(acceleration))); } } // create engine session for processing mfx session pipeline auto engine_session_ptr = engine->initialize_session(mfx_session, cfg_params, provider); const mfxFrameInfo& video_param = engine_session_ptr->get_video_param(); // set valid description description.size = cv::Size { video_param.Width, video_param.Height}; switch(video_param.FourCC) { case MFX_FOURCC_I420: throw std::runtime_error("Cannot parse GMetaArg description: MediaFrame doesn't support I420 type"); case MFX_FOURCC_NV12: description.fmt = cv::MediaFormat::NV12; break; default: throw std::runtime_error("Cannot parse GMetaArg description: MediaFrame unknown 'fmt' type: " + std::to_string(video_param.FourCC)); } description_is_valid = true; //prepare session for processing engine->process(mfx_session); } GSource::Priv::~Priv() { engine.reset(); GAPI_LOG_INFO(nullptr, "consumed frames count: " << consumed_frames_count); GAPI_LOG_INFO(nullptr, "Unload MFX implementation description: " << mfx_impl_description); MFXDispReleaseImplDescription(mfx_handle, mfx_impl_description); GAPI_LOG_INFO(nullptr, "Unload MFX handle: " << mfx_handle); //MFXUnload(mfx_handle); } std::unique_ptr<VPLAccelerationPolicy> GSource::Priv::initializeHWAccel(std::shared_ptr<IDeviceSelector> selector) { std::unique_ptr<VPLAccelerationPolicy> ret; auto accel_mode_it = std::find_if(cfg_params.begin(), cfg_params.end(), [] (const CfgParam& value) { return value.get_name() == CfgParam::acceleration_mode_name(); }); if (accel_mode_it == cfg_params.end()) { GAPI_LOG_DEBUG(nullptr, "No HW Accel requested. Use CPU"); ret.reset(new VPLCPUAccelerationPolicy(selector)); return ret; } GAPI_LOG_DEBUG(nullptr, "Add HW acceleration support"); mfxVariant accel_mode = cfg_param_to_mfx_variant(*accel_mode_it); switch(accel_mode.Data.U32) { case MFX_ACCEL_MODE_VIA_D3D11: { std::unique_ptr<VPLDX11AccelerationPolicy> cand(new VPLDX11AccelerationPolicy(selector)); ret = std::move(cand); break; } case MFX_ACCEL_MODE_VIA_VAAPI: { std::unique_ptr<VPLVAAPIAccelerationPolicy> cand(new VPLVAAPIAccelerationPolicy(selector)); ret = std::move(cand); break; } case MFX_ACCEL_MODE_NA: { std::unique_ptr<VPLCPUAccelerationPolicy> cand(new VPLCPUAccelerationPolicy(selector)); ret = std::move(cand); break; } default: { GAPI_LOG_WARNING(nullptr, "Cannot initialize HW Accel: " "invalid accelerator type: " << std::to_string(accel_mode.Data.U32)); GAPI_Assert(false && "Cannot initialize HW Accel"); } } return ret; } const std::vector<CfgParam>& GSource::Priv::getDefaultCfgParams() { #ifdef __WIN32__ static const std::vector<CfgParam> def_params = get_params_from_string<CfgParam>( "mfxImplDescription.Impl: MFX_IMPL_TYPE_HARDWARE\n" "mfxImplDescription.AccelerationMode: MFX_ACCEL_MODE_VIA_D3D11\n"); #else static const std::vector<CfgParam> def_params = get_params_from_string<CfgParam>( "mfxImplDescription.Impl: MFX_IMPL_TYPE_HARDWARE\n"); #endif return def_params; } const std::vector<CfgParam>& GSource::Priv::getCfgParams() const { return cfg_params; } bool GSource::Priv::pull(cv::gapi::wip::Data& data) { ProcessingEngineBase::ExecutionStatus status = ProcessingEngineBase::ExecutionStatus::Continue; while (0 == engine->get_ready_frames_count() && status == ProcessingEngineBase::ExecutionStatus::Continue) { status = engine->process(mfx_session); } if (engine->get_ready_frames_count()) { engine->get_frame(data); consumed_frames_count++; return true; } else { return false; } } GMetaArg GSource::Priv::descr_of() const { GAPI_Assert(description_is_valid); GMetaArg arg(description); return arg; } } // namespace onevpl } // namespace wip } // namespace gapi } // namespace cv #endif // HAVE_ONEVPL <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <map> #include <boost/utility.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <vpr/Util/Debug.h> #include <vpr/Util/Assert.h> #include <vpr/md/SIM/Network/NetworkGraph.h> namespace vpr { namespace sim { // Crummy helper for crappy C++ I/O. static void skipToEOL (std::istream& stream) { char c; while ( (c = stream.get()) != '\n' ) { /* Loop. */ ; } } vpr::ReturnStatus NetworkGraph::construct (const std::string& path) { vpr::ReturnStatus status; std::ifstream input_file(path.c_str()); if ( input_file.is_open() ) { vpr::Uint32 node_count, full_edge_count, half_edge_count; std::map<int, boost::graph_traits<net_graph_t>::vertex_descriptor> vertex_map; std::string temp_str; input_file >> node_count; for ( vpr::Uint32 i = 0; i < node_count; i++ ) { vpr::Uint32 index; vpr::Uint16 node_type; std::string node_ip; input_file >> index >> node_type >> node_ip; skipToEOL(input_file); // Now create the vertex and add it to the graph. NetworkNode node_prop(index, node_type, node_ip); vertex_map[index] = boost::add_vertex(NodeProperty(node_prop), mGraph); } input_file >> full_edge_count; // The file format tells us that there are twice as many edges as // actually listed--probably to indicate bidirectional links. half_edge_count = full_edge_count / 2; net_edge_t new_edge; bool added; boost::property_map<net_graph_t, boost::edge_weight_t>::type weight_map; weight_map = boost::get(boost::edge_weight_t(), mGraph); for ( vpr::Uint32 i = 0; i < full_edge_count; i++ ) { double length, bw; vpr::Uint32 from_node, to_node, delay; std::string net_type, net_ip; vpr::Uint16 net_id; input_file >> from_node >> to_node >> length >> delay >> bw >> net_type >> net_id >> net_ip; // This is here mainly for debugging this clunky "parser". vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << "Loading edge #" << i << ": (" << from_node << " --> " << to_node << ", " << length << " miles, " << delay << " us, " << bw << " Mbps, type: " << net_type << ", ID: " << net_id << ", " << net_ip << ")\n" << vprDEBUG_FLUSH; // Now add the edge to the graph. NetworkLine line(length, bw, delay, net_type, net_id, net_ip); boost::tie(new_edge, added) = boost::add_edge(vertex_map[from_node], vertex_map[to_node], LineProperty(line), mGraph); if ( added ) { weight_map[new_edge] = line.getWeight(); } // Sanity check to ensure that we do not get stuck trying to read // bytes that aren't there. This probably slows things down, but I // don't know of a better way to do this. if ( input_file.peek() == EOF && i + 1 < full_edge_count ) { vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << "WARNING: Expected " << full_edge_count << " edges, found " << i + 1 << std::endl << vprDEBUG_FLUSH; break; } } mGraphValid = true; } else { vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << "ERROR: Failed to open graph input file named " << path << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } NetworkLine NetworkGraph::getLineProperty (const NetworkGraph::net_edge_t& e) const { // XXX: Need to make an assertion that e is in mGraph! // vprASSERT(... && "Given edge not found in the graph!"); boost::property_map<net_graph_t, network_line_t>::const_type line_prop_map; line_prop_map = boost::get(network_line_t(), mGraph); return line_prop_map[e]; } void NetworkGraph::setLineProperty (const NetworkGraph::net_edge_t& e, const vpr::sim::NetworkLine& prop) { // XXX: Need to make an assertion that e is in mGraph! // vprASSERT(... && "Given edge not found in the graph!"); boost::property_map<net_graph_t, network_line_t>::type line_prop_map; line_prop_map = boost::get(network_line_t(), mGraph); line_prop_map[e] = prop; } vpr::ReturnStatus NetworkGraph::getNodeWithAddr (const vpr::Uint32 addr, NetworkGraph::net_vertex_t& node) { vprASSERT(isValid() && "Trying to use invalid graph"); vpr::ReturnStatus status(vpr::ReturnStatus::Fail); boost::graph_traits<net_graph_t>::vertex_iterator vi, vi_end; NetworkNode node_prop; boost::tie(vi, vi_end) = boost::vertices(mGraph); for ( ; vi != vi_end; vi++ ) { node_prop = getNodeProperty(*vi); if ( node_prop.getIpAddress() == addr ) { node = *vi; status.setCode(vpr::ReturnStatus::Succeed); break; } } return status; } NetworkNode NetworkGraph::getNodeProperty (const NetworkGraph::net_vertex_t& v) const { // XXX: Need to make an assertion that v is in mGraph! // vprASSERT(... && "Given vertex not found in the graph!"); boost::property_map<net_graph_t, network_node_t>::const_type node_prop_map; node_prop_map = boost::get(network_node_t(), mGraph); return node_prop_map[v]; } void NetworkGraph::setNodeProperty (const NetworkGraph::net_vertex_t& v, const vpr::sim::NetworkNode& prop) { // XXX: Need to make an assertion that v is in mGraph! // vprASSERT(... && "Given vertex not found in the graph!"); boost::property_map<net_graph_t, network_node_t>::type node_prop_map; node_prop_map = boost::get(network_node_t(), mGraph); node_prop_map[v] = prop; } NetworkGraph::VertexListPtr NetworkGraph::getShortestPath (const NetworkGraph::net_vertex_t& src, const NetworkGraph::net_vertex_t& dest) const { NetworkGraph::VertexListPtr vlist(new NetworkGraph::VertexList); std::vector<int> dist(boost::num_vertices(mGraph)); std::vector<net_vertex_t> pred(boost::num_vertices(mGraph)); NetworkGraph::net_vertex_t p(dest), q; std::stack<net_vertex_t> vstack; boost::property_map<net_graph_t, network_node_t>::const_type node_prop_map; boost::property_map<net_graph_t, boost::edge_weight_t>::const_type weight_map; node_prop_map = boost::get(network_node_t(), mGraph); weight_map = boost::get(boost::edge_weight_t(), mGraph); // boost::dijkstra_shortest_paths(mGraph, src, // boost::distance_map(&dist[0]).predecessor_map(&pred[0])); boost::dijkstra_shortest_paths(mGraph, src, &pred[0], &dist[0], weight_map, boost::get(boost::vertex_index_t(), mGraph), std::less<int>(), boost::closed_plus<int>(), std::numeric_limits<int>::max(), 0, boost::default_dijkstra_visitor()); vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL) << "Path (dest <-- src): " << node_prop_map[dest].getIpAddressString() << vprDEBUG_FLUSH; vstack.push(dest); // Put the vertices returned in the predecessor map into a stack so that // the order that we can reverse the order and put them into vlist. while ( (q = pred[p]) != p ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_VERB_LVL) << " <-- " << node_prop_map[q].getIpAddressString() << vprDEBUG_FLUSH; vstack.push(q); p = q; } vprDEBUG_CONT(vprDBG_ALL, vprDBG_VERB_LVL) << " <-- " << node_prop_map[src].getIpAddressString() << vprDEBUG_FLUSH; vprDEBUG_CONT_END(vprDBG_ALL, vprDBG_VERB_LVL) << "\n" << vprDEBUG_FLUSH; vprASSERT(p == src && "Destination is unreachable!"); while ( vstack.size() > 0 ) { vlist->push_back(vstack.top()); vstack.pop(); } return vlist; } NetworkGraph::VertexListPtr NetworkGraph::reversePath (NetworkGraph::VertexListPtr path) { VertexListPtr new_path(new NetworkGraph::VertexList(path->size())); NetworkGraph::VertexList::reverse_iterator i; for ( i = path->rbegin(); i != path->rend(); i++ ) { new_path->push_back(*i); } return new_path; } } // End of sim namespace } // End of vpr namespace <commit_msg>Removed a vprDEBUG_CONT() call that was causing the source node to be printed twice. (This was definitely confusing me during debugging last night.)<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <map> #include <boost/utility.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <vpr/Util/Debug.h> #include <vpr/Util/Assert.h> #include <vpr/md/SIM/Network/NetworkGraph.h> namespace vpr { namespace sim { // Crummy helper for crappy C++ I/O. static void skipToEOL (std::istream& stream) { char c; while ( (c = stream.get()) != '\n' ) { /* Loop. */ ; } } vpr::ReturnStatus NetworkGraph::construct (const std::string& path) { vpr::ReturnStatus status; std::ifstream input_file(path.c_str()); if ( input_file.is_open() ) { vpr::Uint32 node_count, full_edge_count, half_edge_count; std::map<int, boost::graph_traits<net_graph_t>::vertex_descriptor> vertex_map; std::string temp_str; input_file >> node_count; for ( vpr::Uint32 i = 0; i < node_count; i++ ) { vpr::Uint32 index; vpr::Uint16 node_type; std::string node_ip; input_file >> index >> node_type >> node_ip; skipToEOL(input_file); // Now create the vertex and add it to the graph. NetworkNode node_prop(index, node_type, node_ip); vertex_map[index] = boost::add_vertex(NodeProperty(node_prop), mGraph); } input_file >> full_edge_count; // The file format tells us that there are twice as many edges as // actually listed--probably to indicate bidirectional links. half_edge_count = full_edge_count / 2; net_edge_t new_edge; bool added; boost::property_map<net_graph_t, boost::edge_weight_t>::type weight_map; weight_map = boost::get(boost::edge_weight_t(), mGraph); for ( vpr::Uint32 i = 0; i < full_edge_count; i++ ) { double length, bw; vpr::Uint32 from_node, to_node, delay; std::string net_type, net_ip; vpr::Uint16 net_id; input_file >> from_node >> to_node >> length >> delay >> bw >> net_type >> net_id >> net_ip; // This is here mainly for debugging this clunky "parser". vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << "Loading edge #" << i << ": (" << from_node << " --> " << to_node << ", " << length << " miles, " << delay << " us, " << bw << " Mbps, type: " << net_type << ", ID: " << net_id << ", " << net_ip << ")\n" << vprDEBUG_FLUSH; // Now add the edge to the graph. NetworkLine line(length, bw, delay, net_type, net_id, net_ip); boost::tie(new_edge, added) = boost::add_edge(vertex_map[from_node], vertex_map[to_node], LineProperty(line), mGraph); if ( added ) { weight_map[new_edge] = line.getWeight(); } // Sanity check to ensure that we do not get stuck trying to read // bytes that aren't there. This probably slows things down, but I // don't know of a better way to do this. if ( input_file.peek() == EOF && i + 1 < full_edge_count ) { vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << "WARNING: Expected " << full_edge_count << " edges, found " << i + 1 << std::endl << vprDEBUG_FLUSH; break; } } mGraphValid = true; } else { vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << "ERROR: Failed to open graph input file named " << path << std::endl << vprDEBUG_FLUSH; status.setCode(vpr::ReturnStatus::Fail); } return status; } NetworkLine NetworkGraph::getLineProperty (const NetworkGraph::net_edge_t& e) const { // XXX: Need to make an assertion that e is in mGraph! // vprASSERT(... && "Given edge not found in the graph!"); boost::property_map<net_graph_t, network_line_t>::const_type line_prop_map; line_prop_map = boost::get(network_line_t(), mGraph); return line_prop_map[e]; } void NetworkGraph::setLineProperty (const NetworkGraph::net_edge_t& e, const vpr::sim::NetworkLine& prop) { // XXX: Need to make an assertion that e is in mGraph! // vprASSERT(... && "Given edge not found in the graph!"); boost::property_map<net_graph_t, network_line_t>::type line_prop_map; line_prop_map = boost::get(network_line_t(), mGraph); line_prop_map[e] = prop; } vpr::ReturnStatus NetworkGraph::getNodeWithAddr (const vpr::Uint32 addr, NetworkGraph::net_vertex_t& node) { vprASSERT(isValid() && "Trying to use invalid graph"); vpr::ReturnStatus status(vpr::ReturnStatus::Fail); boost::graph_traits<net_graph_t>::vertex_iterator vi, vi_end; NetworkNode node_prop; boost::tie(vi, vi_end) = boost::vertices(mGraph); for ( ; vi != vi_end; vi++ ) { node_prop = getNodeProperty(*vi); if ( node_prop.getIpAddress() == addr ) { node = *vi; status.setCode(vpr::ReturnStatus::Succeed); break; } } return status; } NetworkNode NetworkGraph::getNodeProperty (const NetworkGraph::net_vertex_t& v) const { // XXX: Need to make an assertion that v is in mGraph! // vprASSERT(... && "Given vertex not found in the graph!"); boost::property_map<net_graph_t, network_node_t>::const_type node_prop_map; node_prop_map = boost::get(network_node_t(), mGraph); return node_prop_map[v]; } void NetworkGraph::setNodeProperty (const NetworkGraph::net_vertex_t& v, const vpr::sim::NetworkNode& prop) { // XXX: Need to make an assertion that v is in mGraph! // vprASSERT(... && "Given vertex not found in the graph!"); boost::property_map<net_graph_t, network_node_t>::type node_prop_map; node_prop_map = boost::get(network_node_t(), mGraph); node_prop_map[v] = prop; } NetworkGraph::VertexListPtr NetworkGraph::getShortestPath (const NetworkGraph::net_vertex_t& src, const NetworkGraph::net_vertex_t& dest) const { NetworkGraph::VertexListPtr vlist(new NetworkGraph::VertexList); std::vector<int> dist(boost::num_vertices(mGraph)); std::vector<net_vertex_t> pred(boost::num_vertices(mGraph)); NetworkGraph::net_vertex_t p(dest), q; std::stack<net_vertex_t> vstack; boost::property_map<net_graph_t, network_node_t>::const_type node_prop_map; boost::property_map<net_graph_t, boost::edge_weight_t>::const_type weight_map; node_prop_map = boost::get(network_node_t(), mGraph); weight_map = boost::get(boost::edge_weight_t(), mGraph); // boost::dijkstra_shortest_paths(mGraph, src, // boost::distance_map(&dist[0]).predecessor_map(&pred[0])); boost::dijkstra_shortest_paths(mGraph, src, &pred[0], &dist[0], weight_map, boost::get(boost::vertex_index_t(), mGraph), std::less<int>(), boost::closed_plus<int>(), std::numeric_limits<int>::max(), 0, boost::default_dijkstra_visitor()); vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL) << "Path (dest <-- src): " << node_prop_map[dest].getIpAddressString() << vprDEBUG_FLUSH; vstack.push(dest); // Put the vertices returned in the predecessor map into a stack so that // the order that we can reverse the order and put them into vlist. while ( (q = pred[p]) != p ) { vprDEBUG_CONT(vprDBG_ALL, vprDBG_VERB_LVL) << " <-- " << node_prop_map[q].getIpAddressString() << vprDEBUG_FLUSH; vstack.push(q); p = q; } vprDEBUG_CONT_END(vprDBG_ALL, vprDBG_VERB_LVL) << "\n" << vprDEBUG_FLUSH; vprASSERT(p == src && "Destination is unreachable!"); while ( vstack.size() > 0 ) { vlist->push_back(vstack.top()); vstack.pop(); } return vlist; } NetworkGraph::VertexListPtr NetworkGraph::reversePath (NetworkGraph::VertexListPtr path) { VertexListPtr new_path(new NetworkGraph::VertexList(path->size())); NetworkGraph::VertexList::reverse_iterator i; for ( i = path->rbegin(); i != path->rend(); i++ ) { new_path->push_back(*i); } return new_path; } } // End of sim namespace } // End of vpr namespace <|endoftext|>
<commit_before>#include "cvm.h" void DabValue::dump(FILE *file) const { static const char *types[] = {"INVA", "FIXN", "BOOL", "NIL ", "CLAS", "OBJE", "ARRY", "UIN8", "UI16", "UI32", "UI64", "INT8", "IN16", "IN32", "IN64", "METH", "PTR*", "BYT*", "CSTR", "DSTR"}; assert((int)data.type >= 0 && (int)data.type < (int)countof(types)); fprintf(file, "%s ", types[data.type]); print(file, true); } dab_class_t DabValue::class_index() const { switch (data.type) { case TYPE_FIXNUM: return CLASS_FIXNUM; break; case TYPE_BOOLEAN: return CLASS_BOOLEAN; break; case TYPE_NIL: return CLASS_NILCLASS; break; case TYPE_ARRAY: return CLASS_ARRAY; break; case TYPE_CLASS: return (dab_class_t)data.fixnum; break; case TYPE_OBJECT: return (dab_class_t)this->data.object->object->klass; break; case TYPE_UINT8: return CLASS_UINT8; break; case TYPE_UINT16: return CLASS_UINT16; break; case TYPE_UINT32: return CLASS_UINT32; break; case TYPE_UINT64: return CLASS_UINT64; break; case TYPE_INT8: return CLASS_INT8; break; case TYPE_INT16: return CLASS_INT16; break; case TYPE_INT32: return CLASS_INT32; break; case TYPE_INT64: return CLASS_INT64; break; case TYPE_METHOD: return CLASS_METHOD; break; case TYPE_INTPTR: return CLASS_INTPTR; break; case TYPE_BYTEBUFFER: return CLASS_BYTEBUFFER; break; case TYPE_LITERALSTRING: return CLASS_LITERALSTRING; break; case TYPE_DYNAMICSTRING: return CLASS_DYNAMICSTRING; break; default: fprintf(stderr, "Unknown data.type %d.\n", (int)data.type); assert(false); break; } } std::string DabValue::class_name() const { return get_class().name; } DabClass &DabValue::get_class() const { return $VM->get_class(class_index()); } bool DabValue::is_a(const DabClass &klass) const { return get_class().is_subclass_of(klass); } void DabValue::print(FILE *out, bool debug) const { fprintf(out, "%s", print_value(debug).c_str()); } std::string DabValue::print_value(bool debug) const { char buffer[32] = {0}; std::string ret; bool use_ret = false; switch (data.type) { case TYPE_FIXNUM: snprintf(buffer, sizeof(buffer), "%" PRId64, data.fixnum); break; case TYPE_UINT8: snprintf(buffer, sizeof(buffer), "%" PRIu8, data.num_uint8); break; case TYPE_UINT16: snprintf(buffer, sizeof(buffer), "%" PRIu16, data.num_uint16); break; case TYPE_UINT32: snprintf(buffer, sizeof(buffer), "%" PRIu32, data.num_uint32); break; case TYPE_UINT64: snprintf(buffer, sizeof(buffer), "%" PRIu64, data.num_uint64); break; case TYPE_INT8: snprintf(buffer, sizeof(buffer), "%" PRId8, data.num_int8); break; case TYPE_INT16: snprintf(buffer, sizeof(buffer), "%" PRId16, data.num_int16); break; case TYPE_INT32: snprintf(buffer, sizeof(buffer), "%" PRId32, data.num_int32); break; case TYPE_INT64: snprintf(buffer, sizeof(buffer), "%" PRId64, data.num_int64); break; case TYPE_BOOLEAN: snprintf(buffer, sizeof(buffer), "%s", data.boolean ? "true" : "false"); break; case TYPE_NIL: snprintf(buffer, sizeof(buffer), "nil"); break; case TYPE_CLASS: snprintf(buffer, sizeof(buffer), "%s", class_name().c_str()); break; case TYPE_OBJECT: snprintf(buffer, sizeof(buffer), "#%s", class_name().c_str()); break; case TYPE_INTPTR: snprintf(buffer, sizeof(buffer), "%p", data.intptr); break; case TYPE_ARRAY: { use_ret = true; ret = "["; size_t i = 0; for (auto &item : array()) { if (i) ret += ", "; ret += item.print_value(debug); i++; } ret += "]"; } break; case TYPE_LITERALSTRING: case TYPE_DYNAMICSTRING: { use_ret = true; ret = string(); if (debug) { ret = "\"" + ret + "\""; } } break; default: snprintf(buffer, sizeof(buffer), "?"); break; } if (!use_ret) { ret = buffer; } if (debug && is_object()) { char extra[64] = {0}; snprintf(extra, sizeof(extra), " [%d strong]", (int)data.object->count_strong); ret += extra; } return ret; } std::vector<DabValue> &DabValue::array() const { assert(data.type == TYPE_ARRAY); auto *obj = (DabArray *)data.object->object; return obj->array; } std::vector<uint8_t> &DabValue::bytebuffer() const { assert(data.type == TYPE_BYTEBUFFER); auto *obj = (DabByteBuffer *)data.object->object; return obj->bytebuffer; } std::string DabValue::literal_string() const { assert(data.type == TYPE_LITERALSTRING); auto *obj = (DabLiteralString *)data.object->object; return std::string(obj->pointer, obj->length); } std::string DabValue::dynamic_string() const { assert(data.type == TYPE_DYNAMICSTRING); auto *obj = (DabDynamicString *)data.object->object; return obj->value; } std::string DabValue::string() const { bool dynamic = data.type == TYPE_DYNAMICSTRING; bool literal = data.type == TYPE_LITERALSTRING; bool method = data.type == TYPE_METHOD; assert(literal || method || dynamic); if (method) { return $VM->get_symbol(data.fixnum); } else if (dynamic) { return dynamic_string(); } else { return literal_string(); } } bool DabValue::truthy() const { switch (data.type) { case TYPE_FIXNUM: return data.fixnum; case TYPE_UINT8: return data.num_uint8; case TYPE_UINT32: return data.num_uint32; case TYPE_UINT64: return data.num_uint64; case TYPE_INT32: return data.num_int32; case TYPE_BOOLEAN: return data.boolean; case TYPE_INTPTR: return data.intptr; case TYPE_NIL: return false; case TYPE_ARRAY: return array().size() > 0; case TYPE_LITERALSTRING: return literal_string().length(); case TYPE_DYNAMICSTRING: return dynamic_string().length(); default: return true; } } DabValue DabValue::create_instance() const { assert(data.type == TYPE_CLASS); DabBaseObject *object = nullptr; auto type = TYPE_OBJECT; if (data.fixnum == CLASS_ARRAY) { object = new DabArray; type = TYPE_ARRAY; } else if (data.fixnum == CLASS_BYTEBUFFER) { object = new DabByteBuffer; type = TYPE_BYTEBUFFER; } else if (data.fixnum == CLASS_LITERALSTRING) { object = new DabLiteralString; type = TYPE_LITERALSTRING; } else if (data.fixnum == CLASS_DYNAMICSTRING) { object = new DabDynamicString; type = TYPE_DYNAMICSTRING; } else { object = new DabObject; } DabObjectProxy *proxy = new DabObjectProxy; proxy->object = object; proxy->count_strong = 1; proxy->object->klass = this->data.fixnum; DabValue ret; ret.data.type = type; ret.data.object = proxy; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p A (strong %3d): ! created : ", proxy, (int)proxy->count_strong); ret.dump(stderr); fprintf(stderr, "\n"); } return ret; } DabValue DabValue::allocate_dynstr(const char *str) { DabValue klass = $VM->get_class(CLASS_DYNAMICSTRING); auto ret = klass.create_instance(); auto *obj = (DabDynamicString *)ret.data.object->object; obj->value = str; return ret; } DabValue DabValue::_get_instvar(dab_symbol_t symbol) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if (!this->data.object->object) { return DabValue(nullptr); } auto object = (DabObject *)this->data.object->object; auto &instvars = object->instvars; if (!instvars.count(symbol)) { return DabValue(nullptr); } return instvars[symbol]; } DabValue DabValue::get_instvar(dab_symbol_t symbol) { auto ret = _get_instvar(symbol); if ($VM->options.verbose) { auto name = $VM->get_symbol(symbol); fprintf(stderr, "vm: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object, (int)this->data.object->count_strong, name.c_str()); ret.print(stderr); fprintf(stderr, "\n"); } return ret; } void DabValue::set_instvar(dab_symbol_t symbol, const DabValue &value) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if ($VM->options.verbose) { auto name = $VM->get_symbol(symbol); fprintf(stderr, "vm: proxy %p (strong %d): Set instvar <%s> to ", this->data.object, (int)this->data.object->count_strong, name.c_str()); value.print(stderr); fprintf(stderr, "\n"); } if (!this->data.object->object) { return; } auto object = (DabObject *)this->data.object->object; auto &instvars = object->instvars; instvars[symbol] = value; } void DabValue::set_data(const DabValueData &other_data) { data = other_data; if ($VM->options.autorelease) { retain(); } } DabValue::DabValue(const DabValue &other) { set_data(other.data); } DabValue &DabValue::operator=(const DabValue &other) { set_data(other.data); return *this; } DabValue::~DabValue() { if ($VM->options.autorelease) { release(); } } void DabValue::release() { if (is_object()) { this->data.object->release(this); this->data.object = nullptr; } this->data.type = TYPE_NIL; this->data._initialize = 0; } void DabValue::retain() { if (is_object()) { data.object->retain(this); } } // void DabObjectProxy::retain(DabValue *value) { (void)value; if (this->destroying) return; count_strong += 1; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p B (strong %3d): + retained: ", this, (int)this->count_strong); value->dump(stderr); fprintf(stderr, "\n"); } } void DabObjectProxy::release(DabValue *value) { if (this->destroying) return; count_strong -= 1; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p B (strong %3d): - released: ", this, (int)this->count_strong); value->dump(stderr); fprintf(stderr, "\n"); } if (count_strong == 0) { destroy(value); } } void DabObjectProxy::destroy(DabValue *value) { (void)value; this->destroying = true; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p C (strong %3d): X destroy\n", this, (int)this->count_strong); } delete object; delete this; } size_t DabValue::use_count() const { if (is_object()) { return data.object->count_strong; } else { return 65535; } } <commit_msg>vm: dab_value throws on unknown type instead of failing<commit_after>#include "cvm.h" void DabValue::dump(FILE *file) const { static const char *types[] = {"INVA", "FIXN", "BOOL", "NIL ", "CLAS", "OBJE", "ARRY", "UIN8", "UI16", "UI32", "UI64", "INT8", "IN16", "IN32", "IN64", "METH", "PTR*", "BYT*", "CSTR", "DSTR"}; assert((int)data.type >= 0 && (int)data.type < (int)countof(types)); fprintf(file, "%s ", types[data.type]); print(file, true); } dab_class_t DabValue::class_index() const { switch (data.type) { case TYPE_FIXNUM: return CLASS_FIXNUM; break; case TYPE_BOOLEAN: return CLASS_BOOLEAN; break; case TYPE_NIL: return CLASS_NILCLASS; break; case TYPE_ARRAY: return CLASS_ARRAY; break; case TYPE_CLASS: return (dab_class_t)data.fixnum; break; case TYPE_OBJECT: return (dab_class_t)this->data.object->object->klass; break; case TYPE_UINT8: return CLASS_UINT8; break; case TYPE_UINT16: return CLASS_UINT16; break; case TYPE_UINT32: return CLASS_UINT32; break; case TYPE_UINT64: return CLASS_UINT64; break; case TYPE_INT8: return CLASS_INT8; break; case TYPE_INT16: return CLASS_INT16; break; case TYPE_INT32: return CLASS_INT32; break; case TYPE_INT64: return CLASS_INT64; break; case TYPE_METHOD: return CLASS_METHOD; break; case TYPE_INTPTR: return CLASS_INTPTR; break; case TYPE_BYTEBUFFER: return CLASS_BYTEBUFFER; break; case TYPE_LITERALSTRING: return CLASS_LITERALSTRING; break; case TYPE_DYNAMICSTRING: return CLASS_DYNAMICSTRING; break; default: char description[256]; sprintf(description, "Unknown data.type %d.\n", (int)data.type); throw DabRuntimeError(description); } } std::string DabValue::class_name() const { return get_class().name; } DabClass &DabValue::get_class() const { return $VM->get_class(class_index()); } bool DabValue::is_a(const DabClass &klass) const { return get_class().is_subclass_of(klass); } void DabValue::print(FILE *out, bool debug) const { fprintf(out, "%s", print_value(debug).c_str()); } std::string DabValue::print_value(bool debug) const { char buffer[32] = {0}; std::string ret; bool use_ret = false; switch (data.type) { case TYPE_FIXNUM: snprintf(buffer, sizeof(buffer), "%" PRId64, data.fixnum); break; case TYPE_UINT8: snprintf(buffer, sizeof(buffer), "%" PRIu8, data.num_uint8); break; case TYPE_UINT16: snprintf(buffer, sizeof(buffer), "%" PRIu16, data.num_uint16); break; case TYPE_UINT32: snprintf(buffer, sizeof(buffer), "%" PRIu32, data.num_uint32); break; case TYPE_UINT64: snprintf(buffer, sizeof(buffer), "%" PRIu64, data.num_uint64); break; case TYPE_INT8: snprintf(buffer, sizeof(buffer), "%" PRId8, data.num_int8); break; case TYPE_INT16: snprintf(buffer, sizeof(buffer), "%" PRId16, data.num_int16); break; case TYPE_INT32: snprintf(buffer, sizeof(buffer), "%" PRId32, data.num_int32); break; case TYPE_INT64: snprintf(buffer, sizeof(buffer), "%" PRId64, data.num_int64); break; case TYPE_BOOLEAN: snprintf(buffer, sizeof(buffer), "%s", data.boolean ? "true" : "false"); break; case TYPE_NIL: snprintf(buffer, sizeof(buffer), "nil"); break; case TYPE_CLASS: snprintf(buffer, sizeof(buffer), "%s", class_name().c_str()); break; case TYPE_OBJECT: snprintf(buffer, sizeof(buffer), "#%s", class_name().c_str()); break; case TYPE_INTPTR: snprintf(buffer, sizeof(buffer), "%p", data.intptr); break; case TYPE_ARRAY: { use_ret = true; ret = "["; size_t i = 0; for (auto &item : array()) { if (i) ret += ", "; ret += item.print_value(debug); i++; } ret += "]"; } break; case TYPE_LITERALSTRING: case TYPE_DYNAMICSTRING: { use_ret = true; ret = string(); if (debug) { ret = "\"" + ret + "\""; } } break; default: snprintf(buffer, sizeof(buffer), "?"); break; } if (!use_ret) { ret = buffer; } if (debug && is_object()) { char extra[64] = {0}; snprintf(extra, sizeof(extra), " [%d strong]", (int)data.object->count_strong); ret += extra; } return ret; } std::vector<DabValue> &DabValue::array() const { assert(data.type == TYPE_ARRAY); auto *obj = (DabArray *)data.object->object; return obj->array; } std::vector<uint8_t> &DabValue::bytebuffer() const { assert(data.type == TYPE_BYTEBUFFER); auto *obj = (DabByteBuffer *)data.object->object; return obj->bytebuffer; } std::string DabValue::literal_string() const { assert(data.type == TYPE_LITERALSTRING); auto *obj = (DabLiteralString *)data.object->object; return std::string(obj->pointer, obj->length); } std::string DabValue::dynamic_string() const { assert(data.type == TYPE_DYNAMICSTRING); auto *obj = (DabDynamicString *)data.object->object; return obj->value; } std::string DabValue::string() const { bool dynamic = data.type == TYPE_DYNAMICSTRING; bool literal = data.type == TYPE_LITERALSTRING; bool method = data.type == TYPE_METHOD; assert(literal || method || dynamic); if (method) { return $VM->get_symbol(data.fixnum); } else if (dynamic) { return dynamic_string(); } else { return literal_string(); } } bool DabValue::truthy() const { switch (data.type) { case TYPE_FIXNUM: return data.fixnum; case TYPE_UINT8: return data.num_uint8; case TYPE_UINT32: return data.num_uint32; case TYPE_UINT64: return data.num_uint64; case TYPE_INT32: return data.num_int32; case TYPE_BOOLEAN: return data.boolean; case TYPE_INTPTR: return data.intptr; case TYPE_NIL: return false; case TYPE_ARRAY: return array().size() > 0; case TYPE_LITERALSTRING: return literal_string().length(); case TYPE_DYNAMICSTRING: return dynamic_string().length(); default: return true; } } DabValue DabValue::create_instance() const { assert(data.type == TYPE_CLASS); DabBaseObject *object = nullptr; auto type = TYPE_OBJECT; if (data.fixnum == CLASS_ARRAY) { object = new DabArray; type = TYPE_ARRAY; } else if (data.fixnum == CLASS_BYTEBUFFER) { object = new DabByteBuffer; type = TYPE_BYTEBUFFER; } else if (data.fixnum == CLASS_LITERALSTRING) { object = new DabLiteralString; type = TYPE_LITERALSTRING; } else if (data.fixnum == CLASS_DYNAMICSTRING) { object = new DabDynamicString; type = TYPE_DYNAMICSTRING; } else { object = new DabObject; } DabObjectProxy *proxy = new DabObjectProxy; proxy->object = object; proxy->count_strong = 1; proxy->object->klass = this->data.fixnum; DabValue ret; ret.data.type = type; ret.data.object = proxy; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p A (strong %3d): ! created : ", proxy, (int)proxy->count_strong); ret.dump(stderr); fprintf(stderr, "\n"); } return ret; } DabValue DabValue::allocate_dynstr(const char *str) { DabValue klass = $VM->get_class(CLASS_DYNAMICSTRING); auto ret = klass.create_instance(); auto *obj = (DabDynamicString *)ret.data.object->object; obj->value = str; return ret; } DabValue DabValue::_get_instvar(dab_symbol_t symbol) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if (!this->data.object->object) { return DabValue(nullptr); } auto object = (DabObject *)this->data.object->object; auto &instvars = object->instvars; if (!instvars.count(symbol)) { return DabValue(nullptr); } return instvars[symbol]; } DabValue DabValue::get_instvar(dab_symbol_t symbol) { auto ret = _get_instvar(symbol); if ($VM->options.verbose) { auto name = $VM->get_symbol(symbol); fprintf(stderr, "vm: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object, (int)this->data.object->count_strong, name.c_str()); ret.print(stderr); fprintf(stderr, "\n"); } return ret; } void DabValue::set_instvar(dab_symbol_t symbol, const DabValue &value) { assert(this->data.type == TYPE_OBJECT); assert(this->data.object); if ($VM->options.verbose) { auto name = $VM->get_symbol(symbol); fprintf(stderr, "vm: proxy %p (strong %d): Set instvar <%s> to ", this->data.object, (int)this->data.object->count_strong, name.c_str()); value.print(stderr); fprintf(stderr, "\n"); } if (!this->data.object->object) { return; } auto object = (DabObject *)this->data.object->object; auto &instvars = object->instvars; instvars[symbol] = value; } void DabValue::set_data(const DabValueData &other_data) { data = other_data; if ($VM->options.autorelease) { retain(); } } DabValue::DabValue(const DabValue &other) { set_data(other.data); } DabValue &DabValue::operator=(const DabValue &other) { set_data(other.data); return *this; } DabValue::~DabValue() { if ($VM->options.autorelease) { release(); } } void DabValue::release() { if (is_object()) { this->data.object->release(this); this->data.object = nullptr; } this->data.type = TYPE_NIL; this->data._initialize = 0; } void DabValue::retain() { if (is_object()) { data.object->retain(this); } } // void DabObjectProxy::retain(DabValue *value) { (void)value; if (this->destroying) return; count_strong += 1; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p B (strong %3d): + retained: ", this, (int)this->count_strong); value->dump(stderr); fprintf(stderr, "\n"); } } void DabObjectProxy::release(DabValue *value) { if (this->destroying) return; count_strong -= 1; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p B (strong %3d): - released: ", this, (int)this->count_strong); value->dump(stderr); fprintf(stderr, "\n"); } if (count_strong == 0) { destroy(value); } } void DabObjectProxy::destroy(DabValue *value) { (void)value; this->destroying = true; if ($VM->options.verbose) { fprintf(stderr, "vm: proxy %p C (strong %3d): X destroy\n", this, (int)this->count_strong); } delete object; delete this; } size_t DabValue::use_count() const { if (is_object()) { return data.object->count_strong; } else { return 65535; } } <|endoftext|>
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2010 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <string> #include <gmtl/Math.h> #include <gmtl/Vec.h> #include <gmtl/Matrix.h> #include <gmtl/MatrixOps.h> #include <gmtl/Generate.h> #include <gmtl/Xforms.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Type/Position/PositionUnitConversion.h> #include <vrj/Kernel/User.h> #include <vrj/Util/Debug.h> #include <vrj/Display/SurfaceProjection.h> #include <vrj/Display/TrackedSurfaceProjection.h> #include <vrj/Display/DisplayExceptions.h> #include <vrj/Display/SurfaceViewport.h> namespace vrj { SurfaceViewport::SurfaceViewport() : Viewport() , mTracked(false) { /* Do nothing. */ ; } ViewportPtr SurfaceViewport::create() { return ViewportPtr(new SurfaceViewport()); } SurfaceViewport::~SurfaceViewport() { /* Do nothing. */ ; } bool SurfaceViewport::config(jccl::ConfigElementPtr element) { vprASSERT(element.get() != NULL); vprASSERT(element->getID() == "surface_viewport"); // Call base class config if ( ! Viewport::config(element) ) { return false; } bool result(true); mType = SURFACE; // Read in the corners mLLCorner.set(element->getProperty<float>("lower_left_corner", 0), element->getProperty<float>("lower_left_corner", 1), element->getProperty<float>("lower_left_corner", 2)); mLRCorner.set(element->getProperty<float>("lower_right_corner", 0), element->getProperty<float>("lower_right_corner", 1), element->getProperty<float>("lower_right_corner", 2)); mURCorner.set(element->getProperty<float>("upper_right_corner", 0), element->getProperty<float>("upper_right_corner", 1), element->getProperty<float>("upper_right_corner", 2)); mULCorner.set(element->getProperty<float>("upper_left_corner", 0), element->getProperty<float>("upper_left_corner", 1), element->getProperty<float>("upper_left_corner", 2)); // Calculate the rotation and the pts // calculateSurfaceRotation(); // calculateCornersInBaseFrame(); // Get info about being tracked mTracked = element->getProperty<bool>("tracked"); if(mTracked) { mTrackerProxyName = element->getProperty<std::string>("tracker_proxy"); } // Create Projection objects // NOTE: The -'s are because we are measuring distance to // the left(bottom) which is opposite the normal axis direction //vjMatrix rot_inv; //rot_inv.invert(mSurfaceRotation); SurfaceProjectionPtr left_proj; SurfaceProjectionPtr right_proj; if(!mTracked) { left_proj = SurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner); right_proj = SurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner); } else { left_proj = TrackedSurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner, mTrackerProxyName); right_proj = TrackedSurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner, mTrackerProxyName); } try { left_proj->validateCorners(); right_proj->validateCorners(); // NOTE: Even if the corner validation above failed, we still proceed with // setting up mLeftProj and mRightProj. This is because other code is not // written to handle the case of a viewport having no projections. This // could definitely be improved. mLeftProj = left_proj; mRightProj = right_proj; // Configure the projections mLeftProj->config(element); mLeftProj->setEye(Projection::LEFT); mLeftProj->setViewport(shared_from_this()); mRightProj->config(element); mRightProj->setEye(Projection::RIGHT); mRightProj->setViewport(shared_from_this()); } catch (InvalidSurfaceException& ex) { vprDEBUG(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED, "ERROR") << ": The surface defined by the viewport named\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << " '" << element->getName() << "' is invalid!\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << ex.what() << std::endl << vprDEBUG_FLUSH; result = false; } return result; } void SurfaceViewport::updateProjections(const float positionScale) { // -- Calculate Eye Positions -- // const gmtl::Matrix44f cur_head_pos( mUser->getHeadPosProxy()->getData(positionScale) ); /* Coord head_coord(cur_head_pos); // Create a user readable version vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << "vjDisplay::updateProjections: Getting head position" << std::endl << vprDEBUG_FLUSH; vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << "\tHeadPos:" << head_coord.pos << "\tHeadOr:" << head_coord.orient << std::endl << vprDEBUG_FLUSH; */ // Compute location of left and right eyes //float interocularDist = 2.75f/12.0f; float interocular_dist = mUser->getInterocularDistance(); interocular_dist *= positionScale; // Scale eye separation // Distance to move eye. const float eye_offset(interocular_dist * 0.5f); // NOTE: Eye coord system is -z forward, x-right, y-up if (Viewport::LEFT_EYE == mView || Viewport::STEREO == mView) { const gmtl::Matrix44f left_eye_pos( cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(-eye_offset, 0, 0)) ); mLeftProj->calcViewMatrix(left_eye_pos, positionScale); } if (Viewport::RIGHT_EYE == mView || Viewport::STEREO == mView) { const gmtl::Matrix44f right_eye_pos( cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0)) ); mRightProj->calcViewMatrix(right_eye_pos, positionScale); } } std::ostream& SurfaceViewport::outStream(std::ostream& out, const unsigned int indentLevel) { Viewport::outStream(out, indentLevel); out << std::endl; const std::string indent_text(indentLevel, ' '); /* out << "LL: " << mLLCorner << ", LR: " << mLRCorner << ", UR: " << mURCorner << ", UL:" << mULCorner << std::endl; out << "surfRot: \n" << mSurfaceRotation << std::endl; */ if ( mView == vrj::Viewport::LEFT_EYE || mView == vrj::Viewport::STEREO ) { out << indent_text << "Left projection:\n"; mLeftProj->outStream(out, indentLevel + 2); out << std::endl; } if ( mView == vrj::Viewport::RIGHT_EYE || mView == vrj::Viewport::STEREO ) { out << indent_text << "Right projection:\n"; mRightProj->outStream(out, indentLevel + 2); out << std::endl; } return out; } } <commit_msg>Removed code that was commented out 8 to 9 years ago.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2010 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vrj/vrjConfig.h> #include <string> #include <gmtl/Math.h> #include <gmtl/Vec.h> #include <gmtl/Matrix.h> #include <gmtl/MatrixOps.h> #include <gmtl/Generate.h> #include <gmtl/Xforms.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Type/Position/PositionUnitConversion.h> #include <vrj/Kernel/User.h> #include <vrj/Util/Debug.h> #include <vrj/Display/SurfaceProjection.h> #include <vrj/Display/TrackedSurfaceProjection.h> #include <vrj/Display/DisplayExceptions.h> #include <vrj/Display/SurfaceViewport.h> namespace vrj { SurfaceViewport::SurfaceViewport() : Viewport() , mTracked(false) { /* Do nothing. */ ; } ViewportPtr SurfaceViewport::create() { return ViewportPtr(new SurfaceViewport()); } SurfaceViewport::~SurfaceViewport() { /* Do nothing. */ ; } bool SurfaceViewport::config(jccl::ConfigElementPtr element) { vprASSERT(element.get() != NULL); vprASSERT(element->getID() == "surface_viewport"); // Call base class config if ( ! Viewport::config(element) ) { return false; } bool result(true); mType = SURFACE; // Read in the corners mLLCorner.set(element->getProperty<float>("lower_left_corner", 0), element->getProperty<float>("lower_left_corner", 1), element->getProperty<float>("lower_left_corner", 2)); mLRCorner.set(element->getProperty<float>("lower_right_corner", 0), element->getProperty<float>("lower_right_corner", 1), element->getProperty<float>("lower_right_corner", 2)); mURCorner.set(element->getProperty<float>("upper_right_corner", 0), element->getProperty<float>("upper_right_corner", 1), element->getProperty<float>("upper_right_corner", 2)); mULCorner.set(element->getProperty<float>("upper_left_corner", 0), element->getProperty<float>("upper_left_corner", 1), element->getProperty<float>("upper_left_corner", 2)); // Calculate the rotation and the pts // calculateSurfaceRotation(); // calculateCornersInBaseFrame(); // Get info about being tracked mTracked = element->getProperty<bool>("tracked"); if(mTracked) { mTrackerProxyName = element->getProperty<std::string>("tracker_proxy"); } // Create Projection objects // NOTE: The -'s are because we are measuring distance to // the left(bottom) which is opposite the normal axis direction //vjMatrix rot_inv; //rot_inv.invert(mSurfaceRotation); SurfaceProjectionPtr left_proj; SurfaceProjectionPtr right_proj; if(!mTracked) { left_proj = SurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner); right_proj = SurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner); } else { left_proj = TrackedSurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner, mTrackerProxyName); right_proj = TrackedSurfaceProjection::create(mLLCorner, mLRCorner, mURCorner, mULCorner, mTrackerProxyName); } try { left_proj->validateCorners(); right_proj->validateCorners(); // NOTE: Even if the corner validation above failed, we still proceed with // setting up mLeftProj and mRightProj. This is because other code is not // written to handle the case of a viewport having no projections. This // could definitely be improved. mLeftProj = left_proj; mRightProj = right_proj; // Configure the projections mLeftProj->config(element); mLeftProj->setEye(Projection::LEFT); mLeftProj->setViewport(shared_from_this()); mRightProj->config(element); mRightProj->setEye(Projection::RIGHT); mRightProj->setViewport(shared_from_this()); } catch (InvalidSurfaceException& ex) { vprDEBUG(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << clrOutBOLD(clrRED, "ERROR") << ": The surface defined by the viewport named\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << " '" << element->getName() << "' is invalid!\n" << vprDEBUG_FLUSH; vprDEBUG_NEXT(vrjDBG_DISP_MGR, vprDBG_CRITICAL_LVL) << ex.what() << std::endl << vprDEBUG_FLUSH; result = false; } return result; } void SurfaceViewport::updateProjections(const float positionScale) { // -- Calculate Eye Positions -- // const gmtl::Matrix44f cur_head_pos( mUser->getHeadPosProxy()->getData(positionScale) ); // Compute location of left and right eyes float interocular_dist = mUser->getInterocularDistance(); interocular_dist *= positionScale; // Scale eye separation // Distance to move eye. const float eye_offset(interocular_dist * 0.5f); // NOTE: Eye coord system is -z forward, x-right, y-up if (Viewport::LEFT_EYE == mView || Viewport::STEREO == mView) { const gmtl::Matrix44f left_eye_pos( cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(-eye_offset, 0, 0)) ); mLeftProj->calcViewMatrix(left_eye_pos, positionScale); } if (Viewport::RIGHT_EYE == mView || Viewport::STEREO == mView) { const gmtl::Matrix44f right_eye_pos( cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0)) ); mRightProj->calcViewMatrix(right_eye_pos, positionScale); } } std::ostream& SurfaceViewport::outStream(std::ostream& out, const unsigned int indentLevel) { Viewport::outStream(out, indentLevel); out << std::endl; const std::string indent_text(indentLevel, ' '); /* out << "LL: " << mLLCorner << ", LR: " << mLRCorner << ", UR: " << mURCorner << ", UL:" << mULCorner << std::endl; out << "surfRot: \n" << mSurfaceRotation << std::endl; */ if ( mView == vrj::Viewport::LEFT_EYE || mView == vrj::Viewport::STEREO ) { out << indent_text << "Left projection:\n"; mLeftProj->outStream(out, indentLevel + 2); out << std::endl; } if ( mView == vrj::Viewport::RIGHT_EYE || mView == vrj::Viewport::STEREO ) { out << indent_text << "Right projection:\n"; mRightProj->outStream(out, indentLevel + 2); out << std::endl; } return out; } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan, Sachin Chitta */ #include "ompl_interface/ompl_interface.h" #include <planning_models/conversions.h> #include <ompl/tools/debug/Profiler.h> ompl_interface::OMPLInterface::OMPLInterface(const planning_models::KinematicModelConstPtr &kmodel) : kmodel_(kmodel), context_manager_(kmodel), constraints_library_(context_manager_), use_constraints_approximations_(true) { } ompl_interface::OMPLInterface::~OMPLInterface(void) { } ompl_interface::ModelBasedPlanningContextPtr ompl_interface::OMPLInterface::prepareForSolve(const moveit_msgs::MotionPlanRequest &req, const planning_scene::PlanningSceneConstPtr& planning_scene, moveit_msgs::MoveItErrorCodes &error_code, unsigned int &attempts, double &timeout) const { ModelBasedPlanningContextPtr context = getPlanningContext(req); if (!context) { error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME; return context; } timeout = req.allowed_planning_time.toSec(); if (timeout <= 0.0) { error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ALLOWED_PLANNING_TIME; ROS_INFO("The timeout for planning must be positive (%lf specified). Assuming one second instead.", timeout); timeout = 1.0; } attempts = 1; if (req.num_planning_attempts > 0) attempts = req.num_planning_attempts; else if (req.num_planning_attempts < 0) ROS_ERROR("The number of desired planning attempts should be positive. Assuming one attempt."); if (context) { context->clear(); // get the starting state context->setPlanningScene(planning_scene); planning_models::KinematicState start_state = planning_scene->getCurrentState(); planning_models::robotStateToKinematicState(*planning_scene->getTransforms(), req.start_state, start_state); context->setStartState(start_state); context->setPlanningVolume(req.workspace_parameters); if (!context->setPathConstraints(req.path_constraints, &error_code)) return ModelBasedPlanningContextPtr(); if (!context->setGoalConstraints(req.goal_constraints, req.path_constraints, &error_code)) return ModelBasedPlanningContextPtr(); context->configure(); ROS_DEBUG("%s: New planning context is set.", context->getName().c_str()); error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; } return context; } bool ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res) const { ompl::tools::Profiler::ScopedStart pslv; ot::Profiler::ScopedBlock sblock("OMPLInterfaceSolve"); unsigned int attempts = 1; double timeout = 0.0; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, res.error_code, attempts, timeout); if (!context) return false; if (context->solve(timeout, attempts)) { double ptime = context->getLastPlanTime(); if (ptime < timeout) { context->simplifySolution(timeout - ptime); ptime += context->getLastSimplifyTime(); } context->interpolateSolution(); // fill the response ROS_DEBUG("%s: Returning successful solution with %lu states", context->getName().c_str(), context->getOMPLSimpleSetup().getSolutionPath().getStateCount()); pm::kinematicStateToRobotState(context->getCompleteInitialRobotState(), res.trajectory_start); res.planning_time = ros::Duration(ptime); context->getSolutionPath(res.trajectory); return true; } else { ROS_INFO("Unable to solve the planning problem"); return false; } } bool ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::MotionPlanDetailedResponse &res) const { ompl::tools::Profiler::ScopedStart pslv; ot::Profiler::ScopedBlock sblock("OMPLInterfaceSolve"); unsigned int attempts = 1; double timeout = 0.0; moveit_msgs::MoveItErrorCodes error_code; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, error_code, attempts, timeout); if (!context) return false; if (context->solve(timeout, attempts)) { res.trajectory.reserve(3); res.trajectory.resize(1); pm::kinematicStateToRobotState(context->getCompleteInitialRobotState(), res.trajectory_start); res.processing_time.push_back(ros::Duration(context->getLastPlanTime())); res.description.push_back("plan"); context->getSolutionPath(res.trajectory[0]); double ptime = context->getLastPlanTime(); if (ptime < timeout) { context->simplifySolution(timeout - ptime); res.trajectory.resize(2); res.processing_time.push_back(ros::Duration(context->getLastSimplifyTime())); res.description.push_back("simplify"); context->getSolutionPath(res.trajectory[1]); } ros::WallTime start_interpolate = ros::WallTime::now(); res.trajectory.resize(res.trajectory.size() + 1); context->interpolateSolution(); res.processing_time.push_back(ros::Duration((ros::WallTime::now() - start_interpolate).toSec())); res.description.push_back("interpolate"); context->getSolutionPath(res.trajectory.back()); // fill the response ROS_DEBUG("%s: Returning successful solution with %lu states", context->getName().c_str(), context->getOMPLSimpleSetup().getSolutionPath().getStateCount()); return true; } else { ROS_INFO("Unable to solve the planning problem"); return false; } } bool ompl_interface::OMPLInterface::benchmark(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res) const { unsigned int attempts = 1; double timeout = 0.0; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, res.error_code, attempts, timeout); if (!context) return false; return context->benchmark(timeout, std::max(1u, req.average_count), req.filename); } ompl::base::PathPtr ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const std::string &config, const planning_models::KinematicState &start_state, const moveit_msgs::Constraints &goal_constraints, double timeout, const std::string &factory_type) const { moveit_msgs::Constraints empty; return solve(planning_scene, config, start_state, goal_constraints, empty, timeout, factory_type); } ompl::base::PathPtr ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const std::string &config, const planning_models::KinematicState &start_state, const moveit_msgs::Constraints &goal_constraints, const moveit_msgs::Constraints &path_constraints, double timeout, const std::string &factory_type) const { ompl::tools::Profiler::ScopedStart pslv; ModelBasedPlanningContextPtr context = getPlanningContext(config, factory_type); if (!context) return ob::PathPtr(); std::vector<moveit_msgs::Constraints> goal_constraints_v(1, goal_constraints); context->setPlanningScene(planning_scene); context->setStartState(start_state); context->setPathConstraints(path_constraints, NULL); context->setGoalConstraints(goal_constraints_v, path_constraints, NULL); context->configure(); // solve the planning problem if (context->solve(timeout, 1)) { double ptime = context->getLastPlanTime(); if (ptime < timeout) context->simplifySolution(timeout - ptime); context->interpolateSolution(); return ob::PathPtr(new og::PathGeometric(context->getOMPLSimpleSetup().getSolutionPath())); } return ob::PathPtr(); } void ompl_interface::OMPLInterface::terminateSolve(void) { const ModelBasedPlanningContextPtr &context = getLastPlanningContext(); if (context) context->terminateSolve(); } <commit_msg>minor update needed for benchmark message change<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan, Sachin Chitta */ #include "ompl_interface/ompl_interface.h" #include <planning_models/conversions.h> #include <ompl/tools/debug/Profiler.h> ompl_interface::OMPLInterface::OMPLInterface(const planning_models::KinematicModelConstPtr &kmodel) : kmodel_(kmodel), context_manager_(kmodel), constraints_library_(context_manager_), use_constraints_approximations_(true) { } ompl_interface::OMPLInterface::~OMPLInterface(void) { } ompl_interface::ModelBasedPlanningContextPtr ompl_interface::OMPLInterface::prepareForSolve(const moveit_msgs::MotionPlanRequest &req, const planning_scene::PlanningSceneConstPtr& planning_scene, moveit_msgs::MoveItErrorCodes &error_code, unsigned int &attempts, double &timeout) const { ModelBasedPlanningContextPtr context = getPlanningContext(req); if (!context) { error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME; return context; } timeout = req.allowed_planning_time.toSec(); if (timeout <= 0.0) { error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_ALLOWED_PLANNING_TIME; ROS_INFO("The timeout for planning must be positive (%lf specified). Assuming one second instead.", timeout); timeout = 1.0; } attempts = 1; if (req.num_planning_attempts > 0) attempts = req.num_planning_attempts; else if (req.num_planning_attempts < 0) ROS_ERROR("The number of desired planning attempts should be positive. Assuming one attempt."); if (context) { context->clear(); // get the starting state context->setPlanningScene(planning_scene); planning_models::KinematicState start_state = planning_scene->getCurrentState(); planning_models::robotStateToKinematicState(*planning_scene->getTransforms(), req.start_state, start_state); context->setStartState(start_state); context->setPlanningVolume(req.workspace_parameters); if (!context->setPathConstraints(req.path_constraints, &error_code)) return ModelBasedPlanningContextPtr(); if (!context->setGoalConstraints(req.goal_constraints, req.path_constraints, &error_code)) return ModelBasedPlanningContextPtr(); context->configure(); ROS_DEBUG("%s: New planning context is set.", context->getName().c_str()); error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS; } return context; } bool ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res) const { ompl::tools::Profiler::ScopedStart pslv; ot::Profiler::ScopedBlock sblock("OMPLInterfaceSolve"); unsigned int attempts = 1; double timeout = 0.0; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, res.error_code, attempts, timeout); if (!context) return false; if (context->solve(timeout, attempts)) { double ptime = context->getLastPlanTime(); if (ptime < timeout) { context->simplifySolution(timeout - ptime); ptime += context->getLastSimplifyTime(); } context->interpolateSolution(); // fill the response ROS_DEBUG("%s: Returning successful solution with %lu states", context->getName().c_str(), context->getOMPLSimpleSetup().getSolutionPath().getStateCount()); pm::kinematicStateToRobotState(context->getCompleteInitialRobotState(), res.trajectory_start); res.planning_time = ros::Duration(ptime); context->getSolutionPath(res.trajectory); return true; } else { ROS_INFO("Unable to solve the planning problem"); return false; } } bool ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::MotionPlanDetailedResponse &res) const { ompl::tools::Profiler::ScopedStart pslv; ot::Profiler::ScopedBlock sblock("OMPLInterfaceSolve"); unsigned int attempts = 1; double timeout = 0.0; moveit_msgs::MoveItErrorCodes error_code; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, error_code, attempts, timeout); if (!context) return false; if (context->solve(timeout, attempts)) { res.trajectory.reserve(3); res.trajectory.resize(1); pm::kinematicStateToRobotState(context->getCompleteInitialRobotState(), res.trajectory_start); res.processing_time.push_back(ros::Duration(context->getLastPlanTime())); res.description.push_back("plan"); context->getSolutionPath(res.trajectory[0]); double ptime = context->getLastPlanTime(); if (ptime < timeout) { context->simplifySolution(timeout - ptime); res.trajectory.resize(2); res.processing_time.push_back(ros::Duration(context->getLastSimplifyTime())); res.description.push_back("simplify"); context->getSolutionPath(res.trajectory[1]); } ros::WallTime start_interpolate = ros::WallTime::now(); res.trajectory.resize(res.trajectory.size() + 1); context->interpolateSolution(); res.processing_time.push_back(ros::Duration((ros::WallTime::now() - start_interpolate).toSec())); res.description.push_back("interpolate"); context->getSolutionPath(res.trajectory.back()); // fill the response ROS_DEBUG("%s: Returning successful solution with %lu states", context->getName().c_str(), context->getOMPLSimpleSetup().getSolutionPath().getStateCount()); return true; } else { ROS_INFO("Unable to solve the planning problem"); return false; } } bool ompl_interface::OMPLInterface::benchmark(const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res) const { unsigned int attempts = 1; double timeout = 0.0; ModelBasedPlanningContextPtr context = prepareForSolve(req.motion_plan_request, planning_scene, res.error_code, attempts, timeout); if (!context) return false; return context->benchmark(timeout, attempts, req.filename); } ompl::base::PathPtr ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const std::string &config, const planning_models::KinematicState &start_state, const moveit_msgs::Constraints &goal_constraints, double timeout, const std::string &factory_type) const { moveit_msgs::Constraints empty; return solve(planning_scene, config, start_state, goal_constraints, empty, timeout, factory_type); } ompl::base::PathPtr ompl_interface::OMPLInterface::solve(const planning_scene::PlanningSceneConstPtr& planning_scene, const std::string &config, const planning_models::KinematicState &start_state, const moveit_msgs::Constraints &goal_constraints, const moveit_msgs::Constraints &path_constraints, double timeout, const std::string &factory_type) const { ompl::tools::Profiler::ScopedStart pslv; ModelBasedPlanningContextPtr context = getPlanningContext(config, factory_type); if (!context) return ob::PathPtr(); std::vector<moveit_msgs::Constraints> goal_constraints_v(1, goal_constraints); context->setPlanningScene(planning_scene); context->setStartState(start_state); context->setPathConstraints(path_constraints, NULL); context->setGoalConstraints(goal_constraints_v, path_constraints, NULL); context->configure(); // solve the planning problem if (context->solve(timeout, 1)) { double ptime = context->getLastPlanTime(); if (ptime < timeout) context->simplifySolution(timeout - ptime); context->interpolateSolution(); return ob::PathPtr(new og::PathGeometric(context->getOMPLSimpleSetup().getSolutionPath())); } return ob::PathPtr(); } void ompl_interface::OMPLInterface::terminateSolve(void) { const ModelBasedPlanningContextPtr &context = getLastPlanningContext(); if (context) context->terminateSolve(); } <|endoftext|>
<commit_before>/* * DynApproxBetweenness.cpp * * Created on: 31.07.2014 * Author: ebergamini */ #include "DynApproxBetweenness.h" #include "../auxiliary/Random.h" #include "../distance/Diameter.h" #include "../graph/Sampling.h" #include "../graph/DynDijkstra.h" #include "../graph/DynBFS.h" #include "../auxiliary/Log.h" #include "../auxiliary/NumericTools.h" namespace NetworKit { DynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true), storePreds(storePredecessors), epsilon(epsilon), delta(delta) { INFO("Constructing DynApproxBetweenness. storePredecessors = ", storePredecessors); } count DynApproxBetweenness::getNumberOfSamples() { return r; } void DynApproxBetweenness::run() { INFO("Inside DynApproxBetweenness. storePreds = ", storePreds); if (G.isDirected()) { throw std::runtime_error("Invalid argument: G must be undirected."); } scoreData.clear(); scoreData.resize(G.upperNodeIdBound()); u.clear(); v.clear(); sampledPaths.clear(); double c = 0.5; // universal positive constant - see reference in paper edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G); INFO("estimated diameter: ", vd); r = ceil((c / (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 / delta))); INFO("taking ", r, " path samples"); sssp.clear(); sssp.resize(r); u.resize(r); v.resize(r); sampledPaths.resize(r); for (count i = 0; i < r; i++) { DEBUG("sample ", i); // sample random node pair u[i] = Sampling::randomNode(G); do { v[i] = Sampling::randomNode(G); } while (v[i] == u[i]); if (G.isWeighted()) { INFO("Calling DynDijkstra inside run DynApproxBet"); sssp[i].reset(new DynDijkstra(G, u[i], storePreds)); } else { INFO("Calling DynBFS inside run DynApproxBet"); sssp[i].reset(new DynBFS(G, u[i], storePreds)); } DEBUG("running shortest path algorithm for node ", u[i]); INFO("Calling setTargetNodeon sssp instance inside run DynApproxBet"); sssp[i]->setTargetNode(v[i]); INFO("Calling run on sssp instance inside run DynApproxBet"); sssp[i]->run(); INFO("Ran sssp"); if (sssp[i]->distances[v[i]] > 0) { // at least one path between {u, v} exists DEBUG("updating estimate for path ", u[i], " <-> ", v[i]); INFO("Entered if statement."); // random path sampling and estimation update sampledPaths[i].clear(); node t = v[i]; while (t != u[i]) { INFO("Entered while statement"); // sample z in P_u(t) with probability sigma_uz / sigma_us std::vector<std::pair<node, double> > choices; if (storePreds) { for (node z : sssp[i]->previous[t]) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); // sigma_uz / sigma_us } } else { INFO("Storepreds is false"); G.forInEdgesOf(t, [&](node t, node z, edgeweight w){ if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) { // workaround for integer overflow in large graphs INFO("Calling number of paths"); bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); INFO("Called number of paths"); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } }); } INFO("Node considered: ", t); INFO("Source considered: ", u[i]); assert (choices.size() > 0); node z = Aux::Random::weightedChoice(choices); assert (z <= G.upperNodeIdBound()); if (z != u[i]) { scoreData[z] += 1 / (double) r; sampledPaths[i].push_back(z); } t = z; } } } hasRun = true; } void DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) { INFO ("Updating"); for (node i = 0; i < r; i++) { sssp[i]->update(batch); if (sssp[i]->modified()) { // subtract contributions to nodes in the old sampled path for (node z: sampledPaths[i]) { scoreData[z] -= 1 / (double) r; } // sample a new shortest path sampledPaths[i].clear(); node t = v[i]; while (t != u[i]) { // sample z in P_u(t) with probability sigma_uz / sigma_us std::vector<std::pair<node, double> > choices; if (storePreds) { for (node z : sssp[i]->previous[t]) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } } else { G.forInEdgesOf(t, [&](node t, node z, edgeweight w){ if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } }); } assert (choices.size() > 0); // this should fail only if the graph is not connected if (choices.size() == 0) { INFO ("node: ", t); INFO ("source: ", u[i]); INFO ("distance: ", sssp[i]->distances[t]); } node z = Aux::Random::weightedChoice(choices); assert (z <= G.upperNodeIdBound()); if (z != u[i]) { scoreData[z] += 1 / (double) r; sampledPaths[i].push_back(z); } t = z; } } } } } /* namespace NetworKit */ <commit_msg>Correct computation of sample size. While here, const'ify a constant.<commit_after>/* * DynApproxBetweenness.cpp * * Created on: 31.07.2014 * Author: ebergamini */ #include "DynApproxBetweenness.h" #include "../auxiliary/Random.h" #include "../distance/Diameter.h" #include "../graph/Sampling.h" #include "../graph/DynDijkstra.h" #include "../graph/DynBFS.h" #include "../auxiliary/Log.h" #include "../auxiliary/NumericTools.h" namespace NetworKit { DynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true), storePreds(storePredecessors), epsilon(epsilon), delta(delta) { INFO("Constructing DynApproxBetweenness. storePredecessors = ", storePredecessors); } count DynApproxBetweenness::getNumberOfSamples() { return r; } void DynApproxBetweenness::run() { INFO("Inside DynApproxBetweenness. storePreds = ", storePreds); if (G.isDirected()) { throw std::runtime_error("Invalid argument: G must be undirected."); } scoreData.clear(); scoreData.resize(G.upperNodeIdBound()); u.clear(); v.clear(); sampledPaths.clear(); const double c = 0.5; // universal positive constant - see reference in paper edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G); INFO("estimated diameter: ", vd); r = ceil((c / (epsilon * epsilon)) * (floor(log2(vd - 2)) + 1 - log(delta))); INFO("taking ", r, " path samples"); sssp.clear(); sssp.resize(r); u.resize(r); v.resize(r); sampledPaths.resize(r); for (count i = 0; i < r; i++) { DEBUG("sample ", i); // sample random node pair u[i] = Sampling::randomNode(G); do { v[i] = Sampling::randomNode(G); } while (v[i] == u[i]); if (G.isWeighted()) { INFO("Calling DynDijkstra inside run DynApproxBet"); sssp[i].reset(new DynDijkstra(G, u[i], storePreds)); } else { INFO("Calling DynBFS inside run DynApproxBet"); sssp[i].reset(new DynBFS(G, u[i], storePreds)); } DEBUG("running shortest path algorithm for node ", u[i]); INFO("Calling setTargetNodeon sssp instance inside run DynApproxBet"); sssp[i]->setTargetNode(v[i]); INFO("Calling run on sssp instance inside run DynApproxBet"); sssp[i]->run(); INFO("Ran sssp"); if (sssp[i]->distances[v[i]] > 0) { // at least one path between {u, v} exists DEBUG("updating estimate for path ", u[i], " <-> ", v[i]); INFO("Entered if statement."); // random path sampling and estimation update sampledPaths[i].clear(); node t = v[i]; while (t != u[i]) { INFO("Entered while statement"); // sample z in P_u(t) with probability sigma_uz / sigma_us std::vector<std::pair<node, double> > choices; if (storePreds) { for (node z : sssp[i]->previous[t]) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); // sigma_uz / sigma_us } } else { INFO("Storepreds is false"); G.forInEdgesOf(t, [&](node t, node z, edgeweight w){ if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) { // workaround for integer overflow in large graphs INFO("Calling number of paths"); bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); INFO("Called number of paths"); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } }); } INFO("Node considered: ", t); INFO("Source considered: ", u[i]); assert (choices.size() > 0); node z = Aux::Random::weightedChoice(choices); assert (z <= G.upperNodeIdBound()); if (z != u[i]) { scoreData[z] += 1 / (double) r; sampledPaths[i].push_back(z); } t = z; } } } hasRun = true; } void DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) { INFO ("Updating"); for (node i = 0; i < r; i++) { sssp[i]->update(batch); if (sssp[i]->modified()) { // subtract contributions to nodes in the old sampled path for (node z: sampledPaths[i]) { scoreData[z] -= 1 / (double) r; } // sample a new shortest path sampledPaths[i].clear(); node t = v[i]; while (t != u[i]) { // sample z in P_u(t) with probability sigma_uz / sigma_us std::vector<std::pair<node, double> > choices; if (storePreds) { for (node z : sssp[i]->previous[t]) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } } else { G.forInEdgesOf(t, [&](node t, node z, edgeweight w){ if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) { // workaround for integer overflow in large graphs bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t); double weight; tmp.ToDouble(weight); choices.emplace_back(z, weight); } }); } assert (choices.size() > 0); // this should fail only if the graph is not connected if (choices.size() == 0) { INFO ("node: ", t); INFO ("source: ", u[i]); INFO ("distance: ", sssp[i]->distances[t]); } node z = Aux::Random::weightedChoice(choices); assert (z <= G.upperNodeIdBound()); if (z != u[i]) { scoreData[z] += 1 / (double) r; sampledPaths[i].push_back(z); } t = z; } } } } } /* namespace NetworKit */ <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include "curl_downloader.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "common/logging.h" #include "common/asm_atomic.h" extern "C" { #include "curl/curl.h" } extern int FLAGS_agent_curl_recv_buffer_size; static pthread_once_t once_control = PTHREAD_ONCE_INIT; // destroy func process level static void GlobalDestroy() { curl_global_cleanup(); } // init func process level static void GlobalInit() { curl_global_init(CURL_GLOBAL_ALL); ::atexit(GlobalDestroy); } namespace galaxy { static int OPEN_FLAGS = O_CREAT | O_WRONLY; static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO; CurlDownloader::CurlDownloader() : recv_buffer_size_(0), used_length_(0), recv_buffer_(NULL), output_fd_(-1), stoped_(0) { if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) { recv_buffer_size_ = 16 * 1024; } else { recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size; } recv_buffer_ = new char[recv_buffer_size_]; pthread_once(&once_control, GlobalInit); } CurlDownloader::~CurlDownloader() { if (recv_buffer_) { delete recv_buffer_; recv_buffer_ = NULL; } } void CurlDownloader::Stop() { common::atomic_swap(&stoped_, 1); } size_t CurlDownloader::RecvTrunkData(char* ptr, size_t size, size_t nmemb, void* user_data) { CurlDownloader* downloader = static_cast<CurlDownloader*>(user_data); assert(downloader); if (common::atomic_add_ret_old(&downloader->stoped_, 0) == 1) { return 0; } if (size * nmemb <= 0) { return size * nmemb; } if (downloader->used_length_ == downloader->recv_buffer_size_ || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) { // flush to disk if (write(downloader->output_fd_, downloader->recv_buffer_, downloader->used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); return 0; } LOG(INFO, "write file %d", downloader->used_length_); downloader->used_length_ = 0; } memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb); downloader->used_length_ += size * nmemb; return size * nmemb; } int CurlDownloader::Fetch(const std::string& uri, const std::string& path) { output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE); if (output_fd_ == -1) { LOG(WARNING, "open file failed %s err[%d: %s]", path.c_str(), errno, strerror(errno)); return -1; } LOG(INFO, "start to curl data %s", uri.c_str()); CURL* curl = curl_easy_init(); int ret; do { ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str()); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_perform(curl); if (ret != CURLE_OK) { LOG(WARNING, "libcurl perform failed [%d: %s]", ret, curl_easy_strerror((CURLcode)ret)); break; } if (used_length_ != 0) { if (write(output_fd_, recv_buffer_, used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); ret = -1; break; } LOG(INFO, "write file %d", used_length_); used_length_ = 0; } } while(0); if (curl != NULL) { curl_easy_cleanup(curl); } if (ret != CURLE_OK) { return -1; } return 0; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <commit_msg>remove atomic<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include "curl_downloader.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "common/logging.h" extern "C" { #include "curl/curl.h" } extern int FLAGS_agent_curl_recv_buffer_size; static pthread_once_t once_control = PTHREAD_ONCE_INIT; // destroy func process level static void GlobalDestroy() { curl_global_cleanup(); } // init func process level static void GlobalInit() { curl_global_init(CURL_GLOBAL_ALL); ::atexit(GlobalDestroy); } namespace galaxy { static int OPEN_FLAGS = O_CREAT | O_WRONLY; static int OPEN_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IRWXO; CurlDownloader::CurlDownloader() : recv_buffer_size_(0), used_length_(0), recv_buffer_(NULL), output_fd_(-1), stoped_(0) { if (FLAGS_agent_curl_recv_buffer_size <= 16 * 1024) { recv_buffer_size_ = 16 * 1024; } else { recv_buffer_size_ = FLAGS_agent_curl_recv_buffer_size; } recv_buffer_ = new char[recv_buffer_size_]; pthread_once(&once_control, GlobalInit); } CurlDownloader::~CurlDownloader() { if (recv_buffer_) { delete recv_buffer_; recv_buffer_ = NULL; } } void CurlDownloader::Stop() { stoped_ = 1; } size_t CurlDownloader::RecvTrunkData(char* ptr, size_t size, size_t nmemb, void* user_data) { CurlDownloader* downloader = static_cast<CurlDownloader*>(user_data); assert(downloader); if (stoped_ == 1) { return 0; } if (size * nmemb <= 0) { return size * nmemb; } if (downloader->used_length_ == downloader->recv_buffer_size_ || size * nmemb > static_cast<size_t>(downloader->recv_buffer_size_ - downloader->used_length_)) { // flush to disk if (write(downloader->output_fd_, downloader->recv_buffer_, downloader->used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); return 0; } LOG(INFO, "write file %d", downloader->used_length_); downloader->used_length_ = 0; } memcpy(downloader->recv_buffer_ + downloader->used_length_, ptr, size * nmemb); downloader->used_length_ += size * nmemb; return size * nmemb; } int CurlDownloader::Fetch(const std::string& uri, const std::string& path) { output_fd_ = open(path.c_str(), OPEN_FLAGS, OPEN_MODE); if (output_fd_ == -1) { LOG(WARNING, "open file failed %s err[%d: %s]", path.c_str(), errno, strerror(errno)); return -1; } LOG(INFO, "start to curl data %s", uri.c_str()); CURL* curl = curl_easy_init(); int ret; do { ret = curl_easy_setopt(curl, CURLOPT_URL, uri.c_str()); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_URL", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEDATA", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlDownloader::RecvTrunkData); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_WRITEFUNCTION", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); if (ret != CURLE_OK) { LOG(WARNING, "libcurl setopt %s failed [%d: %s]", "CURLOPT_VERBOSE", ret, curl_easy_strerror((CURLcode)ret)); break; } ret = curl_easy_perform(curl); if (ret != CURLE_OK) { LOG(WARNING, "libcurl perform failed [%d: %s]", ret, curl_easy_strerror((CURLcode)ret)); break; } if (used_length_ != 0) { if (write(output_fd_, recv_buffer_, used_length_) == -1) { LOG(WARNING, "write file failed [%d: %s]", errno, strerror(errno)); ret = -1; break; } LOG(INFO, "write file %d", used_length_); used_length_ = 0; } } while(0); if (curl != NULL) { curl_easy_cleanup(curl); } if (ret != CURLE_OK) { return -1; } return 0; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <|endoftext|>
<commit_before>/* dstar_from_grid.cpp */ #ifdef MACOS #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #endif #include <stdlib.h> #include <unistd.h> #include "dstar.h" namespace dstar { class DstarInterface () { }; } // End dstar namespace. int hh, ww; int window; Dstar *dstar; int scale = 6; int mbutton = 0; int mstate = 0; bool b_autoreplan = true; void InitGL(int Width, int Height) { hh = Height; ww = Width; glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void ReSizeGLScene(int Width, int Height) { hh = Height; ww = Width; glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void DrawGLScene() { usleep(100); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); glPushMatrix(); glScaled(scale,scale,1); if (b_autoreplan) dstar->replan(); dstar->draw(); glPopMatrix(); glutSwapBuffers(); } void keyPressed(unsigned char key, int x, int y) { usleep(100); switch(key) { case 'q': case 'Q': glutDestroyWindow(window); exit(0); break; case 'r': case 'R': dstar->replan(); break; case 'a': case 'A': b_autoreplan = !b_autoreplan; break; case 'c': case 'C': dstar->init(40,50,140, 90); break; } } void mouseFunc(int button, int state, int x, int y) { y = hh -y+scale/2; x += scale/2; mbutton = button; if ((mstate = state) == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { dstar->updateCell(x/scale, y/scale, -1); } else if (button == GLUT_RIGHT_BUTTON) { dstar->updateStart(x/scale, y/scale); } else if (button == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x/scale, y/scale); } } } void mouseMotionFunc(int x, int y) { y = hh -y+scale/2; x += scale/2; y /= scale; x /= scale; if (mstate == GLUT_DOWN) { if (mbutton == GLUT_LEFT_BUTTON) { dstar->updateCell(x, y, -1); } else if (mbutton == GLUT_RIGHT_BUTTON) { dstar->updateStart(x, y); } else if (mbutton == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x, y); } } } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(1000, 800); glutInitWindowPosition(50, 20); window = glutCreateWindow("Dstar Visualizer"); glutDisplayFunc(&DrawGLScene); glutIdleFunc(&DrawGLScene); glutReshapeFunc(&ReSizeGLScene); glutKeyboardFunc(&keyPressed); glutMouseFunc(&mouseFunc); glutMotionFunc(&mouseMotionFunc); InitGL(800, 600); dstar = new Dstar(); dstar->init(40,50,140, 90); printf("----------------------------------\n"); printf("Dstar Visualizer\n"); printf("Commands:\n"); printf("[q/Q] - Quit\n"); printf("[r/R] - Replan\n"); printf("[a/A] - Toggle Auto Replan\n"); printf("[c/C] - Clear (restart)\n"); printf("left mouse click - make cell untraversable (cost -1)\n"); printf("middle mouse click - move goal to cell\n"); printf("right mouse click - move start to cell\n"); printf("----------------------------------\n"); glutMainLoop(); return 1; } <commit_msg>First iteration of dstar_from_grid.cpp<commit_after>/* dstar_from_grid.cpp */ #ifdef MACOS #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #include <GL/gl.h> #include <GL/glu.h> #endif #include <stdlib.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <unistd.h> #include "dstar_lite/dstar.h" int hh, ww; int window; Dstar *dstar; int scale = 50; int mbutton = 0; int mstate = 0; bool b_autoreplan = false; void InitGL(int Width, int Height) { hh = Height; ww = Width; glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void ReSizeGLScene(int Width, int Height) { hh = Height; ww = Width; glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,Width,0,Height,-100,100); glMatrixMode(GL_MODELVIEW); } void DrawGLScene() { usleep(100); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glLoadIdentity(); glPushMatrix(); glScaled(scale,scale,1); if (b_autoreplan) dstar->replan(); dstar->draw(); glPopMatrix(); glutSwapBuffers(); } void keyPressed(unsigned char key, int x, int y) { usleep(100); switch(key) { case 'q': case 'Q': glutDestroyWindow(window); exit(0); break; case 'r': case 'R': dstar->replan(); break; case 'a': case 'A': b_autoreplan = !b_autoreplan; break; case 'c': case 'C': dstar->init(1, 1, 3, 3); break; } } void mouseFunc(int button, int state, int x, int y) { y = hh -y+scale/2; x += scale/2; mbutton = button; if ((mstate = state) == GLUT_DOWN) { if (button == GLUT_LEFT_BUTTON) { dstar->updateCell(x/scale, y/scale, -1); } else if (button == GLUT_RIGHT_BUTTON) { dstar->updateStart(x/scale, y/scale); } else if (button == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x/scale, y/scale); } } } void mouseMotionFunc(int x, int y) { y = hh -y+scale/2; x += scale/2; y /= scale; x /= scale; if (mstate == GLUT_DOWN) { if (mbutton == GLUT_LEFT_BUTTON) { dstar->updateCell(x, y, -1); } else if (mbutton == GLUT_RIGHT_BUTTON) { dstar->updateStart(x, y); } else if (mbutton == GLUT_MIDDLE_BUTTON) { dstar->updateGoal(x, y); } } } int main(int argc, char **argv) { // Init GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); // Parse csv file with world grids. // Currently only loads the first grid in the csv file... ifstream file("../resources/gridworld_8.csv"); std::vector<string> value; string tmp; if (file.is_open()) { while (getline(file, tmp)) { value.push_back(tmp); } file.close(); } else { cout << "Could not open the csv file." << endl; } // Construct a grid. const uint grid_size = (uint)std::sqrt(value.size()); std::vector<std::vector<int>> occupancy_grid (grid_size, vector<int>(grid_size)); uint i = 0; uint j = 0; bool first = true; // Reshape input to a grid with x, y coordinates for (uint k = 0; k < value.size(); k++) { j = k % ((uint)std::sqrt(value.size())); // Check that we are not out of bounds. if ( i < grid_size && j < grid_size) { occupancy_grid[i][j] = std::atoi(&value.at(k).at(0)); } else { cerr << "Index out of bounds, check that input grid is squared." << endl; } if (j == 0) { if (first) { first = false; } else { i++; } } } // Initialize window for visualization. glutInitWindowSize(500, 500); glutInitWindowPosition(20, 20); window = glutCreateWindow("Dstar Visualizer"); glutDisplayFunc(&DrawGLScene); glutIdleFunc(&DrawGLScene); glutReshapeFunc(&ReSizeGLScene); glutKeyboardFunc(&keyPressed); glutMouseFunc(&mouseFunc); glutMotionFunc(&mouseMotionFunc); InitGL(30, 20); dstar = new Dstar(); dstar->init(3, 2, 6, 6); for (uint i = 0; i < occupancy_grid.size(); i++) { for (uint j = 0; j < occupancy_grid.at(i).size(); j++) { std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n'; if (occupancy_grid.at(i).at(j) == 1) { dstar->updateCell(i+1, j+1, -1); } } } dstar->draw(); printf("----------------------------------\n"); printf("Dstar Visualizer\n"); printf("Commands:\n"); printf("[q/Q] - Quit\n"); printf("[r/R] - Replan\n"); printf("[a/A] - Toggle Auto Replan\n"); printf("[c/C] - Clear (restart)\n"); printf("left mouse click - make cell untraversable (cost -1)\n"); printf("middle mouse click - move goal to cell\n"); printf("right mouse click - move start to cell\n"); printf("----------------------------------\n"); glutMainLoop(); return 1; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mcnttype.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: tra $ $Date: 2001-02-26 06:59:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _MCNTTYPE_HXX_ #include "mcnttype.hxx" #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace rtl; using namespace std; using namespace osl; //------------------------------------------------------------------------ // constants //------------------------------------------------------------------------ const OUString TSPECIALS = OUString::createFromAscii( "()<>@,;:\\\"/[]?=" ); const OUString TOKEN = OUString::createFromAscii( "!#$%&'*+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~." ); const OUString SPACE = OUString::createFromAscii( " " ); const OUString SEMICOLON = OUString::createFromAscii( ";" ); //------------------------------------------------------------------------ // ctor //------------------------------------------------------------------------ CMimeContentType::CMimeContentType( const OUString& aCntType ) { init( aCntType ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getMediaType( ) throw(RuntimeException) { return m_MediaType; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getMediaSubtype( ) throw(RuntimeException) { return m_MediaSubtype; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getFullMediaType( ) throw(RuntimeException) { return m_MediaType + OUString::createFromAscii( "/" ) + m_MediaSubtype; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ Sequence< OUString > SAL_CALL CMimeContentType::getParameters( ) throw(RuntimeException) { MutexGuard aGuard( m_aMutex ); Sequence< OUString > seqParams; map< OUString, OUString >::iterator iter; map< OUString, OUString >::iterator iter_end = m_ParameterMap.end( ); for ( iter = m_ParameterMap.begin( ); iter != iter_end; ++iter ) { seqParams.realloc( seqParams.getLength( ) + 1 ); seqParams[seqParams.getLength( ) - 1] = iter->first; } return seqParams; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CMimeContentType::hasParameter( const OUString& aName ) throw(RuntimeException) { MutexGuard aGuard( m_aMutex ); return ( m_ParameterMap.end( ) != m_ParameterMap.find( aName ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getParameterValue( const OUString& aName ) throw(NoSuchElementException, RuntimeException) { MutexGuard aGuard( m_aMutex ); if ( !hasParameter( aName ) ) throw NoSuchElementException( ); return m_ParameterMap.find( aName )->second; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::init( const OUString& aCntType ) throw( IllegalArgumentException ) { if ( !aCntType.getLength( ) ) throw IllegalArgumentException( ); m_nPos = 0; m_ContentType = aCntType; getSym( ); type(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::getSym( void ) { if ( m_nPos < m_ContentType.getLength( ) ) { m_nxtSym = OUString( &m_ContentType[m_nPos], 1 ); ++m_nPos; return; } m_nxtSym = OUString( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::acceptSym( const OUString& pSymTlb ) { if ( pSymTlb.indexOf( m_nxtSym ) < 0 ) throw IllegalArgumentException( ); getSym(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::skipSpaces( void ) { while ( SPACE == m_nxtSym ) getSym( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::type( void ) { skipSpaces( ); // check FIRST( type ) if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); // parse while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) m_MediaType += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "/ " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } // check FOLLOW( type ) skipSpaces( ); acceptSym( OUString::createFromAscii( "/" ) ); subtype( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::subtype( void ) { skipSpaces( ); // check FIRST( subtype ) if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) m_MediaSubtype += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } // parse the rest skipSpaces( ); trailer(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::trailer( void ) { while( m_nxtSym.getLength( ) ) { if ( m_nxtSym == OUString::createFromAscii( "(" ) ) { getSym( ); comment( ); acceptSym( OUString::createFromAscii( ")" ) ); } else if ( m_nxtSym == OUString::createFromAscii( ";" ) ) { // get the parameter name getSym( ); skipSpaces( ); if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); OUString pname = pName( ); skipSpaces(); acceptSym( OUString::createFromAscii( "=" ) ); // get the parameter value skipSpaces( ); OUString pvalue = pValue( ); // insert into map if ( !m_ParameterMap.insert( pair < const OUString, OUString > ( pname, pvalue ) ).second ) throw IllegalArgumentException( ); } else throw IllegalArgumentException( ); skipSpaces( ); } } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::pName( ) { OUString pname; while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) pname += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "= " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } return pname; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::pValue( ) { OUString pvalue; // quoted pvalue if ( m_nxtSym == OUString::createFromAscii( "\"" ) ) { getSym( ); pvalue = quotedPValue( ); if ( OUString( &pvalue[pvalue.getLength() - 1], 1 ) != OUString::createFromAscii( "\"" ) ) throw IllegalArgumentException( ); // remove the last quote-sign OUString qpvalue( pvalue, pvalue.getLength( ) - 1 ); pvalue = qpvalue; if ( !pvalue.getLength( ) ) throw IllegalArgumentException( ); } else if ( isInRange( m_nxtSym, TOKEN ) ) // unquoted pvalue { pvalue = nonquotedPValue( ); } else throw IllegalArgumentException( ); return pvalue; } //------------------------------------------------------------------------ // the following combinations within a quoted value are not allowed: // '";' (quote sign followed by semicolon) and '" ' (quote sign followed // by space) //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::quotedPValue( ) { OUString pvalue; sal_Bool bAfterQuoteSign = sal_False; while ( m_nxtSym.getLength( ) ) { if ( bAfterQuoteSign && ((m_nxtSym == SPACE)||(m_nxtSym == SEMICOLON) ) ) break; else if ( isInRange( m_nxtSym, TOKEN + TSPECIALS + SPACE ) ) { pvalue += m_nxtSym; if ( m_nxtSym == OUString::createFromAscii( "\"" ) ) bAfterQuoteSign = sal_True; else bAfterQuoteSign = sal_False; } else throw IllegalArgumentException( ); getSym( ); } return pvalue; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::nonquotedPValue( ) { OUString pvalue; while ( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) pvalue += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } return pvalue; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::comment( void ) { while ( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN + SPACE ) ) getSym( ); else if ( m_nxtSym == OUString::createFromAscii( ")" ) ) break; else throw IllegalArgumentException( ); } } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CMimeContentType::isInRange( const rtl::OUString& aChr, const rtl::OUString& aRange ) { return ( aRange.indexOf( aChr ) > -1 ); }<commit_msg>INTEGRATION: CWS rt02 (1.4.102); FILE MERGED 2003/10/01 12:05:56 rt 1.4.102.1: #i19697# No newline at end of file<commit_after>/************************************************************************* * * $RCSfile: mcnttype.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-10-06 14:36:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _MCNTTYPE_HXX_ #include "mcnttype.hxx" #endif //------------------------------------------------------------------------ // namespace directives //------------------------------------------------------------------------ using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace rtl; using namespace std; using namespace osl; //------------------------------------------------------------------------ // constants //------------------------------------------------------------------------ const OUString TSPECIALS = OUString::createFromAscii( "()<>@,;:\\\"/[]?=" ); const OUString TOKEN = OUString::createFromAscii( "!#$%&'*+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~." ); const OUString SPACE = OUString::createFromAscii( " " ); const OUString SEMICOLON = OUString::createFromAscii( ";" ); //------------------------------------------------------------------------ // ctor //------------------------------------------------------------------------ CMimeContentType::CMimeContentType( const OUString& aCntType ) { init( aCntType ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getMediaType( ) throw(RuntimeException) { return m_MediaType; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getMediaSubtype( ) throw(RuntimeException) { return m_MediaSubtype; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getFullMediaType( ) throw(RuntimeException) { return m_MediaType + OUString::createFromAscii( "/" ) + m_MediaSubtype; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ Sequence< OUString > SAL_CALL CMimeContentType::getParameters( ) throw(RuntimeException) { MutexGuard aGuard( m_aMutex ); Sequence< OUString > seqParams; map< OUString, OUString >::iterator iter; map< OUString, OUString >::iterator iter_end = m_ParameterMap.end( ); for ( iter = m_ParameterMap.begin( ); iter != iter_end; ++iter ) { seqParams.realloc( seqParams.getLength( ) + 1 ); seqParams[seqParams.getLength( ) - 1] = iter->first; } return seqParams; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CMimeContentType::hasParameter( const OUString& aName ) throw(RuntimeException) { MutexGuard aGuard( m_aMutex ); return ( m_ParameterMap.end( ) != m_ParameterMap.find( aName ) ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::getParameterValue( const OUString& aName ) throw(NoSuchElementException, RuntimeException) { MutexGuard aGuard( m_aMutex ); if ( !hasParameter( aName ) ) throw NoSuchElementException( ); return m_ParameterMap.find( aName )->second; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::init( const OUString& aCntType ) throw( IllegalArgumentException ) { if ( !aCntType.getLength( ) ) throw IllegalArgumentException( ); m_nPos = 0; m_ContentType = aCntType; getSym( ); type(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::getSym( void ) { if ( m_nPos < m_ContentType.getLength( ) ) { m_nxtSym = OUString( &m_ContentType[m_nPos], 1 ); ++m_nPos; return; } m_nxtSym = OUString( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::acceptSym( const OUString& pSymTlb ) { if ( pSymTlb.indexOf( m_nxtSym ) < 0 ) throw IllegalArgumentException( ); getSym(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::skipSpaces( void ) { while ( SPACE == m_nxtSym ) getSym( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::type( void ) { skipSpaces( ); // check FIRST( type ) if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); // parse while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) m_MediaType += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "/ " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } // check FOLLOW( type ) skipSpaces( ); acceptSym( OUString::createFromAscii( "/" ) ); subtype( ); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::subtype( void ) { skipSpaces( ); // check FIRST( subtype ) if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) m_MediaSubtype += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } // parse the rest skipSpaces( ); trailer(); } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::trailer( void ) { while( m_nxtSym.getLength( ) ) { if ( m_nxtSym == OUString::createFromAscii( "(" ) ) { getSym( ); comment( ); acceptSym( OUString::createFromAscii( ")" ) ); } else if ( m_nxtSym == OUString::createFromAscii( ";" ) ) { // get the parameter name getSym( ); skipSpaces( ); if ( !isInRange( m_nxtSym, TOKEN ) ) throw IllegalArgumentException( ); OUString pname = pName( ); skipSpaces(); acceptSym( OUString::createFromAscii( "=" ) ); // get the parameter value skipSpaces( ); OUString pvalue = pValue( ); // insert into map if ( !m_ParameterMap.insert( pair < const OUString, OUString > ( pname, pvalue ) ).second ) throw IllegalArgumentException( ); } else throw IllegalArgumentException( ); skipSpaces( ); } } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::pName( ) { OUString pname; while( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) pname += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "= " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } return pname; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::pValue( ) { OUString pvalue; // quoted pvalue if ( m_nxtSym == OUString::createFromAscii( "\"" ) ) { getSym( ); pvalue = quotedPValue( ); if ( OUString( &pvalue[pvalue.getLength() - 1], 1 ) != OUString::createFromAscii( "\"" ) ) throw IllegalArgumentException( ); // remove the last quote-sign OUString qpvalue( pvalue, pvalue.getLength( ) - 1 ); pvalue = qpvalue; if ( !pvalue.getLength( ) ) throw IllegalArgumentException( ); } else if ( isInRange( m_nxtSym, TOKEN ) ) // unquoted pvalue { pvalue = nonquotedPValue( ); } else throw IllegalArgumentException( ); return pvalue; } //------------------------------------------------------------------------ // the following combinations within a quoted value are not allowed: // '";' (quote sign followed by semicolon) and '" ' (quote sign followed // by space) //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::quotedPValue( ) { OUString pvalue; sal_Bool bAfterQuoteSign = sal_False; while ( m_nxtSym.getLength( ) ) { if ( bAfterQuoteSign && ((m_nxtSym == SPACE)||(m_nxtSym == SEMICOLON) ) ) break; else if ( isInRange( m_nxtSym, TOKEN + TSPECIALS + SPACE ) ) { pvalue += m_nxtSym; if ( m_nxtSym == OUString::createFromAscii( "\"" ) ) bAfterQuoteSign = sal_True; else bAfterQuoteSign = sal_False; } else throw IllegalArgumentException( ); getSym( ); } return pvalue; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ OUString SAL_CALL CMimeContentType::nonquotedPValue( ) { OUString pvalue; while ( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN ) ) pvalue += m_nxtSym; else if ( isInRange( m_nxtSym, OUString::createFromAscii( "; " ) ) ) break; else throw IllegalArgumentException( ); getSym( ); } return pvalue; } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ void SAL_CALL CMimeContentType::comment( void ) { while ( m_nxtSym.getLength( ) ) { if ( isInRange( m_nxtSym, TOKEN + SPACE ) ) getSym( ); else if ( m_nxtSym == OUString::createFromAscii( ")" ) ) break; else throw IllegalArgumentException( ); } } //------------------------------------------------------------------------ // //------------------------------------------------------------------------ sal_Bool SAL_CALL CMimeContentType::isInRange( const rtl::OUString& aChr, const rtl::OUString& aRange ) { return ( aRange.indexOf( aChr ) > -1 ); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdexcept> #include <dlfcn.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <QMenu> #include <QAction> #include <QKeyEvent> #include <QHBoxLayout> #include <dependency_graph/graph.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/datablock.inl> #include <dependency_graph/metadata.inl> #include <dependency_graph/attr.inl> #include <qt_node_editor/node.h> #include <qt_node_editor/connected_edge.h> #include <qt_node_editor/graph_widget.h> #include <possumwood_sdk/app.h> #include <possumwood_sdk/gl.h> #include "adaptor.h" #include "main_window.h" #include "gl_init.h" namespace po = boost::program_options; namespace fs = boost::filesystem; using std::cout; using std::endl; using std::flush; #ifndef PLUGIN_DIR #define PLUGIN_DIR "./plugins" #endif int main(int argc, char* argv[]) { // // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("plugin_directory", po::value<std::string>()->default_value(PLUGIN_DIR), "directory to search for plugins") ("scene", po::value<std::string>(), "open a scene file") ; // process the options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << "\n"; return 1; } /////////////////////////////// std::vector<void*> pluginHandles; // scan for plugins for(fs::directory_iterator itr(vm["plugin_directory"].as<std::string>()); itr != fs::directory_iterator(); ++itr) { if(fs::is_regular_file(itr->status()) && itr->path().extension() == ".so") { void* ptr = dlopen(itr->path().string().c_str(), RTLD_NOW); if(ptr) pluginHandles.push_back(ptr); else std::cout << dlerror() << std::endl; } } /////////////////////////////// { GL_CHECK_ERR; { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); // way higher than currently supported - will fall back to highest format.setVersion(6, 0); format.setProfile(QSurfaceFormat::CoreProfile); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); } // create the application object QApplication app(argc, argv); GL_CHECK_ERR; // create the possumwood application possumwood::App papp; GL_CHECK_ERR; // make a main window MainWindow win; win.setWindowIcon(QIcon(":icons/app.png")); win.showMaximized(); GL_CHECK_ERR; std::cout << "OpenGL version supported by this platform is " << glGetString(GL_VERSION) << std::endl; GL_CHECK_ERR; // open the scene file, if specified on the command line if(vm.count("scene")) possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>())); GL_CHECK_ERR; // and start the main application loop app.exec(); GL_CHECK_ERR; } //////////////////////////////// // unload all plugins while(!pluginHandles.empty()) { dlclose(pluginHandles.back()); pluginHandles.pop_back(); } return 0; } <commit_msg>Fixed HighDPI icons throughout the application (yay!)<commit_after>#include <iostream> #include <string> #include <stdexcept> #include <dlfcn.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <QApplication> #include <QMainWindow> #include <QMenu> #include <QAction> #include <QKeyEvent> #include <QHBoxLayout> #include <dependency_graph/graph.h> #include <dependency_graph/node_base.inl> #include <dependency_graph/datablock.inl> #include <dependency_graph/metadata.inl> #include <dependency_graph/attr.inl> #include <qt_node_editor/node.h> #include <qt_node_editor/connected_edge.h> #include <qt_node_editor/graph_widget.h> #include <possumwood_sdk/app.h> #include <possumwood_sdk/gl.h> #include "adaptor.h" #include "main_window.h" #include "gl_init.h" namespace po = boost::program_options; namespace fs = boost::filesystem; using std::cout; using std::endl; using std::flush; #ifndef PLUGIN_DIR #define PLUGIN_DIR "./plugins" #endif int main(int argc, char* argv[]) { // // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("plugin_directory", po::value<std::string>()->default_value(PLUGIN_DIR), "directory to search for plugins") ("scene", po::value<std::string>(), "open a scene file") ; // process the options po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { cout << desc << "\n"; return 1; } /////////////////////////////// std::vector<void*> pluginHandles; // scan for plugins for(fs::directory_iterator itr(vm["plugin_directory"].as<std::string>()); itr != fs::directory_iterator(); ++itr) { if(fs::is_regular_file(itr->status()) && itr->path().extension() == ".so") { void* ptr = dlopen(itr->path().string().c_str(), RTLD_NOW); if(ptr) pluginHandles.push_back(ptr); else std::cout << dlerror() << std::endl; } } /////////////////////////////// { GL_CHECK_ERR; { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); // way higher than currently supported - will fall back to highest format.setVersion(6, 0); format.setProfile(QSurfaceFormat::CoreProfile); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); } // create the application object QApplication app(argc, argv); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); GL_CHECK_ERR; // create the possumwood application possumwood::App papp; GL_CHECK_ERR; // make a main window MainWindow win; win.setWindowIcon(QIcon(":icons/app.png")); win.showMaximized(); GL_CHECK_ERR; std::cout << "OpenGL version supported by this platform is " << glGetString(GL_VERSION) << std::endl; GL_CHECK_ERR; // open the scene file, if specified on the command line if(vm.count("scene")) possumwood::App::instance().loadFile(boost::filesystem::path(vm["scene"].as<std::string>())); GL_CHECK_ERR; // and start the main application loop app.exec(); GL_CHECK_ERR; } //////////////////////////////// // unload all plugins while(!pluginHandles.empty()) { dlclose(pluginHandles.back()); pluginHandles.pop_back(); } return 0; } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Olad.cpp * Main file for olad, parses the options, forks if required and runs the * daemon. * Copyright (C) 2005-2007 Simon Newton * */ #if HAVE_CONFIG_H # include <config.h> #endif #include <getopt.h> #include <iostream> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <sysexits.h> #include <unistd.h> #include <memory> #include "ola/Logging.h" #include "ola/base/Init.h" #include "ola/base/Credentials.h" #include "olad/OlaDaemon.h" using ola::OlaDaemon; using std::string; using std::cout; using std::cerr; using std::endl; // the daemon OlaDaemon *global_olad = NULL; // options struct typedef struct { ola::log_level level; ola::log_output output; bool daemon; bool help; bool version; int httpd; int http_quit; int http_port; int rpc_port; string http_data_dir; string config_dir; string interface; } ola_options; /* * Terminate cleanly on interrupt */ static void sig_interupt(int signo) { if (global_olad) global_olad->Terminate(); (void) signo; } /* * Reload plugins */ static void sig_hup(int signo) { if (global_olad) global_olad->ReloadPlugins(); (void) signo; } /* * Change logging level * * need to fix race conditions here */ static void sig_user1(int signo) { ola::IncrementLogLevel(); (void) signo; } /* * Set up the signal handlers. * @return true on success, false on failure */ static bool InstallSignals() { if (!ola::InstallSignal(SIGINT, sig_interupt)) return false; if (!ola::InstallSignal(SIGTERM, sig_interupt)) return false; if (!ola::InstallSignal(SIGHUP, sig_hup)) return false; if (!ola::InstallSignal(SIGUSR1, sig_user1)) return false; return true; } /* * Display the help message */ static void DisplayHelp() { cout << "Usage: olad [options]\n" "\n" "Start the OLA Daemon.\n" "\n" " -c, --config-dir Path to the config directory\n" " -d, --http-data-dir Path to the static content.\n" " -f, --daemon Fork into background.\n" " -h, --help Display this help message and exit.\n" " -i, --interface <interface name|ip> Network interface to use.\n" " -l, --log-level <level> Set the logging level 0 .. 4 .\n" " -p, --http-port Port to run the http server on (default " << ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" << " -r, --rpc-port Port to listen for RPCs on (default " << ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" << " -s, --syslog Log to syslog rather than stderr.\n" " -v, --version Print the version number\n" " --no-http Don't run the http server\n" " --no-http-quit Disable the /quit handler\n" << endl; } /* * Parse the command line options * * @param argc * @param argv * @param opts pointer to the options struct */ static bool ParseOptions(int argc, char *argv[], ola_options *opts) { static struct option long_options[] = { {"config-dir", required_argument, 0, 'c'}, {"help", no_argument, 0, 'h'}, {"http-data-dir", required_argument, 0, 'd'}, {"http-port", required_argument, 0, 'p'}, {"interface", required_argument, 0, 'i'}, {"log-level", required_argument, 0, 'l'}, {"no-daemon", no_argument, 0, 'f'}, {"no-http", no_argument, &opts->httpd, 0}, {"no-http-quit", no_argument, &opts->http_quit, 0}, {"rpc-port", required_argument, 0, 'r'}, {"syslog", no_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0} }; bool options_valid = true; int c, ll; int option_index = 0; while (1) { c = getopt_long(argc, argv, "c:d:fhi:l:p:r:sv", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'c': opts->config_dir = optarg; break; case 'd': opts->http_data_dir = optarg; break; case 'f': opts->daemon = true; break; case 'h': opts->help = true; break; case 'i': opts->interface = optarg; break; case 's': opts->output = ola::OLA_LOG_SYSLOG; break; case 'l': ll = atoi(optarg); switch (ll) { case 0: // nothing is written at this level // so this turns logging off opts->level = ola::OLA_LOG_NONE; break; case 1: opts->level = ola::OLA_LOG_FATAL; break; case 2: opts->level = ola::OLA_LOG_WARN; break; case 3: opts->level = ola::OLA_LOG_INFO; break; case 4: opts->level = ola::OLA_LOG_DEBUG; break; default : cerr << "Invalid log level " << optarg << endl; options_valid = false; break; } break; case 'p': opts->http_port = atoi(optarg); break; case 'r': opts->rpc_port = atoi(optarg); break; case 'v': opts->version = true; break; case '?': break; default: break; } } return options_valid; } /* * Parse the options, and take action * * @param argc * @param argv * @param opts a pointer to the ola_options struct */ static void Setup(int argc, char*argv[], ola_options *opts) { opts->level = ola::OLA_LOG_WARN; opts->output = ola::OLA_LOG_STDERR; opts->daemon = false; opts->help = false; opts->version = false; opts->httpd = 1; opts->http_quit = 1; opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT; opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT; opts->http_data_dir = ""; opts->config_dir = ""; opts->interface = ""; if (!ParseOptions(argc, argv, opts)) { DisplayHelp(); exit(EX_USAGE); } if (opts->help) { DisplayHelp(); exit(EX_OK); } if (opts->version) { cout << "OLA Daemon version " << VERSION << endl; exit(EX_OK); } // setup the logging ola::InitLogging(opts->level, opts->output); OLA_INFO << "OLA Daemon version " << VERSION; if (opts->daemon) ola::Daemonise(); } /* * Main */ int main(int argc, char *argv[]) { ola_options opts; ola::ExportMap export_map; Setup(argc, argv, &opts); #ifndef OLAD_SKIP_ROOT_CHECK if (!ola::GetEUID()) { OLA_FATAL << "Attempting to run as root, aborting."; return EX_UNAVAILABLE; } #endif ola::ServerInit(argc, argv, &export_map); if (!InstallSignals()) OLA_WARN << "Failed to install signal handlers"; ola::ola_server_options ola_options; ola_options.http_enable = opts.httpd; ola_options.http_enable_quit = opts.http_quit; ola_options.http_port = opts.http_port; ola_options.http_data_dir = opts.http_data_dir; ola_options.interface = opts.interface; std::auto_ptr<OlaDaemon> olad( new OlaDaemon(ola_options, &export_map, opts.rpc_port, opts.config_dir)); if (olad.get() && olad->Init()) { global_olad = olad.get(); olad->Run(); return EX_OK; } global_olad = NULL; return EX_UNAVAILABLE; } <commit_msg> * fix the daemon command line option<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Olad.cpp * Main file for olad, parses the options, forks if required and runs the * daemon. * Copyright (C) 2005-2007 Simon Newton * */ #if HAVE_CONFIG_H # include <config.h> #endif #include <getopt.h> #include <iostream> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <sysexits.h> #include <unistd.h> #include <memory> #include "ola/Logging.h" #include "ola/base/Init.h" #include "ola/base/Credentials.h" #include "olad/OlaDaemon.h" using ola::OlaDaemon; using std::string; using std::cout; using std::cerr; using std::endl; // the daemon OlaDaemon *global_olad = NULL; // options struct typedef struct { ola::log_level level; ola::log_output output; bool daemon; bool help; bool version; int httpd; int http_quit; int http_port; int rpc_port; string http_data_dir; string config_dir; string interface; } ola_options; /* * Terminate cleanly on interrupt */ static void sig_interupt(int signo) { if (global_olad) global_olad->Terminate(); (void) signo; } /* * Reload plugins */ static void sig_hup(int signo) { if (global_olad) global_olad->ReloadPlugins(); (void) signo; } /* * Change logging level * * need to fix race conditions here */ static void sig_user1(int signo) { ola::IncrementLogLevel(); (void) signo; } /* * Set up the signal handlers. * @return true on success, false on failure */ static bool InstallSignals() { if (!ola::InstallSignal(SIGINT, sig_interupt)) return false; if (!ola::InstallSignal(SIGTERM, sig_interupt)) return false; if (!ola::InstallSignal(SIGHUP, sig_hup)) return false; if (!ola::InstallSignal(SIGUSR1, sig_user1)) return false; return true; } /* * Display the help message */ static void DisplayHelp() { cout << "Usage: olad [options]\n" "\n" "Start the OLA Daemon.\n" "\n" " -c, --config-dir Path to the config directory\n" " -d, --http-data-dir Path to the static content.\n" " -f, --daemon Fork into background.\n" " -h, --help Display this help message and exit.\n" " -i, --interface <interface name|ip> Network interface to use.\n" " -l, --log-level <level> Set the logging level 0 .. 4 .\n" " -p, --http-port Port to run the http server on (default " << ola::OlaServer::DEFAULT_HTTP_PORT << ")\n" << " -r, --rpc-port Port to listen for RPCs on (default " << ola::OlaDaemon::DEFAULT_RPC_PORT << ")\n" << " -s, --syslog Log to syslog rather than stderr.\n" " -v, --version Print the version number\n" " --no-http Don't run the http server\n" " --no-http-quit Disable the /quit handler\n" << endl; } /* * Parse the command line options * * @param argc * @param argv * @param opts pointer to the options struct */ static bool ParseOptions(int argc, char *argv[], ola_options *opts) { static struct option long_options[] = { {"config-dir", required_argument, 0, 'c'}, {"help", no_argument, 0, 'h'}, {"http-data-dir", required_argument, 0, 'd'}, {"http-port", required_argument, 0, 'p'}, {"interface", required_argument, 0, 'i'}, {"log-level", required_argument, 0, 'l'}, {"daemon", no_argument, 0, 'f'}, {"no-http", no_argument, &opts->httpd, 0}, {"no-http-quit", no_argument, &opts->http_quit, 0}, {"rpc-port", required_argument, 0, 'r'}, {"syslog", no_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0} }; bool options_valid = true; int c, ll; int option_index = 0; while (1) { c = getopt_long(argc, argv, "c:d:fhi:l:p:r:sv", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'c': opts->config_dir = optarg; break; case 'd': opts->http_data_dir = optarg; break; case 'f': opts->daemon = true; break; case 'h': opts->help = true; break; case 'i': opts->interface = optarg; break; case 's': opts->output = ola::OLA_LOG_SYSLOG; break; case 'l': ll = atoi(optarg); switch (ll) { case 0: // nothing is written at this level // so this turns logging off opts->level = ola::OLA_LOG_NONE; break; case 1: opts->level = ola::OLA_LOG_FATAL; break; case 2: opts->level = ola::OLA_LOG_WARN; break; case 3: opts->level = ola::OLA_LOG_INFO; break; case 4: opts->level = ola::OLA_LOG_DEBUG; break; default : cerr << "Invalid log level " << optarg << endl; options_valid = false; break; } break; case 'p': opts->http_port = atoi(optarg); break; case 'r': opts->rpc_port = atoi(optarg); break; case 'v': opts->version = true; break; case '?': break; default: break; } } return options_valid; } /* * Parse the options, and take action * * @param argc * @param argv * @param opts a pointer to the ola_options struct */ static void Setup(int argc, char*argv[], ola_options *opts) { opts->level = ola::OLA_LOG_WARN; opts->output = ola::OLA_LOG_STDERR; opts->daemon = false; opts->help = false; opts->version = false; opts->httpd = 1; opts->http_quit = 1; opts->http_port = ola::OlaServer::DEFAULT_HTTP_PORT; opts->rpc_port = ola::OlaDaemon::DEFAULT_RPC_PORT; opts->http_data_dir = ""; opts->config_dir = ""; opts->interface = ""; if (!ParseOptions(argc, argv, opts)) { DisplayHelp(); exit(EX_USAGE); } if (opts->help) { DisplayHelp(); exit(EX_OK); } if (opts->version) { cout << "OLA Daemon version " << VERSION << endl; exit(EX_OK); } // setup the logging ola::InitLogging(opts->level, opts->output); OLA_INFO << "OLA Daemon version " << VERSION; if (opts->daemon) ola::Daemonise(); } /* * Main */ int main(int argc, char *argv[]) { ola_options opts; ola::ExportMap export_map; Setup(argc, argv, &opts); #ifndef OLAD_SKIP_ROOT_CHECK if (!ola::GetEUID()) { OLA_FATAL << "Attempting to run as root, aborting."; return EX_UNAVAILABLE; } #endif ola::ServerInit(argc, argv, &export_map); if (!InstallSignals()) OLA_WARN << "Failed to install signal handlers"; ola::ola_server_options ola_options; ola_options.http_enable = opts.httpd; ola_options.http_enable_quit = opts.http_quit; ola_options.http_port = opts.http_port; ola_options.http_data_dir = opts.http_data_dir; ola_options.interface = opts.interface; std::auto_ptr<OlaDaemon> olad( new OlaDaemon(ola_options, &export_map, opts.rpc_port, opts.config_dir)); if (olad.get() && olad->Init()) { global_olad = olad.get(); olad->Run(); return EX_OK; } global_olad = NULL; return EX_UNAVAILABLE; } <|endoftext|>
<commit_before>// [AsmJit] // Complete x86/x64 JIT and Remote Assembler for C++. // // [License] // Zlib - See LICENSE.md file in the package. // [Export] #define ASMJIT_EXPORTS // [Dependencies - AsmJit] #include "../base/cputicks.h" // [Dependencies - Posix] #if defined(ASMJIT_OS_POSIX) # include <time.h> # include <unistd.h> #endif // ASMJIT_OS_POSIX // [Dependencies - Mac] #if defined(ASMJIT_OS_MAC) # include <mach/mach_time.h> #endif // ASMJIT_OS_MAC // [Api-Begin] #include "../apibegin.h" namespace asmjit { // ============================================================================ // [asmjit::CpuTicks - Windows] // ============================================================================ #if defined(ASMJIT_OS_WINDOWS) static volatile uint32_t CpuTicks_hiResOk; static volatile double CpuTicks_hiResFreq; uint32_t CpuTicks::now() { do { uint32_t hiResOk = CpuTicks_hiResOk; if (hiResOk == 1) { LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) break; return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq); } if (hiResOk == 0) { LARGE_INTEGER qpf; if (!::QueryPerformanceFrequency(&qpf)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } double freqDouble = double(qpf.QuadPart) / 1000.0; CpuTicks_hiResFreq = freqDouble; _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0); return static_cast<uint32_t>( static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF); } } while (0); // Bail to mmsystem. return ::GetTickCount(); } // ============================================================================ // [asmjit::CpuTicks - Mac] // ============================================================================ #elif defined(ASMJIT_OS_MAC) static mach_timebase_info_data_t CpuTicks_machTime; uint32_t CpuTicks::now() { // Initialize the first time CpuTicks::now() is called (See Apple's QA1398). if (CpuTicks_machTime.denom == 0) { if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS); return 0; } // mach_absolute_time() returns nanoseconds, we need just milliseconds. uint64_t t = mach_absolute_time() / 1000000; t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom; return static_cast<uint32_t>(t & 0xFFFFFFFFU) } // ============================================================================ // [asmjit::CpuTicks - Posix] // ============================================================================ #else uint32_t CpuTicks::now() { #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000); return static_cast<uint32_t>(t & 0xFFFFFFFFU); #else // _POSIX_MONOTONIC_CLOCK #error "AsmJit - Unsupported OS." return 0; #endif // _POSIX_MONOTONIC_CLOCK } #endif // ASMJIT_OS } // asmjit namespace // [Api-End] #include "../apiend.h" <commit_msg>Fix typo<commit_after>// [AsmJit] // Complete x86/x64 JIT and Remote Assembler for C++. // // [License] // Zlib - See LICENSE.md file in the package. // [Export] #define ASMJIT_EXPORTS // [Dependencies - AsmJit] #include "../base/cputicks.h" // [Dependencies - Posix] #if defined(ASMJIT_OS_POSIX) # include <time.h> # include <unistd.h> #endif // ASMJIT_OS_POSIX // [Dependencies - Mac] #if defined(ASMJIT_OS_MAC) # include <mach/mach_time.h> #endif // ASMJIT_OS_MAC // [Api-Begin] #include "../apibegin.h" namespace asmjit { // ============================================================================ // [asmjit::CpuTicks - Windows] // ============================================================================ #if defined(ASMJIT_OS_WINDOWS) static volatile uint32_t CpuTicks_hiResOk; static volatile double CpuTicks_hiResFreq; uint32_t CpuTicks::now() { do { uint32_t hiResOk = CpuTicks_hiResOk; if (hiResOk == 1) { LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) break; return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq); } if (hiResOk == 0) { LARGE_INTEGER qpf; if (!::QueryPerformanceFrequency(&qpf)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } double freqDouble = double(qpf.QuadPart) / 1000.0; CpuTicks_hiResFreq = freqDouble; _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0); return static_cast<uint32_t>( static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF); } } while (0); // Bail to mmsystem. return ::GetTickCount(); } // ============================================================================ // [asmjit::CpuTicks - Mac] // ============================================================================ #elif defined(ASMJIT_OS_MAC) static mach_timebase_info_data_t CpuTicks_machTime; uint32_t CpuTicks::now() { // Initialize the first time CpuTicks::now() is called (See Apple's QA1398). if (CpuTicks_machTime.denom == 0) { if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS); return 0; } // mach_absolute_time() returns nanoseconds, we need just milliseconds. uint64_t t = mach_absolute_time() / 1000000; t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom; return static_cast<uint32_t>(t & 0xFFFFFFFFU); } // ============================================================================ // [asmjit::CpuTicks - Posix] // ============================================================================ #else uint32_t CpuTicks::now() { #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000); return static_cast<uint32_t>(t & 0xFFFFFFFFU); #else // _POSIX_MONOTONIC_CLOCK #error "AsmJit - Unsupported OS." return 0; #endif // _POSIX_MONOTONIC_CLOCK } #endif // ASMJIT_OS } // asmjit namespace // [Api-End] #include "../apiend.h" <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_l10ntools.hxx" #include "srciter.hxx" #include <stdio.h> #include <tools/fsys.hxx> // // class SourceTreeIterator // /*****************************************************************************/ SourceTreeIterator::SourceTreeIterator( const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in ) /*****************************************************************************/ : bInExecute( sal_False ) , bLocal( bLocal_in ) { (void) rVersion ; if(!bLocal){ rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 ); aRootDirectory = transex::Directory( sRootDirectory ); } } /*****************************************************************************/ SourceTreeIterator::~SourceTreeIterator() /*****************************************************************************/ { } /*****************************************************************************/ void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory ) /*****************************************************************************/ { if ( bInExecute ) { rtl::OUString sDirName = aDirectory.getDirectoryName(); static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) ); static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) ); static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) ); static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) ); static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) ); static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) ); static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) ); if( sDirName.indexOf( WCARD1 , 0 ) > -1 || sDirName.indexOf( WCARD2 , 0 ) > -1 || sDirName.indexOf( WCARD3 , 0 ) > -1 || sDirName.indexOf( WCARD4 , 0 ) > -1 || sDirName.indexOf( WCARD5 , 0 ) > -1 || sDirName.indexOf( WCARD6 , 0 ) > -1 || sDirName.indexOf( WCARD7 , 0 ) > -1 ) return; //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); rtl::OUString sDirNameTmp = aDirectory.getFullName(); ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); #ifdef WNT sDirNameTmpB.Append( ByteString("\\no_localization") ); #else sDirNameTmpB.Append( ByteString("/no_localization") ); #endif //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); DirEntry aDE( sDirNameTmpB.GetBuffer() ); if( aDE.Exists() ) { //printf("#### no_localization file found ... skipping"); return; } aDirectory.setSkipLinks( bSkipLinks ); aDirectory.readDirectory(); OnExecuteDirectory( aDirectory.getFullName() ); if ( aDirectory.getSubDirectories().size() ) for ( sal_uLong i=0;i < aDirectory.getSubDirectories().size();i++ ) ExecuteDirectory( aDirectory.getSubDirectories()[ i ] ); } } /*****************************************************************************/ sal_Bool SourceTreeIterator::StartExecute() /*****************************************************************************/ { bInExecute = sal_True; // FIXME ExecuteDirectory( aRootDirectory ); if ( bInExecute ) { // FIXME bInExecute = sal_False; return sal_True; } return sal_False; } /*****************************************************************************/ void SourceTreeIterator::EndExecute() /*****************************************************************************/ { bInExecute = sal_False; } /*****************************************************************************/ void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory ) /*****************************************************************************/ { fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() ); } <commit_msg>masterfix DEV300: skip .hg subdirs<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_l10ntools.hxx" #include "srciter.hxx" #include <stdio.h> #include <tools/fsys.hxx> // // class SourceTreeIterator // /*****************************************************************************/ SourceTreeIterator::SourceTreeIterator( const ByteString &rRootDirectory, const ByteString &rVersion , bool bLocal_in ) /*****************************************************************************/ : bInExecute( sal_False ) , bLocal( bLocal_in ) { (void) rVersion ; if(!bLocal){ rtl::OUString sRootDirectory( rRootDirectory.GetBuffer() , rRootDirectory.Len() , RTL_TEXTENCODING_UTF8 ); aRootDirectory = transex::Directory( sRootDirectory ); } } /*****************************************************************************/ SourceTreeIterator::~SourceTreeIterator() /*****************************************************************************/ { } /*****************************************************************************/ void SourceTreeIterator::ExecuteDirectory( transex::Directory& aDirectory ) /*****************************************************************************/ { if ( bInExecute ) { rtl::OUString sDirName = aDirectory.getDirectoryName(); static rtl::OUString WCARD1 ( rtl::OUString::createFromAscii( "unxlng" ) ); static rtl::OUString WCARD2 ( rtl::OUString::createFromAscii( "unxsol" ) ); static rtl::OUString WCARD3 ( rtl::OUString::createFromAscii( "wntmsc" ) ); static rtl::OUString WCARD4 ( rtl::OUString::createFromAscii( "common" ) ); static rtl::OUString WCARD5 ( rtl::OUString::createFromAscii( "unxmac" ) ); static rtl::OUString WCARD6 ( rtl::OUString::createFromAscii( "unxubt" ) ); static rtl::OUString WCARD7 ( rtl::OUString::createFromAscii( ".svn" ) ); static rtl::OUString WCARD8 ( rtl::OUString::createFromAscii( ".hg" ) ); if( sDirName.indexOf( WCARD1 , 0 ) > -1 || sDirName.indexOf( WCARD2 , 0 ) > -1 || sDirName.indexOf( WCARD3 , 0 ) > -1 || sDirName.indexOf( WCARD4 , 0 ) > -1 || sDirName.indexOf( WCARD5 , 0 ) > -1 || sDirName.indexOf( WCARD6 , 0 ) > -1 || sDirName.indexOf( WCARD7 , 0 ) > -1 || sDirName.indexOf( WCARD8 , 0 ) > -1 ) return; //printf("**** %s \n", OUStringToOString( sDirName , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); rtl::OUString sDirNameTmp = aDirectory.getFullName(); ByteString sDirNameTmpB( rtl::OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); #ifdef WNT sDirNameTmpB.Append( ByteString("\\no_localization") ); #else sDirNameTmpB.Append( ByteString("/no_localization") ); #endif //printf("**** %s \n", OUStringToOString( sDirNameTmp , RTL_TEXTENCODING_UTF8 , sDirName.getLength() ).getStr() ); DirEntry aDE( sDirNameTmpB.GetBuffer() ); if( aDE.Exists() ) { //printf("#### no_localization file found ... skipping"); return; } aDirectory.setSkipLinks( bSkipLinks ); aDirectory.readDirectory(); OnExecuteDirectory( aDirectory.getFullName() ); if ( aDirectory.getSubDirectories().size() ) for ( sal_uLong i=0;i < aDirectory.getSubDirectories().size();i++ ) ExecuteDirectory( aDirectory.getSubDirectories()[ i ] ); } } /*****************************************************************************/ sal_Bool SourceTreeIterator::StartExecute() /*****************************************************************************/ { bInExecute = sal_True; // FIXME ExecuteDirectory( aRootDirectory ); if ( bInExecute ) { // FIXME bInExecute = sal_False; return sal_True; } return sal_False; } /*****************************************************************************/ void SourceTreeIterator::EndExecute() /*****************************************************************************/ { bInExecute = sal_False; } /*****************************************************************************/ void SourceTreeIterator::OnExecuteDirectory( const rtl::OUString &rDirectory ) /*****************************************************************************/ { fprintf( stdout, "%s\n", rtl::OUStringToOString( rDirectory, RTL_TEXTENCODING_UTF8, rDirectory.getLength() ).getStr() ); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_io_xbus_scominit.C /// @brief Invoke XBUS initfile /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Chris Steffen <[email protected]> // *HWP HWP Backup Owner: Gary Peterson <[email protected]> // *HWP FW Owner : Sumit Kumar <[email protected]> // *HWP Team : IO // *HWP Level : 2 // *HWP Consumed by : FSP:HB //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // // Invoke XBUS scominit file. // // Procedure Prereq: // - System clocks are running. // @endverbatim //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_io_regs.H> #include <p9_io_scom.H> #include <p9_io_xbus_scominit.H> #include <p9_xbus_g0_scom.H> #include <p9_xbus_g1_scom.H> enum { ENUM_ATTR_XBUS_GROUP_0, ENUM_ATTR_XBUS_GROUP_1 }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /** * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id * @param[in] i_target Fapi2 Target * @param[in] i_ctarget Fapi2 Connected Target * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode set_rx_master_mode( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget ); /** * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference * @param[in] i_target Fapi2 Target * @param[in] o_group_id Group ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_group_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_group_id ); /** * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce * @param[in] i_target Fapi2 Target * @param[in] o_chip_id Chip ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_chip_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_chip_id ); /** * @brief HWP that calls the XBUS SCOM initfiles * Should be called for all valid/connected XBUS endpoints * @param[in] i_target Reference to XBUS chiplet target * @param[in] i_connected_target Reference to connected XBUS chiplet target * @param[in] i_group Reference to XBUS group-0/1 * @return FAPI2_RC_SUCCESS on success, error otherwise */ fapi2::ReturnCode p9_io_xbus_scominit( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_connected_target, const uint8_t i_group) { // mark HWP entry FAPI_INF("p9_io_xbus_scominit: Entering ..."); const uint8_t LANE_00 = 0; fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS; // get system target const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target; // assert IO reset to power-up bus endpoint logic // read-modify-write, set single reset bit (HW auto-clears) // on writeback FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Connected Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); // Delay 1ns, 1 Million cycles -- Needed in sim, may not be needed in hw. FAPI_TRY( fapi2::delay( 1, 1000000 ) ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Connected Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); // Set rx master/slave attribute prior to calling the scominit procedures. // The scominit procedure will reference the attribute to set the register field. FAPI_TRY( set_rx_master_mode( i_target, i_connected_target ), "Setting Rx Master Mode Attribute Failed." ); switch(i_group) { case ENUM_ATTR_XBUS_GROUP_0: FAPI_INF("Group 0:Invoke FAPI procedure core: input_target"); FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_target, l_system_target); FAPI_INF("Group 0:Invoke FAPI procedure core: connected_target"); FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_connected_target, l_system_target); break; case ENUM_ATTR_XBUS_GROUP_1: FAPI_INF("Group 1:Invoke FAPI procedure core: input_target"); FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_target, l_system_target); FAPI_INF("Group 1:Invoke FAPI procedure core: connected_target"); FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_connected_target, l_system_target); break; } // mark HWP exit FAPI_INF("p9_io_xbus_scominit: ...Exiting"); fapi_try_exit: return fapi2::current_err; } /** * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id * @param[in] i_target Fapi2 Target * @param[in] i_ctarget Fapi2 Connected Target * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode set_rx_master_mode( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget ) { FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Enter." ); uint8_t l_primary_group_id = 0; uint8_t l_primary_chip_id = 0; uint32_t l_primary_id = 0; uint8_t l_primary_attr = 0; uint8_t l_connected_group_id = 0; uint8_t l_connected_chip_id = 0; uint32_t l_connected_id = 0; uint8_t l_connected_attr = 0; FAPI_TRY( p9_get_proc_fabric_group_id( i_target, l_primary_group_id ) ); FAPI_TRY( p9_get_proc_fabric_group_id( i_ctarget, l_connected_group_id ) ); FAPI_TRY( p9_get_proc_fabric_chip_id( i_target, l_primary_chip_id ) ); FAPI_TRY( p9_get_proc_fabric_chip_id( i_ctarget, l_connected_chip_id ) ); l_primary_id = ( (uint32_t)l_primary_group_id << 8 ) + (uint32_t)l_primary_chip_id; l_connected_id = ( (uint32_t)l_connected_group_id << 8 ) + (uint32_t)l_connected_chip_id; FAPI_DBG( "I/O Xbus Scominit: Target ID(%d) Connected ID(%d)", l_primary_id, l_connected_id ); if( l_primary_id < l_connected_id ) { l_primary_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE; l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE; } else { l_primary_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE; l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE; } FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_target, l_primary_attr ), "I/O Xbus Scominit: Set Primary Master Mode Attribute Failed." ); FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_ctarget, l_connected_attr ), "I/O Xbus Scominit: Set Connected Master Mode Attribute Failed." ); fapi_try_exit: FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Exit." ); return fapi2::current_err; } /** * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference * @param[in] i_target Fapi2 Target * @param[out] o_group_id Group ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_group_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_group_id) { FAPI_IMP("I/O Xbus Scominit: Get Proc Group Start."); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); // Retrieve node attribute FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_GROUP_ID, l_proc, o_group_id ), "(PROC): Error getting ATTR_PROC_FABRIC_GROUP_ID, l_rc 0x%.8X", (uint64_t)fapi2::current_err ); fapi_try_exit: FAPI_IMP("I/O Xbus Scominit: Get Proc Group Exit."); return fapi2::current_err; } /** * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce * @param[in] i_target Fapi2 Target * @param[out] o_chip_id Chip ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_chip_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_chip_id) { FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Start."); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); // Retrieve pos ID attribute FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_CHIP_ID, l_proc, o_chip_id ), "(PROC): Error getting ATTR_PROC_FABRIC_CHIP_ID, l_rc 0x%.8X", (uint64_t)fapi2::current_err ); fapi_try_exit: FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Exit."); return fapi2::current_err; } <commit_msg>Scominit Reset and Delay Update<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_io_xbus_scominit.C /// @brief Invoke XBUS initfile /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Chris Steffen <[email protected]> // *HWP HWP Backup Owner: Gary Peterson <[email protected]> // *HWP FW Owner : Sumit Kumar <[email protected]> // *HWP Team : IO // *HWP Level : 2 // *HWP Consumed by : FSP:HB //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // // Invoke XBUS scominit file. // // Procedure Prereq: // - System clocks are running. // @endverbatim //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_io_regs.H> #include <p9_io_scom.H> #include <p9_io_xbus_scominit.H> #include <p9_xbus_g0_scom.H> #include <p9_xbus_g1_scom.H> enum { ENUM_ATTR_XBUS_GROUP_0, ENUM_ATTR_XBUS_GROUP_1 }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /** * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id * @param[in] i_target Fapi2 Target * @param[in] i_ctarget Fapi2 Connected Target * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode set_rx_master_mode( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget ); /** * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference * @param[in] i_target Fapi2 Target * @param[in] o_group_id Group ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_group_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_group_id ); /** * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce * @param[in] i_target Fapi2 Target * @param[in] o_chip_id Chip ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_chip_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_chip_id ); /** * @brief HWP that calls the XBUS SCOM initfiles * Should be called for all valid/connected XBUS endpoints * @param[in] i_target Reference to XBUS chiplet target * @param[in] i_connected_target Reference to connected XBUS chiplet target * @param[in] i_group Reference to XBUS group-0/1 * @return FAPI2_RC_SUCCESS on success, error otherwise */ fapi2::ReturnCode p9_io_xbus_scominit( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_target, const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_connected_target, const uint8_t i_group) { // mark HWP entry FAPI_INF("p9_io_xbus_scominit: Entering ..."); const uint8_t LANE_00 = 0; fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS; // get system target const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_system_target; // assert IO reset to power-up bus endpoint logic // read-modify-write, set single reset bit (HW auto-clears) // on writeback FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Connected Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 1 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); // Calculated HW Delay needed based on counter size and clock speed. // 50us -- Based on Counter Size, 40us minimum // 1 Million sim cycles -- Based on sim learning FAPI_TRY( fapi2::delay( 50000, 1000000 ) ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_RX_IORESET, i_connected_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Connected Set Reset Hard Failed." ); FAPI_TRY( io::rmw( EDIP_TX_IORESET, i_connected_target, i_group, LANE_00, 0 ), "I/O Xbus Scominit: Primary Set Reset Hard Failed." ); // Set rx master/slave attribute prior to calling the scominit procedures. // The scominit procedure will reference the attribute to set the register field. FAPI_TRY( set_rx_master_mode( i_target, i_connected_target ), "Setting Rx Master Mode Attribute Failed." ); switch(i_group) { case ENUM_ATTR_XBUS_GROUP_0: FAPI_INF("Group 0:Invoke FAPI procedure core: input_target"); FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_target, l_system_target); FAPI_INF("Group 0:Invoke FAPI procedure core: connected_target"); FAPI_EXEC_HWP(rc, p9_xbus_g0_scom, i_connected_target, l_system_target); break; case ENUM_ATTR_XBUS_GROUP_1: FAPI_INF("Group 1:Invoke FAPI procedure core: input_target"); FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_target, l_system_target); FAPI_INF("Group 1:Invoke FAPI procedure core: connected_target"); FAPI_EXEC_HWP(rc, p9_xbus_g1_scom, i_connected_target, l_system_target); break; } // mark HWP exit FAPI_INF("p9_io_xbus_scominit: ...Exiting"); fapi_try_exit: return fapi2::current_err; } /** * @brief Sets ATTR_IO_XBUS_MASTER_MODE based on fabric chip id and fabric group id * @param[in] i_target Fapi2 Target * @param[in] i_ctarget Fapi2 Connected Target * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode set_rx_master_mode( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_ctarget ) { FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Enter." ); uint8_t l_primary_group_id = 0; uint8_t l_primary_chip_id = 0; uint32_t l_primary_id = 0; uint8_t l_primary_attr = 0; uint8_t l_connected_group_id = 0; uint8_t l_connected_chip_id = 0; uint32_t l_connected_id = 0; uint8_t l_connected_attr = 0; FAPI_TRY( p9_get_proc_fabric_group_id( i_target, l_primary_group_id ) ); FAPI_TRY( p9_get_proc_fabric_group_id( i_ctarget, l_connected_group_id ) ); FAPI_TRY( p9_get_proc_fabric_chip_id( i_target, l_primary_chip_id ) ); FAPI_TRY( p9_get_proc_fabric_chip_id( i_ctarget, l_connected_chip_id ) ); l_primary_id = ( (uint32_t)l_primary_group_id << 8 ) + (uint32_t)l_primary_chip_id; l_connected_id = ( (uint32_t)l_connected_group_id << 8 ) + (uint32_t)l_connected_chip_id; FAPI_DBG( "I/O Xbus Scominit: Target ID(%d) Connected ID(%d)", l_primary_id, l_connected_id ); if( l_primary_id < l_connected_id ) { l_primary_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE; l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE; } else { l_primary_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_FALSE; l_connected_attr = fapi2::ENUM_ATTR_IO_XBUS_MASTER_MODE_TRUE; } FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_target, l_primary_attr ), "I/O Xbus Scominit: Set Primary Master Mode Attribute Failed." ); FAPI_TRY( FAPI_ATTR_SET( fapi2::ATTR_IO_XBUS_MASTER_MODE, i_ctarget, l_connected_attr ), "I/O Xbus Scominit: Set Connected Master Mode Attribute Failed." ); fapi_try_exit: FAPI_IMP( "I/O Xbus Scominit: Set Master Mode Exit." ); return fapi2::current_err; } /** * @brief Gets the value of the ATTR_PROC_FABRIC_GROUP_ID and passes back by reference * @param[in] i_target Fapi2 Target * @param[out] o_group_id Group ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_group_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_group_id) { FAPI_IMP("I/O Xbus Scominit: Get Proc Group Start."); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); // Retrieve node attribute FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_GROUP_ID, l_proc, o_group_id ), "(PROC): Error getting ATTR_PROC_FABRIC_GROUP_ID, l_rc 0x%.8X", (uint64_t)fapi2::current_err ); fapi_try_exit: FAPI_IMP("I/O Xbus Scominit: Get Proc Group Exit."); return fapi2::current_err; } /** * @brief Gets the value of the ATTR_PROC_FABRIC_CHIP_ID and passes back by refernce * @param[in] i_target Fapi2 Target * @param[out] o_chip_id Chip ID * @retval ReturnCode Fapi2 ReturnCode */ fapi2::ReturnCode p9_get_proc_fabric_chip_id( const fapi2::Target< fapi2::TARGET_TYPE_XBUS >& i_target, uint8_t& o_chip_id) { FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Start."); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_proc = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); // Retrieve pos ID attribute FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_PROC_FABRIC_CHIP_ID, l_proc, o_chip_id ), "(PROC): Error getting ATTR_PROC_FABRIC_CHIP_ID, l_rc 0x%.8X", (uint64_t)fapi2::current_err ); fapi_try_exit: FAPI_IMP("I/O Xbus Scominit: Get Proc Chip Id Exit."); return fapi2::current_err; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2021 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * Test code for the 2nd order Butterworth low-pass filter * Run this test only using make tests TESTFILTER=LowPassFilter2pVector3f */ #include <gtest/gtest.h> #include <matrix/matrix/math.hpp> #include <px4_platform_common/defines.h> #include "LowPassFilter2pVector3f.hpp" using matrix::Vector3f; class LowPassFilter2pVector3fTest : public ::testing::Test { public: math::LowPassFilter2pVector3f _lpf{800.f, 30.f}; const float _sample_freq = 1000.f; const float _cutoff_freq = 80.f; const float _epsilon_near = 10e-3f; }; TEST_F(LowPassFilter2pVector3fTest, setGet) { _lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq); EXPECT_EQ(_lpf.get_sample_freq(), _sample_freq); EXPECT_EQ(_lpf.get_cutoff_freq(), _cutoff_freq); } TEST_F(LowPassFilter2pVector3fTest, belowCutoff) { _lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq); const float signal_freq = 10.f; const float omega = 2.f * M_PI_F * signal_freq; const float phase_delay = 10.4f * M_PI_F / 180.f; // Given by simulation const float dt = 1.f / _sample_freq; float t = 0.f; for (int i = 0; i < 1000; i++) { float input = sinf(omega * t); float output_expected = sinf(omega * t - phase_delay); Vector3f out = _lpf.apply(Vector3f(0.f, input, -input)); t = i * dt; // Let some time for the filter to settle if (i > 30) { EXPECT_EQ(out(0), 0.f); EXPECT_NEAR(out(1), output_expected, _epsilon_near); EXPECT_NEAR(out(2), -output_expected, _epsilon_near); } } } TEST_F(LowPassFilter2pVector3fTest, aboveCutoff) { _lpf.set_cutoff_frequency(_sample_freq, _cutoff_freq); const float signal_freq = 100.f; const float omega = 2.f * M_PI_F * signal_freq; const float phase_delay = 108.5f * M_PI_F / 180.f; // Given by simulation const float gain = 0.52f; // = -5.66 dB, given by simulation const float dt = 1.f / _sample_freq; float t = 0.f; for (int i = 0; i < 1000; i++) { float input = sinf(omega * t); float output_expected = gain * sinf(omega * t - phase_delay); Vector3f out = _lpf.apply(Vector3f(0.f, input, -input)); t = i * dt; // Let some time for the filter to settle if (i > 30) { EXPECT_EQ(out(0), 0.f); EXPECT_NEAR(out(1), output_expected, _epsilon_near); EXPECT_NEAR(out(2), -output_expected, _epsilon_near); } } } <commit_msg>lpf test: move to common function<commit_after>/**************************************************************************** * * Copyright (C) 2021 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * Test code for the 2nd order Butterworth low-pass filter * Run this test only using make tests TESTFILTER=LowPassFilter2pVector3f */ #include <gtest/gtest.h> #include <matrix/matrix/math.hpp> #include <px4_platform_common/defines.h> #include "LowPassFilter2pVector3f.hpp" using matrix::Vector3f; class LowPassFilter2pVector3fTest : public ::testing::Test { public: void runSimulatedFilter(const Vector3f &signal_freq_hz, const Vector3f &phase_delay_deg, const Vector3f &gain_db); math::LowPassFilter2pVector3f _lpf{800.f, 30.f}; const float _epsilon_near = 10e-3f; }; void LowPassFilter2pVector3fTest::runSimulatedFilter(const Vector3f &signal_freq_hz, const Vector3f &phase_delay_deg, const Vector3f &gain_db) { const Vector3f phase_delay = phase_delay_deg * M_PI_F / 180.f; const Vector3f omega = 2.f * M_PI_F * signal_freq_hz; Vector3f gain; for (int i = 0; i < 3; i++) { gain(i) = powf(10.f, gain_db(i) / 20.f); } const float dt = 1.f / _lpf.get_sample_freq(); float t = 0.f; for (int i = 0; i < 1000; i++) { Vector3f input{0.f, sinf(omega(1) * t), -sinf(omega(2) * t)}; Vector3f output_expected{0.f, gain(1) *sinf(omega(1) * t - phase_delay(1)), -gain(2) *sinf(omega(2) * t - phase_delay(2))}; Vector3f out = _lpf.apply(input); t = i * dt; // Let some time for the filter to settle if (i > 30) { EXPECT_EQ(out(0), 0.f); EXPECT_NEAR(out(1), output_expected(1), _epsilon_near); EXPECT_NEAR(out(2), output_expected(2), _epsilon_near); } } } TEST_F(LowPassFilter2pVector3fTest, setGet) { const float sample_freq = 1000.f; const float cutoff_freq = 80.f; _lpf.set_cutoff_frequency(sample_freq, cutoff_freq); EXPECT_EQ(_lpf.get_sample_freq(), sample_freq); EXPECT_EQ(_lpf.get_cutoff_freq(), cutoff_freq); } TEST_F(LowPassFilter2pVector3fTest, belowAndAboveCutoff) { const float sample_freq = 1000.f; const float cutoff_freq = 80.f; _lpf.set_cutoff_frequency(sample_freq, cutoff_freq); const Vector3f signal_freq_hz{0.f, 10.f, 100.f}; const Vector3f phase_delay_deg = Vector3f{0.f, 10.4f, 108.5f}; // Given by simulation const Vector3f gain_db{0.f, 0.f, -5.66f}; // given by simulation runSimulatedFilter(signal_freq_hz, phase_delay_deg, gain_db); } <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_translate_hpp #define xeumeuleu_translate_hpp #define XEUMEULEU_TRANSCODER_ENCODING "utf-8" #define XEUMEULEU_TRANSCODER_BUFFER_SIZE 128 #include <xeumeuleu/bridges/xerces/detail/xerces.hpp> #include <algorithm> #include <iterator> #include <vector> #include <string> namespace xml { // ============================================================================= /** @class translate @brief String translation helpers */ // Created: MAT 2006-01-04 // ============================================================================= class translate { public: //! @name Constructors/Destructor //@{ explicit translate( const std::string& str ) : transcoder_( create() ) , s_ ( transcode( str ) ) , ch_ ( &s_[0] ) {} explicit translate( const XMLCh* const ch ) : transcoder_( create() ) , ch_ ( ch ) {} translate( const translate& rhs ) : transcoder_( create() ) , s_ ( rhs.s_ ) , ch_ ( s_.empty() ? rhs.ch_ : &s_[0] ) {} //@} //! @name Operators //@{ operator const XMLCh*() const { return ch_; } operator std::string() const { std::string result; const XMLSize_t size = XERCES_CPP_NAMESPACE::XMLString::stringLen( ch_ ); XMLByte s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; XMLSize_t done = 0; while( done < size ) { Count_t read = 0; Count_t written = transcoder_->transcodeTo( ch_ + done, size - done, s, XEUMEULEU_TRANSCODER_BUFFER_SIZE, read, XERCES_CPP_NAMESPACE::XMLTranscoder::UnRep_RepChar ); if( read == 0 ) throw xml::exception( "failed to transcode string" ); done += read; result.append( reinterpret_cast< const char* >( s ), written ); } return result; } bool operator==( const XMLCh* const ch ) const { return XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ ); } bool operator==( const std::string& str ) const { return translate( str ) == ch_; } bool operator!=( const XMLCh* const ch ) const { return ! XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ ); } bool operator!=( const std::string& str ) const { return translate( str ) != ch_; } //@} private: //! @name Helpers //@{ XERCES_CPP_NAMESPACE::XMLTranscoder* create() const { XERCES_CPP_NAMESPACE::XMLTransService::Codes result; XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder( XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgTransService->makeNewTranscoderFor( XEUMEULEU_TRANSCODER_ENCODING, result, 16 * 1024 ) ); if( result != XERCES_CPP_NAMESPACE::XMLTransService::Ok ) throw xml::exception( std::string( "unable to create transcoder for " ) + XEUMEULEU_TRANSCODER_ENCODING ); return transcoder.release(); } std::vector< XMLCh > transcode( const std::string& str ) const { std::vector< XMLCh > result; const XMLByte* in = reinterpret_cast< const XMLByte* >( str.c_str() ); const XMLSize_t length = str.length(); XMLCh s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; unsigned char sizes[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; XMLSize_t done = 0; while( done < length ) { Count_t read = 0; XMLSize_t written = transcoder_->transcodeFrom( in + done, length - done, s, XEUMEULEU_TRANSCODER_BUFFER_SIZE, read, sizes ); if( read == 0 ) throw xml::exception( "failed to transcode string" ); done += read; std::copy( s, s + written, std::back_inserter( result ) ); } result.resize( result.size() + 4 ); return result; } //@} private: //! @name Copy/Assignment //@{ translate& operator=( const translate& ); //!< Assignment operator //@} private: //! @name Member data //@{ XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder_; const std::vector< XMLCh > s_; const XMLCh* const ch_; //@} }; inline bool operator==( const XMLCh* const ch, const translate& tr ) { return tr == ch; } inline bool operator==( const std::string& str, const translate& tr ) { return tr == str; } inline bool operator!=( const XMLCh* const ch, const translate& tr ) { return tr != ch; } inline bool operator!=( const std::string& str, const translate& tr ) { return tr != str; } inline std::string operator+( const translate& tr, const std::string& str ) { return std::string( tr ) + str; } inline std::string operator+( const std::string& str, const translate& tr ) { return str + std::string( tr ); } } #endif // xeumeuleu_translate_hpp <commit_msg>Build translated string more simply and efficiently<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_translate_hpp #define xeumeuleu_translate_hpp #define XEUMEULEU_TRANSCODER_ENCODING "utf-8" #define XEUMEULEU_TRANSCODER_BUFFER_SIZE 128 #include <xeumeuleu/bridges/xerces/detail/xerces.hpp> #include <vector> #include <string> namespace xml { // ============================================================================= /** @class translate @brief String translation helpers */ // Created: MAT 2006-01-04 // ============================================================================= class translate { public: //! @name Constructors/Destructor //@{ explicit translate( const std::string& str ) : transcoder_( create() ) , s_ ( transcode( str ) ) , ch_ ( &s_[0] ) {} explicit translate( const XMLCh* const ch ) : transcoder_( create() ) , ch_ ( ch ) {} translate( const translate& rhs ) : transcoder_( create() ) , s_ ( rhs.s_ ) , ch_ ( s_.empty() ? rhs.ch_ : &s_[0] ) {} //@} //! @name Operators //@{ operator const XMLCh*() const { return ch_; } operator std::string() const { std::string result; const XMLSize_t size = XERCES_CPP_NAMESPACE::XMLString::stringLen( ch_ ); XMLByte s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; XMLSize_t done = 0; while( done < size ) { Count_t read = 0; Count_t written = transcoder_->transcodeTo( ch_ + done, size - done, s, XEUMEULEU_TRANSCODER_BUFFER_SIZE, read, XERCES_CPP_NAMESPACE::XMLTranscoder::UnRep_RepChar ); if( read == 0 ) throw xml::exception( "failed to transcode string" ); done += read; result.append( reinterpret_cast< const char* >( s ), written ); } return result; } bool operator==( const XMLCh* const ch ) const { return XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ ); } bool operator==( const std::string& str ) const { return translate( str ) == ch_; } bool operator!=( const XMLCh* const ch ) const { return ! XERCES_CPP_NAMESPACE::XMLString::equals( ch, ch_ ); } bool operator!=( const std::string& str ) const { return translate( str ) != ch_; } //@} private: //! @name Helpers //@{ XERCES_CPP_NAMESPACE::XMLTranscoder* create() const { XERCES_CPP_NAMESPACE::XMLTransService::Codes result; XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder( XERCES_CPP_NAMESPACE::XMLPlatformUtils::fgTransService->makeNewTranscoderFor( XEUMEULEU_TRANSCODER_ENCODING, result, 16 * 1024 ) ); if( result != XERCES_CPP_NAMESPACE::XMLTransService::Ok ) throw xml::exception( std::string( "unable to create transcoder for " ) + XEUMEULEU_TRANSCODER_ENCODING ); return transcoder.release(); } std::vector< XMLCh > transcode( const std::string& str ) const { std::vector< XMLCh > result; const XMLByte* in = reinterpret_cast< const XMLByte* >( str.c_str() ); const XMLSize_t length = str.length(); XMLCh s[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; unsigned char sizes[ XEUMEULEU_TRANSCODER_BUFFER_SIZE ]; XMLSize_t done = 0; while( done < length ) { Count_t read = 0; XMLSize_t written = transcoder_->transcodeFrom( in + done, length - done, s, XEUMEULEU_TRANSCODER_BUFFER_SIZE, read, sizes ); if( read == 0 ) throw xml::exception( "failed to transcode string" ); done += read; result.insert( result.end(), s, s + written ); } result.resize( result.size() + 4 ); return result; } //@} private: //! @name Copy/Assignment //@{ translate& operator=( const translate& ); //!< Assignment operator //@} private: //! @name Member data //@{ XERCES_CPP_NAMESPACE::Janitor< XERCES_CPP_NAMESPACE::XMLTranscoder > transcoder_; const std::vector< XMLCh > s_; const XMLCh* const ch_; //@} }; inline bool operator==( const XMLCh* const ch, const translate& tr ) { return tr == ch; } inline bool operator==( const std::string& str, const translate& tr ) { return tr == str; } inline bool operator!=( const XMLCh* const ch, const translate& tr ) { return tr != ch; } inline bool operator!=( const std::string& str, const translate& tr ) { return tr != str; } inline std::string operator+( const translate& tr, const std::string& str ) { return std::string( tr ) + str; } inline std::string operator+( const std::string& str, const translate& tr ) { return str + std::string( tr ); } } #endif // xeumeuleu_translate_hpp <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_attribute_output_hpp #define xeumeuleu_attribute_output_hpp #include <xeumeuleu/streams/exception.hpp> #include <xeumeuleu/streams/detail/output_base.hpp> #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Attribute output implementation */ // Created: MAT 2009-11-27 // ============================================================================= class attribute_output : public output_base { public: //! @name Constructors/Destructor //@{ attribute_output( output_base& output, const std::string& attribute ) : output_ ( output ) , attribute_( attribute ) {} virtual ~attribute_output() {} //@} //! @name Operations //@{ virtual void start( const std::string& /*tag*/ ) { throw xml::exception( "Invalid 'start' while writing attribute" ); } virtual void end() { throw xml::exception( "Invalid 'end' while writing attribute" ); } virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); } virtual void write( bool value ) { output_.attribute( attribute_, value ); } virtual void write( int value ) { output_.attribute( attribute_, value ); } virtual void write( long value ) { output_.attribute( attribute_, value ); } virtual void write( long long value ) { output_.attribute( attribute_, value ); } virtual void write( float value ) { output_.attribute( attribute_, value ); } virtual void write( double value ) { output_.attribute( attribute_, value ); } virtual void write( long double value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); } virtual void cdata( const std::string& /*value*/ ) { throw xml::exception( "Invalid 'cdata' while writing attribute" ); } virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ ) { throw xml::exception( "Invalid 'instruction' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, bool /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, float /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void copy( const input_base& /*input*/ ) { throw xml::exception( "Invalid 'copy' while writing attribute" ); } virtual std::auto_ptr< output_base > branch() const { throw xml::exception( "Invalid 'branch' while writing attribute" ); } //@} private: //! @name Copy/Assignment //@{ attribute_output( const attribute_output& ); //!< Copy constructor attribute_output& operator=( const attribute_output& ); //!< Assignment operator //@} private: //! @name Member data //@{ output_base& output_; const std::string& attribute_; //@} }; } #endif // xeumeuleu_attribute_output_hpp /* * Copyright (c) 2009, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_attribute_output_hpp #define xeumeuleu_attribute_output_hpp #include <xeumeuleu/streams/exception.hpp> #include <xeumeuleu/streams/detail/output_base.hpp> #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Attribute output implementation */ // Created: MAT 2009-11-27 // ============================================================================= class attribute_output : public output_base { public: //! @name Constructors/Destructor //@{ attribute_output( output_base& output, const std::string& attribute ) : output_ ( output ) , attribute_( attribute ) {} virtual ~attribute_output() {} //@} //! @name Operations //@{ virtual void start( const std::string& /*tag*/ ) { throw xml::exception( "Invalid 'start' while writing attribute" ); } virtual void end() { throw xml::exception( "Invalid 'end' while writing attribute" ); } virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); } virtual void write( bool value ) { output_.attribute( attribute_, value ); } virtual void write( int value ) { output_.attribute( attribute_, value ); } virtual void write( long value ) { output_.attribute( attribute_, value ); } virtual void write( long long value ) { output_.attribute( attribute_, value ); } virtual void write( float value ) { output_.attribute( attribute_, value ); } virtual void write( double value ) { output_.attribute( attribute_, value ); } virtual void write( long double value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); } virtual void cdata( const std::string& /*value*/ ) { throw xml::exception( "Invalid 'cdata' while writing attribute" ); } virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ ) { throw xml::exception( "Invalid 'instruction' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, bool /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, float /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void copy( const input_base& /*input*/ ) { throw xml::exception( "Invalid 'copy' while writing attribute" ); } virtual std::auto_ptr< output_base > branch() const { throw xml::exception( "Invalid 'branch' while writing attribute" ); } //@} private: //! @name Copy/Assignment //@{ attribute_output( const attribute_output& ); //!< Copy constructor attribute_output& operator=( const attribute_output& ); //!< Assignment operator //@} private: //! @name Member data //@{ output_base& output_; const std::string& attribute_; //@} }; } #endif // xeumeuleu_attribute_output_hpp <commit_msg>Clean-up<commit_after>/* * Copyright (c) 2009, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef xeumeuleu_attribute_output_hpp #define xeumeuleu_attribute_output_hpp #include <xeumeuleu/streams/exception.hpp> #include <xeumeuleu/streams/detail/output_base.hpp> #include <string> namespace xml { // ============================================================================= /** @class output_base @brief Attribute output implementation */ // Created: MAT 2009-11-27 // ============================================================================= class attribute_output : public output_base { public: //! @name Constructors/Destructor //@{ attribute_output( output_base& output, const std::string& attribute ) : output_ ( output ) , attribute_( attribute ) {} virtual ~attribute_output() {} //@} //! @name Operations //@{ virtual void start( const std::string& /*tag*/ ) { throw xml::exception( "Invalid 'start' while writing attribute" ); } virtual void end() { throw xml::exception( "Invalid 'end' while writing attribute" ); } virtual void write( const std::string& value ) { output_.attribute( attribute_, value ); } virtual void write( bool value ) { output_.attribute( attribute_, value ); } virtual void write( int value ) { output_.attribute( attribute_, value ); } virtual void write( long value ) { output_.attribute( attribute_, value ); } virtual void write( long long value ) { output_.attribute( attribute_, value ); } virtual void write( float value ) { output_.attribute( attribute_, value ); } virtual void write( double value ) { output_.attribute( attribute_, value ); } virtual void write( long double value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned int value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long value ) { output_.attribute( attribute_, value ); } virtual void write( unsigned long long value ) { output_.attribute( attribute_, value ); } virtual void cdata( const std::string& /*value*/ ) { throw xml::exception( "Invalid 'cdata' while writing attribute" ); } virtual void instruction( const std::string& /*target*/, const std::string& /*data*/ ) { throw xml::exception( "Invalid 'instruction' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, const std::string& /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, bool /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, float /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, long double /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned int /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void attribute( const std::string& /*name*/, unsigned long long /*value*/ ) { throw xml::exception( "Invalid 'attribute' while writing attribute" ); } virtual void copy( const input_base& /*input*/ ) { throw xml::exception( "Invalid 'copy' while writing attribute" ); } virtual std::auto_ptr< output_base > branch() const { throw xml::exception( "Invalid 'branch' while writing attribute" ); } //@} private: //! @name Copy/Assignment //@{ attribute_output( const attribute_output& ); //!< Copy constructor attribute_output& operator=( const attribute_output& ); //!< Assignment operator //@} private: //! @name Member data //@{ output_base& output_; const std::string& attribute_; //@} }; } #endif // xeumeuleu_attribute_output_hpp <|endoftext|>