text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h>
#include <Core/Logging/Log.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ModuleDialogGeneric::ModuleDialogGeneric(SCIRun::Dataflow::Networks::ModuleStateHandle state, QWidget* parent) : QDialog(parent),
state_(state),
pulling_(false)
{
setModal(false);
if (state_)
{
//TODO: replace with pull_newVersion
LOG_DEBUG("ModuleDialogGeneric connecting to state" << std::endl);
stateConnection_ = state_->connect_state_changed([this]() { pull(); });
}
createExecuteAction();
}
ModuleDialogGeneric::~ModuleDialogGeneric()
{
}
void ModuleDialogGeneric::fixSize()
{
if (minimumWidth() > 0 && minimumHeight() > 0)
{
setFixedSize(minimumWidth(), minimumHeight());
}
}
void ModuleDialogGeneric::createExecuteAction()
{
executeAction_ = new QAction(this);
executeAction_->setText("Execute");
executeAction_->setShortcut(QKeySequence("Ctrl+Shift+E"));
executeAction_->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
connect(executeAction_, SIGNAL(triggered()), this, SIGNAL(executeActionTriggered()));
}
void ModuleDialogGeneric::contextMenuEvent(QContextMenuEvent* e)
{
QMenu menu(this);
menu.addAction(executeAction_);
menu.exec(e->globalPos());
QDialog::contextMenuEvent(e);
}
void ModuleDialogGeneric::addWidgetSlotManager(WidgetSlotManagerPtr ptr)
{
slotManagers_.push_back(ptr);
}
void ModuleDialogGeneric::pull_newVersionToReplaceOld()
{
Pulling p(this);
BOOST_FOREACH(WidgetSlotManagerPtr wsm, slotManagers_)
wsm->pull();
}
class ComboBoxSlotManager : public WidgetSlotManager
{
public:
typedef boost::function<std::string(const QString&)> FromQStringConverter;
typedef boost::function<QString(const std::string&)> ToQStringConverter;
ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,
FromQStringConverter fromLabelConverter = boost::bind(&QString::toStdString, _1),
ToQStringConverter toLabelConverter = &QString::fromStdString) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), fromLabelConverter_(fromLabelConverter), toLabelConverter_(toLabelConverter)
{
connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));
}
ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,
const GuiStringTranslationMap& stringMap) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), stringMap_(stringMap)
{
fromLabelConverter_ = [this](const QString& qstr) { return stringMap_.left.at(qstr.toStdString()); };
toLabelConverter_ = [this](const std::string& str) { return QString::fromStdString(stringMap_.right.at(str)); };
connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto value = state_->getValue(stateKey_).toString();
auto qstring = toLabelConverter_(value);
if (qstring != comboBox_->currentText())
{
LOG_DEBUG("In new version of pull code for combobox: " << value);
comboBox_->setCurrentIndex(comboBox_->findText(qstring));
}
}
virtual void pushImpl() override
{
auto label = fromLabelConverter_(comboBox_->currentText());
if (label != state_->getValue(stateKey_).toString())
{
LOG_DEBUG("In new version of push code for combobox: " << label);
state_->setValue(stateKey_, label);
}
}
private:
AlgorithmParameterName stateKey_;
QComboBox* comboBox_;
FromQStringConverter fromLabelConverter_;
ToQStringConverter toLabelConverter_;
GuiStringTranslationMap stringMap_;
};
void ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox));
}
void ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey, const GuiStringTranslationMap& stringMap)
{
addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox, stringMap));
}
// ASSUMEs true state = comboBox index 1, false state = comboBox index 0.
class TwoChoiceBooleanComboBoxSlotManager : public WidgetSlotManager
{
public:
TwoChoiceBooleanComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox)
{
connect(comboBox, SIGNAL(activated(int)), this, SLOT(push()));
}
virtual void pull() override
{
auto value = state_->getValue(stateKey_).toBool();
auto index = value ? 1 : 0;
if (index != comboBox_->currentIndex())
{
LOG_DEBUG("In new version of pull code for combobox, boolean mode: " << index);
comboBox_->setCurrentIndex(index);
}
}
virtual void pushImpl() override
{
auto index = comboBox_->currentIndex();
if (index != (state_->getValue(stateKey_).toBool() ? 1 : 0))
{
LOG_DEBUG("In new version of push code for combobox, boolean mode: " << index);
state_->setValue(stateKey_, index == 1);
}
}
private:
AlgorithmParameterName stateKey_;
QComboBox* comboBox_;
};
void ModuleDialogGeneric::addTwoChoiceBooleanComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<TwoChoiceBooleanComboBoxSlotManager>(state_, *this, stateKey, comboBox));
}
class TextEditSlotManager : public WidgetSlotManager
{
public:
TextEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QTextEdit* textEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), textEdit_(textEdit)
{
connect(textEdit, SIGNAL(textChanged()), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());
if (newValue != textEdit_->toPlainText())
{
textEdit_->setPlainText(newValue);
LOG_DEBUG("In new version of pull code for TextEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for TextEdit: " << textEdit_->toPlainText().toStdString());
state_->setValue(stateKey_, textEdit_->toPlainText().toStdString());
}
private:
AlgorithmParameterName stateKey_;
QTextEdit* textEdit_;
};
void ModuleDialogGeneric::addTextEditManager(QTextEdit* textEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<TextEditSlotManager>(state_, *this, stateKey, textEdit));
}
class LineEditSlotManager : public WidgetSlotManager
{
public:
LineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)
{
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());
if (newValue != lineEdit_->text())
{
lineEdit_->setText(newValue);
LOG_DEBUG("In new version of pull code for LineEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for LineEdit: " << lineEdit_->text().toStdString());
state_->setValue(stateKey_, lineEdit_->text().toStdString());
}
private:
AlgorithmParameterName stateKey_;
QLineEdit* lineEdit_;
};
void ModuleDialogGeneric::addLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<LineEditSlotManager>(state_, *this, stateKey, lineEdit));
}
class DoubleLineEditSlotManager : public WidgetSlotManager
{
public:
DoubleLineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)
{
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::number(state_->getValue(stateKey_).toDouble());
if (newValue != lineEdit_->text())
{
lineEdit_->setText(newValue);
LOG_DEBUG("In new version of pull code for DoubleLineEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for LineEdit: " << lineEdit_->text().toStdString());
state_->setValue(stateKey_, boost::lexical_cast<double>(lineEdit_->text().toStdString()));
}
private:
AlgorithmParameterName stateKey_;
QLineEdit* lineEdit_;
};
void ModuleDialogGeneric::addDoubleLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<DoubleLineEditSlotManager>(state_, *this, stateKey, lineEdit));
}
class SpinBoxSlotManager : public WidgetSlotManager
{
public:
SpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QSpinBox* spinBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)
{
connect(spinBox_, SIGNAL(valueChanged(int)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = state_->getValue(stateKey_).toInt();
if (newValue != spinBox_->value())
{
spinBox_->setValue(newValue);
LOG_DEBUG("In new version of pull code for SpinBox: " << newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for SpinBox: " << spinBox_->value());
state_->setValue(stateKey_, spinBox_->value());
}
private:
AlgorithmParameterName stateKey_;
QSpinBox* spinBox_;
};
void ModuleDialogGeneric::addSpinBoxManager(QSpinBox* spinBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<SpinBoxSlotManager>(state_, *this, stateKey, spinBox));
}
class DoubleSpinBoxSlotManager : public WidgetSlotManager
{
public:
DoubleSpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QDoubleSpinBox* spinBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)
{
connect(spinBox_, SIGNAL(valueChanged(double)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = state_->getValue(stateKey_).toDouble();
if (newValue != spinBox_->value())
{
spinBox_->setValue(newValue);
LOG_DEBUG("In new version of pull code for DoubleSpinBox: " << newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for DoubleSpinBox: " << spinBox_->value());
state_->setValue(stateKey_, spinBox_->value());
}
private:
AlgorithmParameterName stateKey_;
QDoubleSpinBox* spinBox_;
};
void ModuleDialogGeneric::addDoubleSpinBoxManager(QDoubleSpinBox* spinBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<DoubleSpinBoxSlotManager>(state_, *this, stateKey, spinBox));
}
class CheckBoxSlotManager : public WidgetSlotManager
{
public:
CheckBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QCheckBox* checkBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), checkBox_(checkBox)
{
connect(checkBox_, SIGNAL(stateChanged(int)), this, SLOT(push()));
}
virtual void pull() override
{
bool newValue = state_->getValue(stateKey_).toBool();
if (newValue != checkBox_->isChecked())
{
LOG_DEBUG("In new version of pull code for CheckBox: " << newValue);
checkBox_->setChecked(newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for CheckBox: " << checkBox_->isChecked());
state_->setValue(stateKey_, checkBox_->isChecked());
}
private:
AlgorithmParameterName stateKey_;
QCheckBox* checkBox_;
};
void ModuleDialogGeneric::addCheckBoxManager(QCheckBox* checkBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<CheckBoxSlotManager>(state_, *this, stateKey, checkBox));
}
class CheckableButtonSlotManager : public WidgetSlotManager
{
public:
CheckableButtonSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QAbstractButton* checkable) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), checkable_(checkable)
{
connect(checkable_, SIGNAL(clicked()), this, SLOT(push()));
}
virtual void pull() override
{
bool newValue = state_->getValue(stateKey_).toBool();
if (newValue != checkable_->isChecked())
{
LOG_DEBUG("In new version of pull code for checkable QAbstractButton: " << newValue);
checkable_->setChecked(newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for checkable QAbstractButton: " << checkable_->isChecked());
state_->setValue(stateKey_, checkable_->isChecked());
}
private:
AlgorithmParameterName stateKey_;
QAbstractButton* checkable_;
};
void ModuleDialogGeneric::addCheckableButtonManager(QAbstractButton* checkable, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<CheckableButtonSlotManager>(state_, *this, stateKey, checkable));
}
<commit_msg>Shortcut no work on Mac<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Interface/Modules/Base/ModuleDialogGeneric.h>
#include <Core/Logging/Log.h>
#include <boost/foreach.hpp>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms;
ModuleDialogGeneric::ModuleDialogGeneric(SCIRun::Dataflow::Networks::ModuleStateHandle state, QWidget* parent) : QDialog(parent),
state_(state),
pulling_(false)
{
setModal(false);
if (state_)
{
//TODO: replace with pull_newVersion
LOG_DEBUG("ModuleDialogGeneric connecting to state" << std::endl);
stateConnection_ = state_->connect_state_changed([this]() { pull(); });
}
createExecuteAction();
}
ModuleDialogGeneric::~ModuleDialogGeneric()
{
}
void ModuleDialogGeneric::fixSize()
{
if (minimumWidth() > 0 && minimumHeight() > 0)
{
setFixedSize(minimumWidth(), minimumHeight());
}
}
void ModuleDialogGeneric::createExecuteAction()
{
executeAction_ = new QAction(this);
executeAction_->setText("Execute");
//TODO: doesn't work on Mac
//executeAction_->setShortcut(QKeySequence("Ctrl+1"));
executeAction_->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));
connect(executeAction_, SIGNAL(triggered()), this, SIGNAL(executeActionTriggered()));
}
void ModuleDialogGeneric::contextMenuEvent(QContextMenuEvent* e)
{
QMenu menu(this);
menu.addAction(executeAction_);
menu.exec(e->globalPos());
QDialog::contextMenuEvent(e);
}
void ModuleDialogGeneric::addWidgetSlotManager(WidgetSlotManagerPtr ptr)
{
slotManagers_.push_back(ptr);
}
void ModuleDialogGeneric::pull_newVersionToReplaceOld()
{
Pulling p(this);
BOOST_FOREACH(WidgetSlotManagerPtr wsm, slotManagers_)
wsm->pull();
}
class ComboBoxSlotManager : public WidgetSlotManager
{
public:
typedef boost::function<std::string(const QString&)> FromQStringConverter;
typedef boost::function<QString(const std::string&)> ToQStringConverter;
ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,
FromQStringConverter fromLabelConverter = boost::bind(&QString::toStdString, _1),
ToQStringConverter toLabelConverter = &QString::fromStdString) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), fromLabelConverter_(fromLabelConverter), toLabelConverter_(toLabelConverter)
{
connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));
}
ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,
const GuiStringTranslationMap& stringMap) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), stringMap_(stringMap)
{
fromLabelConverter_ = [this](const QString& qstr) { return stringMap_.left.at(qstr.toStdString()); };
toLabelConverter_ = [this](const std::string& str) { return QString::fromStdString(stringMap_.right.at(str)); };
connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto value = state_->getValue(stateKey_).toString();
auto qstring = toLabelConverter_(value);
if (qstring != comboBox_->currentText())
{
LOG_DEBUG("In new version of pull code for combobox: " << value);
comboBox_->setCurrentIndex(comboBox_->findText(qstring));
}
}
virtual void pushImpl() override
{
auto label = fromLabelConverter_(comboBox_->currentText());
if (label != state_->getValue(stateKey_).toString())
{
LOG_DEBUG("In new version of push code for combobox: " << label);
state_->setValue(stateKey_, label);
}
}
private:
AlgorithmParameterName stateKey_;
QComboBox* comboBox_;
FromQStringConverter fromLabelConverter_;
ToQStringConverter toLabelConverter_;
GuiStringTranslationMap stringMap_;
};
void ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox));
}
void ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey, const GuiStringTranslationMap& stringMap)
{
addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox, stringMap));
}
// ASSUMEs true state = comboBox index 1, false state = comboBox index 0.
class TwoChoiceBooleanComboBoxSlotManager : public WidgetSlotManager
{
public:
TwoChoiceBooleanComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox)
{
connect(comboBox, SIGNAL(activated(int)), this, SLOT(push()));
}
virtual void pull() override
{
auto value = state_->getValue(stateKey_).toBool();
auto index = value ? 1 : 0;
if (index != comboBox_->currentIndex())
{
LOG_DEBUG("In new version of pull code for combobox, boolean mode: " << index);
comboBox_->setCurrentIndex(index);
}
}
virtual void pushImpl() override
{
auto index = comboBox_->currentIndex();
if (index != (state_->getValue(stateKey_).toBool() ? 1 : 0))
{
LOG_DEBUG("In new version of push code for combobox, boolean mode: " << index);
state_->setValue(stateKey_, index == 1);
}
}
private:
AlgorithmParameterName stateKey_;
QComboBox* comboBox_;
};
void ModuleDialogGeneric::addTwoChoiceBooleanComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<TwoChoiceBooleanComboBoxSlotManager>(state_, *this, stateKey, comboBox));
}
class TextEditSlotManager : public WidgetSlotManager
{
public:
TextEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QTextEdit* textEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), textEdit_(textEdit)
{
connect(textEdit, SIGNAL(textChanged()), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());
if (newValue != textEdit_->toPlainText())
{
textEdit_->setPlainText(newValue);
LOG_DEBUG("In new version of pull code for TextEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for TextEdit: " << textEdit_->toPlainText().toStdString());
state_->setValue(stateKey_, textEdit_->toPlainText().toStdString());
}
private:
AlgorithmParameterName stateKey_;
QTextEdit* textEdit_;
};
void ModuleDialogGeneric::addTextEditManager(QTextEdit* textEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<TextEditSlotManager>(state_, *this, stateKey, textEdit));
}
class LineEditSlotManager : public WidgetSlotManager
{
public:
LineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)
{
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());
if (newValue != lineEdit_->text())
{
lineEdit_->setText(newValue);
LOG_DEBUG("In new version of pull code for LineEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for LineEdit: " << lineEdit_->text().toStdString());
state_->setValue(stateKey_, lineEdit_->text().toStdString());
}
private:
AlgorithmParameterName stateKey_;
QLineEdit* lineEdit_;
};
void ModuleDialogGeneric::addLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<LineEditSlotManager>(state_, *this, stateKey, lineEdit));
}
class DoubleLineEditSlotManager : public WidgetSlotManager
{
public:
DoubleLineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)
{
connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = QString::number(state_->getValue(stateKey_).toDouble());
if (newValue != lineEdit_->text())
{
lineEdit_->setText(newValue);
LOG_DEBUG("In new version of pull code for DoubleLineEdit: " << newValue.toStdString());
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for LineEdit: " << lineEdit_->text().toStdString());
state_->setValue(stateKey_, boost::lexical_cast<double>(lineEdit_->text().toStdString()));
}
private:
AlgorithmParameterName stateKey_;
QLineEdit* lineEdit_;
};
void ModuleDialogGeneric::addDoubleLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<DoubleLineEditSlotManager>(state_, *this, stateKey, lineEdit));
}
class SpinBoxSlotManager : public WidgetSlotManager
{
public:
SpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QSpinBox* spinBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)
{
connect(spinBox_, SIGNAL(valueChanged(int)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = state_->getValue(stateKey_).toInt();
if (newValue != spinBox_->value())
{
spinBox_->setValue(newValue);
LOG_DEBUG("In new version of pull code for SpinBox: " << newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for SpinBox: " << spinBox_->value());
state_->setValue(stateKey_, spinBox_->value());
}
private:
AlgorithmParameterName stateKey_;
QSpinBox* spinBox_;
};
void ModuleDialogGeneric::addSpinBoxManager(QSpinBox* spinBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<SpinBoxSlotManager>(state_, *this, stateKey, spinBox));
}
class DoubleSpinBoxSlotManager : public WidgetSlotManager
{
public:
DoubleSpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QDoubleSpinBox* spinBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)
{
connect(spinBox_, SIGNAL(valueChanged(double)), this, SLOT(push()));
}
virtual void pull() override
{
auto newValue = state_->getValue(stateKey_).toDouble();
if (newValue != spinBox_->value())
{
spinBox_->setValue(newValue);
LOG_DEBUG("In new version of pull code for DoubleSpinBox: " << newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for DoubleSpinBox: " << spinBox_->value());
state_->setValue(stateKey_, spinBox_->value());
}
private:
AlgorithmParameterName stateKey_;
QDoubleSpinBox* spinBox_;
};
void ModuleDialogGeneric::addDoubleSpinBoxManager(QDoubleSpinBox* spinBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<DoubleSpinBoxSlotManager>(state_, *this, stateKey, spinBox));
}
class CheckBoxSlotManager : public WidgetSlotManager
{
public:
CheckBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QCheckBox* checkBox) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), checkBox_(checkBox)
{
connect(checkBox_, SIGNAL(stateChanged(int)), this, SLOT(push()));
}
virtual void pull() override
{
bool newValue = state_->getValue(stateKey_).toBool();
if (newValue != checkBox_->isChecked())
{
LOG_DEBUG("In new version of pull code for CheckBox: " << newValue);
checkBox_->setChecked(newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for CheckBox: " << checkBox_->isChecked());
state_->setValue(stateKey_, checkBox_->isChecked());
}
private:
AlgorithmParameterName stateKey_;
QCheckBox* checkBox_;
};
void ModuleDialogGeneric::addCheckBoxManager(QCheckBox* checkBox, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<CheckBoxSlotManager>(state_, *this, stateKey, checkBox));
}
class CheckableButtonSlotManager : public WidgetSlotManager
{
public:
CheckableButtonSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QAbstractButton* checkable) :
WidgetSlotManager(state, dialog), stateKey_(stateKey), checkable_(checkable)
{
connect(checkable_, SIGNAL(clicked()), this, SLOT(push()));
}
virtual void pull() override
{
bool newValue = state_->getValue(stateKey_).toBool();
if (newValue != checkable_->isChecked())
{
LOG_DEBUG("In new version of pull code for checkable QAbstractButton: " << newValue);
checkable_->setChecked(newValue);
}
}
virtual void pushImpl() override
{
LOG_DEBUG("In new version of push code for checkable QAbstractButton: " << checkable_->isChecked());
state_->setValue(stateKey_, checkable_->isChecked());
}
private:
AlgorithmParameterName stateKey_;
QAbstractButton* checkable_;
};
void ModuleDialogGeneric::addCheckableButtonManager(QAbstractButton* checkable, const AlgorithmParameterName& stateKey)
{
addWidgetSlotManager(boost::make_shared<CheckableButtonSlotManager>(state_, *this, stateKey, checkable));
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name: process.cpp
// Purpose: Implementation of class wxExProcess
// Author: Anton van Wezenbeek
// Copyright: (c) 2016 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/process.h>
#include <wx/timer.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/process.h>
#include <wx/extension/debug.h>
#include <wx/extension/defs.h>
#include <wx/extension/itemdlg.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
#define GET_STREAM(SCOPE) \
{ \
if (Is##SCOPE##Available()) \
{ \
wxTextInputStream tis(*Get##SCOPE##Stream()); \
\
while (Is##SCOPE##Available()) \
{ \
const char c = tis.GetChar(); \
\
if (c != 0) \
{ \
text += c; \
} \
} \
} \
}; \
class wxExProcessImp : public wxProcess
{
public:
wxExProcessImp(wxExManagedFrame* frame, wxExShell* shell, bool debug)
: wxProcess(wxPROCESS_REDIRECT)
, m_Debug(debug)
, m_Frame(frame)
, m_Shell(shell)
, m_Timer(std::make_unique<wxTimer>(this)) {
Bind(wxEVT_TIMER, [=](wxTimerEvent& event) {Read();});};
virtual ~wxExProcessImp() {;};
bool Execute(const std::string& command, const std::string& path);
bool Kill();
static int KillAll();
void Read();
bool Write(const std::string& text);
private:
void HandleCommand(const wxString& command);
virtual void OnTerminate(int pid, int status) override {
const auto it = find (m_pids.begin(), m_pids.end(), pid);
if (it != m_pids.end())
{
m_pids.erase(it);
}
m_Timer->Stop();
Read();};
const bool m_Debug;
std::string m_Command, m_StdIn;
wxExManagedFrame* m_Frame;
wxExShell* m_Shell;
std::unique_ptr<wxTimer> m_Timer;
wxCriticalSection m_Critical;
static std::vector<int> m_pids;
};
bool ShowProcess(wxExManagedFrame* frame, bool show)
{
if (frame != nullptr)
{
frame->ShowPane("PROCESS", show);
return true;
}
return false;
}
std::vector<int> wxExProcessImp::m_pids;
wxExShell* wxExProcess::m_Shell = nullptr;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");
wxExProcess::wxExProcess()
: m_Command(wxExConfigFirstOf(_("Process")))
, m_Frame(dynamic_cast<wxExManagedFrame*>(wxTheApp->GetTopWindow()))
{
}
wxExProcess::~wxExProcess()
{
}
wxExProcess::wxExProcess(const wxExProcess& process)
{
*this = process;
}
wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
if (this != &p)
{
m_Command = p.m_Command;
m_Error = p.m_Error;
m_StdErr = p.m_StdErr;
m_StdOut = p.m_StdOut;
}
return *this;
}
int wxExProcess::ConfigDialog(
wxWindow* parent,
const wxString& title,
bool modal)
{
wxExItem ci(_("Process"), ITEM_COMBOBOX, wxAny(), true);
wxTextValidator validator(wxFILTER_EXCLUDE_CHAR_LIST);
validator.SetCharExcludes("?%*\"");
ci.SetValidator(&validator);
const std::vector<wxExItem> v {
ci,
{m_WorkingDirKey, ITEM_COMBOBOX_DIR, wxAny(), true, wxWindow::NewControlId()}};
if (modal)
{
return wxExItemDialog(parent, v, title).ShowModal();
}
else
{
wxExItemDialog* dlg = new wxExItemDialog(parent, v, title);
return dlg->Show();
}
}
bool wxExProcess::Execute(
const std::string& command,
bool wait,
const std::string& wd)
{
m_Error = false;
std::string cwd(wd);
if (command.empty())
{
if (wxExConfigFirstOf(_("Process")).empty())
{
if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
{
return false;
}
}
m_Command = wxExConfigFirstOf(_("Process"));
cwd = wxExConfigFirstOf(m_WorkingDirKey);
}
else
{
m_Command = command;
}
if (!wait)
{
// We need a shell for output.
if (m_Shell == nullptr) return false;
m_Shell->EnableShell(true);
m_Shell->SetProcess(this);
m_Shell->SetName(m_Command);
m_Shell->SetPrompt(
// a unix shell itself has no prompt, so put one here
m_Command.find("bash") == 0 ||
m_Command.find("csh") == 0 ||
m_Command.find("ksh") == 0 ||
m_Command.find("tcsh") == 0 ||
m_Command.find("sh") == 0 ? ">" : "");
m_Process = std::make_unique<wxExProcessImp>(m_Frame, m_Shell, command == "gdb");
if (!m_Process->Execute(m_Command, wd))
{
m_Process.release();
m_Error = true;
}
}
else
{
wxArrayString output;
wxArrayString errors;
struct wxExecuteEnv env;
env.cwd = wd;
if (wxExecute(m_Command, output, errors, wxEXEC_SYNC, &env) == -1)
{
m_StdErr.clear();
m_StdOut.clear();
m_Error = true;
}
else
{
// Set output by converting array strings into normal strings.
m_StdOut = wxJoin(output, '\n', '\n');
m_StdErr = wxJoin(errors, '\n', '\n');
}
if (m_Shell != nullptr)
{
m_Shell->EnableShell(false);
}
}
return !m_Error;
}
bool wxExProcess::IsRunning() const
{
return m_Process != nullptr && wxProcess::Exists(m_Process->GetPid());
}
bool wxExProcess::Kill()
{
bool killed = false;
if (m_Process != nullptr)
{
killed = m_Process->Kill();
m_Process.release();
}
ShowProcess(m_Frame, false);
return killed;
}
int wxExProcess::KillAll()
{
return wxExProcessImp::KillAll();
}
void wxExProcess::PrepareOutput(wxWindow* parent)
{
if (m_Shell == nullptr)
{
m_Shell = new wxExShell(parent,
std::string(),
std::string(),
true,
100);
}
}
#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
if (!m_Error)
{
if (m_Shell != nullptr && ShowProcess(m_Frame, true))
{
m_Shell->AppendText(m_StdOut);
}
else
{
std::cout << m_StdOut << "\n";
}
}
else
{
// Executing command failed, so no output,
// show failing command.
wxLogError("Could not execute: %s", m_Command.c_str());
}
}
#endif
bool wxExProcess::Write(const std::string& text)
{
if (!IsRunning())
{
wxLogStatus("Process is not running");
return false;
}
m_Process->Write(text);
if (!IsRunning())
{
ShowProcess(m_Frame, false);
}
return true;
}
// Implementation.
bool wxExProcessImp::Execute(
const std::string& command, const std::string& path)
{
struct wxExecuteEnv env;
env.cwd = path;
m_Command = command;
if (wxExecute(command, wxEXEC_ASYNC, this, &env) <= 0)
{
return false;
}
m_pids.push_back(GetPid());
ShowProcess(m_Frame, true);
m_Timer->Start(100); // milliseconds
m_Shell->SetFocus();
return true;
}
void wxExProcessImp::HandleCommand(const wxString& command)
{
wxString rest;
if (
command.StartsWith("cd", &rest)
#ifdef __WXMSW__
|| command.StartsWith("chdir", &rest)
#endif
)
{
wxLogNull logNo;
rest.Trim(false);
rest.Trim(true);
if (rest.empty() || rest == "~")
{
#ifdef __WXMSW__
#else
wxSetWorkingDirectory(wxGetHomeDir());
#endif
}
else
{
wxSetWorkingDirectory(rest);
}
}
}
bool wxExProcessImp::Kill()
{
int pid = GetPid();
if (wxProcess::Kill(pid, wxSIGKILL) != wxKILL_OK)
{
return false;
}
const auto it = find (m_pids.begin(), m_pids.end(), pid);
if (it != m_pids.end())
{
m_pids.erase(it);
}
return true;
}
int wxExProcessImp::KillAll()
{
int killed = 0;
for (auto pid : m_pids)
{
if (wxProcess::Kill(pid, wxSIGKILL) == wxKILL_OK)
{
killed++;
}
}
if (killed != m_pids.size())
{
std::cout << "could not kill all processes\n";
}
return killed;
}
void wxExProcessImp::Read()
{
wxCriticalSectionLocker lock(m_Critical);
std::string text;
GET_STREAM(Input);
GET_STREAM(Error);
if (!text.empty())
{
m_Shell->AppendText(
// prevent echo of last input
!m_StdIn.empty() && text.find(m_StdIn) == 0 ?
text.substr(m_StdIn.length()):
text);
if (m_Debug && m_Frame != nullptr)
{
m_Frame->GetDebug()->ProcessStdOut(text);
}
}
if (!m_StdIn.empty())
{
m_StdIn.clear();
m_Shell->Prompt(std::string(), false);
}
}
bool wxExProcessImp::Write(const std::string& text)
{
m_Timer->Stop();
if (m_Command.find("cmd") == 0 ||
m_Command.find("powershell") == 0)
{
m_Shell->DocumentEnd();
}
// Write text to process and restart timer.
wxOutputStream* os = GetOutputStream();
if (os != nullptr)
{
HandleCommand(text);
if (m_Debug && m_Frame != nullptr)
{
m_Frame->GetDebug()->ProcessStdIn(text);
}
const std::string el = (text.size() == 1 && text[0] == 3 ? std::string(): std::string("\n"));
wxTextOutputStream(*os).WriteString(text + el);
m_StdIn = text;
wxMilliSleep(10);
Read();
m_Timer->Start();
}
return true;
}
<commit_msg>use std::find<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name: process.cpp
// Purpose: Implementation of class wxExProcess
// Author: Anton van Wezenbeek
// Copyright: (c) 2016 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/process.h>
#include <wx/timer.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/process.h>
#include <wx/extension/debug.h>
#include <wx/extension/defs.h>
#include <wx/extension/itemdlg.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/shell.h>
#include <wx/extension/util.h> // for wxExConfigFirstOf
#define GET_STREAM(SCOPE) \
{ \
if (Is##SCOPE##Available()) \
{ \
wxTextInputStream tis(*Get##SCOPE##Stream()); \
\
while (Is##SCOPE##Available()) \
{ \
const char c = tis.GetChar(); \
\
if (c != 0) \
{ \
text += c; \
} \
} \
} \
}; \
class wxExProcessImp : public wxProcess
{
public:
wxExProcessImp(wxExManagedFrame* frame, wxExShell* shell, bool debug)
: wxProcess(wxPROCESS_REDIRECT)
, m_Debug(debug)
, m_Frame(frame)
, m_Shell(shell)
, m_Timer(std::make_unique<wxTimer>(this)) {
Bind(wxEVT_TIMER, [=](wxTimerEvent& event) {Read();});};
virtual ~wxExProcessImp() {;};
bool Execute(const std::string& command, const std::string& path);
bool Kill();
static int KillAll();
void Read();
bool Write(const std::string& text);
private:
void HandleCommand(const wxString& command);
virtual void OnTerminate(int pid, int status) override {
const auto it = std::find(m_pids.begin(), m_pids.end(), pid);
if (it != m_pids.end())
{
m_pids.erase(it);
}
m_Timer->Stop();
Read();};
const bool m_Debug;
std::string m_Command, m_StdIn;
wxExManagedFrame* m_Frame;
wxExShell* m_Shell;
std::unique_ptr<wxTimer> m_Timer;
wxCriticalSection m_Critical;
static std::vector<int> m_pids;
};
bool ShowProcess(wxExManagedFrame* frame, bool show)
{
if (frame != nullptr)
{
frame->ShowPane("PROCESS", show);
return true;
}
return false;
}
std::vector<int> wxExProcessImp::m_pids;
wxExShell* wxExProcess::m_Shell = nullptr;
wxString wxExProcess::m_WorkingDirKey = _("Process folder");
wxExProcess::wxExProcess()
: m_Command(wxExConfigFirstOf(_("Process")))
, m_Frame(dynamic_cast<wxExManagedFrame*>(wxTheApp->GetTopWindow()))
{
}
wxExProcess::~wxExProcess()
{
}
wxExProcess::wxExProcess(const wxExProcess& process)
{
*this = process;
}
wxExProcess& wxExProcess::operator=(const wxExProcess& p)
{
if (this != &p)
{
m_Command = p.m_Command;
m_Error = p.m_Error;
m_StdErr = p.m_StdErr;
m_StdOut = p.m_StdOut;
}
return *this;
}
int wxExProcess::ConfigDialog(
wxWindow* parent,
const wxString& title,
bool modal)
{
wxExItem ci(_("Process"), ITEM_COMBOBOX, wxAny(), true);
wxTextValidator validator(wxFILTER_EXCLUDE_CHAR_LIST);
validator.SetCharExcludes("?%*\"");
ci.SetValidator(&validator);
const std::vector<wxExItem> v {
ci,
{m_WorkingDirKey, ITEM_COMBOBOX_DIR, wxAny(), true, wxWindow::NewControlId()}};
if (modal)
{
return wxExItemDialog(parent, v, title).ShowModal();
}
else
{
wxExItemDialog* dlg = new wxExItemDialog(parent, v, title);
return dlg->Show();
}
}
bool wxExProcess::Execute(
const std::string& command,
bool wait,
const std::string& wd)
{
m_Error = false;
std::string cwd(wd);
if (command.empty())
{
if (wxExConfigFirstOf(_("Process")).empty())
{
if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)
{
return false;
}
}
m_Command = wxExConfigFirstOf(_("Process"));
cwd = wxExConfigFirstOf(m_WorkingDirKey);
}
else
{
m_Command = command;
}
if (!wait)
{
// We need a shell for output.
if (m_Shell == nullptr) return false;
m_Shell->EnableShell(true);
m_Shell->SetProcess(this);
m_Shell->SetName(m_Command);
m_Shell->SetPrompt(
// a unix shell itself has no prompt, so put one here
m_Command.find("bash") == 0 ||
m_Command.find("csh") == 0 ||
m_Command.find("ksh") == 0 ||
m_Command.find("tcsh") == 0 ||
m_Command.find("sh") == 0 ? ">" : "");
m_Process = std::make_unique<wxExProcessImp>(m_Frame, m_Shell, command == "gdb");
if (!m_Process->Execute(m_Command, wd))
{
m_Process.release();
m_Error = true;
}
}
else
{
wxArrayString output;
wxArrayString errors;
struct wxExecuteEnv env;
env.cwd = wd;
if (wxExecute(m_Command, output, errors, wxEXEC_SYNC, &env) == -1)
{
m_StdErr.clear();
m_StdOut.clear();
m_Error = true;
}
else
{
// Set output by converting array strings into normal strings.
m_StdOut = wxJoin(output, '\n', '\n');
m_StdErr = wxJoin(errors, '\n', '\n');
}
if (m_Shell != nullptr)
{
m_Shell->EnableShell(false);
}
}
return !m_Error;
}
bool wxExProcess::IsRunning() const
{
return m_Process != nullptr && wxProcess::Exists(m_Process->GetPid());
}
bool wxExProcess::Kill()
{
bool killed = false;
if (m_Process != nullptr)
{
killed = m_Process->Kill();
m_Process.release();
}
ShowProcess(m_Frame, false);
return killed;
}
int wxExProcess::KillAll()
{
return wxExProcessImp::KillAll();
}
void wxExProcess::PrepareOutput(wxWindow* parent)
{
if (m_Shell == nullptr)
{
m_Shell = new wxExShell(parent,
std::string(),
std::string(),
true,
100);
}
}
#if wxUSE_GUI
void wxExProcess::ShowOutput(const wxString& caption) const
{
if (!m_Error)
{
if (m_Shell != nullptr && ShowProcess(m_Frame, true))
{
m_Shell->AppendText(m_StdOut);
}
else
{
std::cout << m_StdOut << "\n";
}
}
else
{
// Executing command failed, so no output,
// show failing command.
wxLogError("Could not execute: %s", m_Command.c_str());
}
}
#endif
bool wxExProcess::Write(const std::string& text)
{
if (!IsRunning())
{
wxLogStatus("Process is not running");
return false;
}
m_Process->Write(text);
if (!IsRunning())
{
ShowProcess(m_Frame, false);
}
return true;
}
// Implementation.
bool wxExProcessImp::Execute(
const std::string& command, const std::string& path)
{
struct wxExecuteEnv env;
env.cwd = path;
m_Command = command;
if (wxExecute(command, wxEXEC_ASYNC, this, &env) <= 0)
{
return false;
}
m_pids.push_back(GetPid());
ShowProcess(m_Frame, true);
m_Timer->Start(100); // milliseconds
m_Shell->SetFocus();
return true;
}
void wxExProcessImp::HandleCommand(const wxString& command)
{
wxString rest;
if (
command.StartsWith("cd", &rest)
#ifdef __WXMSW__
|| command.StartsWith("chdir", &rest)
#endif
)
{
wxLogNull logNo;
rest.Trim(false);
rest.Trim(true);
if (rest.empty() || rest == "~")
{
#ifdef __WXMSW__
#else
wxSetWorkingDirectory(wxGetHomeDir());
#endif
}
else
{
wxSetWorkingDirectory(rest);
}
}
}
bool wxExProcessImp::Kill()
{
int pid = GetPid();
if (wxProcess::Kill(pid, wxSIGKILL) != wxKILL_OK)
{
return false;
}
const auto it = std::find(m_pids.begin(), m_pids.end(), pid);
if (it != m_pids.end())
{
m_pids.erase(it);
}
return true;
}
int wxExProcessImp::KillAll()
{
int killed = 0;
for (auto pid : m_pids)
{
if (wxProcess::Kill(pid, wxSIGKILL) == wxKILL_OK)
{
killed++;
}
}
if (killed != m_pids.size())
{
std::cout << "could not kill all processes\n";
}
return killed;
}
void wxExProcessImp::Read()
{
wxCriticalSectionLocker lock(m_Critical);
std::string text;
GET_STREAM(Input);
GET_STREAM(Error);
if (!text.empty())
{
m_Shell->AppendText(
// prevent echo of last input
!m_StdIn.empty() && text.find(m_StdIn) == 0 ?
text.substr(m_StdIn.length()):
text);
if (m_Debug && m_Frame != nullptr)
{
m_Frame->GetDebug()->ProcessStdOut(text);
}
}
if (!m_StdIn.empty())
{
m_StdIn.clear();
m_Shell->Prompt(std::string(), false);
}
}
bool wxExProcessImp::Write(const std::string& text)
{
m_Timer->Stop();
if (m_Command.find("cmd") == 0 ||
m_Command.find("powershell") == 0)
{
m_Shell->DocumentEnd();
}
// Write text to process and restart timer.
wxOutputStream* os = GetOutputStream();
if (os != nullptr)
{
HandleCommand(text);
if (m_Debug && m_Frame != nullptr)
{
m_Frame->GetDebug()->ProcessStdIn(text);
}
const std::string el = (text.size() == 1 && text[0] == 3 ? std::string(): std::string("\n"));
wxTextOutputStream(*os).WriteString(text + el);
m_StdIn = text;
wxMilliSleep(10);
Read();
m_Timer->Start();
}
return true;
}
<|endoftext|>
|
<commit_before>#include "time.hpp"
#include <inttypes.h>
#ifndef _MSC_VER
#include <sys/time.h>
#endif
#ifdef __MACH__
#include <mach/mach_time.h>
#include "thread_local.hpp"
#include "utils.hpp"
#endif
#include "config/args.hpp"
#include "errors.hpp"
#ifdef _MSC_VER
microtime_t current_microtime() {
FILETIME time;
#if _WIN32_WINNT >= 0x602 // Windows 8
GetSystemTimePreciseAsFileTime(&time);
#else
GetSystemTimeAsFileTime(&time);
#endif
ULARGE_INTEGER nanos100;
nanos100.LowPart = time.dwLowDateTime;
nanos100.HighPart = time.dwHighDateTime;
return nanos100.QuadPart / 10;
}
#else
microtime_t current_microtime() {
// This could be done more efficiently, surely.
struct timeval t;
DEBUG_VAR int res = gettimeofday(&t, nullptr);
rassert(0 == res);
return uint64_t(t.tv_sec) * MILLION + t.tv_usec;
}
#endif
ticks_t secs_to_ticks(time_t secs) {
return static_cast<ticks_t>(secs) * BILLION;
}
#ifdef __MACH__
TLS(mach_timebase_info_data_t, mach_time_info);
#endif // __MACH__
timespec clock_monotonic() {
#ifdef __MACH__
mach_timebase_info_data_t mach_time_info = TLS_get_mach_time_info();
if (mach_time_info.denom == 0) {
mach_timebase_info(&mach_time_info);
guarantee(mach_time_info.denom != 0);
TLS_set_mach_time_info(mach_time_info);
}
const uint64_t t = mach_absolute_time();
uint64_t nanosecs = t * mach_time_info.numer / mach_time_info.denom;
timespec ret;
ret.tv_sec = nanosecs / BILLION;
ret.tv_nsec = nanosecs % BILLION;
return ret;
#elif defined(_WIN32)
timespec ret;
static THREAD_LOCAL LARGE_INTEGER frequency_hz = {0};
if (frequency_hz.QuadPart == 0) {
BOOL res = QueryPerformanceFrequency(&frequency_hz);
guarantee_winerr(res, "QueryPerformanceFrequency failed");
}
LARGE_INTEGER counter;
BOOL res = QueryPerformanceCounter(&counter);
guarantee_winerr(res, "QueryPerformanceCounter failed");
ret.tv_sec = counter.QuadPart / frequency_hz.QuadPart;
ret.tv_nsec = (counter.QuadPart - ret.tv_sec * frequency_hz.QuadPart) * BILLION / frequency_hz.QuadPart;
return ret;
#else
timespec ret;
int res = clock_gettime(CLOCK_MONOTONIC, &ret);
guarantee_err(res == 0, "clock_gettime(CLOCK_MONOTIC, ...) failed");
return ret;
#endif
}
timespec clock_realtime() {
#ifdef __MACH__
struct timeval tv;
int res = gettimeofday(&tv, nullptr);
guarantee_err(res == 0, "gettimeofday failed");
timespec ret;
ret.tv_sec = tv.tv_sec;
ret.tv_nsec = THOUSAND * tv.tv_usec;
return ret;
#elif defined(_MSC_VER)
FILETIME time;
#if _WIN32_WINNT >= 0x602 // Windows 8
GetSystemTimePreciseAsFileTime(&time);
#else
GetSystemTimeAsFileTime(&time);
#endif
ULARGE_INTEGER nanos100;
nanos100.LowPart = time.dwLowDateTime;
nanos100.HighPart = time.dwHighDateTime;
timespec ret;
ret.tv_sec = nanos100.QuadPart / (MILLION * 10);
ret.tv_nsec = (nanos100.QuadPart % (MILLION * 10)) * 100;
return ret;
#else
timespec ret;
int res = clock_gettime(CLOCK_REALTIME, &ret);
guarantee_err(res == 0, "clock_gettime(CLOCK_REALTIME) failed");
return ret;
#endif
}
void add_to_timespec(timespec *ts, int32_t nanoseconds) {
guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);
int64_t new_tv_nsec = ts->tv_nsec + nanoseconds;
if (new_tv_nsec >= 0 || new_tv_nsec % BILLION == 0) {
ts->tv_sec += new_tv_nsec / BILLION;
ts->tv_nsec = new_tv_nsec % BILLION;
} else {
ts->tv_sec += new_tv_nsec / BILLION - 1;
ts->tv_nsec = BILLION + new_tv_nsec % BILLION;
}
guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);
}
timespec subtract_timespecs(const timespec &t1, const timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
timespec res;
res.tv_sec = t1.tv_sec - t2.tv_sec;
if (t2.tv_nsec > t1.tv_nsec) {
--res.tv_sec;
res.tv_nsec = t1.tv_nsec + BILLION - t2.tv_nsec;
} else {
res.tv_nsec = t1.tv_nsec - t2.tv_nsec;
}
guarantee(res.tv_nsec >= 0 && res.tv_nsec < BILLION);
return res;
}
bool operator<(const struct timespec &t1, const struct timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec);
}
bool operator>(const struct timespec &t1, const struct timespec &t2) {
return t2 < t1;
}
bool operator<=(const struct timespec &t1, const struct timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec <= t2.tv_nsec);
}
bool operator>=(const struct timespec &t1, const struct timespec &t2) {
return t2 <= t1;
}
ticks_t get_ticks() {
timespec tv = clock_monotonic();
ticks_t ticks = secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
return ticks;
}
time_t get_secs() {
timespec tv = clock_realtime();
return tv.tv_sec;
}
double ticks_to_secs(ticks_t ticks) {
return ticks / static_cast<double>(BILLION);
}
<commit_msg>Fix current_microtime on Windows<commit_after>#include "time.hpp"
#include <inttypes.h>
#ifndef _MSC_VER
#include <sys/time.h>
#endif
#ifdef __MACH__
#include <mach/mach_time.h>
#include "thread_local.hpp"
#include "utils.hpp"
#endif
#include "config/args.hpp"
#include "errors.hpp"
#ifdef _MSC_VER
microtime_t current_microtime() {
FILETIME time;
#if _WIN32_WINNT >= 0x602 // Windows 8
GetSystemTimePreciseAsFileTime(&time);
#else
GetSystemTimeAsFileTime(&time);
#endif
ULARGE_INTEGER nanos100;
nanos100.LowPart = time.dwLowDateTime;
nanos100.HighPart = time.dwHighDateTime;
// Convert to Unix epoch
nanos100.QuadPart -= 116444736000000000ULL;
return nanos100.QuadPart / 10;
}
#else
microtime_t current_microtime() {
// This could be done more efficiently, surely.
struct timeval t;
DEBUG_VAR int res = gettimeofday(&t, nullptr);
rassert(0 == res);
return uint64_t(t.tv_sec) * MILLION + t.tv_usec;
}
#endif
ticks_t secs_to_ticks(time_t secs) {
return static_cast<ticks_t>(secs) * BILLION;
}
#ifdef __MACH__
TLS(mach_timebase_info_data_t, mach_time_info);
#endif // __MACH__
timespec clock_monotonic() {
#ifdef __MACH__
mach_timebase_info_data_t mach_time_info = TLS_get_mach_time_info();
if (mach_time_info.denom == 0) {
mach_timebase_info(&mach_time_info);
guarantee(mach_time_info.denom != 0);
TLS_set_mach_time_info(mach_time_info);
}
const uint64_t t = mach_absolute_time();
uint64_t nanosecs = t * mach_time_info.numer / mach_time_info.denom;
timespec ret;
ret.tv_sec = nanosecs / BILLION;
ret.tv_nsec = nanosecs % BILLION;
return ret;
#elif defined(_WIN32)
timespec ret;
static THREAD_LOCAL LARGE_INTEGER frequency_hz = {0};
if (frequency_hz.QuadPart == 0) {
BOOL res = QueryPerformanceFrequency(&frequency_hz);
guarantee_winerr(res, "QueryPerformanceFrequency failed");
}
LARGE_INTEGER counter;
BOOL res = QueryPerformanceCounter(&counter);
guarantee_winerr(res, "QueryPerformanceCounter failed");
ret.tv_sec = counter.QuadPart / frequency_hz.QuadPart;
ret.tv_nsec = (counter.QuadPart - ret.tv_sec * frequency_hz.QuadPart) * BILLION / frequency_hz.QuadPart;
return ret;
#else
timespec ret;
int res = clock_gettime(CLOCK_MONOTONIC, &ret);
guarantee_err(res == 0, "clock_gettime(CLOCK_MONOTIC, ...) failed");
return ret;
#endif
}
timespec clock_realtime() {
#ifdef __MACH__
struct timeval tv;
int res = gettimeofday(&tv, nullptr);
guarantee_err(res == 0, "gettimeofday failed");
timespec ret;
ret.tv_sec = tv.tv_sec;
ret.tv_nsec = THOUSAND * tv.tv_usec;
return ret;
#elif defined(_MSC_VER)
FILETIME time;
#if _WIN32_WINNT >= 0x602 // Windows 8
GetSystemTimePreciseAsFileTime(&time);
#else
GetSystemTimeAsFileTime(&time);
#endif
ULARGE_INTEGER nanos100;
nanos100.LowPart = time.dwLowDateTime;
nanos100.HighPart = time.dwHighDateTime;
// Convert to Unix epoch
nanos100.QuadPart -= 116444736000000000ULL;
timespec ret;
ret.tv_sec = nanos100.QuadPart / (MILLION * 10);
ret.tv_nsec = (nanos100.QuadPart % (MILLION * 10)) * 100;
return ret;
#else
timespec ret;
int res = clock_gettime(CLOCK_REALTIME, &ret);
guarantee_err(res == 0, "clock_gettime(CLOCK_REALTIME) failed");
return ret;
#endif
}
void add_to_timespec(timespec *ts, int32_t nanoseconds) {
guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);
int64_t new_tv_nsec = ts->tv_nsec + nanoseconds;
if (new_tv_nsec >= 0 || new_tv_nsec % BILLION == 0) {
ts->tv_sec += new_tv_nsec / BILLION;
ts->tv_nsec = new_tv_nsec % BILLION;
} else {
ts->tv_sec += new_tv_nsec / BILLION - 1;
ts->tv_nsec = BILLION + new_tv_nsec % BILLION;
}
guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);
}
timespec subtract_timespecs(const timespec &t1, const timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
timespec res;
res.tv_sec = t1.tv_sec - t2.tv_sec;
if (t2.tv_nsec > t1.tv_nsec) {
--res.tv_sec;
res.tv_nsec = t1.tv_nsec + BILLION - t2.tv_nsec;
} else {
res.tv_nsec = t1.tv_nsec - t2.tv_nsec;
}
guarantee(res.tv_nsec >= 0 && res.tv_nsec < BILLION);
return res;
}
bool operator<(const struct timespec &t1, const struct timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec);
}
bool operator>(const struct timespec &t1, const struct timespec &t2) {
return t2 < t1;
}
bool operator<=(const struct timespec &t1, const struct timespec &t2) {
guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);
guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);
return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec <= t2.tv_nsec);
}
bool operator>=(const struct timespec &t1, const struct timespec &t2) {
return t2 <= t1;
}
ticks_t get_ticks() {
timespec tv = clock_monotonic();
ticks_t ticks = secs_to_ticks(tv.tv_sec) + tv.tv_nsec;
return ticks;
}
time_t get_secs() {
timespec tv = clock_realtime();
return tv.tv_sec;
}
double ticks_to_secs(ticks_t ticks) {
return ticks / static_cast<double>(BILLION);
}
<|endoftext|>
|
<commit_before>#include "catch_ext.hpp"
#include <mapnik/expression.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/expression_string.hpp>
#include <mapnik/wkt/wkt_factory.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/unicode.hpp>
#include <functional>
#include <map>
namespace {
template <typename Properties>
mapnik::feature_ptr make_test_feature(mapnik::value_integer id, std::string const& wkt, Properties const& prop)
{
auto ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, id));
mapnik::geometry::geometry<double> geom;
if (mapnik::from_wkt(wkt, geom))
{
feature->set_geometry(std::move(geom));
}
for (auto const& kv : prop)
{
feature->put_new(kv.first, kv.second);
}
return feature;
}
template <typename Feature, typename Expression>
mapnik::value_type evaluate(Feature const& feature, Expression const& expr)
{
auto value = mapnik::util::apply_visitor(
mapnik::evaluate<Feature, mapnik::value_type, mapnik::attributes>(
feature, mapnik::attributes()), expr);
return value;
}
mapnik::value evaluate_string(mapnik::feature_ptr const& feature, std::string const& str)
{
auto expr = mapnik::parse_expression(str);
return evaluate(*feature, *expr);
}
std::string parse_and_dump(std::string const& str)
{
auto expr = mapnik::parse_expression(str);
return mapnik::to_expression_string(*expr);
}
} // namespace
TEST_CASE("expressions")
{
using namespace std::placeholders;
using properties_type = std::map<std::string, mapnik::value>;
mapnik::transcoder tr("utf8");
properties_type prop = {{ "foo" , tr.transcode("bar") },
{ "name" , tr.transcode("Québec")},
{ "grass" , tr.transcode("grow")},
{ "wind" , tr.transcode("blow")},
{ "sky" , tr.transcode("is blue")},
{ "τ" , mapnik::value_double(6.2831853)},
{ "double", mapnik::value_double(1.23456)},
{ "int" , mapnik::value_integer(123)},
{ "bool" , mapnik::value_bool(true)},
{ "null" , mapnik::value_null()}};
auto feature = make_test_feature(1, "POINT(100 200)", prop);
auto eval = std::bind(evaluate_string, feature, _1);
auto approx = Approx::custom().epsilon(1e-6);
// primary expressions
// null
TRY_CHECK(parse_and_dump("null") == "null");
// boolean
TRY_CHECK(parse_and_dump("true") == "true");
TRY_CHECK(parse_and_dump("false") == "false");
// floating point
TRY_CHECK(parse_and_dump("3.14159") == "3.14159");
// integer
TRY_CHECK(parse_and_dump("123") == "123");
// unicode
TRY_CHECK(parse_and_dump("''") == "''");
TRY_CHECK(parse_and_dump("'single-quoted string'") == "'single-quoted string'");
TRY_CHECK(parse_and_dump("\"double-quoted string\"") == "'double-quoted string'");
TRY_CHECK(parse_and_dump("'escaped \\' apostrophe'") == "'escaped \\' apostrophe'");
TRY_CHECK(parse_and_dump("'escaped \\\\ backslash'") == "'escaped \\\\ backslash'");
// floating point constants
TRY_CHECK(parse_and_dump("pi") == "3.14159");
TRY_CHECK(parse_and_dump("deg_to_rad") == "0.0174533");
TRY_CHECK(parse_and_dump("rad_to_deg") == "57.2958");
// ascii attribute name
TRY_CHECK(eval(" [foo]='bar' ") == true);
// unicode attribute name
TRY_CHECK(eval("[τ]") == prop.at("τ"));
TRY_CHECK(eval("[τ]") == eval(u8"[\u03C4]"));
// change to TRY_CHECK once \u1234 escape sequence in attribute name
// is implemented in expression grammar
CHECK_NOFAIL(eval("[τ]") == eval("[\\u03C3]"));
// unary functions
// sin / cos
TRY_CHECK(eval(" sin(0.25 * pi) / cos(0.25 * pi) ").to_double() == approx(1.0));
// tan
TRY_CHECK(eval(" tan(0.25 * pi) ").to_double() == approx(1.0));
// atan
TRY_CHECK(eval(" rad_to_deg * atan(1.0) ").to_double() == approx(45.0));
// exp
TRY_CHECK(eval(" exp(0.0) ") == 1.0);
// log
TRY_CHECK(eval(" log(1.0) ") == 0.0);
TRY_CHECK(eval(" log(exp(1.0)) ") == 1.0);
// abs
TRY_CHECK(eval(" abs(cos(-pi)) ") == 1.0);
// length (string)
TRY_CHECK(eval(" length('1234567890') ").to_int() == 10);
// binary functions
// min
TRY_CHECK(eval(" min(-0.01, 0.001) ") == -0.01);
// max
TRY_CHECK(eval(" max(0.01, -0.1) ") == 0.01);
// pow
TRY_CHECK(eval(" pow(2, 32) ") == 4294967296.0);
// geometry types
TRY_CHECK(eval(" [mapnik::geometry_type] = point ") == true);
TRY_CHECK(eval(" [ mapnik::geometry_type] <> linestring ") == true);
TRY_CHECK(eval(" [mapnik::geometry_type ] != polygon ") == true);
TRY_CHECK(eval(" [ mapnik::geometry_type ] neq collection ") == true);
TRY_CHECK(eval(" [mapnik::geometry_type] eq collection ") == false);
//unary expression
TRY_CHECK(eval(" -123.456 ") == -123.456);
TRY_CHECK(eval(" +123.456 ") == 123.456);
// multiplicative/additive
auto expr = mapnik::parse_expression("(2.0 * 2.0 + 3.0 * 3.0)/(2.0 * 2.0 - 3.0 * 3.0)");
TRY_CHECK(evaluate(*feature, *expr) == -2.6);
auto expr2 = mapnik::parse_expression("(2.0 * 2.0 + 3.0 * 3.0)/((2.0 - 3.0) * (2.0 + 3.0))");
TRY_CHECK(evaluate(*feature, *expr) == evaluate(*feature, *expr2));
// logical
TRY_CHECK(eval(" [int] = 123 and [double] = 1.23456 && [bool] = true and [null] = null && [foo] = 'bar' ") == true);
TRY_CHECK(eval(" [int] = 456 or [foo].match('foo') || length([foo]) = 3 ") == true);
TRY_CHECK(eval(" not true and not true ") == eval(" (not true ) and (not true ) "));
TRY_CHECK(eval(" not true or not true ") == eval(" (not true ) or (not true ) "));
TRY_CHECK(eval(" not false and not false ") == eval(" (not false) and (not false) "));
TRY_CHECK(eval(" not false or not false ") == eval(" (not false) or (not false) "));
// test not/and/or precedence using combinations of "not EQ1 OP1 not EQ2 OP2 not EQ3"
TRY_CHECK(eval(" not [grass] = 'grow' and not [wind] = 'blow' and not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' and not [wind] = 'blow' or not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' or not [wind] = 'blow' and not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' or not [wind] = 'blow' or not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grew' and not [wind] = 'blew' and not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' and not [wind] = 'blew' or not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' or not [wind] = 'blew' and not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' or not [wind] = 'blew' or not [sky] = 'was blue' ") == true);
// relational
TRY_CHECK(eval(" [int] > 100 and [int] gt 100.0 and [double] < 2 and [double] lt 2.0 ") == true);
TRY_CHECK(eval(" [int] >= 123 and [int] ge 123.0 and [double] <= 1.23456 and [double] le 1.23456 ") == true);
// empty string/null equality
TRY_CHECK(eval("[null] = null") == true);
TRY_CHECK(eval("[null] != null") == false);
TRY_CHECK(eval("[null] = ''") == false);
///////////////////// ref: https://github.com/mapnik/mapnik/issues/1859
TRY_CHECK(eval("[null] != ''") == false); // back compatible - will be changed in 3.1.x
//////////////////////
TRY_CHECK(eval("'' = [null]") == false);
TRY_CHECK(eval("'' != [null]") == true);
// regex
// replace
TRY_CHECK(eval(" [foo].replace(\"(\\B)|( )\",'$1 ') ") == tr.transcode("b a r"));
// https://en.wikipedia.org/wiki/Chess_symbols_in_Unicode
//'\u265C\u265E\u265D\u265B\u265A\u265D\u265E\u265C' - black chess figures
// replace black knights with white knights
auto val0 = eval(u8"'\u265C\u265E\u265D\u265B\u265A\u265D\u265E\u265C'.replace('\u265E','\u2658')");
auto val1 = eval("'♜♞♝♛♚♝♞♜'.replace('♞','♘')"); // ==> expected ♜♘♝♛♚♝♘♜
TRY_CHECK(val0 == val1);
TRY_CHECK(val0.to_string() == val1.to_string()); // UTF-8
TRY_CHECK(val0.to_unicode() == val1.to_unicode()); // Unicode
// \u+NNNN \U+NNNNNNNN \xNN\xNN
auto val3 = eval("'\\u262f\\xF0\\x9F\\x8D\\xB7'");
auto val4 = eval("'\\U0000262f\\U0001F377'");
auto val5 = eval("\"\\u262f\\xF0\\x9F\\x8D\\xB7\"");
auto val6 = eval("\"\\U0000262f\\U0001F377\"");
// UTF16 surrogate pairs work also ;)
// \ud83d\udd7a\ud83c\udffc => \U0001F57A\U0001F3FC works also
// TODO: find a way to enter UTF16 pairs
TRY_CHECK(val3 == val4);
TRY_CHECK(val5 == val6);
TRY_CHECK(val3.to_string() == val4.to_string()); // UTF-8
TRY_CHECK(val3.to_unicode() == val4.to_unicode()); // Unicod
TRY_CHECK(val5.to_string() == val6.to_string()); // UTF-8
TRY_CHECK(val5.to_unicode() == val6.to_unicode()); // Unicode
// following test will fail if boost_regex is built without ICU support (unpaired surrogates in output)
TRY_CHECK(eval("[name].replace('(\\B)|( )',' ') ") == tr.transcode("Q u é b e c"));
TRY_CHECK(eval("'Москва'.replace('(?<!^)(\\B|b)(?!$)',' ')") == tr.transcode("М о с к в а"));
// 'foo' =~ s:(\w)\1:$1x:r
TRY_CHECK(eval(" 'foo'.replace('(\\w)\\1', '$1x') ") == tr.transcode("fox"));
TRY_CHECK(parse_and_dump(" 'foo'.replace('(\\w)\\1', '$1x') ") == "'foo'.replace('(\\w)\\1','$1x')");
// match
TRY_CHECK(eval(" [name].match('Québec') ") == true);
// 'Québec' =~ m:^Q\S*$:
TRY_CHECK(eval(" [name].match('^Q\\S*$') ") == true);
TRY_CHECK(parse_and_dump(" [name].match('^Q\\S*$') ") == "[name].match('^Q\\S*$')");
// string & value concatenation
// this should evaluate as two strings concatenating
TRY_CHECK(eval("Hello + '!'") == eval("'Hello!'"));
// this should evaulate as a combination of an int value and string
TRY_CHECK(eval("[int]+m") == eval("'123m'"));
}
<commit_msg>add more single/double quotes tests<commit_after>#include "catch_ext.hpp"
#include <mapnik/expression.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/expression_string.hpp>
#include <mapnik/wkt/wkt_factory.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/unicode.hpp>
#include <functional>
#include <map>
namespace {
template <typename Properties>
mapnik::feature_ptr make_test_feature(mapnik::value_integer id, std::string const& wkt, Properties const& prop)
{
auto ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, id));
mapnik::geometry::geometry<double> geom;
if (mapnik::from_wkt(wkt, geom))
{
feature->set_geometry(std::move(geom));
}
for (auto const& kv : prop)
{
feature->put_new(kv.first, kv.second);
}
return feature;
}
template <typename Feature, typename Expression>
mapnik::value_type evaluate(Feature const& feature, Expression const& expr)
{
auto value = mapnik::util::apply_visitor(
mapnik::evaluate<Feature, mapnik::value_type, mapnik::attributes>(
feature, mapnik::attributes()), expr);
return value;
}
mapnik::value evaluate_string(mapnik::feature_ptr const& feature, std::string const& str)
{
auto expr = mapnik::parse_expression(str);
return evaluate(*feature, *expr);
}
std::string parse_and_dump(std::string const& str)
{
auto expr = mapnik::parse_expression(str);
return mapnik::to_expression_string(*expr);
}
} // namespace
TEST_CASE("expressions")
{
using namespace std::placeholders;
using properties_type = std::map<std::string, mapnik::value>;
mapnik::transcoder tr("utf8");
properties_type prop = {{ "foo" , tr.transcode("bar") },
{ "name" , tr.transcode("Québec")},
{ "grass" , tr.transcode("grow")},
{ "wind" , tr.transcode("blow")},
{ "sky" , tr.transcode("is blue")},
{ "τ" , mapnik::value_double(6.2831853)},
{ "double", mapnik::value_double(1.23456)},
{ "int" , mapnik::value_integer(123)},
{ "bool" , mapnik::value_bool(true)},
{ "null" , mapnik::value_null()}};
auto feature = make_test_feature(1, "POINT(100 200)", prop);
auto eval = std::bind(evaluate_string, feature, _1);
auto approx = Approx::custom().epsilon(1e-6);
// primary expressions
// null
TRY_CHECK(parse_and_dump("null") == "null");
// boolean
TRY_CHECK(parse_and_dump("true") == "true");
TRY_CHECK(parse_and_dump("false") == "false");
// floating point
TRY_CHECK(parse_and_dump("3.14159") == "3.14159");
// integer
TRY_CHECK(parse_and_dump("123") == "123");
// unicode
TRY_CHECK(parse_and_dump("''") == "''");
TRY_CHECK(parse_and_dump("'single-quoted string'") == "'single-quoted string'");
TRY_CHECK(parse_and_dump("\"double-quoted string\"") == "'double-quoted string'");
TRY_CHECK(parse_and_dump("'escaped \\' apostrophe'") == "'escaped \\' apostrophe'");
TRY_CHECK(parse_and_dump("'escaped \\\\ backslash'") == "'escaped \\\\ backslash'");
// floating point constants
TRY_CHECK(parse_and_dump("pi") == "3.14159");
TRY_CHECK(parse_and_dump("deg_to_rad") == "0.0174533");
TRY_CHECK(parse_and_dump("rad_to_deg") == "57.2958");
// ascii attribute name
TRY_CHECK(eval(" [foo]='bar' ") == true);
// unicode attribute name
TRY_CHECK(eval("[τ]") == prop.at("τ"));
TRY_CHECK(eval("[τ]") == eval(u8"[\u03C4]"));
// change to TRY_CHECK once \u1234 escape sequence in attribute name
// is implemented in expression grammar
CHECK_NOFAIL(eval("[τ]") == eval("[\\u03C3]"));
// unary functions
// sin / cos
TRY_CHECK(eval(" sin(0.25 * pi) / cos(0.25 * pi) ").to_double() == approx(1.0));
// tan
TRY_CHECK(eval(" tan(0.25 * pi) ").to_double() == approx(1.0));
// atan
TRY_CHECK(eval(" rad_to_deg * atan(1.0) ").to_double() == approx(45.0));
// exp
TRY_CHECK(eval(" exp(0.0) ") == 1.0);
// log
TRY_CHECK(eval(" log(1.0) ") == 0.0);
TRY_CHECK(eval(" log(exp(1.0)) ") == 1.0);
// abs
TRY_CHECK(eval(" abs(cos(-pi)) ") == 1.0);
// length (string)
TRY_CHECK(eval(" length('1234567890') ").to_int() == 10);
// binary functions
// min
TRY_CHECK(eval(" min(-0.01, 0.001) ") == -0.01);
// max
TRY_CHECK(eval(" max(0.01, -0.1) ") == 0.01);
// pow
TRY_CHECK(eval(" pow(2, 32) ") == 4294967296.0);
// geometry types
TRY_CHECK(eval(" [mapnik::geometry_type] = point ") == true);
TRY_CHECK(eval(" [ mapnik::geometry_type] <> linestring ") == true);
TRY_CHECK(eval(" [mapnik::geometry_type ] != polygon ") == true);
TRY_CHECK(eval(" [ mapnik::geometry_type ] neq collection ") == true);
TRY_CHECK(eval(" [mapnik::geometry_type] eq collection ") == false);
//unary expression
TRY_CHECK(eval(" -123.456 ") == -123.456);
TRY_CHECK(eval(" +123.456 ") == 123.456);
// multiplicative/additive
auto expr = mapnik::parse_expression("(2.0 * 2.0 + 3.0 * 3.0)/(2.0 * 2.0 - 3.0 * 3.0)");
TRY_CHECK(evaluate(*feature, *expr) == -2.6);
auto expr2 = mapnik::parse_expression("(2.0 * 2.0 + 3.0 * 3.0)/((2.0 - 3.0) * (2.0 + 3.0))");
TRY_CHECK(evaluate(*feature, *expr) == evaluate(*feature, *expr2));
// logical
TRY_CHECK(eval(" [int] = 123 and [double] = 1.23456 && [bool] = true and [null] = null && [foo] = 'bar' ") == true);
TRY_CHECK(eval(" [int] = 456 or [foo].match('foo') || length([foo]) = 3 ") == true);
TRY_CHECK(eval(" not true and not true ") == eval(" (not true ) and (not true ) "));
TRY_CHECK(eval(" not true or not true ") == eval(" (not true ) or (not true ) "));
TRY_CHECK(eval(" not false and not false ") == eval(" (not false) and (not false) "));
TRY_CHECK(eval(" not false or not false ") == eval(" (not false) or (not false) "));
// test not/and/or precedence using combinations of "not EQ1 OP1 not EQ2 OP2 not EQ3"
TRY_CHECK(eval(" not [grass] = 'grow' and not [wind] = 'blow' and not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' and not [wind] = 'blow' or not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' or not [wind] = 'blow' and not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grow' or not [wind] = 'blow' or not [sky] = 'is blue' ") == false);
TRY_CHECK(eval(" not [grass] = 'grew' and not [wind] = 'blew' and not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' and not [wind] = 'blew' or not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' or not [wind] = 'blew' and not [sky] = 'was blue' ") == true);
TRY_CHECK(eval(" not [grass] = 'grew' or not [wind] = 'blew' or not [sky] = 'was blue' ") == true);
// relational
TRY_CHECK(eval(" [int] > 100 and [int] gt 100.0 and [double] < 2 and [double] lt 2.0 ") == true);
TRY_CHECK(eval(" [int] >= 123 and [int] ge 123.0 and [double] <= 1.23456 and [double] le 1.23456 ") == true);
// empty string/null equality
TRY_CHECK(eval("[null] = null") == true);
TRY_CHECK(eval("[null] != null") == false);
TRY_CHECK(eval("[null] = ''") == false);
///////////////////// ref: https://github.com/mapnik/mapnik/issues/1859
TRY_CHECK(eval("[null] != ''") == false); // back compatible - will be changed in 3.1.x
//////////////////////
TRY_CHECK(eval("'' = [null]") == false);
TRY_CHECK(eval("'' != [null]") == true);
// regex
// replace
TRY_CHECK(eval(" [foo].replace('(\\B)|( )','$1 ') ") == tr.transcode("b a r")); // single quotes
TRY_CHECK(eval(" [foo].replace(\"(\\B)|( )\",\"$1 \") ") == tr.transcode("b a r")); // double quotes
// https://en.wikipedia.org/wiki/Chess_symbols_in_Unicode
//'\u265C\u265E\u265D\u265B\u265A\u265D\u265E\u265C' - black chess figures
// replace black knights with white knights
auto val0 = eval(u8"'\u265C\u265E\u265D\u265B\u265A\u265D\u265E\u265C'.replace('\u265E','\u2658')");
auto val1 = eval("'♜♞♝♛♚♝♞♜'.replace('♞','♘')"); // ==> expected ♜♘♝♛♚♝♘♜
TRY_CHECK(val0 == val1);
TRY_CHECK(val0.to_string() == val1.to_string()); // UTF-8
TRY_CHECK(val0.to_unicode() == val1.to_unicode()); // Unicode
// \u+NNNN \U+NNNNNNNN \xNN\xNN
// single quotes
auto val3 = eval("'\\u262f\\xF0\\x9F\\x8D\\xB7'");
auto val4 = eval("'\\U0000262f\\U0001F377'");
// double quotes
auto val5 = eval("\"\\u262f\\xF0\\x9F\\x8D\\xB7\"");
auto val6 = eval("\"\\U0000262f\\U0001F377\"");
// UTF16 surrogate pairs work also ;)
// \ud83d\udd7a\ud83c\udffc => \U0001F57A\U0001F3FC works also
// TODO: find a way to enter UTF16 pairs
TRY_CHECK(val3 == val4);
TRY_CHECK(val5 == val6);
TRY_CHECK(val3.to_string() == val4.to_string()); // UTF-8
TRY_CHECK(val3.to_unicode() == val4.to_unicode()); // Unicod
TRY_CHECK(val5.to_string() == val6.to_string()); // UTF-8
TRY_CHECK(val5.to_unicode() == val6.to_unicode()); // Unicode
// following test will fail if boost_regex is built without ICU support (unpaired surrogates in output)
TRY_CHECK(eval("[name].replace('(\\B)|( )',' ') ") == tr.transcode("Q u é b e c"));
TRY_CHECK(eval("'Москва'.replace('(?<!^)(\\B|b)(?!$)',' ')") == tr.transcode("М о с к в а"));
// 'foo' =~ s:(\w)\1:$1x:r
TRY_CHECK(eval(" 'foo'.replace('(\\w)\\1', '$1x') ") == tr.transcode("fox"));
TRY_CHECK(parse_and_dump(" 'foo'.replace('(\\w)\\1', '$1x') ") == "'foo'.replace('(\\w)\\1','$1x')");
// match
TRY_CHECK(eval(" [name].match('Québec') ") == true);
// 'Québec' =~ m:^Q\S*$:
TRY_CHECK(eval(" [name].match('^Q\\S*$') ") == true);
TRY_CHECK(parse_and_dump(" [name].match('^Q\\S*$') ") == "[name].match('^Q\\S*$')");
// string & value concatenation
// this should evaluate as two strings concatenating
TRY_CHECK(eval("Hello + '!'") == eval("'Hello!'"));
// this should evaulate as a combination of an int value and string
TRY_CHECK(eval("[int]+m") == eval("'123m'"));
}
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include <cstdlib>
#include <vector>
#include <iostream> // TODO: remove me
#include "../../cvmfs/upload_file_processing/chunk_detector.h"
#include "../../cvmfs/upload_file_processing/char_buffer.h"
class T_ChunkDetectors : public ::testing::Test {
protected:
void CreateBuffers(const size_t buffer_size) {
ClearBuffers();
const size_t MB = 1048576;
const size_t full_size = 100 * MB;
// make sure we always produce the same test data
srand(42);
// produce some test data
size_t i = 0;
while (i < full_size) {
upload::CharBuffer * buffer = new upload::CharBuffer(buffer_size);
buffer->SetUsedBytes(std::min(full_size - i, buffer_size));
buffer->SetBaseOffset(i);
for (size_t j = 0; j < buffer->size(); ++j) {
*(buffer->ptr() + j) = rand() % 256;
}
buffers_.push_back(buffer);
i += buffer->used_bytes();
}
}
virtual void TearDown() {
ClearBuffers();
}
private:
void ClearBuffers() {
Buffers::const_iterator i = buffers_.begin();
Buffers::const_iterator iend = buffers_.end();
for (; i != iend; ++i) {
delete *i;
}
buffers_.clear();
}
protected:
typedef std::vector<upload::CharBuffer*> Buffers;
Buffers buffers_;
};
TEST_F(T_ChunkDetectors, StaticOffsetChunkDetector) {
const size_t static_chunk_size = 1024;
upload::StaticOffsetDetector static_offset_detector(static_chunk_size);
EXPECT_FALSE (static_offset_detector.MightFindChunks(static_chunk_size));
EXPECT_TRUE (static_offset_detector.MightFindChunks(static_chunk_size + 1));
upload::CharBuffer buffer(static_chunk_size);
buffer.SetUsedBytes(static_chunk_size / 2);
off_t next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes());
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes() * 2);
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (static_cast<off_t>(static_chunk_size), next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes() * 3);
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
CreateBuffers(1048576);
off_t next_cut = 0;
int runs = 2;
Buffers::const_iterator i = buffers_.begin();
Buffers::const_iterator iend = buffers_.end();
for (; i != iend; ++i) {
while ((next_cut = static_offset_detector.FindNextCutMark(*i)) != 0) {
EXPECT_EQ (static_cast<off_t>(static_chunk_size) * runs, next_cut);
++runs;
}
}
}
TEST_F(T_ChunkDetectors, Xor32ChunkDetector) {
const size_t base = 512000;
upload::Xor32Detector xor32_detector(base, base * 2, base * 4);
EXPECT_FALSE (xor32_detector.MightFindChunks(0));
EXPECT_FALSE (xor32_detector.MightFindChunks(base));
EXPECT_TRUE (xor32_detector.MightFindChunks(base + 1));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 2));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3 + 1));
// expected cut marks
const off_t expected[] = {
591544, 1112589, 1716139, 2677179, 3473340, 4075967, 4832346,
5467359, 6584843, 7233161, 8237075, 8911472, 10211539, 11708173,
12545542, 13150940, 13746430, 14902448, 15841437, 16458881, 17123801,
17959953, 19894517, 21942517, 22888955, 23820032, 24355174, 25084484,
25791530, 27398981, 28841447, 29685225, 30533040, 32581040, 33565322,
34846885, 35378061, 36354275, 37469200, 38049328, 38748025, 40526310,
41244625, 41925007, 42497297, 43830589, 44347080, 44978978, 45843784,
46489702, 47049471, 47713371, 48414503, 50118479, 50834131, 52830209,
53505714, 54385890, 55416918, 56736198, 57516639, 58112403, 58705576,
59540049, 60904495, 61734883, 62667100, 63296723, 63908168, 64952264,
66536570, 67562340, 68734626, 69540127, 71148388, 71905512, 72813152,
73372989, 74072441, 74621306, 75181178, 75996775, 76631479, 77206009,
77724169, 79104681, 79710589, 81014713, 81612478, 82360921, 83350791,
84079423, 84809053, 85439794, 86132602, 87432725, 88277767, 88889874,
90188927, 90949653, 91472336, 92216519, 92985916, 94199809, 95523530,
96884562, 98506308, 99403409, 101084089, 101672598, 102271189, 103238158,
104050039
};
std::vector<size_t> buffer_sizes;
buffer_sizes.push_back(102400); // 100kB
buffer_sizes.push_back(base); // same as minimal chunk size
buffer_sizes.push_back(base * 2); // same as average chunk size
buffer_sizes.push_back(10485760); // 10MB
std::vector<size_t>::const_iterator i = buffer_sizes.begin();
std::vector<size_t>::const_iterator iend = buffer_sizes.end();
for (; i != iend; ++i) {
// create the test data chunked into buffers of size *i
CreateBuffers(*i);
// go through all the buffers and check if the chunker produces the
// expected results
upload::Xor32Detector detector(base, base * 2, base * 4);
off_t next_cut = 0;
int cut = 0;
bool fail = false;
Buffers::const_iterator j = buffers_.begin();
Buffers::const_iterator jend = buffers_.end();
for (; ! fail && j != jend; ++j) {
while ((next_cut = detector.FindNextCutMark(*j)) != 0) {
const int index = cut++;
if (expected[index] != next_cut) {
EXPECT_EQ(expected[index], next_cut) << "failed with buffer size "
<< *i << " byte... ";
fail = true;
}
}
}
}
}
<commit_msg>use internal PRNG instead of cstdlib's<commit_after>#include <gtest/gtest.h>
#include <vector>
#include <iostream> // TODO: remove me
#include "../../cvmfs/upload_file_processing/chunk_detector.h"
#include "../../cvmfs/upload_file_processing/char_buffer.h"
#include "../../cvmfs/prng.h"
class T_ChunkDetectors : public ::testing::Test {
protected:
void CreateBuffers(const size_t buffer_size) {
ClearBuffers();
const size_t MB = 1048576;
const size_t full_size = 100 * MB;
// make sure we always produce the same test data
rng_.InitSeed(42);
// produce some test data
size_t i = 0;
while (i < full_size) {
upload::CharBuffer * buffer = new upload::CharBuffer(buffer_size);
buffer->SetUsedBytes(std::min(full_size - i, buffer_size));
buffer->SetBaseOffset(i);
for (size_t j = 0; j < buffer->size(); ++j) {
*(buffer->ptr() + j) = static_cast<unsigned char>(rng_.Next(256));
}
buffers_.push_back(buffer);
i += buffer->used_bytes();
}
}
virtual void TearDown() {
ClearBuffers();
}
private:
void ClearBuffers() {
Buffers::const_iterator i = buffers_.begin();
Buffers::const_iterator iend = buffers_.end();
for (; i != iend; ++i) {
delete *i;
}
buffers_.clear();
}
protected:
typedef std::vector<upload::CharBuffer*> Buffers;
Buffers buffers_;
private:
Prng rng_;
};
TEST_F(T_ChunkDetectors, StaticOffsetChunkDetector) {
const size_t static_chunk_size = 1024;
upload::StaticOffsetDetector static_offset_detector(static_chunk_size);
EXPECT_FALSE (static_offset_detector.MightFindChunks(static_chunk_size));
EXPECT_TRUE (static_offset_detector.MightFindChunks(static_chunk_size + 1));
upload::CharBuffer buffer(static_chunk_size);
buffer.SetUsedBytes(static_chunk_size / 2);
off_t next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes());
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes() * 2);
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (static_cast<off_t>(static_chunk_size), next_cut_mark);
buffer.SetBaseOffset(buffer.used_bytes() * 3);
next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);
EXPECT_EQ (0, next_cut_mark);
CreateBuffers(1048576);
off_t next_cut = 0;
int runs = 2;
Buffers::const_iterator i = buffers_.begin();
Buffers::const_iterator iend = buffers_.end();
for (; i != iend; ++i) {
while ((next_cut = static_offset_detector.FindNextCutMark(*i)) != 0) {
EXPECT_EQ (static_cast<off_t>(static_chunk_size) * runs, next_cut);
++runs;
}
}
}
TEST_F(T_ChunkDetectors, Xor32ChunkDetector) {
const size_t base = 512000;
upload::Xor32Detector xor32_detector(base, base * 2, base * 4);
EXPECT_FALSE (xor32_detector.MightFindChunks(0));
EXPECT_FALSE (xor32_detector.MightFindChunks(base));
EXPECT_TRUE (xor32_detector.MightFindChunks(base + 1));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 2));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3));
EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3 + 1));
// expected cut marks
const off_t expected[] = {
1478173, 3106048, 4774918, 5483479, 6145474, 6815524, 7993818,
9827816, 10901280, 11472834, 12866669, 14914669, 15680095, 17728095,
18270545, 20003471, 20608171, 21331281, 21978222, 22534719, 23082248,
24152259, 25139243, 26454712, 28211455, 29378773, 30048887, 31106301,
32584060, 33220713, 33782665, 34554410, 36509543, 37845212, 38357766,
39026052, 39717365, 40902090, 41894611, 42565784, 43651833, 45340938,
45957448, 46753480, 47668586, 48650727, 49349827, 50044561, 50609473,
52448783, 53114708, 53757146, 54854971, 55503055, 56082722, 57245560,
58088890, 59568818, 60827431, 62875431, 63539342, 64281928, 64832251,
65513397, 67561397, 69265229, 70379107, 71426608, 72421269, 72983868,
73937161, 74486883, 75507129, 76825236, 77691932, 79497499, 80381772,
81515814, 82632302, 83187470, 83940560, 84919129, 85716196, 87018583,
88055868, 90103868, 91215622, 93088799, 94465150, 95279802, 95895281,
96736014, 97377339, 99274429, 100477630, 101018222, 101607802, 102485227,
103100922, 103673232, 104338021
};
std::vector<size_t> buffer_sizes;
buffer_sizes.push_back(102400); // 100kB
buffer_sizes.push_back(base); // same as minimal chunk size
buffer_sizes.push_back(base * 2); // same as average chunk size
buffer_sizes.push_back(10485760); // 10MB
std::vector<size_t>::const_iterator i = buffer_sizes.begin();
std::vector<size_t>::const_iterator iend = buffer_sizes.end();
for (; i != iend; ++i) {
// create the test data chunked into buffers of size *i
CreateBuffers(*i);
// go through all the buffers and check if the chunker produces the
// expected results
upload::Xor32Detector detector(base, base * 2, base * 4);
off_t next_cut = 0;
int cut = 0;
bool fail = false;
Buffers::const_iterator j = buffers_.begin();
Buffers::const_iterator jend = buffers_.end();
for (; ! fail && j != jend; ++j) {
while ((next_cut = detector.FindNextCutMark(*j)) != 0) {
const int index = cut++;
if (expected[index] != next_cut) {
EXPECT_EQ(expected[index], next_cut) << "failed with buffer size "
<< *i << " byte... ";
fail = true;
break;
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
#include <usTestingConfig.h>
#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"
#include <assert.h>
#include <set>
US_USE_NAMESPACE
namespace {
std::string GetResourceContent(const ModuleResource& resource)
{
std::string line;
ModuleResourceStream rs(resource);
std::getline(rs, line);
return line;
}
struct ResourceComparator {
bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
{
return mr1 < mr2;
}
};
void testResourceOperators(Module* module)
{
std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}
void testResourcesWithStaticImport(Module* module)
{
ModuleResource resource = module->GetResource("res.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
std::string line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")
resource = module->GetResource("dynamic.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")
resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "static", "Check dynamic resource content")
std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
line = GetResourceContent(resources[1]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
// skip foo.txt
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
// skip special_chars.dummy.txt
line = GetResourceContent(resources[5]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}
} // end unnamed namespace
int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("StaticModuleResourceTest");
ModuleContext* mc = GetModuleContext();
assert(mc);
#ifdef US_BUILD_SHARED_LIBS
SharedLibraryHandle libB("TestModuleB");
try
{
libB.Load();
}
catch (const std::exception& e)
{
US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
}
Module* module = ModuleRegistry::GetModule("TestModuleB Module");
US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")
US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
Module* module = mc->GetModule();
#endif
testResourceOperators(module);
testResourcesWithStaticImport(module);
#ifdef US_BUILD_SHARED_LIBS
ModuleResource resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
libB.Unload();
US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif
US_TEST_END()
}
<commit_msg>Fix unused variable error in release builds.<commit_after>/*=============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 <usModuleContext.h>
#include <usGetModuleContext.h>
#include <usModuleRegistry.h>
#include <usModule.h>
#include <usModuleResource.h>
#include <usModuleResourceStream.h>
#include <usTestingConfig.h>
#include "usTestUtilSharedLibrary.h"
#include "usTestingMacros.h"
#include <assert.h>
#include <set>
US_USE_NAMESPACE
namespace {
std::string GetResourceContent(const ModuleResource& resource)
{
std::string line;
ModuleResourceStream rs(resource);
std::getline(rs, line);
return line;
}
struct ResourceComparator {
bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const
{
return mr1 < mr2;
}
};
void testResourceOperators(Module* module)
{
std::vector<ModuleResource> resources = module->FindResources("", "res.txt", false);
US_TEST_CONDITION_REQUIRED(resources.size() == 2, "Check resource count")
US_TEST_CONDITION(resources[0] != resources[1], "Check non-equality for equally named resources")
}
void testResourcesWithStaticImport(Module* module)
{
ModuleResource resource = module->GetResource("res.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid res.txt resource")
std::string line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic resource", "Check dynamic resource content")
resource = module->GetResource("dynamic.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid dynamic.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "dynamic", "Check dynamic resource content")
resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
line = GetResourceContent(resource);
US_TEST_CONDITION(line == "static", "Check dynamic resource content")
std::vector<ModuleResource> resources = module->FindResources("", "*.txt", false);
std::stable_sort(resources.begin(), resources.end(), ResourceComparator());
#ifdef US_BUILD_SHARED_LIBS
US_TEST_CONDITION(resources.size() == 4, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
line = GetResourceContent(resources[1]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#else
US_TEST_CONDITION(resources.size() == 6, "Check imported resource count")
line = GetResourceContent(resources[0]);
US_TEST_CONDITION(line == "dynamic", "Check dynamic.txt resource content")
// skip foo.txt
line = GetResourceContent(resources[2]);
US_TEST_CONDITION(line == "dynamic resource", "Check res.txt (from importing module) resource content")
line = GetResourceContent(resources[3]);
US_TEST_CONDITION(line == "static resource", "Check res.txt (from imported module) resource content")
// skip special_chars.dummy.txt
line = GetResourceContent(resources[5]);
US_TEST_CONDITION(line == "static", "Check static.txt (from importing module) resource content")
#endif
}
} // end unnamed namespace
int usStaticModuleResourceTest(int /*argc*/, char* /*argv*/[])
{
US_TEST_BEGIN("StaticModuleResourceTest");
assert(GetModuleContext());
#ifdef US_BUILD_SHARED_LIBS
SharedLibraryHandle libB("TestModuleB");
try
{
libB.Load();
}
catch (const std::exception& e)
{
US_TEST_FAILED_MSG(<< "Load module exception: " << e.what())
}
Module* module = ModuleRegistry::GetModule("TestModuleB Module");
US_TEST_CONDITION_REQUIRED(module != NULL, "Test for existing module TestModuleB")
US_TEST_CONDITION(module->GetName() == "TestModuleB Module", "Test module name")
#else
Module* module = mc->GetModule();
#endif
testResourceOperators(module);
testResourcesWithStaticImport(module);
#ifdef US_BUILD_SHARED_LIBS
ModuleResource resource = module->GetResource("static.txt");
US_TEST_CONDITION_REQUIRED(resource.IsValid(), "Check valid static.txt resource")
libB.Unload();
US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, "Check invalid static.txt resource")
#endif
US_TEST_END()
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
using namespace std;
void userin(string &);
void print(const string);
void userin(string &s)
{
getline(cin,s);
return;
}
void print(const string s)
{
cout << "Your message is as follows:" << endl;
cout << s << endl;
}
int main()
{
string uin;
userin(uin);
print(uin);
return 0;
}
<commit_msg>added post confirmation<commit_after>#include <iostream>
#include <string>
using namespace std;
void userin(string &);
void print(const string);
void userin(string &s)
{
getline(cin,s);
return;
}
void print(const string s)
{
char check = ' ';
bool cont = false;
cout << "Your message is as follows:" << endl;
cout << s << endl;
cout << "Your message will tweet as follows:" << endl;
cout << s << "(" << s.size() << "/#" << endl;
while(!cont)
{
cout << "Do you wish to post? (Y or N then hit enter): ";
cin >> check;
if((check == 'Y') || (check == 'y') || (check == 'N') || (check == 'n'))
{
cont = true;
}
else
{
cout << "Please enter a valid choice. Y or y for yes, N or n for no." << endl;
}
}
if(check == 'Y' || check == 'y')
{
//post to twitter. push to twitter push library
}
return;
}
int main()
{
string uin;
userin(uin);
print(uin);
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
#include <map>
#include <typeinfo>
#include <stdexcept>
#include <cstdlib>
#include <ctype.h>
#define PRINT_LINE (std::cout << "line: " << __LINE__ << std::endl)
enum TokenType{
TOKEN_BRACKET_OPEN,
TOKEN_BRACKET_CLOSE,
TOKEN_SYMBOL,
TOKEN_STRING,
TOKEN_INTEGER,
TOKEN_NIL,
};
class Token {
public:
TokenType type;
std::string value;
Token(TokenType atype) : type(atype), value(std::string()) {
}
Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {
}
std::string str() {
std::stringstream ss;
ss << "Token(" << type << ", " << value << ")";
return ss.str();
}
};
namespace Lisp {
class Expression;
}
// memory allocated exprs
std::list<Lisp::Expression*> objects;
namespace Lisp {
class Expression {
public:
Expression() {
objects.push_back(this);
}
virtual ~Expression() {}
virtual std::string lisp_str() = 0;
};
class CallFunction : public Expression {
public:
std::string name;
std::vector<Expression*> args;
CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}
std::string lisp_str() {
std::stringstream ss;
ss << "(" << name << " ";
for(Expression* arg : args) {
ss << arg->lisp_str() << " ";
}
ss << ")";
return ss.str();
}
};
class String : public Expression {
public:
std::string value;
String(std::string &avalue) : value(avalue) {}
std::string lisp_str() { return '"' + value + '"'; }
};
class Integer : public Expression {
public:
unsigned long value;
Integer(std::string &avalue) : value(std::atol(avalue.c_str())) {}
Integer(unsigned long avalue) : value(avalue) {}
std::string lisp_str() { return std::to_string(value); }
};
class Symbol : public Expression {
public:
std::string value;
Symbol(std::string &avalue) : value(avalue) {}
std::string lisp_str() { return value; }
};
class List : public Expression {
public:
std::vector<Expression*> values;
List(std::vector<Expression*> &avalues) : values(avalues) {}
std::string lisp_str() {
std::stringstream ss;
ss << "(";
for(Expression* value : values) {
ss << value->lisp_str() << " ";
}
ss << ")";
return ss.str();
}
};
// TODO: RubyみたくExpression*に埋め込みたい
class Nil : public Expression {
public:
Nil() {}
std::string lisp_str() { return "nil"; }
};
class T : public Expression {
public:
T() {}
std::string lisp_str() { return "T"; }
};
class Parser {
public:
std::vector<Expression*> parse(const std::string &code) {
tokens = tokenize(code);
/*for(auto tok : tokens) {
std::cout << tok->str() << std::endl;
}*/
std::vector<Expression*> exprs;
while(!tokens.empty()) {
exprs.push_back(parse_expr());
}
return exprs;
}
private:
std::list<Token*> tokens;
inline Token* cur_token() {
return tokens.empty() ? nullptr : tokens.front();
}
void consume_token() {
auto ctoken = cur_token();
if(ctoken) delete ctoken;
if(!tokens.empty()) tokens.pop_front();
}
Expression* parse_call_fun() {
consume_token();
if(cur_token()->type != TOKEN_SYMBOL) {
//TODO: raise an error
}
std::string name;
name = cur_token()->value;
consume_token();
std::vector<Expression*> args;
for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {
args.push_back(parse_expr());
}
consume_token();
return new CallFunction(name, args);
}
Expression* parse_expr() {
switch(cur_token()->type) {
case TOKEN_BRACKET_OPEN:
return parse_call_fun();
case TOKEN_STRING:
return new String(cur_token()->value);
case TOKEN_NIL:
return new Nil();
case TOKEN_SYMBOL:
return new Symbol(cur_token()->value);
case TOKEN_INTEGER:
return new Integer(cur_token()->value);
default:
throw std::logic_error("unknown token: " + std::to_string(cur_token()->type));
return nullptr;
}
}
bool is_symbol(char c) {
return isalnum(c) && isalpha(c);
}
bool is_number(char c) {
return isdigit(c);
}
std::list<Token*> tokenize(const std::string &code) {
std::list<Token*> tokens;
for(size_t i = 0 ; i < code.size() - 1 ; i++) { //TODO: -1を修正(EOFっぽい?)
char ch = code[i];
if(ch == '(')
tokens.push_back(new Token(TOKEN_BRACKET_OPEN));
else if(ch == ')')
tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));
else if(ch == '"') { // string
i++;
size_t token_len = 0;
while(code[i + token_len] != '"') {
token_len++;
if(i + token_len >= code.size()) {
//TODO: raise an error
}
}
tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));
i += token_len;
}
else if(ch == ' ' || ch == '\n')
;//skip
else if(is_number(ch)) {
size_t token_len = 0;
while(is_number(code[i + token_len])) {
token_len++;
// TODO: raise an error
}
std::string token_val = code.substr(i, token_len);
tokens.push_back(new Token(TOKEN_INTEGER, token_val));
i += token_len;
}
else { // symbol
size_t token_len = 0;
while(is_symbol(code[i + token_len])) {
token_len++;
if(i + token_len >= code.size()) {
//TODO: raise an error
}
}
std::string token_val = code.substr(i, token_len);
TokenType token_type;
if(token_val == "nil")
token_type = TOKEN_NIL;
else
token_type = TOKEN_SYMBOL;
if(token_type == TOKEN_SYMBOL)
tokens.push_back(new Token(TOKEN_SYMBOL, token_val));
else
tokens.push_back(new Token(token_type));
i += token_len - 1;
}
}
return tokens;
}
};
class Evaluator {
std::map<std::string, Expression*> env;
Expression* eval_expr(Expression* expr) {
const std::type_info& id = typeid(*expr);
if(id == typeid(CallFunction)) {
auto call_fun = (CallFunction*)expr;
auto name = call_fun->name;
if(name == "print") {
std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;
return new Nil();
}
else if(name == "setq") {
env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];
return new Nil();
}
else if(name == "atom") {
auto val = evaluate(call_fun->args[0]);
if(typeid(*val) != typeid(List)) return new T();
else return new Nil();
}
else if(name == "list") {
auto args = call_fun->args;
for(size_t i = 0 ; i < args.size() ; i++) {
args[i] = evaluate(args[i]);
}
return new List(args);
}
}
else if(id == typeid(Symbol)) {
return env[((Symbol*)expr)->value];
}
return expr;
}
public:
Expression* evaluate(Expression* expr) {
return eval_expr(expr);
}
};
}
int main() {
using namespace std;
string code;
//code.reserve(1024);
char ch;
while((ch = cin.get()) != std::char_traits<char>::eof()) {
code.push_back(ch);
}
Lisp::Parser parser;
auto exprs = parser.parse(code);
Lisp::Evaluator evaluator;
for(size_t i = 0 ; i < exprs.size() ; i++) {
exprs[i] = evaluator.evaluate(exprs[i]);
}
// fake GC
for(auto expr : objects) {
delete expr;
}
return 0;
}
<commit_msg>+関数を実装した<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
#include <map>
#include <typeinfo>
#include <stdexcept>
#include <cstdlib>
#include <ctype.h>
#define PRINT_LINE (std::cout << "line: " << __LINE__ << std::endl)
enum TokenType{
TOKEN_BRACKET_OPEN,
TOKEN_BRACKET_CLOSE,
TOKEN_SYMBOL,
TOKEN_STRING,
TOKEN_INTEGER,
TOKEN_NIL,
};
class Token {
public:
TokenType type;
std::string value;
Token(TokenType atype) : type(atype), value(std::string()) {
}
Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {
}
std::string str() {
std::stringstream ss;
ss << "Token(" << type << ", " << value << ")";
return ss.str();
}
};
namespace Lisp {
class Expression;
}
// memory allocated exprs
std::list<Lisp::Expression*> objects;
namespace Lisp {
class Expression {
public:
Expression() {
objects.push_back(this);
}
virtual ~Expression() {}
virtual std::string lisp_str() = 0;
};
class CallFunction : public Expression {
public:
std::string name;
std::vector<Expression*> args;
CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}
std::string lisp_str() {
std::stringstream ss;
ss << "(" << name << " ";
for(Expression* arg : args) {
ss << arg->lisp_str() << " ";
}
ss << ")";
return ss.str();
}
};
class String : public Expression {
public:
std::string value;
String(std::string &avalue) : value(avalue) {}
std::string lisp_str() { return '"' + value + '"'; }
};
class Integer : public Expression {
public:
unsigned long value;
Integer(std::string &avalue) : value(std::atol(avalue.c_str())) {}
Integer(unsigned long avalue) : value(avalue) {}
std::string lisp_str() { return std::to_string(value); }
};
class Symbol : public Expression {
public:
std::string value;
Symbol(std::string &avalue) : value(avalue) {}
std::string lisp_str() { return value; }
};
class List : public Expression {
public:
std::vector<Expression*> values;
List(std::vector<Expression*> &avalues) : values(avalues) {}
std::string lisp_str() {
std::stringstream ss;
ss << "(";
for(Expression* value : values) {
ss << value->lisp_str() << " ";
}
ss << ")";
return ss.str();
}
};
// TODO: RubyみたくExpression*に埋め込みたい
class Nil : public Expression {
public:
Nil() {}
std::string lisp_str() { return "nil"; }
};
class T : public Expression {
public:
T() {}
std::string lisp_str() { return "T"; }
};
class Parser {
public:
std::vector<Expression*> parse(const std::string &code) {
tokens = tokenize(code);
/*for(auto tok : tokens) {
std::cout << tok->str() << std::endl;
}*/
std::vector<Expression*> exprs;
while(!tokens.empty()) {
exprs.push_back(parse_expr());
}
return exprs;
}
private:
std::list<Token*> tokens;
inline Token* cur_token() {
return tokens.empty() ? nullptr : tokens.front();
}
void consume_token() {
auto ctoken = cur_token();
if(ctoken) delete ctoken;
if(!tokens.empty()) tokens.pop_front();
}
Expression* parse_call_fun() {
consume_token();
if(cur_token()->type != TOKEN_SYMBOL) {
//TODO: raise an error
}
std::string name;
name = cur_token()->value;
consume_token();
std::vector<Expression*> args;
for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {
args.push_back(parse_expr());
}
consume_token();
return new CallFunction(name, args);
}
Expression* parse_expr() {
switch(cur_token()->type) {
case TOKEN_BRACKET_OPEN:
return parse_call_fun();
case TOKEN_STRING:
return new String(cur_token()->value);
case TOKEN_NIL:
return new Nil();
case TOKEN_SYMBOL:
return new Symbol(cur_token()->value);
case TOKEN_INTEGER:
return new Integer(cur_token()->value);
default:
throw std::logic_error("unknown token: " + std::to_string(cur_token()->type));
return nullptr;
}
}
bool is_symbol(char c) {
return !isspace(c);
}
bool is_number(char c) {
return isdigit(c);
}
std::list<Token*> tokenize(const std::string &code) {
std::list<Token*> tokens;
for(size_t i = 0 ; i < code.size() - 1 ; i++) { //TODO: -1を修正(EOFっぽい?)
char ch = code[i];
if(ch == '(')
tokens.push_back(new Token(TOKEN_BRACKET_OPEN));
else if(ch == ')')
tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));
else if(ch == '"') { // string
i++;
size_t token_len = 0;
while(code[i + token_len] != '"') {
token_len++;
if(i + token_len >= code.size()) {
//TODO: raise an error
}
}
tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));
i += token_len;
}
else if(ch == ' ' || ch == '\n')
;//skip
else if(is_number(ch)) {
size_t token_len = 0;
while(is_number(code[i + token_len])) {
token_len++;
// TODO: raise an error
}
std::string token_val = code.substr(i, token_len);
tokens.push_back(new Token(TOKEN_INTEGER, token_val));
i += token_len;
}
else { // symbol
size_t token_len = 0;
while(is_symbol(code[i + token_len])) {
token_len++;
if(i + token_len >= code.size()) {
//TODO: raise an error
}
}
std::string token_val = code.substr(i, token_len);
TokenType token_type;
if(token_val == "nil")
token_type = TOKEN_NIL;
else
token_type = TOKEN_SYMBOL;
if(token_type == TOKEN_SYMBOL)
tokens.push_back(new Token(TOKEN_SYMBOL, token_val));
else
tokens.push_back(new Token(token_type));
i += token_len - 1;
}
}
return tokens;
}
};
class Evaluator {
std::map<std::string, Expression*> env;
Expression* eval_expr(Expression* expr) {
const std::type_info& id = typeid(*expr);
if(id == typeid(CallFunction)) {
auto call_fun = (CallFunction*)expr;
auto name = call_fun->name;
if(name == "print") {
std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;
return new Nil();
}
else if(name == "setq") {
env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];
return new Nil();
}
else if(name == "atom") {
auto val = evaluate(call_fun->args[0]);
if(typeid(*val) != typeid(List)) return new T();
else return new Nil();
}
else if(name == "+") {
Integer* sum = new Integer(0);
for(auto arg : call_fun->args) {
sum->value += ((Integer*)evaluate(arg))->value;
}
return sum;
}
else if(name == "list") {
auto args = call_fun->args;
for(size_t i = 0 ; i < args.size() ; i++) {
args[i] = evaluate(args[i]);
}
return new List(args);
}
}
else if(id == typeid(Symbol)) {
return env[((Symbol*)expr)->value];
}
return expr;
}
public:
Expression* evaluate(Expression* expr) {
return eval_expr(expr);
}
};
}
int main() {
using namespace std;
string code;
//code.reserve(1024);
char ch;
while((ch = cin.get()) != std::char_traits<char>::eof()) {
code.push_back(ch);
}
Lisp::Parser parser;
auto exprs = parser.parse(code);
Lisp::Evaluator evaluator;
for(size_t i = 0 ; i < exprs.size() ; i++) {
exprs[i] = evaluator.evaluate(exprs[i]);
}
// fake GC
for(auto expr : objects) {
delete expr;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sfxurl.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: dv $ $Date: 2001-07-12 07:43:50 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>
SfxUrlDialog::SfxUrlDialog( Window *pParent )
: ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
aEdit( this, ResId(RID_URLOPEN_URL) ),
aCancel( this, ResId(RID_URLOPEN_CANCEL) ),
aOk( this, ResId(RID_URLOPEN_OK) )
{
FreeResource();
}
<commit_msg>INTEGRATION: CWS ooo20040704 (1.2.562); FILE MERGED 2004/06/28 13:04:54 waratah 1.2.562.1: #i30812# reorder declaration to match header declares<commit_after>/*************************************************************************
*
* $RCSfile: sfxurl.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-09-08 15:40:54 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>
SfxUrlDialog::SfxUrlDialog( Window *pParent )
: ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
aEdit( this, ResId(RID_URLOPEN_URL) ),
aOk( this, ResId(RID_URLOPEN_OK) ),
aCancel( this, ResId(RID_URLOPEN_CANCEL) )
{
FreeResource();
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include <limits.h>
#include <string.h>
#include "condor_debug.h"
#include "condor_daemon_core.h"
#include "forkwork.h"
// Instantiate the list of Cron Jobs
// Fork worker class constructor
ForkWorker::ForkWorker( void )
{
valid = 0x5a5a;
pid = -1;
parent = -1;
}
// Fork worker class destructor
ForkWorker::~ForkWorker( void )
{
if ( valid != 0x5a5a ) {
dprintf( D_ALWAYS, "ForkWorker: delete invalid!!\n" );
}
valid = 0;
}
// Fork off a real worker job
ForkStatus
ForkWorker::Fork( void )
{
# ifndef WIN32
// Fork
pid = fork( );
if ( pid < 0 ) {
dprintf( D_ALWAYS, "ForkWorker::Fork: Fork failed\n" );
return FORK_FAILED;
} else if ( 0 == pid ) {
// We should really be using DC::Create_Thread() for this.
// However, since we're not, we need to call this method
// to tell DC we're a forked child and that we want to
// exit via exec(), not using exit(), so that destructors
// don't get called...
daemonCore->Forked_Child_Wants_Exit_By_Exec( true );
parent = getppid( );
pid = -1;
return FORK_CHILD;
} else {
// Parent
parent = getpid( );
dprintf( D_JOB, "ForkWorker::Fork: New child of %d = %d\n",
parent, pid );
return FORK_PARENT;
}
# else
return FORK_FAILED;
# endif
}
// Fork work constructor
ForkWork::ForkWork( int max_workers )
{
# ifdef WIN32
max_workers = 0;
# endif
maxWorkers = max_workers;
reaperId = -1;
childExit = false;
}
// Finish initialization
int
ForkWork::Initialize( void )
{
if( reaperId != -1 ) {
// already initialized
return 0;
}
// Register my reaper
reaperId = daemonCore->Register_Reaper(
"ForkWork_Reaper",
(ReaperHandlercpp) &ForkWork::Reaper,
"ForkWork Reaper",
this );
daemonCore->Set_Default_Reaper( reaperId );
return 0;
}
// Fork work denstructor
ForkWork::~ForkWork( void )
{
// Kill 'em all
DeleteAll( );
}
// Set max # of children
void
ForkWork::setMaxWorkers( int max_workers )
{
# ifdef WIN32
max_workers = 0;
# endif
maxWorkers = max_workers;
if ( workerList.Number() > maxWorkers ) {
dprintf( D_JOB, "Warning: # forked workers exceeds max\n" );
}
}
// Kill & delete all running workers
int
ForkWork::DeleteAll( void )
{
ForkWorker *worker;
// Kill 'em all
KillAll( true );
// Walk through the list
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
workerList.DeleteCurrent( );
delete worker;
}
return 0;
}
// Kill all running jobs
int
ForkWork::KillAll( bool force )
{
ForkWorker *worker;
int mypid = getpid();
int num_killed = 0;
// Walk through the list
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
// If I'm the parent, kill it
if ( mypid == worker->getParent() ) {
num_killed++;
if ( force ) {
daemonCore->Send_Signal( worker->getPid(), SIGKILL );
} else {
daemonCore->Send_Signal( worker->getPid(), SIGTERM );
}
}
}
// If we killed some, log it...
if ( num_killed ) {
dprintf( D_JOB, "ForkWork %d: Killed %d jobs\n",
mypid, workerList.Number() );
}
return 0;
}
// Try to fork off another worker
ForkStatus
ForkWork::NewJob( void )
{
// Any open slots?
if ( workerList.Number() >= maxWorkers ) {
if ( maxWorkers ) {
dprintf( D_JOB, "ForkWork: busy\n" );
}
return FORK_BUSY;
}
// Fork off the child
ForkWorker *worker = new ForkWorker( );
ForkStatus status = worker->Fork( );
// Ok, let's see what happenned..
if ( FORK_PARENT == status ) {
workerList.Append( worker );
return FORK_PARENT;
} else if ( FORK_FAILED == status ) {
delete worker;
return FORK_FAILED;
} else {
delete worker;
return FORK_CHILD;
}
}
// Child worker is done
void
ForkWork::WorkerDone( int exit_status )
{
dprintf( D_JOB,
"ForkWork: Child %d done, status %d\n",
getpid(), exit_status );
exit( exit_status );
}
// Child reaper
int
ForkWork::Reaper( int exitPid, int /*exitStatus*/ )
{
ForkWorker *worker;
// Let's find out if it's one of our children...
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
if ( worker->getPid() == exitPid ) {
workerList.DeleteCurrent( );
delete worker;
return 0;
}
}
return 0;
}
<commit_msg>Add basic logging to denote active workers. ===VersionHistory:None===<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include <limits.h>
#include <string.h>
#include "condor_debug.h"
#include "condor_daemon_core.h"
#include "forkwork.h"
// Instantiate the list of Cron Jobs
// Fork worker class constructor
ForkWorker::ForkWorker( void )
{
valid = 0x5a5a;
pid = -1;
parent = -1;
}
// Fork worker class destructor
ForkWorker::~ForkWorker( void )
{
if ( valid != 0x5a5a ) {
dprintf( D_ALWAYS, "ForkWorker: delete invalid!!\n" );
}
valid = 0;
}
// Fork off a real worker job
ForkStatus
ForkWorker::Fork( void )
{
# ifndef WIN32
// Fork
pid = fork( );
if ( pid < 0 ) {
dprintf( D_ALWAYS, "ForkWorker::Fork: Fork failed\n" );
return FORK_FAILED;
} else if ( 0 == pid ) {
// We should really be using DC::Create_Thread() for this.
// However, since we're not, we need to call this method
// to tell DC we're a forked child and that we want to
// exit via exec(), not using exit(), so that destructors
// don't get called...
daemonCore->Forked_Child_Wants_Exit_By_Exec( true );
parent = getppid( );
pid = -1;
return FORK_CHILD;
} else {
// Parent
parent = getpid( );
dprintf( D_JOB, "ForkWorker::Fork: New child of %d = %d\n",
parent, pid );
return FORK_PARENT;
}
# else
return FORK_FAILED;
# endif
}
// Fork work constructor
ForkWork::ForkWork( int max_workers )
{
# ifdef WIN32
max_workers = 0;
# endif
maxWorkers = max_workers;
reaperId = -1;
childExit = false;
}
// Finish initialization
int
ForkWork::Initialize( void )
{
if( reaperId != -1 ) {
// already initialized
return 0;
}
// Register my reaper
reaperId = daemonCore->Register_Reaper(
"ForkWork_Reaper",
(ReaperHandlercpp) &ForkWork::Reaper,
"ForkWork Reaper",
this );
daemonCore->Set_Default_Reaper( reaperId );
return 0;
}
// Fork work denstructor
ForkWork::~ForkWork( void )
{
// Kill 'em all
DeleteAll( );
}
// Set max # of children
void
ForkWork::setMaxWorkers( int max_workers )
{
# ifdef WIN32
max_workers = 0;
# endif
maxWorkers = max_workers;
if ( workerList.Number() > maxWorkers ) {
dprintf( D_JOB, "Warning: # forked workers exceeds max\n" );
}
}
// Kill & delete all running workers
int
ForkWork::DeleteAll( void )
{
ForkWorker *worker;
// Kill 'em all
KillAll( true );
// Walk through the list
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
workerList.DeleteCurrent( );
delete worker;
}
return 0;
}
// Kill all running jobs
int
ForkWork::KillAll( bool force )
{
ForkWorker *worker;
int mypid = getpid();
int num_killed = 0;
// Walk through the list
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
// If I'm the parent, kill it
if ( mypid == worker->getParent() ) {
num_killed++;
if ( force ) {
daemonCore->Send_Signal( worker->getPid(), SIGKILL );
} else {
daemonCore->Send_Signal( worker->getPid(), SIGTERM );
}
}
}
// If we killed some, log it...
if ( num_killed ) {
dprintf( D_JOB, "ForkWork %d: Killed %d jobs\n",
mypid, workerList.Number() );
}
return 0;
}
// Try to fork off another worker
ForkStatus
ForkWork::NewJob( void )
{
ForkStatus status = FORK_BUSY;
// Any open slots?
if ( workerList.Number() >= maxWorkers ) {
if ( maxWorkers ) {
dprintf( D_JOB, "ForkWork: busy\n" );
}
}
else
{
// Fork off the child
ForkWorker *worker = new ForkWorker( );
status = worker->Fork( );
// Ok, let's see what happenned..
if ( FORK_PARENT == status ) {
workerList.Append( worker );
} else if ( FORK_FAILED == status ) {
delete worker;
} else {
delete worker;
status = FORK_CHILD;
}
}
dprintf( D_ALWAYS, "Number of Active Workers %d\n", workerList.Number());
return status;
}
// Child worker is done
void
ForkWork::WorkerDone( int exit_status )
{
dprintf( D_JOB,
"ForkWork: Child %d done, status %d\n",
getpid(), exit_status );
exit( exit_status );
}
// Child reaper
int
ForkWork::Reaper( int exitPid, int /*exitStatus*/ )
{
ForkWorker *worker;
// Let's find out if it's one of our children...
workerList.Rewind( );
while ( workerList.Next( worker ) ) {
if ( worker->getPid() == exitPid ) {
workerList.DeleteCurrent( );
delete worker;
return 0;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "matrix_pseudoinverse_test.hpp"
#include <vmmlib/matrix_pseudoinverse.hpp>
#include <sstream>
#include <stdint.h>
namespace vmml
{
bool
matrix_pseudoinverse_test::run()
{
bool ok = false;
compute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;
matrix< 6, 4, float > input;
double data[] = { 0.8147, 0.9058, 0.1270, 0.9134,
0.6324, 0.0975, 0.2785, 0.5469,
0.9575, 0.9649, 0.1576, 0.9706,
0.9572, 0.4854, 0.8003, 0.1419,
0.4218, 0.9157, 0.7922, 0.9595,
0.6557, 0.0357, 0.8491, 0.9340};
input.set( data, data + 24);
matrix< 6, 4, float > pseudoinverse_transposed_control;
double data2[] = { 0.1880, 0.1967, -0.4289, 0.1703,
0.5039, -0.5719, -0.2487, 0.2746,
0.3297, 0.1597, -0.4866, 0.1270,
0.6085, 0.2728, 0.5149, -0.9327,
-0.9104, 0.6751, 0.6790, 0.1391,
0.0213, -0.7584, 0.2949, 0.6102 };
pseudoinverse_transposed_control.set( data2, data2 + 24);
matrix< 6, 4, float > pseudoinverse_transposed;
compute_pinv( input, pseudoinverse_transposed );
if ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))
{
log( "matrix compute pseudo inverse ", true );
} else
{
std::stringstream error;
error
<< "matrix compute pseudo inverse: " << std::endl
<< "inverse matrix (transposed) should be: " << std::endl << pseudoinverse_transposed_control << std::endl
<< "inverse matrix (transposed) is: " << std::endl << pseudoinverse_transposed << std::endl;
log_error( error.str() );
}
ok = true;
return ok;
}
} // namespace vmml<commit_msg>- added more tests for matrix_pseudoinverse <commit_after>#include "matrix_pseudoinverse_test.hpp"
#include <vmmlib/matrix_pseudoinverse.hpp>
#include <sstream>
#include <stdint.h>
namespace vmml
{
bool
matrix_pseudoinverse_test::run()
{
bool ok = false;
compute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;
matrix< 6, 4, float > input;
double data[] = { 0.8147, 0.9058, 0.1270, 0.9134,
0.6324, 0.0975, 0.2785, 0.5469,
0.9575, 0.9649, 0.1576, 0.9706,
0.9572, 0.4854, 0.8003, 0.1419,
0.4218, 0.9157, 0.7922, 0.9595,
0.6557, 0.0357, 0.8491, 0.9340};
input.set( data, data + 24);
matrix< 6, 4, float > pseudoinverse_transposed_control;
double data2[] = { 0.1880, 0.1967, -0.4289, 0.1703,
0.5039, -0.5719, -0.2487, 0.2746,
0.3297, 0.1597, -0.4866, 0.1270,
0.6085, 0.2728, 0.5149, -0.9327,
-0.9104, 0.6751, 0.6790, 0.1391,
0.0213, -0.7584, 0.2949, 0.6102 };
pseudoinverse_transposed_control.set( data2, data2 + 24);
matrix< 6, 4, float > pseudoinverse_transposed;
compute_pinv( input, pseudoinverse_transposed );
matrix< 4, 6, float > pseudoinverse = transpose( pseudoinverse_transposed );
matrix< 6, 6, float > control;
control.multiply( input, pseudoinverse);
if ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))
{
log( "matrix compute pseudo inverse ", true );
} else
{
std::stringstream error;
error
<< "matrix compute pseudo inverse: " << std::endl
<< "inverse matrix (transposed) should be: " << std::endl << pseudoinverse_transposed_control << std::endl
<< "inverse matrix (transposed) is: " << std::endl << pseudoinverse_transposed << std::endl
<< "identiy matrix (control) is: " << std::endl << control << std::endl;
log_error( error.str() );
}
ok = true;
return ok;
}
} // namespace vmml<|endoftext|>
|
<commit_before>#include <chrono>
#include "depthai/depthai.hpp"
/////////////////////////
// TEST
// ImageManipNode test
////////////////////////
int main(){
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;
// Create pipeline
dai::Pipeline p;
auto xin = p.create<dai::node::XLinkIn>();
auto imageManip = p.create<dai::node::ImageManip>();
auto xout = p.create<dai::node::XLinkOut>();
// resize
const int originalWidth = 640, originalHeight = 360;
const int width = 337, height = 225;
// Properties
xin->setStreamName("in");
xout->setStreamName("out");
imageManip->setResize(width, height);
// Link plugins CAM -> XLINK
xin->out.link(imageManip->inputImage);
imageManip->out.link(xout->input);
// Wait 5 seconds for device
auto wait = steady_clock::now();
bool found;
dai::DeviceInfo deviceInfo;
do{
std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();
if(found) {
dai::Device d(p, deviceInfo);
d.startPipeline();
auto in = d.getInputQueue("in");
auto out = d.getOutputQueue("out");
// Send 10 messages
for(int i = 0; i < 10; i++){
// Create 'rgb interleaved' frame
dai::ImgFrame inFrame;
inFrame.getData().resize(originalWidth * originalHeight * 3);
inFrame.setWidth(originalWidth);
inFrame.setHeight(originalHeight);
inFrame.setType(dai::RawImgFrame::Type::RGB888i);
// Send the frame
in->send(inFrame);
// Retrieve the resized frame
auto outFrame = out->get<dai::ImgFrame>();
// Check that out frame is resized
if(outFrame->getWidth() != width || outFrame->getHeight() != height){
return -1;
}
}
// Exit with success error code
return 0;
}
this_thread::sleep_for(1s);
} while(!found && steady_clock::now() - wait < 5s );
// Otherwise exit with error
return -1;
}<commit_msg>Fixed ImageManip test<commit_after>#include <chrono>
#include "depthai/depthai.hpp"
/////////////////////////
// TEST
// ImageManipNode test
////////////////////////
int main(){
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;
// Create pipeline
dai::Pipeline p;
auto xin = p.create<dai::node::XLinkIn>();
auto imageManip = p.create<dai::node::ImageManip>();
auto xout = p.create<dai::node::XLinkOut>();
// resize
const int originalWidth = 640, originalHeight = 360;
const int width = 337, height = 225;
// Properties
xin->setStreamName("in");
xout->setStreamName("out");
imageManip->setResize(width, height);
// Link plugins CAM -> XLINK
xin->out.link(imageManip->inputImage);
imageManip->out.link(xout->input);
// Wait 5 seconds for device
auto wait = steady_clock::now();
bool found;
dai::DeviceInfo deviceInfo;
do{
std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();
if(found) {
dai::Device d(p, deviceInfo);
d.startPipeline();
auto in = d.getInputQueue("in");
auto out = d.getOutputQueue("out");
// Send 10 messages
for(int i = 0; i < 10; i++){
// Create 'rgb interleaved' frame
dai::ImgFrame inFrame;
inFrame.getData().resize(originalWidth * originalHeight * 3);
inFrame.setWidth(originalWidth);
inFrame.setHeight(originalHeight);
inFrame.setType(dai::RawImgFrame::Type::RGB888p);
// Send the frame
in->send(inFrame);
// Retrieve the resized frame
auto outFrame = out->get<dai::ImgFrame>();
// Check that out frame is resized
if(outFrame->getWidth() != width || outFrame->getHeight() != height){
return -1;
}
}
// Exit with success error code
return 0;
}
this_thread::sleep_for(1s);
} while(!found && steady_clock::now() - wait < 5s );
// Otherwise exit with error
return -1;
}<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "common/logger.h"
namespace peloton {
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
if (parse_tree.get() == nullptr)
return NULL;
std::shared_ptr<planner::AbstractPlan> plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch(parse_item_node_type){
case PARSE_NODE_TYPE_SCAN:
child_plan = new planner::SeqScanPlan();
break;
}
// if (child_plan != nullptr) {
// if (plan_tree != nullptr)
// plan_tree->AddChild(child_plan);
// else
// plan_tree = child_plan;
// }
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<commit_msg>Added parser header to SimpleOptimizer<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "common/logger.h"
namespace peloton {
namespace optimizer {
SimpleOptimizer::SimpleOptimizer() {
}
;
SimpleOptimizer::~SimpleOptimizer() {
}
;
std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
const std::unique_ptr<parser::AbstractParse>& parse_tree) {
if (parse_tree.get() == nullptr)
return NULL;
std::shared_ptr<planner::AbstractPlan> plan_tree;
std::unique_ptr<planner::AbstractPlan> child_plan;
// TODO: Transform the parse tree
// One to one Mapping
auto parse_item_node_type = parse_tree->GetParseNodeType();
switch(parse_item_node_type){
case PARSE_NODE_TYPE_SCAN:
child_plan = new planner::SeqScanPlan();
break;
}
// if (child_plan != nullptr) {
// if (plan_tree != nullptr)
// plan_tree->AddChild(child_plan);
// else
// plan_tree = child_plan;
// }
return plan_tree;
}
} // namespace optimizer
} // namespace peloton
<|endoftext|>
|
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/tensorrt/engine.h"
#include <NvInfer.h>
#include <cuda.h>
#include <glog/logging.h>
#include <string>
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/helper.h"
#include "paddle/fluid/platform/enforce.h"
namespace paddle {
namespace inference {
namespace tensorrt {
int TensorRTEngine::runtime_batch_ = 1;
void TensorRTEngine::InitNetwork() {
freshDeviceId();
infer_builder_.reset(createInferBuilder(&logger_));
if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
infer_networkv2_.reset(infer_builder_->createNetworkV2(
1U << static_cast<int>(
nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
infer_builder_config_.reset(infer_builder_->createBuilderConfig());
infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;
optim_profile_ = infer_builder_->createOptimizationProfile();
#endif
} else {
infer_network_.reset(infer_builder_->createNetwork());
}
}
void TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,
cudaStream_t stream) {
freshDeviceId();
auto infer_context = context();
if (!with_dynamic_shape()) {
infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);
} else {
#if IS_TRT_VERSION_GE(6000)
infer_context->enqueueV2(buffers->data(), stream, nullptr);
#endif
}
SetRuntimeBatch(batch_size);
}
void TensorRTEngine::FreezeNetwork() {
freshDeviceId();
VLOG(3) << "TRT to freeze network";
PADDLE_ENFORCE(infer_builder_ != nullptr,
"Call InitNetwork first to initialize network.");
PADDLE_ENFORCE_EQ(network() != nullptr, true,
platform::errors::InvalidArgument(
"Call InitNetwork first to initialize network."));
// build engine.
infer_builder_->setMaxBatchSize(max_batch_);
infer_builder_->setMaxWorkspaceSize(max_workspace_);
bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);
#if IS_TRT_VERSION_GE(5000)
if (enable_fp16) {
bool support_fp16 = infer_builder_->platformHasFastFp16();
infer_builder_->setFp16Mode(support_fp16);
if (!support_fp16) {
LOG(INFO) << "You specify FP16 mode, but the hardware do not support "
"FP16 speed up, use FP32 instead.";
} else {
LOG(INFO) << "Run Paddle-TRT FP16 mode";
}
}
#else
if (enable_fp16)
LOG(INFO) << "Using FP16 in Paddle-TRT must ensure that the version of TRT "
"is at least 5."
"So, use FP32 to run.";
#endif
bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);
if (enable_int8) {
infer_builder_->setInt8Mode(true);
if (calibrator_) {
infer_builder_->setInt8Calibrator(calibrator_);
} else {
infer_builder_->setInt8Calibrator(nullptr);
#if IS_TRT_VERSION_GE(5000)
infer_builder_->setStrictTypeConstraints(true);
for (auto &quant_range : quant_dynamic_range_) {
auto tensor = quant_range.first;
float range = quant_range.second;
tensor->setDynamicRange(-range, range);
}
std::unordered_set<nvinfer1::ITensor *> all_t;
for (int i = 0; i < network()->getNbLayers(); i++) {
auto layer = network()->getLayer(i);
for (int j = 0; j < layer->getNbOutputs(); j++) {
all_t.insert(layer->getOutput(j));
}
}
for (int i = 0; i < network()->getNbInputs(); i++) {
all_t.insert(network()->getInput(i));
}
for (auto &t : all_t) {
if (!quant_dynamic_range_.count(t)) {
VLOG(3) << "We are in trt int8 mode(not calibration), scale not set"
<< " for tensor " << t->getName()
<< ", this might be ok when trt does not need this range";
}
}
auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {
for (int j = 0; j < layer->getNbInputs(); j++) {
auto *temp_in = layer->getInput(j);
if (!temp_in->dynamicRangeIsSet()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its input("
<< temp_in->getName() << ") doesn't have dynamic range.";
return false;
}
}
for (int j = 0; j < layer->getNbOutputs(); j++) {
auto *temp_out = layer->getOutput(j);
if (temp_out->isNetworkOutput()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its output("
<< temp_out->getName() << ") is the output of the network.";
return false;
}
if (!temp_out->dynamicRangeIsSet()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its output("
<< temp_out->getName() << ") doesn't have dynamic range.";
return false;
}
}
return true;
};
// If a layer's output is the network's output, or not all of its inputs
// and outputs have scales,
// this layer's precision and output type are set to float32.
// This step has no effect if this layer is fused during TRT optimization.
for (int i = 0; i < network()->getNbLayers(); i++) {
auto layer = network()->getLayer(i);
if (!is_layer_int8(layer)) {
layer->setPrecision(nvinfer1::DataType::kFLOAT);
}
}
#endif
}
}
if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
LOG(INFO) << "Run Paddle-TRT Dynamic Shape mode.";
for (auto &input : min_input_shape_) {
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,
Vec2TRT_Dims(input.second, input.first, true));
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,
Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,
Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));
}
infer_builder_config_->addOptimizationProfile(optim_profile_);
if (WithFp16()) {
infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
if (disable_trt_plugin_fp16()) {
LOG(INFO) << "NOTE: In order to achieve higher accuracy, you have "
"disabled the fp16 mode of TRT Plugin,\n"
<< "you can reopen it with "
"'config.SetDynamicShapeInfo(min_shape, max_shape, "
"opt_shape, false /*disable_trt_plugin_fp16*/)'";
}
}
infer_engine_.reset(infer_builder_->buildEngineWithConfig(
*network(), *infer_builder_config_));
#endif
} else {
infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));
}
PADDLE_ENFORCE(infer_engine_ != nullptr, "build cuda engine failed!");
}
nvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,
nvinfer1::DataType dtype,
const nvinfer1::Dims &dims) {
PADDLE_ENFORCE_EQ(network() != nullptr, true,
platform::errors::InvalidArgument(
"The TRT network should be initialized first."));
auto *input = network()->addInput(name.c_str(), dtype, dims);
PADDLE_ENFORCE(input, "infer network add input %s failed", name);
PADDLE_ENFORCE(input->isNetworkInput());
TensorRTEngine::SetITensor(name, input);
return input;
}
void TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,
const std::string &name) {
auto *output = layer->getOutput(offset);
SetITensor(name, output);
PADDLE_ENFORCE(output != nullptr);
output->setName(name.c_str());
PADDLE_ENFORCE(!output->isNetworkInput());
network()->markOutput(*output);
PADDLE_ENFORCE(output->isNetworkOutput());
}
void TensorRTEngine::DeclareOutput(const std::string &name) {
auto *output = TensorRTEngine::GetITensor(name);
PADDLE_ENFORCE(output != nullptr);
output->setName(name.c_str());
PADDLE_ENFORCE(!output->isNetworkInput());
network()->markOutput(*output);
}
void TensorRTEngine::SetITensor(const std::string &name,
nvinfer1::ITensor *tensor) {
PADDLE_ENFORCE(tensor != nullptr);
PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), "duplicate ITensor name %s",
name);
itensor_map_[name] = tensor;
}
nvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {
PADDLE_ENFORCE(itensor_map_.count(name), "no ITensor %s", name);
return itensor_map_[name];
}
void TensorRTEngine::SetRuntimeBatch(size_t batch_size) {
runtime_batch_ = batch_size;
}
float *TensorRTEngine::GetWeightCPUData(const std::string &name,
framework::Tensor *weight_tensor,
bool enable_int8,
const std::vector<float> &scale) {
static int name_suffix_counter = 0;
std::string name_suffix = std::to_string(name_suffix_counter);
std::string splitter = "__";
std::string name_with_suffix = name + splitter + name_suffix;
platform::CPUPlace cpu_place;
PADDLE_ENFORCE_EQ(
weight_map.count(name_with_suffix), 0,
"During TRT Op converter: We set weight %s with the same name "
"twice into the weight_map",
name_with_suffix);
weight_map[name_with_suffix].reset(new framework::Tensor());
weight_map[name_with_suffix]->Resize(weight_tensor->dims());
TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());
float *weight_data =
weight_map[name_with_suffix]->mutable_data<float>(cpu_place);
name_suffix_counter += 1;
return weight_data;
}
int TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }
nvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(
nvinfer1::ITensor *const *inputs, int num_inputs,
plugin::PluginTensorRT *plugin) {
owned_plugin_.emplace_back(plugin);
return network()->addPluginExt(inputs, num_inputs, *plugin);
}
void TensorRTEngine::freshDeviceId() {
int count;
cudaGetDeviceCount(&count);
PADDLE_ENFORCE_LT(device_id_, count);
cudaSetDevice(device_id_);
}
} // namespace tensorrt
} // namespace inference
} // namespace paddle
<commit_msg>add macro check for using TRT api dynamicRangeIsSet() (#25694)<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/tensorrt/engine.h"
#include <NvInfer.h>
#include <cuda.h>
#include <glog/logging.h>
#include <string>
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/helper.h"
#include "paddle/fluid/platform/enforce.h"
namespace paddle {
namespace inference {
namespace tensorrt {
int TensorRTEngine::runtime_batch_ = 1;
void TensorRTEngine::InitNetwork() {
freshDeviceId();
infer_builder_.reset(createInferBuilder(&logger_));
if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
infer_networkv2_.reset(infer_builder_->createNetworkV2(
1U << static_cast<int>(
nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));
infer_builder_config_.reset(infer_builder_->createBuilderConfig());
infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;
optim_profile_ = infer_builder_->createOptimizationProfile();
#endif
} else {
infer_network_.reset(infer_builder_->createNetwork());
}
}
void TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,
cudaStream_t stream) {
freshDeviceId();
auto infer_context = context();
if (!with_dynamic_shape()) {
infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);
} else {
#if IS_TRT_VERSION_GE(6000)
infer_context->enqueueV2(buffers->data(), stream, nullptr);
#endif
}
SetRuntimeBatch(batch_size);
}
void TensorRTEngine::FreezeNetwork() {
freshDeviceId();
VLOG(3) << "TRT to freeze network";
PADDLE_ENFORCE(infer_builder_ != nullptr,
"Call InitNetwork first to initialize network.");
PADDLE_ENFORCE_EQ(network() != nullptr, true,
platform::errors::InvalidArgument(
"Call InitNetwork first to initialize network."));
// build engine.
infer_builder_->setMaxBatchSize(max_batch_);
infer_builder_->setMaxWorkspaceSize(max_workspace_);
bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);
#if IS_TRT_VERSION_GE(5000)
if (enable_fp16) {
bool support_fp16 = infer_builder_->platformHasFastFp16();
infer_builder_->setFp16Mode(support_fp16);
if (!support_fp16) {
LOG(INFO) << "You specify FP16 mode, but the hardware do not support "
"FP16 speed up, use FP32 instead.";
} else {
LOG(INFO) << "Run Paddle-TRT FP16 mode";
}
}
#else
if (enable_fp16)
LOG(INFO) << "Using FP16 in Paddle-TRT must ensure that the version of TRT "
"is at least 5."
"So, use FP32 to run.";
#endif
bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);
if (enable_int8) {
infer_builder_->setInt8Mode(true);
if (calibrator_) {
infer_builder_->setInt8Calibrator(calibrator_);
} else {
infer_builder_->setInt8Calibrator(nullptr);
#if IS_TRT_VERSION_GE(5000)
infer_builder_->setStrictTypeConstraints(true);
for (auto &quant_range : quant_dynamic_range_) {
auto tensor = quant_range.first;
float range = quant_range.second;
tensor->setDynamicRange(-range, range);
}
std::unordered_set<nvinfer1::ITensor *> all_t;
for (int i = 0; i < network()->getNbLayers(); i++) {
auto layer = network()->getLayer(i);
for (int j = 0; j < layer->getNbOutputs(); j++) {
all_t.insert(layer->getOutput(j));
}
}
for (int i = 0; i < network()->getNbInputs(); i++) {
all_t.insert(network()->getInput(i));
}
for (auto &t : all_t) {
if (!quant_dynamic_range_.count(t)) {
VLOG(3) << "We are in trt int8 mode(not calibration), scale not set"
<< " for tensor " << t->getName()
<< ", this might be ok when trt does not need this range";
}
}
#if IS_TRT_VERSION_GE(5122)
auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {
for (int j = 0; j < layer->getNbInputs(); j++) {
auto *temp_in = layer->getInput(j);
if (!temp_in->dynamicRangeIsSet()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its input("
<< temp_in->getName() << ") doesn't have dynamic range.";
return false;
}
}
for (int j = 0; j < layer->getNbOutputs(); j++) {
auto *temp_out = layer->getOutput(j);
if (temp_out->isNetworkOutput()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its output("
<< temp_out->getName() << ") is the output of the network.";
return false;
}
if (!temp_out->dynamicRangeIsSet()) {
VLOG(1) << "Layer(Name: " << layer->getName()
<< ") is set to float32 because its output("
<< temp_out->getName() << ") doesn't have dynamic range.";
return false;
}
}
return true;
};
// If a layer's output is the network's output, or not all of its inputs
// and outputs have scales,
// this layer's precision and output type are set to float32.
// This step has no effect if this layer is fused during TRT optimization.
for (int i = 0; i < network()->getNbLayers(); i++) {
auto layer = network()->getLayer(i);
if (!is_layer_int8(layer)) {
layer->setPrecision(nvinfer1::DataType::kFLOAT);
}
}
#else
LOG(WARNING) << "If your TensorRT version is lower than 5.1.2.2, you "
"must provide quantization scales for all tensors using "
"TRT to run.";
#endif
#endif
}
}
if (with_dynamic_shape_) {
#if IS_TRT_VERSION_GE(6000)
LOG(INFO) << "Run Paddle-TRT Dynamic Shape mode.";
for (auto &input : min_input_shape_) {
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,
Vec2TRT_Dims(input.second, input.first, true));
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,
Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));
optim_profile_->setDimensions(
input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,
Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));
}
infer_builder_config_->addOptimizationProfile(optim_profile_);
if (WithFp16()) {
infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);
if (disable_trt_plugin_fp16()) {
LOG(INFO) << "NOTE: In order to achieve higher accuracy, you have "
"disabled the fp16 mode of TRT Plugin,\n"
<< "you can reopen it with "
"'config.SetDynamicShapeInfo(min_shape, max_shape, "
"opt_shape, false /*disable_trt_plugin_fp16*/)'";
}
}
infer_engine_.reset(infer_builder_->buildEngineWithConfig(
*network(), *infer_builder_config_));
#endif
} else {
infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));
}
PADDLE_ENFORCE(infer_engine_ != nullptr, "build cuda engine failed!");
}
nvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,
nvinfer1::DataType dtype,
const nvinfer1::Dims &dims) {
PADDLE_ENFORCE_EQ(network() != nullptr, true,
platform::errors::InvalidArgument(
"The TRT network should be initialized first."));
auto *input = network()->addInput(name.c_str(), dtype, dims);
PADDLE_ENFORCE(input, "infer network add input %s failed", name);
PADDLE_ENFORCE(input->isNetworkInput());
TensorRTEngine::SetITensor(name, input);
return input;
}
void TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,
const std::string &name) {
auto *output = layer->getOutput(offset);
SetITensor(name, output);
PADDLE_ENFORCE(output != nullptr);
output->setName(name.c_str());
PADDLE_ENFORCE(!output->isNetworkInput());
network()->markOutput(*output);
PADDLE_ENFORCE(output->isNetworkOutput());
}
void TensorRTEngine::DeclareOutput(const std::string &name) {
auto *output = TensorRTEngine::GetITensor(name);
PADDLE_ENFORCE(output != nullptr);
output->setName(name.c_str());
PADDLE_ENFORCE(!output->isNetworkInput());
network()->markOutput(*output);
}
void TensorRTEngine::SetITensor(const std::string &name,
nvinfer1::ITensor *tensor) {
PADDLE_ENFORCE(tensor != nullptr);
PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), "duplicate ITensor name %s",
name);
itensor_map_[name] = tensor;
}
nvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {
PADDLE_ENFORCE(itensor_map_.count(name), "no ITensor %s", name);
return itensor_map_[name];
}
void TensorRTEngine::SetRuntimeBatch(size_t batch_size) {
runtime_batch_ = batch_size;
}
float *TensorRTEngine::GetWeightCPUData(const std::string &name,
framework::Tensor *weight_tensor,
bool enable_int8,
const std::vector<float> &scale) {
static int name_suffix_counter = 0;
std::string name_suffix = std::to_string(name_suffix_counter);
std::string splitter = "__";
std::string name_with_suffix = name + splitter + name_suffix;
platform::CPUPlace cpu_place;
PADDLE_ENFORCE_EQ(
weight_map.count(name_with_suffix), 0,
"During TRT Op converter: We set weight %s with the same name "
"twice into the weight_map",
name_with_suffix);
weight_map[name_with_suffix].reset(new framework::Tensor());
weight_map[name_with_suffix]->Resize(weight_tensor->dims());
TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());
float *weight_data =
weight_map[name_with_suffix]->mutable_data<float>(cpu_place);
name_suffix_counter += 1;
return weight_data;
}
int TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }
nvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(
nvinfer1::ITensor *const *inputs, int num_inputs,
plugin::PluginTensorRT *plugin) {
owned_plugin_.emplace_back(plugin);
return network()->addPluginExt(inputs, num_inputs, *plugin);
}
void TensorRTEngine::freshDeviceId() {
int count;
cudaGetDeviceCount(&count);
PADDLE_ENFORCE_LT(device_id_, count);
cudaSetDevice(device_id_);
}
} // namespace tensorrt
} // namespace inference
} // namespace paddle
<|endoftext|>
|
<commit_before>#include "../../../SDP.hxx"
#include "../../../../Timers.hxx"
El::BigFloat dot(const Block_Vector &a, const Block_Vector &b);
void compute_objectives(const SDP &sdp, const Block_Vector &x,
const Block_Vector &y, El::BigFloat &primal_objective,
El::BigFloat &dual_objective,
El::BigFloat &duality_gap, Timers &timers)
{
auto &objectives_timer(timers.add_and_start("run.objectives"));
primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);
// dual_objective_b is duplicated amongst the processors. y is
// duplicated amongst the blocks, but it is possible for some
// processors to have no blocks. In principle, we only need to
// compute the dot product on the first block, but then we would
// have to make sure that we compute that product over all
// processors that own that block.
if(!y.blocks.empty())
{
dual_objective = sdp.objective_const
+ El::Dotu(sdp.dual_objective_b, y.blocks.front());
}
El::mpi::Broadcast(&dual_objective, 1, 0, El::mpi::COMM_WORLD);
duality_gap
= Abs(primal_objective - dual_objective)
/ Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));
objectives_timer.stop();
}
<commit_msg>Use a simpler version of El::mpi::Broadcast()<commit_after>#include "../../../SDP.hxx"
#include "../../../../Timers.hxx"
El::BigFloat dot(const Block_Vector &a, const Block_Vector &b);
void compute_objectives(const SDP &sdp, const Block_Vector &x,
const Block_Vector &y, El::BigFloat &primal_objective,
El::BigFloat &dual_objective,
El::BigFloat &duality_gap, Timers &timers)
{
auto &objectives_timer(timers.add_and_start("run.objectives"));
primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);
// dual_objective_b is duplicated amongst the processors. y is
// duplicated amongst the blocks, but it is possible for some
// processors to have no blocks. In principle, we only need to
// compute the dot product on the first block, but then we would
// have to make sure that we compute that product over all
// processors that own that block.
if(!y.blocks.empty())
{
dual_objective = sdp.objective_const
+ El::Dotu(sdp.dual_objective_b, y.blocks.front());
}
El::mpi::Broadcast(dual_objective, 0, El::mpi::COMM_WORLD);
duality_gap
= Abs(primal_objective - dual_objective)
/ Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));
objectives_timer.stop();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dynamicregister.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_testshl2.hxx"
#include "dynamicregister.hxx"
#include <osl/process.h>
// #include <osl/mutex.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include "filehelper.hxx"
// -----------------------------------------------------------------------------
DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions)
:m_pModule(new ::osl::Module()),
m_suDLLName(_sDLLName),
m_aOptions(_aOptions)
{
// create and load the module (shared library)
rtl::OUString suFile = FileHelper::convertPath( _sDLLName );
rtl::OString sDLLName = rtl::OUStringToOString(suFile, RTL_TEXTENCODING_ASCII_US);
if (_aOptions.hasOpt("-verbose"))
{
fprintf(stderr, "Try to load '%s'.\n", sDLLName.getStr());
}
if (! m_pModule->load(suFile, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))
{
sDLLName = rtl::OUStringToOString(_sDLLName, RTL_TEXTENCODING_ASCII_US);
fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr());
}
}
DynamicLibraryHelper::~DynamicLibraryHelper()
{
delete m_pModule;
}
<commit_msg>INTEGRATION: CWS ause093 (1.9.6); FILE MERGED 2008/05/07 11:10:44 lla 1.9.6.3: #i88845# cleanup, for load library locally or absolutely 2008/05/06 12:08:20 hjs 1.9.6.2: #i88845# set of changes from lla to get specified library loaded 2008/05/06 06:42:35 lla 1.9.6.1: #i88845# changes for macosx usage<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: dynamicregister.cxx,v $
* $Revision: 1.10 $
*
* 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_testshl2.hxx"
#include "dynamicregister.hxx"
#include <osl/process.h>
// #include <osl/mutex.hxx>
#include <rtl/string.hxx>
#include <rtl/ustring.hxx>
#include "filehelper.hxx"
#include <unistd.h>
#if defined(WIN32)
#include <direct.h> /* w.g. _chdir() */
#endif
namespace fixes
{
void changedir(const char* _sPath)
{
#if defined(WIN32)
// chdir(_sPath) is marked depricated since Visual C++ 2005
// use _chdir instead
::_chdir(_sPath);
#else
::chdir(_sPath);
#endif
}
}
// -----------------------------------------------------------------------------
DynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _suDLLName, GetOpt & _aOptions)
:m_pModule(new ::osl::Module()),
m_suDLLName(_suDLLName),
m_aOptions(_aOptions)
{
// create and load the module (shared library)
m_suAbsolutePathFile = FileHelper::convertPath( _suDLLName );
// due to some problems on mac OS
// we split the absolute pathname to path and filename
// change to the path and load the filename direct
// then change back to the old path.
rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("/"));
sal_Int32 nPos = m_suAbsolutePathFile.lastIndexOf(suPathSeparator);
if (nPos != -1)
{
m_suAbsolutePath = m_suAbsolutePathFile.copy(0, nPos);
m_suFilename = m_suAbsolutePathFile.copy(nPos + 1);
}
else
{
// Should never happen.
rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePathFile, RTL_TEXTENCODING_ASCII_US);
fprintf(stderr, "There is a problem with path '%s'.\n", sPath.getStr());
exit(1);
}
if (getOptions().hasOpt("-absolutepath"))
{
fprintf(stderr, "Hint: Use absolute path to load test library.\n");
loadLibraryFromAbsolutePath();
}
else if (getOptions().hasOpt("-localpath"))
{
fprintf(stderr, "Hint: make a chdir() to the test library, then try to load the test library without given path.\n");
loadLibraryFromLocalPath();
}
else
{
// PLEASE DON'T CHANGE THIS STUPID STRUCTURE, JUST ADD YOUR ENVIRONMENT
#if defined(LINUX)
loadLibraryFromAbsolutePath();
// will fail if load local
#elif defined(SOLARIS)
loadLibraryFromAbsolutePath();
// will also be right if load local
#elif defined(WIN32)
loadLibraryFromAbsolutePath();
// will fail if load local
#elif defined(MACOSX)
loadLibraryFromLocalPath();
// will fail if local absolute
#else
// default is load absolute
loadLibraryFromAbsolutePath();
#endif
}
}
void DynamicLibraryHelper::showFilenameIfVerbose()
{
if (getOptions().hasOpt("-verbose"))
{
rtl::OString sFilename = rtl::OUStringToOString(m_suFilename, RTL_TEXTENCODING_ASCII_US);
rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePath, RTL_TEXTENCODING_ASCII_US);
fprintf(stderr, "Try to load '%s' from '%s'.\n", sFilename.getStr(), sPath.getStr());
// check filename
}
}
void DynamicLibraryHelper::realLoadLibrary(rtl::OUString const& _suLibToLoad)
{
if (! m_pModule->load(_suLibToLoad, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))
{
rtl::OString sDLLName = rtl::OUStringToOString(m_suDLLName, RTL_TEXTENCODING_ASCII_US);
fprintf(stderr, "warning: Can't load module '%s'.\n", sDLLName.getStr());
}
}
void DynamicLibraryHelper::loadLibraryFromAbsolutePath()
{
showFilenameIfVerbose();
realLoadLibrary(m_suAbsolutePathFile);
}
void DynamicLibraryHelper::loadLibraryFromLocalPath()
{
sal_Int32 nPos;
rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("/"));
#if defined(WIN32)
suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii("\\"));
#endif
rtl::OUString suSystemPathFile;
osl::FileBase::getSystemPathFromFileURL(m_suAbsolutePathFile, suSystemPathFile);
nPos = suSystemPathFile.lastIndexOf(suPathSeparator);
rtl::OUString suCurrentDirPath;
if (nPos != -1)
{
// the filename only, no '/' in the path
rtl::OUString suNewPath = suSystemPathFile.copy(0, nPos );
if (suNewPath.getLength() > 0)
{
rtl::OString sPath = rtl::OUStringToOString(suNewPath, RTL_TEXTENCODING_ASCII_US);
osl_getProcessWorkingDir( &suCurrentDirPath.pData );
fixes::changedir(sPath.getStr());
// curNewDirPath should be suPath, small self test
rtl::OUString curNewDirPath;
osl_getProcessWorkingDir( &curNewDirPath.pData );
if (! curNewDirPath.equals(m_suAbsolutePath))
{
fprintf(stderr, "There is a problem with path '%s'.\n", sPath.getStr());
}
}
}
showFilenameIfVerbose();
realLoadLibrary(m_suFilename);
// change back to old directory
if (suCurrentDirPath.getLength() > 0)
{
rtl::OString sCurrentDirPath = rtl::OUStringToOString(suCurrentDirPath, RTL_TEXTENCODING_ASCII_US);
fixes::changedir(sCurrentDirPath.getStr());
}
}
DynamicLibraryHelper::~DynamicLibraryHelper()
{
if (getOptions().hasOpt("-verbose"))
{
fprintf(stderr, "Dtor DynamicLibraryHelper.\n");
fprintf(stderr, "Delete loaded module.");
}
delete m_pModule;
if (getOptions().hasOpt("-verbose"))
{
fprintf(stderr, " [done].\n");
}
}
<|endoftext|>
|
<commit_before>/*
* This file is part ServerManager of package
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
#include "./Files.h"
#include "./Strings.h"
using namespace ServerManager;
using namespace std;
Manager::Manager(){}
void Manager::setConfiguration(Configuration config)
{
this->config = config;
}
string Manager::search(string hostName)
{
string cmd = "cat " + this->config.hosts + " | grep " + hostName;
Console console(cmd);
return console.exec();
}
string Manager::getList()
{
ifstream file(this->config.hosts.c_str());
string line, result;
if (file.good()) {
while(getline(file, line)) {
istringstream line_string(line);
string key;
if (line.find(" ") != std::string::npos) {
if (getline(line_string, key, ' ')) {
this->appendLine(&result, key, line);
}
} else {
if (getline(line_string, key, '\t')) {
this->appendLine(&result, key, line);
}
}
}
file.close();
return result;
} else {
file.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
}
string Manager::create(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
if (hostsFile.good()) {
hostsFile << endl << this->getHostConfig(hostName);
result.append("\nAdded virtual host into hosts file");
hostsFile.close();
} else {
hostsFile.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
string path = this->config.nginx + "/" + hostName + ".conf";
ofstream nginxConfig(path.c_str());
if (nginxConfig.good()) {
nginxConfig << this->getServerConfig(hostName);
if(nginxConfig.good()) {
result.append("\nAdded virtual host nginx configuration");
}
if(!this->config.project.empty()) {
Console testGitRepository("git ls-remote " + this->config.project + " --exit-code");
if(testGitRepository.exec().empty()) {
Console cloneGitRepository("git clone " + this->config.project + " " + this->config.htdocs + "/" + hostName);
cloneGitRepository.exec();
result.append("\nCreated project from git repository");
} else {
nginxConfig.close();
throw "Check if repository of project is valid: " + this->config.project;
}
} else {
Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log);
Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
result.append("\nCreated base project directories: ");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log);
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
}
}
nginxConfig.close();
} else {
nginxConfig.close();
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
if (chmodCmd.exec().empty()) {
result.append("\nSet chmod");
}
return result;
}
string Manager::remove(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
if (rmProject.exec().empty()) {
result.append("\nProject directory has been removed");
} else {
throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
}
if (rmNginxConf.exec().empty()) {
result.append("\nNginx configuration has been removed");
} else {
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
ifstream ihostFile(this->config.hosts.c_str());
if (ihostFile.good()) {
string line, newContent = "";
while(getline(ihostFile, line)) {
if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) {
newContent.append(line + "\n");
}
}
ofstream ohostFile(this->config.hosts.c_str());
ohostFile << newContent;
result.append("\nVirtual host has been removed from hosts file");
ihostFile.close();
ohostFile.close();
} else {
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
ihostFile.close();
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
return result;
}
void Manager::appendLine(string* result,string key, string line)
{
if (key.compare("127.0.0.1") == 0) {
(*result).append(line + "\n");
}
}
string Manager::getServerConfig(string hostName)
{
Files files;
Strings strings;
string content = files.getString(this->config.serverTemplate);
string config = strings.replace("%hostName%", hostName, content);
config = strings.replace("%tld%", this->config.tld, config);
config = strings.replace("%htdocs%", this->config.htdocs, config);
config = strings.replace("%root%", this->config.root, config);
config = strings.replace("%log%", this->config.log, config);
return config;
}
string Manager::getHostConfig(string hostName)
{
Files files;
Strings strings;
string content = files.getString(this->config.systemTemplate);
string host = strings.replace("%hostName%", hostName, content);
host = strings.replace("%tld%", this->config.tld, host);
return host;
}
<commit_msg>Manager create: do not allow duplicates, throw exception<commit_after>/*
* This file is part ServerManager of package
*
* (c) Ondřej Záruba <zarubaondra@gmail.com>
*
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
#include "./Files.h"
#include "./Strings.h"
using namespace ServerManager;
using namespace std;
Manager::Manager(){}
void Manager::setConfiguration(Configuration config)
{
this->config = config;
}
string Manager::search(string hostName)
{
string cmd = "cat " + this->config.hosts + " | grep " + hostName;
Console console(cmd);
return console.exec();
}
string Manager::getList()
{
ifstream file(this->config.hosts.c_str());
string line, result;
if (file.good()) {
while(getline(file, line)) {
istringstream line_string(line);
string key;
if (line.find(" ") != std::string::npos) {
if (getline(line_string, key, ' ')) {
this->appendLine(&result, key, line);
}
} else {
if (getline(line_string, key, '\t')) {
this->appendLine(&result, key, line);
}
}
}
file.close();
return result;
} else {
file.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
}
string Manager::create(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
if (!hostsFile.good()) {
hostsFile.close();
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
}
if (!this->search(hostName).empty()) {
hostsFile.close();
throw "Hostname already exists";
}
hostsFile << endl << this->getHostConfig(hostName);
result.append("\nAdded virtual host into hosts file");
hostsFile.close();
string path = this->config.nginx + "/" + hostName + ".conf";
ofstream nginxConfig(path.c_str());
if (nginxConfig.good()) {
nginxConfig << this->getServerConfig(hostName);
if(nginxConfig.good()) {
result.append("\nAdded virtual host nginx configuration");
}
if(!this->config.project.empty()) {
Console testGitRepository("git ls-remote " + this->config.project + " --exit-code");
if(testGitRepository.exec().empty()) {
Console cloneGitRepository("git clone " + this->config.project + " " + this->config.htdocs + "/" + hostName);
cloneGitRepository.exec();
result.append("\nCreated project from git repository");
} else {
nginxConfig.close();
throw "Check if repository of project is valid: " + this->config.project;
}
} else {
Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log);
Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
result.append("\nCreated base project directories: ");
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log);
result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
}
}
nginxConfig.close();
} else {
nginxConfig.close();
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
if (chmodCmd.exec().empty()) {
result.append("\nSet chmod");
}
return result;
}
string Manager::remove(string hostName)
{
string result;
Console console("nginx -s stop");
if (console.exec().empty()) {
result.append("Stoping nginx");
}
Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
if (rmProject.exec().empty()) {
result.append("\nProject directory has been removed");
} else {
throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
}
if (rmNginxConf.exec().empty()) {
result.append("\nNginx configuration has been removed");
} else {
throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
}
ifstream ihostFile(this->config.hosts.c_str());
if (ihostFile.good()) {
string line, newContent = "";
while(getline(ihostFile, line)) {
if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) {
newContent.append(line + "\n");
}
}
ofstream ohostFile(this->config.hosts.c_str());
ohostFile << newContent;
result.append("\nVirtual host has been removed from hosts file");
ihostFile.close();
ohostFile.close();
} else {
throw "Invalid path to hosts file or you don't run as administrator(sudo)";
ihostFile.close();
}
Console nginxStart("nginx");
if (nginxStart.exec().empty()) {
result.append("\nStarting nginx");
}
return result;
}
void Manager::appendLine(string* result,string key, string line)
{
if (key.compare("127.0.0.1") == 0) {
(*result).append(line + "\n");
}
}
string Manager::getServerConfig(string hostName)
{
Files files;
Strings strings;
string content = files.getString(this->config.serverTemplate);
string config = strings.replace("%hostName%", hostName, content);
config = strings.replace("%tld%", this->config.tld, config);
config = strings.replace("%htdocs%", this->config.htdocs, config);
config = strings.replace("%root%", this->config.root, config);
config = strings.replace("%log%", this->config.log, config);
return config;
}
string Manager::getHostConfig(string hostName)
{
Files files;
Strings strings;
string content = files.getString(this->config.systemTemplate);
string host = strings.replace("%hostName%", hostName, content);
host = strings.replace("%tld%", this->config.tld, host);
return host;
}
<|endoftext|>
|
<commit_before>/************************************************
* 该例程讲解用C++11来实现一个ScopeGuard类
************************************************/
#include "ScopeGuard.hpp"
#include <iostream>
#include <functional>
int main()
{
std::function<void()> func = []
{
std::cout << "Cleanup from unnormal exit" << std::endl;
};
{
// 正常退出
auto ret = makeGuard(func);
ret.dismiss();
}
{
// 非正常退出,调用func函数
makeGuard(func);
}
return 0;
}
<commit_msg>Update scopeguard<commit_after>/************************************************
* 该例程讲解用C++11来实现一个ScopeGuard类
************************************************/
#include "ScopeGuard.hpp"
#include <iostream>
#include <functional>
int main()
{
std::function<void()> func = []
{
std::cout << "Cleanup from unnormal exit" << std::endl;
};
{
// 正常退出
auto ret = makeGuard(func);
ret.dismiss();
}
{
// 非正常退出,调用func函数
auto ret = makeGuard(func);
}
return 0;
}
<|endoftext|>
|
<commit_before>/** @file main.cc
*
* Driver file for testing LCC
*
* @author Nishant Mehta (niche)
*/
// example for running program via fx-run on no.cc.gatech.edu:
// fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,
#include <fastlib/fastlib.h>
#include <armadillo>
#include "lcc.h"
using namespace arma;
using namespace std;
int main(int argc, char* argv[]) {
fx_module* root = fx_init(argc, argv, NULL);
double lambda = fx_param_double_req(NULL, "lambda");
// if using fx-run, one could just leave results_dir blank
const char* results_dir = fx_param_str(NULL, "results_dir", "");
const char* data_dir =
fx_param_str_req(NULL, "data_dir");
//const char* initial_dictionary_fullpath =
// fx_param_str_req(NULL, "initial_dictionary");
u32 digit_1 = fx_param_int_req(NULL, "digit1");
u32 digit_2 = fx_param_int_req(NULL, "digit2");
u32 n_iterations = fx_param_int_req(NULL, "n_iterations");
u32 n_atoms = fx_param_int_req(NULL, "n_atoms");
// Load Data
char* data_filename = (char*) malloc(320 * sizeof(char));
sprintf(data_filename,
"%s/train%d.arm",
data_dir,
digit_1);
mat X_neg;
X_neg.load(data_filename);
u32 n_neg_points = X_neg.n_cols;
sprintf(data_filename,
"%s/train%d.arm",
data_dir,
digit_2);
mat X_pos;
X_pos.load(data_filename);
u32 n_pos_points = X_pos.n_cols;
free(data_filename);
mat X = join_rows(X_neg, X_pos);
u32 n_points = X.n_cols;
// normalize each column of data
for(u32 i = 0; i < n_points; i++) {
X.col(i) /= norm(X.col(i), 2);
}
// create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program
vec y = vec(n_points);
y.subvec(0, n_neg_points - 1).fill(-1);
y.subvec(n_neg_points, n_points - 1).fill(1);
// run LCC
LocalCoordinateCoding lcc;
//mat initial_D;
//initial_D.load("/home/niche/fastlib-stl/contrib/niche/local_coordinate_coding/D.dat");
//initial_D.load(initial_dictionary_fullpath);
//u32 n_atoms = initial_D.n_cols;
lcc.Init(X, n_atoms, lambda);
lcc.DataDependentRandomInitDictionary();
//printf("n_atoms = %d\n", n_atoms);
wall_clock timer;
timer.tic();
lcc.DoLCC(n_iterations);
double n_secs = timer.toc();
cout << "took " << n_secs << " seconds" << endl;
mat learned_D;
lcc.GetDictionary(learned_D);
mat learned_V;
lcc.GetCoding(learned_V);
if(strlen(results_dir) == 0) {
learned_D.save("D.dat", raw_ascii);
learned_V.save("V.dat", raw_ascii);
y.save("y.dat", raw_ascii);
}
else {
char* data_fullpath = (char*) malloc(320 * sizeof(char));
sprintf(data_fullpath, "%s/D.dat", results_dir);
learned_D.save(data_fullpath, raw_ascii);
sprintf(data_fullpath, "%s/V.dat", results_dir);
learned_V.save(data_fullpath, raw_ascii);
sprintf(data_fullpath, "%s/y.dat", results_dir);
y.save(data_fullpath, raw_ascii);
free(data_fullpath);
}
fx_done(root);
}
<commit_msg>changed mnist_main to allow specification of initial dictionary<commit_after>/** @file main.cc
*
* Driver file for testing LCC
*
* @author Nishant Mehta (niche)
*/
// example for running program via fx-run on no.cc.gatech.edu:
// fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,
#include <fastlib/fastlib.h>
#include <armadillo>
#include "lcc.h"
using namespace arma;
using namespace std;
int main(int argc, char* argv[]) {
fx_module* root = fx_init(argc, argv, NULL);
double lambda = fx_param_double_req(NULL, "lambda");
// if using fx-run, one could just leave results_dir blank
const char* results_dir = fx_param_str(NULL, "results_dir", "");
const char* data_dir =
fx_param_str_req(NULL, "data_dir");
const char* initial_dictionary_fullpath =
fx_param_str(NULL, "initial_dictionary", "");
u32 digit_1 = fx_param_int_req(NULL, "digit1");
u32 digit_2 = fx_param_int_req(NULL, "digit2");
u32 n_iterations = fx_param_int_req(NULL, "n_iterations");
u32 n_atoms = fx_param_int_req(NULL, "n_atoms");
// Load Data
char* data_filename = (char*) malloc(320 * sizeof(char));
sprintf(data_filename,
"%s/train%d.arm",
data_dir,
digit_1);
mat X_neg;
X_neg.load(data_filename);
u32 n_neg_points = X_neg.n_cols;
sprintf(data_filename,
"%s/train%d.arm",
data_dir,
digit_2);
mat X_pos;
X_pos.load(data_filename);
u32 n_pos_points = X_pos.n_cols;
free(data_filename);
mat X = join_rows(X_neg, X_pos);
u32 n_points = X.n_cols;
// normalize each column of data
for(u32 i = 0; i < n_points; i++) {
X.col(i) /= norm(X.col(i), 2);
}
// create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program
vec y = vec(n_points);
y.subvec(0, n_neg_points - 1).fill(-1);
y.subvec(n_neg_points, n_points - 1).fill(1);
// run LCC
LocalCoordinateCoding lcc;
lcc.Init(X, n_atoms, lambda);
if(strlen(initial_dictionary_fullpath) == 0) {
lcc.DataDependentRandomInitDictionary();
}
else {
mat initial_D;
initial_D.load(initial_dictionary_fullpath);
if(initial_D.n_cols != n_atoms) {
fprintf(stderr, "Error: The specified initial dictionary to load has %d atoms, but the learned dictionary was specified to have %d atoms! Exiting..\n",
initial_D.n_cols,
n_atoms);
return EXIT_FAILURE;
}
if(initial_D.n_rows != X.n_rows) {
fprintf(stderr, "Error: The specified initial dictionary to load has %d dimensions, but the specified data has %d dimensions! Exiting..\n",
initial_D.n_rows,
X.n_rows);
return EXIT_FAILURE;
}
lcc.SetDictionary(initial_D);
}
wall_clock timer;
timer.tic();
lcc.DoLCC(n_iterations);
double n_secs = timer.toc();
cout << "took " << n_secs << " seconds" << endl;
mat learned_D;
lcc.GetDictionary(learned_D);
mat learned_V;
lcc.GetCoding(learned_V);
if(strlen(results_dir) == 0) {
learned_D.save("D.dat", raw_ascii);
learned_V.save("V.dat", raw_ascii);
y.save("y.dat", raw_ascii);
}
else {
char* data_fullpath = (char*) malloc(320 * sizeof(char));
sprintf(data_fullpath, "%s/D.dat", results_dir);
learned_D.save(data_fullpath, raw_ascii);
sprintf(data_fullpath, "%s/V.dat", results_dir);
learned_V.save(data_fullpath, raw_ascii);
sprintf(data_fullpath, "%s/y.dat", results_dir);
y.save(data_fullpath, raw_ascii);
free(data_fullpath);
}
fx_done(root);
}
<|endoftext|>
|
<commit_before>#include "Buffer.h"
#include "System/Common.h"
#include <stdarg.h>
#include <stdlib.h>
Buffer::Buffer()
{
Init();
}
Buffer::~Buffer()
{
if (buffer != array && !preallocated)
free(buffer);
}
void Buffer::SetPreallocated(char* buffer_, unsigned size_)
{
preallocated = true;
buffer = buffer_;
size = size_;
}
int Buffer::Cmp(const Buffer& a, const Buffer& b)
{
int ret;
unsigned alen, blen;
alen = a.length;
blen = b.length;
ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
int Buffer::Cmp(const char* buffer_, unsigned length_)
{
int ret;
unsigned alen, blen;
alen = length;
blen = length_;
ret = memcmp(buffer, buffer_, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
int Buffer::Cmp(const char* str)
{
int ret;
unsigned alen, blen;
alen = length;
blen = strlen(str);
ret = memcmp(buffer, str, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
void Buffer::Lengthen(unsigned k)
{
length += k;
}
void Buffer::Shorten(unsigned k)
{
length -= k;
}
void Buffer::Allocate(unsigned size_, bool keepold)
{
char* newbuffer;
if (size_ <= size)
return;
size_ = NextPowerOfTwo(size_);
if (buffer == array || preallocated)
newbuffer = (char*) malloc(size_);
else
newbuffer = (char*) realloc(buffer, size_);
ASSERT(newbuffer != NULL);
if (keepold && length > 0)
{
if (buffer == array)
memcpy(newbuffer, buffer, length);
}
buffer = newbuffer;
size = size_;
preallocated = false;
}
int Buffer::Readf(const char* format, ...) const
{
int read;
va_list ap;
va_start(ap, format);
read = VReadf(buffer, length, format, ap);
va_end(ap);
return read;
}
unsigned Buffer::Writef(const char* fmt, ...)
{
unsigned required;
va_list ap;
while (true)
{
va_start(ap, fmt);
required = VWritef(buffer, size, fmt, ap);
va_end(ap);
if (required <= size)
{
length = required;
break;
}
Allocate(required, false);
}
return length;
}
unsigned Buffer::Appendf(const char* fmt, ...)
{
unsigned required;
va_list ap;
while (true)
{
va_start(ap, fmt);
required = VWritef(GetPosition(), GetRemaining(), fmt, ap);
va_end(ap);
// snwritef returns number of bytes required
if (required <= GetRemaining())
break;
Allocate(length + required, true);
}
length += required;
return required;
}
void Buffer::Write(const char* buffer_, unsigned length_)
{
if (length_ > size)
Allocate(length_);
memmove(buffer, buffer_, length_);
length = length_;
}
void Buffer::Write(const char* str)
{
Write(str, strlen(str));
}
void Buffer::Write(Buffer& other)
{
Write(other.GetBuffer(), other.GetLength());
}
void Buffer::Write(ReadBuffer other)
{
Write(other.GetBuffer(), other.GetLength());
}
void Buffer::Append(char c)
{
Append(&c, 1);
}
void Buffer::Append(const char* buffer_, unsigned length_)
{
if (length_ > GetRemaining())
Allocate(length + length_);
memcpy(GetPosition(), buffer_, length_);
Lengthen(length_);
}
void Buffer::Append(const char* str)
{
Append(str, strlen(str));
}
void Buffer::Append(Buffer& other)
{
Append(other.GetBuffer(), other.GetLength());
}
void Buffer::Append(ReadBuffer other)
{
Append(other.GetBuffer(), other.GetLength());
}
void Buffer::AppendLittle16(uint16_t x)
{
x = ToLittle16(x);
Append((const char*) &x, sizeof(uint16_t));
}
void Buffer::AppendLittle32(uint32_t x)
{
x = ToLittle32(x);
Append((const char*) &x, sizeof(uint32_t));
}
void Buffer::AppendLittle64(uint64_t x)
{
x = ToLittle64(x);
Append((const char*) &x, sizeof(uint64_t));
}
char Buffer::GetCharAt(unsigned i)
{
if (i > length - 1)
ASSERT_FAIL();
return *(buffer + i);
}
void Buffer::SetCharAt(unsigned i, char c)
{
buffer[i] = c;
}
bool Buffer::IsAsciiPrintable()
{
unsigned i;
for (i = 0; i < length; i++)
{
if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)
return false;
}
return true;
}
void Buffer::ToHexadecimal()
{
unsigned i;
unsigned x;
Buffer printable;
printable.Allocate(length * 3);
for (i = 0; i < length; i++)
{
x = (unsigned char) buffer[i];
printable.Appendf("%x ", x);
}
Write(printable);
}
void Buffer::NullTerminate()
{
Append("", 1);
}
void Buffer::Zero()
{
memset(buffer, 0, size);
}
void Buffer::ZeroRest()
{
memset(buffer + length, 0, size - length);
}
void Buffer::SetLength(unsigned length_)
{
length = length_;
if (length > size)
ASSERT_FAIL();
}
void Buffer::Init()
{
buffer = array;
size = SIZE(array);
length = 0;
preallocated = false;
prev = next = this;
}
unsigned Buffer::GetSize()
{
return size;
}
char* Buffer::GetBuffer()
{
return buffer;
}
unsigned Buffer::GetLength()
{
return length;
}
unsigned Buffer::GetRemaining()
{
return size - length;
}
char* Buffer::GetPosition()
{
return buffer + length;
}
uint32_t Buffer::GetChecksum()
{
return ChecksumBuffer(buffer, length);
}
void Buffer::Clear()
{
length = 0;
}
void Buffer::Reset()
{
if (buffer != array && !preallocated)
free(buffer);
Init();
}
Buffer::Buffer(const Buffer& other)
{
// ASSERT_FAIL();
Init();
*this = other; // call operator=()
}
Buffer& Buffer::operator=(const Buffer& other)
{
// ASSERT_FAIL();
if (other.size != size)
Allocate(other.size, false);
memcpy(buffer, other.buffer, other.size);
length = other.length;
prev = next = this;
return *this;
}
<commit_msg>Fixed hex conversion in buffer.<commit_after>#include "Buffer.h"
#include "System/Common.h"
#include <stdarg.h>
#include <stdlib.h>
Buffer::Buffer()
{
Init();
}
Buffer::~Buffer()
{
if (buffer != array && !preallocated)
free(buffer);
}
void Buffer::SetPreallocated(char* buffer_, unsigned size_)
{
preallocated = true;
buffer = buffer_;
size = size_;
}
int Buffer::Cmp(const Buffer& a, const Buffer& b)
{
int ret;
unsigned alen, blen;
alen = a.length;
blen = b.length;
ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
int Buffer::Cmp(const char* buffer_, unsigned length_)
{
int ret;
unsigned alen, blen;
alen = length;
blen = length_;
ret = memcmp(buffer, buffer_, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
int Buffer::Cmp(const char* str)
{
int ret;
unsigned alen, blen;
alen = length;
blen = strlen(str);
ret = memcmp(buffer, str, MIN(alen, blen));
if (ret != 0)
return ret;
if (alen < blen)
return -1;
else if (blen < alen)
return 1;
else
return 0;
}
void Buffer::Lengthen(unsigned k)
{
length += k;
}
void Buffer::Shorten(unsigned k)
{
length -= k;
}
void Buffer::Allocate(unsigned size_, bool keepold)
{
char* newbuffer;
if (size_ <= size)
return;
size_ = NextPowerOfTwo(size_);
if (buffer == array || preallocated)
newbuffer = (char*) malloc(size_);
else
newbuffer = (char*) realloc(buffer, size_);
ASSERT(newbuffer != NULL);
if (keepold && length > 0)
{
if (buffer == array)
memcpy(newbuffer, buffer, length);
}
buffer = newbuffer;
size = size_;
preallocated = false;
}
int Buffer::Readf(const char* format, ...) const
{
int read;
va_list ap;
va_start(ap, format);
read = VReadf(buffer, length, format, ap);
va_end(ap);
return read;
}
unsigned Buffer::Writef(const char* fmt, ...)
{
unsigned required;
va_list ap;
while (true)
{
va_start(ap, fmt);
required = VWritef(buffer, size, fmt, ap);
va_end(ap);
if (required <= size)
{
length = required;
break;
}
Allocate(required, false);
}
return length;
}
unsigned Buffer::Appendf(const char* fmt, ...)
{
unsigned required;
va_list ap;
while (true)
{
va_start(ap, fmt);
required = VWritef(GetPosition(), GetRemaining(), fmt, ap);
va_end(ap);
// snwritef returns number of bytes required
if (required <= GetRemaining())
break;
Allocate(length + required, true);
}
length += required;
return required;
}
void Buffer::Write(const char* buffer_, unsigned length_)
{
if (length_ > size)
Allocate(length_);
memmove(buffer, buffer_, length_);
length = length_;
}
void Buffer::Write(const char* str)
{
Write(str, strlen(str));
}
void Buffer::Write(Buffer& other)
{
Write(other.GetBuffer(), other.GetLength());
}
void Buffer::Write(ReadBuffer other)
{
Write(other.GetBuffer(), other.GetLength());
}
void Buffer::Append(char c)
{
Append(&c, 1);
}
void Buffer::Append(const char* buffer_, unsigned length_)
{
if (length_ > GetRemaining())
Allocate(length + length_);
memcpy(GetPosition(), buffer_, length_);
Lengthen(length_);
}
void Buffer::Append(const char* str)
{
Append(str, strlen(str));
}
void Buffer::Append(Buffer& other)
{
Append(other.GetBuffer(), other.GetLength());
}
void Buffer::Append(ReadBuffer other)
{
Append(other.GetBuffer(), other.GetLength());
}
void Buffer::AppendLittle16(uint16_t x)
{
x = ToLittle16(x);
Append((const char*) &x, sizeof(uint16_t));
}
void Buffer::AppendLittle32(uint32_t x)
{
x = ToLittle32(x);
Append((const char*) &x, sizeof(uint32_t));
}
void Buffer::AppendLittle64(uint64_t x)
{
x = ToLittle64(x);
Append((const char*) &x, sizeof(uint64_t));
}
char Buffer::GetCharAt(unsigned i)
{
if (i > length - 1)
ASSERT_FAIL();
return *(buffer + i);
}
void Buffer::SetCharAt(unsigned i, char c)
{
buffer[i] = c;
}
bool Buffer::IsAsciiPrintable()
{
unsigned i;
for (i = 0; i < length; i++)
{
if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)
return false;
}
return true;
}
void Buffer::ToHexadecimal()
{
unsigned i;
unsigned char x;
Buffer printable;
const char digits[] = "0123456789ABCDEF";
printable.Allocate(length * 3);
for (i = 0; i < length; i++)
{
x = (unsigned char) buffer[i];
printable.Append(digits[x / 16]);
printable.Append(digits[x % 16]);
if (i != length - 1)
printable.Append(' ');
}
Write(printable);
}
void Buffer::NullTerminate()
{
Append("", 1);
}
void Buffer::Zero()
{
memset(buffer, 0, size);
}
void Buffer::ZeroRest()
{
memset(buffer + length, 0, size - length);
}
void Buffer::SetLength(unsigned length_)
{
length = length_;
if (length > size)
ASSERT_FAIL();
}
void Buffer::Init()
{
buffer = array;
size = SIZE(array);
length = 0;
preallocated = false;
prev = next = this;
}
unsigned Buffer::GetSize()
{
return size;
}
char* Buffer::GetBuffer()
{
return buffer;
}
unsigned Buffer::GetLength()
{
return length;
}
unsigned Buffer::GetRemaining()
{
return size - length;
}
char* Buffer::GetPosition()
{
return buffer + length;
}
uint32_t Buffer::GetChecksum()
{
return ChecksumBuffer(buffer, length);
}
void Buffer::Clear()
{
length = 0;
}
void Buffer::Reset()
{
if (buffer != array && !preallocated)
free(buffer);
Init();
}
Buffer::Buffer(const Buffer& other)
{
// ASSERT_FAIL();
Init();
*this = other; // call operator=()
}
Buffer& Buffer::operator=(const Buffer& other)
{
// ASSERT_FAIL();
if (other.size != size)
Allocate(other.size, false);
memcpy(buffer, other.buffer, other.size);
length = other.length;
prev = next = this;
return *this;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2009 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "MacDisplay.h"
#include "BzfEvent.h"
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
bool MacDisplay::pending;
CGrafPtr MacDisplay::window;
CGLContextObj MacDisplay::context;
MacDisplay::MacDisplay() {
pending = true;
setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),
CGDisplayPixelsHigh(kCGDirectMainDisplay));
}
MacDisplay::MacDisplay(const char *, const char *) {
#pragma unused (name, videoFormat)
is_valid = true;
pending = false;
cursor_region = CGPathCreateMutable();
ResInfo** resInfo = NULL;
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
CGDisplayPixelsWide(kCGDirectMainDisplay),
CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);
//numModes = 1;
//currentMode = 0;
// register modes
initResolutions(resInfo, 1, 0);
}
bool MacDisplay::isEventPending() const
{
::OSStatus status = ::noErr;
::EventRef eventRef = 0;
status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);
return (status == ::noErr) ? true : false;
}
bool MacDisplay::peekEvent (BzfEvent &) const
{
return false;
}
bool MacDisplay::getEvent (BzfEvent &bzf_event) const {
::EventRef eventRef = 0;
::OSStatus status = ::noErr;
::UInt32 eventClass = 0;
::UInt32 eventKind = 0;
::EventTime eventTime = 0;
::HIPoint eventLocation = {0, 0};
::HIPoint eventDelta = {0, 0};
::UInt32 eventModifiers = 0;
::EventMouseButton eventButtons = 0;
char eventChar = 0;
::UInt32 eventKeyCode = 0;
::WindowRef eventWindow = NULL;
const ::Boolean removeEventFromQueue = true;
/* initialize the event for safety */
bzf_event.keyDown.chr = 0;
bzf_event.type = (BzfEvent::Type)-1;
status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);
if(status != ::noErr) {
return false;
}
eventTime = ::GetEventTime(eventRef);
eventClass = ::GetEventClass(eventRef);
eventKind = ::GetEventKind(eventRef);
// make note of any modifiers being pressed
bzf_event.keyDown.shift = 0;
status = GetEventParameter(eventRef,
::kEventParamKeyModifiers,
::typeUInt32,
NULL,
sizeof(::UInt32),
NULL,
&eventModifiers);
if (eventModifiers & cmdKey) {
// command and option both serve as bzflag alt even
bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
}
if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;
if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;
switch(eventClass) {
case ::kEventClassMouse:
status = GetEventParameter(eventRef,
::kEventParamWindowMouseLocation,
::typeHIPoint,
NULL,
sizeof(::HIPoint),
NULL,
&eventLocation);
status = GetEventParameter(eventRef,
::kEventParamMouseButton,
::typeMouseButton,
NULL,
sizeof(::EventMouseButton),
NULL,
&eventButtons);
status = GetEventParameter(eventRef,
::kEventParamMouseDelta,
::typeHIPoint,
NULL,
sizeof(::HIPoint),
NULL,
&eventDelta);
// handle the main event type
switch(eventKind) {
case ::kEventMouseDown:
case ::kEventMouseUp:
if(eventKind == ::kEventMouseDown) {
bzf_event.type = BzfEvent::KeyDown;
} else {
bzf_event.type = BzfEvent::KeyUp;
}
if(eventButtons > 9) {
// bzflag only handles 9 buttons for now
eventButtons = 9;
}
switch(eventButtons) {
case ::kEventMouseButtonSecondary:
bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
break;
case ::kEventMouseButtonTertiary:
bzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;
break;
default:
/* consistent wth the rest of the mac experience, a command click is
* the same as a right click.
*/
if (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {
bzf_event.keyDown.shift = 0;
bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
} else {
bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;
}
break;
}
break;
case ::kEventMouseMoved:
bzf_event.type = BzfEvent::MouseMove;
bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);
bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);
break;
case ::kEventMouseWheelMoved:
break;
}
break;
case ::kEventClassKeyboard:
status = GetEventParameter(eventRef,
::kEventParamKeyMacCharCodes,
::typeChar,
NULL,
sizeof(char),
NULL,
&eventChar);
status = GetEventParameter(eventRef,
::kEventParamKeyCode,
::typeUInt32,
NULL,
sizeof(eventKeyCode),
NULL,
&eventKeyCode);
switch(eventKind) {
case ::kEventRawKeyDown:
case ::kEventRawKeyRepeat:
bzf_event.type = BzfEvent::KeyDown;
getKey(bzf_event.keyDown, eventChar, eventKeyCode);
break;
case ::kEventRawKeyUp:
bzf_event.type = BzfEvent::KeyUp;
getKey(bzf_event.keyUp, eventChar, eventKeyCode);
break;
}
break;
case ::kEventClassApplication:
switch(eventKind) {
case ::kEventAppQuit:
bzf_event.type = BzfEvent::Quit;
break;
}
break;
case ::kEventClassWindow:
status = GetEventParameter(eventRef,
::kEventParamDirectObject,
::typeWindowRef,
NULL,
sizeof(::WindowRef),
NULL,
&eventWindow);
switch(eventKind) {
case ::kEventWindowUpdate:
case ::kEventWindowDrawContent:
bzf_event.type = BzfEvent::Redraw;
BeginUpdate(eventWindow);
EndUpdate(eventWindow);
break;
}
break;
case ::kEventClassCommand:
switch(eventKind) {
}
break;
}
ReleaseEvent(eventRef);
return true;
}
void MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {
enum {
kF1KeyCode = 0x7A, // Undo
kF2KeyCode = 0x78, // Cut
kF3KeyCode = 0x63, // Copy
kF4KeyCode = 0x76, // Paste
kF5KeyCode = 0x60,
kF6KeyCode = 0x61,
kF7KeyCode = 0x62,
kF8KeyCode = 0x64,
kF9KeyCode = 0x65,
kF10KeyCode = 0x6D,
kF11KeyCode = 0x67,
kF12KeyCode = 0x6F,
kF13KeyCode = 0x69, // Print Screen
kF14KeyCode = 0x6B, // Scroll Lock
kF15KeyCode = 0x71 // Pause
};
bzf_key.chr = 0;
bzf_key.button = BzfKeyEvent::NoButton;
switch (char_code) {
case kUpArrowCharCode : bzf_key.button = BzfKeyEvent::Up; break;
case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down; break;
case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left; break;
case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right; break;
case kHomeCharCode : bzf_key.button = BzfKeyEvent::Home; break;
case kEndCharCode : bzf_key.button = BzfKeyEvent::End; break;
case kPageUpCharCode : bzf_key.button = BzfKeyEvent::PageUp; break;
case kPageDownCharCode : bzf_key.button = BzfKeyEvent::PageDown; break;
case kHelpCharCode : bzf_key.button = BzfKeyEvent::Insert; break;
case kDeleteCharCode : bzf_key.button = BzfKeyEvent::Delete; break;
case kFunctionKeyCharCode:
switch(keycode) {
// These are the f-key codes on my apple extended keyboard
case kF15KeyCode: bzf_key.button = BzfKeyEvent::Pause; break;
case kF12KeyCode: bzf_key.button = BzfKeyEvent::F12; break;
case kF11KeyCode: bzf_key.button = BzfKeyEvent::F11; break;
case kF10KeyCode: bzf_key.button = BzfKeyEvent::F10; break;
case kF9KeyCode: bzf_key.button = BzfKeyEvent::F9; break;
case kF8KeyCode: bzf_key.button = BzfKeyEvent::F8; break;
case kF7KeyCode: bzf_key.button = BzfKeyEvent::F7; break;
case kF6KeyCode: bzf_key.button = BzfKeyEvent::F6; break;
case kF5KeyCode: bzf_key.button = BzfKeyEvent::F5; break;
case kF4KeyCode: bzf_key.button = BzfKeyEvent::F4; break;
case kF3KeyCode: bzf_key.button = BzfKeyEvent::F3; break;
case kF2KeyCode: bzf_key.button = BzfKeyEvent::F2; break;
case kF1KeyCode: bzf_key.button = BzfKeyEvent::F1; break;
default: fprintf(stderr, "Uknown function key code: 0x%lX\n", (long unsigned int) keycode); break;
}
break;
// standard key; a-z, 0-9 etc
default: bzf_key.chr = char_code; break;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>spelling<commit_after>/* bzflag
* Copyright (c) 1993 - 2009 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "MacDisplay.h"
#include "BzfEvent.h"
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
bool MacDisplay::pending;
CGrafPtr MacDisplay::window;
CGLContextObj MacDisplay::context;
MacDisplay::MacDisplay() {
pending = true;
setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),
CGDisplayPixelsHigh(kCGDirectMainDisplay));
}
MacDisplay::MacDisplay(const char *, const char *) {
#pragma unused (name, videoFormat)
is_valid = true;
pending = false;
cursor_region = CGPathCreateMutable();
ResInfo** resInfo = NULL;
resInfo = new ResInfo*[1];
resInfo[0] = new ResInfo("default",
CGDisplayPixelsWide(kCGDirectMainDisplay),
CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);
//numModes = 1;
//currentMode = 0;
// register modes
initResolutions(resInfo, 1, 0);
}
bool MacDisplay::isEventPending() const
{
::OSStatus status = ::noErr;
::EventRef eventRef = 0;
status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);
return (status == ::noErr) ? true : false;
}
bool MacDisplay::peekEvent (BzfEvent &) const
{
return false;
}
bool MacDisplay::getEvent (BzfEvent &bzf_event) const {
::EventRef eventRef = 0;
::OSStatus status = ::noErr;
::UInt32 eventClass = 0;
::UInt32 eventKind = 0;
::EventTime eventTime = 0;
::HIPoint eventLocation = {0, 0};
::HIPoint eventDelta = {0, 0};
::UInt32 eventModifiers = 0;
::EventMouseButton eventButtons = 0;
char eventChar = 0;
::UInt32 eventKeyCode = 0;
::WindowRef eventWindow = NULL;
const ::Boolean removeEventFromQueue = true;
/* initialize the event for safety */
bzf_event.keyDown.chr = 0;
bzf_event.type = (BzfEvent::Type)-1;
status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);
if(status != ::noErr) {
return false;
}
eventTime = ::GetEventTime(eventRef);
eventClass = ::GetEventClass(eventRef);
eventKind = ::GetEventKind(eventRef);
// make note of any modifiers being pressed
bzf_event.keyDown.shift = 0;
status = GetEventParameter(eventRef,
::kEventParamKeyModifiers,
::typeUInt32,
NULL,
sizeof(::UInt32),
NULL,
&eventModifiers);
if (eventModifiers & cmdKey) {
// command and option both serve as bzflag alt even
bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
}
if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;
if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;
switch(eventClass) {
case ::kEventClassMouse:
status = GetEventParameter(eventRef,
::kEventParamWindowMouseLocation,
::typeHIPoint,
NULL,
sizeof(::HIPoint),
NULL,
&eventLocation);
status = GetEventParameter(eventRef,
::kEventParamMouseButton,
::typeMouseButton,
NULL,
sizeof(::EventMouseButton),
NULL,
&eventButtons);
status = GetEventParameter(eventRef,
::kEventParamMouseDelta,
::typeHIPoint,
NULL,
sizeof(::HIPoint),
NULL,
&eventDelta);
// handle the main event type
switch(eventKind) {
case ::kEventMouseDown:
case ::kEventMouseUp:
if(eventKind == ::kEventMouseDown) {
bzf_event.type = BzfEvent::KeyDown;
} else {
bzf_event.type = BzfEvent::KeyUp;
}
if(eventButtons > 9) {
// bzflag only handles 9 buttons for now
eventButtons = 9;
}
switch(eventButtons) {
case ::kEventMouseButtonSecondary:
bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
break;
case ::kEventMouseButtonTertiary:
bzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;
break;
default:
/* consistent wth the rest of the mac experience, a command click is
* the same as a right click.
*/
if (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {
bzf_event.keyDown.shift = 0;
bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
} else {
bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;
}
break;
}
break;
case ::kEventMouseMoved:
bzf_event.type = BzfEvent::MouseMove;
bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);
bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);
break;
case ::kEventMouseWheelMoved:
break;
}
break;
case ::kEventClassKeyboard:
status = GetEventParameter(eventRef,
::kEventParamKeyMacCharCodes,
::typeChar,
NULL,
sizeof(char),
NULL,
&eventChar);
status = GetEventParameter(eventRef,
::kEventParamKeyCode,
::typeUInt32,
NULL,
sizeof(eventKeyCode),
NULL,
&eventKeyCode);
switch(eventKind) {
case ::kEventRawKeyDown:
case ::kEventRawKeyRepeat:
bzf_event.type = BzfEvent::KeyDown;
getKey(bzf_event.keyDown, eventChar, eventKeyCode);
break;
case ::kEventRawKeyUp:
bzf_event.type = BzfEvent::KeyUp;
getKey(bzf_event.keyUp, eventChar, eventKeyCode);
break;
}
break;
case ::kEventClassApplication:
switch(eventKind) {
case ::kEventAppQuit:
bzf_event.type = BzfEvent::Quit;
break;
}
break;
case ::kEventClassWindow:
status = GetEventParameter(eventRef,
::kEventParamDirectObject,
::typeWindowRef,
NULL,
sizeof(::WindowRef),
NULL,
&eventWindow);
switch(eventKind) {
case ::kEventWindowUpdate:
case ::kEventWindowDrawContent:
bzf_event.type = BzfEvent::Redraw;
BeginUpdate(eventWindow);
EndUpdate(eventWindow);
break;
}
break;
case ::kEventClassCommand:
switch(eventKind) {
}
break;
}
ReleaseEvent(eventRef);
return true;
}
void MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {
enum {
kF1KeyCode = 0x7A, // Undo
kF2KeyCode = 0x78, // Cut
kF3KeyCode = 0x63, // Copy
kF4KeyCode = 0x76, // Paste
kF5KeyCode = 0x60,
kF6KeyCode = 0x61,
kF7KeyCode = 0x62,
kF8KeyCode = 0x64,
kF9KeyCode = 0x65,
kF10KeyCode = 0x6D,
kF11KeyCode = 0x67,
kF12KeyCode = 0x6F,
kF13KeyCode = 0x69, // Print Screen
kF14KeyCode = 0x6B, // Scroll Lock
kF15KeyCode = 0x71 // Pause
};
bzf_key.chr = 0;
bzf_key.button = BzfKeyEvent::NoButton;
switch (char_code) {
case kUpArrowCharCode : bzf_key.button = BzfKeyEvent::Up; break;
case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down; break;
case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left; break;
case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right; break;
case kHomeCharCode : bzf_key.button = BzfKeyEvent::Home; break;
case kEndCharCode : bzf_key.button = BzfKeyEvent::End; break;
case kPageUpCharCode : bzf_key.button = BzfKeyEvent::PageUp; break;
case kPageDownCharCode : bzf_key.button = BzfKeyEvent::PageDown; break;
case kHelpCharCode : bzf_key.button = BzfKeyEvent::Insert; break;
case kDeleteCharCode : bzf_key.button = BzfKeyEvent::Delete; break;
case kFunctionKeyCharCode:
switch(keycode) {
// These are the f-key codes on my apple extended keyboard
case kF15KeyCode: bzf_key.button = BzfKeyEvent::Pause; break;
case kF12KeyCode: bzf_key.button = BzfKeyEvent::F12; break;
case kF11KeyCode: bzf_key.button = BzfKeyEvent::F11; break;
case kF10KeyCode: bzf_key.button = BzfKeyEvent::F10; break;
case kF9KeyCode: bzf_key.button = BzfKeyEvent::F9; break;
case kF8KeyCode: bzf_key.button = BzfKeyEvent::F8; break;
case kF7KeyCode: bzf_key.button = BzfKeyEvent::F7; break;
case kF6KeyCode: bzf_key.button = BzfKeyEvent::F6; break;
case kF5KeyCode: bzf_key.button = BzfKeyEvent::F5; break;
case kF4KeyCode: bzf_key.button = BzfKeyEvent::F4; break;
case kF3KeyCode: bzf_key.button = BzfKeyEvent::F3; break;
case kF2KeyCode: bzf_key.button = BzfKeyEvent::F2; break;
case kF1KeyCode: bzf_key.button = BzfKeyEvent::F1; break;
default: fprintf(stderr, "Unknown function key code: 0x%lX\n", (long unsigned int) keycode); break;
}
break;
// standard key; a-z, 0-9 etc
default: bzf_key.chr = char_code; break;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*
* Request.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Request.hpp>
#include <boost/tokenizer.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Log.hpp>
#include <core/Thread.hpp>
namespace rstudio {
namespace core {
namespace http {
Request::Request()
: remoteUid_(-1),
parsedCookies_(false),
parsedFormFields_(false),
parsedQueryParams_(false)
{
}
Request::~Request()
{
}
std::string Request::absoluteUri() const
{
std::string scheme = "http";
std::string forwardedScheme = headerValue("X-Forwarded-Proto");
if (!forwardedScheme.empty())
scheme = forwardedScheme;
return scheme + "://" + host() + uri();
}
bool Request::acceptsContentType(const std::string& contentType) const
{
return headerValue("Accept").find(contentType) != std::string::npos;
}
bool Request::acceptsEncoding(const std::string& encoding) const
{
// read , separated fields
using namespace boost ;
char_separator<char> comma(",");
tokenizer<char_separator<char> > tokens(acceptEncoding(), comma);
return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();
}
boost::posix_time::ptime Request::ifModifiedSince() const
{
using namespace boost::posix_time;
std::string modifiedSinceDate = headerValue("If-Modified-Since");
if (!modifiedSinceDate.empty())
{
return util::parseHttpDate(modifiedSinceDate);
}
else
{
return ptime(not_a_date_time);
}
}
std::string Request::path() const
{
std::string::size_type pos = uri().find('?');
if (pos != std::string::npos)
return uri().substr(0, pos);
else
return uri();
}
std::string Request::queryString() const
{
// find ? in uri()
std::string::size_type pos = uri().find('?');
if (pos != std::string::npos)
{
std::string::size_type qsPos = pos + 1;
if (uri().length() > qsPos)
return uri().substr(qsPos);
else
return std::string();
}
else
{
return std::string();
}
}
const Fields& Request::queryParams() const
{
if (!parsedQueryParams_)
{
util::parseQueryString(queryString(), &queryParams_);
parsedQueryParams_ = true;
}
return queryParams_;
}
std::string Request::cookieValue(const std::string& name) const
{
// parse cookies on demand
if ( !parsedCookies_ )
{
for (Headers::const_iterator it =
headers().begin(); it != headers().end(); ++it )
{
scanHeaderForCookie(it->name, it->value) ;
}
parsedCookies_ = true ;
}
// lookup the cookie
return util::fieldValue(cookies_, name);
}
std::string Request::formFieldValue(const std::string& name) const
{
ensureFormFieldsParsed();
// lookup the form field
return util::fieldValue(formFields_, name);
}
const Fields& Request::formFields() const
{
ensureFormFieldsParsed();
return formFields_ ;
}
const File& Request::uploadedFile(const std::string& name) const
{
ensureFormFieldsParsed();
// lookup the file
for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)
{
if (it->first == name)
return it->second;
}
// not found
return emptyFile_;
}
std::string Request::queryParamValue(const std::string& name) const
{
// lookup the query param
return util::fieldValue(queryParams(), name);
}
void Request::setBody(const std::string& body)
{
body_ = body;
setContentLength(body_.length());
}
void Request::debugPrintUri(const std::string& caption) const
{
static boost::mutex printMutex;
LOCK_MUTEX(printMutex)
{
std::cerr << caption << ": " << uri() << std::endl;
}
END_LOCK_MUTEX
}
void Request::resetMembers()
{
method_.clear() ;
uri_.clear() ;
parsedCookies_ = false ;
cookies_.clear() ;
parsedFormFields_ = false ;
formFields_.clear() ;
parsedQueryParams_ = false;
queryParams_.clear();
}
void Request::appendFirstLineBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
using boost::asio::buffer ;
// request line
buffers.push_back(buffer(method_)) ;
appendSpaceBuffer(buffers) ;
buffers.push_back(buffer(uri_)) ;
appendSpaceBuffer(buffers) ;
appendHttpVersionBuffers(buffers) ;
}
void Request::ensureFormFieldsParsed() const
{
// parase form fields on demand
if ( !parsedFormFields_ )
{
std::string contentType = headerValue("Content-Type");
if (contentType == "application/x-www-form-urlencoded")
{
util::parseFields(body(),
"&",
"=",
&formFields_,
util::FieldDecodeForm);
}
else if (contentType.find("multipart/form-data") == 0)
{
util::parseMultipartForm(contentType, body(), &formFields_, &files_);
}
else
{
// no form fields available
}
parsedFormFields_ = true ;
}
}
void Request::scanHeaderForCookie(const std::string& name,
const std::string& value) const
{
if (boost::iequals(name, "cookie"))
util::parseFields(value, ";, ", "= ", &cookies_, util::FieldDecodeNone) ;
}
std::ostream& operator << (std::ostream& stream, const Request& r)
{
// output request line
stream << r.method() << " "
<< r.uri()
<< " HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
<< std::endl ;
// output headers and body
const Message& m = r ;
stream << m ;
return stream ;
}
} // namespacce http
} // namespace core
} // namespace rstudio
<commit_msg>fix potential memory error<commit_after>/*
* Request.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/http/Request.hpp>
#include <boost/tokenizer.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <core/Log.hpp>
#include <core/Thread.hpp>
namespace rstudio {
namespace core {
namespace http {
Request::Request()
: remoteUid_(-1),
parsedCookies_(false),
parsedFormFields_(false),
parsedQueryParams_(false)
{
}
Request::~Request()
{
}
std::string Request::absoluteUri() const
{
std::string scheme = "http";
std::string forwardedScheme = headerValue("X-Forwarded-Proto");
if (!forwardedScheme.empty())
scheme = forwardedScheme;
return scheme + "://" + host() + uri();
}
bool Request::acceptsContentType(const std::string& contentType) const
{
return headerValue("Accept").find(contentType) != std::string::npos;
}
bool Request::acceptsEncoding(const std::string& encoding) const
{
// read , separated fields
using namespace boost ;
char_separator<char> comma(",");
std::string accepted = acceptEncoding();
tokenizer<char_separator<char>> tokens(accepted, comma);
return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();
}
boost::posix_time::ptime Request::ifModifiedSince() const
{
using namespace boost::posix_time;
std::string modifiedSinceDate = headerValue("If-Modified-Since");
if (!modifiedSinceDate.empty())
{
return util::parseHttpDate(modifiedSinceDate);
}
else
{
return ptime(not_a_date_time);
}
}
std::string Request::path() const
{
std::string::size_type pos = uri().find('?');
if (pos != std::string::npos)
return uri().substr(0, pos);
else
return uri();
}
std::string Request::queryString() const
{
// find ? in uri()
std::string::size_type pos = uri().find('?');
if (pos != std::string::npos)
{
std::string::size_type qsPos = pos + 1;
if (uri().length() > qsPos)
return uri().substr(qsPos);
else
return std::string();
}
else
{
return std::string();
}
}
const Fields& Request::queryParams() const
{
if (!parsedQueryParams_)
{
util::parseQueryString(queryString(), &queryParams_);
parsedQueryParams_ = true;
}
return queryParams_;
}
std::string Request::cookieValue(const std::string& name) const
{
// parse cookies on demand
if ( !parsedCookies_ )
{
for (Headers::const_iterator it =
headers().begin(); it != headers().end(); ++it )
{
scanHeaderForCookie(it->name, it->value) ;
}
parsedCookies_ = true ;
}
// lookup the cookie
return util::fieldValue(cookies_, name);
}
std::string Request::formFieldValue(const std::string& name) const
{
ensureFormFieldsParsed();
// lookup the form field
return util::fieldValue(formFields_, name);
}
const Fields& Request::formFields() const
{
ensureFormFieldsParsed();
return formFields_ ;
}
const File& Request::uploadedFile(const std::string& name) const
{
ensureFormFieldsParsed();
// lookup the file
for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)
{
if (it->first == name)
return it->second;
}
// not found
return emptyFile_;
}
std::string Request::queryParamValue(const std::string& name) const
{
// lookup the query param
return util::fieldValue(queryParams(), name);
}
void Request::setBody(const std::string& body)
{
body_ = body;
setContentLength(body_.length());
}
void Request::debugPrintUri(const std::string& caption) const
{
static boost::mutex printMutex;
LOCK_MUTEX(printMutex)
{
std::cerr << caption << ": " << uri() << std::endl;
}
END_LOCK_MUTEX
}
void Request::resetMembers()
{
method_.clear() ;
uri_.clear() ;
parsedCookies_ = false ;
cookies_.clear() ;
parsedFormFields_ = false ;
formFields_.clear() ;
parsedQueryParams_ = false;
queryParams_.clear();
}
void Request::appendFirstLineBuffers(
std::vector<boost::asio::const_buffer>& buffers) const
{
using boost::asio::buffer ;
// request line
buffers.push_back(buffer(method_)) ;
appendSpaceBuffer(buffers) ;
buffers.push_back(buffer(uri_)) ;
appendSpaceBuffer(buffers) ;
appendHttpVersionBuffers(buffers) ;
}
void Request::ensureFormFieldsParsed() const
{
// parase form fields on demand
if ( !parsedFormFields_ )
{
std::string contentType = headerValue("Content-Type");
if (contentType == "application/x-www-form-urlencoded")
{
util::parseFields(body(),
"&",
"=",
&formFields_,
util::FieldDecodeForm);
}
else if (contentType.find("multipart/form-data") == 0)
{
util::parseMultipartForm(contentType, body(), &formFields_, &files_);
}
else
{
// no form fields available
}
parsedFormFields_ = true ;
}
}
void Request::scanHeaderForCookie(const std::string& name,
const std::string& value) const
{
if (boost::iequals(name, "cookie"))
util::parseFields(value, ";, ", "= ", &cookies_, util::FieldDecodeNone) ;
}
std::ostream& operator << (std::ostream& stream, const Request& r)
{
// output request line
stream << r.method() << " "
<< r.uri()
<< " HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
<< std::endl ;
// output headers and body
const Message& m = r ;
stream << m ;
return stream ;
}
} // namespacce http
} // namespace core
} // namespace rstudio
<|endoftext|>
|
<commit_before>
#include "lcio.h"
#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std ;
using namespace lcio ;
static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ; // mc particles per event
static const int NHITS = 50 ; // calorimeter hits per event
static string FILEN = "simjob.slcio" ;
/** Simple test program to demonstrate writing of data with lcio.
*/
int main(int argc, char** argv ){
try{
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
if( argc > 1 ) { FILEN = argv[1] ; }
try{ lcWrt->open( FILEN ) ;
}
catch( IOException& e ){
cout << e.what() << endl ;
return 0 ;
}
// int status ;
// if( (status = lcWrt->open( FILEN )) != LCIO::SUCCESS ) {
// cout << " couldn't open file : " << FILEN << " status: " << status << endl ;
// return 0 ;
// }
// loop over runs
for(int rn=0;rn<NRUN;rn++){
LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
runHdr->setRunNumber( rn ) ;
string detName("D09TileHcal") ;
runHdr->setDetectorName( detName ) ;
stringstream description ;
description << " run: " << rn <<" just for testing lcio - no physics !" ;
runHdr->setDescription( description.str() ) ;
string ecalName("ECAL007") ;
runHdr->addActiveSubdetector( ecalName ) ;
string tpcName("TPC4711") ;
runHdr->addActiveSubdetector( tpcName ) ;
lcWrt->writeRunHeader( runHdr ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( rn ) ;
evt->setEventNumber( i ) ;
evt->setDetectorName( detName ) ;
// create and add some mc particles
LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;
MCParticleImpl* mom = new MCParticleImpl ;
mom->setPDG( 1 ) ;
float p0[3] = { 0. , 0. , 1000. } ;
mom->setMomentum( p0 ) ;
for(int j=0;j<NMCPART;j++){
MCParticleImpl* mcp = new MCParticleImpl ;
mcp->setPDG( 1000 * (j+1) ) ;
float p[3] = { j*1. , 4./1024. , 8./1024. } ;
mcp->setMomentum( p ) ;
// create and add some daughters
for(int k=0;k<3;k++){
MCParticleImpl* d1 = new MCParticleImpl ;
d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;
float pd1[3] = { k*1. , 4.1 , 8.1 } ;
d1->setMomentum( pd1 ) ;
for(int l=0;l<2;l++){
MCParticleImpl* d2 = new MCParticleImpl ;
d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;
float pd2[3] = { l*1. , 0.41 , 4.1 } ;
d2->setMomentum( pd2 ) ;
d2->setParent( d1 );
d1->addDaughter( d2 ) ;
mcVec->push_back( d2 ) ;
}
d1->setParent( mcp );
mcp->addDaughter( d1 ) ;
mcVec->push_back( d1 ) ;
}
mcp->setParent( mom );
mom->addDaughter( mcp ) ;
mcVec->push_back( mcp ) ;
}
mcVec->push_back( mom ) ;
// now add some calorimeter hits
LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;
// set flag for long format (including position )
// and PDG
LCFlagImpl chFlag(0) ;
chFlag.setBit( LCIO::CHBIT_LONG ) ;
chFlag.setBit( LCIO::CHBIT_PDG ) ;
calVec->setFlag( chFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;
hit->setEnergy( 3.1415 * rand()/RAND_MAX ) ;
float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
calVec->push_back( hit ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
// in order to access a MCParticle, we need a dynamic cast as the
// LCCollection returns an LCIOObject - this is like vectors in Java
hit->addMCParticleContribution( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) ,
0.314159, 0.1155 ) ; // no pdg
}
// we can modify hits that already exist in a collection, e.g. in a simulation step function ...
// we need a non const pointer to the hit and use the std::vector::operator[]() instead of the
// LCCollection::getElementAt(i)
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;
existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>
(mcVec->getElementAt(0)),
0.1, 0. ) ;
}
// and finally some tracker hits
// with some user extensions (4 floats and 2 ints) per track:
// we just create parallel collections of float and int vectors
LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;
LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;
for(int j=0;j<NHITS;j++){
SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
LCFloatVec* extF = new LCFloatVec ;
LCIntVec* extI = new LCIntVec ;
hit->setdEdx( 30e-9 ) ;
double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;
// fill the extension vectors (4 floats, 2 ints)
extF->push_back( 3.14159 ) ;
for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;
extI->push_back( 123456789 ) ;
extI->push_back( mcIndx ) ;
// add the hit and the extensions to their corresponding collections
trkVec->push_back( hit ) ;
extFVec->push_back( extF ) ;
extIVec->push_back( extI ) ;
}
// add all collection to the event
evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ;
evt->addCollection( (LCCollection*) calVec , ecalName ) ;
evt->addCollection( (LCCollection*) trkVec , tpcName ) ;
evt->addCollection( (LCCollection*) extFVec , tpcName+"UserFloatExtensionTPC" ) ;
evt->addCollection( (LCCollection*) extIVec , tpcName+"UserIntExtensionTPC" ) ;
// test: add a collection for one event only:
if( rn == NRUN-1 && i == 0 ) { // first event o last run
LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCFloatVec* addExt = new LCFloatVec ;
addExt->push_back( 1. );
addExt->push_back( 2. );
addExt->push_back( 3. );
addExt->push_back( 4. );
addExtVec->push_back( addExt ) ;
evt->addCollection( (LCCollection*) addExtVec , "AdditionalExtension" ) ;
}
// write the event to the file
lcWrt->writeEvent( evt ) ;
// dump the event to the screen
LCTOOLS::dumpEvent( evt ) ;
// LCTOOLS::printMCParticles( mcVec ) ;
// we created the event so we need to take care of deleting it ...
delete evt ;
if( ! (i%100) ) cout << ". " << flush ;
} // evt loop
} // run loop
cout << endl
<< " created " << NRUN << " runs with " << NRUN*NEVENT << " events"
<< endl << endl ;
lcWrt->close() ;
} catch( Exception& ex){
cout << " an excpetion occured: " << endl ;
cout << " " << ex.what() << endl ;
return 1 ;
}
return 0 ;
}
<commit_msg>changed name of extension collections.<commit_after>
#include "lcio.h"
#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"
#include <cstdlib>
#include <iostream>
#include <sstream>
using namespace std ;
using namespace lcio ;
static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ; // mc particles per event
static const int NHITS = 50 ; // calorimeter hits per event
static string FILEN = "simjob.slcio" ;
/** Simple test program to demonstrate writing of data with lcio.
*/
int main(int argc, char** argv ){
try{
// create sio writer
LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;
if( argc > 1 ) { FILEN = argv[1] ; }
try{ lcWrt->open( FILEN ) ;
}
catch( IOException& e ){
cout << e.what() << endl ;
return 0 ;
}
// int status ;
// if( (status = lcWrt->open( FILEN )) != LCIO::SUCCESS ) {
// cout << " couldn't open file : " << FILEN << " status: " << status << endl ;
// return 0 ;
// }
// loop over runs
for(int rn=0;rn<NRUN;rn++){
LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
runHdr->setRunNumber( rn ) ;
string detName("D09TileHcal") ;
runHdr->setDetectorName( detName ) ;
stringstream description ;
description << " run: " << rn <<" just for testing lcio - no physics !" ;
runHdr->setDescription( description.str() ) ;
string ecalName("ECAL007") ;
runHdr->addActiveSubdetector( ecalName ) ;
string tpcName("TPC4711") ;
runHdr->addActiveSubdetector( tpcName ) ;
lcWrt->writeRunHeader( runHdr ) ;
// EventLoop - create some events and write them to the file
for(int i=0;i<NEVENT;i++){
// we need to use the implementation classes here
LCEventImpl* evt = new LCEventImpl() ;
evt->setRunNumber( rn ) ;
evt->setEventNumber( i ) ;
evt->setDetectorName( detName ) ;
// create and add some mc particles
LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;
MCParticleImpl* mom = new MCParticleImpl ;
mom->setPDG( 1 ) ;
float p0[3] = { 0. , 0. , 1000. } ;
mom->setMomentum( p0 ) ;
for(int j=0;j<NMCPART;j++){
MCParticleImpl* mcp = new MCParticleImpl ;
mcp->setPDG( 1000 * (j+1) ) ;
float p[3] = { j*1. , 4./1024. , 8./1024. } ;
mcp->setMomentum( p ) ;
// create and add some daughters
for(int k=0;k<3;k++){
MCParticleImpl* d1 = new MCParticleImpl ;
d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;
float pd1[3] = { k*1. , 4.1 , 8.1 } ;
d1->setMomentum( pd1 ) ;
for(int l=0;l<2;l++){
MCParticleImpl* d2 = new MCParticleImpl ;
d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;
float pd2[3] = { l*1. , 0.41 , 4.1 } ;
d2->setMomentum( pd2 ) ;
d2->setParent( d1 );
d1->addDaughter( d2 ) ;
mcVec->push_back( d2 ) ;
}
d1->setParent( mcp );
mcp->addDaughter( d1 ) ;
mcVec->push_back( d1 ) ;
}
mcp->setParent( mom );
mom->addDaughter( mcp ) ;
mcVec->push_back( mcp ) ;
}
mcVec->push_back( mom ) ;
// now add some calorimeter hits
LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;
// set flag for long format (including position )
// and PDG
LCFlagImpl chFlag(0) ;
chFlag.setBit( LCIO::CHBIT_LONG ) ;
chFlag.setBit( LCIO::CHBIT_PDG ) ;
calVec->setFlag( chFlag.getFlag() ) ;
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;
hit->setEnergy( 3.1415 * rand()/RAND_MAX ) ;
float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
calVec->push_back( hit ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
// in order to access a MCParticle, we need a dynamic cast as the
// LCCollection returns an LCIOObject - this is like vectors in Java
hit->addMCParticleContribution( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) ,
0.314159, 0.1155 ) ; // no pdg
}
// we can modify hits that already exist in a collection, e.g. in a simulation step function ...
// we need a non const pointer to the hit and use the std::vector::operator[]() instead of the
// LCCollection::getElementAt(i)
for(int j=0;j<NHITS;j++){
SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;
existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>
(mcVec->getElementAt(0)),
0.1, 0. ) ;
}
// and finally some tracker hits
// with some user extensions (4 floats and 2 ints) per track:
// we just create parallel collections of float and int vectors
LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;
LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;
for(int j=0;j<NHITS;j++){
SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
LCFloatVec* extF = new LCFloatVec ;
LCIntVec* extI = new LCIntVec ;
hit->setdEdx( 30e-9 ) ;
double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;
hit->setPosition( pos ) ;
// assign the hits randomly to MC particles
float rn = .99999*rand()/RAND_MAX ;
int mcIndx = static_cast<int>( NMCPART * rn ) ;
hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;
// fill the extension vectors (4 floats, 2 ints)
extF->push_back( 3.14159 ) ;
for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;
extI->push_back( 123456789 ) ;
extI->push_back( mcIndx ) ;
// add the hit and the extensions to their corresponding collections
trkVec->push_back( hit ) ;
extFVec->push_back( extF ) ;
extIVec->push_back( extI ) ;
}
// add all collection to the event
evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ;
evt->addCollection( (LCCollection*) calVec , ecalName ) ;
evt->addCollection( (LCCollection*) trkVec , tpcName ) ;
evt->addCollection( (LCCollection*) extFVec , tpcName+"UserFloatExtension" ) ;
evt->addCollection( (LCCollection*) extIVec , tpcName+"UserIntExtension" ) ;
// test: add a collection for one event only:
if( rn == NRUN-1 && i == 0 ) { // first event o last run
LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;
LCFloatVec* addExt = new LCFloatVec ;
addExt->push_back( 1. );
addExt->push_back( 2. );
addExt->push_back( 3. );
addExt->push_back( 4. );
addExtVec->push_back( addExt ) ;
evt->addCollection( (LCCollection*) addExtVec , "AdditionalExtension" ) ;
}
// write the event to the file
lcWrt->writeEvent( evt ) ;
// dump the event to the screen
LCTOOLS::dumpEvent( evt ) ;
// LCTOOLS::printMCParticles( mcVec ) ;
// we created the event so we need to take care of deleting it ...
delete evt ;
if( ! (i%100) ) cout << ". " << flush ;
} // evt loop
} // run loop
cout << endl
<< " created " << NRUN << " runs with " << NRUN*NEVENT << " events"
<< endl << endl ;
lcWrt->close() ;
} catch( Exception& ex){
cout << " an excpetion occured: " << endl ;
cout << " " << ex.what() << endl ;
return 1 ;
}
return 0 ;
}
<|endoftext|>
|
<commit_before>#include <cppunit/XmlOutputterHook.h>
#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>
CPPUNIT_NS_BEGIN
PlugInManager::PlugInManager()
{
}
PlugInManager::~PlugInManager()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
unload( *it );
}
void
PlugInManager::load( const std::string &libraryFileName,
const PlugInParameters ¶meters )
{
PlugInInfo info;
info.m_fileName = libraryFileName;
info.m_manager = new DynamicLibraryManager( libraryFileName );
TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
info.m_interface = (*plug)();
m_plugIns.push_back( info );
info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}
void
PlugInManager::unload( const std::string &libraryFileName )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
{
if ( it->m_fileName == libraryFileName )
{
unload( *it );
m_plugIns.erase( it );
break;
}
}
}
void
PlugInManager::addListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->addListener( eventManager );
}
void
PlugInManager::removeListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->removeListener( eventManager );
}
void
PlugInManager::unload( PlugInInfo &plugIn )
{
try
{
plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
delete plugIn.m_manager;
}
catch (...)
{
delete plugIn.m_manager;
plugIn.m_manager = NULL;
throw;
}
}
void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->addXmlOutputterHooks( outputter );
}
void
PlugInManager::removeXmlOutputterHooks()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->removeXmlOutputterHooks();
}
CPPUNIT_NS_END
#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<commit_msg>Dereferencing fix for SUN4<commit_after>#include <cppunit/XmlOutputterHook.h>
#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>
CPPUNIT_NS_BEGIN
PlugInManager::PlugInManager()
{
}
PlugInManager::~PlugInManager()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
unload( *it );
}
void
PlugInManager::load( const std::string &libraryFileName,
const PlugInParameters ¶meters )
{
PlugInInfo info;
info.m_fileName = libraryFileName;
info.m_manager = new DynamicLibraryManager( libraryFileName );
TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
info.m_interface = (*plug)();
m_plugIns.push_back( info );
info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}
void
PlugInManager::unload( const std::string &libraryFileName )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
{
if ( (*it).m_fileName == libraryFileName )
{
unload( *it );
m_plugIns.erase( it );
break;
}
}
}
void
PlugInManager::addListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->addListener( eventManager );
}
void
PlugInManager::removeListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->removeListener( eventManager );
}
void
PlugInManager::unload( PlugInInfo &plugIn )
{
try
{
plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
delete plugIn.m_manager;
}
catch (...)
{
delete plugIn.m_manager;
plugIn.m_manager = NULL;
throw;
}
}
void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->addXmlOutputterHooks( outputter );
}
void
PlugInManager::removeXmlOutputterHooks()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->removeXmlOutputterHooks();
}
CPPUNIT_NS_END
#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
//@file
// WeaveArray.cpp
//
//@author
// ab5tract
//
//@brief
// Implementation of the WeaveArray class.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// includes
//-----------------------------------------------------------------------------
#include "WeaveArray.h"
//----------------------------------------------------------------------------
// create, general info and destroy methodes
//----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Create
void CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)
{
pModule = new WeaveArray ();
}
//-----------------------------------------------------------------------------
// destroy
void DestroyModule (void* pModule)
{
// cast is important to call the good destructor
delete ((WeaveArray*)pModule);
}
//-----------------------------------------------------------------------------
// module description
void WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
{
//identification of the module
pModuleInfo->Name = "weave array";
pModuleInfo->Description = "Weave Arrays";
pModuleInfo->ModuleType = mtSimple;
pModuleInfo->BackColor = sdkGetUsineColor(clDataModuleColor);
pModuleInfo->NumberOfParams = 3;
pModuleInfo->Version = "1.0";
pModuleInfo->DontProcess = TRUE;
}
//-----------------------------------------------------------------------------
// query system and init methodes
//-----------------------------------------------------------------------------
// query system not used
//void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
//{
//}
//----------------------------------------------------------------------------
// parameters and process
//----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Parameters description
void WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo)
{
// all parameters declared in the module class
switch (ParamIndex)
{
// waInput1
case 0:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "array 1";
pParamInfo->IsInput = TRUE;
pParamInfo->IsOutput = FALSE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// waInput2
case 1:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "array 2";
pParamInfo->IsInput = TRUE;
pParamInfo->IsOutput = FALSE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// waOutput
case 2:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "output";
pParamInfo->IsInput = FALSE;
pParamInfo->IsOutput = TRUE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// default case
default:
break;
}
}
//-----------------------------------------------------------------------------
// set the parameters events address
void WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent)
{
//Initialyse all events adress declared in your module class
switch (ParamIndex)
{
// waInput1
case 0:
waInput1 = pEvent;
break;
// waInput2
case 1:
waInput2 = pEvent;
break;
// waOutput
case 2:
waOutput = pEvent;
break;
// default case
default:
break;
}
}
//-----------------------------------------------------------------------------
// Parameters callback
void WeaveArray::onCallBack (UsineMessage* Message)
{
try
{
if (Message->message == NOTIFY_MSG_USINE_CALLBACK)
{
int paramIndex = (int)Message->wParam;
if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)
{
/*
int tmp1,tmp2;
tmp1 = sdkGetEvtSize(waInput1);
tmp2 = sdkGetEvtSize(waInput2);
if (tmp1 != input1Length || tmp2 != input2Length)
{
input1Length = tmp1;
input2Length = tmp2;
outputLength = input1Length + input2Length;
for( int i=0; i < outputLength; i++)
{
sdkSetEvtArrayData(waOutput, i, 0);
}
}
*/
input1Length = sdkGetEvtSize(waInput1);
input2Length = sdkGetEvtSize(waInput2);
outputLength = input1Length + input2Length;
writeOutput();
}
}
}
catch (...)
{
//sdkTraceErrorChar("error");
}
}
void WeaveArray::writeOutput()
{
sdkSetEvtSize(waOutput, outputLength);
int i;
int r = 0;
if ( input1Length <= input2Length )
{
for ( i=0; i < input1Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
}
for ( i=input1Length; i < input2Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));
}
}
else
{
for ( i=0; i < input2Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
}
for ( i=input2Length; i < input1Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));
}
}
}
<commit_msg>remove unnecessary code<commit_after>//-----------------------------------------------------------------------------
//@file
// WeaveArray.cpp
//
//@author
// ab5tract
//
//@brief
// Implementation of the WeaveArray class.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// includes
//-----------------------------------------------------------------------------
#include "WeaveArray.h"
//----------------------------------------------------------------------------
// create, general info and destroy methodes
//----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Create
void CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)
{
pModule = new WeaveArray ();
}
//-----------------------------------------------------------------------------
// destroy
void DestroyModule (void* pModule)
{
// cast is important to call the good destructor
delete ((WeaveArray*)pModule);
}
//-----------------------------------------------------------------------------
// module description
void WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
{
//identification of the module
pModuleInfo->Name = "weave array";
pModuleInfo->Description = "Weave Arrays";
pModuleInfo->ModuleType = mtSimple;
pModuleInfo->BackColor = sdkGetUsineColor(clDataModuleColor);
pModuleInfo->NumberOfParams = 3;
pModuleInfo->Version = "1.0";
pModuleInfo->DontProcess = TRUE;
}
//-----------------------------------------------------------------------------
// query system and init methodes
//-----------------------------------------------------------------------------
// query system not used
//void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
//{
//}
//----------------------------------------------------------------------------
// parameters and process
//----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Parameters description
void WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo)
{
// all parameters declared in the module class
switch (ParamIndex)
{
// waInput1
case 0:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "array 1";
pParamInfo->IsInput = TRUE;
pParamInfo->IsOutput = FALSE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// waInput2
case 1:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "array 2";
pParamInfo->IsInput = TRUE;
pParamInfo->IsOutput = FALSE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// waOutput
case 2:
pParamInfo->ParamType = ptArray;
pParamInfo->Caption = "output";
pParamInfo->IsInput = FALSE;
pParamInfo->IsOutput = TRUE;
pParamInfo->MinValue = - FLT_MAX;
pParamInfo->MaxValue = FLT_MAX;
pParamInfo->CallBackType = ctImmediate;
break;
// default case
default:
break;
}
}
//-----------------------------------------------------------------------------
// set the parameters events address
void WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent)
{
//Initialyse all events adress declared in your module class
switch (ParamIndex)
{
// waInput1
case 0:
waInput1 = pEvent;
break;
// waInput2
case 1:
waInput2 = pEvent;
break;
// waOutput
case 2:
waOutput = pEvent;
break;
// default case
default:
break;
}
}
//-----------------------------------------------------------------------------
// Parameters callback
void WeaveArray::onCallBack (UsineMessage* Message)
{
try
{
if (Message->message == NOTIFY_MSG_USINE_CALLBACK)
{
int paramIndex = (int)Message->wParam;
if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)
{
input1Length = sdkGetEvtSize(waInput1);
input2Length = sdkGetEvtSize(waInput2);
outputLength = input1Length + input2Length;
writeOutput();
}
}
}
catch (...)
{
//sdkTraceErrorChar("error");
}
}
void WeaveArray::writeOutput()
{
sdkSetEvtSize(waOutput, outputLength);
int i;
int r = 0;
if ( input1Length <= input2Length )
{
for ( i=0; i < input1Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
}
for ( i=input1Length; i < input2Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));
}
}
else
{
for ( i=0; i < input2Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
}
for ( i=input2Length; i < input1Length; i++ )
{
sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));
}
}
}
<|endoftext|>
|
<commit_before>/*
* Mlock Allocator
* (C) 2012 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/locking_allocator.h>
#include <botan/internal/assert.h>
#include <algorithm>
#include <cstring>
#include <sys/mman.h>
#include <sys/resource.h>
namespace Botan {
namespace {
size_t mlock_limit()
{
struct rlimit limits;
::getrlimit(RLIMIT_MEMLOCK, &limits);
if(limits.rlim_cur < limits.rlim_max)
{
limits.rlim_cur = limits.rlim_max;
::setrlimit(RLIMIT_MEMLOCK, &limits);
::getrlimit(RLIMIT_MEMLOCK, &limits);
}
/*
* Linux defaults to only 64 KiB of mlockable memory per process
* (too small) but BSDs offer a small fraction of total RAM (more
* than we need). Bound the total mlock size to 256 KiB which is
* enough to run the entire test suite without spilling to non-mlock
* memory, but small enough that we should not cause problems if
* multiple processes are mlocking on the same machine.
*/
return std::min<size_t>(limits.rlim_cur, 256*1024);
}
bool ptr_in_pool(const void* pool_ptr, size_t poolsize,
const void* buf_ptr, size_t bufsize)
{
const size_t pool = reinterpret_cast<size_t>(pool_ptr);
const size_t buf = reinterpret_cast<size_t>(buf_ptr);
if(buf < pool || buf >= pool + poolsize)
return false;
BOTAN_ASSERT(buf + bufsize <= pool + poolsize,
"Invalid pointer/length halfway into mem pool");
return true;
}
}
void* mlock_allocator::allocate(size_t n, size_t alignment)
{
if(!m_pool || n >= m_poolsize)
return nullptr; // bigger than the whole pool!
std::lock_guard<std::mutex> lock(m_mutex);
auto best_fit = m_freelist.end();
for(auto i = m_freelist.begin(); i != m_freelist.end(); ++i)
{
// If we have a perfect fit, use it immediately
if(i->second == n && (i->first % alignment) == 0)
{
const size_t offset = i->first;
m_freelist.erase(i);
::memset(m_pool + offset, 0, n);
return m_pool + offset;
}
if((i->second > (i->first % alignment) + n) &&
((best_fit == m_freelist.end()) || (best_fit->second > i->second)))
{
best_fit = i;
}
}
if(best_fit != m_freelist.end())
{
const size_t offset = best_fit->first;
size_t alignment_padding = offset % alignment;
best_fit->first += n + alignment_padding;
best_fit->second -= n + alignment_padding;
// Need to realign, split the block
if(alignment_padding)
m_freelist.insert(best_fit, std::make_pair(offset, alignment_padding));
::memset(m_pool + offset + alignment_padding, 0, n);
return m_pool + offset + alignment_padding;
}
return nullptr;
}
bool mlock_allocator::deallocate(void* p, size_t n)
{
if(!m_pool || !ptr_in_pool(m_pool, m_poolsize, p, n))
return false;
std::lock_guard<std::mutex> lock(m_mutex);
const size_t start = static_cast<byte*>(p) - m_pool;
auto comp = [](std::pair<size_t, size_t> x, std::pair<size_t, size_t> y){ return x.first < y.first; };
auto i = std::lower_bound(m_freelist.begin(), m_freelist.end(),
std::make_pair(start, 0), comp);
// try to merge with later block
if(start + n == i->first)
{
i->first = start;
i->second += n;
n = 0;
}
// try to merge with previous block
if(i != m_freelist.begin())
{
auto prev = std::prev(i);
if(prev->first + prev->second == start)
{
if(n)
{
prev->second += n;
n = 0;
}
else
{
// merge adjoining
prev->second += i->second;
m_freelist.erase(i);
}
}
}
if(n != 0) // no merge possible?
m_freelist.insert(i, std::make_pair(start, n));
return true;
}
mlock_allocator::mlock_allocator() :
m_poolsize(mlock_limit()),
m_pool(nullptr)
{
#if !defined(MAP_NOCORE)
#define MAP_NOCORE 0
#endif
if(m_poolsize)
{
m_pool = static_cast<byte*>(
::mmap(
nullptr, m_poolsize,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE,
-1, 0));
if(m_pool == static_cast<byte*>(MAP_FAILED))
throw std::runtime_error("Failed to mmap pool");
std::memset(m_pool, 0x00, m_poolsize);
if(::mlock(m_pool, m_poolsize) != 0)
{
::munmap(m_pool, m_poolsize);
m_pool = nullptr;
throw std::runtime_error("Failed to lock pool");
}
m_freelist.push_back(std::make_pair(0, m_poolsize));
}
}
mlock_allocator::~mlock_allocator()
{
if(m_pool)
{
std::memset(m_pool, 0, m_poolsize);
::munlock(m_pool, m_poolsize);
::munmap(m_pool, m_poolsize);
m_pool = nullptr;
}
}
mlock_allocator& mlock_allocator::instance()
{
static mlock_allocator mlock;
return mlock;
}
}
<commit_msg>Fix alignment again and add assert checks so we don't mess up again.<commit_after>/*
* Mlock Allocator
* (C) 2012 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/locking_allocator.h>
#include <botan/internal/assert.h>
#include <algorithm>
#include <cstring>
#include <sys/mman.h>
#include <sys/resource.h>
namespace Botan {
namespace {
size_t mlock_limit()
{
struct rlimit limits;
::getrlimit(RLIMIT_MEMLOCK, &limits);
if(limits.rlim_cur < limits.rlim_max)
{
limits.rlim_cur = limits.rlim_max;
::setrlimit(RLIMIT_MEMLOCK, &limits);
::getrlimit(RLIMIT_MEMLOCK, &limits);
}
/*
* Linux defaults to only 64 KiB of mlockable memory per process
* (too small) but BSDs offer a small fraction of total RAM (more
* than we need). Bound the total mlock size to 256 KiB which is
* enough to run the entire test suite without spilling to non-mlock
* memory, but small enough that we should not cause problems if
* multiple processes are mlocking on the same machine.
*/
return std::min<size_t>(limits.rlim_cur, 256*1024);
}
bool ptr_in_pool(const void* pool_ptr, size_t poolsize,
const void* buf_ptr, size_t bufsize)
{
const size_t pool = reinterpret_cast<size_t>(pool_ptr);
const size_t buf = reinterpret_cast<size_t>(buf_ptr);
if(buf < pool || buf >= pool + poolsize)
return false;
BOTAN_ASSERT(buf + bufsize <= pool + poolsize,
"Invalid pointer/length halfway into mem pool");
return true;
}
size_t padding_for_alignment(size_t offset, size_t desired_alignment)
{
size_t mod = offset % desired_alignment;
if(mod == 0)
return 0; // already right on
return desired_alignment - mod;
}
}
void* mlock_allocator::allocate(size_t n, size_t alignment)
{
if(!m_pool || n >= m_poolsize)
return nullptr; // bigger than the whole pool!
std::lock_guard<std::mutex> lock(m_mutex);
auto best_fit = m_freelist.end();
for(auto i = m_freelist.begin(); i != m_freelist.end(); ++i)
{
// If we have a perfect fit, use it immediately
if(i->second == n && (i->first % alignment) == 0)
{
const size_t offset = i->first;
m_freelist.erase(i);
::memset(m_pool + offset, 0, n);
BOTAN_ASSERT((reinterpret_cast<size_t>(m_pool) + offset) % alignment == 0,
"Returning correctly aligned pointer");
return m_pool + offset;
}
if((i->second >= (n + padding_for_alignment(i->first, alignment)) &&
((best_fit == m_freelist.end()) || (best_fit->second > i->second))))
{
best_fit = i;
}
}
if(best_fit != m_freelist.end())
{
const size_t offset = best_fit->first;
const size_t alignment_padding = padding_for_alignment(offset, alignment);
best_fit->first += n + alignment_padding;
best_fit->second -= n + alignment_padding;
// Need to realign, split the block
if(alignment_padding)
{
if(best_fit->second == 0)
{
/*
We used the entire block except for small piece used for
alignment at the beginning, so just update this entry.
*/
best_fit->second = alignment_padding;
}
else
m_freelist.insert(best_fit, std::make_pair(offset, alignment_padding));
}
::memset(m_pool + offset + alignment_padding, 0, n);
BOTAN_ASSERT((reinterpret_cast<size_t>(m_pool) + offset + alignment_padding) % alignment == 0,
"Returning correctly aligned pointer");
return m_pool + offset + alignment_padding;
}
return nullptr;
}
bool mlock_allocator::deallocate(void* p, size_t n)
{
if(!m_pool || !ptr_in_pool(m_pool, m_poolsize, p, n))
return false;
std::lock_guard<std::mutex> lock(m_mutex);
const size_t start = static_cast<byte*>(p) - m_pool;
auto comp = [](std::pair<size_t, size_t> x, std::pair<size_t, size_t> y){ return x.first < y.first; };
auto i = std::lower_bound(m_freelist.begin(), m_freelist.end(),
std::make_pair(start, 0), comp);
// try to merge with later block
if(start + n == i->first)
{
i->first = start;
i->second += n;
n = 0;
}
// try to merge with previous block
if(i != m_freelist.begin())
{
auto prev = std::prev(i);
if(prev->first + prev->second == start)
{
if(n)
{
prev->second += n;
n = 0;
}
else
{
// merge adjoining
prev->second += i->second;
m_freelist.erase(i);
}
}
}
if(n != 0) // no merge possible?
m_freelist.insert(i, std::make_pair(start, n));
return true;
}
mlock_allocator::mlock_allocator() :
m_poolsize(mlock_limit()),
m_pool(nullptr)
{
#if !defined(MAP_NOCORE)
#define MAP_NOCORE 0
#endif
if(m_poolsize)
{
m_pool = static_cast<byte*>(
::mmap(
nullptr, m_poolsize,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE,
-1, 0));
if(m_pool == static_cast<byte*>(MAP_FAILED))
throw std::runtime_error("Failed to mmap pool");
std::memset(m_pool, 0x00, m_poolsize);
if(::mlock(m_pool, m_poolsize) != 0)
{
::munmap(m_pool, m_poolsize);
m_pool = nullptr;
throw std::runtime_error("Failed to lock pool");
}
m_freelist.push_back(std::make_pair(0, m_poolsize));
}
}
mlock_allocator::~mlock_allocator()
{
if(m_pool)
{
std::memset(m_pool, 0, m_poolsize);
::munlock(m_pool, m_poolsize);
::munmap(m_pool, m_poolsize);
m_pool = nullptr;
}
}
mlock_allocator& mlock_allocator::instance()
{
static mlock_allocator mlock;
return mlock;
}
}
<|endoftext|>
|
<commit_before>#include "SysConfig.h"
#if(HAS_PCA9539)
#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"
namespace
{
CTimer pca9539_sample_timer;
}
CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
: m_pca( i2cInterfaceIn )
{
}
void CPCA9539::Initialize()
{
Serial.println( "CPCA9539.Status:INIT;" );
pca9539_sample_timer.Reset();
Serial.println( "CPCA9539.Status:POST_INIT;");
}
void CPCA9539::Update( CCommand &commandIn )
{
if( pca9539_sample_timer.HasElapsed( 1000 ) )
{
Serial.println( "PCA9539.Status:LOOP;" );
}
}
#endif<commit_msg>Init in module class<commit_after>#include "SysConfig.h"
#if(HAS_PCA9539)
#include <CI2C.h>
#include "CPCA9539.h"
#include "CTimer.h"
#include "NDataManager.h"
namespace
{
CTimer pca9539_sample_timer;
}
CPCA9539::CPCA9539( CI2C *i2cInterfaceIn )
: m_pca( i2cInterfaceIn )
{
}
void CPCA9539::Initialize()
{
Serial.println( "CPCA9539.Status:INIT;" );
pca9539_sample_timer.Reset();
Serial.println( "CPCA9539.Status:POST_INIT;");
}
void CPCA9539::Update( CCommand &commandIn )
{
if( pca9539_sample_timer.HasElapsed( 1000 ) )
{
Serial.println( "PCA9539.Status:LOOP;" );
m_pca.Initialize();
}
}
#endif<|endoftext|>
|
<commit_before>/******************************************************************************\
* EventHandler.hpp *
* An event handler providing GUI-like events *
* *
* *
* Copyright (C) 2006 by Leandro Motta Barros. *
* *
* This program is distributed under the OpenSceneGraph Public License. You *
* should have received a copy of it with the source distribution, in a file *
* named 'COPYING.txt'. *
\******************************************************************************/
#ifndef _GUISH_EVENT_HANDLER_HPP_
#define _GUISH_EVENT_HANDLER_HPP_
#include <boost/signal.hpp>
#include <osgProducer/Viewer>
#include <OSGUIsh/FocusPolicy.hpp>
#include <OSGUIsh/ManualFocusPolicy.hpp>
namespace OSGUIsh
{
/** A \c struct grouping parameters passed to event handlers. Future versions
* of OSGUish may add more members here if necessary without breaking
* existing user code.
* @note Be aware that, in the general case,
* <tt>hit.getNodePath().back() != node.get()</tt>. \c hit contains
* the actual, "low level" hit, while \c node contains the node
* registered with OSGUish. For instance, suppose you register a
* car node, that has a car body node and four wheel nodes as
* subnodes. \c node will always be the whole car, while \c hit will
* be the "car body" or one of the "wheels".
*/
struct HandlerParams
{
public:
/// Convenience constructor.
HandlerParams (NodePtr nodeParam,
const osgGA::GUIEventAdapter& eventParam,
const osgUtil::Hit& hitParam)
: node(nodeParam), event(eventParam), hit(hitParam)
{ }
/// The node generating the event.
NodePtr node;
/** The event data, as passed by OSG. Here you can find many useful
* information, like "which mouse button was pressed".
*/
const osgGA::GUIEventAdapter& event;
/** The \c osgUtil::Hit for the node that was under the mouse pointer
* when the event was generated.
* @note Notice that, in some cases, the \c osgUtil::Hit for the node
* under the mouse pointer doesn't really have something to do
* with the event being handled. For example, if the event is a
* <tt>KeyUp</tt> and the focus policy is not the "node under
* mouse has focus" policy, than the hit will not be related to
* the node generating the event.
* <p>Also, in cases like the above, the hit may even be
* invalid, since, perhaps, there will not be any registered
* node under the mouse pointer.
*/
const osgUtil::Hit& hit;
};
/** An event handler providing GUI-like events for nodes. The \c EventHandler
* has an internal list of nodes being "observed". Every observed node has a
* collection of signals associated to it. These signals represent the
* events that can be generated for the node.
*/
class EventHandler: public osgGA::GUIEventHandler
{
public:
/** Constructs an \c EventHandler.
* @param viewer The viewer used to view the scene graph. This used
* for calling its \c computeIntersections() method.
* @param kbdPolicyFactory The factory that will be used to create the
* \c FocusPolicy used to automatically set the focus for
* keyboard events.
* @param wheelPolicyFactory The factory that will be used to create
* the \c FocusPolicy used to automatically set the focus for
* mouse wheel events.
*/
EventHandler (osgProducer::Viewer& viewer,
const FocusPolicyFactory& kbdPolicyFactory =
FocusPolicyFactoryMason<ManualFocusPolicy>(),
const FocusPolicyFactory& wheelPolicyFactory =
FocusPolicyFactoryMason<ManualFocusPolicy>());
/** Handles upcoming events (overloads virtual method).
* @return See \c handleReturnValues_ please.
*/
bool handle (const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&);
/** Sets the list of root nodes used when picking.
* <p>This deserves some words: when using multiple
* <tt>osg::CameraNode</tt>s (in particular when using HUDs), picking
* in OSG can be problematic. The details of this problem are not
* important here (basically, we don't have control on the relative
* "z-order" of objects in different <tt>CameraNode</tt>s). But it is
* important to know that, if we want to pick objects in different
* camera nodes, we may have some unpredictable results.
* <p>So, what's the solution? Actually, there is no solution. At
* least, not an easy one. So, OSGUIsh uses a list of root nodes when
* picking, as a way to offer some control to its users.
* <p>Suppose, for instance, that you want to pick both in a group of
* objects and in a HUD. By default, OSGUIsh will pick from the root
* of the whole scene (objects and HUD), which (as described above)
* will not work. So, you call \c setPickingRoots() passing two nodes:
* first the HUD, second the group of objects.
* <p>Once you do this, OSGUIsh will start picking in two stages.
* First, it will try picking the HUD. If it hits something in the
* HUD, that hit will be used. If not, OSGUIsh will try picking the
* group of objects.
*/
void setPickingRoots (std::vector<NodePtr> newRoot);
/** Sets the root used by OSGUIsh when picking.
* @see setPickingRoots for a longer discussion on how OSGUIsh
* performs picking (you can set more than one root, for
* example).
*/
void setPickingRoot (NodePtr newRoot);
/** A type representing a signal used in OSGUIsh. This signal returns
* nothing and takes a \c HandlerParams, which packs all relevant data
* for an event handler function.
*/
typedef boost::signal<void (HandlerParams&)> Signal_t;
/// A (smart) pointer to a \c Signal_t;
typedef boost::shared_ptr<Signal_t> SignalPtr;
/** Adds a given node to the list of nodes being "observed" by this
* \c EventHandler. In other words, signals for this node will be
* triggered from this call on.
* @param node The node that will be added to this \c EventHandler.
*/
void addNode (const NodePtr node);
/** Returns a signal associated with a given node. This is typically
* used to call \c connect() on the returned signal.
* @param node The desired node.
* @param signal The desired signal. Valid signals are
* <tt>"MouseEnter"</tt>, <tt>"MouseLeave"</tt>,
* <tt>"MouseMove"</tt>, <tt>"MouseDown"</tt>,
* <tt>"MouseUp"</tt>, <tt>"Click"</tt>,
* <tt>"DoubleClick"</tt>, <tt>"MouseWheelUp"</tt>,
* <tt>"MouseWheelDown"</tt>, <tt>"KeyUp"</tt> and
* <tt>"KeyDown"</tt>.
*/
SignalPtr getSignal (const NodePtr node, const std::string& signal);
/** Ignores or stops to ignore faces that are back-facing the viewer
* when picking. It may be useful to ignore back faces when backface
* culling is enabled.
* @param ignore If \c true, back faces will be ignored when picking.
* If \c false, back faces will be considered when piking.
*/
void ignoreBackFaces (bool ignore = true)
{ ignoreBackFaces_ = ignore; }
/// Sets the node that will receive keyboard events.
void setKeyboardFocus (const NodePtr node);
/// Sets the node that will receive mouse wheel events.
void setMouseWheelFocus (const NodePtr node);
/** Sets the focus policy for keyboard events to a given one.
* @param policyFactory The factory that will be used to create the
* actual policy.
*/
void setKeyboardFocusPolicy (const FocusPolicyFactory& policyFactory);
/** Sets the focus policy for mouse wheel events to a given one.
* @param policyFactory The factory that will be used to create the
* actual policy.
*/
void setMouseWheelFocusPolicy (const FocusPolicyFactory& policyFactory);
private:
/** Returns the first node in an \c osg::NodePath that is present in the
* list of nodes being "observed" by this \c EventHandler. This is
* necessary in the cases in which the user is picking a node that is
* child of an added node. That's the case, for instance, of when the
* user adds a node read from a 3D model file returned by
* \c osgDB::readNodeFile().
* @param nodePath The node path leading to the node being queried.
* @returns The first in \c nodePath that as added to the list of
* nodes being observed.
*/
NodePtr getObservedNode (const osg::NodePath& nodePath);
/** Handles a \c FRAME event triggered by Producer. Signals triggered
* here are <tt>"MouseEnter"</tt>, <tt>"MouseLeave"</tt> and
* <tt>"MouseMove"</tt>.
* @param ea The event generated by Producer.
*/
void handleFrameEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c PUSH event triggered by Producer. The only signal
* triggered here is <tt>"MouseDown"</tt>, but this function also does
* bookkeeping related to other mouse signals.
* @param ea The event generated by Producer.
*/
void handlePushEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c RELEASE event triggered by Producer. Signals triggered
* here are <tt>"MouseUp"</tt>, <tt>"Click"</tt> and
* <tt>"DoubleClick"</tt>.
* @param ea The event generated by Producer.
*/
void handleReleaseEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c KEYDOWN event triggered by Producer. The only signal
* triggered here is <tt>"KeyDown"</tt>.
* @param ea The event generated by Producer.
*/
void handleKeyDownEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c KEYUP event triggered by Producer. The only signal
* triggered here is <tt>"KeyUp"</tt>.
* @param ea The event generated by Producer.
*/
void handleKeyUpEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c SCROLL event triggered by Producer. The signal
* triggered here are <tt>"ScrollUp"</tt> and <tt>"ScrollDown"</tt>.
* @param ea The event generated by Producer.
*/
void handleScrollEvent (const osgGA::GUIEventAdapter& ea);
/// The viewer viewing the nodes.
osgProducer::Viewer& viewer_;
/** If this is \c true, faces back-facing the viewer will be ignored
* while picking.
*/
bool ignoreBackFaces_;
/** The list of root nodes used when picking.
* @see setPickingRoots for a discussion on how this is used and why
* this is necessary.
*/
std::vector<NodePtr> pickingRoots_;
/** The values to be returned by the \c handle() method, depending on
* the event type it is handling. Values are not initialized, meaning
* that \c handle(), by default, returns \c false for all event types.
* @todo Implement a method like \c setHandleReturnValue(), so that
* the user can configure this.
*/
std::map <osgGA::GUIEventAdapter::EventType, bool> handleReturnValues_;
/// Type mapping a signal name to the signal object.
typedef std::map <std::string, SignalPtr> SignalCollection_t;
/// Type mapping nodes to the collection of signals associated to it.
typedef std::map <NodePtr, SignalCollection_t > SignalsMap_t;
/** Structure containing all the signals used by this \c EventHandler.
* It can be used with a syntax like this:
* <tt>signals_[node]["MouseMove"]->connect(&MyHandler);</tt>
*/
SignalsMap_t signals_;
/** The \c osgUtil::Hit structure for the node currently under the
* mouse pointer. (Respecting the \c ignoreBackFaces_ flag.)
*/
osgUtil::Hit hitUnderMouse_;
//
// For "MouseEnter", "MouseLeave", "MouseMove"
//
/// The node currently under the mouse pointer.
NodePtr nodeUnderMouse_;
/** The position (in the object coordinate system) of
* \c nodeUnderMouse_ currently under the mouse pointer.
*/
osg::Vec3 positionUnderMouse_;
//
// For "Click" and "DoubleClick"
//
/// The buttons of a mouse.
enum MouseButton
{
LEFT_MOUSE_BUTTON, ///< The left button.
MIDDLE_MOUSE_BUTTON, ///< The middle button.
RIGHT_MOUSE_BUTTON, ///< The right button.
MOUSE_BUTTON_COUNT ///< The number of buttons in a mouse.
};
/** Returns the mouse button used in the \c osgGA::GUIEventAdapter
* passed as parameter.
*/
MouseButton getMouseButton (const osgGA::GUIEventAdapter& ea);
/** An array indicating (for every mouse button) which was the node
* that received the last mouse down event. This is used to identify
* clicks.
*/
NodePtr nodeThatGotMouseDown_[MOUSE_BUTTON_COUNT];
/** An array indicating (for every mouse button) which was the node
* that received the last click event. This is used to identify double
* clicks.
*/
NodePtr nodeThatGotClick_[MOUSE_BUTTON_COUNT];
/** An array indicating (for every mouse button) the time at which the
* last click event has happened. This is used to identify double
* clicks.
*/
double timeOfLastClick_[MOUSE_BUTTON_COUNT];
//
// For "KeyUp" and "KeyDown"
//
/// The node receiving keyboard events.
NodePtr kbdFocus_;
/// The focus policy for keyboard-related events.
FocusPolicyPtr kbdFocusPolicy_;
//
// For "MouseWheelUp" and "MouseWheelDown"
//
/// The node receiving mouse wheel events.
NodePtr wheelFocus_;
/// The focus policy for mouse wheel-related events.
FocusPolicyPtr wheelFocusPolicy_;
};
} // namespace OSGUIsh
#endif // _GUISH_EVENT_HANDLER_HPP_
<commit_msg>Documented the glitch concerning the call to 'osgProducer::Viewer::setSceneData()', the construction of 'OSGUIsh::EventHandler' and the default picking root.<commit_after>/******************************************************************************\
* EventHandler.hpp *
* An event handler providing GUI-like events *
* *
* *
* Copyright (C) 2006 by Leandro Motta Barros. *
* *
* This program is distributed under the OpenSceneGraph Public License. You *
* should have received a copy of it with the source distribution, in a file *
* named 'COPYING.txt'. *
\******************************************************************************/
#ifndef _GUISH_EVENT_HANDLER_HPP_
#define _GUISH_EVENT_HANDLER_HPP_
#include <boost/signal.hpp>
#include <osgProducer/Viewer>
#include <OSGUIsh/FocusPolicy.hpp>
#include <OSGUIsh/ManualFocusPolicy.hpp>
namespace OSGUIsh
{
/** A \c struct grouping parameters passed to event handlers. Future versions
* of OSGUish may add more members here if necessary without breaking
* existing user code.
* @note Be aware that, in the general case,
* <tt>hit.getNodePath().back() != node.get()</tt>. \c hit contains
* the actual, "low level" hit, while \c node contains the node
* registered with OSGUish. For instance, suppose you register a
* car node, that has a car body node and four wheel nodes as
* subnodes. \c node will always be the whole car, while \c hit will
* be the "car body" or one of the "wheels".
*/
struct HandlerParams
{
public:
/// Convenience constructor.
HandlerParams (NodePtr nodeParam,
const osgGA::GUIEventAdapter& eventParam,
const osgUtil::Hit& hitParam)
: node(nodeParam), event(eventParam), hit(hitParam)
{ }
/// The node generating the event.
NodePtr node;
/** The event data, as passed by OSG. Here you can find many useful
* information, like "which mouse button was pressed".
*/
const osgGA::GUIEventAdapter& event;
/** The \c osgUtil::Hit for the node that was under the mouse pointer
* when the event was generated.
* @note Notice that, in some cases, the \c osgUtil::Hit for the node
* under the mouse pointer doesn't really have something to do
* with the event being handled. For example, if the event is a
* <tt>KeyUp</tt> and the focus policy is not the "node under
* mouse has focus" policy, than the hit will not be related to
* the node generating the event.
* <p>Also, in cases like the above, the hit may even be
* invalid, since, perhaps, there will not be any registered
* node under the mouse pointer.
*/
const osgUtil::Hit& hit;
};
/** An event handler providing GUI-like events for nodes. The \c EventHandler
* has an internal list of nodes being "observed". Every observed node has a
* collection of signals associated to it. These signals represent the
* events that can be generated for the node.
*/
class EventHandler: public osgGA::GUIEventHandler
{
public:
/** Constructs an \c EventHandler. The constructor will set the picking
* root to \c viewer.getSceneSceneData(). So, if you want to use this
* default value, call setSceneData() on the viewer before passing it
* to this constructor.
* @param viewer The viewer used to view the scene graph. This used
* for calling its \c computeIntersections() method.
* @param kbdPolicyFactory The factory that will be used to create the
* \c FocusPolicy used to automatically set the focus for
* keyboard events.
* @param wheelPolicyFactory The factory that will be used to create
* the \c FocusPolicy used to automatically set the focus for
* mouse wheel events.
* @see setPickingRoots for a way to manually set the picking roots
* (and also for an explanation on what are these "picking roots"
* after all).
* @see setPickingRoot for another way to manually set the picking
* roots.
*/
EventHandler (osgProducer::Viewer& viewer,
const FocusPolicyFactory& kbdPolicyFactory =
FocusPolicyFactoryMason<ManualFocusPolicy>(),
const FocusPolicyFactory& wheelPolicyFactory =
FocusPolicyFactoryMason<ManualFocusPolicy>());
/** Handles upcoming events (overloads virtual method).
* @return See \c handleReturnValues_ please.
*/
bool handle (const osgGA::GUIEventAdapter& ea,
osgGA::GUIActionAdapter&);
/** Sets the list of root nodes used when picking.
* <p>This deserves some words: when using multiple
* <tt>osg::CameraNode</tt>s (in particular when using HUDs), picking
* in OSG can be problematic. The details of this problem are not
* important here (basically, we don't have control on the relative
* "z-order" of objects in different <tt>CameraNode</tt>s). But it is
* important to know that, if we want to pick objects in different
* camera nodes, we may have some unpredictable results.
* <p>So, what's the solution? Actually, there is no solution. At
* least, not an easy one. So, OSGUIsh uses a list of root nodes when
* picking, as a way to offer some control to its users.
* <p>Suppose, for instance, that you want to pick both in a group of
* objects and in a HUD. By default, OSGUIsh will pick from the root
* of the whole scene (objects and HUD), which (as described above)
* will not work. So, you call \c setPickingRoots() passing two nodes:
* first the HUD, second the group of objects.
* <p>Once you do this, OSGUIsh will start picking in two stages.
* First, it will try picking the HUD. If it hits something in the
* HUD, that hit will be used. If not, OSGUIsh will try picking the
* group of objects.
*/
void setPickingRoots (std::vector<NodePtr> newRoot);
/** Sets the root used by OSGUIsh when picking.
* @see setPickingRoots for a longer discussion on how OSGUIsh
* performs picking (you can set more than one root, for
* example).
*/
void setPickingRoot (NodePtr newRoot);
/** A type representing a signal used in OSGUIsh. This signal returns
* nothing and takes a \c HandlerParams, which packs all relevant data
* for an event handler function.
*/
typedef boost::signal<void (HandlerParams&)> Signal_t;
/// A (smart) pointer to a \c Signal_t;
typedef boost::shared_ptr<Signal_t> SignalPtr;
/** Adds a given node to the list of nodes being "observed" by this
* \c EventHandler. In other words, signals for this node will be
* triggered from this call on.
* @param node The node that will be added to this \c EventHandler.
*/
void addNode (const NodePtr node);
/** Returns a signal associated with a given node. This is typically
* used to call \c connect() on the returned signal.
* @param node The desired node.
* @param signal The desired signal. Valid signals are
* <tt>"MouseEnter"</tt>, <tt>"MouseLeave"</tt>,
* <tt>"MouseMove"</tt>, <tt>"MouseDown"</tt>,
* <tt>"MouseUp"</tt>, <tt>"Click"</tt>,
* <tt>"DoubleClick"</tt>, <tt>"MouseWheelUp"</tt>,
* <tt>"MouseWheelDown"</tt>, <tt>"KeyUp"</tt> and
* <tt>"KeyDown"</tt>.
*/
SignalPtr getSignal (const NodePtr node, const std::string& signal);
/** Ignores or stops to ignore faces that are back-facing the viewer
* when picking. It may be useful to ignore back faces when backface
* culling is enabled.
* @param ignore If \c true, back faces will be ignored when picking.
* If \c false, back faces will be considered when piking.
*/
void ignoreBackFaces (bool ignore = true)
{ ignoreBackFaces_ = ignore; }
/// Sets the node that will receive keyboard events.
void setKeyboardFocus (const NodePtr node);
/// Sets the node that will receive mouse wheel events.
void setMouseWheelFocus (const NodePtr node);
/** Sets the focus policy for keyboard events to a given one.
* @param policyFactory The factory that will be used to create the
* actual policy.
*/
void setKeyboardFocusPolicy (const FocusPolicyFactory& policyFactory);
/** Sets the focus policy for mouse wheel events to a given one.
* @param policyFactory The factory that will be used to create the
* actual policy.
*/
void setMouseWheelFocusPolicy (const FocusPolicyFactory& policyFactory);
private:
/** Returns the first node in an \c osg::NodePath that is present in the
* list of nodes being "observed" by this \c EventHandler. This is
* necessary in the cases in which the user is picking a node that is
* child of an added node. That's the case, for instance, of when the
* user adds a node read from a 3D model file returned by
* \c osgDB::readNodeFile().
* @param nodePath The node path leading to the node being queried.
* @returns The first in \c nodePath that as added to the list of
* nodes being observed.
*/
NodePtr getObservedNode (const osg::NodePath& nodePath);
/** Handles a \c FRAME event triggered by Producer. Signals triggered
* here are <tt>"MouseEnter"</tt>, <tt>"MouseLeave"</tt> and
* <tt>"MouseMove"</tt>.
* @param ea The event generated by Producer.
*/
void handleFrameEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c PUSH event triggered by Producer. The only signal
* triggered here is <tt>"MouseDown"</tt>, but this function also does
* bookkeeping related to other mouse signals.
* @param ea The event generated by Producer.
*/
void handlePushEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c RELEASE event triggered by Producer. Signals triggered
* here are <tt>"MouseUp"</tt>, <tt>"Click"</tt> and
* <tt>"DoubleClick"</tt>.
* @param ea The event generated by Producer.
*/
void handleReleaseEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c KEYDOWN event triggered by Producer. The only signal
* triggered here is <tt>"KeyDown"</tt>.
* @param ea The event generated by Producer.
*/
void handleKeyDownEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c KEYUP event triggered by Producer. The only signal
* triggered here is <tt>"KeyUp"</tt>.
* @param ea The event generated by Producer.
*/
void handleKeyUpEvent (const osgGA::GUIEventAdapter& ea);
/** Handles a \c SCROLL event triggered by Producer. The signal
* triggered here are <tt>"ScrollUp"</tt> and <tt>"ScrollDown"</tt>.
* @param ea The event generated by Producer.
*/
void handleScrollEvent (const osgGA::GUIEventAdapter& ea);
/// The viewer viewing the nodes.
osgProducer::Viewer& viewer_;
/** If this is \c true, faces back-facing the viewer will be ignored
* while picking.
*/
bool ignoreBackFaces_;
/** The list of root nodes used when picking.
* @see setPickingRoots for a discussion on how this is used and why
* this is necessary.
*/
std::vector<NodePtr> pickingRoots_;
/** The values to be returned by the \c handle() method, depending on
* the event type it is handling. Values are not initialized, meaning
* that \c handle(), by default, returns \c false for all event types.
* @todo Implement a method like \c setHandleReturnValue(), so that
* the user can configure this.
*/
std::map <osgGA::GUIEventAdapter::EventType, bool> handleReturnValues_;
/// Type mapping a signal name to the signal object.
typedef std::map <std::string, SignalPtr> SignalCollection_t;
/// Type mapping nodes to the collection of signals associated to it.
typedef std::map <NodePtr, SignalCollection_t > SignalsMap_t;
/** Structure containing all the signals used by this \c EventHandler.
* It can be used with a syntax like this:
* <tt>signals_[node]["MouseMove"]->connect(&MyHandler);</tt>
*/
SignalsMap_t signals_;
/** The \c osgUtil::Hit structure for the node currently under the
* mouse pointer. (Respecting the \c ignoreBackFaces_ flag.)
*/
osgUtil::Hit hitUnderMouse_;
//
// For "MouseEnter", "MouseLeave", "MouseMove"
//
/// The node currently under the mouse pointer.
NodePtr nodeUnderMouse_;
/** The position (in the object coordinate system) of
* \c nodeUnderMouse_ currently under the mouse pointer.
*/
osg::Vec3 positionUnderMouse_;
//
// For "Click" and "DoubleClick"
//
/// The buttons of a mouse.
enum MouseButton
{
LEFT_MOUSE_BUTTON, ///< The left button.
MIDDLE_MOUSE_BUTTON, ///< The middle button.
RIGHT_MOUSE_BUTTON, ///< The right button.
MOUSE_BUTTON_COUNT ///< The number of buttons in a mouse.
};
/** Returns the mouse button used in the \c osgGA::GUIEventAdapter
* passed as parameter.
*/
MouseButton getMouseButton (const osgGA::GUIEventAdapter& ea);
/** An array indicating (for every mouse button) which was the node
* that received the last mouse down event. This is used to identify
* clicks.
*/
NodePtr nodeThatGotMouseDown_[MOUSE_BUTTON_COUNT];
/** An array indicating (for every mouse button) which was the node
* that received the last click event. This is used to identify double
* clicks.
*/
NodePtr nodeThatGotClick_[MOUSE_BUTTON_COUNT];
/** An array indicating (for every mouse button) the time at which the
* last click event has happened. This is used to identify double
* clicks.
*/
double timeOfLastClick_[MOUSE_BUTTON_COUNT];
//
// For "KeyUp" and "KeyDown"
//
/// The node receiving keyboard events.
NodePtr kbdFocus_;
/// The focus policy for keyboard-related events.
FocusPolicyPtr kbdFocusPolicy_;
//
// For "MouseWheelUp" and "MouseWheelDown"
//
/// The node receiving mouse wheel events.
NodePtr wheelFocus_;
/// The focus policy for mouse wheel-related events.
FocusPolicyPtr wheelFocusPolicy_;
};
} // namespace OSGUIsh
#endif // _GUISH_EVENT_HANDLER_HPP_
<|endoftext|>
|
<commit_before>///
/// anax
/// Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com)
///
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from the
/// use of this software.
///
/// 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:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment
/// in the product documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
/// 3. The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
#ifndef __ANAX_COMPONENTFILTER_HPP__
#define __ANAX_COMPONENTFILTER_HPP__
#include <type_traits>
#include <boost/dynamic_bitset.hpp>
#include "detail/EntityIdPool.hpp"
#include "detail/ContainerUtils.hpp"
#include "config.hpp"
#include "Component.hpp"
#include "ComponentTypeList.hpp"
namespace anax
{
/// \brief A class used to filter out Components
///
/// This class was designed to be used in conjuction
/// with systems in the entity systems. As it grants
/// the ability to filter out entities with specific
/// components.
///
/// \author Miguel Martin
class ComponentFilter
{
public:
ComponentFilter() {}
ComponentFilter(const ComponentFilter&) = default;
ComponentFilter(ComponentFilter&&) = default;
ComponentFilter& operator=(const ComponentFilter&) = default;
ComponentFilter& operator=(ComponentFilter&&) = default;
// TODO: Documentation
template <typename C1>
ComponentFilter& requires()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_requiredComponentsList, C1::GetTypeId());
_requiredComponentsList[C1::GetTypeId()] = true;
return *this;
}
template <typename C1>
ComponentFilter& requiresOneOf()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_requiresOneOfComponentsList, C1::GetTypeId());
_requiresOneOfComponentsList[C1::GetTypeId()] = true;
return *this;
}
template <typename C1>
ComponentFilter& exclude()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_excludeComponentsList, C1::GetTypeId());
_excludeComponentsList[C1::GetTypeId()] = true;
return *this;
}
#ifndef ANAX_DONT_USE_VARIADIC_TEMPLATES
template <typename C1, typename C2, typename... Components>
ComponentFilter& requires()
{
requires<C1>();
requires<C2, Components...>();
return *this;
}
template <typename C1, typename C2, typename... Components>
ComponentFilter& requiresOneOf()
{
requiresOneOf<C1>();
requiresOneOf<C2, Components...>();
return *this;
}
template <typename C1, typename C2, typename... Components>
ComponentFilter& excludes()
{
excludes<C1>();
excludes<C2, Components...>();
return *this;
}
#endif // ANAX_DONT_USE_VARIADIC_TEMPLATES
/// Determines if a list of component types passes the filter
/// \param componentTypeList The list of component types you wish to check if it passes through the filter
/// \return true if the list of component types passes through the filter (i.e. is valid)
bool doesPassFilter(const ComponentTypeList& componentTypeList) const;
/// Clears the filter
void clear();
private:
/// A list of component types that are required
ComponentTypeList _requiredComponentsList;
/// A list of component types that are required
/// at least once
ComponentTypeList _requiresOneOfComponentsList;
/// A list of component types that must be excluded
ComponentTypeList _excludeComponentsList;
};
}
#endif // __ANAX_COMPONENTFILTER_HPP__<commit_msg>Forgot to add s to exclude method in ComponentFilter<commit_after>///
/// anax
/// Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com)
///
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from the
/// use of this software.
///
/// 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:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment
/// in the product documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
/// 3. The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
#ifndef __ANAX_COMPONENTFILTER_HPP__
#define __ANAX_COMPONENTFILTER_HPP__
#include <type_traits>
#include <boost/dynamic_bitset.hpp>
#include "detail/EntityIdPool.hpp"
#include "detail/ContainerUtils.hpp"
#include "config.hpp"
#include "Component.hpp"
#include "ComponentTypeList.hpp"
namespace anax
{
/// \brief A class used to filter out Components
///
/// This class was designed to be used in conjuction
/// with systems in the entity systems. As it grants
/// the ability to filter out entities with specific
/// components.
///
/// \author Miguel Martin
class ComponentFilter
{
public:
ComponentFilter() {}
ComponentFilter(const ComponentFilter&) = default;
ComponentFilter(ComponentFilter&&) = default;
ComponentFilter& operator=(const ComponentFilter&) = default;
ComponentFilter& operator=(ComponentFilter&&) = default;
// TODO: Documentation
template <typename C1>
ComponentFilter& requires()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_requiredComponentsList, C1::GetTypeId());
_requiredComponentsList[C1::GetTypeId()] = true;
return *this;
}
template <typename C1>
ComponentFilter& requiresOneOf()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_requiresOneOfComponentsList, C1::GetTypeId());
_requiresOneOfComponentsList[C1::GetTypeId()] = true;
return *this;
}
template <typename C1>
ComponentFilter& excludes()
{
static_assert(std::is_base_of<BaseComponent, C1>(), "C1 does not inherit from Component");
detail::EnsureCapacity(_excludeComponentsList, C1::GetTypeId());
_excludeComponentsList[C1::GetTypeId()] = true;
return *this;
}
#ifndef ANAX_DONT_USE_VARIADIC_TEMPLATES
template <typename C1, typename C2, typename... Components>
ComponentFilter& requires()
{
requires<C1>();
requires<C2, Components...>();
return *this;
}
template <typename C1, typename C2, typename... Components>
ComponentFilter& requiresOneOf()
{
requiresOneOf<C1>();
requiresOneOf<C2, Components...>();
return *this;
}
template <typename C1, typename C2, typename... Components>
ComponentFilter& excludes()
{
excludes<C1>();
excludes<C2, Components...>();
return *this;
}
#endif // ANAX_DONT_USE_VARIADIC_TEMPLATES
/// Determines if a list of component types passes the filter
/// \param componentTypeList The list of component types you wish to check if it passes through the filter
/// \return true if the list of component types passes through the filter (i.e. is valid)
bool doesPassFilter(const ComponentTypeList& componentTypeList) const;
/// Clears the filter
void clear();
private:
/// A list of component types that are required
ComponentTypeList _requiredComponentsList;
/// A list of component types that are required
/// at least once
ComponentTypeList _requiresOneOfComponentsList;
/// A list of component types that must be excluded
ComponentTypeList _excludeComponentsList;
};
}
#endif // __ANAX_COMPONENTFILTER_HPP__<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <type_traits>
#include <archie/meta/static_constexpr_storage.hpp>
#include <archie/fused/if_t.hpp>
namespace archie {
namespace detail {
template <typename...>
struct to_function_pointer_;
template <typename R, typename... Args>
struct to_function_pointer_<R(Args...)> {
using type = R (*)(Args...);
template <typename T>
type operator()(T&& t) const {
return fused::if_(std::is_convertible<std::decay_t<T>, type>{},
[](auto&& x) -> type { return std::forward<decltype(x)>(x); },
[](auto&& x) -> type {
using ObjT = std::decay_t<decltype(x)>;
static_assert(std::is_empty<ObjT>::value &&
std::is_trivially_constructible<ObjT>::value,
"");
return [](Args... args) {
return std::add_const_t<ObjT>{}(std::forward<Args>(args)...);
};
})(std::forward<T>(t));
}
};
}
template <typename...>
struct pure_function;
template <typename R, typename... Args>
struct pure_function<R(Args...)> {
using type = R (*)(Args...);
pure_function() = default;
template <typename T>
explicit pure_function(T t)
: fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}
template <typename T>
pure_function& operator=(T t) {
fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);
return *this;
}
template <typename... U>
auto operator()(U&&... u) const {
return (*fptr)(std::forward<U>(u)...);
}
explicit operator bool() const { return fptr != nullptr; }
operator type() const { return fptr; }
private:
type fptr = nullptr;
};
}
<commit_msg>decltype(auto)<commit_after>#pragma once
#include <utility>
#include <type_traits>
#include <archie/meta/static_constexpr_storage.hpp>
#include <archie/fused/if_t.hpp>
namespace archie {
namespace detail {
template <typename...>
struct to_function_pointer_;
template <typename R, typename... Args>
struct to_function_pointer_<R(Args...)> {
using type = R (*)(Args...);
template <typename T>
type operator()(T&& t) const {
return fused::if_(std::is_convertible<std::decay_t<T>, type>{},
[](auto&& x) -> type { return std::forward<decltype(x)>(x); },
[](auto&& x) -> type {
using ObjT = std::decay_t<decltype(x)>;
static_assert(std::is_empty<ObjT>::value &&
std::is_trivially_constructible<ObjT>::value,
"");
return [](Args... args) {
return std::add_const_t<ObjT>{}(std::forward<Args>(args)...);
};
})(std::forward<T>(t));
}
};
}
template <typename...>
struct pure_function;
template <typename R, typename... Args>
struct pure_function<R(Args...)> {
using type = R (*)(Args...);
pure_function() = default;
template <typename T>
explicit pure_function(T t)
: fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}
template <typename T>
pure_function& operator=(T t) {
fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);
return *this;
}
template <typename... U>
decltype(auto) operator()(U&&... u) const {
return (*fptr)(std::forward<U>(u)...);
}
explicit operator bool() const { return fptr != nullptr; }
operator type() const { return fptr; }
private:
type fptr = nullptr;
};
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <string>
#include "blib/bun/CppTypeToSQLString.hpp"
namespace blib{
namespace bun{
namespace __private{
template<typename T>
struct OneToNCreation{
std::string parent_table(){
return "";
}
std::string table_name(){
return "";
}
std::string sql(){
return "";
}
private:
std::string __parent_table(const std::string& /*parent_table*/){
return "";
}
std::string __table_name(const std::string& /*table-name*/){
return "";
}
}
template<typename T>
struct OneToNCreation<std::vector<T>>{
std::string parent_table(){
return "";
}
std::string table_name(){
return "";
}
std::string sql(){
return "";
}
private:
std::string __parent_table(const std::string& parent_table){
return "";
}
std::string __table_name(const std::string& /*table-name*/){
return "";
}
}
}
}
}<commit_msg>Adding some more changes<commit_after>#include <vector>
#include <string>
#include "blib/bun/CppTypeToSQLString.hpp"
namespace blib{
namespace bun{
namespace __private{
template<typename T>
struct NxNMappingTables{
static std::string base_table_name();
static std::string table_name();
}
template<typename T>
struct OneToNCreationSql{
static std::string sql(){
return "";
}
}
template<typename T>
struct OneToNCreationSql<std::vector<T>>{
static std::string const& table_name(){
static const std::string table_name = NxNMappingTables<std::vector<T>>::base_table_name() + "_" + NxNMappingTables<std::vector<T>>::table_name()
return table_name;
}
static std::string sql(){
static std::string sql = "CREATE TABLE '" + table_name() + "' WITH "
}
}
}
}
}<|endoftext|>
|
<commit_before>#pragma once
#include "clam/ClamAnalysisParams.hh"
#include "clam/Clam.hh"
#include <map>
namespace clam {
class DomainRegistry {
public:
typedef std::map<CrabDomain::Type, clam_abstract_domain> FactoryMap;
template<typename AbsDom>
static bool add(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
auto dom = DomainRegistry::makeTopDomain<AbsDom>();
return map.insert({dom_ty, dom}).second;
}
static bool count(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
return map.find(dom_ty) != map.end();
}
static clam_abstract_domain at(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
return map.at(dom_ty);
}
private:
static FactoryMap& getFactoryMap() {
static FactoryMap map;
return map;
}
/* The domains instantiations happen in lib/Clam/domains */
template<typename AbsDom>
static clam_abstract_domain makeTopDomain();
};
#define REGISTER_DOMAIN(domain_enum_val, domain_decl) \
bool domain_decl ## _entry = DomainRegistry::add<domain_decl>(domain_enum_val);
} //end namespace clam
<commit_msg>refactor(RegisterAnalysis): reset stats after adding domain<commit_after>#pragma once
#include "clam/ClamAnalysisParams.hh"
#include "clam/Clam.hh"
#include "crab/support/stats.hpp"
#include <map>
namespace clam {
class DomainRegistry {
public:
typedef std::map<CrabDomain::Type, clam_abstract_domain> FactoryMap;
template<typename AbsDom>
static bool add(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
auto dom = DomainRegistry::makeTopDomain<AbsDom>();
bool res = map.insert({dom_ty, dom}).second;
crab::CrabStats::reset();
return res;
}
static bool count(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
return map.find(dom_ty) != map.end();
}
static clam_abstract_domain at(CrabDomain::Type dom_ty) {
auto &map = getFactoryMap();
return map.at(dom_ty);
}
private:
static FactoryMap& getFactoryMap() {
static FactoryMap map;
return map;
}
/* The domains instantiations happen in lib/Clam/domains */
template<typename AbsDom>
static clam_abstract_domain makeTopDomain();
};
#define REGISTER_DOMAIN(domain_enum_val, domain_decl) \
bool domain_decl ## _entry = DomainRegistry::add<domain_decl>(domain_enum_val);
} //end namespace clam
<|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief bit operation
*/
#include <assert.h>
#include <cybozu/inttype.hpp>
#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
#if defined(_WIN32)
#include <intrin.h>
#elif defined(__linux__) || defined(__CYGWIN__) || defined(__clang__)
#include <x86intrin.h>
#elif defined(__GNUC__)
#include <emmintrin.h>
#endif
#endif
namespace cybozu {
namespace bit_op_local {
template<bool equalTo8>
struct Tag {};
// sizeof(T) < 8
template<>
struct Tag<false> {
template<class T>
static inline int bsf(T x)
{
#if defined(_MSC_VER)
unsigned long out;
_BitScanForward(&out, x);
#pragma warning(suppress: 6102)
return out;
#else
return __builtin_ctz(x);
#endif
}
template<class T>
static inline int bsr(T x)
{
#if defined(_MSC_VER)
unsigned long out;
_BitScanReverse(&out, x);
#pragma warning(suppress: 6102)
return out;
#else
return __builtin_clz(x) ^ 0x1f;
#endif
}
};
// sizeof(T) == 8
template<>
struct Tag<true> {
template<class T>
static inline int bsf(T x)
{
#if defined(_MSC_VER) && defined(_WIN64)
unsigned long out;
_BitScanForward64(&out, x);
#pragma warning(suppress: 6102)
return out;
#elif defined(__x86_64__)
return __builtin_ctzl(x);
#else
const uint32_t L = uint32_t(x);
if (L) return Tag<false>::bsf(L);
const uint32_t H = uint32_t(x >> 32);
return Tag<false>::bsf(H) + 32;
#endif
}
template<class T>
static inline int bsr(T x)
{
#if defined(_MSC_VER) && defined(_WIN64)
unsigned long out;
_BitScanReverse64(&out, x);
#pragma warning(suppress: 6102)
return out;
#elif defined(__x86_64__)
return __builtin_clzl(x) ^ 0x3f;
#else
const uint32_t H = uint32_t(x >> 32);
if (H) return Tag<false>::bsr(H) + 32;
const uint32_t L = uint32_t(x);
return Tag<false>::bsr(L);
#endif
}
};
} // bit_op_local
template<class T>
int bsf(T x)
{
return bit_op_local::Tag<sizeof(T) == 8>::bsf(x);
}
template<class T>
int bsr(T x)
{
return bit_op_local::Tag<sizeof(T) == 8>::bsr(x);
}
template<class T>
uint64_t makeBitMask64(T x)
{
assert(x < 64);
return (uint64_t(1) << x) - 1;
}
template<class T>
uint32_t popcnt(T x);
template<>
inline uint32_t popcnt<uint32_t>(uint32_t x)
{
#if defined(_MSC_VER)
return static_cast<uint32_t>(_mm_popcnt_u32(x));
#else
return static_cast<uint32_t>(__builtin_popcount(x));
#endif
}
template<>
inline uint32_t popcnt<uint64_t>(uint64_t x)
{
#if defined(_WIN64)
return static_cast<uint32_t>(_mm_popcnt_u64(x));
#elif defined(__x86_64__)
return static_cast<uint32_t>(__builtin_popcountl(x));
#else
return popcnt<uint32_t>(static_cast<uint32_t>(x)) + popcnt<uint32_t>(static_cast<uint32_t>(x >> 32));
#endif
}
} // cybozu
<commit_msg>fix bsr/bsf for uint64_t on mingw<commit_after>#pragma once
/**
@file
@brief bit operation
*/
#include <assert.h>
#include <cybozu/inttype.hpp>
#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
#if defined(_WIN32)
#include <intrin.h>
#elif defined(__linux__) || defined(__CYGWIN__) || defined(__clang__)
#include <x86intrin.h>
#elif defined(__GNUC__)
#include <emmintrin.h>
#endif
#endif
namespace cybozu {
namespace bit_op_local {
template<bool equalTo8>
struct Tag {};
// sizeof(T) < 8
template<>
struct Tag<false> {
template<class T>
static inline int bsf(T x)
{
#if defined(_MSC_VER)
unsigned long out;
_BitScanForward(&out, x);
#pragma warning(suppress: 6102)
return out;
#else
return __builtin_ctz(x);
#endif
}
template<class T>
static inline int bsr(T x)
{
#if defined(_MSC_VER)
unsigned long out;
_BitScanReverse(&out, x);
#pragma warning(suppress: 6102)
return out;
#else
return __builtin_clz(x) ^ 0x1f;
#endif
}
};
// sizeof(T) == 8
template<>
struct Tag<true> {
template<class T>
static inline int bsf(T x)
{
#if defined(_MSC_VER) && defined(_WIN64)
unsigned long out;
_BitScanForward64(&out, x);
#pragma warning(suppress: 6102)
return out;
#elif defined(__x86_64__)
return __builtin_ctzll(x);
#else
const uint32_t L = uint32_t(x);
if (L) return Tag<false>::bsf(L);
const uint32_t H = uint32_t(x >> 32);
return Tag<false>::bsf(H) + 32;
#endif
}
template<class T>
static inline int bsr(T x)
{
#if defined(_MSC_VER) && defined(_WIN64)
unsigned long out;
_BitScanReverse64(&out, x);
#pragma warning(suppress: 6102)
return out;
#elif defined(__x86_64__)
return __builtin_clzll(x) ^ 0x3f;
#else
const uint32_t H = uint32_t(x >> 32);
if (H) return Tag<false>::bsr(H) + 32;
const uint32_t L = uint32_t(x);
return Tag<false>::bsr(L);
#endif
}
};
} // bit_op_local
template<class T>
int bsf(T x)
{
return bit_op_local::Tag<sizeof(T) == 8>::bsf(x);
}
template<class T>
int bsr(T x)
{
return bit_op_local::Tag<sizeof(T) == 8>::bsr(x);
}
template<class T>
uint64_t makeBitMask64(T x)
{
assert(x < 64);
return (uint64_t(1) << x) - 1;
}
template<class T>
uint32_t popcnt(T x);
template<>
inline uint32_t popcnt<uint32_t>(uint32_t x)
{
#if defined(_MSC_VER)
return static_cast<uint32_t>(_mm_popcnt_u32(x));
#else
return static_cast<uint32_t>(__builtin_popcount(x));
#endif
}
template<>
inline uint32_t popcnt<uint64_t>(uint64_t x)
{
#if defined(__x86_64__)
return static_cast<uint32_t>(__builtin_popcountll(x));
#elif defined(_WIN64)
return static_cast<uint32_t>(_mm_popcnt_u64(x));
#else
return popcnt<uint32_t>(static_cast<uint32_t>(x)) + popcnt<uint32_t>(static_cast<uint32_t>(x >> 32));
#endif
}
} // cybozu
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2016 CNRS
// Authors: Joseph Mirabel from Florent Lamiraux
//
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_GRIPPER_HH
# define HPP_PINOCCHIO_GRIPPER_HH
# include <hpp/model/fwd.hh>
# include <hpp/model/joint.hh>
namespace hpp {
namespace model {
/// Definition of a robot gripper
///
/// This class represent a robot gripper as a frame attached to the joint
/// of the robot that holds the gripper.
///
/// \image html figures/figure-gripper.png
///
/// To graps a box-shaped object with small lengths along x and y, the
/// gripper frame should coincide with the object frame.
class HPP_MODEL_DLLAPI Gripper
{
public:
/// Return a shared pointer to new instance
/// \param joint joint of the robot that will hold handles,
/// \param objectPositionInJoint object position in the the grasping
/// joint.
static GripperPtr_t create (const std::string& name,
const DevicePtr_t& device);
{
Gripper* ptr = new Gripper (name, device);
GripperPtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
/// Get joint that grip
const JointPtr_t& joint () const
{
return joint_;
}
/// Get handle position in the the Grippering joint
const Transform3f& objectPositionInJoint () const
{
return device_->model()->getFramePlacement(fid_);
}
///get name
const std::string& name () const
{
return name_;
}
/// Get the clearance
///
/// The clearance is a distance, from the center of the gripper and along
/// the x-aixs, that "ensures" an object being at that distance is not
/// colliding with this gripper.
/// It also gives an order of magnitude of the size of the gripper.
value_type clearance () const
{
return clearance_;
}
/// Set the clearance
/// \sa clearance()
void clearance (const value_type& clearance)
{
clearance_ = clearance;
}
GripperPtr_t clone () const;
virtual std::ostream& print (std::ostream& os) const;
protected:
/// Constructor
/// \param name of the gripper in the device,
/// \param device
/// \todo device should be of type DeviceConstPtr_t but the constructor of
/// JointPtr_t needs a DevicePtr_t.
Gripper (const std::string& name, const DevicePtr_t& device) :
name_ (name),
device_ (device),
clearance_ (0)
{
fid_ = device->model()->getFrameId (name);
joint_ = JointPtr_t (
new Joint(device, device->model()->getFrameParent (fid)));
}
void init (GripperWkPtr_t weakPtr)
{
weakPtr_ = weakPtr;
}
private:
std::string name_;
DeviceConstPtr_t device_;
/// Joint of the robot that holds handles.
JointPtr_t joint_;
se3::FrameIndex fid_;
/// Clearance
value_type clearance_;
/// Weak pointer to itself
GripperWkPtr_t weakPtr_;
}; // class Gripper
std::ostream& operator<< (std::ostream& os, const Gripper& gripper);
} // namespace model
} // namespace hpp
#endif // HPP_PINOCCHIO_GRIPPER_HH
<commit_msg>Add Gripper::frameId<commit_after>//
// Copyright (c) 2016 CNRS
// Authors: Joseph Mirabel from Florent Lamiraux
//
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio 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
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_PINOCCHIO_GRIPPER_HH
# define HPP_PINOCCHIO_GRIPPER_HH
# include <hpp/model/fwd.hh>
# include <hpp/model/joint.hh>
namespace hpp {
namespace model {
/// Definition of a robot gripper
///
/// This class represent a robot gripper as a frame attached to the joint
/// of the robot that holds the gripper.
///
/// \image html figures/figure-gripper.png
///
/// To graps a box-shaped object with small lengths along x and y, the
/// gripper frame should coincide with the object frame.
class HPP_MODEL_DLLAPI Gripper
{
public:
/// Return a shared pointer to new instance
/// \param joint joint of the robot that will hold handles,
/// \param objectPositionInJoint object position in the the grasping
/// joint.
static GripperPtr_t create (const std::string& name,
const DevicePtr_t& device);
{
Gripper* ptr = new Gripper (name, device);
GripperPtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
/// Get joint to which the gripper is attached
const JointPtr_t& joint () const
{
return joint_;
}
/// Get the frame Id of the gripper in the vector of frame of the Model
const se3::FrameIndex& frameId () const
{
return fid_;
}
/// Get handle position in the the Grippering joint
const Transform3f& objectPositionInJoint () const
{
return device_->model()->getFramePlacement(fid_);
}
///get name
const std::string& name () const
{
return name_;
}
/// Get the clearance
///
/// The clearance is a distance, from the center of the gripper and along
/// the x-aixs, that "ensures" an object being at that distance is not
/// colliding with this gripper.
/// It also gives an order of magnitude of the size of the gripper.
value_type clearance () const
{
return clearance_;
}
/// Set the clearance
/// \sa clearance()
void clearance (const value_type& clearance)
{
clearance_ = clearance;
}
GripperPtr_t clone () const;
virtual std::ostream& print (std::ostream& os) const;
protected:
/// Constructor
/// \param name of the gripper in the device,
/// \param device
/// \todo device should be of type DeviceConstPtr_t but the constructor of
/// JointPtr_t needs a DevicePtr_t.
Gripper (const std::string& name, const DevicePtr_t& device) :
name_ (name),
device_ (device),
clearance_ (0)
{
fid_ = device->model()->getFrameId (name);
joint_ = JointPtr_t (
new Joint(device, device->model()->getFrameParent (fid)));
}
void init (GripperWkPtr_t weakPtr)
{
weakPtr_ = weakPtr;
}
private:
std::string name_;
DeviceConstPtr_t device_;
/// Joint of the robot that holds handles.
JointPtr_t joint_;
se3::FrameIndex fid_;
/// Clearance
value_type clearance_;
/// Weak pointer to itself
GripperWkPtr_t weakPtr_;
}; // class Gripper
std::ostream& operator<< (std::ostream& os, const Gripper& gripper);
} // namespace model
} // namespace hpp
#endif // HPP_PINOCCHIO_GRIPPER_HH
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_FILE_POOL_HPP
#define TORRENT_FILE_POOL_HPP
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/filesystem/path.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/file.hpp"
namespace libtorrent
{
using boost::multi_index::multi_index_container;
using boost::multi_index::ordered_non_unique;
using boost::multi_index::ordered_unique;
using boost::multi_index::indexed_by;
using boost::multi_index::member;
namespace pt = boost::posix_time;
namespace fs = boost::filesystem;
struct TORRENT_EXPORT file_pool : boost::noncopyable
{
file_pool(int size = 40): m_size(size) {}
boost::shared_ptr<file> open_file(void* st, fs::path const& p, file::open_mode m);
void release(void* st);
void resize(int size);
private:
int m_size;
struct lru_file_entry
{
lru_file_entry(boost::shared_ptr<file> const& f)
: file_ptr(f)
, last_use(pt::second_clock::universal_time()) {}
mutable boost::shared_ptr<file> file_ptr;
fs::path file_path;
void* key;
pt::ptime last_use;
file::open_mode mode;
};
typedef multi_index_container<
lru_file_entry, indexed_by<
ordered_unique<member<lru_file_entry, fs::path
, &lru_file_entry::file_path> >
, ordered_non_unique<member<lru_file_entry, pt::ptime
, &lru_file_entry::last_use> >
, ordered_non_unique<member<lru_file_entry, void*
, &lru_file_entry::key> >
>
> file_set;
file_set m_files;
};
}
#endif<commit_msg>added missing newline at the end of file<commit_after>/*
Copyright (c) 2006, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_FILE_POOL_HPP
#define TORRENT_FILE_POOL_HPP
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/filesystem/path.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/file.hpp"
namespace libtorrent
{
using boost::multi_index::multi_index_container;
using boost::multi_index::ordered_non_unique;
using boost::multi_index::ordered_unique;
using boost::multi_index::indexed_by;
using boost::multi_index::member;
namespace pt = boost::posix_time;
namespace fs = boost::filesystem;
struct TORRENT_EXPORT file_pool : boost::noncopyable
{
file_pool(int size = 40): m_size(size) {}
boost::shared_ptr<file> open_file(void* st, fs::path const& p, file::open_mode m);
void release(void* st);
void resize(int size);
private:
int m_size;
struct lru_file_entry
{
lru_file_entry(boost::shared_ptr<file> const& f)
: file_ptr(f)
, last_use(pt::second_clock::universal_time()) {}
mutable boost::shared_ptr<file> file_ptr;
fs::path file_path;
void* key;
pt::ptime last_use;
file::open_mode mode;
};
typedef multi_index_container<
lru_file_entry, indexed_by<
ordered_unique<member<lru_file_entry, fs::path
, &lru_file_entry::file_path> >
, ordered_non_unique<member<lru_file_entry, pt::ptime
, &lru_file_entry::last_use> >
, ordered_non_unique<member<lru_file_entry, void*
, &lru_file_entry::key> >
>
> file_set;
file_set m_files;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED
#define TORRENT_SOCKET_IO_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/lazy_entry.hpp"
#include <string>
namespace libtorrent
{
TORRENT_EXPORT std::string print_address(address const& addr);
TORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);
TORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);
namespace detail
{
template<class OutIt>
void write_address(address const& a, OutIt& out)
{
#if TORRENT_USE_IPV6
if (a.is_v4())
{
#endif
write_uint32(a.to_v4().to_ulong(), out);
#if TORRENT_USE_IPV6
}
else if (a.is_v6())
{
address_v6::bytes_type bytes
= a.to_v6().to_bytes();
std::copy(bytes.begin(), bytes.end(), out);
}
#endif
}
template<class InIt>
address read_v4_address(InIt& in)
{
unsigned long ip = read_uint32(in);
return address_v4(ip);
}
#if TORRENT_USE_IPV6
template<class InIt>
address read_v6_address(InIt& in)
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes;
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
*i = read_uint8(in);
return address_v6(bytes);
}
#endif
template<class Endpoint, class OutIt>
void write_endpoint(Endpoint const& e, OutIt& out)
{
write_address(e.address(), out);
write_uint16(e.port(), out);
}
template<class Endpoint, class InIt>
Endpoint read_v4_endpoint(InIt& in)
{
address addr = read_v4_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#if TORRENT_USE_IPV6
template<class Endpoint, class InIt>
Endpoint read_v6_endpoint(InIt& in)
{
address addr = read_v6_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#endif
template <class EndpointType>
void read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)
{
using namespace libtorrent;
if (n->type() != lazy_entry::list_t) return;
for (int i = 0; i < n->list_size(); ++i)
{
lazy_entry const* e = n->list_at(i);
if (e->type() != lazy_entry::string_t) return;
if (e->string_length() < 6) continue;
char const* in = e->string_ptr();
if (e->string_length() == 6)
epl.push_back(read_v4_endpoint<EndpointType>(in));
#if TORRENT_USE_IPV6
else if (e->string_length() == 18)
epl.push_back(read_v6_endpoint<EndpointType>(in));
#endif
}
}
}
}
#endif
<commit_msg>fixed bug in write_address<commit_after>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED
#define TORRENT_SOCKET_IO_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/lazy_entry.hpp"
#include <string>
namespace libtorrent
{
TORRENT_EXPORT std::string print_address(address const& addr);
TORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);
TORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);
namespace detail
{
template<class OutIt>
void write_address(address const& a, OutIt& out)
{
#if TORRENT_USE_IPV6
if (a.is_v4())
{
#endif
write_uint32(a.to_v4().to_ulong(), out);
#if TORRENT_USE_IPV6
}
else if (a.is_v6())
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes = a.to_v6().to_bytes();
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
write_uint8(*i, out);
}
#endif
}
template<class InIt>
address read_v4_address(InIt& in)
{
unsigned long ip = read_uint32(in);
return address_v4(ip);
}
#if TORRENT_USE_IPV6
template<class InIt>
address read_v6_address(InIt& in)
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes;
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
*i = read_uint8(in);
return address_v6(bytes);
}
#endif
template<class Endpoint, class OutIt>
void write_endpoint(Endpoint const& e, OutIt& out)
{
write_address(e.address(), out);
write_uint16(e.port(), out);
}
template<class Endpoint, class InIt>
Endpoint read_v4_endpoint(InIt& in)
{
address addr = read_v4_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#if TORRENT_USE_IPV6
template<class Endpoint, class InIt>
Endpoint read_v6_endpoint(InIt& in)
{
address addr = read_v6_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#endif
template <class EndpointType>
void read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)
{
using namespace libtorrent;
if (n->type() != lazy_entry::list_t) return;
for (int i = 0; i < n->list_size(); ++i)
{
lazy_entry const* e = n->list_at(i);
if (e->type() != lazy_entry::string_t) return;
if (e->string_length() < 6) continue;
char const* in = e->string_ptr();
if (e->string_length() == 6)
epl.push_back(read_v4_endpoint<EndpointType>(in));
#if TORRENT_USE_IPV6
else if (e->string_length() == 18)
epl.push_back(read_v6_endpoint<EndpointType>(in));
#endif
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED
#define TORRENT_SOCKET_IO_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/lazy_entry.hpp"
#include <string>
namespace libtorrent
{
TORRENT_EXPORT std::string print_address(address const& addr);
TORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);
TORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);
namespace detail
{
template<class OutIt>
void write_address(address const& a, OutIt& out)
{
#if TORRENT_USE_IPV6
if (a.is_v4())
{
#endif
write_uint32(a.to_v4().to_ulong(), out);
#if TORRENT_USE_IPV6
}
else if (a.is_v6())
{
address_v6::bytes_type bytes
= a.to_v6().to_bytes();
std::copy(bytes.begin(), bytes.end(), out);
}
#endif
}
template<class InIt>
address read_v4_address(InIt& in)
{
unsigned long ip = read_uint32(in);
return address_v4(ip);
}
#if TORRENT_USE_IPV6
template<class InIt>
address read_v6_address(InIt& in)
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes;
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
*i = read_uint8(in);
return address_v6(bytes);
}
#endif
template<class Endpoint, class OutIt>
void write_endpoint(Endpoint const& e, OutIt& out)
{
write_address(e.address(), out);
write_uint16(e.port(), out);
}
template<class Endpoint, class InIt>
Endpoint read_v4_endpoint(InIt& in)
{
address addr = read_v4_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#if TORRENT_USE_IPV6
template<class Endpoint, class InIt>
Endpoint read_v6_endpoint(InIt& in)
{
address addr = read_v6_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#endif
template <class EndpointType>
void read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)
{
using namespace libtorrent;
if (n->type() != lazy_entry::list_t) return;
for (int i = 0; i < n->list_size(); ++i)
{
lazy_entry const* e = n->list_at(i);
if (e->type() != lazy_entry::string_t) return;
if (e->string_length() < 6) continue;
char const* in = e->string_ptr();
if (e->string_length() == 6)
epl.push_back(read_v4_endpoint<EndpointType>(in));
#if TORRENT_USE_IPV6
else if (e->string_length() == 18)
epl.push_back(read_v6_endpoint<EndpointType>(in));
#endif
}
}
}
}
#endif
<commit_msg>fixed bug in write_address<commit_after>/*
Copyright (c) 2009, Arvid Norberg
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 author 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.
*/
#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED
#define TORRENT_SOCKET_IO_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/lazy_entry.hpp"
#include <string>
namespace libtorrent
{
TORRENT_EXPORT std::string print_address(address const& addr);
TORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);
TORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);
namespace detail
{
template<class OutIt>
void write_address(address const& a, OutIt& out)
{
#if TORRENT_USE_IPV6
if (a.is_v4())
{
#endif
write_uint32(a.to_v4().to_ulong(), out);
#if TORRENT_USE_IPV6
}
else if (a.is_v6())
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes = a.to_v6().to_bytes();
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
write_uint8(*i, out);
}
#endif
}
template<class InIt>
address read_v4_address(InIt& in)
{
unsigned long ip = read_uint32(in);
return address_v4(ip);
}
#if TORRENT_USE_IPV6
template<class InIt>
address read_v6_address(InIt& in)
{
typedef address_v6::bytes_type bytes_t;
bytes_t bytes;
for (bytes_t::iterator i = bytes.begin()
, end(bytes.end()); i != end; ++i)
*i = read_uint8(in);
return address_v6(bytes);
}
#endif
template<class Endpoint, class OutIt>
void write_endpoint(Endpoint const& e, OutIt& out)
{
write_address(e.address(), out);
write_uint16(e.port(), out);
}
template<class Endpoint, class InIt>
Endpoint read_v4_endpoint(InIt& in)
{
address addr = read_v4_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#if TORRENT_USE_IPV6
template<class Endpoint, class InIt>
Endpoint read_v6_endpoint(InIt& in)
{
address addr = read_v6_address(in);
int port = read_uint16(in);
return Endpoint(addr, port);
}
#endif
template <class EndpointType>
void read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)
{
using namespace libtorrent;
if (n->type() != lazy_entry::list_t) return;
for (int i = 0; i < n->list_size(); ++i)
{
lazy_entry const* e = n->list_at(i);
if (e->type() != lazy_entry::string_t) return;
if (e->string_length() < 6) continue;
char const* in = e->string_ptr();
if (e->string_length() == 6)
epl.push_back(read_v4_endpoint<EndpointType>(in));
#if TORRENT_USE_IPV6
else if (e->string_length() == 18)
epl.push_back(read_v6_endpoint<EndpointType>(in));
#endif
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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
*
*****************************************************************************/
#ifndef MAPNIK_TEXT_RENDERER_HPP
#define MAPNIK_TEXT_RENDERER_HPP
// mapnik
#include <mapnik/text/placement_finder.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/symbolizer_enumerations.hpp>
#include <mapnik/util/noncopyable.hpp>
// agg
#include <agg_trans_affine.h>
// freetype2
extern "C"
{
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_STROKER_H
}
namespace mapnik
{
struct glyph_t
{
FT_Glyph image;
detail::evaluated_format_properties const& properties;
glyph_t(FT_Glyph image_, detail::evaluated_format_properties const& properties_)
: image(image_), properties(properties_) {}
};
class text_renderer : private util::noncopyable
{
public:
text_renderer (halo_rasterizer_e rasterizer,
composite_mode_e comp_op = src_over,
composite_mode_e halo_comp_op = src_over,
double scale_factor=1.0,
stroker_ptr stroker=stroker_ptr());
void set_transform(agg::trans_affine const& transform);
void set_halo_transform(agg::trans_affine const& halo_transform);
protected:
using glyph_vector = std::vector<glyph_t>;
void prepare_glyphs(glyph_positions const& positions);
halo_rasterizer_e rasterizer_;
composite_mode_e comp_op_;
composite_mode_e halo_comp_op_;
double scale_factor_;
glyph_vector glyphs_;
stroker_ptr stroker_;
agg::trans_affine transform_;
agg::trans_affine halo_transform_;
};
template <typename T>
class agg_text_renderer : public text_renderer
{
public:
using pixmap_type = T;
agg_text_renderer (pixmap_type & pixmap, halo_rasterizer_e rasterizer,
composite_mode_e comp_op = src_over,
composite_mode_e halo_comp_op = src_over,
double scale_factor = 1.0,
stroker_ptr stroker = stroker_ptr());
void render(glyph_positions const& positions);
private:
pixmap_type & pixmap_;
void render_halo(FT_Bitmap_ *bitmap, unsigned rgba, int x, int y,
double halo_radius, double opacity,
composite_mode_e comp_op);
};
template <typename T>
class grid_text_renderer : public text_renderer
{
public:
using pixmap_type = T;
grid_text_renderer (pixmap_type & pixmap,
composite_mode_e comp_op = src_over,
double scale_factor = 1.0);
void render(glyph_positions const& positions, value_integer feature_id);
private:
pixmap_type & pixmap_;
void render_halo_id(FT_Bitmap_ *bitmap, mapnik::value_integer feature_id, int x, int y, int halo_radius);
};
}
#endif // RENDERER_HPP
<commit_msg>formattin<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 Artem Pavlenko
*
* 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
*
*****************************************************************************/
#ifndef MAPNIK_TEXT_RENDERER_HPP
#define MAPNIK_TEXT_RENDERER_HPP
// mapnik
#include <mapnik/text/placement_finder.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/symbolizer_enumerations.hpp>
#include <mapnik/util/noncopyable.hpp>
// agg
#include <agg_trans_affine.h>
// freetype2
extern "C"
{
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_STROKER_H
}
namespace mapnik
{
struct glyph_t
{
FT_Glyph image;
detail::evaluated_format_properties const& properties;
glyph_t(FT_Glyph image_, detail::evaluated_format_properties const& properties_)
: image(image_), properties(properties_) {}
};
class text_renderer : private util::noncopyable
{
public:
text_renderer (halo_rasterizer_e rasterizer,
composite_mode_e comp_op = src_over,
composite_mode_e halo_comp_op = src_over,
double scale_factor = 1.0,
stroker_ptr stroker = stroker_ptr());
void set_transform(agg::trans_affine const& transform);
void set_halo_transform(agg::trans_affine const& halo_transform);
protected:
using glyph_vector = std::vector<glyph_t>;
void prepare_glyphs(glyph_positions const& positions);
halo_rasterizer_e rasterizer_;
composite_mode_e comp_op_;
composite_mode_e halo_comp_op_;
double scale_factor_;
glyph_vector glyphs_;
stroker_ptr stroker_;
agg::trans_affine transform_;
agg::trans_affine halo_transform_;
};
template <typename T>
class agg_text_renderer : public text_renderer
{
public:
using pixmap_type = T;
agg_text_renderer (pixmap_type & pixmap, halo_rasterizer_e rasterizer,
composite_mode_e comp_op = src_over,
composite_mode_e halo_comp_op = src_over,
double scale_factor = 1.0,
stroker_ptr stroker = stroker_ptr());
void render(glyph_positions const& positions);
private:
pixmap_type & pixmap_;
void render_halo(FT_Bitmap_ *bitmap, unsigned rgba, int x, int y,
double halo_radius, double opacity,
composite_mode_e comp_op);
};
template <typename T>
class grid_text_renderer : public text_renderer
{
public:
using pixmap_type = T;
grid_text_renderer (pixmap_type & pixmap,
composite_mode_e comp_op = src_over,
double scale_factor = 1.0);
void render(glyph_positions const& positions, value_integer feature_id);
private:
pixmap_type & pixmap_;
void render_halo_id(FT_Bitmap_ *bitmap, mapnik::value_integer feature_id, int x, int y, int halo_radius);
};
}
#endif // RENDERER_HPP
<|endoftext|>
|
<commit_before>#ifndef VSMC_SMP_BACKEND_STD_HPP
#define VSMC_SMP_BACKEND_STD_HPP
#include <vsmc/smp/base.hpp>
#include <vsmc/utility/stdtbb.hpp>
#include <vsmc/utility/tbb_op.hpp>
namespace vsmc {
/// \brief Particle::weight_set_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename BaseState>
class WeightSetSTD : public traits::WeightSetTypeTrait<BaseState>::type
{
typedef typename traits::WeightSetTypeTrait<BaseState>::type base;
public :
typedef typename traits::SizeTypeTrait<base>::type size_type;
explicit WeightSetSTD (size_type N) : base(N) {}
private :
void log_weight2weight ()
{
const size_type N = static_cast<size_type>(this->size());
parallel_for(BlockedRange<size_type>(0, N), tbb_op::exp<double>(
this->log_weight_ptr(), this->weight_ptr()));
}
void weight2log_weight ()
{
const size_type N = static_cast<size_type>(this->size());
parallel_for(BlockedRange<size_type>(0, N), tbb_op::log<double>(
this->weight_ptr(), this->log_weight_ptr()));
}
}; // class WeightSetSTD
/// \brief Particle::value_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename BaseState>
class StateSTD : public BaseState
{
public :
typedef typename traits::SizeTypeTrait<BaseState>::type size_type;
explicit StateSTD (size_type N) : BaseState(N) {}
template <typename IntType>
void copy (size_type N, const IntType *copy_from)
{
VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(STD);
parallel_for(BlockedRange<size_type>(0, N),
copy_work_<IntType>(this, copy_from));
}
private :
template <typename IntType>
class copy_work_
{
public :
copy_work_ (StateSTD<BaseState> *state, const IntType *copy_from) :
state_(state), copy_from_(copy_from) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type to = range.begin(); to != range.end(); ++to)
state_->copy_particle(copy_from_[to], to);
}
private :
StateSTD<BaseState> *const state_;
const IntType *const copy_from_;
}; // class copy_work_
}; // class StateSTD
/// \brief Sampler<T>::init_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class InitializeSTD : public InitializeBase<T, Derived>
{
public :
std::size_t operator() (Particle<T> &particle, void *param)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->initialize_param(particle, param);
this->pre_processor(particle);
std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),
work_(this, &particle), static_cast<std::size_t>(0));
this->post_processor(particle);
return accept;
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Initialize)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (InitializeSTD<T, Derived> *init,
Particle<T> *particle) :
init_(init), particle_(particle) {}
void operator() (const BlockedRange<size_type> &range,
std::size_t &accept) const
{
std::size_t acc = 0;
for (size_type i = range.begin(); i != range.end(); ++i) {
Particle<T> *const part = particle_;
acc += init_->initialize_state(SingleParticle<T>(i, part));
}
accept = acc;
}
private :
InitializeSTD<T, Derived> *const init_;
Particle<T> *const particle_;
}; // class work_
}; // class InitializeSTD
/// \brief Sampler<T>::move_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class MoveSTD : public MoveBase<T, Derived>
{
public :
std::size_t operator() (std::size_t iter, Particle<T> &particle)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),
work_(this, iter, &particle), static_cast<std::size_t>(0));
this->post_processor(iter, particle);
return accept;
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Move)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (MoveSTD<T, Derived> *move, std::size_t iter,
Particle<T> *particle):
move_(move), iter_(iter), particle_(particle) {}
void operator() (const BlockedRange<size_type> &range,
std::size_t &accept) const
{
std::size_t acc = 0;
for (size_type i = range.begin(); i != range.end(); ++i) {
Particle<T> *const part = particle_;
acc += move_->move_state(iter_, SingleParticle<T>(i, part));
}
accept = acc;
}
private :
MoveSTD<T, Derived> *const move_;
const std::size_t iter_;
Particle<T> *const particle_;
}; // class work_
}; // class MoveSTD
/// \brief Monitor<T>::eval_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class MonitorEvalSTD : public MonitorEvalBase<T, Derived>
{
public :
void operator() (std::size_t iter, std::size_t dim,
const Particle<T> &particle, double *res)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
parallel_for(BlockedRange<size_type>(0, N),
work_(this, iter, dim, &particle, res));
this->post_processor(iter, particle);
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, MonitorEval)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (MonitorEvalSTD<T, Derived> *monitor,
std::size_t iter, std::size_t dim,
const Particle<T> *particle, double *res) :
monitor_(monitor), iter_(iter), dim_(dim), particle_(particle),
res_(res) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
double *const r = res_ + i * dim_;
const Particle<T> *const part = particle_;
monitor_->monitor_state(iter_, dim_,
ConstSingleParticle<T>(i, part), r);
}
}
private :
MonitorEvalSTD<T, Derived> *const monitor_;
const std::size_t iter_;
const std::size_t dim_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // class MonitorEvalSTD
/// \brief Path<T>::eval_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class PathEvalSTD : public PathEvalBase<T, Derived>
{
public :
double operator() (std::size_t iter, const Particle<T> &particle,
double *res)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
parallel_for(BlockedRange<size_type>(0, N),
work_(this, iter, &particle, res));
this->post_processor(iter, particle);
return this->path_grid(iter, particle);
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, PathEval)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (PathEvalSTD<T, Derived> *path, std::size_t iter,
const Particle<T> *particle, double *res) :
path_(path), iter_(iter), particle_(particle), res_(res) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
const Particle<T> *const part = particle_;
res_[i] = path_->path_state(iter_,
ConstSingleParticle<T>(i, part));
}
}
private :
PathEvalSTD<T, Derived> *const path_;
const std::size_t iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // PathEvalSTD
} // namespace vsmc
#endif // VSMC_SMP_BACKEND_STD_HPP
<commit_msg>stdtbb backend normalize weights parallelized<commit_after>#ifndef VSMC_SMP_BACKEND_STD_HPP
#define VSMC_SMP_BACKEND_STD_HPP
#include <vsmc/smp/base.hpp>
#include <vsmc/utility/stdtbb.hpp>
#include <vsmc/utility/tbb_op.hpp>
namespace vsmc {
/// \brief Particle::weight_set_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename BaseState>
class WeightSetSTD : public traits::WeightSetTypeTrait<BaseState>::type
{
typedef typename traits::WeightSetTypeTrait<BaseState>::type base;
public :
typedef typename traits::SizeTypeTrait<base>::type size_type;
explicit WeightSetSTD (size_type N) : base(N) {}
private :
void log_weight2weight ()
{
const size_type N = static_cast<size_type>(this->size());
parallel_for(BlockedRange<size_type>(0, N), tbb_op::exp<double>(
this->log_weight_ptr(), this->weight_ptr()));
}
void weight2log_weight ()
{
const size_type N = static_cast<size_type>(this->size());
parallel_for(BlockedRange<size_type>(0, N), tbb_op::log<double>(
this->weight_ptr(), this->log_weight_ptr()));
}
void normalize_log_weight ()
{
const size_type N = static_cast<size_type>(this->size());
tbb_op::maximum<double> max_weight(this->log_weight_ptr());
parallel_reduce(BlockedRange<size_type>(0, N), max_weight);
parallel_for(BlockedRange<size_type>(0, N), tbb_op::minus<double>(
this->log_weight_ptr(), this->log_weight_ptr(),
max_weight.result()));
}
void normalize_weight ()
{
const size_type N = static_cast<size_type>(this->size());
tbb_op::summation<double> coeff(this->weight_ptr());
parallel_reduce(BlockedRange<size_type>(0, N), coeff);
parallel_for(BlockedRange<size_type>(0, N),
tbb_op::multiplies<double>(
this->weight_ptr(), this->weight_ptr(),
1 / coeff.result()));
tbb_op::square_sum<double> ess(this->weight_ptr());
parallel_reduce(BlockedRange<size_type>(0, this->size()), ess);
this->set_ess(1 / ess.result());
}
}; // class WeightSetSTD
/// \brief Particle::value_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename BaseState>
class StateSTD : public BaseState
{
public :
typedef typename traits::SizeTypeTrait<BaseState>::type size_type;
explicit StateSTD (size_type N) : BaseState(N) {}
template <typename IntType>
void copy (size_type N, const IntType *copy_from)
{
VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(STD);
parallel_for(BlockedRange<size_type>(0, N),
copy_work_<IntType>(this, copy_from));
}
private :
template <typename IntType>
class copy_work_
{
public :
copy_work_ (StateSTD<BaseState> *state, const IntType *copy_from) :
state_(state), copy_from_(copy_from) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type to = range.begin(); to != range.end(); ++to)
state_->copy_particle(copy_from_[to], to);
}
private :
StateSTD<BaseState> *const state_;
const IntType *const copy_from_;
}; // class copy_work_
}; // class StateSTD
/// \brief Sampler<T>::init_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class InitializeSTD : public InitializeBase<T, Derived>
{
public :
std::size_t operator() (Particle<T> &particle, void *param)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->initialize_param(particle, param);
this->pre_processor(particle);
std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),
work_(this, &particle), static_cast<std::size_t>(0));
this->post_processor(particle);
return accept;
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Initialize)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (InitializeSTD<T, Derived> *init,
Particle<T> *particle) :
init_(init), particle_(particle) {}
void operator() (const BlockedRange<size_type> &range,
std::size_t &accept) const
{
std::size_t acc = 0;
for (size_type i = range.begin(); i != range.end(); ++i) {
Particle<T> *const part = particle_;
acc += init_->initialize_state(SingleParticle<T>(i, part));
}
accept = acc;
}
private :
InitializeSTD<T, Derived> *const init_;
Particle<T> *const particle_;
}; // class work_
}; // class InitializeSTD
/// \brief Sampler<T>::move_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class MoveSTD : public MoveBase<T, Derived>
{
public :
std::size_t operator() (std::size_t iter, Particle<T> &particle)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),
work_(this, iter, &particle), static_cast<std::size_t>(0));
this->post_processor(iter, particle);
return accept;
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Move)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (MoveSTD<T, Derived> *move, std::size_t iter,
Particle<T> *particle):
move_(move), iter_(iter), particle_(particle) {}
void operator() (const BlockedRange<size_type> &range,
std::size_t &accept) const
{
std::size_t acc = 0;
for (size_type i = range.begin(); i != range.end(); ++i) {
Particle<T> *const part = particle_;
acc += move_->move_state(iter_, SingleParticle<T>(i, part));
}
accept = acc;
}
private :
MoveSTD<T, Derived> *const move_;
const std::size_t iter_;
Particle<T> *const particle_;
}; // class work_
}; // class MoveSTD
/// \brief Monitor<T>::eval_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class MonitorEvalSTD : public MonitorEvalBase<T, Derived>
{
public :
void operator() (std::size_t iter, std::size_t dim,
const Particle<T> &particle, double *res)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
parallel_for(BlockedRange<size_type>(0, N),
work_(this, iter, dim, &particle, res));
this->post_processor(iter, particle);
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, MonitorEval)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (MonitorEvalSTD<T, Derived> *monitor,
std::size_t iter, std::size_t dim,
const Particle<T> *particle, double *res) :
monitor_(monitor), iter_(iter), dim_(dim), particle_(particle),
res_(res) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
double *const r = res_ + i * dim_;
const Particle<T> *const part = particle_;
monitor_->monitor_state(iter_, dim_,
ConstSingleParticle<T>(i, part), r);
}
}
private :
MonitorEvalSTD<T, Derived> *const monitor_;
const std::size_t iter_;
const std::size_t dim_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // class MonitorEvalSTD
/// \brief Path<T>::eval_type subtype using C++11 concurrency
/// \ingroup SMP
template <typename T, typename Derived>
class PathEvalSTD : public PathEvalBase<T, Derived>
{
public :
double operator() (std::size_t iter, const Particle<T> &particle,
double *res)
{
typedef typename Particle<T>::size_type size_type;
const size_type N = static_cast<size_type>(particle.size());
this->pre_processor(iter, particle);
parallel_for(BlockedRange<size_type>(0, N),
work_(this, iter, &particle, res));
this->post_processor(iter, particle);
return this->path_grid(iter, particle);
}
protected :
VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, PathEval)
private :
class work_
{
public :
typedef typename Particle<T>::size_type size_type;
work_ (PathEvalSTD<T, Derived> *path, std::size_t iter,
const Particle<T> *particle, double *res) :
path_(path), iter_(iter), particle_(particle), res_(res) {}
void operator() (const BlockedRange<size_type> &range) const
{
for (size_type i = range.begin(); i != range.end(); ++i) {
const Particle<T> *const part = particle_;
res_[i] = path_->path_state(iter_,
ConstSingleParticle<T>(i, part));
}
}
private :
PathEvalSTD<T, Derived> *const path_;
const std::size_t iter_;
const Particle<T> *const particle_;
double *const res_;
}; // class work_
}; // PathEvalSTD
} // namespace vsmc
#endif // VSMC_SMP_BACKEND_STD_HPP
<|endoftext|>
|
<commit_before>#ifndef VSMC_SMP_STATE_TUPLE_HPP
#define VSMC_SMP_STATE_TUPLE_HPP
#include <vsmc/smp/base.hpp>
#include <vsmc/core/single_particle.hpp>
#include <vsmc/utility/tuple_manip.hpp>
namespace vsmc {
/// \brief Base type of StateTuple
/// \ingroup SMP
template <MatrixOrder Order, typename T, typename... Types>
class StateTupleBase
{
public :
typedef std::size_t size_type;
typedef std::tuple<T, Types...> state_tuple_type;
template <std::size_t Pos> struct state_type
{typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};
class state_pack_type
{
public :
state_pack_type () {}
state_pack_type (const state_tuple_type &data) : data_(data) {}
operator state_tuple_type () {return data_;}
template <std::size_t Pos>
typename state_type<Pos>::type &get ()
{return std::get<Pos>(data_);}
template <std::size_t Pos>
const typename state_type<Pos>::type &get () const
{return std::get<Pos>(data_);}
template <typename Archive>
void serialize (Archive &ar, const unsigned)
{serialize(ar, Position<0>());}
template <typename Archive>
void serialize (Archive &ar, const unsigned) const
{serialize(ar, Position<0>());}
private :
state_tuple_type data_;
static const std::size_t dim_ = sizeof...(Types) + 1;
template <typename Archive, std::size_t Pos>
void serialize (Archive &ar, Position<Pos>)
{
ar & std::get<Pos>(data_);
serialize(ar, Position<Pos + 1>());
}
template <typename Archive>
void serialize (Archive &ar, Position<dim_>) {}
template <typename Archive, std::size_t Pos>
void serialize (Archive &ar, Position<Pos>) const
{
ar & std::get<Pos>(data_);
serialize(ar, Position<Pos + 1>());
}
template <typename Archive>
void serialize (Archive &ar, Position<dim_>) const {}
};
template <typename S>
struct single_particle_type : public SingleParticleBase<S>
{
single_particle_type (typename Particle<S>::size_type id,
Particle<S> *particle_ptr) :
SingleParticleBase<S>(id, particle_ptr) {}
static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}
template <std::size_t Pos>
typename state_type<Pos>::type &state (Position<Pos>) const
{
return this->mutable_particle_ptr()->value().
state(this->id(), Position<Pos>());
}
template <std::size_t Pos>
typename state_type<Pos>::type &state () const
{return this->state(Position<Pos>());}
};
template <typename S>
struct const_single_particle_type : public ConstSingleParticleBase<S>
{
const_single_particle_type (typename Particle<S>::size_type id,
const Particle<S> *particle_ptr) :
ConstSingleParticleBase<S>(id, particle_ptr) {}
static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}
template <std::size_t Pos>
const typename state_type<Pos>::type &state (Position<Pos>) const
{
return this->particle_ptr()->value().
state(this->id(), Position<Pos>());
}
template <std::size_t Pos>
const typename state_type<Pos>::type &state () const
{return this->state(Position<Pos>());}
};
size_type size () const {return size_;}
static VSMC_CONSTEXPR std::size_t dim () {return dim_;}
state_pack_type state_pack (size_type id) const
{
state_pack_type pack;
pack_particle(id, pack, Position<0>());
return pack;
}
void state_unpack (size_type id, const state_pack_type &pack)
{unpack_particle(id, pack, Position<0>());}
template <typename IntType>
void copy (size_type N, const IntType *copy_from)
{
VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(Tuple);
for (size_type to = 0; to != N; ++to)
copy_particle(copy_from[to], to);
}
template <std::size_t Pos, typename OutputIter>
OutputIter read_state (Position<Pos>, OutputIter first) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
for (size_type i = 0; i != size_; ++i, ++first)
*first = sptr->state(i, Position<Pos>());
return first;
}
template <std::size_t Pos, typename OutputIter>
OutputIter read_state (OutputIter first) const
{return read_state(Position<Pos>(), first);}
template <typename OutputStream>
OutputStream &print (OutputStream &os, std::size_t iter = 0,
char sepchar = ' ', char eolchar = '\n') const
{
for (size_type i = 0; i != size_; ++i) {
os << iter << sepchar;
print_particle(os, i, sepchar, eolchar, Position<0>());
}
return os;
}
protected :
explicit StateTupleBase (size_type N) : size_(N) {}
void copy_particle (size_type from, size_type to)
{
if (from != to)
copy_particle(from, to, Position<0>());
}
private :
size_type size_;
static const std::size_t dim_ = sizeof...(Types) + 1;
template <std::size_t Pos>
void pack_particle (size_type id, state_pack_type &pack,
Position<Pos>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
pack.template get<Pos>() = sptr->state(id, Position<Pos>());
pack_particle(id, pack, Position<Pos + 1>());
}
void pack_particle (size_type id, state_pack_type &pack,
Position<dim_>) const {}
template <std::size_t Pos>
void unpack_particle (size_type id, const state_pack_type &pack,
Position<Pos>)
{
StateTuple<Order, T, Types...> *sptr =
static_cast<StateTuple<Order, T, Types...> *>(this);
sptr->state(id, Position<Pos>()) = pack.template get<Pos>();
unpack_particle(id, pack, Position<Pos + 1>());
}
void unpack_particle (size_type id, const state_pack_type &pack,
Position<dim_>) {}
template <std::size_t Pos>
void copy_particle (size_type from, size_type to, Position<Pos>)
{
StateTuple<Order, T, Types...> *sptr =
static_cast<StateTuple<Order, T, Types...> *>(this);
sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());
copy_particle(from, to, Position<Pos + 1>());
}
void copy_particle (size_type from, size_type to, Position<dim_>) {}
template <typename OutputStream, std::size_t Pos>
void print_particle (OutputStream &os, size_type id,
char sepchar, char eolchar, Position<Pos>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
os << sptr->state(id, Position<Pos>()) << sepchar;
print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());
}
template <typename OutputStream>
void print_particle (OutputStream &os, size_type id,
char sepchar, char eolchar, Position<dim_ - 1>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
os << sptr->state(id, Position<dim_ - 1>()) << eolchar;
}
}; // class StateTupleBase
/// \brief Particle::value_type subtype
/// \ingroup SMP
template <typename T, typename... Types>
class StateTuple<RowMajor, T, Types...> :
public StateTupleBase<RowMajor, T, Types...>
{
public :
typedef StateTupleBase<RowMajor, T, Types...>
state_tuple_base_type;
typedef typename state_tuple_base_type::size_type size_type;
explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>)
{return std::get<Pos>(state_[id]);}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>) const
{return std::get<Pos>(state_[id]);}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id)
{return state(id, Position<Pos>());}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id) const
{return state(id, Position<Pos>());}
private :
std::vector<std::tuple<T, Types...> > state_;
}; // StateTuple
/// \brief Particle::value_type subtype
/// \ingroup SMP
template <typename T, typename... Types>
class StateTuple<ColMajor, T, Types...> :
public StateTupleBase<ColMajor, T, Types...>
{
public :
typedef StateTupleBase<ColMajor, T, Types...>
state_tuple_base_type;
typedef typename state_tuple_base_type::size_type size_type;
explicit StateTuple (size_type N) : state_tuple_base_type(N)
{init_state(N, Position<0>());}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>)
{return std::get<Pos>(state_)[id];}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>) const
{return std::get<Pos>(state_)[id];}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id)
{return state(id, Position<Pos>());}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id) const
{return state(id, Position<Pos>());}
private :
typename tuple::TupleApplyVector<std::tuple<T, Types...> >::type state_;
template <std::size_t Pos>
void init_state (size_type N, Position<Pos>)
{
std::get<Pos>(state_).resize(N);
init_state(N, Position<Pos + 1>());
}
void init_state (size_type N, Position<sizeof...(Types)>)
{std::get<sizeof...(Types)>(state_).resize(N);}
}; // class StateTuple
} // namespace vsmc
#endif // VSMC_SMP_STATE_TUPLE_HPP
<commit_msg>add move for StateTuple::state_pack_type<commit_after>#ifndef VSMC_SMP_STATE_TUPLE_HPP
#define VSMC_SMP_STATE_TUPLE_HPP
#include <vsmc/smp/base.hpp>
#include <vsmc/core/single_particle.hpp>
#include <vsmc/utility/tuple_manip.hpp>
namespace vsmc {
/// \brief Base type of StateTuple
/// \ingroup SMP
template <MatrixOrder Order, typename T, typename... Types>
class StateTupleBase
{
public :
typedef std::size_t size_type;
typedef std::tuple<T, Types...> state_tuple_type;
template <std::size_t Pos> struct state_type
{typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};
class state_pack_type
{
public :
state_pack_type () {}
state_pack_type (const state_pack_type &other) : data_(other.data_) {}
state_pack_type &operator= (const state_pack_type &other)
{
if (this != &other)
data_ = other.data_;
return *this;
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
state_pack_type (state_pack_type &&other) :
data_(cxx11::move(other.data_)) {}
state_pack_type &operator= (state_pack_type &&other)
{
if (this != &other)
data_ = cxx11::move(other.data_);
return *this;
}
#endif
state_pack_type (const state_tuple_type &data) : data_(data) {}
operator state_tuple_type () {return data_;}
template <std::size_t Pos>
typename state_type<Pos>::type &get ()
{return std::get<Pos>(data_);}
template <std::size_t Pos>
const typename state_type<Pos>::type &get () const
{return std::get<Pos>(data_);}
template <typename Archive>
void serialize (Archive &ar, const unsigned)
{serialize(ar, Position<0>());}
template <typename Archive>
void serialize (Archive &ar, const unsigned) const
{serialize(ar, Position<0>());}
private :
state_tuple_type data_;
static const std::size_t dim_ = sizeof...(Types) + 1;
template <typename Archive, std::size_t Pos>
void serialize (Archive &ar, Position<Pos>)
{
ar & std::get<Pos>(data_);
serialize(ar, Position<Pos + 1>());
}
template <typename Archive>
void serialize (Archive &ar, Position<dim_>) {}
template <typename Archive, std::size_t Pos>
void serialize (Archive &ar, Position<Pos>) const
{
ar & std::get<Pos>(data_);
serialize(ar, Position<Pos + 1>());
}
template <typename Archive>
void serialize (Archive &ar, Position<dim_>) const {}
};
template <typename S>
struct single_particle_type : public SingleParticleBase<S>
{
single_particle_type (typename Particle<S>::size_type id,
Particle<S> *particle_ptr) :
SingleParticleBase<S>(id, particle_ptr) {}
static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}
template <std::size_t Pos>
typename state_type<Pos>::type &state (Position<Pos>) const
{
return this->mutable_particle_ptr()->value().
state(this->id(), Position<Pos>());
}
template <std::size_t Pos>
typename state_type<Pos>::type &state () const
{return this->state(Position<Pos>());}
};
template <typename S>
struct const_single_particle_type : public ConstSingleParticleBase<S>
{
const_single_particle_type (typename Particle<S>::size_type id,
const Particle<S> *particle_ptr) :
ConstSingleParticleBase<S>(id, particle_ptr) {}
static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}
template <std::size_t Pos>
const typename state_type<Pos>::type &state (Position<Pos>) const
{
return this->particle_ptr()->value().
state(this->id(), Position<Pos>());
}
template <std::size_t Pos>
const typename state_type<Pos>::type &state () const
{return this->state(Position<Pos>());}
};
size_type size () const {return size_;}
static VSMC_CONSTEXPR std::size_t dim () {return dim_;}
state_pack_type state_pack (size_type id) const
{
state_pack_type pack;
pack_particle(id, pack, Position<0>());
return pack;
}
void state_unpack (size_type id, const state_pack_type &pack)
{unpack_particle(id, pack, Position<0>());}
template <typename IntType>
void copy (size_type N, const IntType *copy_from)
{
VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(Tuple);
for (size_type to = 0; to != N; ++to)
copy_particle(copy_from[to], to);
}
template <std::size_t Pos, typename OutputIter>
OutputIter read_state (Position<Pos>, OutputIter first) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
for (size_type i = 0; i != size_; ++i, ++first)
*first = sptr->state(i, Position<Pos>());
return first;
}
template <std::size_t Pos, typename OutputIter>
OutputIter read_state (OutputIter first) const
{return read_state(Position<Pos>(), first);}
template <typename OutputStream>
OutputStream &print (OutputStream &os, std::size_t iter = 0,
char sepchar = ' ', char eolchar = '\n') const
{
for (size_type i = 0; i != size_; ++i) {
os << iter << sepchar;
print_particle(os, i, sepchar, eolchar, Position<0>());
}
return os;
}
protected :
explicit StateTupleBase (size_type N) : size_(N) {}
void copy_particle (size_type from, size_type to)
{
if (from != to)
copy_particle(from, to, Position<0>());
}
private :
size_type size_;
static const std::size_t dim_ = sizeof...(Types) + 1;
template <std::size_t Pos>
void pack_particle (size_type id, state_pack_type &pack,
Position<Pos>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
pack.template get<Pos>() = sptr->state(id, Position<Pos>());
pack_particle(id, pack, Position<Pos + 1>());
}
void pack_particle (size_type id, state_pack_type &pack,
Position<dim_>) const {}
template <std::size_t Pos>
void unpack_particle (size_type id, const state_pack_type &pack,
Position<Pos>)
{
StateTuple<Order, T, Types...> *sptr =
static_cast<StateTuple<Order, T, Types...> *>(this);
sptr->state(id, Position<Pos>()) = pack.template get<Pos>();
unpack_particle(id, pack, Position<Pos + 1>());
}
void unpack_particle (size_type id, const state_pack_type &pack,
Position<dim_>) {}
template <std::size_t Pos>
void copy_particle (size_type from, size_type to, Position<Pos>)
{
StateTuple<Order, T, Types...> *sptr =
static_cast<StateTuple<Order, T, Types...> *>(this);
sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());
copy_particle(from, to, Position<Pos + 1>());
}
void copy_particle (size_type from, size_type to, Position<dim_>) {}
template <typename OutputStream, std::size_t Pos>
void print_particle (OutputStream &os, size_type id,
char sepchar, char eolchar, Position<Pos>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
os << sptr->state(id, Position<Pos>()) << sepchar;
print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());
}
template <typename OutputStream>
void print_particle (OutputStream &os, size_type id,
char sepchar, char eolchar, Position<dim_ - 1>) const
{
const StateTuple<Order, T, Types...> *sptr =
static_cast<const StateTuple<Order, T, Types...> *>(this);
os << sptr->state(id, Position<dim_ - 1>()) << eolchar;
}
}; // class StateTupleBase
/// \brief Particle::value_type subtype
/// \ingroup SMP
template <typename T, typename... Types>
class StateTuple<RowMajor, T, Types...> :
public StateTupleBase<RowMajor, T, Types...>
{
public :
typedef StateTupleBase<RowMajor, T, Types...>
state_tuple_base_type;
typedef typename state_tuple_base_type::size_type size_type;
explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>)
{return std::get<Pos>(state_[id]);}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>) const
{return std::get<Pos>(state_[id]);}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id)
{return state(id, Position<Pos>());}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id) const
{return state(id, Position<Pos>());}
private :
std::vector<std::tuple<T, Types...> > state_;
}; // StateTuple
/// \brief Particle::value_type subtype
/// \ingroup SMP
template <typename T, typename... Types>
class StateTuple<ColMajor, T, Types...> :
public StateTupleBase<ColMajor, T, Types...>
{
public :
typedef StateTupleBase<ColMajor, T, Types...>
state_tuple_base_type;
typedef typename state_tuple_base_type::size_type size_type;
explicit StateTuple (size_type N) : state_tuple_base_type(N)
{init_state(N, Position<0>());}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>)
{return std::get<Pos>(state_)[id];}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id, Position<Pos>) const
{return std::get<Pos>(state_)[id];}
template <std::size_t Pos>
typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id)
{return state(id, Position<Pos>());}
template <std::size_t Pos>
const typename state_tuple_base_type::template state_type<Pos>::type
&state (size_type id) const
{return state(id, Position<Pos>());}
private :
typename tuple::TupleApplyVector<std::tuple<T, Types...> >::type state_;
template <std::size_t Pos>
void init_state (size_type N, Position<Pos>)
{
std::get<Pos>(state_).resize(N);
init_state(N, Position<Pos + 1>());
}
void init_state (size_type N, Position<sizeof...(Types)>)
{std::get<sizeof...(Types)>(state_).resize(N);}
}; // class StateTuple
} // namespace vsmc
#endif // VSMC_SMP_STATE_TUPLE_HPP
<|endoftext|>
|
<commit_before>#pragma once
#include "zmsg_cmm.hpp"
namespace zmsg {
template<>
struct zmsg<mid_t::motor_test_start> {
public:
UINT32 FSPattern;
UINT32 FibreType;
UINT32 FibreAlignment;
BOOL XImageFocus;
BOOL YImageFocus;
UINT32 FibreShift;
BOOL DischargeStrengthAdjustment;
BOOL TensionSet;
FLOAT CutAngleLimit;
FLOAT LossLimit;
FLOAT FibreAngleLimit;
ULONG CleanDischargeTime;
ULONG FibreIntervalSetup;
LONG FSPosSetup;
UINT16 FibrePreFSStrength;
ULONG FibrePreFSTime;
ULONG FibreOverlapSetup;
UINT16 Discharge1Strength;
ULONG Discharge1Time;
UINT16 Discharge2Strength;
ULONG Discharge2LastTime;
ULONG Discharge2StartTime;
ULONG Discharge2StopTime;
ULONG ExtraManualDischargeTime;
BOOL ConeFS;
ULONG ConeFSWaitTime;
ULONG ConeFSSpeed;
ULONG ConeFSStretchLength;
UINT32 LossEstimationMode;
FLOAT LeftFibreMFD;
FLOAT RightFibreMFD;
FLOAT LeastLoss;
FLOAT RateOfSyntropyBending;
FLOAT RateOfReverseBending;
FLOAT RateOfMFDDeviation;
BOOL AutoStart;
BOOL Stop1;
BOOL Stop2;
/*data dispaly*/
BOOL CutAngle;
BOOL OffsetData;
/*omitted choice*/
BOOL Cut;
BOOL Loss;
BOOL FibreCoreAngle;
BOOL Bubble;
BOOL Thick;
BOOL Thin;
/*dischargesupplement*/
BOOL AirPressure;
BOOL Temperature;
/*fiber_image_display*/
UINT32 ImgGap;
UINT32 ImgStop1;
UINT32 ImgAlign;
UINT32 ImgStop2;
UINT32 ImgDischarge;
UINT32 ImgLossEstimation;
/*else*/
BOOL FibreAutoFeed;
BOOL BadCutSurface;
BOOL AutoAlignAfterStop;
ULONG ManualDischargeTimes;
/* motor test para */
UINT32 MotorTestTimes;
UINT32 ElectricArcTestTimes;
UINT32 CleanArcRate;
public:
ZMSG_PU(
FSPattern,
FibreType,
FibreAlignment,
XImageFocus,
YImageFocus,
FibreShift,
DischargeStrengthAdjustment,
TensionSet,
CutAngleLimit,
LossLimit,
FibreAngleLimit,
CleanDischargeTime,
FibreIntervalSetup,
FSPosSetup,
FibrePreFSStrength,
FibrePreFSTime,
FibreOverlapSetup,
Discharge1Strength,
Discharge1Time,
Discharge2Strength,
Discharge2LastTime,
Discharge2StartTime,
Discharge2StopTime,
ExtraManualDischargeTime,
ConeFS,
ConeFSWaitTime,
ConeFSSpeed,
ConeFSStretchLength,
LossEstimationMode,
LeftFibreMFD,
RightFibreMFD,
LeastLoss,
RateOfSyntropyBending,
RateOfReverseBending,
RateOfMFDDeviation,
AutoStart,
Stop1,
Stop2,
CutAngle,
OffsetData,
Cut,
Loss,
FibreCoreAngle,
Bubble,
Thick,
Thin,
AirPressure,
Temperature,
ImgGap,
ImgStop1,
ImgAlign,
ImgStop2,
ImgDischarge,
ImgLossEstimation,
FibreAutoFeed,
BadCutSurface,
AutoAlignAfterStop,
ManualDischargeTimes,
MotorTestTimes,
ElectricArcTestTimes,
CleanArcRate)
};
template<>
struct zmsg<mid_t::motor_test_result> {
motor_test_err_t code;
/// \note following are error times
UINT32 reset;
UINT32 push;
UINT32 ele_arc;
UINT32 img;
public:
ZMSG_PU(code, reset, push, ele_arc, img);
};
} /* namespace zmsg */
<commit_msg>zmsg: motor_test_result : add test times<commit_after>#pragma once
#include "zmsg_cmm.hpp"
namespace zmsg {
template<>
struct zmsg<mid_t::motor_test_start> {
public:
UINT32 FSPattern;
UINT32 FibreType;
UINT32 FibreAlignment;
BOOL XImageFocus;
BOOL YImageFocus;
UINT32 FibreShift;
BOOL DischargeStrengthAdjustment;
BOOL TensionSet;
FLOAT CutAngleLimit;
FLOAT LossLimit;
FLOAT FibreAngleLimit;
ULONG CleanDischargeTime;
ULONG FibreIntervalSetup;
LONG FSPosSetup;
UINT16 FibrePreFSStrength;
ULONG FibrePreFSTime;
ULONG FibreOverlapSetup;
UINT16 Discharge1Strength;
ULONG Discharge1Time;
UINT16 Discharge2Strength;
ULONG Discharge2LastTime;
ULONG Discharge2StartTime;
ULONG Discharge2StopTime;
ULONG ExtraManualDischargeTime;
BOOL ConeFS;
ULONG ConeFSWaitTime;
ULONG ConeFSSpeed;
ULONG ConeFSStretchLength;
UINT32 LossEstimationMode;
FLOAT LeftFibreMFD;
FLOAT RightFibreMFD;
FLOAT LeastLoss;
FLOAT RateOfSyntropyBending;
FLOAT RateOfReverseBending;
FLOAT RateOfMFDDeviation;
BOOL AutoStart;
BOOL Stop1;
BOOL Stop2;
/*data dispaly*/
BOOL CutAngle;
BOOL OffsetData;
/*omitted choice*/
BOOL Cut;
BOOL Loss;
BOOL FibreCoreAngle;
BOOL Bubble;
BOOL Thick;
BOOL Thin;
/*dischargesupplement*/
BOOL AirPressure;
BOOL Temperature;
/*fiber_image_display*/
UINT32 ImgGap;
UINT32 ImgStop1;
UINT32 ImgAlign;
UINT32 ImgStop2;
UINT32 ImgDischarge;
UINT32 ImgLossEstimation;
/*else*/
BOOL FibreAutoFeed;
BOOL BadCutSurface;
BOOL AutoAlignAfterStop;
ULONG ManualDischargeTimes;
/* motor test para */
UINT32 MotorTestTimes;
UINT32 ElectricArcTestTimes;
UINT32 CleanArcRate;
public:
ZMSG_PU(
FSPattern,
FibreType,
FibreAlignment,
XImageFocus,
YImageFocus,
FibreShift,
DischargeStrengthAdjustment,
TensionSet,
CutAngleLimit,
LossLimit,
FibreAngleLimit,
CleanDischargeTime,
FibreIntervalSetup,
FSPosSetup,
FibrePreFSStrength,
FibrePreFSTime,
FibreOverlapSetup,
Discharge1Strength,
Discharge1Time,
Discharge2Strength,
Discharge2LastTime,
Discharge2StartTime,
Discharge2StopTime,
ExtraManualDischargeTime,
ConeFS,
ConeFSWaitTime,
ConeFSSpeed,
ConeFSStretchLength,
LossEstimationMode,
LeftFibreMFD,
RightFibreMFD,
LeastLoss,
RateOfSyntropyBending,
RateOfReverseBending,
RateOfMFDDeviation,
AutoStart,
Stop1,
Stop2,
CutAngle,
OffsetData,
Cut,
Loss,
FibreCoreAngle,
Bubble,
Thick,
Thin,
AirPressure,
Temperature,
ImgGap,
ImgStop1,
ImgAlign,
ImgStop2,
ImgDischarge,
ImgLossEstimation,
FibreAutoFeed,
BadCutSurface,
AutoAlignAfterStop,
ManualDischargeTimes,
MotorTestTimes,
ElectricArcTestTimes,
CleanArcRate)
};
template<>
struct zmsg<mid_t::motor_test_result> {
motor_test_err_t code;
UINT32 motor_test_times;
UINT32 ele_arc_test_times;
/// \note following are error times
UINT32 reset;
UINT32 push;
UINT32 ele_arc;
UINT32 img;
public:
ZMSG_PU(code, reset, push, ele_arc, img);
};
} /* namespace zmsg */
<|endoftext|>
|
<commit_before>#pragma once
#include "../std/string.hpp"
namespace classificator
{
void ReadVisibility(string const & fPath);
void Load();
}
<commit_msg>Remove obsolete declaration.<commit_after>#pragma once
#include "../std/string.hpp"
namespace classificator
{
void Load();
}
<|endoftext|>
|
<commit_before>
// Note - python_bindings_common.h must be included before condor_common to avoid
// re-definition warnings.
#include "python_bindings_common.h"
#include "condor_adtypes.h"
#include "dc_collector.h"
#include "condor_version.h"
#include <memory>
#include "old_boost.h"
#include "classad_wrapper.h"
#include "module_lock.h"
#include "htcondor.h"
#include "daemon_location.h"
using namespace boost::python;
static boost::python::list
toList(const boost::shared_ptr<classad::ClassAd> ad, const std::vector<std::string> &attrs)
{
int idx = 1;
bool hasattr = true;
boost::python::list result;
while (hasattr)
{
hasattr = false;
boost::shared_ptr<ClassAdWrapper> nextAd(new ClassAdWrapper());
for (std::vector<std::string>::const_iterator it = attrs.begin(); it != attrs.end(); it++)
{
std::stringstream attr; attr << *it << idx;
classad::ExprTree *expr = NULL;
if ((expr = ad->Lookup(attr.str())))
{
classad::ExprTree *copy = expr->Copy();
if (!copy) { THROW_EX(HTCondorInternalError, "Unable to create copy of ClassAd expression"); }
if (!nextAd->Insert(*it, copy)) { THROW_EX(HTCondorInternalError, "Unable to copy attribute into destination ClassAd"); }
hasattr = true;
}
}
if (hasattr)
{
result.append(nextAd);
}
idx++;
}
return result;
}
struct Negotiator {
void use_local_negotiator()
{
Daemon neg( DT_NEGOTIATOR, 0, 0 );
bool result;
{
condor::ModuleLock ml;
result = neg.locate();
}
if (result)
{
if (neg.addr())
{
m_addr = neg.addr();
}
else
{
THROW_EX(HTCondorLocateError, "Unable to locate negotiator address.");
}
m_version = neg.version() ? neg.version() : "";
}
else
{
THROW_EX(HTCondorLocateError, "Unable to locate local daemon");
}
}
Negotiator() {
use_local_negotiator();
}
Negotiator(boost::python::object loc)
: m_addr(), m_version("")
{
int rv = construct_for_location(loc, DT_NEGOTIATOR, m_addr, m_version);
if (rv == 0) {
use_local_negotiator();
} else if (rv < 0) {
if (rv == -2) { boost::python::throw_error_already_set(); }
THROW_EX(HTCondorValueError, "Unknown type");
}
}
~Negotiator()
{
}
boost::python::object location() const {
return make_daemon_location(DT_NEGOTIATOR, m_addr, m_version);
}
void setPriority(const std::string &user, float prio)
{
if (prio < 0) THROW_EX(HTCondorValueError, "User priority must be non-negative");
sendUserValue(SET_PRIORITY, user, prio);
}
void setFactor(const std::string &user, float factor)
{
if (factor<1) THROW_EX(HTCondorValueError, "Priority factors must be >= 1");
sendUserValue(SET_PRIORITYFACTOR, user, factor);
}
void setUsage(const std::string &user, float usage)
{
if (usage < 0) THROW_EX(HTCondorValueError, "Usage must be non-negative.");
sendUserValue(SET_ACCUMUSAGE, user, usage);
}
void setBeginUsage(const std::string &user, time_t time)
{
sendUserValue(SET_BEGINTIME, user, time);
}
void setLastUsage(const std::string &user, time_t time)
{
sendUserValue(SET_LASTTIME, user, time);
}
void setCeiling(const std::string &user, float ceiling)
{
if (ceiling < -1) THROW_EX(HTCondorValueError, "Ceiling must be greater than -1.");
sendUserValue(SET_CEILING, user, ceiling);
}
void resetUsage(const std::string &user)
{
sendUserCmd(RESET_USAGE, user);
}
void deleteUser(const std::string &user)
{
sendUserCmd(DELETE_USER, user);
}
void resetAllUsage()
{
Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());
bool result;
{
condor::ModuleLock ml;
result = negotiator.sendCommand(RESET_ALL_USAGE, Stream::reli_sock, 0);
}
if (!result)
{
THROW_EX(HTCondorIOError, "Failed to send RESET_ALL_USAGE command");
}
}
boost::python::list
getResourceUsage(const std::string &user)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(GET_RESLIST);
if (!sock->put(user.c_str()) ||
!sock->end_of_message())
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send GET_RESLIST command to negotiator" );
}
sock->decode();
boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());
bool result;
{
condor::ModuleLock ml;
result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();
}
if (result)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to get classad from negotiator");
}
sock->close();
std::vector<std::string> attrs;
attrs.push_back("Name");
attrs.push_back("StartTime");
return toList(ad, attrs);
}
boost::python::list
getPriorities(bool rollup=false)
{
boost::shared_ptr<Sock> sock = getSocket(rollup ? GET_PRIORITY_ROLLUP : GET_PRIORITY);
sock->decode();
boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());
bool result;
{
condor::ModuleLock ml;
result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();
}
if (result)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to get classad from negotiator");
}
sock->close();
std::vector<std::string> attrs;
attrs.push_back("Name");
attrs.push_back("Priority");
attrs.push_back("ResourcesUsed");
attrs.push_back("Requested");
attrs.push_back("WeightedResourcesUsed");
attrs.push_back("PriorityFactor");
attrs.push_back("BeginUsageTime");
attrs.push_back("LastUsageTime");
attrs.push_back("WeightedAccumulatedUsage");
attrs.push_back("AccountingGroup");
attrs.push_back("IsAccountingGroup");
attrs.push_back("AccumulatedUsage");
return toList(ad, attrs);
}
private:
void checkUser(const std::string &user)
{
if( user.find('@') == std::string::npos )
{
THROW_EX(HTCondorValueError, "You must specify the full name of the submittor you wish (user@uid.domain)");
}
}
boost::shared_ptr<Sock> getSocket(int cmd)
{
Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());
Sock *raw_sock;
{
condor::ModuleLock ml;
raw_sock = negotiator.startCommand(cmd, Stream::reli_sock, 0);
}
boost::shared_ptr<Sock> sock(raw_sock);
if (!sock.get()) { THROW_EX(HTCondorIOError, "Unable to connect to the negotiator"); }
return sock;
}
void sendUserValue(int cmd, const std::string &user, float val)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
void sendUserValue(int cmd, const std::string &user, time_t val)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
void sendUserCmd(int cmd, const std::string &user)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
std::string m_addr;
std::string m_version;
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(priority_overloads, getPriorities, 0, 1);
void export_negotiator()
{
class_<Negotiator>("Negotiator",
R"C0ND0R(
This class provides a query interface to the *condor_negotiator*.
It primarily allows one to query and set various parameters in the fair-share accounting.
)C0ND0R",
init<boost::python::object>(
R"C0ND0R(
:param location_ad: A ClassAd or DaemonLocation describing the *condor_negotiator*
location and version. If omitted, the default pool negotiator is assumed.
:type location_ad: :class:`~classad.ClassAd` or :class:`DaemonLocation`
)C0ND0R",
boost::python::args("self", "ad")))
.def(boost::python::init<>(boost::python::args("self")))
.add_property("location", &Negotiator::location,
R"C0ND0R(
The negotiator to query or send commands to
:rtype: location :class:`DaemonLocation`
)C0ND0R")
.def("setPriority", &Negotiator::setPriority,
R"C0ND0R(
Set the real priority of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float prio: The priority to be set for the user; must be greater-than 0.0.
)C0ND0R",
boost::python::args("self", "user", "prio"))
.def("setFactor", &Negotiator::setFactor,
R"C0ND0R(
Set the priority factor of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float factor: The priority factor to be set for the user; must be greater-than or equal-to 1.0.
)C0ND0R",
boost::python::args("self", "user", "factor"))
.def("setCeiling", &Negotiator::setCeiling,
R"C0ND0R(
Set the submitter ceiling of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float ceiling: The ceiling t be set for the submitter; must be greater-than or equal-to -1.0.
)C0ND0R",
boost::python::args("self", "user", "ceiling"))
.def("setUsage", &Negotiator::setUsage,
R"C0ND0R(
Set the accumulated usage of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float usage: The usage, in hours, to be set for the user.
)C0ND0R",
boost::python::args("self", "user", "usage"))
.def("setBeginUsage", &Negotiator::setBeginUsage,
R"C0ND0R(
Manually set the time that a user begins using the pool.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param int value: The Unix timestamp of initial usage.
)C0ND0R",
boost::python::args("self", "user", "value"))
.def("setLastUsage", &Negotiator::setLastUsage,
R"C0ND0R(
Manually set the time that a user last used the pool.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param int value: The Unix timestamp of last usage.
)C0ND0R",
boost::python::args("self", "user", "value"))
.def("resetUsage", &Negotiator::resetUsage,
R"C0ND0R(
Reset all usage accounting of the specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
)C0ND0R",
boost::python::args("self", "user"))
.def("deleteUser", &Negotiator::deleteUser,
R"C0ND0R(
Delete all records of a user from the Negotiator's fair-share accounting.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
)C0ND0R",
boost::python::args("self", "user"))
.def("resetAllUsage", &Negotiator::resetAllUsage,
R"C0ND0R(
Reset all usage accounting. All known user records in the negotiator are deleted.
)C0ND0R",
boost::python::args("self"))
.def("getResourceUsage", &Negotiator::getResourceUsage,
R"C0ND0R(
Get the resources (slots) used by a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:return: List of ads describing the resources (slots) in use.
:rtype: list[:class:`~classad.ClassAd`]
)C0ND0R",
boost::python::args("self", "user"))
.def("getPriorities", &Negotiator::getPriorities, priority_overloads(
R"C0ND0R(
Retrieve the pool accounting information, one per entry.
Returns a list of accounting ClassAds.
:param bool rollup: Set to ``True`` if accounting information, as applied to
hierarchical group quotas, should be summed for groups and subgroups.
:return: A list of accounting ads, one per entity.
:rtype: list[:class:`~classad.ClassAd`]
)C0ND0R",
boost::python::args("self", "rollup")))
;
}
<commit_msg>Updated negotiator.getPriorites python binding to include ceiling (HTCONDOR-560)<commit_after>
// Note - python_bindings_common.h must be included before condor_common to avoid
// re-definition warnings.
#include "python_bindings_common.h"
#include "condor_adtypes.h"
#include "dc_collector.h"
#include "condor_version.h"
#include <memory>
#include "old_boost.h"
#include "classad_wrapper.h"
#include "module_lock.h"
#include "htcondor.h"
#include "daemon_location.h"
using namespace boost::python;
static boost::python::list
toList(const boost::shared_ptr<classad::ClassAd> ad, const std::vector<std::string> &attrs)
{
int idx = 1;
bool hasattr = true;
boost::python::list result;
while (hasattr)
{
hasattr = false;
boost::shared_ptr<ClassAdWrapper> nextAd(new ClassAdWrapper());
for (std::vector<std::string>::const_iterator it = attrs.begin(); it != attrs.end(); it++)
{
std::stringstream attr; attr << *it << idx;
classad::ExprTree *expr = NULL;
if ((expr = ad->Lookup(attr.str())))
{
classad::ExprTree *copy = expr->Copy();
if (!copy) { THROW_EX(HTCondorInternalError, "Unable to create copy of ClassAd expression"); }
if (!nextAd->Insert(*it, copy)) { THROW_EX(HTCondorInternalError, "Unable to copy attribute into destination ClassAd"); }
hasattr = true;
}
}
if (hasattr)
{
result.append(nextAd);
}
idx++;
}
return result;
}
struct Negotiator {
void use_local_negotiator()
{
Daemon neg( DT_NEGOTIATOR, 0, 0 );
bool result;
{
condor::ModuleLock ml;
result = neg.locate();
}
if (result)
{
if (neg.addr())
{
m_addr = neg.addr();
}
else
{
THROW_EX(HTCondorLocateError, "Unable to locate negotiator address.");
}
m_version = neg.version() ? neg.version() : "";
}
else
{
THROW_EX(HTCondorLocateError, "Unable to locate local daemon");
}
}
Negotiator() {
use_local_negotiator();
}
Negotiator(boost::python::object loc)
: m_addr(), m_version("")
{
int rv = construct_for_location(loc, DT_NEGOTIATOR, m_addr, m_version);
if (rv == 0) {
use_local_negotiator();
} else if (rv < 0) {
if (rv == -2) { boost::python::throw_error_already_set(); }
THROW_EX(HTCondorValueError, "Unknown type");
}
}
~Negotiator()
{
}
boost::python::object location() const {
return make_daemon_location(DT_NEGOTIATOR, m_addr, m_version);
}
void setPriority(const std::string &user, float prio)
{
if (prio < 0) THROW_EX(HTCondorValueError, "User priority must be non-negative");
sendUserValue(SET_PRIORITY, user, prio);
}
void setFactor(const std::string &user, float factor)
{
if (factor<1) THROW_EX(HTCondorValueError, "Priority factors must be >= 1");
sendUserValue(SET_PRIORITYFACTOR, user, factor);
}
void setUsage(const std::string &user, float usage)
{
if (usage < 0) THROW_EX(HTCondorValueError, "Usage must be non-negative.");
sendUserValue(SET_ACCUMUSAGE, user, usage);
}
void setBeginUsage(const std::string &user, time_t time)
{
sendUserValue(SET_BEGINTIME, user, time);
}
void setLastUsage(const std::string &user, time_t time)
{
sendUserValue(SET_LASTTIME, user, time);
}
void setCeiling(const std::string &user, float ceiling)
{
if (ceiling < -1) THROW_EX(HTCondorValueError, "Ceiling must be greater than -1.");
sendUserValue(SET_CEILING, user, ceiling);
}
void resetUsage(const std::string &user)
{
sendUserCmd(RESET_USAGE, user);
}
void deleteUser(const std::string &user)
{
sendUserCmd(DELETE_USER, user);
}
void resetAllUsage()
{
Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());
bool result;
{
condor::ModuleLock ml;
result = negotiator.sendCommand(RESET_ALL_USAGE, Stream::reli_sock, 0);
}
if (!result)
{
THROW_EX(HTCondorIOError, "Failed to send RESET_ALL_USAGE command");
}
}
boost::python::list
getResourceUsage(const std::string &user)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(GET_RESLIST);
if (!sock->put(user.c_str()) ||
!sock->end_of_message())
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send GET_RESLIST command to negotiator" );
}
sock->decode();
boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());
bool result;
{
condor::ModuleLock ml;
result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();
}
if (result)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to get classad from negotiator");
}
sock->close();
std::vector<std::string> attrs;
attrs.push_back("Name");
attrs.push_back("StartTime");
return toList(ad, attrs);
}
boost::python::list
getPriorities(bool rollup=false)
{
boost::shared_ptr<Sock> sock = getSocket(rollup ? GET_PRIORITY_ROLLUP : GET_PRIORITY);
sock->decode();
boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());
bool result;
{
condor::ModuleLock ml;
result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();
}
if (result)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to get classad from negotiator");
}
sock->close();
std::vector<std::string> attrs;
attrs.push_back("Name");
attrs.push_back("Priority");
attrs.push_back("ResourcesUsed");
attrs.push_back("Requested");
attrs.push_back("WeightedResourcesUsed");
attrs.push_back("PriorityFactor");
attrs.push_back("BeginUsageTime");
attrs.push_back("LastUsageTime");
attrs.push_back("WeightedAccumulatedUsage");
attrs.push_back("AccountingGroup");
attrs.push_back("IsAccountingGroup");
attrs.push_back("AccumulatedUsage");
attrs.push_back("Ceiling");
return toList(ad, attrs);
}
private:
void checkUser(const std::string &user)
{
if( user.find('@') == std::string::npos )
{
THROW_EX(HTCondorValueError, "You must specify the full name of the submittor you wish (user@uid.domain)");
}
}
boost::shared_ptr<Sock> getSocket(int cmd)
{
Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());
Sock *raw_sock;
{
condor::ModuleLock ml;
raw_sock = negotiator.startCommand(cmd, Stream::reli_sock, 0);
}
boost::shared_ptr<Sock> sock(raw_sock);
if (!sock.get()) { THROW_EX(HTCondorIOError, "Unable to connect to the negotiator"); }
return sock;
}
void sendUserValue(int cmd, const std::string &user, float val)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
void sendUserValue(int cmd, const std::string &user, time_t val)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
void sendUserCmd(int cmd, const std::string &user)
{
checkUser(user);
boost::shared_ptr<Sock> sock = getSocket(cmd);
bool retval;
{
condor::ModuleLock ml;
retval = !sock->put(user.c_str()) || !sock->end_of_message();
}
if (retval)
{
sock->close();
THROW_EX(HTCondorIOError, "Failed to send command to negotiator\n" );
}
sock->close();
}
std::string m_addr;
std::string m_version;
};
BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(priority_overloads, getPriorities, 0, 1);
void export_negotiator()
{
class_<Negotiator>("Negotiator",
R"C0ND0R(
This class provides a query interface to the *condor_negotiator*.
It primarily allows one to query and set various parameters in the fair-share accounting.
)C0ND0R",
init<boost::python::object>(
R"C0ND0R(
:param location_ad: A ClassAd or DaemonLocation describing the *condor_negotiator*
location and version. If omitted, the default pool negotiator is assumed.
:type location_ad: :class:`~classad.ClassAd` or :class:`DaemonLocation`
)C0ND0R",
boost::python::args("self", "ad")))
.def(boost::python::init<>(boost::python::args("self")))
.add_property("location", &Negotiator::location,
R"C0ND0R(
The negotiator to query or send commands to
:rtype: location :class:`DaemonLocation`
)C0ND0R")
.def("setPriority", &Negotiator::setPriority,
R"C0ND0R(
Set the real priority of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float prio: The priority to be set for the user; must be greater-than 0.0.
)C0ND0R",
boost::python::args("self", "user", "prio"))
.def("setFactor", &Negotiator::setFactor,
R"C0ND0R(
Set the priority factor of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float factor: The priority factor to be set for the user; must be greater-than or equal-to 1.0.
)C0ND0R",
boost::python::args("self", "user", "factor"))
.def("setCeiling", &Negotiator::setCeiling,
R"C0ND0R(
Set the submitter ceiling of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float ceiling: The ceiling t be set for the submitter; must be greater-than or equal-to -1.0.
)C0ND0R",
boost::python::args("self", "user", "ceiling"))
.def("setUsage", &Negotiator::setUsage,
R"C0ND0R(
Set the accumulated usage of a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param float usage: The usage, in hours, to be set for the user.
)C0ND0R",
boost::python::args("self", "user", "usage"))
.def("setBeginUsage", &Negotiator::setBeginUsage,
R"C0ND0R(
Manually set the time that a user begins using the pool.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param int value: The Unix timestamp of initial usage.
)C0ND0R",
boost::python::args("self", "user", "value"))
.def("setLastUsage", &Negotiator::setLastUsage,
R"C0ND0R(
Manually set the time that a user last used the pool.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:param int value: The Unix timestamp of last usage.
)C0ND0R",
boost::python::args("self", "user", "value"))
.def("resetUsage", &Negotiator::resetUsage,
R"C0ND0R(
Reset all usage accounting of the specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
)C0ND0R",
boost::python::args("self", "user"))
.def("deleteUser", &Negotiator::deleteUser,
R"C0ND0R(
Delete all records of a user from the Negotiator's fair-share accounting.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
)C0ND0R",
boost::python::args("self", "user"))
.def("resetAllUsage", &Negotiator::resetAllUsage,
R"C0ND0R(
Reset all usage accounting. All known user records in the negotiator are deleted.
)C0ND0R",
boost::python::args("self"))
.def("getResourceUsage", &Negotiator::getResourceUsage,
R"C0ND0R(
Get the resources (slots) used by a specified user.
:param str user: A fully-qualified user name (``USER@DOMAIN``).
:return: List of ads describing the resources (slots) in use.
:rtype: list[:class:`~classad.ClassAd`]
)C0ND0R",
boost::python::args("self", "user"))
.def("getPriorities", &Negotiator::getPriorities, priority_overloads(
R"C0ND0R(
Retrieve the pool accounting information, one per entry.
Returns a list of accounting ClassAds.
:param bool rollup: Set to ``True`` if accounting information, as applied to
hierarchical group quotas, should be summed for groups and subgroups.
:return: A list of accounting ads, one per entity.
:rtype: list[:class:`~classad.ClassAd`]
)C0ND0R",
boost::python::args("self", "rollup")))
;
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/pb_utils.hpp"
#include "rdb_protocol/minidriver.hpp"
namespace ql {
// This file implements terms that are rewritten into other terms.
class rewrite_term_t : public term_t {
public:
rewrite_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec,
r::reql_t (*rewrite)(protob_t<const Term> in,
const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in))
: term_t(term), in(term), out(make_counted_term()) {
int args_size = in->args_size();
rcheck(argspec.contains(args_size),
base_exc_t::GENERIC,
strprintf("Expected %s but found %d.",
argspec.print().c_str(), args_size));
out->Swap(&rewrite(in, this, in).get());
propagate(out.get()); // duplicates `in` backtrace (see `pb_rcheckable_t`)
real = compile_term(env, out);
}
private:
virtual void accumulate_captures(var_captures_t *captures) const {
return real->accumulate_captures(captures);
}
virtual bool is_deterministic() const {
return real->is_deterministic();
}
virtual counted_t<val_t> term_eval(scope_env_t *env, eval_flags_t) const {
return real->eval(env);
}
protob_t<const Term> in;
protob_t<Term> out;
counted_t<const term_t> real;
};
class inner_join_term_t : public rewrite_term_t {
public:
inner_join_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(3), rewrite) { }
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &right = in->args(1);
const Term &func = in->args(2);
auto n = pb::dummy_var_t::INNERJOIN_N;
auto m = pb::dummy_var_t::INNERJOIN_M;
r::reql_t term =
r::expr(left).concat_map(
r::fun(n,
r::expr(right).concat_map(
r::fun(m,
r::branch(
r::expr(func)(r::var(n), r::var(m)),
r::array(r::object(
r::optarg("left", n), r::optarg("right", m))),
r::array())))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "inner_join"; }
};
class outer_join_term_t : public rewrite_term_t {
public:
outer_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :
rewrite_term_t(env, term, argspec_t(3), rewrite) { }
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &right = in->args(1);
const Term &func = in->args(2);
auto n = pb::dummy_var_t::OUTERJOIN_N;
auto m = pb::dummy_var_t::OUTERJOIN_M;
auto lst = pb::dummy_var_t::OUTERJOIN_LST;
r::reql_t inner_concat_map =
r::expr(right).concat_map(
r::fun(m,
r::branch(
r::expr(func)(n, m),
r::array(r::object(r::optarg("left", n), r::optarg("right", m))),
r::array())));
r::reql_t term =
r::expr(left).concat_map(
r::fun(n,
std::move(inner_concat_map).coerce_to("ARRAY").do_(lst,
r::branch(
r::expr(lst).count() > 0,
lst,
r::array(r::object(r::optarg("left", n)))))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "outer_join"; }
};
class eq_join_term_t : public rewrite_term_t {
public:
eq_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :
rewrite_term_t(env, term, argspec_t(3), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &left_attr = in->args(1);
const Term &right = in->args(2);
auto row = pb::dummy_var_t::EQJOIN_ROW;
auto v = pb::dummy_var_t::EQJOIN_V;
r::reql_t get_all =
r::expr(right).get_all(
r::expr(left_attr)(row, r::optarg("_SHORTCUT_", GET_FIELD_SHORTCUT)));
get_all.copy_optargs_from_term(*optargs_in);
return r::expr(left).concat_map(
r::fun(row,
r::branch(
r::null() == row,
r::array(),
std::move(get_all).default_(r::array()).map(
r::fun(v, r::object(r::optarg("left", row),
r::optarg("right", v)))))));
}
virtual const char *name() const { return "inner_join"; }
};
class delete_term_t : public rewrite_term_t {
public:
delete_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(1), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto x = pb::dummy_var_t::IGNORED;
r::reql_t term = r::expr(in->args(0)).replace(r::fun(x, r::null()));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "delete"; }
};
class update_term_t : public rewrite_term_t {
public:
update_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto old_row = pb::dummy_var_t::UPDATE_OLDROW;
auto new_row = pb::dummy_var_t::UPDATE_NEWROW;
r::reql_t term =
r::expr(in->args(0)).replace(
r::fun(old_row,
r::branch(
r::null() == old_row,
r::null(),
r::fun(new_row,
r::branch(
r::null() == new_row,
old_row,
r::expr(old_row).merge(new_row)))(
r::expr(in->args(1))(old_row,
r::optarg("_EVAL_FLAGS_", LITERAL_OK)),
r::optarg("_EVAL_FLAGS_", LITERAL_OK)))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "update"; }
};
class skip_term_t : public rewrite_term_t {
public:
skip_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
r::reql_t term =
r::expr(in->args(0)).slice(in->args(1), -1,
r::optarg("right_bound", "closed"));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "skip"; }
};
class difference_term_t : public rewrite_term_t {
public:
difference_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto row = pb::dummy_var_t::DIFFERENCE_ROW;
r::reql_t term =
r::expr(in->args(0)).filter(
r::fun(row,
!r::expr(in->args(1)).contains(row)));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "difference"; }
};
class with_fields_term_t : public rewrite_term_t {
public:
with_fields_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(1, -1), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
r::reql_t has_fields = r::expr(in->args(0)).has_fields();
has_fields.copy_args_from_term(*in, 1);
has_fields.copy_optargs_from_term(*optargs_in);
r::reql_t pluck = std::move(has_fields).pluck();
pluck.copy_args_from_term(*in, 1);
return pluck;
}
virtual const char *name() const { return "with_fields"; }
};
counted_t<term_t> make_skip_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<skip_term_t>(env, term);
}
counted_t<term_t> make_inner_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<inner_join_term_t>(env, term);
}
counted_t<term_t> make_outer_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<outer_join_term_t>(env, term);
}
counted_t<term_t> make_eq_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<eq_join_term_t>(env, term);
}
counted_t<term_t> make_update_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<update_term_t>(env, term);
}
counted_t<term_t> make_delete_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<delete_term_t>(env, term);
}
counted_t<term_t> make_difference_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<difference_term_t>(env, term);
}
counted_t<term_t> make_with_fields_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<with_fields_term_t>(env, term);
}
} // namespace ql
<commit_msg>Use actual name for `eq_join`<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/terms/terms.hpp"
#include <string>
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/error.hpp"
#include "rdb_protocol/pb_utils.hpp"
#include "rdb_protocol/minidriver.hpp"
namespace ql {
// This file implements terms that are rewritten into other terms.
class rewrite_term_t : public term_t {
public:
rewrite_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec,
r::reql_t (*rewrite)(protob_t<const Term> in,
const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in))
: term_t(term), in(term), out(make_counted_term()) {
int args_size = in->args_size();
rcheck(argspec.contains(args_size),
base_exc_t::GENERIC,
strprintf("Expected %s but found %d.",
argspec.print().c_str(), args_size));
out->Swap(&rewrite(in, this, in).get());
propagate(out.get()); // duplicates `in` backtrace (see `pb_rcheckable_t`)
real = compile_term(env, out);
}
private:
virtual void accumulate_captures(var_captures_t *captures) const {
return real->accumulate_captures(captures);
}
virtual bool is_deterministic() const {
return real->is_deterministic();
}
virtual counted_t<val_t> term_eval(scope_env_t *env, eval_flags_t) const {
return real->eval(env);
}
protob_t<const Term> in;
protob_t<Term> out;
counted_t<const term_t> real;
};
class inner_join_term_t : public rewrite_term_t {
public:
inner_join_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(3), rewrite) { }
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &right = in->args(1);
const Term &func = in->args(2);
auto n = pb::dummy_var_t::INNERJOIN_N;
auto m = pb::dummy_var_t::INNERJOIN_M;
r::reql_t term =
r::expr(left).concat_map(
r::fun(n,
r::expr(right).concat_map(
r::fun(m,
r::branch(
r::expr(func)(r::var(n), r::var(m)),
r::array(r::object(
r::optarg("left", n), r::optarg("right", m))),
r::array())))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "inner_join"; }
};
class outer_join_term_t : public rewrite_term_t {
public:
outer_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :
rewrite_term_t(env, term, argspec_t(3), rewrite) { }
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &right = in->args(1);
const Term &func = in->args(2);
auto n = pb::dummy_var_t::OUTERJOIN_N;
auto m = pb::dummy_var_t::OUTERJOIN_M;
auto lst = pb::dummy_var_t::OUTERJOIN_LST;
r::reql_t inner_concat_map =
r::expr(right).concat_map(
r::fun(m,
r::branch(
r::expr(func)(n, m),
r::array(r::object(r::optarg("left", n), r::optarg("right", m))),
r::array())));
r::reql_t term =
r::expr(left).concat_map(
r::fun(n,
std::move(inner_concat_map).coerce_to("ARRAY").do_(lst,
r::branch(
r::expr(lst).count() > 0,
lst,
r::array(r::object(r::optarg("left", n)))))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "outer_join"; }
};
class eq_join_term_t : public rewrite_term_t {
public:
eq_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :
rewrite_term_t(env, term, argspec_t(3), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
const Term &left = in->args(0);
const Term &left_attr = in->args(1);
const Term &right = in->args(2);
auto row = pb::dummy_var_t::EQJOIN_ROW;
auto v = pb::dummy_var_t::EQJOIN_V;
r::reql_t get_all =
r::expr(right).get_all(
r::expr(left_attr)(row, r::optarg("_SHORTCUT_", GET_FIELD_SHORTCUT)));
get_all.copy_optargs_from_term(*optargs_in);
return r::expr(left).concat_map(
r::fun(row,
r::branch(
r::null() == row,
r::array(),
std::move(get_all).default_(r::array()).map(
r::fun(v, r::object(r::optarg("left", row),
r::optarg("right", v)))))));
}
virtual const char *name() const { return "eq_join"; }
};
class delete_term_t : public rewrite_term_t {
public:
delete_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(1), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto x = pb::dummy_var_t::IGNORED;
r::reql_t term = r::expr(in->args(0)).replace(r::fun(x, r::null()));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "delete"; }
};
class update_term_t : public rewrite_term_t {
public:
update_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto old_row = pb::dummy_var_t::UPDATE_OLDROW;
auto new_row = pb::dummy_var_t::UPDATE_NEWROW;
r::reql_t term =
r::expr(in->args(0)).replace(
r::fun(old_row,
r::branch(
r::null() == old_row,
r::null(),
r::fun(new_row,
r::branch(
r::null() == new_row,
old_row,
r::expr(old_row).merge(new_row)))(
r::expr(in->args(1))(old_row,
r::optarg("_EVAL_FLAGS_", LITERAL_OK)),
r::optarg("_EVAL_FLAGS_", LITERAL_OK)))));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "update"; }
};
class skip_term_t : public rewrite_term_t {
public:
skip_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
r::reql_t term =
r::expr(in->args(0)).slice(in->args(1), -1,
r::optarg("right_bound", "closed"));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "skip"; }
};
class difference_term_t : public rewrite_term_t {
public:
difference_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(2), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
auto row = pb::dummy_var_t::DIFFERENCE_ROW;
r::reql_t term =
r::expr(in->args(0)).filter(
r::fun(row,
!r::expr(in->args(1)).contains(row)));
term.copy_optargs_from_term(*optargs_in);
return term;
}
virtual const char *name() const { return "difference"; }
};
class with_fields_term_t : public rewrite_term_t {
public:
with_fields_term_t(compile_env_t *env, const protob_t<const Term> &term)
: rewrite_term_t(env, term, argspec_t(1, -1), rewrite) { }
private:
static r::reql_t rewrite(protob_t<const Term> in,
UNUSED const pb_rcheckable_t *bt_src,
protob_t<const Term> optargs_in) {
r::reql_t has_fields = r::expr(in->args(0)).has_fields();
has_fields.copy_args_from_term(*in, 1);
has_fields.copy_optargs_from_term(*optargs_in);
r::reql_t pluck = std::move(has_fields).pluck();
pluck.copy_args_from_term(*in, 1);
return pluck;
}
virtual const char *name() const { return "with_fields"; }
};
counted_t<term_t> make_skip_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<skip_term_t>(env, term);
}
counted_t<term_t> make_inner_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<inner_join_term_t>(env, term);
}
counted_t<term_t> make_outer_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<outer_join_term_t>(env, term);
}
counted_t<term_t> make_eq_join_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<eq_join_term_t>(env, term);
}
counted_t<term_t> make_update_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<update_term_t>(env, term);
}
counted_t<term_t> make_delete_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<delete_term_t>(env, term);
}
counted_t<term_t> make_difference_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<difference_term_t>(env, term);
}
counted_t<term_t> make_with_fields_term(
compile_env_t *env, const protob_t<const Term> &term) {
return make_counted<with_fields_term_t>(env, term);
}
} // namespace ql
<|endoftext|>
|
<commit_before>/*
* ccookies.hpp
*
* Created on: 19.11.2014
* Author: andreas
*/
#ifndef CCOOKIES_HPP_
#define CCOOKIES_HPP_
#include <inttypes.h>
#include <rofl/common/crofdpt.h>
#include <rofl/common/cauxid.h>
#include <rofl/common/crandom.h>
#include <rofl/common/openflow/messages/cofmsg_packet_in.h>
#include <rofl/common/openflow/messages/cofmsg_flow_removed.h>
namespace roflibs {
namespace common {
namespace openflow {
class ccookiebox; // forward declaration, see below
class ccookie_owner {
public:
/**
*
*/
virtual
~ccookie_owner();
public:
/**
*
*/
uint64_t
acquire_cookie();
/**
*
*/
void
release_cookie(uint64_t cookie);
protected:
friend class ccookiebox;
/**
*
*/
virtual void
handle_packet_in(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0;
/**
*
*/
virtual void
handle_flow_removed(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0;
};
class ccookie_find_by_owner {
ccookie_owner* owner;
public:
ccookie_find_by_owner(ccookie_owner* owner) :
owner(owner) {};
bool operator() (const std::pair<uint64_t, ccookie_owner*>& p) {
return (p.second == owner);
};
};
class ccookiebox {
private:
static ccookiebox* cookiebox;
uint64_t next_cookie;
std::map<uint64_t, ccookie_owner*> cookiestore;
ccookiebox() : next_cookie(rofl::crandom(8).uint64()) {};
~ccookiebox() {};
public:
/**
*
*/
static ccookiebox&
get_instance() {
if ((ccookiebox*)0 == ccookiebox::cookiebox) {
ccookiebox::cookiebox = new ccookiebox();
}
return *(ccookiebox::cookiebox);
};
/**
*
*/
void
handle_packet_in(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) {
if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {
return;
}
cookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg);
};
/**
*
*/
void
handle_flow_removed(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) {
if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {
return;
}
cookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg);
};
private:
friend class ccookie_owner;
/**
*
*/
void
deregister_cookie_owner(ccookie_owner* owner) {
std::map<uint64_t, ccookie_owner*>::iterator it;
while ((it = find_if(cookiestore.begin(), cookiestore.end(),
ccookie_find_by_owner(owner))) != cookiestore.end()) {
cookiestore.erase(it);
}
};
/**
*
*/
uint64_t
acquire_cookie(ccookie_owner* owner) {
do {
next_cookie++;
} while (cookiestore.find(next_cookie) != cookiestore.end());
cookiestore[next_cookie] = owner;
return next_cookie;
};
/**
*
*/
void
release_cookie(ccookie_owner* owner, uint64_t cookie) {
if (cookiestore.find(cookie) == cookiestore.end()) {
return;
}
if (cookiestore[cookie] != owner) {
return;
}
cookiestore.erase(cookie);
};
};
}; // end of namespace openflow
}; // end of namespace common
}; // end of namespace roflibs
#endif /* CCOOKIES_HPP_ */
<commit_msg>ccookiebox => added more debug output<commit_after>/*
* ccookies.hpp
*
* Created on: 19.11.2014
* Author: andreas
*/
#ifndef CCOOKIES_HPP_
#define CCOOKIES_HPP_
#include <inttypes.h>
#include <rofl/common/crofdpt.h>
#include <rofl/common/cauxid.h>
#include <rofl/common/crandom.h>
#include <rofl/common/openflow/messages/cofmsg_packet_in.h>
#include <rofl/common/openflow/messages/cofmsg_flow_removed.h>
#include "roflibs/netlink/clogging.hpp"
namespace roflibs {
namespace common {
namespace openflow {
class ccookiebox; // forward declaration, see below
class ccookie_owner {
public:
/**
*
*/
virtual
~ccookie_owner();
public:
/**
*
*/
uint64_t
acquire_cookie();
/**
*
*/
void
release_cookie(uint64_t cookie);
protected:
friend class ccookiebox;
/**
*
*/
virtual void
handle_packet_in(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0;
/**
*
*/
virtual void
handle_flow_removed(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0;
};
class ccookie_find_by_owner {
ccookie_owner* owner;
public:
ccookie_find_by_owner(ccookie_owner* owner) :
owner(owner) {};
bool operator() (const std::pair<uint64_t, ccookie_owner*>& p) {
return (p.second == owner);
};
};
class ccookiebox {
private:
static ccookiebox* cookiebox;
uint64_t next_cookie;
std::map<uint64_t, ccookie_owner*> cookiestore;
ccookiebox() : next_cookie(rofl::crandom(8).uint64()) {};
~ccookiebox() {};
public:
/**
*
*/
static ccookiebox&
get_instance() {
if ((ccookiebox*)0 == ccookiebox::cookiebox) {
ccookiebox::cookiebox = new ccookiebox();
}
return *(ccookiebox::cookiebox);
};
/**
*
*/
void
handle_packet_in(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) {
if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {
rofcore::logging::debug << "[ccookiebox][handle_packet_in] cookie:" << (unsigned long long)msg.get_cookie()
<< " not found, dropping packet" << std::endl;
return;
}
cookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg);
};
/**
*
*/
void
handle_flow_removed(
rofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) {
if (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {
rofcore::logging::debug << "[ccookiebox][handle_flow_removed] cookie:" << (unsigned long long)msg.get_cookie()
<< " not found, dropping packet" << std::endl;
return;
}
cookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg);
};
private:
friend class ccookie_owner;
/**
*
*/
void
deregister_cookie_owner(ccookie_owner* owner) {
std::map<uint64_t, ccookie_owner*>::iterator it;
while ((it = find_if(cookiestore.begin(), cookiestore.end(),
ccookie_find_by_owner(owner))) != cookiestore.end()) {
cookiestore.erase(it);
}
};
/**
*
*/
uint64_t
acquire_cookie(ccookie_owner* owner) {
do {
next_cookie++;
} while (cookiestore.find(next_cookie) != cookiestore.end());
cookiestore[next_cookie] = owner;
return next_cookie;
};
/**
*
*/
void
release_cookie(ccookie_owner* owner, uint64_t cookie) {
if (cookiestore.find(cookie) == cookiestore.end()) {
return;
}
if (cookiestore[cookie] != owner) {
return;
}
cookiestore.erase(cookie);
};
};
}; // end of namespace openflow
}; // end of namespace common
}; // end of namespace roflibs
#endif /* CCOOKIES_HPP_ */
<|endoftext|>
|
<commit_before>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacnuniverselistmodel.h"
#include <QDebug>
#include <QNetworkInterface>
#include "streamingacn.h"
#include "streamcommon.h"
#include "ipaddr.h"
#include "preferences.h"
#include "sacnsocket.h"
#include "consts.h"
sACNUniverseInfo::sACNUniverseInfo(int u)
{
universe = u;
}
sACNUniverseInfo::~sACNUniverseInfo()
{
qDeleteAll(sources);
sources.clear();
sourcesByCid.clear();
}
sACNBasicSourceInfo::sACNBasicSourceInfo(sACNUniverseInfo *p)
{
parent = p;
}
sACNUniverseListModel::sACNUniverseListModel(QObject *parent) : QAbstractItemModel(parent)
{
m_start = MIN_SACN_UNIVERSE;
setStartUniverse(m_start);
m_checkTimeoutTimer = new QTimer(this);
connect(m_checkTimeoutTimer, SIGNAL(timeout()), this, SLOT(checkTimeouts()));
m_checkTimeoutTimer->start(5000);
}
void sACNUniverseListModel::setStartUniverse(int start)
{
QMutexLocker locker(&mutex_readPendingDatagrams);
QNetworkInterface iface = Preferences::getInstance()->networkInterface();
// Limit max value
static const int startMax = (MAX_SACN_UNIVERSE - NUM_UNIVERSES_LISTED) + 1;
if (start > startMax) start = startMax;
beginResetModel();
qDeleteAll(m_universes);
m_universes.clear();
// Destroy all old sockets
qDeleteAll(m_sockets);
m_sockets.clear();
// Listen unicast
m_sockets.push_back(new sACNRxSocket(this));
m_sockets.back()->bindUnicast();
connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
// Listen multicast
m_start = start;
for(int universe=m_start; universe<m_start+NUM_UNIVERSES_LISTED; universe++)
{
CIPAddr addr;
GetUniverseAddress(universe, addr);
m_sockets.push_back(new sACNRxSocket(this));
m_sockets.back()->bindMulticast(universe);
connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
m_universes << new sACNUniverseInfo(universe);
}
endResetModel();
}
int sACNUniverseListModel::rowCount(const QModelIndex &parent) const
{
if(parent.isValid() && parent.internalPointer()==NULL)
{
return m_universes[parent.row()]->sources.count();
}
if(!parent.isValid())
{
return m_universes.count();
}
return 0;
}
int sACNUniverseListModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant sACNUniverseListModel::data(const QModelIndex &index, int role) const
{
if(role==Qt::DisplayRole)
{
if(index.parent().isValid())
{
sACNBasicSourceInfo *info = (sACNBasicSourceInfo *) index.internalPointer();
return tr("%1 (%2)").arg(info->name).arg(info->address.toString());
}
else
return QVariant(tr("Universe %1").arg(index.row() + m_start));
}
return QVariant();
}
QModelIndex sACNUniverseListModel::index(int row, int column, const QModelIndex &parent) const
{
if(!hasIndex(row, column, parent))
return QModelIndex();
if(!parent.isValid()) // This is a root item
return createIndex(row, column);
if(parent.isValid() && !parent.parent().isValid())
{
if(m_universes[parent.row()]->sources.count() >= row)
{
return createIndex(row, column, m_universes[parent.row()]->sources.at(row));
}
}
return QModelIndex();
}
QModelIndex sACNUniverseListModel::parent(const QModelIndex &index) const
{
if(!index.isValid())
return QModelIndex();
sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());
if(i)
{
int parentRow = i->parent->universe - m_start;
return createIndex(parentRow, 0);
}
return QModelIndex();
}
void sACNUniverseListModel::readPendingDatagrams()
{
QMutexLocker locker(&mutex_readPendingDatagrams);
// Check all sockets
foreach (sACNRxSocket* m_socket, m_sockets)
{
while(m_socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(m_socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
m_socket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
// Process the data
CID source_cid;
uint1 start_code;
uint1 sequence;
uint2 universe;
uint2 slot_count;
uint1* pdata;
char source_name [SOURCE_NAME_SIZE];
uint1 priority;
//These only apply to the ratified version of the spec, so we will hardwire
//them to be 0 just in case they never get set.
uint2 reserved = 0;
uint1 options = 0;
uint1 *pbuf = (uint1*)datagram.data();
if(!ValidateStreamHeader(pbuf, datagram.length(), source_cid, source_name, priority,
start_code, reserved, sequence, options, universe, slot_count, pdata))
{
// Recieved a packet but not valid. Log and discard
qDebug() << "Invalid Packet";
continue;
}
sACNBasicSourceInfo *info = 0;
int univIndex = universe - m_start;
if (
(univIndex > m_universes.count())
or (univIndex < 0)
) { continue; }
if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))
{
info = new sACNBasicSourceInfo(m_universes[univIndex]);
info->cid = source_cid;
}
else
{
info = m_universes[univIndex]->sourcesByCid.value(source_cid);
info->timeout.restart();
}
info->address = sender;
info->name = source_name;
if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))
{
// We are adding the source for this universe
QModelIndex parent = index(m_start - universe, 0);
int firstRow = m_universes[univIndex]->sources.count()+1;
int lastRow = firstRow;
beginInsertRows(parent, firstRow, lastRow);
m_universes[univIndex]->sources << info;
m_universes[univIndex]->sourcesByCid[source_cid] = info;
endInsertRows();
}
}
}
}
void sACNUniverseListModel::checkTimeouts()
{
foreach(sACNUniverseInfo *info, m_universes)
{
for(int row=0; row<info->sources.count(); row++)
{
sACNBasicSourceInfo *source = info->sources[row];
if(source->timeout.elapsed() > 5000)
{
beginRemoveRows( createIndex(info->universe - m_start, 0),
row, row);
info->sources.removeAll(source);
info->sourcesByCid.remove(source->cid);
delete source;
endRemoveRows();
}
}
}
}
int sACNUniverseListModel::indexToUniverse(const QModelIndex &index)
{
if(!index.isValid())
return 0;
if(index.internalPointer()==NULL)
{
// root item
return m_start + index.row();
}
sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());
if(i)
{
return i->parent->universe;
}
return 0;
}
<commit_msg>Fix the build for MSVC<commit_after>// Copyright 2016 Tom Barthel-Steer
// http://www.tomsteer.net
//
// 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 "sacnuniverselistmodel.h"
#include <QDebug>
#include <QNetworkInterface>
#include "streamingacn.h"
#include "streamcommon.h"
#include "ipaddr.h"
#include "preferences.h"
#include "sacnsocket.h"
#include "consts.h"
sACNUniverseInfo::sACNUniverseInfo(int u)
{
universe = u;
}
sACNUniverseInfo::~sACNUniverseInfo()
{
qDeleteAll(sources);
sources.clear();
sourcesByCid.clear();
}
sACNBasicSourceInfo::sACNBasicSourceInfo(sACNUniverseInfo *p)
{
parent = p;
}
sACNUniverseListModel::sACNUniverseListModel(QObject *parent) : QAbstractItemModel(parent)
{
m_start = MIN_SACN_UNIVERSE;
setStartUniverse(m_start);
m_checkTimeoutTimer = new QTimer(this);
connect(m_checkTimeoutTimer, SIGNAL(timeout()), this, SLOT(checkTimeouts()));
m_checkTimeoutTimer->start(5000);
}
void sACNUniverseListModel::setStartUniverse(int start)
{
QMutexLocker locker(&mutex_readPendingDatagrams);
QNetworkInterface iface = Preferences::getInstance()->networkInterface();
// Limit max value
static const int startMax = (MAX_SACN_UNIVERSE - NUM_UNIVERSES_LISTED) + 1;
if (start > startMax) start = startMax;
beginResetModel();
qDeleteAll(m_universes);
m_universes.clear();
// Destroy all old sockets
qDeleteAll(m_sockets);
m_sockets.clear();
// Listen unicast
m_sockets.push_back(new sACNRxSocket(this));
m_sockets.back()->bindUnicast();
connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
// Listen multicast
m_start = start;
for(int universe=m_start; universe<m_start+NUM_UNIVERSES_LISTED; universe++)
{
CIPAddr addr;
GetUniverseAddress(universe, addr);
m_sockets.push_back(new sACNRxSocket(this));
m_sockets.back()->bindMulticast(universe);
connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
m_universes << new sACNUniverseInfo(universe);
}
endResetModel();
}
int sACNUniverseListModel::rowCount(const QModelIndex &parent) const
{
if(parent.isValid() && parent.internalPointer()==NULL)
{
return m_universes[parent.row()]->sources.count();
}
if(!parent.isValid())
{
return m_universes.count();
}
return 0;
}
int sACNUniverseListModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant sACNUniverseListModel::data(const QModelIndex &index, int role) const
{
if(role==Qt::DisplayRole)
{
if(index.parent().isValid())
{
sACNBasicSourceInfo *info = (sACNBasicSourceInfo *) index.internalPointer();
return tr("%1 (%2)").arg(info->name).arg(info->address.toString());
}
else
return QVariant(tr("Universe %1").arg(index.row() + m_start));
}
return QVariant();
}
QModelIndex sACNUniverseListModel::index(int row, int column, const QModelIndex &parent) const
{
if(!hasIndex(row, column, parent))
return QModelIndex();
if(!parent.isValid()) // This is a root item
return createIndex(row, column);
if(parent.isValid() && !parent.parent().isValid())
{
if(m_universes[parent.row()]->sources.count() >= row)
{
return createIndex(row, column, m_universes[parent.row()]->sources.at(row));
}
}
return QModelIndex();
}
QModelIndex sACNUniverseListModel::parent(const QModelIndex &index) const
{
if(!index.isValid())
return QModelIndex();
sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());
if(i)
{
int parentRow = i->parent->universe - m_start;
return createIndex(parentRow, 0);
}
return QModelIndex();
}
void sACNUniverseListModel::readPendingDatagrams()
{
QMutexLocker locker(&mutex_readPendingDatagrams);
// Check all sockets
foreach (sACNRxSocket* m_socket, m_sockets)
{
while(m_socket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(m_socket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
m_socket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
// Process the data
CID source_cid;
uint1 start_code;
uint1 sequence;
uint2 universe;
uint2 slot_count;
uint1* pdata;
char source_name [SOURCE_NAME_SIZE];
uint1 priority;
//These only apply to the ratified version of the spec, so we will hardwire
//them to be 0 just in case they never get set.
uint2 reserved = 0;
uint1 options = 0;
uint1 *pbuf = (uint1*)datagram.data();
if(!ValidateStreamHeader(pbuf, datagram.length(), source_cid, source_name, priority,
start_code, reserved, sequence, options, universe, slot_count, pdata))
{
// Recieved a packet but not valid. Log and discard
qDebug() << "Invalid Packet";
continue;
}
sACNBasicSourceInfo *info = 0;
int univIndex = universe - m_start;
if (
(univIndex > m_universes.count())
|| (univIndex < 0)
) { continue; }
if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))
{
info = new sACNBasicSourceInfo(m_universes[univIndex]);
info->cid = source_cid;
}
else
{
info = m_universes[univIndex]->sourcesByCid.value(source_cid);
info->timeout.restart();
}
info->address = sender;
info->name = source_name;
if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))
{
// We are adding the source for this universe
QModelIndex parent = index(m_start - universe, 0);
int firstRow = m_universes[univIndex]->sources.count()+1;
int lastRow = firstRow;
beginInsertRows(parent, firstRow, lastRow);
m_universes[univIndex]->sources << info;
m_universes[univIndex]->sourcesByCid[source_cid] = info;
endInsertRows();
}
}
}
}
void sACNUniverseListModel::checkTimeouts()
{
foreach(sACNUniverseInfo *info, m_universes)
{
for(int row=0; row<info->sources.count(); row++)
{
sACNBasicSourceInfo *source = info->sources[row];
if(source->timeout.elapsed() > 5000)
{
beginRemoveRows( createIndex(info->universe - m_start, 0),
row, row);
info->sources.removeAll(source);
info->sourcesByCid.remove(source->cid);
delete source;
endRemoveRows();
}
}
}
}
int sACNUniverseListModel::indexToUniverse(const QModelIndex &index)
{
if(!index.isValid())
return 0;
if(index.internalPointer()==NULL)
{
// root item
return m_start + index.row();
}
sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());
if(i)
{
return i->parent->universe;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
*
* TransactionParser
* ledger-core
*
* Created by Pierre Pollastri on 27/03/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "TransactionParser.hpp"
#include "utils/DateUtils.hpp"
#define PROXY_PARSE(method, ...) \
auto& currentObject = _hierarchy.top(); \
if (currentObject == "block") { \
return _blockParser.method(__VA_ARGS__); \
} else if (currentObject == "inputs") { \
return _inputParser.method(__VA_ARGS__); \
} else if (currentObject == "outputs") { \
return _outputParser.method(__VA_ARGS__); \
} else \
namespace ledger {
namespace core {
bool TransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
_lastKey = std::string(str, length);
PROXY_PARSE(Key, str, length, copy) {
return true;
}
}
bool TransactionParser::StartObject() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
auto& currentObject = _hierarchy.top();
if (currentObject == "inputs") {
BitcoinLikeBlockchainExplorerInput input;
input.index = _transaction->inputs.size();
_transaction->inputs.push_back(input);
_inputParser.init(&_transaction->inputs.back());
} else if (currentObject == "outputs") {
BitcoinLikeBlockchainExplorerOutput output;
_transaction->outputs.push_back(output);
_outputParser.init(&_transaction->outputs.back());
// Set block height
if (_transaction->block.hasValue()) {
_transaction->outputs.back().blockHeight = _transaction->block.getValue().height;
}
} else if (currentObject == "block") {
BitcoinLikeBlockchainExplorer::Block block;
_transaction->block = Option<BitcoinLikeBlockchainExplorer::Block>(block);
_blockParser.init(&_transaction->block.getValue());
}
return true;
}
bool TransactionParser::EndObject(rapidjson::SizeType memberCount) {
auto& currentObject = _hierarchy.top();
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool TransactionParser::StartArray() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
_arrayDepth += 1;
return true;
}
bool TransactionParser::EndArray(rapidjson::SizeType elementCount) {
_arrayDepth -= 1;
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool TransactionParser::Null() {
PROXY_PARSE(Null) {
return true;
}
}
bool TransactionParser::Bool(bool b) {
PROXY_PARSE(Bool, b) {
return true;
}
}
bool TransactionParser::Int(int i) {
return Uint64(i);
}
bool TransactionParser::Uint(unsigned i) {
return Uint64(i);
}
bool TransactionParser::Int64(int64_t i) {
return Uint64(i);
}
bool TransactionParser::Uint64(uint64_t i) {
PROXY_PARSE(Uint64, i) {
return true;
}
}
bool TransactionParser::Double(double d) {
PROXY_PARSE(Double, d) {
return true;
}
}
bool TransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(RawNumber, str, length, copy) {
std::string number(str, length);
BigInt value = BigInt::fromString(number);
if (_lastKey == "lock_time") {
_transaction->lockTime = value.toUint64();
} else if (_lastKey == "fees") {
_transaction->fees = Option<BigInt>(value);
} else if (_lastKey == "confirmations") {
_transaction->confirmations = value.toUint64();
}
return true;
}
}
bool TransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(String, str, length, copy) {
std::string value(str, length);
if (_lastKey == "hash") {
_transaction->hash = value;
} else if (_lastKey == "received_at") {
_transaction->receivedAt = DateUtils::fromJSON(value);
}
return true;
}
}
TransactionParser::TransactionParser(std::string& lastKey) :
_lastKey(lastKey), _blockParser(lastKey), _inputParser(lastKey), _outputParser(lastKey)
{
_arrayDepth = 0;
}
void TransactionParser::init(BitcoinLikeBlockchainExplorerTransaction *transaction) {
_transaction = transaction;
}
}
}<commit_msg>COIN-1420: use of tx id field instead of hash for v3 btc explorers<commit_after>/*
*
* TransactionParser
* ledger-core
*
* Created by Pierre Pollastri on 27/03/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include "TransactionParser.hpp"
#include "utils/DateUtils.hpp"
#define PROXY_PARSE(method, ...) \
auto& currentObject = _hierarchy.top(); \
if (currentObject == "block") { \
return _blockParser.method(__VA_ARGS__); \
} else if (currentObject == "inputs") { \
return _inputParser.method(__VA_ARGS__); \
} else if (currentObject == "outputs") { \
return _outputParser.method(__VA_ARGS__); \
} else \
namespace ledger {
namespace core {
bool TransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
_lastKey = std::string(str, length);
PROXY_PARSE(Key, str, length, copy) {
return true;
}
}
bool TransactionParser::StartObject() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
auto& currentObject = _hierarchy.top();
if (currentObject == "inputs") {
BitcoinLikeBlockchainExplorerInput input;
input.index = _transaction->inputs.size();
_transaction->inputs.push_back(input);
_inputParser.init(&_transaction->inputs.back());
} else if (currentObject == "outputs") {
BitcoinLikeBlockchainExplorerOutput output;
_transaction->outputs.push_back(output);
_outputParser.init(&_transaction->outputs.back());
// Set block height
if (_transaction->block.hasValue()) {
_transaction->outputs.back().blockHeight = _transaction->block.getValue().height;
}
} else if (currentObject == "block") {
BitcoinLikeBlockchainExplorer::Block block;
_transaction->block = Option<BitcoinLikeBlockchainExplorer::Block>(block);
_blockParser.init(&_transaction->block.getValue());
}
return true;
}
bool TransactionParser::EndObject(rapidjson::SizeType memberCount) {
auto& currentObject = _hierarchy.top();
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool TransactionParser::StartArray() {
if (_arrayDepth == 0) {
_hierarchy.push(_lastKey);
}
_arrayDepth += 1;
return true;
}
bool TransactionParser::EndArray(rapidjson::SizeType elementCount) {
_arrayDepth -= 1;
if (_arrayDepth == 0) {
_hierarchy.pop();
}
return true;
}
bool TransactionParser::Null() {
PROXY_PARSE(Null) {
return true;
}
}
bool TransactionParser::Bool(bool b) {
PROXY_PARSE(Bool, b) {
return true;
}
}
bool TransactionParser::Int(int i) {
return Uint64(i);
}
bool TransactionParser::Uint(unsigned i) {
return Uint64(i);
}
bool TransactionParser::Int64(int64_t i) {
return Uint64(i);
}
bool TransactionParser::Uint64(uint64_t i) {
PROXY_PARSE(Uint64, i) {
return true;
}
}
bool TransactionParser::Double(double d) {
PROXY_PARSE(Double, d) {
return true;
}
}
bool TransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(RawNumber, str, length, copy) {
std::string number(str, length);
BigInt value = BigInt::fromString(number);
if (_lastKey == "lock_time") {
_transaction->lockTime = value.toUint64();
} else if (_lastKey == "fees") {
_transaction->fees = Option<BigInt>(value);
} else if (_lastKey == "confirmations") {
_transaction->confirmations = value.toUint64();
}
return true;
}
}
bool TransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {
PROXY_PARSE(String, str, length, copy) {
std::string value(str, length);
if (_lastKey == "hash") {
if (_transaction->hash.empty()) {
_transaction->hash = value;
}
}
else if (_lastKey == "id") {
_transaction->hash = value;
}
else if (_lastKey == "received_at") {
_transaction->receivedAt = DateUtils::fromJSON(value);
}
return true;
}
}
TransactionParser::TransactionParser(std::string& lastKey) :
_lastKey(lastKey), _blockParser(lastKey), _inputParser(lastKey), _outputParser(lastKey)
{
_arrayDepth = 0;
}
void TransactionParser::init(BitcoinLikeBlockchainExplorerTransaction *transaction) {
_transaction = transaction;
}
}
}<|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 "otbWrapperQtWidgetStringListParameter.h"
namespace otb
{
namespace Wrapper
{
QtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m)
: QtWidgetParameterBase(param, m),
m_StringListParam(param)
{
connect( this, SIGNAL(Change()), GetModel(), SLOT(NotifyUpdate()) );
}
QtWidgetStringListParameter::~QtWidgetStringListParameter()
{
}
void QtWidgetStringListParameter::DoUpdateGUI()
{
m_LineEditList.clear();
m_StringLayout = new QVBoxLayout();
for(unsigned int i=0; i<m_StringListParam->GetValue().size(); i++)
{
QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();
stringSelection->setFixedHeight( 30 );
QString val(m_StringListParam->GetNthElement(i).c_str());
stringSelection->GetInput()->setText( m_StringListParam->GetNthElement(i).c_str() ); //val );
m_StringLayout->addWidget( stringSelection );
m_LineEditList.push_back(stringSelection);
connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) );
connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );
}
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
}
void QtWidgetStringListParameter::DoCreateWidget()
{
m_LineEditList.clear();
const unsigned int sp(2);
const unsigned int buttonSize(30);
// Global layout
QHBoxLayout * hLayout = new QHBoxLayout;
hLayout->setSpacing(sp);
hLayout->setContentsMargins(sp, sp, sp, sp);
if( m_StringListParam->GetRole() != Role_Output )
{
// Button layout
QVBoxLayout * buttonLayout = new QVBoxLayout;
buttonLayout->setSpacing(sp);
buttonLayout->setContentsMargins(sp, sp, sp, sp);
QHBoxLayout * addSupLayout = new QHBoxLayout;
addSupLayout->setSpacing(sp);
addSupLayout->setContentsMargins(sp, sp, sp, sp);
QHBoxLayout * upDownLayout = new QHBoxLayout;
upDownLayout->setSpacing(sp);
upDownLayout->setContentsMargins(sp, sp, sp, sp);
// Add file button
QPushButton * addButton = new QPushButton;
addButton->setText("+");
addButton->setFixedWidth(buttonSize);
addButton->setToolTip("Add a string selector...");
connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) );
addSupLayout->addWidget(addButton);
// Supress file button
QPushButton * supButton = new QPushButton;
supButton->setText("-");
supButton->setFixedWidth(buttonSize);
supButton->setToolTip("Supress the selected string...");
connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) );
addSupLayout->addWidget(supButton);
buttonLayout->addLayout(addSupLayout);
// Up file edit
QPushButton * upButton = new QPushButton;
upButton->setText("Up");
upButton->setFixedWidth(buttonSize);
upButton->setToolTip("Up the selected string in the list...");
connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) );
upDownLayout->addWidget(upButton);
// Down file edit
QPushButton * downButton = new QPushButton;
downButton->setText("Down");
downButton->setFixedWidth(buttonSize);
downButton->setToolTip("Down the selected string in the list...");
connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) );
upDownLayout->addWidget(downButton);
buttonLayout->addLayout(upDownLayout);
// Erase file edit
QPushButton * eraseButton = new QPushButton;
eraseButton->setText("Erase");
eraseButton->setFixedWidth(2*(buttonSize+sp));
eraseButton->setToolTip("Erase the selected string of the list...");
connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) );
buttonLayout->addWidget(eraseButton);
hLayout->addLayout(buttonLayout);
}
QVBoxLayout * fileLayout = new QVBoxLayout();
fileLayout->setSpacing(0);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(fileLayout);
QScrollArea * scroll = new QScrollArea();
scroll->setWidget(mainGroup);
scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidgetResizable(true);
hLayout->addWidget(scroll);
this->setLayout(hLayout);
//m_StringLayout = fileLayout;
m_HLayout = hLayout;
m_Scroll = scroll;
}
void
QtWidgetStringListParameter::UpdateStringList()
{
// save value
for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ )
{
m_StringListParam->SetNthElement(j, m_LineEditList[j]->GetStringName());
}
emit Change();
}
void
QtWidgetStringListParameter::UpString()
{
if(m_LineEditList.size() < 2 )
return;
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(2);
// Map link between old and new index in the list
std::map<unsigned int, unsigned int> idMap;
// Init map
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
idMap[i] = i;
}
// If the first item is checked, uncheck it...
// It won't be moved
if( m_LineEditList[0]->IsChecked() )
{
m_LineEditList[0]->SetChecked(false);
}
// If other item are checked, up the index
// Starts at 1 because the first item mustn't move
for(unsigned int i=1; i<m_LineEditList.size(); i++ )
{
if( m_LineEditList[i]->IsChecked() )
{
unsigned int tmp = idMap[i];
idMap[i] = i-1;
idMap[idMap[i-1]] = tmp;
}
}
this->UpdateStringList( idMap );
this->RecreateStringList();
}
void
QtWidgetStringListParameter::DownString()
{
if(m_LineEditList.size() < 2 )
return;
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
// Map link between old and new index in the list
std::map<unsigned int, unsigned int> idMap;
// Init map
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
idMap[i] = i;
}
// If the last item is checked, uncheck it...
// It won't be moved
if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() )
{
m_LineEditList[m_LineEditList.size()-1]->SetChecked(false);
}
// If other item are checked, up the index
// Stops at size-1 because the last item mustn't move
for(int i=m_LineEditList.size()-2; i>=0; i-- )
{
if( m_LineEditList[i]->IsChecked() )
{
unsigned int tmp = idMap[i];
idMap[i] = i+1;
idMap[idMap[i+1]] = tmp;
}
}
this->UpdateStringList( idMap );
this->RecreateStringList();
}
void
QtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap )
{
std::vector<QtStringSelectionWidget *> tmpList;
// Keys become values and inverse
std::map<unsigned int, unsigned int> idMapBis;
for(unsigned int i=0; i<idMap.size(); i++ )
{
idMapBis[ idMap[i] ] = i;
}
// Create the new item list
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] );
tmpList.push_back(m_LineEditList[ idMapBis[i] ]);
}
m_LineEditList = tmpList;
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
// notify of value change
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
void QtWidgetStringListParameter::SetString(const QString& value)
{
m_StringListParam->AddString(value.toAscii().constData());
m_StringListParam->SetUserValue(true);
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
void
QtWidgetStringListParameter::AddString()
{
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
m_StringLayout->addWidget( m_LineEditList[i] );
}
QtStringSelectionWidget * stringInput = new QtStringSelectionWidget();
stringInput->setFixedHeight( 30 );
m_StringLayout->addWidget( stringInput );
m_LineEditList.push_back(stringInput);
m_StringListParam->AddNullElement();
connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()));
connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
}
void
QtWidgetStringListParameter::SupressString()
{
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
std::vector<QtStringSelectionWidget *> tmpList;
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
if( !m_LineEditList[i]->IsChecked() )
{
m_StringLayout->addWidget( m_LineEditList[i] );
tmpList.push_back(m_LineEditList[i]);
}
}
m_LineEditList = tmpList;
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
this->RecreateStringList();
}
void
QtWidgetStringListParameter::EraseString()
{
m_LineEditList.clear();
m_StringLayout = new QVBoxLayout();
QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();
stringSelection->setFixedHeight( 30 );
m_StringLayout->addWidget( stringSelection );
m_LineEditList.push_back(stringSelection);
m_StringListParam->AddNullElement();
connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) );
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
this->RecreateStringList();
}
void QtWidgetStringListParameter::RecreateStringList()
{
// save value
m_StringListParam->ClearValue();
if( m_LineEditList.size() != 0)
{
for(unsigned int j=0; j<m_LineEditList.size(); j++ )
{
m_StringListParam->AddString(m_LineEditList[j]->GetStringName());
}
emit Change();
// notify of value change
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
}
}
}
<commit_msg>ENH: adapted QtWidgetStringListParameter to StringSelectionWidget revamp<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 "otbWrapperQtWidgetStringListParameter.h"
namespace otb
{
namespace Wrapper
{
QtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m)
: QtWidgetParameterBase(param, m),
m_StringListParam(param)
{
/*
connect( this,
SIGNAL(Change()),
GetModel(),
SLOT(NotifyUpdate()) );
*/
}
QtWidgetStringListParameter::~QtWidgetStringListParameter()
{
}
void QtWidgetStringListParameter::DoUpdateGUI()
{
m_LineEditList.clear();
m_StringLayout = new QVBoxLayout();
for(unsigned int i=0; i<m_StringListParam->GetValue().size(); i++)
{
QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();
stringSelection->setFixedHeight( 30 );
stringSelection->SetText( m_StringListParam->GetNthElement(i).c_str() );
m_StringLayout->addWidget( stringSelection );
m_LineEditList.push_back(stringSelection);
connect( stringSelection,
SIGNAL( InternalQLineEditEditionFinished() ),
this,
SLOT( UpdateStringList() )
);
connect( stringSelection,
SIGNAL(InternalQLineEditEditionFinished()),
GetModel(),
SLOT(NotifyUpdate())
);
std::cout << "NotifyUpdate" << std::endl;
}
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
}
void QtWidgetStringListParameter::DoCreateWidget()
{
m_LineEditList.clear();
const unsigned int sp(2);
const unsigned int buttonSize(30);
// Global layout
QHBoxLayout * hLayout = new QHBoxLayout;
hLayout->setSpacing(sp);
hLayout->setContentsMargins(sp, sp, sp, sp);
if( m_StringListParam->GetRole() != Role_Output )
{
// Button layout
QVBoxLayout * buttonLayout = new QVBoxLayout;
buttonLayout->setSpacing(sp);
buttonLayout->setContentsMargins(sp, sp, sp, sp);
QHBoxLayout * addSupLayout = new QHBoxLayout;
addSupLayout->setSpacing(sp);
addSupLayout->setContentsMargins(sp, sp, sp, sp);
QHBoxLayout * upDownLayout = new QHBoxLayout;
upDownLayout->setSpacing(sp);
upDownLayout->setContentsMargins(sp, sp, sp, sp);
// Add file button
QPushButton * addButton = new QPushButton;
addButton->setText("+");
addButton->setFixedWidth(buttonSize);
addButton->setToolTip("Add a string selector...");
connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) );
addSupLayout->addWidget(addButton);
// Supress file button
QPushButton * supButton = new QPushButton;
supButton->setText("-");
supButton->setFixedWidth(buttonSize);
supButton->setToolTip("Supress the selected string...");
connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) );
addSupLayout->addWidget(supButton);
buttonLayout->addLayout(addSupLayout);
// Up file edit
QPushButton * upButton = new QPushButton;
upButton->setText("Up");
upButton->setFixedWidth(buttonSize);
upButton->setToolTip("Up the selected string in the list...");
connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) );
upDownLayout->addWidget(upButton);
// Down file edit
QPushButton * downButton = new QPushButton;
downButton->setText("Down");
downButton->setFixedWidth(buttonSize);
downButton->setToolTip("Down the selected string in the list...");
connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) );
upDownLayout->addWidget(downButton);
buttonLayout->addLayout(upDownLayout);
// Erase file edit
QPushButton * eraseButton = new QPushButton;
eraseButton->setText("Erase");
eraseButton->setFixedWidth(2*(buttonSize+sp));
eraseButton->setToolTip("Erase the selected string of the list...");
connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) );
buttonLayout->addWidget(eraseButton);
hLayout->addLayout(buttonLayout);
}
QVBoxLayout * fileLayout = new QVBoxLayout();
fileLayout->setSpacing(0);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(fileLayout);
QScrollArea * scroll = new QScrollArea();
scroll->setWidget(mainGroup);
scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidgetResizable(true);
hLayout->addWidget(scroll);
this->setLayout(hLayout);
//m_StringLayout = fileLayout;
m_HLayout = hLayout;
m_Scroll = scroll;
}
void
QtWidgetStringListParameter::UpdateStringList()
{
// save value
for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ )
{
m_StringListParam->SetNthElement(j, m_LineEditList[j]->ToStdString());
}
// notify model text changed
emit Change();
}
void
QtWidgetStringListParameter::UpString()
{
if(m_LineEditList.size() < 2 )
return;
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(2);
// Map link between old and new index in the list
std::map<unsigned int, unsigned int> idMap;
// Init map
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
idMap[i] = i;
}
// If the first item is checked, uncheck it...
// It won't be moved
if( m_LineEditList[0]->IsChecked() )
{
m_LineEditList[0]->SetChecked(false);
}
// If other item are checked, up the index
// Starts at 1 because the first item mustn't move
for(unsigned int i=1; i<m_LineEditList.size(); i++ )
{
if( m_LineEditList[i]->IsChecked() )
{
unsigned int tmp = idMap[i];
idMap[i] = i-1;
idMap[idMap[i-1]] = tmp;
}
}
this->UpdateStringList( idMap );
this->RecreateStringList();
}
void
QtWidgetStringListParameter::DownString()
{
if(m_LineEditList.size() < 2 )
return;
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
// Map link between old and new index in the list
std::map<unsigned int, unsigned int> idMap;
// Init map
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
idMap[i] = i;
}
// If the last item is checked, uncheck it...
// It won't be moved
if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() )
{
m_LineEditList[m_LineEditList.size()-1]->SetChecked(false);
}
// If other item are checked, up the index
// Stops at size-1 because the last item mustn't move
for(int i=m_LineEditList.size()-2; i>=0; i-- )
{
if( m_LineEditList[i]->IsChecked() )
{
unsigned int tmp = idMap[i];
idMap[i] = i+1;
idMap[idMap[i+1]] = tmp;
}
}
this->UpdateStringList( idMap );
this->RecreateStringList();
}
void
QtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap )
{
std::vector<QtStringSelectionWidget *> tmpList;
// Keys become values and inverse
std::map<unsigned int, unsigned int> idMapBis;
for(unsigned int i=0; i<idMap.size(); i++ )
{
idMapBis[ idMap[i] ] = i;
}
// Create the new item list
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] );
tmpList.push_back(m_LineEditList[ idMapBis[i] ]);
}
m_LineEditList = tmpList;
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
// notify of value change
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
void QtWidgetStringListParameter::SetString(const QString& value)
{
m_StringListParam->AddString(value.toAscii().constData());
m_StringListParam->SetUserValue(true);
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
void
QtWidgetStringListParameter::AddString()
{
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
m_StringLayout->addWidget( m_LineEditList[i] );
}
QtStringSelectionWidget * stringInput = new QtStringSelectionWidget();
stringInput->setFixedHeight( 30 );
m_StringLayout->addWidget( stringInput );
m_LineEditList.push_back(stringInput);
m_StringListParam->AddNullElement();
connect( stringInput,
SIGNAL(InternalQLineEditEditionFinished()),
this,
SLOT(UpdateStringList()));
connect( stringInput,
SIGNAL(InternalQLineEditEditionFinished()),
GetModel(),
SLOT(NotifyUpdate()) );
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
}
void
QtWidgetStringListParameter::SupressString()
{
m_StringLayout = new QVBoxLayout();
m_StringLayout->setSpacing(0);
std::vector<QtStringSelectionWidget *> tmpList;
for(unsigned int i=0; i<m_LineEditList.size(); i++ )
{
if( !m_LineEditList[i]->IsChecked() )
{
m_StringLayout->addWidget( m_LineEditList[i] );
tmpList.push_back(m_LineEditList[i]);
}
}
m_LineEditList = tmpList;
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
this->RecreateStringList();
}
void
QtWidgetStringListParameter::EraseString()
{
m_LineEditList.clear();
m_StringLayout = new QVBoxLayout();
QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();
stringSelection->setFixedHeight( 30 );
m_StringLayout->addWidget( stringSelection );
m_LineEditList.push_back(stringSelection);
m_StringListParam->AddNullElement();
connect( stringSelection,
SIGNAL(InternalQLineEditEditionFinished()),
this,
SLOT(UpdateStringList()) );
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(m_StringLayout);
m_Scroll->setWidget(mainGroup);
this->update();
this->RecreateStringList();
}
void QtWidgetStringListParameter::RecreateStringList()
{
// save value
m_StringListParam->ClearValue();
if( m_LineEditList.size() != 0)
{
for(unsigned int j=0; j<m_LineEditList.size(); j++ )
{
m_StringListParam->AddString(m_LineEditList[j]->ToStdString());
}
emit Change();
// notify of value change
QString key( m_StringListParam->GetKey() );
emit ParameterChanged(key);
}
}
}
}
<|endoftext|>
|
<commit_before>// ヘッダのインクルード
#include <iostream> // C++標準入出力
#include <cstring> // C文字列処理
// クラスclass_profileの定義
class class_profile{ // 簡易名簿
// privateメンバ
private: // このクラス内部からのみアクセス可.
// privateメンバ変数
char name[32]; // 名前
int age; // 年齢
char address[128]; // 住所
// publicメンバ
public: // このクラスの外部からもアクセス可.
// コンストラクタ
class_profile(); // 各メンバの初期化処理を行うコンストラクタclass_profile
// publicメンバ関数
void input(); // 名前(name), 年齢(age), 住所(address)の入力.
void output(); // 名前(name), 年齢(age), 住所(address)の入力.
};
// class_profileのメンバの定義
// コンストラクタclass_profile()
class_profile::class_profile(){ // name, age, addressの初期化処理
// name, age, addressの初期化
strcpy(name, "(none)"); // 名前が無いことを意味する"(none)"に初期化しておく.
age = -1; // 年齢が無いことを意味する-1に初期化しておく.
strcpy(address, "(none)"); // 住所が無いことを意味する"(none")に初期化しておく.
}
// メンバ関数input()
void class_profile::input(){ // name, age, addressの入力.
// name, age, addressの入力.
std::cout << "name: "; // nameの入力フォーム
std::cin >> name; // 入力された文字列をnameに格納.
std::cout << "age: "; // ageの入力フォーム
std::cin >> age; // 入力された整数をageに格納.
std::cout << "address: "; // addressの入力フォーム
std::cin >> address; // 入力された文字列をaddressに格納.
}
// メンバ関数output()
void class_profile::output(){ // name, age, addressの出力.
// name, age, addressの出力.
std::cout << "name: " << name << std::endl; // nameの内容を出力.
std::cout << "age: " << age << std::endl; // ageの内容を出力.
std::cout << "address: " << address << std::endl; // addressの内容を出力.
}
// main関数の定義
int main(){
// オブジェクトの宣言
class_profile prof; // class_profileのオブジェクトprofを宣言, この場合はここでコンストラクタが呼ばれる.
// profの中身がコンストラクタによって初期化されているか確認.
prof.output(); // output()メンバ関数でデータを出力する.
// 1行空ける.
std::cout << std::endl; // std::endlで1行空ける.
// profに名簿データを入力.
prof.input(); // input()メンバ関数でデータを入力する.
// 1行空ける.
std::cout << std::endl; // std::endlで1行空ける.
// profの名簿データを出力.
prof.output(); // output()メンバ関数でデータを出力する.
// プログラムの終了
return 0;
}
<commit_msg>fixed comment<commit_after>// ヘッダのインクルード
#include <iostream> // C++標準入出力
#include <cstring> // C文字列処理
// クラスclass_profileの定義
class class_profile{ // 簡易名簿
// privateメンバ
private: // このクラス内部からのみアクセス可.
// privateメンバ変数
char name[32]; // 名前
int age; // 年齢
char address[128]; // 住所
// publicメンバ
public: // このクラスの外部からもアクセス可.
// コンストラクタ
class_profile(); // 各メンバの初期化処理を行うコンストラクタclass_profile
// publicメンバ関数
void input(); // 名前(name), 年齢(age), 住所(address)の入力.
void output(); // 名前(name), 年齢(age), 住所(address)の出力.
};
// class_profileのメンバの定義
// コンストラクタclass_profile()
class_profile::class_profile(){ // name, age, addressの初期化処理
// name, age, addressの初期化
strcpy(name, "(none)"); // 名前が無いことを意味する"(none)"に初期化しておく.
age = -1; // 年齢が無いことを意味する-1に初期化しておく.
strcpy(address, "(none)"); // 住所が無いことを意味する"(none")に初期化しておく.
}
// メンバ関数input()
void class_profile::input(){ // name, age, addressの入力.
// name, age, addressの入力.
std::cout << "name: "; // nameの入力フォーム
std::cin >> name; // 入力された文字列をnameに格納.
std::cout << "age: "; // ageの入力フォーム
std::cin >> age; // 入力された整数をageに格納.
std::cout << "address: "; // addressの入力フォーム
std::cin >> address; // 入力された文字列をaddressに格納.
}
// メンバ関数output()
void class_profile::output(){ // name, age, addressの出力.
// name, age, addressの出力.
std::cout << "name: " << name << std::endl; // nameの内容を出力.
std::cout << "age: " << age << std::endl; // ageの内容を出力.
std::cout << "address: " << address << std::endl; // addressの内容を出力.
}
// main関数の定義
int main(){
// オブジェクトの宣言
class_profile prof; // class_profileのオブジェクトprofを宣言, この場合はここでコンストラクタが呼ばれる.
// profの中身がコンストラクタによって初期化されているか確認.
prof.output(); // output()メンバ関数でデータを出力する.
// 1行空ける.
std::cout << std::endl; // std::endlで1行空ける.
// profに名簿データを入力.
prof.input(); // input()メンバ関数でデータを入力する.
// 1行空ける.
std::cout << std::endl; // std::endlで1行空ける.
// profの名簿データを出力.
prof.output(); // output()メンバ関数でデータを出力する.
// プログラムの終了
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2014 Sarah Wong
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 "configuration.h"
#include "ui_configuration.h"
#include <QDebug>
#include <QResource>
#include <portaudiocpp/System.hxx>
#include <portaudiocpp/SystemHostApiIterator.hxx>
#include <portaudiocpp/SystemDeviceIterator.hxx>
#include "tinyscheme/scheme-private.h"
#include "tinyscheme/scheme.h"
namespace {
template <class IndexMapType, class ItemIter, class ItemType, class Callable1,
class Callable2>
static void insertWithDefault(QComboBox *comboBox, IndexMapType &map,
ItemIter begin, ItemIter end,
ItemType& defaultItem,
Callable1 stringGenerator,
Callable2 mapItemGenerator) {
int itemPosition = 0;
comboBox->clear();
map.clear();
{
map[itemPosition] = mapItemGenerator(defaultItem);
comboBox->insertItem(itemPosition++,
QLatin1String("Default: ") + stringGenerator(defaultItem));
}
comboBox->insertSeparator(itemPosition++);
while (begin != end) {
ItemType& item = *begin;
map[itemPosition] = mapItemGenerator(item);
comboBox->insertItem(itemPosition++, stringGenerator(item));
++begin;
}
}
struct GetDataFromResource {
GetDataFromResource(const char *file)
{
QResource resource(file);
Q_ASSERT(resource.isValid());
if (resource.isCompressed())
m_byteArray = qUncompress(resource.data(), resource.size());
else
m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size());
}
const QByteArray& byteArray() const { return m_byteArray; }
QByteArray m_byteArray;
};
} // namespace anonymous
Configuration::Configuration(QWidget *parent) :
QDialog(parent),
ui(new Ui::Configuration)
{
ui->setupUi(this);
GetDataFromResource defaultConfigScm(":/tinyscheme/default-config.scm");
ui->txtConfig->setPlainText(
QString::fromUtf8(defaultConfigScm.byteArray().data(),
defaultConfigScm.byteArray().size()));
portaudio::System& sys = portaudio::System::instance();
insertWithDefault(
ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(),
sys.hostApisEnd(), sys.defaultHostApi(),
[](portaudio::HostApi &hostApi) { return hostApi.name(); },
[](portaudio::HostApi &hostApi) { return hostApi.typeId(); });
}
PaDeviceIndex Configuration::getDeviceIndex() const
{
auto index = ui->cmbInputDevice->currentIndex();
Q_ASSERT(index != -1);
return m_indexToDeviceIndex[index];
}
void Configuration::on_cmbAudioHost_currentIndexChanged(int index)
{
if (index == -1)
return;
portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId(
m_indexToHostApiTypeId[index]);
insertWithDefault(
ui->cmbInputDevice, m_indexToDeviceIndex,
hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(),
[](portaudio::Device &device) { return device.name(); },
[](portaudio::Device &device) { return device.index(); });
}
namespace {
struct Ptr {
scheme *sc_;
pointer p_;
Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {}
#define P(v) Ptr(sc_, v)
Ptr nil () { return P(sc_->NIL); }
bool is_nil () { return p_ == sc_->NIL; }
bool is_string () { return sc_->vptr->is_string(p_); }
char *string_value() { return sc_->vptr->string_value(p_); }
bool is_number () { return sc_->vptr->is_number(p_); }
num nvalue () { return sc_->vptr->nvalue(p_); }
long ivalue () { return sc_->vptr->ivalue(p_); }
double rvalue () { return sc_->vptr->rvalue(p_); }
bool is_integer () { return sc_->vptr->is_integer(p_); }
bool is_real () { return sc_->vptr->is_real(p_); }
bool is_character () { return sc_->vptr->is_character(p_); }
long charvalue () { return sc_->vptr->charvalue(p_); }
bool is_list () { return sc_->vptr->is_list(sc_, p_); }
bool is_vector () { return sc_->vptr->is_vector(p_); }
int list_length () { return sc_->vptr->list_length(sc_, p_); }
long vector_length() { return sc_->vptr->vector_length(p_); }
Ptr vector_elem (int ielem) { return P(sc_->vptr->vector_elem(p_, ielem)); }
bool is_pair () { return sc_->vptr->is_pair(p_); }
Ptr car () { return P(sc_->vptr->pair_car(p_)); }
Ptr cdr () { return P(sc_->vptr->pair_cdr(p_)); }
bool is_symbol () { return sc_->vptr->is_symbol(p_); }
char *symname () { return sc_->vptr->symname(p_); }
#undef P
};
struct Config {
Config(const char *configScript) : sc_(scheme_init_new())
{
Q_ASSERT(sc_ != nullptr);
scheme_set_output_port_file(sc_, stdout);
loadResource(":/tinyscheme/init.scm");
loadResource(":/tinyscheme/config-helper.scm");
read_eval("(begin (display 1337) (newline))");
scheme_load_string(sc_, configScript);
if (sc_->retcode != 0) qDebug() << "Scheme failed" << __LINE__;
pointer ret = read_eval("(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))");
qDebug() << sc_->vptr->ivalue(ret);
}
void loadResource(const char *resource)
{
GetDataFromResource gdfr(resource);
scheme_load_string(sc_, gdfr.byteArray().data());
}
pointer read_eval(const char* script)
{
// tinyscheme bug: When executing
//
// (read (open-input-string script))
//
// sc_->inport needs to be set, or there will be an error when
// read is restoring the previous inport value when returning.
scheme_set_input_port_file(sc_, stdin); // TODO stdin?
pointer fun = scheme_eval(sc_, mk_symbol(sc_, "read-eval"));
pointer arg = mk_string(sc_, script);
return scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0));
}
scheme *sc_;
};
} // namespace anonymous
void Configuration::on_buttonBox_accepted()
{
QString configText = ui->txtConfig->toPlainText();
QByteArray configTextBa = configText.toUtf8();
Config cfg(configTextBa.constData());
emit accept();
}
Configuration::~Configuration()
{
delete ui;
}
<commit_msg>Config read_eval to use new Ptr class!<commit_after>/*
Copyright 2014 Sarah Wong
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 "configuration.h"
#include "ui_configuration.h"
#include <QDebug>
#include <QResource>
#include <portaudiocpp/System.hxx>
#include <portaudiocpp/SystemHostApiIterator.hxx>
#include <portaudiocpp/SystemDeviceIterator.hxx>
#include "tinyscheme/scheme-private.h"
#include "tinyscheme/scheme.h"
namespace {
template <class IndexMapType, class ItemIter, class ItemType, class Callable1,
class Callable2>
static void insertWithDefault(QComboBox *comboBox, IndexMapType &map,
ItemIter begin, ItemIter end,
ItemType& defaultItem,
Callable1 stringGenerator,
Callable2 mapItemGenerator) {
int itemPosition = 0;
comboBox->clear();
map.clear();
{
map[itemPosition] = mapItemGenerator(defaultItem);
comboBox->insertItem(itemPosition++,
QLatin1String("Default: ") + stringGenerator(defaultItem));
}
comboBox->insertSeparator(itemPosition++);
while (begin != end) {
ItemType& item = *begin;
map[itemPosition] = mapItemGenerator(item);
comboBox->insertItem(itemPosition++, stringGenerator(item));
++begin;
}
}
struct GetDataFromResource {
GetDataFromResource(const char *file)
{
QResource resource(file);
Q_ASSERT(resource.isValid());
if (resource.isCompressed())
m_byteArray = qUncompress(resource.data(), resource.size());
else
m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size());
}
const QByteArray& byteArray() const { return m_byteArray; }
QByteArray m_byteArray;
};
} // namespace anonymous
Configuration::Configuration(QWidget *parent) :
QDialog(parent),
ui(new Ui::Configuration)
{
ui->setupUi(this);
GetDataFromResource defaultConfigScm(":/tinyscheme/default-config.scm");
ui->txtConfig->setPlainText(
QString::fromUtf8(defaultConfigScm.byteArray().data(),
defaultConfigScm.byteArray().size()));
portaudio::System& sys = portaudio::System::instance();
insertWithDefault(
ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(),
sys.hostApisEnd(), sys.defaultHostApi(),
[](portaudio::HostApi &hostApi) { return hostApi.name(); },
[](portaudio::HostApi &hostApi) { return hostApi.typeId(); });
}
PaDeviceIndex Configuration::getDeviceIndex() const
{
auto index = ui->cmbInputDevice->currentIndex();
Q_ASSERT(index != -1);
return m_indexToDeviceIndex[index];
}
void Configuration::on_cmbAudioHost_currentIndexChanged(int index)
{
if (index == -1)
return;
portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId(
m_indexToHostApiTypeId[index]);
insertWithDefault(
ui->cmbInputDevice, m_indexToDeviceIndex,
hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(),
[](portaudio::Device &device) { return device.name(); },
[](portaudio::Device &device) { return device.index(); });
}
namespace {
struct Ptr {
scheme *sc_;
pointer p_;
Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {}
#define P(v) Ptr(sc_, v)
Ptr nil () { return P(sc_->NIL); }
bool is_nil () { return p_ == sc_->NIL; }
bool is_string () { return sc_->vptr->is_string(p_); }
char *string_value() { return sc_->vptr->string_value(p_); }
bool is_number () { return sc_->vptr->is_number(p_); }
num nvalue () { return sc_->vptr->nvalue(p_); }
long ivalue () { return sc_->vptr->ivalue(p_); }
double rvalue () { return sc_->vptr->rvalue(p_); }
bool is_integer () { return sc_->vptr->is_integer(p_); }
bool is_real () { return sc_->vptr->is_real(p_); }
bool is_character () { return sc_->vptr->is_character(p_); }
long charvalue () { return sc_->vptr->charvalue(p_); }
bool is_list () { return sc_->vptr->is_list(sc_, p_); }
bool is_vector () { return sc_->vptr->is_vector(p_); }
int list_length () { return sc_->vptr->list_length(sc_, p_); }
long vector_length() { return sc_->vptr->vector_length(p_); }
Ptr vector_elem (int ielem) { return P(sc_->vptr->vector_elem(p_, ielem)); }
bool is_pair () { return sc_->vptr->is_pair(p_); }
Ptr car () { return P(sc_->vptr->pair_car(p_)); }
Ptr cdr () { return P(sc_->vptr->pair_cdr(p_)); }
bool is_symbol () { return sc_->vptr->is_symbol(p_); }
char *symname () { return sc_->vptr->symname(p_); }
#undef P
};
struct Config {
Config(const char *configScript) : sc_(scheme_init_new())
{
Q_ASSERT(sc_ != nullptr);
scheme_set_output_port_file(sc_, stdout);
loadResource(":/tinyscheme/init.scm");
loadResource(":/tinyscheme/config-helper.scm");
read_eval("(begin (display 1337) (newline))");
scheme_load_string(sc_, configScript);
if (sc_->retcode != 0) qDebug() << "Scheme failed" << __LINE__;
Ptr ret = read_eval("(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))");
qDebug() << ret.ivalue();
}
void loadResource(const char *resource)
{
GetDataFromResource gdfr(resource);
scheme_load_string(sc_, gdfr.byteArray().data());
}
Ptr read_eval(const char* script)
{
// tinyscheme bug: When executing
//
// (read (open-input-string script))
//
// sc_->inport needs to be set, or there will be an error when
// read is restoring the previous inport value when returning.
scheme_set_input_port_file(sc_, stdin); // TODO stdin?
pointer fun = scheme_eval(sc_, mk_symbol(sc_, "read-eval"));
pointer arg = mk_string(sc_, script);
return Ptr(sc_, scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0)));
}
scheme *sc_;
};
} // namespace anonymous
void Configuration::on_buttonBox_accepted()
{
QString configText = ui->txtConfig->toPlainText();
QByteArray configTextBa = configText.toUtf8();
Config cfg(configTextBa.constData());
emit accept();
}
Configuration::~Configuration()
{
delete ui;
}
<|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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 2012 Heiko Strathmann
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/lib/common.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/features/Features.h>
#include <shogun/features/DummyFeatures.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
void
CCustomKernel::init()
{
m_row_subset=NULL;
m_col_subset=NULL;
SG_ADD((CSGObject**)&m_row_subset, "row_subset", "Subset of rows",
MS_NOT_AVAILABLE);
SG_ADD((CSGObject**)&m_col_subset, "col_subset", "Subset of columns",
MS_NOT_AVAILABLE);
m_parameters->add(&kmatrix, "kmatrix", "Kernel matrix.");
m_parameters->add(&upper_diagonal, "upper_diagonal");
}
CCustomKernel::CCustomKernel()
: CKernel(10), kmatrix(), upper_diagonal(false)
{
init();
}
CCustomKernel::CCustomKernel(CKernel* k)
: CKernel(10)
{
init();
set_full_kernel_matrix_from_full(k->get_kernel_matrix());
// SG_PRINT("created custom kernel with kernel matrix:\n");
// print_kernel_matrix();
}
CCustomKernel::CCustomKernel(SGMatrix<float64_t> km)
: CKernel(10), upper_diagonal(false)
{
init();
set_full_kernel_matrix_from_full(km);
}
CCustomKernel::~CCustomKernel()
{
SG_UNREF(m_row_subset);
SG_UNREF(m_col_subset);
cleanup();
}
bool CCustomKernel::dummy_init(int32_t rows, int32_t cols)
{
return init(new CDummyFeatures(rows), new CDummyFeatures(cols));
}
bool CCustomKernel::init(CFeatures* l, CFeatures* r)
{
remove_row_subset();
remove_col_subset();
CKernel::init(l, r);
SG_DEBUG( "num_vec_lhs: %d vs num_rows %d\n", l->get_num_vectors(), kmatrix.num_rows);
SG_DEBUG( "num_vec_rhs: %d vs num_cols %d\n", r->get_num_vectors(), kmatrix.num_cols);
ASSERT(l->get_num_vectors()==kmatrix.num_rows);
ASSERT(r->get_num_vectors()==kmatrix.num_cols);
return init_normalizer();
}
void CCustomKernel::cleanup_custom()
{
SG_DEBUG("cleanup up custom kernel\n");
remove_row_subset();
remove_col_subset();
SG_FREE(kmatrix.matrix);
kmatrix.matrix=NULL;
upper_diagonal=false;
kmatrix.num_cols=0;
kmatrix.num_rows=0;
}
void CCustomKernel::cleanup()
{
remove_row_subset();
remove_col_subset();
cleanup_custom();
CKernel::cleanup();
}
void CCustomKernel::set_row_subset(CSubset* subset)
{
SG_UNREF(m_row_subset);
m_row_subset=subset;
SG_REF(subset);
/* update num_lhs */
num_lhs=subset ? subset->get_size() : 0;
}
void CCustomKernel::set_col_subset(CSubset* subset)
{
SG_UNREF(m_col_subset);
m_col_subset=subset;
SG_REF(subset);
/* update num_rhs */
num_rhs=subset ? subset->get_size() : 0;
}
void CCustomKernel::remove_row_subset()
{
set_row_subset(NULL);
/* restore num_lhs */
num_lhs=kmatrix.num_rows;
}
void CCustomKernel::remove_col_subset()
{
set_col_subset(NULL);
/* restore num_rhs */
num_rhs=kmatrix.num_cols;
}
void CCustomKernel::print_kernel_matrix(const char* prefix) const
{
index_t num_rows=m_row_subset ? m_row_subset->get_size() : kmatrix.num_rows;
index_t num_cols=m_col_subset ? m_col_subset->get_size() : kmatrix.num_cols;
for (index_t i=0; i<num_rows; ++i)
{
for (index_t j=0; j<num_cols; ++j)
{
index_t real_i=row_subset_idx_conversion(i);
index_t real_j=col_subset_idx_conversion(j);
SG_PRINT("%s%4.2f", kmatrix.matrix[kmatrix.num_rows*real_j+real_i],
prefix);
if (j<num_cols-1)
SG_PRINT(", \t");
}
SG_PRINT("\n");
}
}
<commit_msg>free kernel matrix only if there is one specified<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 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Written (W) 2012 Heiko Strathmann
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include <shogun/lib/common.h>
#include <shogun/kernel/CustomKernel.h>
#include <shogun/features/Features.h>
#include <shogun/features/DummyFeatures.h>
#include <shogun/io/SGIO.h>
using namespace shogun;
void
CCustomKernel::init()
{
m_row_subset=NULL;
m_col_subset=NULL;
SG_ADD((CSGObject**)&m_row_subset, "row_subset", "Subset of rows",
MS_NOT_AVAILABLE);
SG_ADD((CSGObject**)&m_col_subset, "col_subset", "Subset of columns",
MS_NOT_AVAILABLE);
m_parameters->add(&kmatrix, "kmatrix", "Kernel matrix.");
m_parameters->add(&upper_diagonal, "upper_diagonal");
}
CCustomKernel::CCustomKernel()
: CKernel(10), kmatrix(), upper_diagonal(false)
{
init();
}
CCustomKernel::CCustomKernel(CKernel* k)
: CKernel(10)
{
init();
set_full_kernel_matrix_from_full(k->get_kernel_matrix());
// SG_PRINT("created custom kernel with kernel matrix:\n");
// print_kernel_matrix();
}
CCustomKernel::CCustomKernel(SGMatrix<float64_t> km)
: CKernel(10), upper_diagonal(false)
{
init();
set_full_kernel_matrix_from_full(km);
}
CCustomKernel::~CCustomKernel()
{
SG_UNREF(m_row_subset);
SG_UNREF(m_col_subset);
cleanup();
}
bool CCustomKernel::dummy_init(int32_t rows, int32_t cols)
{
return init(new CDummyFeatures(rows), new CDummyFeatures(cols));
}
bool CCustomKernel::init(CFeatures* l, CFeatures* r)
{
remove_row_subset();
remove_col_subset();
CKernel::init(l, r);
SG_DEBUG( "num_vec_lhs: %d vs num_rows %d\n", l->get_num_vectors(), kmatrix.num_rows);
SG_DEBUG( "num_vec_rhs: %d vs num_cols %d\n", r->get_num_vectors(), kmatrix.num_cols);
ASSERT(l->get_num_vectors()==kmatrix.num_rows);
ASSERT(r->get_num_vectors()==kmatrix.num_cols);
return init_normalizer();
}
void CCustomKernel::cleanup_custom()
{
SG_DEBUG("cleanup up custom kernel\n");
remove_row_subset();
remove_col_subset();
if (kmatrix.matrix)
SG_FREE(kmatrix.matrix);
kmatrix.matrix=NULL;
upper_diagonal=false;
kmatrix.num_cols=0;
kmatrix.num_rows=0;
}
void CCustomKernel::cleanup()
{
remove_row_subset();
remove_col_subset();
cleanup_custom();
CKernel::cleanup();
}
void CCustomKernel::set_row_subset(CSubset* subset)
{
SG_UNREF(m_row_subset);
m_row_subset=subset;
SG_REF(subset);
/* update num_lhs */
num_lhs=subset ? subset->get_size() : 0;
}
void CCustomKernel::set_col_subset(CSubset* subset)
{
SG_UNREF(m_col_subset);
m_col_subset=subset;
SG_REF(subset);
/* update num_rhs */
num_rhs=subset ? subset->get_size() : 0;
}
void CCustomKernel::remove_row_subset()
{
set_row_subset(NULL);
/* restore num_lhs */
num_lhs=kmatrix.num_rows;
}
void CCustomKernel::remove_col_subset()
{
set_col_subset(NULL);
/* restore num_rhs */
num_rhs=kmatrix.num_cols;
}
void CCustomKernel::print_kernel_matrix(const char* prefix) const
{
index_t num_rows=m_row_subset ? m_row_subset->get_size() : kmatrix.num_rows;
index_t num_cols=m_col_subset ? m_col_subset->get_size() : kmatrix.num_cols;
for (index_t i=0; i<num_rows; ++i)
{
for (index_t j=0; j<num_cols; ++j)
{
index_t real_i=row_subset_idx_conversion(i);
index_t real_j=col_subset_idx_conversion(j);
SG_PRINT("%s%4.2f", kmatrix.matrix[kmatrix.num_rows*real_j+real_i],
prefix);
if (j<num_cols-1)
SG_PRINT(", \t");
}
SG_PRINT("\n");
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "slib/graphics/drawable.h"
#include "slib/graphics/image.h"
#include "slib/graphics/platform.h"
#include "slib/core/file.h"
#include "slib/core/asset.h"
namespace slib
{
Ref<Bitmap> Drawable::toBitmap()
{
if (isBitmap()) {
return (Bitmap*)this;
}
sl_int32 width = (sl_int32)(getDrawableWidth());
sl_int32 height = (sl_int32)(getDrawableHeight());
if (width > 0 && height > 0) {
Ref<Bitmap> bitmap = Bitmap::create(width, height);
if (bitmap.isNotNull()) {
Ref<Canvas> canvas = bitmap->getCanvas();
if (canvas.isNotNull()) {
canvas->draw(Rectangle(0, 0, (sl_real)width, (sl_real)height), this);
}
return bitmap;
}
}
return sl_null;
}
Ref<Image> Drawable::toImage()
{
if (isImage()) {
return (Image*)this;
}
Ref<Bitmap> bitmap = toBitmap();
if (bitmap.isNotNull()) {
return Image::create(bitmap);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::create(const Ref<Image>& image)
{
if (image.isNotNull()) {
ImageDesc desc;
image->getDesc(desc);
return PlatformDrawable::create(desc);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromMemory(const Memory& mem)
{
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem.getData(), mem.getSize());
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromFile(const String& filePath)
{
Memory mem = File::readAllBytes(filePath);
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromAsset(const String& path)
{
Memory mem = Assets::readAllBytes(path);
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem);
}
#if defined(SLIB_PLATFORM_IS_APPLE)
CGImageRef image = GraphicsPlatform::loadCGImageFromApp(path);
if (image) {
Ref<Drawable> ret = GraphicsPlatform::createImageDrawable(image);
CGImageRelease(image);
return ret;
}
#endif
return sl_null;
}
}
<commit_msg>graphics: minor fix on conversion from drawable to bitmap<commit_after>/*
* Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "slib/graphics/drawable.h"
#include "slib/graphics/image.h"
#include "slib/graphics/platform.h"
#include "slib/core/file.h"
#include "slib/core/asset.h"
namespace slib
{
Ref<Bitmap> Drawable::toBitmap()
{
if (isBitmap()) {
return (Bitmap*)this;
}
sl_int32 width = (sl_int32)(getDrawableWidth());
sl_int32 height = (sl_int32)(getDrawableHeight());
if (width > 0 && height > 0) {
Ref<Bitmap> bitmap = Bitmap::create(width, height);
if (bitmap.isNotNull()) {
bitmap->resetPixels(Color::None);
Ref<Canvas> canvas = bitmap->getCanvas();
if (canvas.isNotNull()) {
canvas->draw(Rectangle(0, 0, (sl_real)width, (sl_real)height), this);
}
return bitmap;
}
}
return sl_null;
}
Ref<Image> Drawable::toImage()
{
if (isImage()) {
return (Image*)this;
}
Ref<Bitmap> bitmap = toBitmap();
if (bitmap.isNotNull()) {
return Image::create(bitmap);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::create(const Ref<Image>& image)
{
if (image.isNotNull()) {
ImageDesc desc;
image->getDesc(desc);
return PlatformDrawable::create(desc);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromMemory(const Memory& mem)
{
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem.getData(), mem.getSize());
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromFile(const String& filePath)
{
Memory mem = File::readAllBytes(filePath);
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem);
}
return sl_null;
}
Ref<Drawable> PlatformDrawable::loadFromAsset(const String& path)
{
Memory mem = Assets::readAllBytes(path);
if (mem.isNotNull()) {
return PlatformDrawable::loadFromMemory(mem);
}
#if defined(SLIB_PLATFORM_IS_APPLE)
CGImageRef image = GraphicsPlatform::loadCGImageFromApp(path);
if (image) {
Ref<Drawable> ret = GraphicsPlatform::createImageDrawable(image);
CGImageRelease(image);
return ret;
}
#endif
return sl_null;
}
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename ArrayType> void array(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> ColVectorType;
typedef Array<Scalar, 1, ArrayType::ColsAtCompileTime> RowVectorType;
Index rows = m.rows();
Index cols = m.cols();
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
ColVectorType cv1 = ColVectorType::Random(rows);
RowVectorType rv1 = RowVectorType::Random(cols);
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
// scalar addition
VERIFY_IS_APPROX(m1 + s1, s1 + m1);
VERIFY_IS_APPROX(m1 + s1, ArrayType::Constant(rows,cols,s1) + m1);
VERIFY_IS_APPROX(s1 - m1, (-m1)+s1 );
VERIFY_IS_APPROX(m1 - s1, m1 - ArrayType::Constant(rows,cols,s1));
VERIFY_IS_APPROX(s1 - m1, ArrayType::Constant(rows,cols,s1) - m1);
VERIFY_IS_APPROX((m1*Scalar(2)) - s2, (m1+m1) - ArrayType::Constant(rows,cols,s2) );
m3 = m1;
m3 += s2;
VERIFY_IS_APPROX(m3, m1 + s2);
m3 = m1;
m3 -= s1;
VERIFY_IS_APPROX(m3, m1 - s1);
// scalar operators via Maps
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) -= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 - m2);
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) += ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 + m2);
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) *= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 * m2);
m3 = m1;
m2 = ArrayType::Random(rows,cols);
m2 = (m2==0).select(1,m2);
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) /= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 / m2);
// reductions
VERIFY_IS_APPROX(m1.colwise().sum().sum(), m1.sum());
VERIFY_IS_APPROX(m1.rowwise().sum().sum(), m1.sum());
if (!internal::isApprox(m1.sum(), (m1+m2).sum(), test_precision<Scalar>()))
VERIFY_IS_NOT_APPROX(((m1+m2).rowwise().sum()).sum(), m1.sum());
VERIFY_IS_APPROX(m1.colwise().sum(), m1.colwise().redux(internal::scalar_sum_op<Scalar>()));
// vector-wise ops
m3 = m1;
VERIFY_IS_APPROX(m3.colwise() += cv1, m1.colwise() + cv1);
m3 = m1;
VERIFY_IS_APPROX(m3.colwise() -= cv1, m1.colwise() - cv1);
m3 = m1;
VERIFY_IS_APPROX(m3.rowwise() += rv1, m1.rowwise() + rv1);
m3 = m1;
VERIFY_IS_APPROX(m3.rowwise() -= rv1, m1.rowwise() - rv1);
}
template<typename ArrayType> void comparisons(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> VectorType;
Index rows = m.rows();
Index cols = m.cols();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
VERIFY(((m1 + Scalar(1)) > m1).all());
VERIFY(((m1 - Scalar(1)) < m1).all());
if (rows*cols>1)
{
m3 = m1;
m3(r,c) += 1;
VERIFY(! (m1 < m3).all() );
VERIFY(! (m1 > m3).all() );
}
// comparisons to scalar
VERIFY( (m1 != (m1(r,c)+1) ).any() );
VERIFY( (m1 > (m1(r,c)-1) ).any() );
VERIFY( (m1 < (m1(r,c)+1) ).any() );
VERIFY( (m1 == m1(r,c) ).any() );
// test Select
VERIFY_IS_APPROX( (m1<m2).select(m1,m2), m1.cwiseMin(m2) );
VERIFY_IS_APPROX( (m1>m2).select(m1,m2), m1.cwiseMax(m2) );
Scalar mid = (m1.cwiseAbs().minCoeff() + m1.cwiseAbs().maxCoeff())/Scalar(2);
for (int j=0; j<cols; ++j)
for (int i=0; i<rows; ++i)
m3(i,j) = internal::abs(m1(i,j))<mid ? 0 : m1(i,j);
VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))
.select(ArrayType::Zero(rows,cols),m1), m3);
// shorter versions:
VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))
.select(0,m1), m3);
VERIFY_IS_APPROX( (m1.abs()>=ArrayType::Constant(rows,cols,mid))
.select(m1,0), m3);
// even shorter version:
VERIFY_IS_APPROX( (m1.abs()<mid).select(0,m1), m3);
// count
VERIFY(((m1.abs()+1)>RealScalar(0.1)).count() == rows*cols);
typedef Array<typename ArrayType::Index, Dynamic, 1> ArrayOfIndices;
// TODO allows colwise/rowwise for array
VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).colwise().count(), ArrayOfIndices::Constant(cols,rows).transpose());
VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).rowwise().count(), ArrayOfIndices::Constant(rows, cols));
}
template<typename ArrayType> void array_real(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
Index rows = m.rows();
Index cols = m.cols();
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
VERIFY_IS_APPROX(m1.sin(), std::sin(m1));
VERIFY_IS_APPROX(m1.sin(), internal::sin(m1));
VERIFY_IS_APPROX(m1.cos(), std::cos(m1));
VERIFY_IS_APPROX(m1.cos(), internal::cos(m1));
VERIFY_IS_APPROX(internal::cos(m1+RealScalar(3)*m2), internal::cos((m1+RealScalar(3)*m2).eval()));
VERIFY_IS_APPROX(std::cos(m1+RealScalar(3)*m2), std::cos((m1+RealScalar(3)*m2).eval()));
VERIFY_IS_APPROX(m1.abs().sqrt(), std::sqrt(std::abs(m1)));
VERIFY_IS_APPROX(m1.abs().sqrt(), internal::sqrt(internal::abs(m1)));
VERIFY_IS_APPROX(m1.abs(), internal::sqrt(internal::abs2(m1)));
VERIFY_IS_APPROX(internal::abs2(internal::real(m1)) + internal::abs2(internal::imag(m1)), internal::abs2(m1));
VERIFY_IS_APPROX(internal::abs2(std::real(m1)) + internal::abs2(std::imag(m1)), internal::abs2(m1));
if(!NumTraits<Scalar>::IsComplex)
VERIFY_IS_APPROX(internal::real(m1), m1);
VERIFY_IS_APPROX(m1.abs().log(), std::log(std::abs(m1)));
VERIFY_IS_APPROX(m1.abs().log(), internal::log(internal::abs(m1)));
VERIFY_IS_APPROX(m1.exp(), std::exp(m1));
VERIFY_IS_APPROX(m1.exp() * m2.exp(), std::exp(m1+m2));
VERIFY_IS_APPROX(m1.exp(), internal::exp(m1));
VERIFY_IS_APPROX(m1.exp() / m2.exp(), std::exp(m1-m2));
VERIFY_IS_APPROX(m1.pow(2), m1.square());
VERIFY_IS_APPROX(std::pow(m1,2), m1.square());
m3 = m1.abs();
VERIFY_IS_APPROX(m3.pow(RealScalar(0.5)), m3.sqrt());
VERIFY_IS_APPROX(std::pow(m3,RealScalar(0.5)), m3.sqrt());
}
void test_array()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( array(Array<float, 1, 1>()) );
//CALL_SUBTEST_2( array(Array22f()) );
//CALL_SUBTEST_3( array(Array44d()) );
//CALL_SUBTEST_4( array(ArrayXXcf(3, 3)) );
//CALL_SUBTEST_5( array(ArrayXXf(8, 12)) );
//CALL_SUBTEST_6( array(ArrayXXi(8, 12)) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( comparisons(Array<float, 1, 1>()) );
//CALL_SUBTEST_2( comparisons(Array22f()) );
//CALL_SUBTEST_3( comparisons(Array44d()) );
//CALL_SUBTEST_5( comparisons(ArrayXXf(8, 12)) );
//CALL_SUBTEST_6( comparisons(ArrayXXi(8, 12)) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( array_real(Array<float, 1, 1>()) );
//CALL_SUBTEST_2( array_real(Array22f()) );
//CALL_SUBTEST_3( array_real(Array44d()) );
//CALL_SUBTEST_5( array_real(ArrayXXf(8, 12)) );
}
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<int>::type, int >::value));
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<float>::type, float >::value));
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Array2i>::type, ArrayBase<Array2i> >::value));
typedef CwiseUnaryOp<internal::scalar_sum_op<double>, ArrayXd > Xpr;
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Xpr>::type,
ArrayBase<Xpr>
>::value));
}
<commit_msg>Re-enabled the missing tests, again...<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename ArrayType> void array(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> ColVectorType;
typedef Array<Scalar, 1, ArrayType::ColsAtCompileTime> RowVectorType;
Index rows = m.rows();
Index cols = m.cols();
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
ColVectorType cv1 = ColVectorType::Random(rows);
RowVectorType rv1 = RowVectorType::Random(cols);
Scalar s1 = internal::random<Scalar>(),
s2 = internal::random<Scalar>();
// scalar addition
VERIFY_IS_APPROX(m1 + s1, s1 + m1);
VERIFY_IS_APPROX(m1 + s1, ArrayType::Constant(rows,cols,s1) + m1);
VERIFY_IS_APPROX(s1 - m1, (-m1)+s1 );
VERIFY_IS_APPROX(m1 - s1, m1 - ArrayType::Constant(rows,cols,s1));
VERIFY_IS_APPROX(s1 - m1, ArrayType::Constant(rows,cols,s1) - m1);
VERIFY_IS_APPROX((m1*Scalar(2)) - s2, (m1+m1) - ArrayType::Constant(rows,cols,s2) );
m3 = m1;
m3 += s2;
VERIFY_IS_APPROX(m3, m1 + s2);
m3 = m1;
m3 -= s1;
VERIFY_IS_APPROX(m3, m1 - s1);
// scalar operators via Maps
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) -= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 - m2);
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) += ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 + m2);
m3 = m1;
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) *= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 * m2);
m3 = m1;
m2 = ArrayType::Random(rows,cols);
m2 = (m2==0).select(1,m2);
ArrayType::Map(m1.data(), m1.rows(), m1.cols()) /= ArrayType::Map(m2.data(), m2.rows(), m2.cols());
VERIFY_IS_APPROX(m1, m3 / m2);
// reductions
VERIFY_IS_APPROX(m1.colwise().sum().sum(), m1.sum());
VERIFY_IS_APPROX(m1.rowwise().sum().sum(), m1.sum());
if (!internal::isApprox(m1.sum(), (m1+m2).sum(), test_precision<Scalar>()))
VERIFY_IS_NOT_APPROX(((m1+m2).rowwise().sum()).sum(), m1.sum());
VERIFY_IS_APPROX(m1.colwise().sum(), m1.colwise().redux(internal::scalar_sum_op<Scalar>()));
// vector-wise ops
m3 = m1;
VERIFY_IS_APPROX(m3.colwise() += cv1, m1.colwise() + cv1);
m3 = m1;
VERIFY_IS_APPROX(m3.colwise() -= cv1, m1.colwise() - cv1);
m3 = m1;
VERIFY_IS_APPROX(m3.rowwise() += rv1, m1.rowwise() + rv1);
m3 = m1;
VERIFY_IS_APPROX(m3.rowwise() -= rv1, m1.rowwise() - rv1);
}
template<typename ArrayType> void comparisons(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> VectorType;
Index rows = m.rows();
Index cols = m.cols();
Index r = internal::random<Index>(0, rows-1),
c = internal::random<Index>(0, cols-1);
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
VERIFY(((m1 + Scalar(1)) > m1).all());
VERIFY(((m1 - Scalar(1)) < m1).all());
if (rows*cols>1)
{
m3 = m1;
m3(r,c) += 1;
VERIFY(! (m1 < m3).all() );
VERIFY(! (m1 > m3).all() );
}
// comparisons to scalar
VERIFY( (m1 != (m1(r,c)+1) ).any() );
VERIFY( (m1 > (m1(r,c)-1) ).any() );
VERIFY( (m1 < (m1(r,c)+1) ).any() );
VERIFY( (m1 == m1(r,c) ).any() );
// test Select
VERIFY_IS_APPROX( (m1<m2).select(m1,m2), m1.cwiseMin(m2) );
VERIFY_IS_APPROX( (m1>m2).select(m1,m2), m1.cwiseMax(m2) );
Scalar mid = (m1.cwiseAbs().minCoeff() + m1.cwiseAbs().maxCoeff())/Scalar(2);
for (int j=0; j<cols; ++j)
for (int i=0; i<rows; ++i)
m3(i,j) = internal::abs(m1(i,j))<mid ? 0 : m1(i,j);
VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))
.select(ArrayType::Zero(rows,cols),m1), m3);
// shorter versions:
VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))
.select(0,m1), m3);
VERIFY_IS_APPROX( (m1.abs()>=ArrayType::Constant(rows,cols,mid))
.select(m1,0), m3);
// even shorter version:
VERIFY_IS_APPROX( (m1.abs()<mid).select(0,m1), m3);
// count
VERIFY(((m1.abs()+1)>RealScalar(0.1)).count() == rows*cols);
typedef Array<typename ArrayType::Index, Dynamic, 1> ArrayOfIndices;
// TODO allows colwise/rowwise for array
VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).colwise().count(), ArrayOfIndices::Constant(cols,rows).transpose());
VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).rowwise().count(), ArrayOfIndices::Constant(rows, cols));
}
template<typename ArrayType> void array_real(const ArrayType& m)
{
typedef typename ArrayType::Index Index;
typedef typename ArrayType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
Index rows = m.rows();
Index cols = m.cols();
ArrayType m1 = ArrayType::Random(rows, cols),
m2 = ArrayType::Random(rows, cols),
m3(rows, cols);
VERIFY_IS_APPROX(m1.sin(), std::sin(m1));
VERIFY_IS_APPROX(m1.sin(), internal::sin(m1));
VERIFY_IS_APPROX(m1.cos(), std::cos(m1));
VERIFY_IS_APPROX(m1.cos(), internal::cos(m1));
VERIFY_IS_APPROX(internal::cos(m1+RealScalar(3)*m2), internal::cos((m1+RealScalar(3)*m2).eval()));
VERIFY_IS_APPROX(std::cos(m1+RealScalar(3)*m2), std::cos((m1+RealScalar(3)*m2).eval()));
VERIFY_IS_APPROX(m1.abs().sqrt(), std::sqrt(std::abs(m1)));
VERIFY_IS_APPROX(m1.abs().sqrt(), internal::sqrt(internal::abs(m1)));
VERIFY_IS_APPROX(m1.abs(), internal::sqrt(internal::abs2(m1)));
VERIFY_IS_APPROX(internal::abs2(internal::real(m1)) + internal::abs2(internal::imag(m1)), internal::abs2(m1));
VERIFY_IS_APPROX(internal::abs2(std::real(m1)) + internal::abs2(std::imag(m1)), internal::abs2(m1));
if(!NumTraits<Scalar>::IsComplex)
VERIFY_IS_APPROX(internal::real(m1), m1);
VERIFY_IS_APPROX(m1.abs().log(), std::log(std::abs(m1)));
VERIFY_IS_APPROX(m1.abs().log(), internal::log(internal::abs(m1)));
VERIFY_IS_APPROX(m1.exp(), std::exp(m1));
VERIFY_IS_APPROX(m1.exp() * m2.exp(), std::exp(m1+m2));
VERIFY_IS_APPROX(m1.exp(), internal::exp(m1));
VERIFY_IS_APPROX(m1.exp() / m2.exp(), std::exp(m1-m2));
VERIFY_IS_APPROX(m1.pow(2), m1.square());
VERIFY_IS_APPROX(std::pow(m1,2), m1.square());
m3 = m1.abs();
VERIFY_IS_APPROX(m3.pow(RealScalar(0.5)), m3.sqrt());
VERIFY_IS_APPROX(std::pow(m3,RealScalar(0.5)), m3.sqrt());
}
void test_array()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( array(Array<float, 1, 1>()) );
CALL_SUBTEST_2( array(Array22f()) );
CALL_SUBTEST_3( array(Array44d()) );
CALL_SUBTEST_4( array(ArrayXXcf(3, 3)) );
CALL_SUBTEST_5( array(ArrayXXf(8, 12)) );
CALL_SUBTEST_6( array(ArrayXXi(8, 12)) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( comparisons(Array<float, 1, 1>()) );
CALL_SUBTEST_2( comparisons(Array22f()) );
CALL_SUBTEST_3( comparisons(Array44d()) );
CALL_SUBTEST_5( comparisons(ArrayXXf(8, 12)) );
CALL_SUBTEST_6( comparisons(ArrayXXi(8, 12)) );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( array_real(Array<float, 1, 1>()) );
CALL_SUBTEST_2( array_real(Array22f()) );
CALL_SUBTEST_3( array_real(Array44d()) );
CALL_SUBTEST_5( array_real(ArrayXXf(8, 12)) );
}
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<int>::type, int >::value));
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<float>::type, float >::value));
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Array2i>::type, ArrayBase<Array2i> >::value));
typedef CwiseUnaryOp<internal::scalar_sum_op<double>, ArrayXd > Xpr;
VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Xpr>::type,
ArrayBase<Xpr>
>::value));
}
<|endoftext|>
|
<commit_before>#pragma once
#include "console_user_server_client.hpp"
#include "constants.hpp"
#include "input_source_manager.hpp"
#include "local_datagram/server_manager.hpp"
#include "shell_utility.hpp"
#include "types.hpp"
#include <vector>
namespace krbn {
class receiver final {
public:
// Signals
boost::signals2::signal<void(void)> bound;
boost::signals2::signal<void(const boost::system::error_code&)> bind_failed;
boost::signals2::signal<void(void)> closed;
// Methods
receiver(const receiver&) = delete;
receiver(void) : last_select_input_source_time_stamp_(0) {
dispatcher_ = std::make_unique<thread_utility::dispatcher>();
}
void async_start(void) {
dispatcher_->enqueue([this] {
if (server_manager_) {
return;
}
auto uid = getuid();
auto socket_file_path = console_user_server_client::make_console_user_server_socket_file_path(uid);
unlink(socket_file_path.c_str());
size_t buffer_size = 32 * 1024;
std::chrono::milliseconds server_check_interval(3000);
std::chrono::milliseconds reconnect_interval(1000);
server_manager_ = std::make_unique<local_datagram::server_manager>(socket_file_path,
buffer_size,
server_check_interval,
reconnect_interval);
server_manager_->bound.connect([this] {
dispatcher_->enqueue([this] {
bound();
});
});
server_manager_->bind_failed.connect([this](auto&& error_code) {
dispatcher_->enqueue([this, error_code] {
bind_failed(error_code);
});
});
server_manager_->closed.connect([this] {
dispatcher_->enqueue([this] {
closed();
});
});
server_manager_->received.connect([this](auto&& buffer) {
dispatcher_->enqueue([this, buffer] {
if (auto type = types::find_operation_type(*buffer)) {
switch (*type) {
case operation_type::shell_command_execution:
if (buffer->size() != sizeof(operation_type_shell_command_execution_struct)) {
logger::get_logger().error("invalid size for operation_type::shell_command_execution");
} else {
auto p = reinterpret_cast<operation_type_shell_command_execution_struct*>(&((*buffer)[0]));
// Ensure shell_command is null-terminated string even if corrupted data is sent.
p->shell_command[sizeof(p->shell_command) - 1] = '\0';
std::string background_shell_command = shell_utility::make_background_command(p->shell_command);
system(background_shell_command.c_str());
}
break;
case operation_type::select_input_source:
if (buffer->size() != sizeof(operation_type_select_input_source_struct)) {
logger::get_logger().error("invalid size for operation_type::select_input_source");
} else {
auto p = reinterpret_cast<operation_type_select_input_source_struct*>(&((*buffer)[0]));
// Ensure input_source_selector's strings are null-terminated string even if corrupted data is sent.
p->language[sizeof(p->language) - 1] = '\0';
p->input_source_id[sizeof(p->input_source_id) - 1] = '\0';
p->input_mode_id[sizeof(p->input_mode_id) - 1] = '\0';
uint64_t time_stamp = p->time_stamp;
boost::optional<std::string> language(std::string(p->language));
boost::optional<std::string> input_source_id(std::string(p->input_source_id));
boost::optional<std::string> input_mode_id(std::string(p->input_mode_id));
if (language && language->empty()) {
language = boost::none;
}
if (input_source_id && input_source_id->empty()) {
input_source_id = boost::none;
}
if (input_mode_id && input_mode_id->empty()) {
input_mode_id = boost::none;
}
input_source_selector input_source_selector(language,
input_source_id,
input_mode_id);
if (last_select_input_source_time_stamp_ == time_stamp) {
return;
}
if (input_source_manager_.select(input_source_selector)) {
last_select_input_source_time_stamp_ = time_stamp;
}
}
break;
default:
break;
}
}
});
});
server_manager_->async_start();
logger::get_logger().info("receiver is initialized");
});
}
~receiver(void) {
dispatcher_->enqueue([this] {
server_manager_ = nullptr;
});
dispatcher_->terminate();
dispatcher_ = nullptr;
logger::get_logger().info("receiver is terminated");
}
private:
std::unique_ptr<thread_utility::dispatcher> dispatcher_;
std::unique_ptr<local_datagram::server_manager> server_manager_;
input_source_manager input_source_manager_;
uint64_t last_select_input_source_time_stamp_;
};
} // namespace krbn
<commit_msg>fix console_user_server<commit_after>#pragma once
#include "console_user_server_client.hpp"
#include "constants.hpp"
#include "input_source_manager.hpp"
#include "local_datagram/server_manager.hpp"
#include "shell_utility.hpp"
#include "types.hpp"
#include <vector>
namespace krbn {
class receiver final {
public:
// Signals
boost::signals2::signal<void(void)> bound;
boost::signals2::signal<void(const boost::system::error_code&)> bind_failed;
boost::signals2::signal<void(void)> closed;
// Methods
receiver(const receiver&) = delete;
receiver(void) : last_select_input_source_time_stamp_(0) {
dispatcher_ = std::make_unique<thread_utility::dispatcher>();
}
void async_start(void) {
dispatcher_->enqueue([this] {
if (server_manager_) {
return;
}
auto uid = getuid();
auto socket_file_path = console_user_server_client::make_console_user_server_socket_file_path(uid);
unlink(socket_file_path.c_str());
size_t buffer_size = 32 * 1024;
std::chrono::milliseconds server_check_interval(3000);
std::chrono::milliseconds reconnect_interval(1000);
server_manager_ = std::make_unique<local_datagram::server_manager>(socket_file_path,
buffer_size,
server_check_interval,
reconnect_interval);
server_manager_->bound.connect([this] {
dispatcher_->enqueue([this] {
bound();
});
});
server_manager_->bind_failed.connect([this](auto&& error_code) {
dispatcher_->enqueue([this, error_code] {
bind_failed(error_code);
});
});
server_manager_->closed.connect([this] {
dispatcher_->enqueue([this] {
closed();
});
});
server_manager_->received.connect([this](auto&& buffer) {
dispatcher_->enqueue([this, buffer] {
if (auto type = types::find_operation_type(*buffer)) {
switch (*type) {
case operation_type::shell_command_execution:
if (buffer->size() != sizeof(operation_type_shell_command_execution_struct)) {
logger::get_logger().error("invalid size for operation_type::shell_command_execution");
} else {
auto p = reinterpret_cast<operation_type_shell_command_execution_struct*>(&((*buffer)[0]));
// Ensure shell_command is null-terminated string even if corrupted data is sent.
p->shell_command[sizeof(p->shell_command) - 1] = '\0';
std::string background_shell_command = shell_utility::make_background_command(p->shell_command);
system(background_shell_command.c_str());
}
break;
case operation_type::select_input_source:
if (buffer->size() != sizeof(operation_type_select_input_source_struct)) {
logger::get_logger().error("invalid size for operation_type::select_input_source");
} else {
auto p = reinterpret_cast<operation_type_select_input_source_struct*>(&((*buffer)[0]));
// Ensure input_source_selector's strings are null-terminated string even if corrupted data is sent.
p->language[sizeof(p->language) - 1] = '\0';
p->input_source_id[sizeof(p->input_source_id) - 1] = '\0';
p->input_mode_id[sizeof(p->input_mode_id) - 1] = '\0';
auto time_stamp = p->time_stamp;
boost::optional<std::string> language(std::string(p->language));
boost::optional<std::string> input_source_id(std::string(p->input_source_id));
boost::optional<std::string> input_mode_id(std::string(p->input_mode_id));
if (language && language->empty()) {
language = boost::none;
}
if (input_source_id && input_source_id->empty()) {
input_source_id = boost::none;
}
if (input_mode_id && input_mode_id->empty()) {
input_mode_id = boost::none;
}
input_source_selector input_source_selector(language,
input_source_id,
input_mode_id);
if (last_select_input_source_time_stamp_ == time_stamp) {
return;
}
if (input_source_manager_.select(input_source_selector)) {
last_select_input_source_time_stamp_ = time_stamp;
}
}
break;
default:
break;
}
}
});
});
server_manager_->async_start();
logger::get_logger().info("receiver is initialized");
});
}
~receiver(void) {
dispatcher_->enqueue([this] {
server_manager_ = nullptr;
});
dispatcher_->terminate();
dispatcher_ = nullptr;
logger::get_logger().info("receiver is terminated");
}
private:
std::unique_ptr<thread_utility::dispatcher> dispatcher_;
std::unique_ptr<local_datagram::server_manager> server_manager_;
input_source_manager input_source_manager_;
absolute_time last_select_input_source_time_stamp_;
};
} // namespace krbn
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015 gRPC authors.
*
* 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 "src/core/ext/filters/client_channel/uri_parser.h"
#include <string.h>
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/slice/percent_encoding.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/support/string.h"
/** a size_t default value... maps to all 1's */
#define NOT_SET (~(size_t)0)
static grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section,
bool suppress_errors) {
char* line_prefix;
size_t pfx_len;
if (!suppress_errors) {
gpr_asprintf(&line_prefix, "bad uri.%s: '", section);
pfx_len = strlen(line_prefix) + pos;
gpr_log(GPR_ERROR, "%s%s'", line_prefix, uri_text);
gpr_free(line_prefix);
line_prefix = (char*)gpr_malloc(pfx_len + 1);
memset(line_prefix, ' ', pfx_len);
line_prefix[pfx_len] = 0;
gpr_log(GPR_ERROR, "%s^ here", line_prefix);
gpr_free(line_prefix);
}
return NULL;
}
/** Returns a copy of percent decoded \a src[begin, end) */
static char* decode_and_copy_component(grpc_exec_ctx* exec_ctx, const char* src,
size_t begin, size_t end) {
grpc_slice component =
grpc_slice_from_copied_buffer(src + begin, end - begin);
grpc_slice decoded_component =
grpc_permissive_percent_decode_slice(component);
char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII);
grpc_slice_unref_internal(exec_ctx, component);
grpc_slice_unref_internal(exec_ctx, decoded_component);
return out;
}
static bool valid_hex(char c) {
return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) ||
((c >= '0') && (c <= '9'));
}
/** Returns how many chars to advance if \a uri_text[i] begins a valid \a pchar
* production. If \a uri_text[i] introduces an invalid \a pchar (such as percent
* sign not followed by two hex digits), NOT_SET is returned. */
static size_t parse_pchar(const char* uri_text, size_t i) {
/* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "=" */
char c = uri_text[i];
switch (c) {
default:
if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9'))) {
return 1;
}
break;
case ':':
case '@':
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
return 1;
case '%': /* pct-encoded */
if (valid_hex(uri_text[i + 1]) && valid_hex(uri_text[i + 2])) {
return 2;
}
return NOT_SET;
}
return 0;
}
/* *( pchar / "?" / "/" ) */
static int parse_fragment_or_query(const char* uri_text, size_t* i) {
char c;
while ((c = uri_text[*i]) != 0) {
const size_t advance = parse_pchar(uri_text, *i); /* pchar */
switch (advance) {
case 0: /* uri_text[i] isn't in pchar */
/* maybe it's ? or / */
if (uri_text[*i] == '?' || uri_text[*i] == '/') {
(*i)++;
break;
} else {
return 1;
}
GPR_UNREACHABLE_CODE(return 0);
default:
(*i) += advance;
break;
case NOT_SET: /* uri_text[i] introduces an invalid URI */
return 0;
}
}
/* *i is the first uri_text position past the \a query production, maybe \0 */
return 1;
}
static void parse_query_parts(grpc_uri* uri) {
static const char* QUERY_PARTS_SEPARATOR = "&";
static const char* QUERY_PARTS_VALUE_SEPARATOR = "=";
GPR_ASSERT(uri->query != NULL);
if (uri->query[0] == '\0') {
uri->query_parts = NULL;
uri->query_parts_values = NULL;
uri->num_query_parts = 0;
return;
}
gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts,
&uri->num_query_parts);
uri->query_parts_values =
(char**)gpr_malloc(uri->num_query_parts * sizeof(char**));
for (size_t i = 0; i < uri->num_query_parts; i++) {
char** query_param_parts;
size_t num_query_param_parts;
char* full = uri->query_parts[i];
gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts,
&num_query_param_parts);
GPR_ASSERT(num_query_param_parts > 0);
uri->query_parts[i] = query_param_parts[0];
if (num_query_param_parts > 1) {
/* TODO(dgq): only the first value after the separator is considered.
* Perhaps all chars after the first separator for the query part should
* be included, even if they include the separator. */
uri->query_parts_values[i] = query_param_parts[1];
} else {
uri->query_parts_values[i] = NULL;
}
for (size_t j = 2; j < num_query_param_parts; j++) {
gpr_free(query_param_parts[j]);
}
gpr_free(query_param_parts);
gpr_free(full);
}
}
grpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text,
bool suppress_errors) {
grpc_uri* uri;
size_t scheme_begin = 0;
size_t scheme_end = NOT_SET;
size_t authority_begin = NOT_SET;
size_t authority_end = NOT_SET;
size_t path_begin = NOT_SET;
size_t path_end = NOT_SET;
size_t query_begin = NOT_SET;
size_t query_end = NOT_SET;
size_t fragment_begin = NOT_SET;
size_t fragment_end = NOT_SET;
size_t i;
for (i = scheme_begin; uri_text[i] != 0; i++) {
if (uri_text[i] == ':') {
scheme_end = i;
break;
}
if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue;
if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue;
if (i != scheme_begin) {
if (uri_text[i] >= '0' && uri_text[i] <= '9') continue;
if (uri_text[i] == '+') continue;
if (uri_text[i] == '-') continue;
if (uri_text[i] == '.') continue;
}
break;
}
if (scheme_end == NOT_SET) {
return bad_uri(uri_text, i, "scheme", suppress_errors);
}
if (uri_text[scheme_end + 1] == '/' && uri_text[scheme_end + 2] == '/') {
authority_begin = scheme_end + 3;
for (i = authority_begin; uri_text[i] != 0 && authority_end == NOT_SET;
i++) {
if (uri_text[i] == '/' || uri_text[i] == '?' || uri_text[i] == '#') {
authority_end = i;
}
}
if (authority_end == NOT_SET && uri_text[i] == 0) {
authority_end = i;
}
if (authority_end == NOT_SET) {
return bad_uri(uri_text, i, "authority", suppress_errors);
}
/* TODO(ctiller): parse the authority correctly */
path_begin = authority_end;
} else {
path_begin = scheme_end + 1;
}
for (i = path_begin; uri_text[i] != 0; i++) {
if (uri_text[i] == '?' || uri_text[i] == '#') {
path_end = i;
break;
}
}
if (path_end == NOT_SET && uri_text[i] == 0) {
path_end = i;
}
if (path_end == NOT_SET) {
return bad_uri(uri_text, i, "path", suppress_errors);
}
if (uri_text[i] == '?') {
query_begin = ++i;
if (!parse_fragment_or_query(uri_text, &i)) {
return bad_uri(uri_text, i, "query", suppress_errors);
} else if (uri_text[i] != 0 && uri_text[i] != '#') {
/* We must be at the end or at the beginning of a fragment */
return bad_uri(uri_text, i, "query", suppress_errors);
}
query_end = i;
}
if (uri_text[i] == '#') {
fragment_begin = ++i;
if (!parse_fragment_or_query(uri_text, &i)) {
return bad_uri(uri_text, i - fragment_end, "fragment", suppress_errors);
} else if (uri_text[i] != 0) {
/* We must be at the end */
return bad_uri(uri_text, i, "fragment", suppress_errors);
}
fragment_end = i;
}
uri = (grpc_uri*)gpr_zalloc(sizeof(*uri));
uri->scheme =
decode_and_copy_component(exec_ctx, uri_text, scheme_begin, scheme_end);
uri->authority = decode_and_copy_component(exec_ctx, uri_text,
authority_begin, authority_end);
uri->path =
decode_and_copy_component(exec_ctx, uri_text, path_begin, path_end);
uri->query =
decode_and_copy_component(exec_ctx, uri_text, query_begin, query_end);
uri->fragment = decode_and_copy_component(exec_ctx, uri_text, fragment_begin,
fragment_end);
parse_query_parts(uri);
return uri;
}
const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) {
GPR_ASSERT(key != NULL);
if (key[0] == '\0') return NULL;
for (size_t i = 0; i < uri->num_query_parts; ++i) {
if (0 == strcmp(key, uri->query_parts[i])) {
return uri->query_parts_values[i];
}
}
return NULL;
}
void grpc_uri_destroy(grpc_uri* uri) {
if (!uri) return;
gpr_free(uri->scheme);
gpr_free(uri->authority);
gpr_free(uri->path);
gpr_free(uri->query);
for (size_t i = 0; i < uri->num_query_parts; ++i) {
gpr_free(uri->query_parts[i]);
gpr_free(uri->query_parts_values[i]);
}
gpr_free(uri->query_parts);
gpr_free(uri->query_parts_values);
gpr_free(uri->fragment);
gpr_free(uri);
}
<commit_msg>Fix internal UBSAN failure<commit_after>/*
*
* Copyright 2015 gRPC authors.
*
* 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 "src/core/ext/filters/client_channel/uri_parser.h"
#include <string.h>
#include <grpc/slice_buffer.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/slice/percent_encoding.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/support/string.h"
/** a size_t default value... maps to all 1's */
#define NOT_SET (~(size_t)0)
static grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section,
bool suppress_errors) {
char* line_prefix;
size_t pfx_len;
if (!suppress_errors) {
gpr_asprintf(&line_prefix, "bad uri.%s: '", section);
pfx_len = strlen(line_prefix) + pos;
gpr_log(GPR_ERROR, "%s%s'", line_prefix, uri_text);
gpr_free(line_prefix);
line_prefix = (char*)gpr_malloc(pfx_len + 1);
memset(line_prefix, ' ', pfx_len);
line_prefix[pfx_len] = 0;
gpr_log(GPR_ERROR, "%s^ here", line_prefix);
gpr_free(line_prefix);
}
return NULL;
}
/** Returns a copy of percent decoded \a src[begin, end) */
static char* decode_and_copy_component(grpc_exec_ctx* exec_ctx, const char* src,
size_t begin, size_t end) {
grpc_slice component =
(begin == NOT_SET || end == NOT_SET)
? grpc_empty_slice()
: grpc_slice_from_copied_buffer(src + begin, end - begin);
grpc_slice decoded_component =
grpc_permissive_percent_decode_slice(component);
char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII);
grpc_slice_unref_internal(exec_ctx, component);
grpc_slice_unref_internal(exec_ctx, decoded_component);
return out;
}
static bool valid_hex(char c) {
return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) ||
((c >= '0') && (c <= '9'));
}
/** Returns how many chars to advance if \a uri_text[i] begins a valid \a pchar
* production. If \a uri_text[i] introduces an invalid \a pchar (such as percent
* sign not followed by two hex digits), NOT_SET is returned. */
static size_t parse_pchar(const char* uri_text, size_t i) {
/* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "=" */
char c = uri_text[i];
switch (c) {
default:
if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9'))) {
return 1;
}
break;
case ':':
case '@':
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
return 1;
case '%': /* pct-encoded */
if (valid_hex(uri_text[i + 1]) && valid_hex(uri_text[i + 2])) {
return 2;
}
return NOT_SET;
}
return 0;
}
/* *( pchar / "?" / "/" ) */
static int parse_fragment_or_query(const char* uri_text, size_t* i) {
char c;
while ((c = uri_text[*i]) != 0) {
const size_t advance = parse_pchar(uri_text, *i); /* pchar */
switch (advance) {
case 0: /* uri_text[i] isn't in pchar */
/* maybe it's ? or / */
if (uri_text[*i] == '?' || uri_text[*i] == '/') {
(*i)++;
break;
} else {
return 1;
}
GPR_UNREACHABLE_CODE(return 0);
default:
(*i) += advance;
break;
case NOT_SET: /* uri_text[i] introduces an invalid URI */
return 0;
}
}
/* *i is the first uri_text position past the \a query production, maybe \0 */
return 1;
}
static void parse_query_parts(grpc_uri* uri) {
static const char* QUERY_PARTS_SEPARATOR = "&";
static const char* QUERY_PARTS_VALUE_SEPARATOR = "=";
GPR_ASSERT(uri->query != NULL);
if (uri->query[0] == '\0') {
uri->query_parts = NULL;
uri->query_parts_values = NULL;
uri->num_query_parts = 0;
return;
}
gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts,
&uri->num_query_parts);
uri->query_parts_values =
(char**)gpr_malloc(uri->num_query_parts * sizeof(char**));
for (size_t i = 0; i < uri->num_query_parts; i++) {
char** query_param_parts;
size_t num_query_param_parts;
char* full = uri->query_parts[i];
gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts,
&num_query_param_parts);
GPR_ASSERT(num_query_param_parts > 0);
uri->query_parts[i] = query_param_parts[0];
if (num_query_param_parts > 1) {
/* TODO(dgq): only the first value after the separator is considered.
* Perhaps all chars after the first separator for the query part should
* be included, even if they include the separator. */
uri->query_parts_values[i] = query_param_parts[1];
} else {
uri->query_parts_values[i] = NULL;
}
for (size_t j = 2; j < num_query_param_parts; j++) {
gpr_free(query_param_parts[j]);
}
gpr_free(query_param_parts);
gpr_free(full);
}
}
grpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text,
bool suppress_errors) {
grpc_uri* uri;
size_t scheme_begin = 0;
size_t scheme_end = NOT_SET;
size_t authority_begin = NOT_SET;
size_t authority_end = NOT_SET;
size_t path_begin = NOT_SET;
size_t path_end = NOT_SET;
size_t query_begin = NOT_SET;
size_t query_end = NOT_SET;
size_t fragment_begin = NOT_SET;
size_t fragment_end = NOT_SET;
size_t i;
for (i = scheme_begin; uri_text[i] != 0; i++) {
if (uri_text[i] == ':') {
scheme_end = i;
break;
}
if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue;
if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue;
if (i != scheme_begin) {
if (uri_text[i] >= '0' && uri_text[i] <= '9') continue;
if (uri_text[i] == '+') continue;
if (uri_text[i] == '-') continue;
if (uri_text[i] == '.') continue;
}
break;
}
if (scheme_end == NOT_SET) {
return bad_uri(uri_text, i, "scheme", suppress_errors);
}
if (uri_text[scheme_end + 1] == '/' && uri_text[scheme_end + 2] == '/') {
authority_begin = scheme_end + 3;
for (i = authority_begin; uri_text[i] != 0 && authority_end == NOT_SET;
i++) {
if (uri_text[i] == '/' || uri_text[i] == '?' || uri_text[i] == '#') {
authority_end = i;
}
}
if (authority_end == NOT_SET && uri_text[i] == 0) {
authority_end = i;
}
if (authority_end == NOT_SET) {
return bad_uri(uri_text, i, "authority", suppress_errors);
}
/* TODO(ctiller): parse the authority correctly */
path_begin = authority_end;
} else {
path_begin = scheme_end + 1;
}
for (i = path_begin; uri_text[i] != 0; i++) {
if (uri_text[i] == '?' || uri_text[i] == '#') {
path_end = i;
break;
}
}
if (path_end == NOT_SET && uri_text[i] == 0) {
path_end = i;
}
if (path_end == NOT_SET) {
return bad_uri(uri_text, i, "path", suppress_errors);
}
if (uri_text[i] == '?') {
query_begin = ++i;
if (!parse_fragment_or_query(uri_text, &i)) {
return bad_uri(uri_text, i, "query", suppress_errors);
} else if (uri_text[i] != 0 && uri_text[i] != '#') {
/* We must be at the end or at the beginning of a fragment */
return bad_uri(uri_text, i, "query", suppress_errors);
}
query_end = i;
}
if (uri_text[i] == '#') {
fragment_begin = ++i;
if (!parse_fragment_or_query(uri_text, &i)) {
return bad_uri(uri_text, i - fragment_end, "fragment", suppress_errors);
} else if (uri_text[i] != 0) {
/* We must be at the end */
return bad_uri(uri_text, i, "fragment", suppress_errors);
}
fragment_end = i;
}
uri = (grpc_uri*)gpr_zalloc(sizeof(*uri));
uri->scheme =
decode_and_copy_component(exec_ctx, uri_text, scheme_begin, scheme_end);
uri->authority = decode_and_copy_component(exec_ctx, uri_text,
authority_begin, authority_end);
uri->path =
decode_and_copy_component(exec_ctx, uri_text, path_begin, path_end);
uri->query =
decode_and_copy_component(exec_ctx, uri_text, query_begin, query_end);
uri->fragment = decode_and_copy_component(exec_ctx, uri_text, fragment_begin,
fragment_end);
parse_query_parts(uri);
return uri;
}
const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) {
GPR_ASSERT(key != NULL);
if (key[0] == '\0') return NULL;
for (size_t i = 0; i < uri->num_query_parts; ++i) {
if (0 == strcmp(key, uri->query_parts[i])) {
return uri->query_parts_values[i];
}
}
return NULL;
}
void grpc_uri_destroy(grpc_uri* uri) {
if (!uri) return;
gpr_free(uri->scheme);
gpr_free(uri->authority);
gpr_free(uri->path);
gpr_free(uri->query);
for (size_t i = 0; i < uri->num_query_parts; ++i) {
gpr_free(uri->query_parts[i]);
gpr_free(uri->query_parts_values[i]);
}
gpr_free(uri->query_parts);
gpr_free(uri->query_parts_values);
gpr_free(uri->fragment);
gpr_free(uri);
}
<|endoftext|>
|
<commit_before>/*
*The MIT License (MIT)
*
* Copyright (c) <2016> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE http_connection_tests
#include <boost/test/unit_test.hpp>
#include <errno.h>
#include "buffered_socket.h"
#include "eventloop.h"
#include "http_connection.h"
#include "socket.h"
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif
static bool close_called = false;
static bool create_called = false;
static const char *readbuffer;
static const char *readbuffer_ptr;
static size_t readbuffer_length;
static char write_buffer[5000];
size_t write_buffer_written;
static char *write_buffer_ptr;
static const int FD_WOULDBLOCK = 1;
static const int FD_COMPLETE_STARTLINE = 2;
static const int FD_CLOSE = 3;
static const int FD_ERROR = 4;
extern "C" {
ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)
{
(void)io_vec;
(void)count;
switch (sock) {
case FD_COMPLETE_STARTLINE: {
size_t complete_length = 0;
for (unsigned int i = 0; i < count; i++) {
memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);
complete_length += io_vec[i].iov_len;
write_buffer_ptr += io_vec[i].iov_len;
}
write_buffer_written = complete_length;
return complete_length;
}
case FD_WOULDBLOCK:
default:
errno = EWOULDBLOCK;
return -1;
}
}
ssize_t socket_read(socket_type sock, void *buf, size_t count)
{
(void)buf;
(void)count;
switch (sock) {
case FD_COMPLETE_STARTLINE:
if (readbuffer_length > 0) {
size_t len = MIN(readbuffer_length, count);
memcpy(buf, readbuffer_ptr, len);
readbuffer_length -= len;
readbuffer_ptr += len;
return len;
} else {
errno = EWOULDBLOCK;
return -1;
}
break;
case FD_CLOSE:
return 0;
case FD_ERROR:
errno = EINVAL;
return -1;
case FD_WOULDBLOCK:
default:
errno = EWOULDBLOCK;
return -1;
}
}
int socket_close(socket_type sock)
{
(void)sock;
close_called = true;
return 0;
}
}
static enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)
{
(void)this_ptr;
(void)ev;
return EL_CONTINUE_LOOP;
}
static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)
{
(void)this_ptr;
(void)ev;
}
int on_create(struct http_connection *connection)
{
(void)connection;
create_called = true;
return 0;
}
struct F {
F()
{
close_called = false;
create_called = false;
loop.init = NULL;
loop.destroy = NULL;
loop.run = NULL;
loop.add = eventloop_fake_add;
loop.remove = eventloop_fake_remove;
readbuffer_ptr = readbuffer;
write_buffer_ptr = write_buffer;
write_buffer_written = 0;
http_parser_settings_init(&parser_settings);
http_parser_init(&parser, HTTP_RESPONSE);
handler[0].request_target = "/";
handler[0].create = NULL;
handler[0].on_header_field = NULL;
handler[0].on_header_value = NULL;
handler[0].on_headers_complete = NULL;
handler[0].on_body = NULL;
handler[0].on_message_complete = NULL;
http_server.handler = handler;
http_server.num_handlers = ARRAY_SIZE(handler);
}
~F()
{
}
struct eventloop loop;
http_parser parser;
http_parser_settings parser_settings;
struct url_handler handler[1];
struct http_server http_server;
};
BOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F)
{
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);
BOOST_CHECK_MESSAGE(connection != NULL, "Connection allocation failed!");
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F)
{
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);
BOOST_CHECK(connection != NULL);
struct buffered_socket *bs = connection->bs;
connection->bs = NULL;
free_connection(connection);
BOOST_CHECK_MESSAGE(!close_called, "Close was called after buffered_socket migration!");
buffered_socket_close(bs);
free(bs);
BOOST_CHECK_MESSAGE(close_called, "Close was not called after buffered_socket_close!");
}
BOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_close, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_error, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F)
{
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection != NULL);
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F)
{
handler[0].create = on_create;
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection != NULL);
BOOST_CHECK_MESSAGE(create_called, "Create callback was not called!");
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F)
{
handler[0].request_target = "/foobar/";
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 404);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F)
{
handler[0].request_target = "/foobar/";
readbuffer = "GET http://ww%.google.de/ HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 400);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F)
{
readbuffer = "CONNECT www.example.com:443 HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 400);
}
<commit_msg>Initialize loop variable completely.<commit_after>/*
*The MIT License (MIT)
*
* Copyright (c) <2016> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE http_connection_tests
#include <boost/test/unit_test.hpp>
#include <errno.h>
#include "buffered_socket.h"
#include "eventloop.h"
#include "http_connection.h"
#include "socket.h"
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#endif
static bool close_called = false;
static bool create_called = false;
static const char *readbuffer;
static const char *readbuffer_ptr;
static size_t readbuffer_length;
static char write_buffer[5000];
size_t write_buffer_written;
static char *write_buffer_ptr;
static const int FD_WOULDBLOCK = 1;
static const int FD_COMPLETE_STARTLINE = 2;
static const int FD_CLOSE = 3;
static const int FD_ERROR = 4;
extern "C" {
ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)
{
(void)io_vec;
(void)count;
switch (sock) {
case FD_COMPLETE_STARTLINE: {
size_t complete_length = 0;
for (unsigned int i = 0; i < count; i++) {
memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);
complete_length += io_vec[i].iov_len;
write_buffer_ptr += io_vec[i].iov_len;
}
write_buffer_written = complete_length;
return complete_length;
}
case FD_WOULDBLOCK:
default:
errno = EWOULDBLOCK;
return -1;
}
}
ssize_t socket_read(socket_type sock, void *buf, size_t count)
{
(void)buf;
(void)count;
switch (sock) {
case FD_COMPLETE_STARTLINE:
if (readbuffer_length > 0) {
size_t len = MIN(readbuffer_length, count);
memcpy(buf, readbuffer_ptr, len);
readbuffer_length -= len;
readbuffer_ptr += len;
return len;
} else {
errno = EWOULDBLOCK;
return -1;
}
break;
case FD_CLOSE:
return 0;
case FD_ERROR:
errno = EINVAL;
return -1;
case FD_WOULDBLOCK:
default:
errno = EWOULDBLOCK;
return -1;
}
}
int socket_close(socket_type sock)
{
(void)sock;
close_called = true;
return 0;
}
}
static enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)
{
(void)this_ptr;
(void)ev;
return EL_CONTINUE_LOOP;
}
static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)
{
(void)this_ptr;
(void)ev;
}
int on_create(struct http_connection *connection)
{
(void)connection;
create_called = true;
return 0;
}
struct F {
F()
{
close_called = false;
create_called = false;
loop.this_ptr = NULL;
loop.init = NULL;
loop.destroy = NULL;
loop.run = NULL;
loop.add = eventloop_fake_add;
loop.remove = eventloop_fake_remove;
readbuffer_ptr = readbuffer;
write_buffer_ptr = write_buffer;
write_buffer_written = 0;
http_parser_settings_init(&parser_settings);
http_parser_init(&parser, HTTP_RESPONSE);
handler[0].request_target = "/";
handler[0].create = NULL;
handler[0].on_header_field = NULL;
handler[0].on_header_value = NULL;
handler[0].on_headers_complete = NULL;
handler[0].on_body = NULL;
handler[0].on_message_complete = NULL;
http_server.handler = handler;
http_server.num_handlers = ARRAY_SIZE(handler);
}
~F()
{
}
struct eventloop loop;
http_parser parser;
http_parser_settings parser_settings;
struct url_handler handler[1];
struct http_server http_server;
};
BOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F)
{
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);
BOOST_CHECK_MESSAGE(connection != NULL, "Connection allocation failed!");
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F)
{
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);
BOOST_CHECK(connection != NULL);
struct buffered_socket *bs = connection->bs;
connection->bs = NULL;
free_connection(connection);
BOOST_CHECK_MESSAGE(!close_called, "Close was called after buffered_socket migration!");
buffered_socket_close(bs);
free(bs);
BOOST_CHECK_MESSAGE(close_called, "Close was not called after buffered_socket_close!");
}
BOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_close, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_error, F)
{
readbuffer = "aaaa\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false);
BOOST_CHECK(connection == NULL);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F)
{
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection != NULL);
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F)
{
handler[0].create = on_create;
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection != NULL);
BOOST_CHECK_MESSAGE(create_called, "Create callback was not called!");
free_connection(connection);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F)
{
handler[0].request_target = "/foobar/";
readbuffer = "GET /infotext.html HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 404);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F)
{
handler[0].request_target = "/foobar/";
readbuffer = "GET http://ww%.google.de/ HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 400);
}
BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F)
{
readbuffer = "CONNECT www.example.com:443 HTTP/1.1\r\n";
readbuffer_ptr = readbuffer;
readbuffer_length = ::strlen(readbuffer);
struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);
BOOST_CHECK(connection == NULL);
size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);
BOOST_CHECK(nparsed == write_buffer_written);
BOOST_CHECK(parser.status_code == 400);
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// The number of pages a cluster consists of (2^p) is dependent
// on the cluster, so the world must store the ps in the special
// cluster in order to be able to find the cluster boundaries.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// Checker templates
//
template <unsigned>
struct IsZero;
template <>
struct IsZero<0>
{};
template <unsigned long DIVISOR, unsigned long DIVIDEND>
struct Divides : IsZero<DIVIDEND % DIVISOR>
{};
// World: define the layout of a world in the memory
// and subdivide in pages. Provide info about the
// location and size.
// NUMPAGES: how many pages should this world hold
// BASE: where should this world be located in the memory
// PAGE: bits needed to address a byte in a page. i.e.
// pagesize == 2^PAGE bytes
//
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct World
{
enum { PageSize = 1 << PAGE };
struct Page
{
char raw[PageSize];
};
Page pages[NUMPAGES];
static void* start(void)
{
Divides<PageSize, BASE> c1;
return reinterpret_cast<void*>(BASE);
}
static size_t size(void)
{
return PageSize * NUMPAGES;
}
void protectPageRW(unsigned pagenum)
{
protectClusterRW(pagenum, 1);
}
void protectClusterRW(unsigned from_pagenum, unsigned ps)
{
if (0 != mprotect(pages + from_pagenum, PageSize * ps, PROT_NONE))
perror("mprotect");
}
void* operator new(size_t s, int hdl)
{
void* here(mmap(start(),
s,
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == here)
perror("mmap");
assert(s == size());
assert(here == start());
assert(sysconf(_SC_PAGESIZE) == PageSize);
return here;
}
};
// MISC ideas
// allocation: tell a cluster to allocate an obj of a certain
// metadata "class". returns a cluster address, which may be the
// same as the current cluster or pointer to a new cluster with
// the object being in there. In this case the pointer must be
// stored away for the next allocation request.
// GC: use a posix message queue to tell which thread stack ranges
// must be mprotected. This way the threads can be starved out
// systematically.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct ClusteredWorld : World<NUMPAGES, BASE, PAGE>
{
template <unsigned long CLUSTER, unsigned long SCALE>
struct Cluster
{
static inline void* Raw2Meta(void* obj)
{
return RawObj2Meta<PAGE, CLUSTER, SCALE>(obj);
}
};
};
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
// http://www.opengroup.org/onlinepubs/007908799/xsh/sigaction.html
// http://www.gnu.org/software/libc/manual/html_node/Sigaction-Function-Example.html
// http://www.opengroup.org/onlinepubs/000095399/basedefs/signal.h.html
void yummy(int, siginfo_t *, void *);
void yummy(int, siginfo_t* indo, void *)
{
printf("gggg\n");
abort();
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
# ifdef __APPLE__
typedef ClusteredWorld<100, 0xFF000000UL, 12> world;
# else
typedef ClusteredWorld<100, 0xFF000000UL, 13> world;
# endif
int tr(ftruncate(hdl, world::size()));
if (tr == -1)
perror("ftruncate");
world* w(new(hdl) world);
void* area(w);
if (MAP_FAILED == area)
perror("mmap");
w->protectPageRW(0);
struct sigaction act, oact;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
act.sa_sigaction = yummy;
if (sigaction(SIGBUS/*SEGV*/, &act, &oact))
perror("sigaction");
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, world::Cluster<4, 3>::Raw2Meta(p));
*p = 0;
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, world::Cluster<4, 3>::Raw2Meta(p));
*p = 0;
}
sleep(3);
int um(munmap(area, world::size()));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<commit_msg>do the right thing on Solaris<commit_after>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// The number of pages a cluster consists of (2^p) is dependent
// on the cluster, so the world must store the ps in the special
// cluster in order to be able to find the cluster boundaries.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// Checker templates
//
template <unsigned>
struct IsZero;
template <>
struct IsZero<0>
{};
template <unsigned long DIVISOR, unsigned long DIVIDEND>
struct Divides : IsZero<DIVIDEND % DIVISOR>
{};
// World: define the layout of a world in the memory
// and subdivide in pages. Provide info about the
// location and size.
// NUMPAGES: how many pages should this world hold
// BASE: where should this world be located in the memory
// PAGE: bits needed to address a byte in a page. i.e.
// pagesize == 2^PAGE bytes
//
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct World
{
enum { PageSize = 1 << PAGE };
struct Page
{
char raw[PageSize];
};
Page pages[NUMPAGES];
static void* start(void)
{
Divides<PageSize, BASE> c1;
return reinterpret_cast<void*>(BASE);
}
static size_t size(void)
{
return PageSize * NUMPAGES;
}
void protectPageRW(unsigned pagenum)
{
protectClusterRW(pagenum, 1);
}
void protectClusterRW(unsigned from_pagenum, unsigned ps)
{
if (0 != mprotect(pages + from_pagenum, PageSize * ps, PROT_NONE))
perror("mprotect");
}
void* operator new(size_t s, int hdl)
{
void* here(mmap(start(),
s,
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == here)
perror("mmap");
assert(s == size());
assert(here == start());
assert(sysconf(_SC_PAGESIZE) == PageSize);
return here;
}
};
// MISC ideas
// allocation: tell a cluster to allocate an obj of a certain
// metadata "class". returns a cluster address, which may be the
// same as the current cluster or pointer to a new cluster with
// the object being in there. In this case the pointer must be
// stored away for the next allocation request.
// GC: use a posix message queue to tell which thread stack ranges
// must be mprotected. This way the threads can be starved out
// systematically.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct ClusteredWorld : World<NUMPAGES, BASE, PAGE>
{
template <unsigned long CLUSTER, unsigned long SCALE>
struct Cluster
{
static inline void* Raw2Meta(void* obj)
{
return RawObj2Meta<PAGE, CLUSTER, SCALE>(obj);
}
};
};
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
// http://www.opengroup.org/onlinepubs/007908799/xsh/sigaction.html
// http://www.gnu.org/software/libc/manual/html_node/Sigaction-Function-Example.html
// http://www.opengroup.org/onlinepubs/000095399/basedefs/signal.h.html
void yummy(int, siginfo_t *, void *);
void yummy(int, siginfo_t* indo, void *)
{
printf("gggg\n");
abort();
}
void wummy(int, siginfo_t *, void *);
void wummy(int, siginfo_t* indo, void *)
{
printf("Solaris:gggg\n");
abort();
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
# ifdef __APPLE__
typedef ClusteredWorld<100, 0xFF000000UL, 12> world;
# else
typedef ClusteredWorld<100, 0xFF000000UL, 13> world;
# endif
int tr(ftruncate(hdl, world::size()));
if (tr == -1)
perror("ftruncate");
world* w(new(hdl) world);
void* area(w);
if (MAP_FAILED == area)
perror("mmap");
w->protectPageRW(0);
struct sigaction act, oact;
memset(&act, 0, sizeof act);
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
# ifdef __APPLE__
act.sa_sigaction = yummy;
if (sigaction(SIGBUS, &act, &oact))
# else
act.sa_sigaction = wummy;
if (sigaction(SIGSEGV, &act, &oact))
# endif
perror("sigaction");
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, world::Cluster<4, 3>::Raw2Meta(p));
*p = 0;
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, world::Cluster<4, 3>::Raw2Meta(p));
*p = 0;
}
sleep(3);
int um(munmap(area, world::size()));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
#include <tightdb/column_string_enum.hpp>
#include <tightdb/index_string.hpp>
using namespace std;
using namespace tightdb;
namespace {
// Getter function for string index
StringData get_string(void* column, size_t ndx)
{
return static_cast<ColumnStringEnum*>(column)->get(ndx);
}
} // anonymous namespace
ColumnStringEnum::ColumnStringEnum(ref_type keys, ref_type values, ArrayParent* column_parent,
size_t column_ndx_in_parent, ArrayParent* keys_parent,
size_t keys_ndx_in_parent, Allocator& alloc):
Column(values, column_parent, column_ndx_in_parent, alloc), // Throws
m_keys(keys, keys_parent, keys_ndx_in_parent, alloc), // Throws
m_index(0)
{
}
ColumnStringEnum::~ColumnStringEnum() TIGHTDB_NOEXCEPT
{
delete m_index;
}
void ColumnStringEnum::destroy() TIGHTDB_NOEXCEPT
{
m_keys.destroy();
Column::destroy();
if (m_index)
m_index->destroy();
}
void ColumnStringEnum::adjust_keys_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT
{
m_keys.adjust_ndx_in_parent(diff);
}
void ColumnStringEnum::adjust_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT
{
Column::adjust_ndx_in_parent(diff);
}
void ColumnStringEnum::update_from_parent(size_t old_baseline) TIGHTDB_NOEXCEPT
{
m_array->update_from_parent(old_baseline);
m_keys.update_from_parent(old_baseline);
}
void ColumnStringEnum::add(StringData value)
{
insert(Column::size(), value);
}
void ColumnStringEnum::set(size_t ndx, StringData value)
{
TIGHTDB_ASSERT(ndx < Column::size());
// Update index
// (it is important here that we do it before actually setting
// the value, or the index would not be able to find the correct
// position to update (as it looks for the old value))
if (m_index) {
StringData oldVal = get(ndx);
m_index->set(ndx, oldVal, value);
}
size_t key_ndx = GetKeyNdxOrAdd(value);
Column::set(ndx, key_ndx);
}
void ColumnStringEnum::insert(size_t ndx, StringData value)
{
TIGHTDB_ASSERT(ndx <= Column::size());
size_t key_ndx = GetKeyNdxOrAdd(value);
Column::insert(ndx, key_ndx);
if (m_index) {
bool is_last = ndx+1 == size();
m_index->insert(ndx, value, is_last);
}
}
void ColumnStringEnum::erase(size_t ndx, bool is_last)
{
TIGHTDB_ASSERT(ndx < Column::size());
// Update index
// (it is important here that we do it before actually setting
// the value, or the index would not be able to find the correct
// position to update (as it looks for the old value))
if (m_index) {
StringData old_val = get(ndx);
m_index->erase(ndx, old_val, is_last);
}
Column::erase(ndx, is_last);
}
void ColumnStringEnum::clear()
{
// Note that clearing a StringEnum does not remove keys
Column::clear();
if (m_index)
m_index->clear();
}
size_t ColumnStringEnum::count(size_t key_ndx) const
{
return Column::count(key_ndx);
}
size_t ColumnStringEnum::count(StringData value) const
{
if (m_index)
return m_index->count(value);
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == not_found) return 0;
return Column::count(key_ndx);
}
void ColumnStringEnum::find_all(Array& res, StringData value, size_t begin, size_t end) const
{
if (m_index && begin == 0 && end == size_t(-1))
return m_index->find_all(res, value);
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == size_t(-1)) return;
Column::find_all(res, key_ndx, begin, end);
return;
}
void ColumnStringEnum::find_all(Array& res, size_t key_ndx, size_t begin, size_t end) const
{
if (key_ndx == size_t(-1)) return;
Column::find_all(res, key_ndx, begin, end);
return;
}
FindRes ColumnStringEnum::find_all_indexref(StringData value, size_t& dst) const
{
// TIGHTDB_ASSERT(value.m_data); fixme
TIGHTDB_ASSERT(m_index);
return m_index->find_all(value, dst);
}
size_t ColumnStringEnum::find_first(size_t key_ndx, size_t begin, size_t end) const
{
// Find key
if (key_ndx == size_t(-1)) return size_t(-1);
return Column::find_first(key_ndx, begin, end);
}
size_t ColumnStringEnum::find_first(StringData value, size_t begin, size_t end) const
{
if (m_index && begin == 0 && end == size_t(-1))
return m_index->find_first(value);
// Find key
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == size_t(-1)) return size_t(-1);
return Column::find_first(key_ndx, begin, end);
}
size_t ColumnStringEnum::GetKeyNdx(StringData value) const
{
return m_keys.find_first(value);
}
size_t ColumnStringEnum::GetKeyNdxOrAdd(StringData value)
{
size_t res = m_keys.find_first(value);
if (res != size_t(-1)) return res;
else {
// Add key if it does not exist
size_t pos = m_keys.size();
m_keys.add(value);
return pos;
}
}
bool ColumnStringEnum::compare_string(const AdaptiveStringColumn& c) const
{
const size_t n = size();
if (c.size() != n) return false;
for (size_t i=0; i<n; ++i) {
if (get(i) != c.get(i)) return false;
}
return true;
}
bool ColumnStringEnum::compare_string(const ColumnStringEnum& c) const
{
const size_t n = size();
if (c.size() != n) return false;
for (size_t i=0; i<n; ++i) {
if (get(i) != c.get(i)) return false;
}
return true;
}
StringIndex& ColumnStringEnum::create_index()
{
TIGHTDB_ASSERT(m_index == null_ptr);
// Create new index
m_index = new StringIndex(this, &get_string, m_array->get_alloc());
// Populate the index
const size_t count = size();
for (size_t i = 0; i < count; ++i) {
StringData value = get(i);
m_index->insert(i, value, true);
}
return *m_index;
}
void ColumnStringEnum::set_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent)
{
TIGHTDB_ASSERT(!m_index);
m_index = new StringIndex(ref, parent, ndx_in_parent, this, &get_string, m_array->get_alloc());
}
void ColumnStringEnum::install_index(StringIndex* index) TIGHTDB_NOEXCEPT
{
TIGHTDB_ASSERT(m_index == null_ptr);
index->set_target(this, &get_string);
m_index = index; // we now own this index
}
#ifdef TIGHTDB_DEBUG
void ColumnStringEnum::Verify() const
{
m_keys.Verify();
Column::Verify();
}
void ColumnStringEnum::to_dot(ostream& out, StringData title) const
{
ref_type ref = m_keys.get_ref();
out << "subgraph cluster_string_enum_column" << ref << " {" << endl;
out << " label = \"String enum column";
if (title.size() != 0)
out << "\\n'" << title << "'";
out << "\";" << endl;
m_keys.to_dot(out, "keys");
Column::to_dot(out, "values");
out << "}" << endl;
}
namespace {
void leaf_dumper(MemRef mem, Allocator& alloc, ostream& out, int level)
{
Array leaf(mem, 0, 0, alloc);
int indent = level * 2;
out << setw(indent) << "" << "String enumeration leaf (size: "<<leaf.size()<<")\n";
}
} // anonymous namespace
void ColumnStringEnum::dump_node_structure(ostream& out, int level) const
{
m_array->dump_bptree_structure(out, level, &leaf_dumper);
}
#endif // TIGHTDB_DEBUG
<commit_msg>A bit of style cleanup<commit_after>#include <iostream>
#include <iomanip>
#include <tightdb/column_string_enum.hpp>
#include <tightdb/index_string.hpp>
using namespace std;
using namespace tightdb;
namespace {
// Getter function for string index
StringData get_string(void* column, size_t ndx)
{
return static_cast<ColumnStringEnum*>(column)->get(ndx);
}
} // anonymous namespace
ColumnStringEnum::ColumnStringEnum(ref_type keys, ref_type values, ArrayParent* column_parent,
size_t column_ndx_in_parent, ArrayParent* keys_parent,
size_t keys_ndx_in_parent, Allocator& alloc):
Column(values, column_parent, column_ndx_in_parent, alloc), // Throws
m_keys(keys, keys_parent, keys_ndx_in_parent, alloc), // Throws
m_index(0)
{
}
ColumnStringEnum::~ColumnStringEnum() TIGHTDB_NOEXCEPT
{
delete m_index;
}
void ColumnStringEnum::destroy() TIGHTDB_NOEXCEPT
{
m_keys.destroy();
Column::destroy();
if (m_index)
m_index->destroy();
}
void ColumnStringEnum::adjust_keys_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT
{
m_keys.adjust_ndx_in_parent(diff);
}
void ColumnStringEnum::adjust_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT
{
Column::adjust_ndx_in_parent(diff);
}
void ColumnStringEnum::update_from_parent(size_t old_baseline) TIGHTDB_NOEXCEPT
{
m_array->update_from_parent(old_baseline);
m_keys.update_from_parent(old_baseline);
}
void ColumnStringEnum::add(StringData value)
{
insert(Column::size(), value);
}
void ColumnStringEnum::set(size_t ndx, StringData value)
{
TIGHTDB_ASSERT(ndx < Column::size());
// Update index
// (it is important here that we do it before actually setting
// the value, or the index would not be able to find the correct
// position to update (as it looks for the old value))
if (m_index) {
StringData oldVal = get(ndx);
m_index->set(ndx, oldVal, value);
}
size_t key_ndx = GetKeyNdxOrAdd(value);
Column::set(ndx, key_ndx);
}
void ColumnStringEnum::insert(size_t ndx, StringData value)
{
TIGHTDB_ASSERT(ndx <= Column::size());
size_t key_ndx = GetKeyNdxOrAdd(value);
Column::insert(ndx, key_ndx);
if (m_index) {
bool is_last = ndx+1 == size();
m_index->insert(ndx, value, is_last);
}
}
void ColumnStringEnum::erase(size_t ndx, bool is_last)
{
TIGHTDB_ASSERT(ndx < Column::size());
// Update index
// (it is important here that we do it before actually setting
// the value, or the index would not be able to find the correct
// position to update (as it looks for the old value))
if (m_index) {
StringData old_val = get(ndx);
m_index->erase(ndx, old_val, is_last);
}
Column::erase(ndx, is_last);
}
void ColumnStringEnum::clear()
{
// Note that clearing a StringEnum does not remove keys
Column::clear();
if (m_index)
m_index->clear();
}
size_t ColumnStringEnum::count(size_t key_ndx) const
{
return Column::count(key_ndx);
}
size_t ColumnStringEnum::count(StringData value) const
{
if (m_index)
return m_index->count(value);
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == not_found)
return 0;
return Column::count(key_ndx);
}
void ColumnStringEnum::find_all(Array& res, StringData value, size_t begin, size_t end) const
{
if (m_index && begin == 0 && end == size_t(-1))
return m_index->find_all(res, value);
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == size_t(-1))
return;
Column::find_all(res, key_ndx, begin, end);
}
void ColumnStringEnum::find_all(Array& res, size_t key_ndx, size_t begin, size_t end) const
{
if (key_ndx == size_t(-1))
return;
Column::find_all(res, key_ndx, begin, end);
}
FindRes ColumnStringEnum::find_all_indexref(StringData value, size_t& dst) const
{
// TIGHTDB_ASSERT(value.m_data); fixme
TIGHTDB_ASSERT(m_index);
return m_index->find_all(value, dst);
}
size_t ColumnStringEnum::find_first(size_t key_ndx, size_t begin, size_t end) const
{
// Find key
if (key_ndx == size_t(-1))
return size_t(-1);
return Column::find_first(key_ndx, begin, end);
}
size_t ColumnStringEnum::find_first(StringData value, size_t begin, size_t end) const
{
if (m_index && begin == 0 && end == size_t(-1))
return m_index->find_first(value);
// Find key
size_t key_ndx = m_keys.find_first(value);
if (key_ndx == size_t(-1))
return size_t(-1);
return Column::find_first(key_ndx, begin, end);
}
size_t ColumnStringEnum::GetKeyNdx(StringData value) const
{
return m_keys.find_first(value);
}
size_t ColumnStringEnum::GetKeyNdxOrAdd(StringData value)
{
size_t res = m_keys.find_first(value);
if (res != size_t(-1))
return res;
else {
// Add key if it does not exist
size_t pos = m_keys.size();
m_keys.add(value);
return pos;
}
}
bool ColumnStringEnum::compare_string(const AdaptiveStringColumn& c) const
{
size_t n = size();
if (c.size() != n)
return false;
for (size_t i = 0; i != n; ++i) {
if (get(i) != c.get(i))
return false;
}
return true;
}
bool ColumnStringEnum::compare_string(const ColumnStringEnum& c) const
{
size_t n = size();
if (c.size() != n)
return false;
for (size_t i = 0; i != n; ++i) {
if (get(i) != c.get(i))
return false;
}
return true;
}
StringIndex& ColumnStringEnum::create_index()
{
TIGHTDB_ASSERT(!m_index);
// Create new index
m_index = new StringIndex(this, &get_string, m_array->get_alloc());
// Populate the index
size_t n = size();
for (size_t i = 0; i != n; ++i) {
StringData value = get(i);
m_index->insert(i, value, true);
}
return *m_index;
}
void ColumnStringEnum::set_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent)
{
TIGHTDB_ASSERT(!m_index);
m_index = new StringIndex(ref, parent, ndx_in_parent, this, &get_string, m_array->get_alloc());
}
void ColumnStringEnum::install_index(StringIndex* index) TIGHTDB_NOEXCEPT
{
TIGHTDB_ASSERT(m_index == null_ptr);
index->set_target(this, &get_string);
m_index = index; // we now own this index
}
#ifdef TIGHTDB_DEBUG
void ColumnStringEnum::Verify() const
{
m_keys.Verify();
Column::Verify();
}
void ColumnStringEnum::to_dot(ostream& out, StringData title) const
{
ref_type ref = m_keys.get_ref();
out << "subgraph cluster_string_enum_column" << ref << " {" << endl;
out << " label = \"String enum column";
if (title.size() != 0)
out << "\\n'" << title << "'";
out << "\";" << endl;
m_keys.to_dot(out, "keys");
Column::to_dot(out, "values");
out << "}" << endl;
}
namespace {
void leaf_dumper(MemRef mem, Allocator& alloc, ostream& out, int level)
{
Array leaf(mem, 0, 0, alloc);
int indent = level * 2;
out << setw(indent) << "" << "String enumeration leaf (size: "<<leaf.size()<<")\n";
}
} // anonymous namespace
void ColumnStringEnum::dump_node_structure(ostream& out, int level) const
{
m_array->dump_bptree_structure(out, level, &leaf_dumper);
}
#endif // TIGHTDB_DEBUG
<|endoftext|>
|
<commit_before>/*
* spatial_displacement_leafless.cpp
*
* Created on: Aug 12, 2010
* Author: Mark Christensen
*/
#include "spatial_displacement_leafless.h"
#include "../system/discursive_system.h"
using namespace std;
SpatialDisplacementLeafless::SpatialDisplacementLeafless(int width, int height):width(width), height(height), growthUnit(5.0)
{
}
void SpatialDisplacementLeafless::decorate(SurrogateTreeNode* tree)
{
// Iterate over each node with children
// First, "count". Calculates child center of mass and subtree depth
this->count(tree);
// Second, float weighted surrogate nodes into position
//this->expand(tree,(3.14159/2),0,0);
// Max tree depth
double maxDepth = tree->findMax(TreeNodeKey::DEPTH);
this->expand(tree,(3.14159/2),0,0,(this->height)/maxDepth);
// Third, transform coordinates
this->transform(tree);
}
// Scale point values to fit within width and height give
// with root at (width/2, height)
// Transformation flips y values and shifts x values
// after scaling
void SpatialDisplacementLeafless::transform(SurrogateTreeNode* tree)
{
// Calculate resize scaling factors
double allowedWidth = this->width;
double allowedHeight = this->height;
double xMax = tree->findMax(TreeNodeKey::X);
double xMin = tree->findMin(TreeNodeKey::X);
double yMax = tree->findMax(TreeNodeKey::Y);
double yMin = tree->findMin(TreeNodeKey::Y);
DiscursiveDebugPrint("Mins: (%f,%f), Maxs: (%f,%f)\n",xMin,yMin,xMax,yMax);
double currWidth = xMax - xMin;
double currHeight = yMax - yMin;
double minDim = min(allowedHeight, allowedWidth);
double scalingFactorW = minDim/currWidth;
double scalingFactorH = minDim/currHeight;
// Transform points to look more "naturally tree-like"
tree->scale(TreeNodeKey::Y, scalingFactorH);
PropertyInverter inverter(this->height * 0.98);
tree->transform(TreeNodeKey::Y,&inverter);
PropertyShifter shifter(-1*((xMax + xMin) / 2));
tree->transform(TreeNodeKey::X,&shifter);
// Scale tree values
tree->scale(TreeNodeKey::X, scalingFactorW);
PropertyShifter shifter2(minDim * 1 / 2);
tree->transform(TreeNodeKey::X,&shifter2);
}
// Sorted in increasing order
void SpatialDisplacementLeafless::insertOrderedBy(vector<SurrogateTreeNode*>* list, SurrogateTreeNode* tree, string property)
{
//printf("Inserting '%s' from %s. Current size: %d\n",property.c_str(),tree->data[TreeNodeKey::NAME].c_str(), list->size());
SurrogateTreeNode* node;
bool inserted = false;
long comp = atol(tree->data[property].c_str());
long curr = 0;
for(vector<SurrogateTreeNode*>::iterator iter = list->begin(); iter != list->end(); ++iter)
{
node = *iter;
curr = atol(node->data[property].c_str());
//printf("%ld < %ld?\n",atol(tree->data[property].c_str()),atol(node->data[property].c_str()));
if(comp < curr)
{
list->insert(iter,tree);
inserted = true;
break;
}
}
if(!inserted)
{
//printf("Inserting at end\n");
list->push_back(tree);
}
}
void SpatialDisplacementLeafless::expand(SurrogateTreeNode* tree, double rootAngle, double rootX, double rootY, double allowedHeight)
{
if(tree->children->size() > 0)
{
// Determine initial layout based on creation time of child nodes.
// Files are split into different list than directories.
vector<SurrogateTreeNode*> files;
vector<SurrogateTreeNode*> dirs;
SurrogateTreeNode* node = NULL;
int maxChild = 1;
int childSize;
int mass = 0;
int children = 0;
double minChildMass = DBL_MAX;
for(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)
{
children++;
node = *iter;
// Directory
if(node->children->size() > 0)
{
//printf("Inserting into dirs...\n");
this->insertOrderedBy(&dirs,node,TreeNodeKey::SIZE);
childSize = atoi(node->data[TreeNodeKey::SIZE].c_str());
mass += childSize;
if(childSize > maxChild )
{
maxChild = childSize;
}
if(childSize < minChildMass)
{
minChildMass = childSize;
}
}
// File
else
{
//printf("Inserting into files...\n");
this->insertOrderedBy(&files,node,TreeNodeKey::CREATION_TIME);
mass++;
if(minChildMass > 1)
{
minChildMass = 1;
}
}
}
// Map for retrieving resutls
unordered_map<SurrogateTreeNode*,int> pairs;
double masses[children];
double positions[children];
memset(positions,0,children*sizeof(double));
// Layout directories first
// Start left if even number of items.
bool left = children % 2 != 0;
int center = children / 2;
int dist = 0;
//TreeDisplacementNode* treeNode;
int i = 0;
int location;
int nodeMass;
for(; i < (int)dirs.size(); i++)
{
dist = (i+1)/2;
nodeMass = atoi(dirs[i]->data[TreeNodeKey::SIZE].c_str());
if(left)
{
location = center - dist;
}
else
{
location = center + dist;
}
masses[location] = nodeMass;
pairs[dirs[i]] = location;
for(int k = location; k < children; k++)
{
positions[k] += nodeMass;
}
left = !left;
}
// Now layout files
for(int j = 0; j < (int)files.size(); j++)
{
dist = ((i + j + 1)/2);
nodeMass = 1;
if(left)
{
location = center - dist;
}
else
{
location = center + dist;
}
masses[location] = nodeMass;
pairs[files[j]] = location;
for(int k = location; k < children; k++)
{
positions[k] += nodeMass;
}
left = !left;
}
// Calculate spacing to range [0,splay]
double deltaSplay = 0;
double splay = 3.14159 / 2;
double com;
if(mass > minChildMass)
{
deltaSplay = splay / (mass - minChildMass);
}
DiscursiveDebugPrint("Subtree mass effects [");
for(i = 0; i < children; i++)
{
DiscursiveDebugPrint("%f,",positions[i]);
}
DiscursiveDebugPrint("] @ %f\n", deltaSplay);
positions[0] = 0;
com = 0;
for(i = 1; i < children; i++)
{
positions[i] = (positions[i] - minChildMass)*deltaSplay;
com += (positions[i] * masses[i]);
}
// Final part of CoM calculation
com /= mass;
// Transform positions to arc
//double arcRadius = 10.0;
// double deltaAngle = splay / children;
int maxDepth = (int)tree->findMax(TreeNodeKey::DEPTH);
int depth;
double arcRadius = allowedHeight/maxDepth;
double ratio;
double angle;
// Controls width of fan-out. > 1 : Wide tree
// < 1 : Narrow tree
double widthHeightScaleFactor = 1.0;
// Transform positions to arc and Update new positions
// Dirs first
for(i = 0; i < (int)dirs.size(); i++)
{
node = dirs[i];
depth = atoi(node->data[TreeNodeKey::DEPTH].c_str());
ratio = depth / (double)maxDepth;
angle = rootAngle - (positions[pairs[node]] - com);
double newX = rootX + (ratio * arcRadius * cos(angle));
double newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));
node->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));
node->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));
// Run expand on child
double childRot = (3.14159/2);//angle;// + ((3.14159/2)-angle)/2;
this->expand(node,childRot,newX,newY,allowedHeight - arcRadius);
}
// Then files
for(int j = 0; j < (int)files.size(); j++)
{
node = files[j];
depth = atoi(node->data[TreeNodeKey::DEPTH].c_str());
ratio = depth / (double)maxDepth;
angle = rootAngle - (positions[pairs[node]] - com);
double newX = rootX + (ratio * arcRadius * cos(angle));
double newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));
node->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));
node->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));
}
// for(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)
// {
// node = *iter;
// depth = atoi(node->data[TreeNodeKey::DEPTH].c_str());
// ratio = depth / (double)maxDepth;
// angle = rootAngle + ();
// double newX = rootX + ();
// double newY = rootY;
// //printf("%s final position at (%f,%f)\n",node->data[TreeNodeKey::NAME].c_str(),newX, newY);
// node->data[TreeNodeKey::X] = boost::lexical_cast<string>(newX);
// node->data[TreeNodeKey::Y] = boost::lexical_cast<string>(newY);
// printf("%s @ (%s,%s)\n",node->data[TreeNodeKey::NAME].c_str(),node->data[TreeNodeKey::X].c_str(),node->data[TreeNodeKey::Y].c_str());
// // Run expand on child
// double childRot = treeNode->getRotation() + ((3.14159/2)-treeNode->getRotation())/2;
// this->expand(node,childRot,newX,newY,allowedHeight - arcRadius);
// }
}
else
{
//printf("No children for node '%s'\n", tree->data[TreeNodeKey::NAME].c_str());
}
}
int SpatialDisplacementLeafless::count(SurrogateTreeNode* tree)
{
// Count all children plus ourselves (initial 1)
int sum = 1;
int maxDepth = 0;
int childDepth = 0;
for(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)
{
sum += this->count(*iter);
//childDepth = atoi((*iter)->data["count"].c_str());
childDepth = atoi((*iter)->data[TreeNodeKey::DEPTH].c_str());
if(childDepth > maxDepth)
{
maxDepth = childDepth;
}
}
// Assign count to data
tree->set(TreeNodeKey::SIZE, boost::lexical_cast<string>(sum));
DiscursiveDebugPrint("Size of tree %s is %s in this and %d sublevels\n",tree->data[TreeNodeKey::NAME].c_str(),tree->data[TreeNodeKey::SIZE].c_str(),maxDepth);
tree->set(TreeNodeKey::DEPTH, boost::lexical_cast<string>(maxDepth + 1));
return sum;
}
<commit_msg>Fixed some scaling but the layout is wrong for small trees now.<commit_after>/*
* spatial_displacement_leafless.cpp
*
* Created on: Aug 12, 2010
* Author: Mark Christensen
*/
#include "spatial_displacement_leafless.h"
#include "../system/discursive_system.h"
using namespace std;
SpatialDisplacementLeafless::SpatialDisplacementLeafless(int width, int height):width(width), height(height), growthUnit(5.0)
{
}
void SpatialDisplacementLeafless::decorate(SurrogateTreeNode* tree)
{
// Iterate over each node with children
// First, "count". Calculates child center of mass and subtree depth
this->count(tree);
// Second, float weighted surrogate nodes into position
//this->expand(tree,(3.14159/2),0,0);
// Max tree depth
double maxDepth = tree->findMax(TreeNodeKey::DEPTH);
this->expand(tree,(3.14159/2),0,0,(this->height)/maxDepth);
// Third, transform coordinates
this->transform(tree);
}
// Scale point values to fit within width and height give
// with root at (width/2, height)
// Transformation flips y values and shifts x values
// after scaling
void SpatialDisplacementLeafless::transform(SurrogateTreeNode* tree)
{
// Calculate resize scaling factors
double allowedWidth = this->width*0.95;
double allowedHeight = this->height*0.95;
double xMax = tree->findMax(TreeNodeKey::X);
double xMin = tree->findMin(TreeNodeKey::X);
double yMax = tree->findMax(TreeNodeKey::Y);
double yMin = tree->findMin(TreeNodeKey::Y);
DiscursiveDebugPrint("Mins: (%f,%f), Maxs: (%f,%f)\n",xMin,yMin,xMax,yMax);
//double currWidth = xMax - xMin;
double maxXDim = max(fabs(xMax),fabs(xMin));
double currWidth = xMax - xMin;
double currHeight = yMax - yMin;
double minDim = min(allowedHeight, allowedWidth);
double scalingFactorW = minDim/(2*maxXDim);
double scalingFactorH = minDim/currHeight;
// Transform points to look more "naturally tree-like"
tree->scale(TreeNodeKey::Y, scalingFactorH * 0.98);
PropertyInverter inverter(this->height * 0.98);
tree->transform(TreeNodeKey::Y,&inverter);
// PropertyShifter shifter(-1*((xMax + xMin) / 2));
PropertyShifter shifter(-xMin);
tree->transform(TreeNodeKey::X,&shifter);
// Scale tree values
tree->scale(TreeNodeKey::X, scalingFactorW);
// PropertyShifter shifter2(minDim * 1 / 2);
PropertyShifter shifter2(maxXDim * scalingFactorW);
tree->transform(TreeNodeKey::X,&shifter2);
}
// Sorted in increasing order
void SpatialDisplacementLeafless::insertOrderedBy(vector<SurrogateTreeNode*>* list, SurrogateTreeNode* tree, string property)
{
//printf("Inserting '%s' from %s. Current size: %d\n",property.c_str(),tree->data[TreeNodeKey::NAME].c_str(), list->size());
SurrogateTreeNode* node;
bool inserted = false;
long comp = atol(tree->data[property].c_str());
long curr = 0;
for(vector<SurrogateTreeNode*>::iterator iter = list->begin(); iter != list->end(); ++iter)
{
node = *iter;
curr = atol(node->data[property].c_str());
//printf("%ld < %ld?\n",atol(tree->data[property].c_str()),atol(node->data[property].c_str()));
if(comp < curr)
{
list->insert(iter,tree);
inserted = true;
break;
}
}
if(!inserted)
{
//printf("Inserting at end\n");
list->push_back(tree);
}
}
void SpatialDisplacementLeafless::expand(SurrogateTreeNode* tree, double rootAngle, double rootX, double rootY, double allowedHeight)
{
if(tree->children->size() > 0)
{
// Determine initial layout based on creation time of child nodes.
// Files are split into different list than directories.
vector<SurrogateTreeNode*> files;
vector<SurrogateTreeNode*> dirs;
SurrogateTreeNode* node = NULL;
int maxChild = 1;
int childSize;
int mass = 0;
int children = 0;
double minChildMass = DBL_MAX;
for(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)
{
children++;
node = *iter;
// Directory
if(node->children->size() > 0)
{
//printf("Inserting into dirs...\n");
this->insertOrderedBy(&dirs,node,TreeNodeKey::SIZE);
childSize = atoi(node->data[TreeNodeKey::SIZE].c_str());
mass += childSize;
if(childSize > maxChild )
{
maxChild = childSize;
}
if(childSize < minChildMass)
{
minChildMass = childSize;
}
}
// File
else
{
//printf("Inserting into files...\n");
this->insertOrderedBy(&files,node,TreeNodeKey::CREATION_TIME);
mass++;
if(minChildMass > 1)
{
minChildMass = 1;
}
}
}
// Map for retrieving resutls
unordered_map<SurrogateTreeNode*,int> pairs;
double masses[children];
double positions[children];
memset(positions,0,children*sizeof(double));
// Layout directories first
// Start left if even number of items.
bool left = children % 2 != 0;
int center = children / 2;
int dist = 0;
//TreeDisplacementNode* treeNode;
int i = 0;
int location;
int nodeMass;
for(; i < (int)dirs.size(); i++)
{
dist = (i+1)/2;
nodeMass = atoi(dirs[i]->data[TreeNodeKey::SIZE].c_str());
if(left)
{
location = center - dist;
}
else
{
location = center + dist;
}
masses[location] = nodeMass;
pairs[dirs[i]] = location;
for(int k = location; k < children; k++)
{
positions[k] += nodeMass;
}
left = !left;
}
// Now layout files
// for(int j = 0; j < (int)files.size(); j++)
// {
// dist = ((i + j + 1)/2);
// nodeMass = 1;
// if(left)
// {
// location = center - dist;
// }
// else
// {
// location = center + dist;
// }
// masses[location] = nodeMass;
// pairs[files[j]] = location;
// for(int k = location; k < children; k++)
// {
// positions[k] += nodeMass;
// }
// left = !left;
// }
// Calculate spacing to range [0,splay]
double deltaSplay = 0;
double splay = 3.14159 / 2;
double com;
double max = 0;
if(mass > minChildMass)
{
deltaSplay = splay / (mass - minChildMass);
}
DiscursiveDebugPrint("Subtree mass effects [");
for(i = 0; i < children; i++)
{
DiscursiveDebugPrint("%f,",positions[i]);
}
DiscursiveDebugPrint("] @ %f\n", deltaSplay);
// Convert masses to initial locations
// Record bounds
positions[0] = 0;
com = 0;
for(i = 1; i < children; i++)
{
positions[i] = (positions[i] - minChildMass)*deltaSplay;
com += (positions[i] * masses[i]);
if(positions[i] > max)
{
max = positions[i];
}
}
// Final part of CoM calculation
com /= mass;
// Balance tree
double balancedCom = com;
double divergence = balancedCom - (max/2);
double scale;
bool shortenLeft;
printf("CoM: %f, Max: %f, Divergence: %f\n", balancedCom, max, divergence);
while(fabs(divergence) > 3.14159 / 50)
{
// Shorten left half
if(divergence > 0)
{
shortenLeft = true;
scale = (max - balancedCom)/balancedCom;
}
// Shorten right half
else
{
shortenLeft = false;
scale = balancedCom/(max - balancedCom);
}
com = 0;
for(i = 1; i < children; i++)
{
// Adjust position
if(shortenLeft && positions[i] < balancedCom)
{
positions[i] = (positions[i] - divergence) * scale;
}
else if(!shortenLeft && positions[i] > balancedCom)
{
positions[i] = ((positions[i] - balancedCom) * scale) + balancedCom;
}
else if(shortenLeft && positions[i] > balancedCom)
{
positions[i] -= (2 * balancedCom - max);
}
// else
// {
// positions[i] = ;
// }
// Aggregate new position to calc new CoM
com += (positions[i] * masses[i]);
}
max = 2*(max - balancedCom);
balancedCom = com/mass;
divergence = balancedCom - (max/2);
// printf("CoM: %f, Max: %f, Divergence: %f\n", balancedCom, max, divergence);
}
// Transform positions to arc
//double arcRadius = 10.0;
// double deltaAngle = splay / children;
int maxDepth = (int)tree->findMax(TreeNodeKey::DEPTH);
int depth;
double arcRadius = allowedHeight/maxDepth;
double ratio;
double angle;
// Controls width of fan-out. > 1 : Wide tree
// < 1 : Narrow tree
double widthHeightScaleFactor = 1.0;
// Transform positions to arc and Update new positions
// Dirs first
for(i = 0; i < (int)dirs.size(); i++)
{
node = dirs[i];
depth = atoi(node->data[TreeNodeKey::DEPTH].c_str());
ratio = depth / (double)maxDepth;
angle = rootAngle - (positions[pairs[node]] - com);
double newX = rootX + (ratio * arcRadius * cos(angle));
double newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));
node->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));
node->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));
// Run expand on child
double childRot = (3.14159/2);//angle;// + ((3.14159/2)-angle)/2;
this->expand(node,childRot,newX,newY,allowedHeight - arcRadius);
}
// Then files
for(int j = 0; j < (int)files.size(); j++)
{
node = files[j];
depth = atoi(node->data[TreeNodeKey::DEPTH].c_str());
ratio = depth / (double)maxDepth;
angle = rootAngle - (positions[pairs[node]] - com);
double newX = rootX + (ratio * arcRadius * cos(angle));
double newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));
node->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));
node->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));
}
}
}
int SpatialDisplacementLeafless::count(SurrogateTreeNode* tree)
{
// Count all children plus ourselves (initial 1)
int sum = 1;
int maxDepth = 0;
int childDepth = 0;
for(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)
{
sum += this->count(*iter);
//childDepth = atoi((*iter)->data["count"].c_str());
childDepth = atoi((*iter)->data[TreeNodeKey::DEPTH].c_str());
if(childDepth > maxDepth)
{
maxDepth = childDepth;
}
}
// Assign count to data
tree->set(TreeNodeKey::SIZE, boost::lexical_cast<string>(sum));
DiscursiveDebugPrint("Size of tree %s is %s in this and %d sublevels\n",tree->data[TreeNodeKey::NAME].c_str(),tree->data[TreeNodeKey::SIZE].c_str(),maxDepth);
tree->set(TreeNodeKey::DEPTH, boost::lexical_cast<string>(maxDepth + 1));
return sum;
}
<|endoftext|>
|
<commit_before>// Helper classes for writing unittests testing the entire asynchronous
// stack. Allows to send incoming messages (in gridconnect format) and set
// expectations on messages produced.
//
// Only include this file in unittests.
#ifndef _UTILS_ASYNC_IF_TEST_HELPER_HXX_
#define _UTILS_ASYNC_IF_TEST_HELPER_HXX_
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/EventService.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet_config.h"
#include "utils/GridConnectHub.hxx"
#include "utils/test_main.hxx"
using ::testing::AtLeast;
using ::testing::AtMost;
using ::testing::Eq;
using ::testing::Field;
using ::testing::Invoke;
using ::testing::IsNull;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::NotNull;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::StrCaseEq;
using ::testing::StrictMock;
using ::testing::WithArg;
using ::testing::_;
class TrainTestHelper;
///@todo(balazs.racz) remove
// void (*g_invoke)(Notifiable *) = &InvokeNotification;
HubFlow gc_hub0(&g_service);
CanHubFlow can_hub0(&g_service);
GCAdapterBase *g_gc_adapter = nullptr;
HubFlow gc_hub1(&g_service);
CanHubFlow can_hub1(&g_service);
GCAdapterBase *g_gc_adapter1 = nullptr;
/** Helper class for setting expectation on the CANbus traffic in unit
* tests. */
class MockSend : public HubPort
{
public:
MockSend()
: HubPort(&g_service)
{
}
MOCK_METHOD1(mwrite, void(const string &s));
virtual Action entry()
{
string s(message()->data()->data(), message()->data()->size());
mwrite(s);
return release_and_exit();
}
};
void InvokeNotification(Notifiable *done)
{
done->notify();
}
static void print_packet(const string &pkt)
{
fprintf(stderr, "%s\n", pkt.c_str());
}
class AsyncCanTest : public testing::Test
{
public:
static void SetUpTestCase()
{
g_gc_adapter =
GCAdapterBase::CreateGridConnectAdapter(&gc_hub0, &can_hub0, false);
}
static void TearDownTestCase()
{
delete g_gc_adapter;
}
protected:
AsyncCanTest()
{
gc_hub0.register_port(&canBus_);
}
~AsyncCanTest()
{
gc_hub0.unregister_port(&canBus_);
if (printer_.get())
{
gc_hub0.unregister_port(printer_.get());
}
}
/** Delays the current thread until we are certain that all asynchrnous
processing has completed. */
void wait()
{
wait_for_main_executor();
}
/** Adds an expectation that the code will send a packet to the CANbus.
Example:
expect_packet(":X1954412DN05010101FFFF0000;");
@param gc_packet the packet in GridConnect format, including the leading
: and trailing ;
*/
#define expect_packet(gc_packet) \
EXPECT_CALL(canBus_, mwrite(StrCaseEq(gc_packet)))
/** Ignores all produced packets.
*
* Tihs can be used in tests where the expectations are tested in a higher
* level than monitoring the CANbus traffic.
*/
void expect_any_packet()
{
EXPECT_CALL(canBus_, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(
WithArg<0>(Invoke(print_packet)));
}
/** Prints all packets sent to the canbus until the end of the current test
* function.
*/
void print_all_packets()
{
NiceMock<MockSend> *m = new NiceMock<MockSend>();
EXPECT_CALL(*m, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(
WithArg<0>(Invoke(print_packet)));
gc_hub0.register_port(m);
printer_.reset(m);
}
/** Injects a packet to the interface. This acts as if a different node on
the CANbus had sent that packet.
Example:
send_packet(":X195B4001N05010101FFFF0000;");
@param gc_packet the packet in GridConnect format, including the leading
: and trailing ;
*/
void send_packet(const string &gc_packet)
{
Buffer<HubData> *packet;
mainBufferPool->alloc(&packet);
packet->data()->assign(gc_packet);
packet->data()->skipMember_ = &canBus_;
gc_hub0.send(packet);
}
/** Injects an incoming packet to the interface and expects that the node
will send out a response packet for it.
As a side effect, clears all pending expectations on the CANbus.
Example:
send_packet_and_expect_response(":X198F4001N05010101FFFF0000;",
":X194C412DN05010101FFFF0000;");
@param pkt is the packet to inject, in GridConnect format.
@param resp is the response to expect, also in GridConnect format.
*/
#define send_packet_and_expect_response(pkt, resp) \
do \
{ \
expect_packet(resp); \
send_packet_and_flush_expect(pkt); \
} while (0)
void send_packet_and_flush_expect(const string &pkt)
{
send_packet(pkt);
wait();
Mock::VerifyAndClear(&canBus_);
}
/// Helper object for setting expectations on the packets sent on the bus.
NiceMock<MockSend> canBus_;
/// Object for debug-printing every packet (if requested).
std::unique_ptr<HubPort> printer_;
};
namespace nmranet
{
/*
const char *Node::MANUFACTURER = "Stuart W. Baker";
const char *Node::HARDWARE_REV = "N/A";
const char *Node::SOFTWARE_REV = "0.1";
const size_t Datagram::POOL_SIZE = 10;
const size_t Datagram::THREAD_STACK_SIZE = 512;
const size_t Stream::CHANNELS_PER_NODE = 10;
const uint16_t Stream::MAX_BUFFER_SIZE = 512;*/
static const NodeID TEST_NODE_ID = 0x02010d000003ULL;
/** Test fixture base class with helper methods for exercising the asynchronous
* interface code.
*
* Usage:
*
* Inherit your test fixture class from AsyncIfTest.
*/
class AsyncIfTest : public AsyncCanTest
{
protected:
AsyncIfTest()
: pendingAliasAllocation_(false)
{
ifCan_.reset(new IfCan(&g_executor, &can_hub0, 10, 10, 5));
ifCan_->local_aliases()->add(TEST_NODE_ID, 0x22A);
}
~AsyncIfTest()
{
wait();
if (pendingAliasAllocation_)
{
ifCan_->alias_allocator()->TEST_finish_pending_allocation();
wait();
}
}
friend class ::TrainTestHelper;
/** Creates an alias allocator flow, and injects an already allocated
* alias. */
void create_allocated_alias()
{
ifCan_->set_alias_allocator(
new AliasAllocator(TEST_NODE_ID, ifCan_.get()));
Buffer<AliasInfo> *a;
mainBufferPool->alloc(&a);
a->data()->alias = 0x33A;
a->data()->state = AliasInfo::STATE_RESERVED;
ifCan_->local_aliases()->add(AliasCache::RESERVED_ALIAS_NODE_ID,
a->data()->alias);
ifCan_->alias_allocator()->reserved_aliases()->insert(a);
aliasSeed_ = 0x44C;
pendingAliasAllocation_ = false;
}
void expect_next_alias_allocation(NodeAlias a = 0)
{
pendingAliasAllocation_ = true;
if (!a)
{
ifCan_->alias_allocator()->seed_ = aliasSeed_;
a = aliasSeed_;
aliasSeed_++;
}
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X17020%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X1610D%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X15000%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X14003%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X10700%03XN;", a)))
.Times(AtMost(1))
.RetiresOnSaturation();
}
BarrierNotifiable *get_notifiable()
{
bn_.reset(&n_);
return &bn_;
}
void wait_for_notification()
{
n_.wait_for_notification();
}
SyncNotifiable n_;
BarrierNotifiable bn_;
/// The interface under test.
std::unique_ptr<IfCan> ifCan_;
/** Temporary object used to send aliases around in the alias allocator
* flow. */
AliasInfo testAlias_;
/// The next alias we will make the allocator create.
NodeAlias aliasSeed_;
/// true if we have a pending async alias allocation task.
bool pendingAliasAllocation_;
};
class AsyncNodeTest : public AsyncIfTest
{
protected:
AsyncNodeTest()
: eventService_(ifCan_.get())
{
EXPECT_CALL(canBus_, mwrite(":X1910022AN02010D000003;")).Times(1);
ownedNode_.reset(new DefaultNode(ifCan_.get(), TEST_NODE_ID));
node_ = ownedNode_.get();
ifCan_->add_addressed_message_support();
wait();
Mock::VerifyAndClear(&canBus_);
// AddEventHandlerToIf(ifCan_.get());
}
~AsyncNodeTest()
{
wait_for_event_thread();
}
void wait_for_event_thread()
{
while (EventService::instance->event_processing_pending())
{
usleep(100);
}
AsyncIfTest::wait();
}
EventService eventService_;
std::unique_ptr<DefaultNode> ownedNode_;
Node *node_;
};
class MockMessageHandler : public MessageHandler
{
public:
MOCK_METHOD2(handle_message,
void(NMRAnetMessage *message, unsigned priority));
virtual void send(Buffer<NMRAnetMessage> *message, unsigned priority)
{
handle_message(message->data(), priority);
message->unref();
}
};
MATCHER_P(IsBufferValue, id, "")
{
uint64_t value = htobe64(id);
if (arg.size() != 8)
return false;
if (memcmp(&value, arg.data(), 8))
return false;
return true;
}
MATCHER_P(IsBufferValueString, expected, "")
{
string s(expected);
return arg == s;
}
MATCHER_P(IsBufferNodeValue, id, "")
{
uint64_t value = htobe64(id);
if (arg->used() != 6)
return false;
uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;
uint8_t *actual = static_cast<uint8_t *>(arg->start());
if (memcmp(expected, actual, 6))
{
for (int i = 0; i < 6; ++i)
{
if (expected[i] != actual[i])
{
LOG(INFO, "mismatch at position %d, expected %02x actual %02x",
i, expected[i], actual[i]);
}
}
return false;
}
return true;
}
MATCHER_P(IsBufferNodeValueString, id, "")
{
uint64_t value = htobe64(id);
if (arg.size() != 6)
return false;
uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;
uint8_t *actual = static_cast<uint8_t *>(arg->start());
if (memcmp(expected, actual, 6))
{
for (int i = 0; i < 6; ++i)
{
if (expected[i] != actual[i])
{
LOG(INFO, "mismatch at position %d, expected %02x actual %02x",
i, expected[i], actual[i]);
}
}
return false;
}
return true;
}
} // namespace nmranet
#endif // _UTILS_ASYNC_IF_TEST_HELPER_HXX_
<commit_msg>Adds an assertion guard against calling print_all_packets multiple times. It would lead to a crash anyway.<commit_after>// Helper classes for writing unittests testing the entire asynchronous
// stack. Allows to send incoming messages (in gridconnect format) and set
// expectations on messages produced.
//
// Only include this file in unittests.
#ifndef _UTILS_ASYNC_IF_TEST_HELPER_HXX_
#define _UTILS_ASYNC_IF_TEST_HELPER_HXX_
#include "nmranet/AliasAllocator.hxx"
#include "nmranet/IfCan.hxx"
#include "nmranet/EventService.hxx"
#include "nmranet/DefaultNode.hxx"
#include "nmranet_config.h"
#include "utils/GridConnectHub.hxx"
#include "utils/test_main.hxx"
using ::testing::AtLeast;
using ::testing::AtMost;
using ::testing::Eq;
using ::testing::Field;
using ::testing::Invoke;
using ::testing::IsNull;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::NotNull;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::StrCaseEq;
using ::testing::StrictMock;
using ::testing::WithArg;
using ::testing::_;
class TrainTestHelper;
///@todo(balazs.racz) remove
// void (*g_invoke)(Notifiable *) = &InvokeNotification;
HubFlow gc_hub0(&g_service);
CanHubFlow can_hub0(&g_service);
GCAdapterBase *g_gc_adapter = nullptr;
HubFlow gc_hub1(&g_service);
CanHubFlow can_hub1(&g_service);
GCAdapterBase *g_gc_adapter1 = nullptr;
/** Helper class for setting expectation on the CANbus traffic in unit
* tests. */
class MockSend : public HubPort
{
public:
MockSend()
: HubPort(&g_service)
{
}
MOCK_METHOD1(mwrite, void(const string &s));
virtual Action entry()
{
string s(message()->data()->data(), message()->data()->size());
mwrite(s);
return release_and_exit();
}
};
void InvokeNotification(Notifiable *done)
{
done->notify();
}
static void print_packet(const string &pkt)
{
fprintf(stderr, "%s\n", pkt.c_str());
}
class AsyncCanTest : public testing::Test
{
public:
static void SetUpTestCase()
{
g_gc_adapter =
GCAdapterBase::CreateGridConnectAdapter(&gc_hub0, &can_hub0, false);
}
static void TearDownTestCase()
{
delete g_gc_adapter;
}
protected:
AsyncCanTest()
{
gc_hub0.register_port(&canBus_);
}
~AsyncCanTest()
{
gc_hub0.unregister_port(&canBus_);
if (printer_.get())
{
gc_hub0.unregister_port(printer_.get());
}
}
/** Delays the current thread until we are certain that all asynchrnous
processing has completed. */
void wait()
{
wait_for_main_executor();
}
/** Adds an expectation that the code will send a packet to the CANbus.
Example:
expect_packet(":X1954412DN05010101FFFF0000;");
@param gc_packet the packet in GridConnect format, including the leading
: and trailing ;
*/
#define expect_packet(gc_packet) \
EXPECT_CALL(canBus_, mwrite(StrCaseEq(gc_packet)))
/** Ignores all produced packets.
*
* Tihs can be used in tests where the expectations are tested in a higher
* level than monitoring the CANbus traffic.
*/
void expect_any_packet()
{
EXPECT_CALL(canBus_, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(
WithArg<0>(Invoke(print_packet)));
}
/** Prints all packets sent to the canbus until the end of the current test
* function.
*/
void print_all_packets()
{
HASSERT(!printer_ && "cannot have more than one print_all_packets call");
NiceMock<MockSend> *m = new NiceMock<MockSend>();
EXPECT_CALL(*m, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(
WithArg<0>(Invoke(print_packet)));
gc_hub0.register_port(m);
printer_.reset(m);
}
/** Injects a packet to the interface. This acts as if a different node on
the CANbus had sent that packet.
Example:
send_packet(":X195B4001N05010101FFFF0000;");
@param gc_packet the packet in GridConnect format, including the leading
: and trailing ;
*/
void send_packet(const string &gc_packet)
{
Buffer<HubData> *packet;
mainBufferPool->alloc(&packet);
packet->data()->assign(gc_packet);
packet->data()->skipMember_ = &canBus_;
gc_hub0.send(packet);
}
/** Injects an incoming packet to the interface and expects that the node
will send out a response packet for it.
As a side effect, clears all pending expectations on the CANbus.
Example:
send_packet_and_expect_response(":X198F4001N05010101FFFF0000;",
":X194C412DN05010101FFFF0000;");
@param pkt is the packet to inject, in GridConnect format.
@param resp is the response to expect, also in GridConnect format.
*/
#define send_packet_and_expect_response(pkt, resp) \
do \
{ \
expect_packet(resp); \
send_packet_and_flush_expect(pkt); \
} while (0)
void send_packet_and_flush_expect(const string &pkt)
{
send_packet(pkt);
wait();
Mock::VerifyAndClear(&canBus_);
}
/// Helper object for setting expectations on the packets sent on the bus.
NiceMock<MockSend> canBus_;
/// Object for debug-printing every packet (if requested).
std::unique_ptr<HubPort> printer_;
};
namespace nmranet
{
/*
const char *Node::MANUFACTURER = "Stuart W. Baker";
const char *Node::HARDWARE_REV = "N/A";
const char *Node::SOFTWARE_REV = "0.1";
const size_t Datagram::POOL_SIZE = 10;
const size_t Datagram::THREAD_STACK_SIZE = 512;
const size_t Stream::CHANNELS_PER_NODE = 10;
const uint16_t Stream::MAX_BUFFER_SIZE = 512;*/
static const NodeID TEST_NODE_ID = 0x02010d000003ULL;
/** Test fixture base class with helper methods for exercising the asynchronous
* interface code.
*
* Usage:
*
* Inherit your test fixture class from AsyncIfTest.
*/
class AsyncIfTest : public AsyncCanTest
{
protected:
AsyncIfTest()
: pendingAliasAllocation_(false)
{
ifCan_.reset(new IfCan(&g_executor, &can_hub0, 10, 10, 5));
ifCan_->local_aliases()->add(TEST_NODE_ID, 0x22A);
}
~AsyncIfTest()
{
wait();
if (pendingAliasAllocation_)
{
ifCan_->alias_allocator()->TEST_finish_pending_allocation();
wait();
}
}
friend class ::TrainTestHelper;
/** Creates an alias allocator flow, and injects an already allocated
* alias. */
void create_allocated_alias()
{
ifCan_->set_alias_allocator(
new AliasAllocator(TEST_NODE_ID, ifCan_.get()));
Buffer<AliasInfo> *a;
mainBufferPool->alloc(&a);
a->data()->alias = 0x33A;
a->data()->state = AliasInfo::STATE_RESERVED;
ifCan_->local_aliases()->add(AliasCache::RESERVED_ALIAS_NODE_ID,
a->data()->alias);
ifCan_->alias_allocator()->reserved_aliases()->insert(a);
aliasSeed_ = 0x44C;
pendingAliasAllocation_ = false;
}
void expect_next_alias_allocation(NodeAlias a = 0)
{
pendingAliasAllocation_ = true;
if (!a)
{
ifCan_->alias_allocator()->seed_ = aliasSeed_;
a = aliasSeed_;
aliasSeed_++;
}
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X17020%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X1610D%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X15000%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X14003%03XN;", a)))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(canBus_, mwrite(StringPrintf(":X10700%03XN;", a)))
.Times(AtMost(1))
.RetiresOnSaturation();
}
BarrierNotifiable *get_notifiable()
{
bn_.reset(&n_);
return &bn_;
}
void wait_for_notification()
{
n_.wait_for_notification();
}
SyncNotifiable n_;
BarrierNotifiable bn_;
/// The interface under test.
std::unique_ptr<IfCan> ifCan_;
/** Temporary object used to send aliases around in the alias allocator
* flow. */
AliasInfo testAlias_;
/// The next alias we will make the allocator create.
NodeAlias aliasSeed_;
/// true if we have a pending async alias allocation task.
bool pendingAliasAllocation_;
};
class AsyncNodeTest : public AsyncIfTest
{
protected:
AsyncNodeTest()
: eventService_(ifCan_.get())
{
EXPECT_CALL(canBus_, mwrite(":X1910022AN02010D000003;")).Times(1);
ownedNode_.reset(new DefaultNode(ifCan_.get(), TEST_NODE_ID));
node_ = ownedNode_.get();
ifCan_->add_addressed_message_support();
wait();
Mock::VerifyAndClear(&canBus_);
// AddEventHandlerToIf(ifCan_.get());
}
~AsyncNodeTest()
{
wait_for_event_thread();
}
void wait_for_event_thread()
{
while (EventService::instance->event_processing_pending())
{
usleep(100);
}
AsyncIfTest::wait();
}
EventService eventService_;
std::unique_ptr<DefaultNode> ownedNode_;
Node *node_;
};
class MockMessageHandler : public MessageHandler
{
public:
MOCK_METHOD2(handle_message,
void(NMRAnetMessage *message, unsigned priority));
virtual void send(Buffer<NMRAnetMessage> *message, unsigned priority)
{
handle_message(message->data(), priority);
message->unref();
}
};
MATCHER_P(IsBufferValue, id, "")
{
uint64_t value = htobe64(id);
if (arg.size() != 8)
return false;
if (memcmp(&value, arg.data(), 8))
return false;
return true;
}
MATCHER_P(IsBufferValueString, expected, "")
{
string s(expected);
return arg == s;
}
MATCHER_P(IsBufferNodeValue, id, "")
{
uint64_t value = htobe64(id);
if (arg->used() != 6)
return false;
uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;
uint8_t *actual = static_cast<uint8_t *>(arg->start());
if (memcmp(expected, actual, 6))
{
for (int i = 0; i < 6; ++i)
{
if (expected[i] != actual[i])
{
LOG(INFO, "mismatch at position %d, expected %02x actual %02x",
i, expected[i], actual[i]);
}
}
return false;
}
return true;
}
MATCHER_P(IsBufferNodeValueString, id, "")
{
uint64_t value = htobe64(id);
if (arg.size() != 6)
return false;
uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;
uint8_t *actual = static_cast<uint8_t *>(arg->start());
if (memcmp(expected, actual, 6))
{
for (int i = 0; i < 6; ++i)
{
if (expected[i] != actual[i])
{
LOG(INFO, "mismatch at position %d, expected %02x actual %02x",
i, expected[i], actual[i]);
}
}
return false;
}
return true;
}
} // namespace nmranet
#endif // _UTILS_ASYNC_IF_TEST_HELPER_HXX_
<|endoftext|>
|
<commit_before>
/*!
* \file cuda_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/cuda_utilities.h"
#include "../global/global.h"
/*
PCM : n_ghost = 2
PLMP : n_ghost = 2
PLMC : n_ghost = 3
PPMP : n_ghost = 4
PPMC : n_ghost = 4
*/
// =============================================================================
// Local helper functions
namespace
{
struct TestParams
{
std::vector<int> n_ghost {2, 2, 3, 4};
std::vector<int> nx {1, 2048, 2048, 2048};
std::vector<int> ny {1, 2048, 2048, 2048};
std::vector<int> nz {1, 4096, 4096, 4096};
std::vector<std::string> names {"Single-cell 3D PCM/PLMP case", "Large 3D PCM/PLMP case", "Large PLMC case", "Large PPMP/PPMC case"};
};
}
TEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<std::vector<int>> fiducial_indices {{1, 2, 3, 4, 5, 6},
{4, 5, 6, 7, 8, 9},
{7, 8, 9, 4, 5, 6},
{7, 8, 9, 4, 5, 6}};
for (size_t i = 0; i < parameters.names.size(); i++)
{
int is;
int ie;
int js;
int je;
int ks;
int ke;
cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);
std::vector<int> test_indices {is, ie, js, je, ks, ke};
std::vector<std::string> index_names {"is", "ie", "js", "je", "ks", "ke"};
for (int j = 0; j < test_indices.size(); j++)
{
testingUtilities::checkResults(fiducial_indices[i][j], test_indices[i], index_names[j] + " " + parameters.names[i]);
}
}
}<commit_msg>add test for real index utility function<commit_after>
/*!
* \file cuda_utilities_tests.cpp
* \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
* \brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp
*
*/
// STL Includes
#include <vector>
#include <string>
#include <iostream>
// External Includes
#include <gtest/gtest.h> // Include GoogleTest and related libraries/headers
// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/cuda_utilities.h"
#include "../global/global.h"
/*
PCM : n_ghost = 2
PLMP : n_ghost = 2
PLMC : n_ghost = 3
PPMP : n_ghost = 4
PPMC : n_ghost = 4
*/
// =============================================================================
// Local helper functions
namespace
{
struct TestParams
{
std::vector<int> n_ghost {2, 2, 3, 4};
std::vector<int> nx {100, 2048, 2048, 2048};
std::vector<int> ny {1, 2048, 2048, 2048};
std::vector<int> nz {1, 4096, 4096, 4096};
std::vector<std::string> names {"Single-cell 3D PCM/PLMP case", "Large 3D PCM/PLMP case", "Large PLMC case", "Large PPMP/PPMC case"};
};
}
TEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {
TestParams parameters;
std::vector<std::vector<int>> fiducial_indices {{2, 98, 0, 1, 0, 1},
{2, 2046, 2, 2046, 2, 2046},
{3, 2045, 3, 2045, 3, 2045},
{4, 2044, 4, 2044, 4, 2044}};
for (size_t i = 0; i < parameters.names.size(); i++)
{
int is;
int ie;
int js;
int je;
int ks;
int ke;
cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);
std::vector<std::string> index_names {"is", "ie", "js", "je", "ks", "ke"};
std::vector<int> test_indices {is, ie, js, je, ks, ke};
std::cout >> test_indices << "\n"
for (size_t j = 0; j < test_indices.size(); j++)
{
testingUtilities::checkResults(fiducial_indices[i][j], test_indices[j], index_names[j] + " " + parameters.names[i]);
}
}
}<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "homography.h"
#include "plane_ref.h"
#include "timestamp.h"
#include "utm.h"
/**
* \file homography.cxx
*
* \brief Implementation of the homography classes.
*/
namespace vistk
{
homography_base
::homography_base(homography_base const& h)
: m_transform(h.m_transform)
, m_valid(h.m_valid)
, m_new_reference(h.m_new_reference)
{
}
homography_base
::~homography_base()
{
}
homography_base::transform_t const&
homography_base
::transform() const
{
return m_transform;
}
bool
homography_base
::is_valid() const
{
return m_valid;
}
bool
homography_base
::is_new_reference() const
{
return m_new_reference;
}
void
homography_base
::set_transform(transform_t const& trans)
{
m_transform = trans;
}
void
homography_base
::set_identity()
{
m_transform.set_identity();
}
void
homography_base
::set_valid(bool valid)
{
m_valid = valid;
}
void
homography_base
::set_new_reference(bool new_reference)
{
m_new_reference = new_reference;
}
bool
homography_base
::operator == (homography_base const& h) const
{
return ((m_valid == h.m_valid) &&
(m_new_reference == h.m_new_reference) &&
(m_transform == h.m_transform));
}
homography_base
::homography_base()
: m_valid(false)
, m_new_reference(false)
{
set_identity();
}
template <typename Source, typename Dest>
homography<Source, Dest>
::homography()
{
}
template <typename Source, typename Dest>
homography<Source, Dest>
::homography(self_t const& h)
: homography_base(h)
, m_source(h.m_source)
, m_dest(h.m_dest)
{
}
template <typename Source, typename Dest>
homography<Source, Dest>
::~homography()
{
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::source_t
homography<Source, Dest>
::source() const
{
return m_source;
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::dest_t
homography<Source, Dest>
::destination() const
{
return m_dest;
}
template <typename Source, typename Dest>
void
homography<Source, Dest>
::set_source(source_t const& src)
{
m_source = src;
}
template <typename Source, typename Dest>
void
homography<Source, Dest>
::set_destination(dest_t const& dest)
{
m_dest = dest;
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::inverse_t
homography<Source, Dest>
::inverse() const
{
inverse_t result;
result.set_transform(transform().get_inverse());
result.set_source(m_dest);
result.set_destination(m_source);
result.set_valid(is_valid());
result.set_new_reference(is_new_reference());
return result;
}
template <typename Source, typename Dest>
bool
homography<Source, Dest>
::operator == (self_t const& h) const
{
return ((homography::operator == (h)) &&
(m_source == h.m_source) &&
(m_dest == h.m_dest));
}
// Keep in sync with homography_types.h
template class homography<timestamp, timestamp>;
template class homography<timestamp, plane_ref_t>;
template class homography<plane_ref_t, timestamp>;
template class homography<timestamp, utm_zone_t>;
template class homography<utm_zone_t, timestamp>;
template class homography<plane_ref_t, utm_zone_t>;
template class homography<utm_zone_t, plane_ref_t>;
template <typename Source, typename Shared, typename Dest>
homography<Source, Dest>
operator * (homography<Shared, Dest> const& l, homography<Source, Shared> const& r)
{
homography<Source, Dest> result;
result.set_transform(l.transform() * r.transform());
result.set_source(r.source());
result.set_destination(l.dest());
result.set_valid(l.is_valid() && r.is_valid());
return result;
}
#ifndef DOXYGEN_IGNORE
/**
* \def INSTANTIATE_SELF_MULT
*
* \brief Instantiates multiplication with homogeneous types.
*
* \param X The reference plane for the multiplication.
*/
#define INSTANTIATE_SELF_MULT(X) \
template <> homography<X, X> operator * <X, X, X>(homography<X, X> const&, homography<X, X> const&)
/**
* \def INSTANTIATE_DUAL_MULT_RAW
*
* \brief Instantiates multiplication with two distinct types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
*/
#define INSTANTIATE_DUAL_MULT_RAW(X, Y) \
template <> homography<X, X> operator * <X, Y, X>(homography<Y, X> const&, homography<X, Y> const&); \
template <> homography<X, Y> operator * <X, X, Y>(homography<X, Y> const&, homography<X, X> const&); \
template <> homography<X, Y> operator * <X, Y, Y>(homography<Y, Y> const&, homography<X, Y> const&)
/**
* \def INSTANTIATE_DUAL_MULT
*
* \brief Instantiates multiplication with two distinct types.
*
* This instantiates all permutations between the two types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
*/
#define INSTANTIATE_DUAL_MULT(X, Y) \
INSTANTIATE_DUAL_MULT_RAW(X, Y); \
INSTANTIATE_DUAL_MULT_RAW(Y, X)
/**
* \def INSTANTIATE_TRIP_MULT_RAW
*
* \brief Instantiates multiplication with three distinct types.
*
* \param X The source type in the multiplication.
* \param Y The shared type in the multiplication.
* \param Z The destination type in the multiplication.
*/
#define INSTANTIATE_TRIP_MULT_RAW(X,Y,Z) \
template <> homography<X, Z> operator * <X, Y, Z>(homography<Y, Z> const&, homography<X, Y> const&)
/**
* \def INSTANTIATE_TRIP_MULT
*
* \brief Instantiates multiplication with three distinct types.
*
* This instantiates all permutations between the three types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
* \param Z The third type in the multiplication.
*/
#define INSTANTIATE_TRIP_MULT(X,Y,Z) \
INSTANTIATE_TRIP_MULT_RAW(X, Y, Z); \
INSTANTIATE_TRIP_MULT_RAW(X, Z, Y); \
INSTANTIATE_TRIP_MULT_RAW(Y, X, Z); \
INSTANTIATE_TRIP_MULT_RAW(Y, Z, Y); \
INSTANTIATE_TRIP_MULT_RAW(Z, X, Y); \
INSTANTIATE_TRIP_MULT_RAW(Z, Y, X)
// Instantiate all allowable types
INSTANTIATE_SELF_MULT(timestamp);
INSTANTIATE_SELF_MULT(plane_ref_t);
INSTANTIATE_SELF_MULT(utm_zone_t);
INSTANTIATE_DUAL_MULT(timestamp, plane_ref_t);
INSTANTIATE_DUAL_MULT(timestamp, utm_zone_t);
INSTANTIATE_DUAL_MULT(plane_ref_t, utm_zone_t);
INSTANTIATE_TRIP_MULT(timestamp, plane_ref_t, utm_zone_t);
#undef INSTANTIATE_SELF_MULT
#undef INSTANTIATE_DUAL_MULT_RAW
#undef INSTANTIATE_DUAL_MULT
#undef INSTANTIATE_TRIP_MULT_RAW
#undef INSTANTIATE_TRIP_MULT
#endif // DOXYGEN_IGNORE
}
<commit_msg>Call the proper operator ==<commit_after>/*ckwg +5
* Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "homography.h"
#include "plane_ref.h"
#include "timestamp.h"
#include "utm.h"
/**
* \file homography.cxx
*
* \brief Implementation of the homography classes.
*/
namespace vistk
{
homography_base
::homography_base(homography_base const& h)
: m_transform(h.m_transform)
, m_valid(h.m_valid)
, m_new_reference(h.m_new_reference)
{
}
homography_base
::~homography_base()
{
}
homography_base::transform_t const&
homography_base
::transform() const
{
return m_transform;
}
bool
homography_base
::is_valid() const
{
return m_valid;
}
bool
homography_base
::is_new_reference() const
{
return m_new_reference;
}
void
homography_base
::set_transform(transform_t const& trans)
{
m_transform = trans;
}
void
homography_base
::set_identity()
{
m_transform.set_identity();
}
void
homography_base
::set_valid(bool valid)
{
m_valid = valid;
}
void
homography_base
::set_new_reference(bool new_reference)
{
m_new_reference = new_reference;
}
bool
homography_base
::operator == (homography_base const& h) const
{
return ((m_valid == h.m_valid) &&
(m_new_reference == h.m_new_reference) &&
(m_transform == h.m_transform));
}
homography_base
::homography_base()
: m_valid(false)
, m_new_reference(false)
{
set_identity();
}
template <typename Source, typename Dest>
homography<Source, Dest>
::homography()
{
}
template <typename Source, typename Dest>
homography<Source, Dest>
::homography(self_t const& h)
: homography_base(h)
, m_source(h.m_source)
, m_dest(h.m_dest)
{
}
template <typename Source, typename Dest>
homography<Source, Dest>
::~homography()
{
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::source_t
homography<Source, Dest>
::source() const
{
return m_source;
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::dest_t
homography<Source, Dest>
::destination() const
{
return m_dest;
}
template <typename Source, typename Dest>
void
homography<Source, Dest>
::set_source(source_t const& src)
{
m_source = src;
}
template <typename Source, typename Dest>
void
homography<Source, Dest>
::set_destination(dest_t const& dest)
{
m_dest = dest;
}
template <typename Source, typename Dest>
typename homography<Source, Dest>::inverse_t
homography<Source, Dest>
::inverse() const
{
inverse_t result;
result.set_transform(transform().get_inverse());
result.set_source(m_dest);
result.set_destination(m_source);
result.set_valid(is_valid());
result.set_new_reference(is_new_reference());
return result;
}
template <typename Source, typename Dest>
bool
homography<Source, Dest>
::operator == (self_t const& h) const
{
return ((homography_base::operator == (h)) &&
(m_source == h.m_source) &&
(m_dest == h.m_dest));
}
// Keep in sync with homography_types.h
template class homography<timestamp, timestamp>;
template class homography<timestamp, plane_ref_t>;
template class homography<plane_ref_t, timestamp>;
template class homography<timestamp, utm_zone_t>;
template class homography<utm_zone_t, timestamp>;
template class homography<plane_ref_t, utm_zone_t>;
template class homography<utm_zone_t, plane_ref_t>;
template <typename Source, typename Shared, typename Dest>
homography<Source, Dest>
operator * (homography<Shared, Dest> const& l, homography<Source, Shared> const& r)
{
homography<Source, Dest> result;
result.set_transform(l.transform() * r.transform());
result.set_source(r.source());
result.set_destination(l.dest());
result.set_valid(l.is_valid() && r.is_valid());
return result;
}
#ifndef DOXYGEN_IGNORE
/**
* \def INSTANTIATE_SELF_MULT
*
* \brief Instantiates multiplication with homogeneous types.
*
* \param X The reference plane for the multiplication.
*/
#define INSTANTIATE_SELF_MULT(X) \
template <> homography<X, X> operator * <X, X, X>(homography<X, X> const&, homography<X, X> const&)
/**
* \def INSTANTIATE_DUAL_MULT_RAW
*
* \brief Instantiates multiplication with two distinct types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
*/
#define INSTANTIATE_DUAL_MULT_RAW(X, Y) \
template <> homography<X, X> operator * <X, Y, X>(homography<Y, X> const&, homography<X, Y> const&); \
template <> homography<X, Y> operator * <X, X, Y>(homography<X, Y> const&, homography<X, X> const&); \
template <> homography<X, Y> operator * <X, Y, Y>(homography<Y, Y> const&, homography<X, Y> const&)
/**
* \def INSTANTIATE_DUAL_MULT
*
* \brief Instantiates multiplication with two distinct types.
*
* This instantiates all permutations between the two types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
*/
#define INSTANTIATE_DUAL_MULT(X, Y) \
INSTANTIATE_DUAL_MULT_RAW(X, Y); \
INSTANTIATE_DUAL_MULT_RAW(Y, X)
/**
* \def INSTANTIATE_TRIP_MULT_RAW
*
* \brief Instantiates multiplication with three distinct types.
*
* \param X The source type in the multiplication.
* \param Y The shared type in the multiplication.
* \param Z The destination type in the multiplication.
*/
#define INSTANTIATE_TRIP_MULT_RAW(X,Y,Z) \
template <> homography<X, Z> operator * <X, Y, Z>(homography<Y, Z> const&, homography<X, Y> const&)
/**
* \def INSTANTIATE_TRIP_MULT
*
* \brief Instantiates multiplication with three distinct types.
*
* This instantiates all permutations between the three types.
*
* \param X The first type in the multiplication.
* \param Y The second type in the multiplication.
* \param Z The third type in the multiplication.
*/
#define INSTANTIATE_TRIP_MULT(X,Y,Z) \
INSTANTIATE_TRIP_MULT_RAW(X, Y, Z); \
INSTANTIATE_TRIP_MULT_RAW(X, Z, Y); \
INSTANTIATE_TRIP_MULT_RAW(Y, X, Z); \
INSTANTIATE_TRIP_MULT_RAW(Y, Z, Y); \
INSTANTIATE_TRIP_MULT_RAW(Z, X, Y); \
INSTANTIATE_TRIP_MULT_RAW(Z, Y, X)
// Instantiate all allowable types
INSTANTIATE_SELF_MULT(timestamp);
INSTANTIATE_SELF_MULT(plane_ref_t);
INSTANTIATE_SELF_MULT(utm_zone_t);
INSTANTIATE_DUAL_MULT(timestamp, plane_ref_t);
INSTANTIATE_DUAL_MULT(timestamp, utm_zone_t);
INSTANTIATE_DUAL_MULT(plane_ref_t, utm_zone_t);
INSTANTIATE_TRIP_MULT(timestamp, plane_ref_t, utm_zone_t);
#undef INSTANTIATE_SELF_MULT
#undef INSTANTIATE_DUAL_MULT_RAW
#undef INSTANTIATE_DUAL_MULT
#undef INSTANTIATE_TRIP_MULT_RAW
#undef INSTANTIATE_TRIP_MULT
#endif // DOXYGEN_IGNORE
}
<|endoftext|>
|
<commit_before>#include "halley/core/graphics/sprite/animation.h"
#include "halley/core/graphics/sprite/sprite_sheet.h"
#include "halley/core/graphics/material/material.h"
#include "halley/core/graphics/material/material_definition.h"
#include "halley/core/graphics/material/material_parameter.h"
#include "halley/core/api/halley_api.h"
#include "resources/resources.h"
#include "halley/bytes/byte_serializer.h"
#include <gsl/gsl_assert>
#include <utility>
using namespace Halley;
AnimationFrame::AnimationFrame(int frameNumber, int duration, const String& imageName, const SpriteSheet& sheet, const Vector<AnimationDirection>& directions)
: duration(duration)
{
const size_t n = directions.size();
sprites.resize(n);
for (size_t i = 0; i < n; i++) {
sprites[i] = &sheet.getSprite(directions[i].needsToProcessFrameName(imageName) ? directions[i].getFrameName(frameNumber, imageName) : imageName);
}
}
int AnimationFrame::getDuration() const
{
return duration;
}
AnimationFrameDefinition::AnimationFrameDefinition()
: frameNumber(-1)
{}
AnimationFrameDefinition::AnimationFrameDefinition(int frameNumber, int duration, String imageName)
: imageName(std::move(imageName))
, frameNumber(frameNumber)
, duration(duration)
{
}
AnimationFrame AnimationFrameDefinition::makeFrame(const SpriteSheet& sheet, const Vector<AnimationDirection>& directions) const
{
return AnimationFrame(frameNumber, duration, imageName, sheet, directions);
}
void AnimationFrameDefinition::serialize(Serializer& s) const
{
s << imageName;
s << frameNumber;
s << duration;
}
void AnimationFrameDefinition::deserialize(Deserializer& s)
{
s >> imageName;
s >> frameNumber;
s >> duration;
}
AnimationSequence::AnimationSequence() {}
AnimationSequence::AnimationSequence(String name, bool loop, bool noFlip)
: name(std::move(name))
, loop(loop)
, noFlip(noFlip)
{}
void AnimationSequence::serialize(Serializer& s) const
{
s << frameDefinitions;
s << name;
s << loop;
s << noFlip;
}
void AnimationSequence::deserialize(Deserializer& s)
{
s >> frameDefinitions;
s >> name;
s >> loop;
s >> noFlip;
}
void AnimationSequence::addFrame(const AnimationFrameDefinition& animationFrameDefinition)
{
frameDefinitions.push_back(animationFrameDefinition);
}
Rect4i AnimationSequence::getBounds() const
{
Vector2i topLeft;
Vector2i bottomRight;
for (auto& frame: frames) {
auto& sprite = frame.getSprite(0);
if (sprite.size.x >= 0.1f && sprite.size.y > 0.0f) {
auto offset = Vector2i(Vector2f(sprite.pivot * sprite.size).round());
const Vector2i tl = -offset;
const Vector2i br = Vector2i(sprite.size) - offset;
topLeft = Vector2i::min(topLeft, tl);
bottomRight = Vector2i::max(bottomRight, br);
}
}
return Rect4i(topLeft, bottomRight);
}
AnimationDirection::AnimationDirection()
: id(-1)
, flip(false)
{}
AnimationDirection::AnimationDirection(String name, String fileName, bool flip, int id)
: name(std::move(name))
, fileName(std::move(fileName))
, id(id)
, flip(flip)
{
}
bool AnimationDirection::needsToProcessFrameName(const String& baseName) const
{
return baseName.find("%f") != std::string::npos || baseName.find("%dir%") != std::string::npos;
}
String AnimationDirection::getFrameName(int frameNumber, String baseName) const
{
try {
baseName = baseName.replaceAll("%dir%", fileName);
size_t frameToken = baseName.find("%f");
if (frameToken != std::string::npos) {
size_t endToken = baseName.find('%', frameToken + 1);
if (endToken != std::string::npos) {
int minWidth = 0;
if (baseName[frameToken + 2] == ':' && baseName[frameToken + 3] == '0') {
minWidth = baseName.subToInteger(frameToken + 4, endToken);
}
std::stringstream ss;
ss << std::setfill('0') << std::setw(minWidth) << frameNumber;
baseName = baseName.left(frameToken) + ss.str() + baseName.mid(endToken + 1);
}
}
return baseName;
} catch (...) {
throw Exception("Invalid frame name: " + baseName, HalleyExceptions::Graphics);
}
}
void AnimationDirection::serialize(Serializer& s) const
{
s << name;
s << fileName;
s << id;
s << flip;
}
void AnimationDirection::deserialize(Deserializer& s)
{
s >> name;
s >> fileName;
s >> id;
s >> flip;
}
Animation::Animation()
{}
std::unique_ptr<Animation> Animation::loadResource(ResourceLoader& loader)
{
auto result = std::make_unique<Animation>();
auto sData = loader.getStatic();
Deserializer s(sData->getSpan());
s >> *result;
result->loadDependencies(loader);
return result;
}
void Animation::reload(Resource&& resource)
{
*this = std::move(dynamic_cast<Animation&>(resource));
}
void Animation::loadDependencies(ResourceLoader& loader)
{
spriteSheet = loader.getAPI().getResource<SpriteSheet>(spriteSheetName);
auto matDef = loader.getAPI().getResource<MaterialDefinition>(materialName);
material = std::make_shared<Material>(matDef);
material->set("tex0", spriteSheet->getTexture());
for (auto& s: sequences) {
for (auto& f : s.frameDefinitions) {
s.frames.emplace_back(f.makeFrame(*spriteSheet, directions));
}
}
}
void Animation::setName(const String& n)
{
name = n;
}
void Animation::setMaterialName(const String& n)
{
materialName = n;
}
void Animation::setSpriteSheetName(const String& n)
{
spriteSheetName = n;
}
void Animation::addSequence(const AnimationSequence& sequence)
{
sequences.push_back(sequence);
}
void Animation::addDirection(const AnimationDirection& direction)
{
directions.push_back(direction);
}
const AnimationSequence& Animation::getSequence(const String& seqName) const
{
for (auto& seq: sequences) {
if (seq.name == seqName) {
return seq;
}
}
return sequences.at(0);
}
const AnimationDirection& Animation::getDirection(const String& dirName) const
{
Expects(directions.size() > 0);
for (auto& dir : directions) {
if (dir.name == dirName) {
return dir;
}
}
return directions[0];
}
const AnimationDirection& Animation::getDirection(int id) const
{
Expects(id >= 0);
Expects(directions.size() > 0);
if (id < int(directions.size())) {
return directions[id];
} else {
return directions[0];
}
}
Vector2i Animation::getPivot() const
{
return sequences.at(0).getFrame(0).getSprite(0).origPivot;
}
bool Animation::hasSequence(const String& seqName) const
{
for (auto& s: sequences) {
if (s.getName() == seqName) {
return true;
}
}
return false;
}
void Animation::serialize(Serializer& s) const
{
s << name;
s << spriteSheetName;
s << materialName;
s << sequences;
s << directions;
}
void Animation::deserialize(Deserializer& s)
{
s >> name;
s >> spriteSheetName;
s >> materialName;
s >> sequences;
s >> directions;
}
<commit_msg>Fix bounds calculation<commit_after>#include "halley/core/graphics/sprite/animation.h"
#include "halley/core/graphics/sprite/sprite_sheet.h"
#include "halley/core/graphics/material/material.h"
#include "halley/core/graphics/material/material_definition.h"
#include "halley/core/graphics/material/material_parameter.h"
#include "halley/core/api/halley_api.h"
#include "resources/resources.h"
#include "halley/bytes/byte_serializer.h"
#include <gsl/gsl_assert>
#include <utility>
using namespace Halley;
AnimationFrame::AnimationFrame(int frameNumber, int duration, const String& imageName, const SpriteSheet& sheet, const Vector<AnimationDirection>& directions)
: duration(duration)
{
const size_t n = directions.size();
sprites.resize(n);
for (size_t i = 0; i < n; i++) {
sprites[i] = &sheet.getSprite(directions[i].needsToProcessFrameName(imageName) ? directions[i].getFrameName(frameNumber, imageName) : imageName);
}
}
int AnimationFrame::getDuration() const
{
return duration;
}
AnimationFrameDefinition::AnimationFrameDefinition()
: frameNumber(-1)
{}
AnimationFrameDefinition::AnimationFrameDefinition(int frameNumber, int duration, String imageName)
: imageName(std::move(imageName))
, frameNumber(frameNumber)
, duration(duration)
{
}
AnimationFrame AnimationFrameDefinition::makeFrame(const SpriteSheet& sheet, const Vector<AnimationDirection>& directions) const
{
return AnimationFrame(frameNumber, duration, imageName, sheet, directions);
}
void AnimationFrameDefinition::serialize(Serializer& s) const
{
s << imageName;
s << frameNumber;
s << duration;
}
void AnimationFrameDefinition::deserialize(Deserializer& s)
{
s >> imageName;
s >> frameNumber;
s >> duration;
}
AnimationSequence::AnimationSequence() {}
AnimationSequence::AnimationSequence(String name, bool loop, bool noFlip)
: name(std::move(name))
, loop(loop)
, noFlip(noFlip)
{}
void AnimationSequence::serialize(Serializer& s) const
{
s << frameDefinitions;
s << name;
s << loop;
s << noFlip;
}
void AnimationSequence::deserialize(Deserializer& s)
{
s >> frameDefinitions;
s >> name;
s >> loop;
s >> noFlip;
}
void AnimationSequence::addFrame(const AnimationFrameDefinition& animationFrameDefinition)
{
frameDefinitions.push_back(animationFrameDefinition);
}
Rect4i AnimationSequence::getBounds() const
{
Vector2i topLeft(99999, 99999);
Vector2i bottomRight;
for (auto& frame: frames) {
auto& sprite = frame.getSprite(0);
if (sprite.size.x >= 0.1f && sprite.size.y > 0.0f) {
auto offset = Vector2i(Vector2f(sprite.pivot * sprite.size).round());
const Vector2i tl = -offset;
const Vector2i br = tl + Vector2i(sprite.size);
topLeft = Vector2i::min(topLeft, tl);
bottomRight = Vector2i::max(bottomRight, br);
}
}
return Rect4i(topLeft, bottomRight);
}
AnimationDirection::AnimationDirection()
: id(-1)
, flip(false)
{}
AnimationDirection::AnimationDirection(String name, String fileName, bool flip, int id)
: name(std::move(name))
, fileName(std::move(fileName))
, id(id)
, flip(flip)
{
}
bool AnimationDirection::needsToProcessFrameName(const String& baseName) const
{
return baseName.find("%f") != std::string::npos || baseName.find("%dir%") != std::string::npos;
}
String AnimationDirection::getFrameName(int frameNumber, String baseName) const
{
try {
baseName = baseName.replaceAll("%dir%", fileName);
size_t frameToken = baseName.find("%f");
if (frameToken != std::string::npos) {
size_t endToken = baseName.find('%', frameToken + 1);
if (endToken != std::string::npos) {
int minWidth = 0;
if (baseName[frameToken + 2] == ':' && baseName[frameToken + 3] == '0') {
minWidth = baseName.subToInteger(frameToken + 4, endToken);
}
std::stringstream ss;
ss << std::setfill('0') << std::setw(minWidth) << frameNumber;
baseName = baseName.left(frameToken) + ss.str() + baseName.mid(endToken + 1);
}
}
return baseName;
} catch (...) {
throw Exception("Invalid frame name: " + baseName, HalleyExceptions::Graphics);
}
}
void AnimationDirection::serialize(Serializer& s) const
{
s << name;
s << fileName;
s << id;
s << flip;
}
void AnimationDirection::deserialize(Deserializer& s)
{
s >> name;
s >> fileName;
s >> id;
s >> flip;
}
Animation::Animation()
{}
std::unique_ptr<Animation> Animation::loadResource(ResourceLoader& loader)
{
auto result = std::make_unique<Animation>();
auto sData = loader.getStatic();
Deserializer s(sData->getSpan());
s >> *result;
result->loadDependencies(loader);
return result;
}
void Animation::reload(Resource&& resource)
{
*this = std::move(dynamic_cast<Animation&>(resource));
}
void Animation::loadDependencies(ResourceLoader& loader)
{
spriteSheet = loader.getAPI().getResource<SpriteSheet>(spriteSheetName);
auto matDef = loader.getAPI().getResource<MaterialDefinition>(materialName);
material = std::make_shared<Material>(matDef);
material->set("tex0", spriteSheet->getTexture());
for (auto& s: sequences) {
for (auto& f : s.frameDefinitions) {
s.frames.emplace_back(f.makeFrame(*spriteSheet, directions));
}
}
}
void Animation::setName(const String& n)
{
name = n;
}
void Animation::setMaterialName(const String& n)
{
materialName = n;
}
void Animation::setSpriteSheetName(const String& n)
{
spriteSheetName = n;
}
void Animation::addSequence(const AnimationSequence& sequence)
{
sequences.push_back(sequence);
}
void Animation::addDirection(const AnimationDirection& direction)
{
directions.push_back(direction);
}
const AnimationSequence& Animation::getSequence(const String& seqName) const
{
for (auto& seq: sequences) {
if (seq.name == seqName) {
return seq;
}
}
return sequences.at(0);
}
const AnimationDirection& Animation::getDirection(const String& dirName) const
{
Expects(directions.size() > 0);
for (auto& dir : directions) {
if (dir.name == dirName) {
return dir;
}
}
return directions[0];
}
const AnimationDirection& Animation::getDirection(int id) const
{
Expects(id >= 0);
Expects(directions.size() > 0);
if (id < int(directions.size())) {
return directions[id];
} else {
return directions[0];
}
}
Vector2i Animation::getPivot() const
{
return sequences.at(0).getFrame(0).getSprite(0).origPivot;
}
bool Animation::hasSequence(const String& seqName) const
{
for (auto& s: sequences) {
if (s.getName() == seqName) {
return true;
}
}
return false;
}
void Animation::serialize(Serializer& s) const
{
s << name;
s << spriteSheetName;
s << materialName;
s << sequences;
s << directions;
}
void Animation::deserialize(Deserializer& s)
{
s >> name;
s >> spriteSheetName;
s >> materialName;
s >> sequences;
s >> directions;
}
<|endoftext|>
|
<commit_before>/************************************************************************
This file is part of Freekick.
Freekick 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.
Freekick 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 Freekick. If not, see <http://www.gnu.org/licenses/>.
Copyright Antti Salonen, 2008
**************************************************************************/
#include "tasks/PlaySoccer.h"
namespace freekick
{
namespace match
{
namespace client
{
namespace ai_client
{
namespace tasks
{
PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)
: mMatchStatus(ms),
mPlayerID(id)
{
mPlayer = mMatchStatus->getPlayer(mPlayerID);
}
bool PlaySoccer::finished() const
{
const BallState bs = mMatchStatus->getBallState();
if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)
{
return true;
}
return false;
}
boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()
{
if(mPlayer->isSubstitute())
{
// TODO: replace with BeingASubstituteTask
if(emptyTasks())
{
boost::shared_ptr<Idle> t(new Idle(mPlayerID));
addTask(t);
}
}
else
{
Helpers h(mMatchStatus, mPlayerID);
clearTasks();
if(!emptyTasks())
{
// TODO: check if current task should be cleared
clearTasks();
}
if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)
{
boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if(h.iskickoff && !h.startplay) // goto start formation
{
boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)
{
if(h.abletokick)
{
boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if(h.ourclubhasball) // run to ball
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
else // defensive
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
}
}
else
{
addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);
future_pos.y = 0.0f;
float future_dist = (mPlayer->getPosition() - future_pos).length();
if(future_dist < AIConfig::getInstance()->max_future_fetch_distance)
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));
addTask(t);
}
}
}
}
}
boost::shared_ptr<Task> nexttask = getNextTask();
boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();
return msg;
}
}
}
}
}
}
<commit_msg>ai: fixed issue of ai trying to kick ball when not allowed<commit_after>/************************************************************************
This file is part of Freekick.
Freekick 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.
Freekick 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 Freekick. If not, see <http://www.gnu.org/licenses/>.
Copyright Antti Salonen, 2008
**************************************************************************/
#include "tasks/PlaySoccer.h"
namespace freekick
{
namespace match
{
namespace client
{
namespace ai_client
{
namespace tasks
{
PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)
: mMatchStatus(ms),
mPlayerID(id)
{
mPlayer = mMatchStatus->getPlayer(mPlayerID);
}
bool PlaySoccer::finished() const
{
const BallState bs = mMatchStatus->getBallState();
if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)
{
return true;
}
return false;
}
boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()
{
if(mPlayer->isSubstitute())
{
// TODO: replace with BeingASubstituteTask
if(emptyTasks())
{
boost::shared_ptr<Idle> t(new Idle(mPlayerID));
addTask(t);
}
}
else
{
Helpers h(mMatchStatus, mPlayerID);
clearTasks();
if(!emptyTasks())
{
// TODO: check if current task should be cleared
clearTasks();
}
if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)
{
boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if(h.iskickoff && !h.startplay) // goto start formation
{
boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)
{
if(h.abletokick)
{
boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
if(h.ourclubhasball) // run to ball
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
else // defensive
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
}
}
else
{
addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);
future_pos.y = 0.0f;
float future_dist = (mPlayer->getPosition() - future_pos).length();
if(h.allowed_to_kick && future_dist < AIConfig::getInstance()->max_future_fetch_distance)
{
boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));
addTask(t);
}
else
{
boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));
addTask(t);
}
}
}
}
}
boost::shared_ptr<Task> nexttask = getNextTask();
boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();
return msg;
}
}
}
}
}
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp>
#include <limits>
namespace stan {
namespace math {
template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {
using boost::math::digamma;
using std::exp;
using std::fabs;
using std::log;
using std::pow;
T u = gamma_p(x1.val_, x2.val_);
if (is_inf(x1.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
if (is_inf(x2.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);
T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));
return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
}
template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, double x2) {
using boost::math::digamma;
using std::exp;
using std::fabs;
using std::log;
using std::pow;
T u = gamma_p(x1.val_, x2);
if (is_inf(x1.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
if (is_inf(x2))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);
return fvar<T>(u, x1.d_ * der1);
}
template <typename T>
inline fvar<T> gamma_p(double x1, const fvar<T> &x2) {
using std::exp;
using std::log;
T u = gamma_p(x1, x2.val_);
if (is_inf(x1))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - stan::math::lgamma(x1));
return fvar<T>(u, x2.d_ * der2);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Remove unnecessary namespace qualification<commit_after>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP
#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/fun/value_of_rec.hpp>
#include <stan/math/prim/scal/err/domain_error.hpp>
#include <stan/math/prim/scal/fun/gamma_p.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp>
#include <limits>
namespace stan {
namespace math {
template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {
using boost::math::digamma;
using std::exp;
using std::fabs;
using std::log;
using std::pow;
T u = gamma_p(x1.val_, x2.val_);
if (is_inf(x1.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
if (is_inf(x2.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);
T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));
return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);
}
template <typename T>
inline fvar<T> gamma_p(const fvar<T> &x1, double x2) {
using boost::math::digamma;
using std::exp;
using std::fabs;
using std::log;
using std::pow;
T u = gamma_p(x1.val_, x2);
if (is_inf(x1.val_))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
if (is_inf(x2))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);
return fvar<T>(u, x1.d_ * der1);
}
template <typename T>
inline fvar<T> gamma_p(double x1, const fvar<T> &x2) {
using std::exp;
using std::log;
T u = gamma_p(x1, x2.val_);
if (is_inf(x1))
return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());
T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - lgamma(x1));
return fvar<T>(u, x2.d_ * der2);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestStringToNumeric.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkDelimitedTextReader.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkStringArray.h"
#include "vtkStringToNumeric.h"
#include "vtkTable.h"
#include "vtkTestUtilities.h"
#include "vtkMath.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type,name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
namespace
{
int ArrayTypesTest(int argc, char* argv[])
{
char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/authors.csv");
VTK_CREATE(vtkDelimitedTextReader, reader);
reader->SetFileName(file);
reader->SetHaveHeaders(true);
delete [] file;
VTK_CREATE(vtkStringToNumeric, numeric);
numeric->SetInputConnection(reader->GetOutputPort());
numeric->Update();
vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
cerr << "Testing array types..." << endl;
int errors = 0;
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Author")))
{
cerr << "ERROR: Author array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Affiliation")))
{
cerr << "ERROR: Affiliation array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Alma Mater")))
{
cerr << "ERROR: Alma Mater array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Categories")))
{
cerr << "ERROR: Categories array missing" << endl;
++errors;
}
if (!vtkIntArray::SafeDownCast(table->GetColumnByName("Age")))
{
cerr << "ERROR: Age array missing or not converted to int" << endl;
++errors;
}
else
{
vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName("Age"));
int sum = 0;
for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)
{
sum += age->GetValue(i);
}
if (sum != 181)
{
cerr << "ERROR: Age sum is incorrect" << endl;
++errors;
}
}
if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness")))
{
cerr << "ERROR: Coolness array missing or not converted to double" << endl;
++errors;
}
else
{
vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness"));
double sum = 0;
for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)
{
sum += cool->GetValue(i);
}
double eps = 10e-8;
double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);
if (diff > eps)
{
cerr << "ERROR: Coolness sum is incorrect" << endl;
++errors;
}
}
return errors;
}
int WhitespaceAndEmptyCellsTest()
{
// Setup a table of string columns, which is to get converted to numeric
VTK_CREATE(vtkTable, inputTable);
VTK_CREATE(vtkStringArray, integerColumn);
integerColumn->SetName("IntegerColumn");
integerColumn->SetNumberOfTuples(2);
integerColumn->SetValue(0, " ");
integerColumn->SetValue(1, " 1 ");
VTK_CREATE(vtkStringArray, doubleColumn);
doubleColumn->SetName("DoubleColumn");
doubleColumn->SetNumberOfTuples(2);
doubleColumn->SetValue(0, " ");
doubleColumn->SetValue(1, " 1.1 ");
inputTable->AddColumn(integerColumn);
inputTable->AddColumn(doubleColumn);
// Setup the vtkStringToNumeric which is under test
VTK_CREATE(vtkStringToNumeric, numeric);
int const defaultIntValue = 100;
numeric->SetDefaultIntegerValue(defaultIntValue);
numeric->SetDefaultDoubleValue(vtkMath::Nan());
numeric->SetTrimWhitespacePriorToNumericConversion(true);
numeric->SetInput(inputTable);
numeric->Update();
vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
table->Dump();
cerr << "Testing handling whitespace and empty cells..." << endl;
int errors = 0;
if (!vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn")))
{
cerr << "ERROR: IntegerColumn array missing or not converted to int" << endl;
++errors;
}
else
{
vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn"));
if (defaultIntValue != column->GetValue(0))
{
cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << defaultIntValue;
++errors;
}
if (1 != column->GetValue(1))
{
cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1";
++errors;
}
}
if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn")))
{
cerr << "ERROR: DoubleColumn array missing or not converted to double" << endl;
++errors;
}
else
{
vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn"));
if (!vtkMath::IsNan(column->GetValue(0)))
{
cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << vtkMath::Nan();
++errors;
}
if (1.1 != column->GetValue(1))
{
cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1.1";
++errors;
}
}
return errors;
}
}
int TestStringToNumeric(int argc, char* argv[])
{
int errors = ArrayTypesTest(argc, argv);
errors += WhitespaceAndEmptyCellsTest();
cerr << "...done testing" << endl;
cerr << errors << " errors found." << endl;
return errors;
}
<commit_msg>Adding back testing for ForceDouble<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestStringToNumeric.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkDelimitedTextReader.h"
#include "vtkDoubleArray.h"
#include "vtkIntArray.h"
#include "vtkStringArray.h"
#include "vtkStringToNumeric.h"
#include "vtkTable.h"
#include "vtkTestUtilities.h"
#include "vtkMath.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type,name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
namespace
{
int ArrayTypesTest(int argc, char* argv[])
{
char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/authors.csv");
VTK_CREATE(vtkDelimitedTextReader, reader);
reader->SetFileName(file);
reader->SetHaveHeaders(true);
delete [] file;
VTK_CREATE(vtkStringToNumeric, numeric);
numeric->SetInputConnection(reader->GetOutputPort());
numeric->Update();
vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
cerr << "Testing array types..." << endl;
int errors = 0;
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Author")))
{
cerr << "ERROR: Author array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Affiliation")))
{
cerr << "ERROR: Affiliation array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Alma Mater")))
{
cerr << "ERROR: Alma Mater array missing" << endl;
++errors;
}
if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Categories")))
{
cerr << "ERROR: Categories array missing" << endl;
++errors;
}
if (!vtkIntArray::SafeDownCast(table->GetColumnByName("Age")))
{
cerr << "ERROR: Age array missing or not converted to int" << endl;
++errors;
}
else
{
vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName("Age"));
int sum = 0;
for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)
{
sum += age->GetValue(i);
}
if (sum != 181)
{
cerr << "ERROR: Age sum is incorrect" << endl;
++errors;
}
}
if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness")))
{
cerr << "ERROR: Coolness array missing or not converted to double" << endl;
++errors;
}
else
{
vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness"));
double sum = 0;
for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)
{
sum += cool->GetValue(i);
}
double eps = 10e-8;
double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);
if (diff > eps)
{
cerr << "ERROR: Coolness sum is incorrect" << endl;
++errors;
}
}
cerr << "Testing force double..." << endl;
numeric->ForceDoubleOn();
numeric->Update();
table = vtkTable::SafeDownCast(numeric->GetOutput());
if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Age")))
{
cerr << "ERROR: Arrays should have been forced to double" << endl;
++errors;
}
return errors;
}
int WhitespaceAndEmptyCellsTest()
{
// Setup a table of string columns, which is to get converted to numeric
VTK_CREATE(vtkTable, inputTable);
VTK_CREATE(vtkStringArray, integerColumn);
integerColumn->SetName("IntegerColumn");
integerColumn->SetNumberOfTuples(2);
integerColumn->SetValue(0, " ");
integerColumn->SetValue(1, " 1 ");
VTK_CREATE(vtkStringArray, doubleColumn);
doubleColumn->SetName("DoubleColumn");
doubleColumn->SetNumberOfTuples(2);
doubleColumn->SetValue(0, " ");
doubleColumn->SetValue(1, " 1.1 ");
inputTable->AddColumn(integerColumn);
inputTable->AddColumn(doubleColumn);
// Setup the vtkStringToNumeric which is under test
VTK_CREATE(vtkStringToNumeric, numeric);
int const defaultIntValue = 100;
numeric->SetDefaultIntegerValue(defaultIntValue);
numeric->SetDefaultDoubleValue(vtkMath::Nan());
numeric->SetTrimWhitespacePriorToNumericConversion(true);
numeric->SetInput(inputTable);
numeric->Update();
vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());
table->Dump();
cerr << "Testing handling whitespace and empty cells..." << endl;
int errors = 0;
if (!vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn")))
{
cerr << "ERROR: IntegerColumn array missing or not converted to int" << endl;
++errors;
}
else
{
vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn"));
if (defaultIntValue != column->GetValue(0))
{
cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << defaultIntValue;
++errors;
}
if (1 != column->GetValue(1))
{
cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1";
++errors;
}
}
if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn")))
{
cerr << "ERROR: DoubleColumn array missing or not converted to double" << endl;
++errors;
}
else
{
vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn"));
if (!vtkMath::IsNan(column->GetValue(0)))
{
cerr << "ERROR: Empty cell value is: " << column->GetValue(0) << ". Expected: " << vtkMath::Nan();
++errors;
}
if (1.1 != column->GetValue(1))
{
cerr << "ERROR: Cell with whitespace value is: " << column->GetValue(1) << ". Expected: 1.1";
++errors;
}
}
return errors;
}
}
int TestStringToNumeric(int argc, char* argv[])
{
int errors = ArrayTypesTest(argc, argv);
errors += WhitespaceAndEmptyCellsTest();
cerr << "...done testing" << endl;
cerr << errors << " errors found." << endl;
return errors;
}
<|endoftext|>
|
<commit_before>// GrowthRegion.cpp
// Implements the GrowthRegion class
#include "GrowthRegion.h"
#include "InputXML.h"
#include "Model.h"
#include "InstModel.h"
#include "SupplyDemand.h"
#include "BuildingManager.h"
#include "SymbolicFunctionFactories.h"
#include "CycException.h"
#include <stdlib.h>
#include <map>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
#include <libxml/xpath.h>
using namespace std;
using namespace boost;
/* --------------------
* GrowthRegion Class Methods
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GrowthRegion::GrowthRegion() {
builders_ = map<Producer*,Model*>();
producers_ = map<Producer*,Model*>();
commodities_ = vector<Commodity>();
sdmanager_ = SupplyDemandManager();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {
LOG(LEV_DEBUG2, "greg") << "A Growth Region is being initialized";
// xml inits
Model::init(cur); // name_ and model_impl_
RegionModel::initAllowedFacilities(cur); // allowedFacilities_
// get path to this model
xmlNodePtr model_cur =
XMLinput->get_xpath_element(context,cur,"model/GrowthRegion");
// get all commodities
xmlNodeSetPtr commodity_nodes =
XMLinput->get_xpath_elements(context,model_cur,"gcommodity");\
// for now we can only handle one commodity
if (commodity_nodes->nodeNr > 1) {
stringstream err("");
err << "GrowthRegion can currently only handle demand for "
<< "one commodity type.";
throw CycException(err.str());
}
// populate supply demand manager info for each commodity
for (int i=0;i<commodity_nodes->nodeNr;i++) {
initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());
}
// instantiate building manager
initBuildManager();
// parent_ and tick listener, model 'born'
RegionModel::initSimInteraction(this);
// children->setParent, requires init()
RegionModel::initChildren(cur);
// populate producers_, builders_
populateProducerMaps();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initBuildManager() {
buildmanager_ =
shared_ptr<BuildingManager>(new BuildingManager(sdmanager_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur) {
init(cur,XMLinput->context());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initCommodity(xmlNodePtr& node,
xmlXPathContextPtr context) {
// instantiate product
string name =
(const char*)XMLinput->get_xpath_content(context,node,"name");
Commodity commodity(name);
int position = commodities_.size();
commodities_.push_back(commodity);
// instantiate demand
string type =
(const char*)XMLinput->get_xpath_content(context,node,"demand/type");
string params =
(const char*)XMLinput->get_xpath_content(context,node,"demand/parameters");
BasicFunctionFactory bff;
FunctionPtr demand = bff.getFunctionPtr(type,params);
// set up producers vector
vector<Producer> producers;
xmlNodeSetPtr producer_nodes =
XMLinput->get_xpath_elements(context,node,"demand/metby");
for (int i=0; i<producer_nodes->nodeNr; i++) {
xmlNodePtr pnode = producer_nodes->nodeTab[i];
producers.push_back(getProducer(context,pnode,commodities_.at(position)));
} // end producer nodes
// populate info
sdmanager_.registerCommodity(commodities_.at(position),demand,producers);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Producer GrowthRegion::getProducer(xmlXPathContextPtr& context,
xmlNodePtr& node,
Commodity& commodity) {
string fac_name =
(const char*)XMLinput->get_xpath_content(context,node,"facility");
double capacity =
atof((const char*)
XMLinput->get_xpath_content(context,node,"capacity"));
double cost = capacity; // cost = capacity
return Producer(fac_name,commodity,capacity,cost);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::copy(GrowthRegion* src) {
RegionModel::copy(src);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::str() {
std::string s = RegionModel::str();
// if ( builders_ == NULL || builders_->empty() ){
// s += name() + " has no builders (currently).";
// } else {
// s += name() + " has the following builders: " ;
// for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
// mit != builders_->end(); mit++) {
// s += " prototype=" + mit->first->name() + "(";
// for(list<Model*>::iterator inst = mit->second->begin();
// inst != mit->second->end(); inst++) {
// s += (*inst)->name() + ", ";
// }
// s += "), ";
// }
// }
return s;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::handleTick(int time) {
// for each commodity
for (int i = 0; i < commodities_.size(); i++) {
Commodity c = commodities_.at(i);
// does demand exist?
double unmet_demand =
sdmanager_.supply(c) - sdmanager_.demand(c,time);
// if so, determine which prototypes to build and build them
if (unmet_demand > 0) {
vector<BuildOrder> orders =
buildmanager_->makeBuildDecision(c,unmet_demand);
// build the prototypes
orderBuilds(orders);
}
}
// After we finish building, call the normal handleTick for a region
RegionModel::handleTick(time);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerMaps() {
// if there are no children, yell
if ( children_.empty() ) {
stringstream err("");
err << "GrowthRegion " << this->name()
<< " cannot populate its list"
<< " of builders because it has no children.";
throw CycOverrideException(err.str());
}
// for each commodity
for (int i = 0; i < commodities_.size(); i++) {
Commodity c = commodities_.at(i);
// map each producer's name to a pointer to it
map<string,Producer*> producer_names;
populateProducerNames(c,producer_names);
// populate the maps with those producer names
populateMaps(this,producer_names);
}
// if there are no builders, yell
if ( builders_.empty() ) {
stringstream err("");
err << "GrowthRegion " << this->name()
<< " has finished populating"
<< " its list of builders, but that list is empty.";
throw CycOverrideException(err.str());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerNames(Commodity& c,
std::map<std::string,Producer*>&
producer_names) {
for (int j = 0; j < sdmanager_.nProducers(c); j++) {
Producer* p = sdmanager_.producer(c,j);
producer_names[p->name()] = p;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateMaps(Model* node,
std::map<std::string,Producer*>&
producer_names) {
// the name to search for
string model_name = node->name();
// if the model is in producers, log it as a producer
// and its parent as a builder
map<string,Producer*>::iterator it = producer_names.find(model_name);
if (it != producer_names.end()) {
producers_[it->second] = node;
builders_[it->second] = node->parent();
}
// perform the same operation for each of this node's children
for (int i = 0; i < node->nChildren(); i++) {
populateMaps(node->children(i),producer_names);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::printMaps() {
stringstream ss("");
map<Producer*,Model*>::iterator it;
ss << "Producer map:" << endl;
for (it = producers_.begin(); it != producers_.end(); it++) {
ss << "\t" << it->first->name() << " producer produces model "
<< it->second->name() << endl;
}
ss << "Builder map:" << endl;
for (it = builders_.begin(); it != builders_.end(); it++) {
ss << "\t" << it->first->name() << " producer is built by model "
<< it->second->name() << endl;
}
return ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {
// for each order
for (int i = 0; i < orders.size(); i++) {
BuildOrder bo = orders.at(i);
// for each instance of a prototype order
for (int j = 0; j < bo.number; j++) {
Model* builder = builders_[bo.producer];
Model* prototype = producers_[bo.producer];
orderBuild(builder,prototype);
}
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuild(Model* builder, Model* prototype) {
// build functions must know who is placing the build order
dynamic_cast<InstModel*>(builder)->build(prototype,this);
}
/* -------------------- */
/* --------------------
* Model Class Methods
* --------------------
*/
extern "C" Model* constructGrowthRegion() {
return new GrowthRegion();
}
/* -------------------- */
<commit_msg>in cyclus pull request https://github.com/cyclus/core/pull/285, the BuildManager constructor was changed to take a pointer. This makes cycamore's GrowthRegion compatible with that change. A previously noted occaisionally failing test 'TestBuildDecision' continues to fail despite this change.<commit_after>// GrowthRegion.cpp
// Implements the GrowthRegion class
#include "GrowthRegion.h"
#include "InputXML.h"
#include "Model.h"
#include "InstModel.h"
#include "SupplyDemand.h"
#include "BuildingManager.h"
#include "SymbolicFunctionFactories.h"
#include "CycException.h"
#include <stdlib.h>
#include <map>
#include <vector>
#include <string>
#include <boost/shared_ptr.hpp>
#include <libxml/xpath.h>
using namespace std;
using namespace boost;
/* --------------------
* GrowthRegion Class Methods
* --------------------
*/
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GrowthRegion::GrowthRegion() {
builders_ = map<Producer*,Model*>();
producers_ = map<Producer*,Model*>();
commodities_ = vector<Commodity>();
sdmanager_ = SupplyDemandManager();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {
LOG(LEV_DEBUG2, "greg") << "A Growth Region is being initialized";
// xml inits
Model::init(cur); // name_ and model_impl_
RegionModel::initAllowedFacilities(cur); // allowedFacilities_
// get path to this model
xmlNodePtr model_cur =
XMLinput->get_xpath_element(context,cur,"model/GrowthRegion");
// get all commodities
xmlNodeSetPtr commodity_nodes =
XMLinput->get_xpath_elements(context,model_cur,"gcommodity");\
// for now we can only handle one commodity
if (commodity_nodes->nodeNr > 1) {
stringstream err("");
err << "GrowthRegion can currently only handle demand for "
<< "one commodity type.";
throw CycException(err.str());
}
// populate supply demand manager info for each commodity
for (int i=0;i<commodity_nodes->nodeNr;i++) {
initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());
}
// instantiate building manager
initBuildManager();
// parent_ and tick listener, model 'born'
RegionModel::initSimInteraction(this);
// children->setParent, requires init()
RegionModel::initChildren(cur);
// populate producers_, builders_
populateProducerMaps();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initBuildManager() {
buildmanager_ =
shared_ptr<BuildingManager>(new BuildingManager(&sdmanager_));
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::init(xmlNodePtr cur) {
init(cur,XMLinput->context());
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::initCommodity(xmlNodePtr& node,
xmlXPathContextPtr context) {
// instantiate product
string name =
(const char*)XMLinput->get_xpath_content(context,node,"name");
Commodity commodity(name);
int position = commodities_.size();
commodities_.push_back(commodity);
// instantiate demand
string type =
(const char*)XMLinput->get_xpath_content(context,node,"demand/type");
string params =
(const char*)XMLinput->get_xpath_content(context,node,"demand/parameters");
BasicFunctionFactory bff;
FunctionPtr demand = bff.getFunctionPtr(type,params);
// set up producers vector
vector<Producer> producers;
xmlNodeSetPtr producer_nodes =
XMLinput->get_xpath_elements(context,node,"demand/metby");
for (int i=0; i<producer_nodes->nodeNr; i++) {
xmlNodePtr pnode = producer_nodes->nodeTab[i];
producers.push_back(getProducer(context,pnode,commodities_.at(position)));
} // end producer nodes
// populate info
sdmanager_.registerCommodity(commodities_.at(position),demand,producers);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Producer GrowthRegion::getProducer(xmlXPathContextPtr& context,
xmlNodePtr& node,
Commodity& commodity) {
string fac_name =
(const char*)XMLinput->get_xpath_content(context,node,"facility");
double capacity =
atof((const char*)
XMLinput->get_xpath_content(context,node,"capacity"));
double cost = capacity; // cost = capacity
return Producer(fac_name,commodity,capacity,cost);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::copy(GrowthRegion* src) {
RegionModel::copy(src);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::str() {
std::string s = RegionModel::str();
// if ( builders_ == NULL || builders_->empty() ){
// s += name() + " has no builders (currently).";
// } else {
// s += name() + " has the following builders: " ;
// for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
// mit != builders_->end(); mit++) {
// s += " prototype=" + mit->first->name() + "(";
// for(list<Model*>::iterator inst = mit->second->begin();
// inst != mit->second->end(); inst++) {
// s += (*inst)->name() + ", ";
// }
// s += "), ";
// }
// }
return s;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::handleTick(int time) {
// for each commodity
for (int i = 0; i < commodities_.size(); i++) {
Commodity c = commodities_.at(i);
// does demand exist?
double unmet_demand =
sdmanager_.supply(c) - sdmanager_.demand(c,time);
// if so, determine which prototypes to build and build them
if (unmet_demand > 0) {
vector<BuildOrder> orders =
buildmanager_->makeBuildDecision(c,unmet_demand);
// build the prototypes
orderBuilds(orders);
}
}
// After we finish building, call the normal handleTick for a region
RegionModel::handleTick(time);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerMaps() {
// if there are no children, yell
if ( children_.empty() ) {
stringstream err("");
err << "GrowthRegion " << this->name()
<< " cannot populate its list"
<< " of builders because it has no children.";
throw CycOverrideException(err.str());
}
// for each commodity
for (int i = 0; i < commodities_.size(); i++) {
Commodity c = commodities_.at(i);
// map each producer's name to a pointer to it
map<string,Producer*> producer_names;
populateProducerNames(c,producer_names);
// populate the maps with those producer names
populateMaps(this,producer_names);
}
// if there are no builders, yell
if ( builders_.empty() ) {
stringstream err("");
err << "GrowthRegion " << this->name()
<< " has finished populating"
<< " its list of builders, but that list is empty.";
throw CycOverrideException(err.str());
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateProducerNames(Commodity& c,
std::map<std::string,Producer*>&
producer_names) {
for (int j = 0; j < sdmanager_.nProducers(c); j++) {
Producer* p = sdmanager_.producer(c,j);
producer_names[p->name()] = p;
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::populateMaps(Model* node,
std::map<std::string,Producer*>&
producer_names) {
// the name to search for
string model_name = node->name();
// if the model is in producers, log it as a producer
// and its parent as a builder
map<string,Producer*>::iterator it = producer_names.find(model_name);
if (it != producer_names.end()) {
producers_[it->second] = node;
builders_[it->second] = node->parent();
}
// perform the same operation for each of this node's children
for (int i = 0; i < node->nChildren(); i++) {
populateMaps(node->children(i),producer_names);
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string GrowthRegion::printMaps() {
stringstream ss("");
map<Producer*,Model*>::iterator it;
ss << "Producer map:" << endl;
for (it = producers_.begin(); it != producers_.end(); it++) {
ss << "\t" << it->first->name() << " producer produces model "
<< it->second->name() << endl;
}
ss << "Builder map:" << endl;
for (it = builders_.begin(); it != builders_.end(); it++) {
ss << "\t" << it->first->name() << " producer is built by model "
<< it->second->name() << endl;
}
return ss.str();
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {
// for each order
for (int i = 0; i < orders.size(); i++) {
BuildOrder bo = orders.at(i);
// for each instance of a prototype order
for (int j = 0; j < bo.number; j++) {
Model* builder = builders_[bo.producer];
Model* prototype = producers_[bo.producer];
orderBuild(builder,prototype);
}
}
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void GrowthRegion::orderBuild(Model* builder, Model* prototype) {
// build functions must know who is placing the build order
dynamic_cast<InstModel*>(builder)->build(prototype,this);
}
/* -------------------- */
/* --------------------
* Model Class Methods
* --------------------
*/
extern "C" Model* constructGrowthRegion() {
return new GrowthRegion();
}
/* -------------------- */
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreParticleResource.h"
#include "OgreTextureResource.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "ResourceHandler.h"
#include <Ogre.h>
namespace OgreRenderer
{
OgreParticleResource::OgreParticleResource(const std::string& id) :
ResourceInterface(id)
{
}
OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) :
ResourceInterface(id)
{
SetData(source);
}
OgreParticleResource::~OgreParticleResource()
{
RemoveTemplates();
}
bool OgreParticleResource::SetData(Foundation::AssetPtr source)
{
RemoveTemplates();
references_.clear();
if (!source)
{
OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (!source->GetSize())
{
OgreRenderingModule::LogError("Zero sized particle system asset");
return false;
}
// Detected template names
Core::StringVector new_templates;
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
try
{
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
// Parsed/modified script
std::ostringstream output;
while (!data->eof())
{
Ogre::String line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Process opening/closing braces
if (!ResourceHandler::ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
if (brace_level == 0)
{
line = id_ + "_" + Core::ToString<size_t>(new_templates.size());
new_templates.push_back(line);
// New script compilers need this
line = "particle_system " + line;
}
else
{
// Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
if (line.substr(0, 8) == "affector")
{
std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, "\t ");
if (line_vec.size() >= 2)
{
if (line_vec[1] == "ColourImage")
{
skip_until_next = true;
skip_brace_level = brace_level;
}
}
}
// Check for image/material definition
else if (line.substr(0, 8) == "material")
{
std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, "\t ");
if (line_vec.size() >= 2)
{
std::string mat_name = line_vec[1];
// Material script mode
if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == "script"))
{
references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));
line = "material " + mat_name;
}
// Texture mode
else
{
//! @todo handle legacy material variations
std::string variation;
if (line_vec.size() >= 3)
variation = line_vec[2];
references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));
line = "material " + mat_name;
}
}
}
}
// Write line to the copy
if (!skip_until_next)
output << line << std::endl;
else
OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
}
else
{
// Write line to the copy
if (!skip_until_next)
output << line << std::endl;
else
OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
if (brace_level <= skip_brace_level)
skip_until_next = false;
}
}
}
std::string output_str = output.str();
Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogWarning(e.what());
OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + source->GetId() + ".");
}
// Check which templates actually succeeded
for (Core::uint i = 0; i < new_templates.size(); ++i)
{
if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
{
templates_.push_back(new_templates[i]);
OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
}
}
// Theoretical success if at least one template was created
return IsValid();
}
static const std::string type_name("OgreParticle");
const std::string& OgreParticleResource::GetType() const
{
return type_name;
}
const std::string& OgreParticleResource::GetTypeStatic()
{
return type_name;
}
Core::uint OgreParticleResource::GetNumTemplates() const
{
return templates_.size();
}
const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const
{
static const std::string empty;
if (index >= templates_.size())
return empty;
return templates_[index];
}
void OgreParticleResource::RemoveTemplates()
{
for (unsigned i = 0; i < templates_.size(); ++i)
{
try
{
Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
} catch (...) {}
}
templates_.clear();
}
bool OgreParticleResource::IsValid() const
{
return (templates_.size() > 0);
}
}<commit_msg>[Fix] Should now compile also with latest Ogre and GCC. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OgreMaterialResource.h"
#include "OgreParticleResource.h"
#include "OgreTextureResource.h"
#include "OgreRenderingModule.h"
#include "OgreMaterialUtils.h"
#include "ResourceHandler.h"
#include <Ogre.h>
namespace OgreRenderer
{
OgreParticleResource::OgreParticleResource(const std::string& id) :
ResourceInterface(id)
{
}
OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) :
ResourceInterface(id)
{
SetData(source);
}
OgreParticleResource::~OgreParticleResource()
{
RemoveTemplates();
}
bool OgreParticleResource::SetData(Foundation::AssetPtr source)
{
RemoveTemplates();
references_.clear();
if (!source)
{
OgreRenderingModule::LogError("Null source asset data pointer");
return false;
}
if (!source->GetSize())
{
OgreRenderingModule::LogError("Zero sized particle system asset");
return false;
}
// Detected template names
Core::StringVector new_templates;
Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));
try
{
int brace_level = 0;
bool skip_until_next = false;
int skip_brace_level = 0;
// Parsed/modified script
std::ostringstream output;
while (!data->eof())
{
Ogre::String line = data->getLine();
// Skip empty lines & comments
if ((line.length()) && (line.substr(0, 2) != "//"))
{
// Process opening/closing braces
if (!ResourceHandler::ProcessBraces(line, brace_level))
{
// If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal
if (brace_level == 0)
{
line = id_ + "_" + Core::ToString<size_t>(new_templates.size());
new_templates.push_back(line);
// New script compilers need this
line = "particle_system " + line;
}
else
{
// Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded
if (line.substr(0, 8) == "affector")
{
std::vector<Ogre::String> line_vec;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
line_vec = Ogre::StringUtil::split(line, "\t ");
#else
Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
int size = vec.size();
line_vec.resize(size);
for (int i = 0; i < size; ++i)
line_vec[i] = vec[i];
#endif
if (line_vec.size() >= 2)
{
if (line_vec[1] == "ColourImage")
{
skip_until_next = true;
skip_brace_level = brace_level;
}
}
}
// Check for image/material definition
else if (line.substr(0, 8) == "material")
{
std::vector<Ogre::String> line_vec;
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6
line_vec = Ogre::StringUtil::split(line, "\t ");
#else
Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,"\t ");
int size = vec.size();
line_vec.resize(size);
for (int i = 0; i < size; ++i)
line_vec[i] = vec[i];
#endif
if (line_vec.size() >= 2)
{
std::string mat_name = line_vec[1];
// Material script mode
if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == "script"))
{
references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));
line = "material " + mat_name;
}
// Texture mode
else
{
//! @todo handle legacy material variations
std::string variation;
if (line_vec.size() >= 3)
variation = line_vec[2];
references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));
line = "material " + mat_name;
}
}
}
}
// Write line to the copy
if (!skip_until_next)
output << line << std::endl;
else
OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
}
else
{
// Write line to the copy
if (!skip_until_next)
output << line << std::endl;
else
OgreRenderingModule::LogDebug("Skipping risky particle effect line: " + line);
if (brace_level <= skip_brace_level)
skip_until_next = false;
}
}
}
std::string output_str = output.str();
Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));
Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
catch (Ogre::Exception& e)
{
OgreRenderingModule::LogWarning(e.what());
OgreRenderingModule::LogWarning("Failed to parse Ogre particle script " + source->GetId() + ".");
}
// Check which templates actually succeeded
for (Core::uint i = 0; i < new_templates.size(); ++i)
{
if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))
{
templates_.push_back(new_templates[i]);
OgreRenderingModule::LogDebug("Ogre particle system template " + new_templates[i] + " created");
}
}
// Theoretical success if at least one template was created
return IsValid();
}
static const std::string type_name("OgreParticle");
const std::string& OgreParticleResource::GetType() const
{
return type_name;
}
const std::string& OgreParticleResource::GetTypeStatic()
{
return type_name;
}
Core::uint OgreParticleResource::GetNumTemplates() const
{
return templates_.size();
}
const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const
{
static const std::string empty;
if (index >= templates_.size())
return empty;
return templates_[index];
}
void OgreParticleResource::RemoveTemplates()
{
for (unsigned i = 0; i < templates_.size(); ++i)
{
try
{
Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);
} catch (...) {}
}
templates_.clear();
}
bool OgreParticleResource::IsValid() const
{
return (templates_.size() > 0);
}
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010, Antonie Jovanoski
*
* All rights reserved.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
*/
#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetfriendshipdestroy.h"
#include "qtweetuser.h"
#include "qtweetconvert.h"
/**
* Constructor
*/
QTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :
QTweetNetBase(parent)
{
}
/**
* Constructor
* @param oauthTwitter OAuthTwitter object
* @param parent parent QObject
*/
QTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
QTweetNetBase(oauthTwitter, parent)
{
}
/**
* Unfollows the specified user
* @param userid user id to unfollow
* @param includeEntities when set totrue, each tweet will include a node called "entities,".
*/
void QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)
{
if (!isAuthenticationEnabled()) {
qCritical("Needs authentication to be enabled");
return;
}
QUrl url("http://api.twitter.com/1/friendships/destroy.json");
url.addQueryItem("user_id", QString::number(userid));
if (includeEntities)
url.addQueryItem("include_entities", "true");
QNetworkRequest req(url);
QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);
req.setRawHeader(AUTH_HEADER, oauthHeader);
QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
/**
* Unfollows the specified user
* @param screenName screen name to unfollow
* @param includeEntities when set totrue, each tweet will include a node called "entities,".
*/
void QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)
{
if (!isAuthenticationEnabled()) {
qCritical("Needs authentication to be enabled");
return;
}
QUrl url("http://api.twitter.com/1/friendships/destroy.json");
url.addQueryItem("screen_name", screenName);
if (includeEntities)
url.addQueryItem("include_entities", "true");
QNetworkRequest req(url);
QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);
req.setRawHeader(AUTH_HEADER, oauthHeader);
QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
void QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)
{
if (ok) {
QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());
emit parsedUser(user);
} else {
qDebug() << "QTweetFriendshipCreate parser error: " << errorMsg;
setLastErrorMessage(errorMsg);
emit error(JsonParsingError, errorMsg);
}
}
<commit_msg>Fixed issue 9.<commit_after>/* Copyright (c) 2010, Antonie Jovanoski
*
* All rights reserved.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
*/
#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetfriendshipdestroy.h"
#include "qtweetuser.h"
#include "qtweetconvert.h"
/**
* Constructor
*/
QTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :
QTweetNetBase(parent)
{
}
/**
* Constructor
* @param oauthTwitter OAuthTwitter object
* @param parent parent QObject
*/
QTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :
QTweetNetBase(oauthTwitter, parent)
{
}
/**
* Unfollows the specified user
* @param userid user id to unfollow
* @param includeEntities when set totrue, each tweet will include a node called "entities,".
*/
void QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)
{
if (!isAuthenticationEnabled()) {
qCritical("Needs authentication to be enabled");
return;
}
QUrl url("http://api.twitter.com/1/friendships/destroy.json");
url.addQueryItem("user_id", QString::number(userid));
if (includeEntities)
url.addQueryItem("include_entities", "true");
QNetworkRequest req(url);
QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);
req.setRawHeader(AUTH_HEADER, oauthHeader);
QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
/**
* Unfollows the specified user
* @param screenName screen name to unfollow
* @param includeEntities when set totrue, each tweet will include a node called "entities,".
*/
void QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)
{
if (!isAuthenticationEnabled()) {
qCritical("Needs authentication to be enabled");
return;
}
QUrl url("http://api.twitter.com/1/friendships/destroy.json");
url.addQueryItem("screen_name", screenName);
if (includeEntities)
url.addQueryItem("include_entities", "true");
QNetworkRequest req(url);
QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);
req.setRawHeader(AUTH_HEADER, oauthHeader);
QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);
connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}
void QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)
{
if (ok) {
QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());
emit parsedUser(user);
} else {
qDebug() << "QTweetFriendshipCreate parser error: " << errorMsg;
setLastErrorMessage(errorMsg);
emit error(JsonParsingError, errorMsg);
}
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "resetapplet.h"
#include "resetwidget.h"
#include "resetbrief.h"
#include <MTheme>
#include <MAction>
#include <QDBusInterface>
#undef DEBUG
#include "../debug.h"
Q_EXPORT_PLUGIN2(resetapplet, ResetApplet)
ResetApplet::ResetApplet() :
m_ResetBusinessLogic (new ResetBusinessLogic)
{
}
ResetApplet::~ResetApplet()
{
delete m_ResetBusinessLogic;
}
void
ResetApplet::init()
{
}
DcpWidget *
ResetApplet::pageMain(
int widgetId)
{
SYS_DEBUG ("widgetId = %d", widgetId);
switch (widgetId) {
case 0:
if (m_MainWidget == 0)
m_MainWidget = new ResetWidget (m_ResetBusinessLogic);
return m_MainWidget;
default:
SYS_WARNING ("Unknown widgetId: %d", widgetId);
}
return 0;
}
DcpWidget *
ResetApplet::constructWidget (
int widgetId)
{
SYS_DEBUG ("-----------------------------------");
SYS_DEBUG ("*** widgetId = %d", widgetId);
return pageMain (widgetId);
}
QString
ResetApplet::title() const
{
//% "Reset settings"
return qtTrId ("qtn_rset_reset_settings");
}
QVector<MAction*>
ResetApplet::viewMenuItems()
{
MAction *helpAction;
QVector<MAction*> vector;
SYS_DEBUG ("");
helpAction = new MAction (
//% "User Guide"
qtTrId ("qtn_comm_userguide"),
pageMain (0));
helpAction->setLocation (MAction::ApplicationMenuLocation);
connect (helpAction, SIGNAL (triggered (bool)),
this, SLOT (userGuide ()));
vector.append(helpAction);
return vector;
}
void
ResetApplet::userGuide ()
{
QDBusInterface userguide ("com.nokia.userguide", "/",
"com.nokia.UserGuideIf");
userguide.call ("pageByPath", "tips.cfg");
SYS_DEBUG ("");
}
DcpBrief *
ResetApplet::constructBrief (
int partId)
{
Q_UNUSED (partId);
return new ResetBrief (m_ResetBusinessLogic);
}
<commit_msg>removed menu from reset applet.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "resetapplet.h"
#include "resetwidget.h"
#include "resetbrief.h"
#include <MTheme>
#include <MAction>
#include <QDBusInterface>
#undef DEBUG
#include "../debug.h"
Q_EXPORT_PLUGIN2(resetapplet, ResetApplet)
ResetApplet::ResetApplet() :
m_ResetBusinessLogic (new ResetBusinessLogic)
{
}
ResetApplet::~ResetApplet()
{
delete m_ResetBusinessLogic;
}
void
ResetApplet::init()
{
}
DcpWidget *
ResetApplet::pageMain(
int widgetId)
{
SYS_DEBUG ("widgetId = %d", widgetId);
switch (widgetId) {
case 0:
if (m_MainWidget == 0)
m_MainWidget = new ResetWidget (m_ResetBusinessLogic);
return m_MainWidget;
default:
SYS_WARNING ("Unknown widgetId: %d", widgetId);
}
return 0;
}
DcpWidget *
ResetApplet::constructWidget (
int widgetId)
{
SYS_DEBUG ("-----------------------------------");
SYS_DEBUG ("*** widgetId = %d", widgetId);
return pageMain (widgetId);
}
QString
ResetApplet::title() const
{
//% "Reset settings"
return qtTrId ("qtn_rset_reset_settings");
}
QVector<MAction*>
ResetApplet::viewMenuItems()
{
QVector<MAction*> vector;
return vector;
}
void
ResetApplet::userGuide ()
{
QDBusInterface userguide ("com.nokia.userguide", "/",
"com.nokia.UserGuideIf");
userguide.call ("pageByPath", "tips.cfg");
SYS_DEBUG ("");
}
DcpBrief *
ResetApplet::constructBrief (
int partId)
{
Q_UNUSED (partId);
return new ResetBrief (m_ResetBusinessLogic);
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 <iostream>
#include <sstream>
#include "itkTimeProbesCollectorBase.h"
#include "tubeMessage.h"
#include "tubeMacro.h"
#include "metaScene.h"
#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkGroupSpatialObject.h"
#include "ClipTubesCLP.h"
template< unsigned int VDimension >
bool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,
std::vector<double> boxPos, std::vector<double> boxSize)
{
// Return a boolean indicating if any slice of the tube
// is included in the box.
// A slice is considered as a point and an associated radius
bool hasXInside=false;
bool hasYInside=false,
bool hasZInside=false;
if( pointPos[0] + tubeRadius >= boxPos[0] &&
pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )
{
hasXInside = true;
}
if( pointPos[1] <= boxPos[1] &&
pointPos[1] >= boxPos[1] - boxSize[1] )
{
hasYInside = true;
}
switch( VDimension )
{
case 2:
{
hasZInside = true;
break;
}
case 3:
{
if( pointPos[2] + tubeRadius >= boxPos[2] &&
pointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )
{
hasZInside = true;
}
break;
}
default:
{
tubeErrorMacro(
<< "Error: Only 2D and 3D data is currently supported." );
return EXIT_FAILURE;
}
}
return (hasXInside && hasYInside && hasZInside);
}
template< unsigned int VDimension >
int DoIt (int argc, char * argv[])
{
PARSE_ARGS;
// Ensure that the input image dimension is valid
// We only support 2D and 3D Images due to the
// limitation of itkTubeSpatialObject
if( VDimension != 2 && VDimension != 3 )
{
tube::ErrorMessage(
"Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
// The timeCollector to perform basic profiling of algorithmic components
itk::TimeProbesCollectorBase timeCollector;
// Load TRE File
tubeStandardOutputMacro( << "\n>> Loading TRE File" );
typedef itk::SpatialObjectReader< VDimension > TubesReaderType;
typedef itk::GroupSpatialObject< VDimension > TubeGroupType;
// typedef itk::TubeSpatialObject< VDimension > TubeType;
/*WARNING :
dynamic_cast on "typedef itk::TubeSpatialObject< VDimension > TubeType"
causes SEGFAULT
so TubeType corresponds to VesselTubeType to prevent issues
so TubePointType corresponds to VesselTubePointType */
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef itk::VesselTubeSpatialObjectPoint< VDimension > TubePointType;
timeCollector.Start( "Loading Input TRE File" );
typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();
try
{
tubeFileReader->SetFileName( inputTREFile.c_str() );
tubeFileReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error loading TRE File: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename TubeGroupType::Pointer pSourceTubeGroup =
tubeFileReader->GetGroup();
typename TubeGroupType::ChildrenListPointer pSourceTubeList =
pSourceTubeGroup->GetChildren();
timeCollector.Stop( "Loading Input TRE File" );
// Compute clipping
tubeStandardOutputMacro( << "\n>> Finding Tubes for Clipping" );
timeCollector.Start( "Selecting Tubes" );
//Target Group to save desired tubes
typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();
int targetTubeId=0;
for( typename TubeGroupType::ChildrenListType::iterator
tubeList_it = pSourceTubeList->begin();
tubeList_it != pSourceTubeList->end(); ++tubeList_it)
{
//**** Source Tube **** :
typename TubeType::Pointer pCurSourceTube =
dynamic_cast< TubeType* >( tubeList_it->GetPointer() );
//dynamic_cast verification
if(!pCurSourceTube)
{
return EXIT_FAILURE;
}
//Point List for TargetTube
typename TubeType::PointListType TargetPointList;
//Get points in current source tube
typename TubeType::PointListType pointList =
pCurSourceTube->GetPoints();
for( typename TubeType::PointListType::const_iterator
pointList_it = pointList.begin();
pointList_it != pointList.end(); ++pointList_it )
{
TubePointType curSourcePoint = *pointList_it;
typename TubePointType::PointType curSourcePos =
curSourcePoint.GetPosition();
//Save point in target tube if it belongs to the box
if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))
{
if(ClipTubes)
{
TargetPointList.push_back(curSourcePoint);
}
else
{
pCurSourceTube->SetId(targetTubeId);
++targetTubeId;
pTargetTubeGroup->AddSpatialObject(pCurSourceTube);
break;
}
}
else
{
if( TargetPointList.size() > 0 )
{
//**** Target Tube **** :
typename TubeType::Pointer pTargetTube = TubeType::New();
pTargetTube->SetId(targetTubeId);
++targetTubeId;
//Save clipped tube
pTargetTube->SetPoints(TargetPointList);
pTargetTubeGroup->AddSpatialObject(pTargetTube);
TargetPointList.clear();
}
}
}
}
timeCollector.Stop( "Selecting Tubes" );
// Write output TRE file
tubeStandardOutputMacro(
<< "\n>> Writing TRE file" );
timeCollector.Start( "Writing output TRE file" );
typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();
try
{
tubeWriter->SetFileName( outputTREFile.c_str() );
tubeWriter->SetInput(pTargetTubeGroup);
tubeWriter->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error writing TRE file: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Writing output TRE file" );
timeCollector.Report();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
if(boxCorner.empty() || boxSize.empty())
{
tube::ErrorMessage(
"Error: longflags --boxCorner and --boxSize are both required");
return EXIT_FAILURE;
}
MetaScene *mScene = new MetaScene;
mScene->Read( inputTREFile.c_str() );
if( mScene->GetObjectList()->empty() )
{
tubeWarningMacro( << "Input TRE file has no spatial objects" );
return EXIT_SUCCESS;
}
switch( mScene->GetObjectList()->front()->NDims() )
{
case 2:
{
return DoIt<2>( argc, argv );
break;
}
case 3:
{
return DoIt<3>( argc, argv );
break;
}
default:
{
tubeErrorMacro(
<< "Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
}
}<commit_msg>STYLE: KWStyle test OK<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 <iostream>
#include <sstream>
#include "itkTimeProbesCollectorBase.h"
#include "tubeMessage.h"
#include "tubeMacro.h"
#include "metaScene.h"
#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkGroupSpatialObject.h"
#include "ClipTubesCLP.h"
template< unsigned int VDimension >
bool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,
std::vector<double> boxPos, std::vector<double> boxSize)
{
// Return a boolean indicating if any slice of the tube
// is included in the box.
// A slice is considered as a point and an associated radius
bool hasXInside=false;
bool hasYInside=false,
bool hasZInside=false;
if( pointPos[0] + tubeRadius >= boxPos[0] &&
pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )
{
hasXInside = true;
}
if( pointPos[1] <= boxPos[1] &&
pointPos[1] >= boxPos[1] - boxSize[1] )
{
hasYInside = true;
}
switch( VDimension )
{
case 2:
{
hasZInside = true;
break;
}
case 3:
{
if( pointPos[2] + tubeRadius >= boxPos[2] &&
pointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )
{
hasZInside = true;
}
break;
}
default:
{
tubeErrorMacro(
<< "Error: Only 2D and 3D data is currently supported." );
return EXIT_FAILURE;
}
}
return (hasXInside && hasYInside && hasZInside);
}
template< unsigned int VDimension >
int DoIt (int argc, char * argv[])
{
PARSE_ARGS;
// Ensure that the input image dimension is valid
// We only support 2D and 3D Images due to the
// limitation of itkTubeSpatialObject
if( VDimension != 2 && VDimension != 3 )
{
tube::ErrorMessage(
"Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
// The timeCollector to perform basic profiling of algorithmic components
itk::TimeProbesCollectorBase timeCollector;
// Load TRE File
tubeStandardOutputMacro( << "\n>> Loading TRE File" );
typedef itk::SpatialObjectReader< VDimension > TubesReaderType;
typedef itk::GroupSpatialObject< VDimension > TubeGroupType;
//typedef itk::TubeSpatialObject< VDimension > TubeType;
/*WARNING :
dynamic_cast on "typedef itk::TubeSpatialObject< VDimension > TubeType"
causes SEGFAULT
so TubeType corresponds to VesselTubeType to prevent issues
so TubePointType corresponds to VesselTubePointType */
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef itk::VesselTubeSpatialObjectPoint< VDimension > TubePointType;
timeCollector.Start( "Loading Input TRE File" );
typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();
try
{
tubeFileReader->SetFileName( inputTREFile.c_str() );
tubeFileReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error loading TRE File: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
typename TubeGroupType::Pointer pSourceTubeGroup =
tubeFileReader->GetGroup();
typename TubeGroupType::ChildrenListPointer pSourceTubeList =
pSourceTubeGroup->GetChildren();
timeCollector.Stop( "Loading Input TRE File" );
// Compute clipping
tubeStandardOutputMacro( << "\n>> Finding Tubes for Clipping" );
timeCollector.Start( "Selecting Tubes" );
//Target Group to save desired tubes
typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();
int targetTubeId=0;
for( typename TubeGroupType::ChildrenListType::iterator
tubeList_it = pSourceTubeList->begin();
tubeList_it != pSourceTubeList->end(); ++tubeList_it)
{
//**** Source Tube **** :
typename TubeType::Pointer pCurSourceTube =
dynamic_cast< TubeType* >( tubeList_it->GetPointer() );
//dynamic_cast verification
if(!pCurSourceTube)
{
return EXIT_FAILURE;
}
//Point List for TargetTube
typename TubeType::PointListType TargetPointList;
//Get points in current source tube
typename TubeType::PointListType pointList =
pCurSourceTube->GetPoints();
for( typename TubeType::PointListType::const_iterator
pointList_it = pointList.begin();
pointList_it != pointList.end(); ++pointList_it )
{
TubePointType curSourcePoint = *pointList_it;
typename TubePointType::PointType curSourcePos =
curSourcePoint.GetPosition();
//Save point in target tube if it belongs to the box
if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))
{
if(ClipTubes)
{
TargetPointList.push_back(curSourcePoint);
}
else
{
pCurSourceTube->SetId(targetTubeId);
++targetTubeId;
pTargetTubeGroup->AddSpatialObject(pCurSourceTube);
break;
}
}
else
{
if( TargetPointList.size() > 0 )
{
//**** Target Tube **** :
typename TubeType::Pointer pTargetTube = TubeType::New();
pTargetTube->SetId(targetTubeId);
++targetTubeId;
//Save clipped tube
pTargetTube->SetPoints(TargetPointList);
pTargetTubeGroup->AddSpatialObject(pTargetTube);
TargetPointList.clear();
}
}
}
}
timeCollector.Stop( "Selecting Tubes" );
// Write output TRE file
tubeStandardOutputMacro(
<< "\n>> Writing TRE file" );
timeCollector.Start( "Writing output TRE file" );
typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();
try
{
tubeWriter->SetFileName( outputTREFile.c_str() );
tubeWriter->SetInput(pTargetTubeGroup);
tubeWriter->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error writing TRE file: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Writing output TRE file" );
timeCollector.Report();
return EXIT_SUCCESS;
}
// Main
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
if(boxCorner.empty() || boxSize.empty())
{
tube::ErrorMessage(
"Error: longflags --boxCorner and --boxSize are both required");
return EXIT_FAILURE;
}
MetaScene *mScene = new MetaScene;
mScene->Read( inputTREFile.c_str() );
if( mScene->GetObjectList()->empty() )
{
tubeWarningMacro( << "Input TRE file has no spatial objects" );
return EXIT_SUCCESS;
}
switch( mScene->GetObjectList()->front()->NDims() )
{
case 2:
{
return DoIt<2>( argc, argv );
break;
}
case 3:
{
return DoIt<3>( argc, argv );
break;
}
default:
{
tubeErrorMacro(
<< "Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
}
}
<|endoftext|>
|
<commit_before>// $Id$
//
// Task to skim ESD files.
//
//
#include "AliEsdSkimTask.h"
#include <TClonesArray.h>
#include <TFile.h>
#include <TTree.h>
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDtrackCuts.h"
#include "AliMultiplicity.h"
//_________________________________________________________________________________________________
AliEsdSkimTask::AliEsdSkimTask(const char *opt) :
AliAnalysisTaskSE(opt), fEvent(0), fTree(0), fCuts(0),
fDoZDC(1), fDoV0(1), fDoT0(1), fDoTPCv(1), fDoSPDv(1), fDoPriv(1),
fDoEmCs(1), fDoPCs(1), fDoEmT(1), fDoPT(1), fDoTracks(1), fDoMult(1),
fDoTof(1), fDoPileup(1), fDoClus(1), fEmcNames(""),
fDoMiniTracks(0), fTracks("Tracks"), fPhosClusOnly(0)
{
// Constructor.
if (!opt)
return;
DefineOutput(1, TTree::Class());
}
//_________________________________________________________________________________________________
void AliEsdSkimTask::UserExec(Option_t */*opt*/)
{
// Process event.
AliESDEvent *esdin = dynamic_cast<AliESDEvent*>(InputEvent());
if (!esdin)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
fEvent->Reset();
TList* objsin = esdin->GetList();
TList* objsout = fEvent->GetList();
AliESDHeader *header = dynamic_cast<AliESDHeader*>(objsin->FindObject("AliESDHeader"));
if (header) {
am->LoadBranch("AliESDHeader.");
*header = *esdin->GetHeader();
}
AliESDRun *run = dynamic_cast<AliESDRun*>(objsin->FindObject("AliESDRun"));
if (run) {
am->LoadBranch("AliESDRun.");
*run = *esdin->GetESDRun();
}
AliESDZDC *zdc = dynamic_cast<AliESDZDC*>(objsin->FindObject("AliESDZDC"));
if (zdc) {
am->LoadBranch("AliESDZDC.");
*zdc = *esdin->GetESDZDC();
}
AliESDVZERO *v0 = dynamic_cast<AliESDVZERO*>(objsin->FindObject("AliESDVZERO"));
if (v0) {
am->LoadBranch("AliESDVZERO.");
*v0 = *esdin->GetVZEROData();
}
AliESDTZERO *t0 = dynamic_cast<AliESDTZERO*>(objsin->FindObject("AliESDTZERO"));
if (t0) {
am->LoadBranch("AliESDTZERO.");
*t0 = *esdin->GetESDTZERO();
}
AliESDVertex *tpcv = dynamic_cast<AliESDVertex*>(objsin->FindObject("TPCVertex"));
if (tpcv) {
am->LoadBranch("TPCVertex.");
*tpcv = *esdin->GetPrimaryVertexTPC();
}
AliESDVertex *spdv = dynamic_cast<AliESDVertex*>(objsin->FindObject("SPDVertex"));
if (spdv) {
am->LoadBranch("SPDVertex.");
*spdv = *esdin->GetPrimaryVertexSPD();
}
AliESDVertex *priv = dynamic_cast<AliESDVertex*>(objsin->FindObject("PrimaryVertex"));
if (priv) {
am->LoadBranch("PrimaryVertex.");
*priv = *esdin->GetPrimaryVertexTracks();
}
AliESDCaloCells *ecells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject("EMCALCells"));
if (ecells) {
am->LoadBranch("EMCALCells.");
*ecells = *esdin->GetEMCALCells();
}
AliESDCaloCells *pcells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject("PHOSCells"));
if (pcells) {
am->LoadBranch("PHOSCells.");
*pcells = *esdin->GetPHOSCells();
}
AliESDCaloTrigger *etrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject("EMCALTrigger"));
if (etrig) {
am->LoadBranch("EMCALTrigger.");
*etrig = *esdin->GetCaloTrigger("EMCAL");
}
AliESDCaloTrigger *ptrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject("PHOSTrigger"));
if (ptrig) {
am->LoadBranch("PHOSTrigger.");
*ptrig = *esdin->GetCaloTrigger("PHOS");
}
AliMultiplicity *mult = dynamic_cast<AliMultiplicity*>(objsin->FindObject("AliMultiplicity"));
if (mult) {
am->LoadBranch("AliMultiplicity.");
*mult = *esdin->GetMultiplicity();
}
AliTOFHeader *tofh = dynamic_cast<AliTOFHeader*>(objsin->FindObject("AliTOFHeader"));
if (tofh) {
am->LoadBranch("AliTOFHeader.");
*tofh = *esdin->GetTOFHeader();
}
TClonesArray *spup = dynamic_cast<TClonesArray*>(objsin->FindObject("SPDPileupVertices"));
if (spup) {
am->LoadBranch("SPDPileupVertices");
Int_t N = esdin->GetNumberOfPileupVerticesSPD();
for (Int_t i=0; i<N; ++i) {
const AliESDVertex *vtx = esdin->GetPileupVertexSPD(i);
if (vtx)
fEvent->AddPileupVertexSPD(vtx);
}
}
TClonesArray *tpup = dynamic_cast<TClonesArray*>(objsin->FindObject("TrkPileupVertices"));
if (tpup) {
am->LoadBranch("TrkPileupVertices");
Int_t N = esdin->GetNumberOfPileupVerticesTracks();
for (Int_t i=0; i<N; ++i) {
const AliESDVertex *vtx = esdin->GetPileupVertexTracks(i);
if (vtx)
fEvent->AddPileupVertexTracks(vtx);
}
}
TClonesArray *clus = dynamic_cast<TClonesArray*>(objsin->FindObject("CaloClusters"));
if (clus) {
am->LoadBranch("");
Int_t N = esdin->GetNumberOfCaloClusters();
for (Int_t i=0; i<N; ++i) {
AliESDCaloCluster *c = esdin->GetCaloCluster(i);
if (fPhosClusOnly && c->IsEMCAL())
continue;
if (c)
fEvent->AddCaloCluster(c);
}
}
TObjArray *namearr = fEmcNames.Tokenize(";");
if (namearr) {
for (Int_t i=0; i<namearr->GetEntries(); ++i) {
TString cname(namearr->At(i)->GetName());
if (cname.Length()<=0)
continue;
TClonesArray *arrin = dynamic_cast<TClonesArray*>(objsin->FindObject(cname));
TClonesArray *arrout = dynamic_cast<TClonesArray*>(objsout->FindObject(cname));
//AliFatal(Form("Can not find tracks with name %s", fTracks.Data()));
arrout->Delete();
const Int_t N = arrin->GetEntries();
for (Int_t iC=0, nC=0; iC<N; ++iC) {
AliESDCaloCluster *c = dynamic_cast<AliESDCaloCluster*>(arrin->At(iC));
if (!c)
continue;
new ((*arrout)[nC++]) AliESDCaloCluster(*c);
}
}
delete namearr;
}
if (fDoTracks) {
am->LoadBranch("Tracks");
TClonesArray *tracks = dynamic_cast<TClonesArray*>(objsin->FindObject(fTracks));
if (!tracks) {
AliFatal(Form("Can not find tracks with name %s", fTracks.Data()));
return;
}
const Int_t Ntracks = tracks->GetEntries();
Int_t nacc = 0;
for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {
AliESDtrack *track = dynamic_cast<AliESDtrack*>(tracks->At(iTracks));
if (!track)
continue;
if (fCuts) {
if (!fCuts->IsSelected(track))
continue;
}
if (fDoMiniTracks) {
track->MakeMiniESDtrack();
}
fEvent->AddTrack(track);
++nacc;
}
if (fCuts)
AliInfo(Form("Selected %d out of %d \n", nacc, Ntracks));
}
fTree->Fill();
}
//_________________________________________________________________________________________________
void AliEsdSkimTask::UserCreateOutputObjects()
{
// Create output objects.
fTree = new TTree("esdTree", "Tree with skimmed ESD objects");
fEvent = new AliESDEvent;
fEvent->AddObject(new AliESDHeader());
fEvent->AddObject(new AliESDRun());
if (fDoZDC)
fEvent->AddObject(new AliESDZDC());
if (fDoV0)
fEvent->AddObject(new AliESDVZERO());
if (fDoT0)
fEvent->AddObject(new AliESDTZERO());
if (fDoTPCv) {
AliESDVertex *tpcv = new AliESDVertex();
tpcv->SetName("TPCVertex");
fEvent->AddObject(tpcv);
}
if (fDoSPDv) {
AliESDVertex *spdv = new AliESDVertex();
spdv->SetName("SPDVertex");
fEvent->AddObject(spdv);
}
if (fDoPriv) {
AliESDVertex *priv = new AliESDVertex();
priv->SetName("PrimaryVertex");
fEvent->AddObject(priv);
}
if (fDoEmCs) {
fEvent->AddObject(new AliESDCaloCells("EMCALCells","EMCALCells"));
}
if (fDoPCs) {
fEvent->AddObject(new AliESDCaloCells("PHOSCells","PHOSCells"));
}
if (fDoEmT) {
AliESDCaloTrigger *etrig = new AliESDCaloTrigger;
etrig->SetName("EMCALTrigger");
fEvent->AddObject(etrig);
}
if (fDoPT) {
AliESDCaloTrigger *ptrig = new AliESDCaloTrigger;
ptrig->SetName("PHOSTrigger");
fEvent->AddObject(ptrig);
}
if (fDoMult) {
fEvent->AddObject(new AliMultiplicity());
}
if (fDoPileup) {
TClonesArray *arr1 = new TClonesArray("AliESDVertex",0);
arr1->SetName("SPDPileupVertices");
fEvent->AddObject(arr1);
TClonesArray *arr2 = new TClonesArray("AliESDVertex",0);
arr2->SetName("TPCPileupVertices");
fEvent->AddObject(arr2);
}
if (fDoTof) {
fEvent->AddObject(new AliTOFHeader());
}
if (fDoClus) {
TClonesArray *arr = new TClonesArray("AliESDCaloCluster",0);
arr->SetName("CaloClusters");
fEvent->AddObject(arr);
}
TObjArray *namearr = fEmcNames.Tokenize(";");
if (namearr) {
for (Int_t i=0; i<namearr->GetEntries(); ++i) {
TString cname(namearr->At(i)->GetName());
if (cname.Length()<=0)
continue;
TClonesArray *arr = new TClonesArray("AliESDCaloCluster",0);
arr->SetName(cname);
fEvent->AddObject(arr);
}
delete namearr;
}
if (fDoTracks) {
TClonesArray *arr = new TClonesArray("AliESDtrack",0);
arr->SetName("Tracks");
fEvent->AddObject(arr);
}
fEvent->GetStdContent();
fEvent->WriteToTree(fTree);
fTree->GetUserInfo()->Add(fEvent);
TFile *file = OpenFile(1);
fTree->SetDirectory(file);
fTree->SetAutoFlush(-1024*1024*1024);
fTree->SetAutoSave(-1024*1024*1024);
PostData(1,fTree);
}
<commit_msg>make mini esd tracks<commit_after>// $Id$
//
// Task to skim ESD files.
//
//
#include "AliEsdSkimTask.h"
#include <TClonesArray.h>
#include <TFile.h>
#include <TTree.h>
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliESDtrackCuts.h"
#include "AliMultiplicity.h"
//_________________________________________________________________________________________________
AliEsdSkimTask::AliEsdSkimTask(const char *opt) :
AliAnalysisTaskSE(opt), fEvent(0), fTree(0), fCuts(0),
fDoZDC(1), fDoV0(1), fDoT0(1), fDoTPCv(1), fDoSPDv(1), fDoPriv(1),
fDoEmCs(1), fDoPCs(1), fDoEmT(1), fDoPT(1), fDoTracks(1), fDoMult(1),
fDoTof(1), fDoPileup(1), fDoClus(1), fEmcNames(""),
fDoMiniTracks(0), fTracks("Tracks"), fPhosClusOnly(0)
{
// Constructor.
if (!opt)
return;
DefineOutput(1, TTree::Class());
}
//_________________________________________________________________________________________________
void AliEsdSkimTask::UserExec(Option_t */*opt*/)
{
// Process event.
AliESDEvent *esdin = dynamic_cast<AliESDEvent*>(InputEvent());
if (!esdin)
return;
AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
fEvent->Reset();
TList* objsin = esdin->GetList();
TList* objsout = fEvent->GetList();
AliESDHeader *header = dynamic_cast<AliESDHeader*>(objsin->FindObject("AliESDHeader"));
if (header) {
am->LoadBranch("AliESDHeader.");
*header = *esdin->GetHeader();
}
AliESDRun *run = dynamic_cast<AliESDRun*>(objsin->FindObject("AliESDRun"));
if (run) {
am->LoadBranch("AliESDRun.");
*run = *esdin->GetESDRun();
}
AliESDZDC *zdc = dynamic_cast<AliESDZDC*>(objsin->FindObject("AliESDZDC"));
if (zdc) {
am->LoadBranch("AliESDZDC.");
*zdc = *esdin->GetESDZDC();
}
AliESDVZERO *v0 = dynamic_cast<AliESDVZERO*>(objsin->FindObject("AliESDVZERO"));
if (v0) {
am->LoadBranch("AliESDVZERO.");
*v0 = *esdin->GetVZEROData();
}
AliESDTZERO *t0 = dynamic_cast<AliESDTZERO*>(objsin->FindObject("AliESDTZERO"));
if (t0) {
am->LoadBranch("AliESDTZERO.");
*t0 = *esdin->GetESDTZERO();
}
AliESDVertex *tpcv = dynamic_cast<AliESDVertex*>(objsin->FindObject("TPCVertex"));
if (tpcv) {
am->LoadBranch("TPCVertex.");
*tpcv = *esdin->GetPrimaryVertexTPC();
}
AliESDVertex *spdv = dynamic_cast<AliESDVertex*>(objsin->FindObject("SPDVertex"));
if (spdv) {
am->LoadBranch("SPDVertex.");
*spdv = *esdin->GetPrimaryVertexSPD();
}
AliESDVertex *priv = dynamic_cast<AliESDVertex*>(objsin->FindObject("PrimaryVertex"));
if (priv) {
am->LoadBranch("PrimaryVertex.");
*priv = *esdin->GetPrimaryVertexTracks();
}
AliESDCaloCells *ecells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject("EMCALCells"));
if (ecells) {
am->LoadBranch("EMCALCells.");
*ecells = *esdin->GetEMCALCells();
}
AliESDCaloCells *pcells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject("PHOSCells"));
if (pcells) {
am->LoadBranch("PHOSCells.");
*pcells = *esdin->GetPHOSCells();
}
AliESDCaloTrigger *etrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject("EMCALTrigger"));
if (etrig) {
am->LoadBranch("EMCALTrigger.");
*etrig = *esdin->GetCaloTrigger("EMCAL");
}
AliESDCaloTrigger *ptrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject("PHOSTrigger"));
if (ptrig) {
am->LoadBranch("PHOSTrigger.");
*ptrig = *esdin->GetCaloTrigger("PHOS");
}
AliMultiplicity *mult = dynamic_cast<AliMultiplicity*>(objsin->FindObject("AliMultiplicity"));
if (mult) {
am->LoadBranch("AliMultiplicity.");
*mult = *esdin->GetMultiplicity();
}
AliTOFHeader *tofh = dynamic_cast<AliTOFHeader*>(objsin->FindObject("AliTOFHeader"));
if (tofh) {
am->LoadBranch("AliTOFHeader.");
*tofh = *esdin->GetTOFHeader();
}
TClonesArray *spup = dynamic_cast<TClonesArray*>(objsin->FindObject("SPDPileupVertices"));
if (spup) {
am->LoadBranch("SPDPileupVertices");
Int_t N = esdin->GetNumberOfPileupVerticesSPD();
for (Int_t i=0; i<N; ++i) {
const AliESDVertex *vtx = esdin->GetPileupVertexSPD(i);
if (vtx)
fEvent->AddPileupVertexSPD(vtx);
}
}
TClonesArray *tpup = dynamic_cast<TClonesArray*>(objsin->FindObject("TrkPileupVertices"));
if (tpup) {
am->LoadBranch("TrkPileupVertices");
Int_t N = esdin->GetNumberOfPileupVerticesTracks();
for (Int_t i=0; i<N; ++i) {
const AliESDVertex *vtx = esdin->GetPileupVertexTracks(i);
if (vtx)
fEvent->AddPileupVertexTracks(vtx);
}
}
TClonesArray *clus = dynamic_cast<TClonesArray*>(objsin->FindObject("CaloClusters"));
if (clus) {
am->LoadBranch("");
Int_t N = esdin->GetNumberOfCaloClusters();
for (Int_t i=0; i<N; ++i) {
AliESDCaloCluster *c = esdin->GetCaloCluster(i);
if (fPhosClusOnly && c->IsEMCAL())
continue;
if (c)
fEvent->AddCaloCluster(c);
}
}
TObjArray *namearr = fEmcNames.Tokenize(";");
if (namearr) {
for (Int_t i=0; i<namearr->GetEntries(); ++i) {
TString cname(namearr->At(i)->GetName());
if (cname.Length()<=0)
continue;
TClonesArray *arrin = dynamic_cast<TClonesArray*>(objsin->FindObject(cname));
TClonesArray *arrout = dynamic_cast<TClonesArray*>(objsout->FindObject(cname));
//AliFatal(Form("Can not find tracks with name %s", fTracks.Data()));
arrout->Delete();
const Int_t N = arrin->GetEntries();
for (Int_t iC=0, nC=0; iC<N; ++iC) {
AliESDCaloCluster *c = dynamic_cast<AliESDCaloCluster*>(arrin->At(iC));
if (!c)
continue;
new ((*arrout)[nC++]) AliESDCaloCluster(*c);
}
}
delete namearr;
}
if (fDoTracks) {
am->LoadBranch("Tracks");
TClonesArray *tracks = dynamic_cast<TClonesArray*>(objsin->FindObject(fTracks));
if (!tracks) {
AliFatal(Form("Can not find tracks with name %s", fTracks.Data()));
return;
}
const Int_t Ntracks = tracks->GetEntries();
Int_t nacc = 0;
for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {
AliESDtrack *track = dynamic_cast<AliESDtrack*>(tracks->At(iTracks));
if (!track)
continue;
if (fCuts) {
if (!fCuts->IsSelected(track))
continue;
}
if (fDoMiniTracks) {
class AliEsdMiniTrack : public AliESDtrack
{
public:
AliEsdMiniTrack(const AliESDtrack &t) : AliESDtrack(t) {}
void MakeMiniESDtrack() {
delete fCp; fCp = 0;
delete fIp; fIp = 0;
delete fTPCInner; fTPCInner = 0;
delete fOp; fOp = 0;
delete fHMPIDp; fHMPIDp = 0;
for (Int_t i=0; i<3;i++) fKinkIndexes[i] = 0;
for (Int_t i=0; i<3;i++) fV0Indexes[i] = 0;
fTRDchi2 = 0;
fTRDncls = 0;
fTRDncls0 = 0;
fTRDsignal = 0;
for (Int_t i=0;i<kTRDnPlanes;i++) {
fTRDTimBin[i] = 0;
}
for (Int_t i=0;i<AliPID::kSPECIES;i++) fTRDr[i] = 0;
fTRDLabel = 0;
fTRDQuality = -1;
fTRDntracklets = 0;
if(fTRDnSlices)
delete[] fTRDslices;
fTRDslices = 0;
fTRDnSlices = 0;
fTRDBudget = -1;
fHMPIDchi2 = 0;
fHMPIDqn = 0;
fHMPIDcluIdx = -1;
fHMPIDsignal = 0;
for (Int_t i=0;i<AliPID::kSPECIES;i++) fHMPIDr[i] = 0;
fHMPIDtrkTheta = 0;
fHMPIDtrkPhi = 0;
fHMPIDtrkX = 0;
fHMPIDtrkY = 0;
fHMPIDmipX = fCacheNCrossedRows;
fHMPIDmipY = fCacheChi2TPCConstrainedVsGlobal;
}
};
AliEsdMiniTrack *newtrack = new AliEsdMiniTrack(*track);
newtrack->MakeMiniESDtrack();
if (track->GetEMCALcluster()==-123) {
newtrack->SetEMCALcluster(track->GetEMCALcluster());
newtrack->SetTRDQuality(track->GetTRDQuality());
newtrack->SetTRDBudget(track->GetTRDBudget());
}
track = newtrack;
}
fEvent->AddTrack(track);
++nacc;
}
if (fCuts)
AliInfo(Form("Selected %d out of %d \n", nacc, Ntracks));
}
fTree->Fill();
}
//_________________________________________________________________________________________________
void AliEsdSkimTask::UserCreateOutputObjects()
{
// Create output objects.
fTree = new TTree("esdTree", "Tree with skimmed ESD objects");
fEvent = new AliESDEvent;
fEvent->AddObject(new AliESDHeader());
fEvent->AddObject(new AliESDRun());
if (fDoZDC)
fEvent->AddObject(new AliESDZDC());
if (fDoV0)
fEvent->AddObject(new AliESDVZERO());
if (fDoT0)
fEvent->AddObject(new AliESDTZERO());
if (fDoTPCv) {
AliESDVertex *tpcv = new AliESDVertex();
tpcv->SetName("TPCVertex");
fEvent->AddObject(tpcv);
}
if (fDoSPDv) {
AliESDVertex *spdv = new AliESDVertex();
spdv->SetName("SPDVertex");
fEvent->AddObject(spdv);
}
if (fDoPriv) {
AliESDVertex *priv = new AliESDVertex();
priv->SetName("PrimaryVertex");
fEvent->AddObject(priv);
}
if (fDoEmCs) {
fEvent->AddObject(new AliESDCaloCells("EMCALCells","EMCALCells"));
}
if (fDoPCs) {
fEvent->AddObject(new AliESDCaloCells("PHOSCells","PHOSCells"));
}
if (fDoEmT) {
AliESDCaloTrigger *etrig = new AliESDCaloTrigger;
etrig->SetName("EMCALTrigger");
fEvent->AddObject(etrig);
}
if (fDoPT) {
AliESDCaloTrigger *ptrig = new AliESDCaloTrigger;
ptrig->SetName("PHOSTrigger");
fEvent->AddObject(ptrig);
}
if (fDoMult) {
fEvent->AddObject(new AliMultiplicity());
}
if (fDoPileup) {
TClonesArray *arr1 = new TClonesArray("AliESDVertex",0);
arr1->SetName("SPDPileupVertices");
fEvent->AddObject(arr1);
TClonesArray *arr2 = new TClonesArray("AliESDVertex",0);
arr2->SetName("TPCPileupVertices");
fEvent->AddObject(arr2);
}
if (fDoTof) {
fEvent->AddObject(new AliTOFHeader());
}
if (fDoClus) {
TClonesArray *arr = new TClonesArray("AliESDCaloCluster",0);
arr->SetName("CaloClusters");
fEvent->AddObject(arr);
}
TObjArray *namearr = fEmcNames.Tokenize(";");
if (namearr) {
for (Int_t i=0; i<namearr->GetEntries(); ++i) {
TString cname(namearr->At(i)->GetName());
if (cname.Length()<=0)
continue;
TClonesArray *arr = new TClonesArray("AliESDCaloCluster",0);
arr->SetName(cname);
fEvent->AddObject(arr);
}
delete namearr;
}
if (fDoTracks) {
TClonesArray *arr = new TClonesArray("AliESDtrack",0);
arr->SetName("Tracks");
fEvent->AddObject(arr);
}
fEvent->GetStdContent();
fEvent->WriteToTree(fTree);
fTree->GetUserInfo()->Add(fEvent);
TFile *file = OpenFile(1);
fTree->SetDirectory(file);
fTree->SetAutoFlush(-1024*1024*1024);
fTree->SetAutoSave(-1024*1024*1024);
PostData(1,fTree);
}
<|endoftext|>
|
<commit_before>#ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_
#define MRR_POSIX_LIB_SHARED_MEM_HXX_
#include <sys/shm.h>
#include <sys/stat.h>
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TODO:
//
// Break this into 3 partial specializations:
//
// Single Value:
//
// template<typename T>
// struct shared_memory<T,1>;
//
//
// String:
//
// template <unsigned N>
// struct shared_memory<char,N>;
//
//
// Array:
//
// template <typename T, unsigned N>
// struct shared_memory<T,N>;
//
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
namespace mrr {
namespace posix {
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size = 1>
struct shared_memory
{
using value_type = T;
using stripped_ptr_type = typename std::remove_pointer<value_type>::type;
using flag_type = int;
shared_memory(int flags)
: segment_id_(shmget(IPC_PRIVATE, sizeof(T)*Size, flags)),
shared_mem_(static_cast<value_type*>(shmat(segment_id_, NULL, 0)))
{
}
shared_memory()
: segment_id_(-1), shared_mem_(nullptr)
{
}
shared_memory(shared_memory const& shm)
: segment_id_(shm.segment_id_), shared_mem_(shm.shared_mem_)
{
}
int segment_id() const
{
return segment_id_;
}
void attach(int segment_id)
{
segment_id_ = segment_id;
shared_mem_ = static_cast<value_type*>(shmat(segment_id_, NULL, 0));
}
void clear()
{
shmdt(shared_mem_);
}
void release()
{
shmctl(segment_id_, IPC_RMID, NULL);
}
~shared_memory()
{
release();
}
shared_memory& operator =(value_type const& val)
{
*shared_mem_ = val;
return *this;
}
// For char[]
shared_memory& operator =(value_type const * const& str)
{
sprintf(shared_mem_, str);
return *this;
}
value_type* operator&()
{
return shared_mem_;
}
std::ostream& print(std::ostream& os) const
{
if(Size > 1 && std::is_same<value_type,char>::value)
os << shared_mem_;
else
os << *shared_mem_;
return os;
}
value_type& operator*()
{
return *shared_mem_;
}
private:
int segment_id_;
value_type* shared_mem_;
}; // struct shared_memory
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
} // namespace posix
} // namespace mrr
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size>
std::ostream& operator <<(std::ostream& os, mrr::posix::shared_memory<T,Size> const& mem)
{
return mem.print(os);
}
#endif // #ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_
<commit_msg>Moved core functionality of shared memory to shared_memory_base<T,N><commit_after>#ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_
#define MRR_POSIX_LIB_SHARED_MEM_HXX_
#include <sys/shm.h>
#include <sys/stat.h>
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// TODO:
//
// Break this into 3 partial specializations:
//
// Single Value:
//
// template<typename T>
// struct shared_memory<T,1>;
//
//
// String:
//
// template <unsigned N>
// struct shared_memory<char,N>;
//
//
// Array:
//
// template <typename T, unsigned N>
// struct shared_memory<T,N>;
//
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
namespace mrr {
namespace posix {
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size>
struct shared_memory;
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size>
struct shared_memory_base
{
using value_type = T;
using flag_type = int;
private:
friend class shared_memory<T,Size>;
protected:
shared_memory_base(int flags)
: segment_id_(shmget(IPC_PRIVATE, sizeof(T)*Size, flags)),
shared_mem_(static_cast<value_type*>(shmat(segment_id_, NULL, 0)))
{
}
shared_memory_base()
: segment_id_(-1), shared_mem_(nullptr)
{
}
public:
int segment_id() const
{
return segment_id_;
}
void attach(int segment_id)
{
segment_id_ = segment_id;
shared_mem_ = static_cast<value_type*>(shmat(segment_id_, NULL, 0));
}
void clear()
{
shmdt(shared_mem_);
}
void release()
{
shmctl(segment_id_, IPC_RMID, NULL);
}
~shared_memory_base()
{
release();
}
protected:
int segment_id_;
value_type* shared_mem_;
}; // struct shared_memory base
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size = 1>
struct shared_memory : shared_memory_base<T,Size>
{
using base_type = shared_memory_base<T,Size>;
using value_type = typename base_type::value_type;
using flag_type = typename base_type::flag_type;
shared_memory(int flags)
: base_type(flags)
{
}
shared_memory()
: base_type()
{
}
shared_memory& operator =(value_type const& val)
{
*base_type::shared_mem_ = val;
return *this;
}
// For char[]
shared_memory& operator =(value_type const * const& str)
{
sprintf(base_type::shared_mem_, str);
return *this;
}
value_type* operator&()
{
return base_type::shared_mem_;
}
std::ostream& print(std::ostream& os) const
{
if(Size > 1 && std::is_same<value_type,char>::value)
os << base_type::shared_mem_;
else
os << *base_type::shared_mem_;
return os;
}
value_type& operator*()
{
return *base_type::shared_mem_;
}
}; // struct shared_memory
//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
} // namespace posix
} // namespace mrr
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
template <typename T, unsigned Size>
std::ostream& operator <<(std::ostream& os, mrr::posix::shared_memory<T,Size> const& mem)
{
return mem.print(os);
}
#endif // #ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/lookup_table_op.h"
#include <memory>
#include "paddle/fluid/framework/no_need_buffer_vars_inference.h"
#include "paddle/fluid/framework/var_type_inference.h"
namespace paddle {
namespace operators {
class LookupTableOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("W"), "Input", "W", "LookupTable");
OP_INOUT_CHECK(ctx->HasInput("Ids"), "Input", "Ids", "LookupTable");
OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "LookupTable");
auto table_dims = ctx->GetInputDim("W");
auto ids_dims = ctx->GetInputDim("Ids");
int ids_rank = ids_dims.size();
VLOG(5) << "ids rank is " << ids_rank << std::endl;
PADDLE_ENFORCE_EQ(
table_dims.size(), 2,
platform::errors::InvalidArgument(
"ShapeError: The dimensions of the 'lookup table' must be 2. "
"But received lookup table's dimensions = %d, "
"lookup table's shape = [%s].",
table_dims.size(), table_dims));
PADDLE_ENFORCE_EQ(
ids_dims[ids_rank - 1], 1,
platform::errors::InvalidArgument(
"ShapeError: The last dimensions of the 'Ids' tensor must be 1. "
"But received Ids's last dimensions = %d, Ids's shape = [%s].",
ids_dims[ids_rank - 1], ids_dims));
auto output_dims =
framework::vectorize(framework::slice_ddim(ids_dims, 0, ids_rank - 1));
output_dims.push_back(table_dims[1]);
ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
if (ctx->GetOutputsVarType("Out")[0] ==
framework::proto::VarType::LOD_TENSOR) {
ctx->ShareLoD("Ids", /*->*/ "Out");
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "W");
return framework::OpKernelType(data_type, ctx.device_context());
}
};
class LookupTableOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("W",
"(Tensor) The input represents embedding tensors, "
"which is a learnable parameter.");
AddInput("Ids",
"An input with type int64 "
"contains the ids to be looked up in W. "
"The last dimension size must be 1.");
AddOutput("Out", "The lookup results, which have the same type as W.");
AddAttr<bool>("is_sparse",
"(boolean, default false) "
"Sparse update.")
.SetDefault(false);
AddAttr<bool>("is_distributed",
"(boolean, default false) distributed lookup table.")
.SetDefault(false);
AddAttr<int64_t>("padding_idx",
"(int64, default -1) "
"If the value is -1, it makes no effect to lookup. "
"Otherwise the given value indicates padding the output "
"with zeros whenever lookup encounters it in Ids.")
.SetDefault(kNoPadding);
// for parameter training config
AddAttr<bool>("remote_prefetch",
"pull sparse params from parameters, this can only be used "
"in distributed training")
.SetDefault(false);
AddAttr<std::string>("entry_config",
"embedding sparse feature entry config, "
" probability entry / counting "
" this can only be used in distributed training"
"entry")
.SetDefault("");
AddAttr<bool>("is_test",
"(bool, default false) Set to true for inference only, false "
"for training.")
.SetDefault(false);
AddAttr<std::string>("entry",
"(std::string, default "
") for entry attribute.")
.SetDefault("none");
AddAttr<std::vector<std::string>>(
"table_names",
"(string vector, the split table names that will be fetched from "
"parameter server)"
"in the order of input variables for mapping")
.SetDefault({});
AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0);
AddAttr<bool>("grad_inplace",
"(boolean, default false) "
"If the grad op reuse the input's variable.")
.SetDefault(false);
AddAttr<std::vector<std::string>>(
"epmap",
"(string vector, default 127.0.0.1:6164)"
"Server endpoints in the order of input variables for mapping")
.SetDefault({});
AddAttr<std::vector<int64_t>>("height_sections",
"Height for each output SelectedRows.")
.SetDefault(std::vector<int64_t>({}));
AddComment(R"DOC(
Lookup Table Operator.
This operator is used to perform lookups on the parameter W,
then concatenated into a dense tensor.
The input Ids can carry the LoD (Level of Details) information,
or not. And the output only shares the LoD information with input Ids.
)DOC");
}
};
DECLARE_NO_NEED_BUFFER_VARS_INFERER(LookupTableGradOpNoBufferVarsInferer, "W");
template <typename T>
class LookupTableGradOpMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("lookup_table_grad");
op->SetInput("W", this->Input("W"));
op->SetInput("Ids", this->Input("Ids"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("W"), this->InputGrad("W"));
op->SetAttrMap(this->Attrs());
}
};
class LookupTableOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
auto table_dims = ctx->GetInputDim("W");
ctx->SetOutputDim(framework::GradVarName("W"), table_dims);
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out"));
return framework::OpKernelType(data_type, ctx.device_context());
}
};
class LookupTableOpGradVarTypeInference : public framework::VarTypeInference {
public:
void operator()(framework::InferVarTypeContext* ctx) const override {
auto out_var_name = framework::GradVarName("W");
auto attr = ctx->GetAttr("is_sparse");
bool is_sparse = BOOST_GET(bool, attr);
if (is_sparse) {
VLOG(3) << "lookup_table_grad op " << framework::GradVarName("W")
<< " is set to SelectedRows";
ctx->SetOutputType(out_var_name,
framework::proto::VarType::SELECTED_ROWS);
} else {
VLOG(3) << "lookup_table_grad op " << framework::GradVarName("W")
<< " is set to LoDTensor";
ctx->SetOutputType(out_var_name, framework::proto::VarType::LOD_TENSOR);
}
ctx->SetOutputDataType(out_var_name, ctx->GetInputDataType("W"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(lookup_table, ops::LookupTableOp, ops::LookupTableOpMaker,
ops::LookupTableGradOpMaker<paddle::framework::OpDesc>,
ops::LookupTableGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(lookup_table_grad, ops::LookupTableOpGrad,
ops::LookupTableGradOpNoBufferVarsInferer,
ops::LookupTableOpGradVarTypeInference);
REGISTER_OP_CPU_KERNEL(lookup_table, ops::LookupTableKernel<float>,
ops::LookupTableKernel<double>,
ops::LookupTableKernel<int8_t>);
REGISTER_OP_CPU_KERNEL(lookup_table_grad, ops::LookupTableGradKernel<float>,
ops::LookupTableGradKernel<double>);
<commit_msg>for inference checkpoint (#30081)<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/lookup_table_op.h"
#include <memory>
#include "paddle/fluid/framework/no_need_buffer_vars_inference.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/framework/var_type_inference.h"
namespace paddle {
namespace operators {
class LookupTableOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
OP_INOUT_CHECK(ctx->HasInput("W"), "Input", "W", "LookupTable");
OP_INOUT_CHECK(ctx->HasInput("Ids"), "Input", "Ids", "LookupTable");
OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "LookupTable");
auto table_dims = ctx->GetInputDim("W");
auto ids_dims = ctx->GetInputDim("Ids");
int ids_rank = ids_dims.size();
VLOG(5) << "ids rank is " << ids_rank << std::endl;
PADDLE_ENFORCE_EQ(
table_dims.size(), 2,
platform::errors::InvalidArgument(
"ShapeError: The dimensions of the 'lookup table' must be 2. "
"But received lookup table's dimensions = %d, "
"lookup table's shape = [%s].",
table_dims.size(), table_dims));
PADDLE_ENFORCE_EQ(
ids_dims[ids_rank - 1], 1,
platform::errors::InvalidArgument(
"ShapeError: The last dimensions of the 'Ids' tensor must be 1. "
"But received Ids's last dimensions = %d, Ids's shape = [%s].",
ids_dims[ids_rank - 1], ids_dims));
auto output_dims =
framework::vectorize(framework::slice_ddim(ids_dims, 0, ids_rank - 1));
output_dims.push_back(table_dims[1]);
ctx->SetOutputDim("Out", framework::make_ddim(output_dims));
if (ctx->GetOutputsVarType("Out")[0] ==
framework::proto::VarType::LOD_TENSOR) {
ctx->ShareLoD("Ids", /*->*/ "Out");
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "W");
return framework::OpKernelType(data_type, ctx.device_context());
}
};
class LookupTableOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("W",
"(Tensor) The input represents embedding tensors, "
"which is a learnable parameter.");
AddInput("Ids",
"An input with type int64 "
"contains the ids to be looked up in W. "
"The last dimension size must be 1.");
AddOutput("Out", "The lookup results, which have the same type as W.");
AddAttr<bool>("is_sparse",
"(boolean, default false) "
"Sparse update.")
.SetDefault(false);
AddAttr<bool>("is_distributed",
"(boolean, default false) distributed lookup table.")
.SetDefault(false);
AddAttr<int64_t>("padding_idx",
"(int64, default -1) "
"If the value is -1, it makes no effect to lookup. "
"Otherwise the given value indicates padding the output "
"with zeros whenever lookup encounters it in Ids.")
.SetDefault(kNoPadding);
// for parameter training config
AddAttr<bool>("remote_prefetch",
"pull sparse params from parameters, this can only be used "
"in distributed training")
.SetDefault(false);
AddAttr<std::string>("entry_config",
"embedding sparse feature entry config, "
" probability entry / counting "
" this can only be used in distributed training"
"entry")
.SetDefault("");
AddAttr<bool>("is_test",
"(bool, default false) Set to true for inference only, false "
"for training.")
.SetDefault(false);
AddAttr<std::string>("entry",
"(std::string, default "
") for entry attribute.")
.SetDefault("none");
AddAttr<std::vector<std::string>>(
"table_names",
"(string vector, the split table names that will be fetched from "
"parameter server)"
"in the order of input variables for mapping")
.SetDefault({});
AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0);
AddAttr<bool>("grad_inplace",
"(boolean, default false) "
"If the grad op reuse the input's variable.")
.SetDefault(false);
AddAttr<std::vector<std::string>>(
"epmap",
"(string vector, default 127.0.0.1:6164)"
"Server endpoints in the order of input variables for mapping")
.SetDefault({});
AddAttr<std::vector<int64_t>>("height_sections",
"Height for each output SelectedRows.")
.SetDefault(std::vector<int64_t>({}));
AddComment(R"DOC(
Lookup Table Operator.
This operator is used to perform lookups on the parameter W,
then concatenated into a dense tensor.
The input Ids can carry the LoD (Level of Details) information,
or not. And the output only shares the LoD information with input Ids.
)DOC");
}
};
DECLARE_NO_NEED_BUFFER_VARS_INFERER(LookupTableGradOpNoBufferVarsInferer, "W");
template <typename T>
class LookupTableGradOpMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("lookup_table_grad");
op->SetInput("W", this->Input("W"));
op->SetInput("Ids", this->Input("Ids"));
op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
op->SetOutput(framework::GradVarName("W"), this->InputGrad("W"));
op->SetAttrMap(this->Attrs());
}
};
class LookupTableOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
auto table_dims = ctx->GetInputDim("W");
ctx->SetOutputDim(framework::GradVarName("W"), table_dims);
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out"));
return framework::OpKernelType(data_type, ctx.device_context());
}
};
class LookupTableOpGradVarTypeInference : public framework::VarTypeInference {
public:
void operator()(framework::InferVarTypeContext* ctx) const override {
auto out_var_name = framework::GradVarName("W");
auto attr = ctx->GetAttr("is_sparse");
bool is_sparse = BOOST_GET(bool, attr);
if (is_sparse) {
VLOG(3) << "lookup_table_grad op " << framework::GradVarName("W")
<< " is set to SelectedRows";
ctx->SetOutputType(out_var_name,
framework::proto::VarType::SELECTED_ROWS);
} else {
VLOG(3) << "lookup_table_grad op " << framework::GradVarName("W")
<< " is set to LoDTensor";
ctx->SetOutputType(out_var_name, framework::proto::VarType::LOD_TENSOR);
}
ctx->SetOutputDataType(out_var_name, ctx->GetInputDataType("W"));
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(lookup_table, ops::LookupTableOp, ops::LookupTableOpMaker,
ops::LookupTableGradOpMaker<paddle::framework::OpDesc>,
ops::LookupTableGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(lookup_table_grad, ops::LookupTableOpGrad,
ops::LookupTableGradOpNoBufferVarsInferer,
ops::LookupTableOpGradVarTypeInference);
REGISTER_OP_CPU_KERNEL(lookup_table, ops::LookupTableKernel<float>,
ops::LookupTableKernel<double>,
ops::LookupTableKernel<int8_t>);
REGISTER_OP_CPU_KERNEL(lookup_table_grad, ops::LookupTableGradKernel<float>,
ops::LookupTableGradKernel<double>);
/* ========================== register checkpoint ===========================*/
REGISTER_OP_VERSION(lookup_table)
.AddCheckpoint(
R"ROC(
Upgrade lookup_table add 1 attribute [entry_config].
)ROC",
paddle::framework::compatible::OpVersionDesc().NewAttr(
"entry_config",
"(std::string) embedding sparse feature entry config.", ""));
/* ========================================================================== */
<|endoftext|>
|
<commit_before>//===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
//
// This file implements program code generation debugging support.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "SystemUtils.h"
#include "ListReducer.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalValue.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/Statistic.h"
#include "Support/StringExtras.h"
#include <algorithm>
#include <set>
class ReduceMisCodegenFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix) {
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepSuffix;
return NoFailure;
}
bool TestFuncs(const std::vector<Function*> &CodegenTest,
bool KeepFiles = false);
void DisambiguateGlobalSymbols(Module *M);
};
bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
bool KeepFiles)
{
DEBUG(std::cerr << "Test functions are:\n");
for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();
I != E; ++I)
DEBUG(std::cerr << "\t" << (*I)->getName() << "\n");
// Clone the module for the two halves of the program we want.
Module *SafeModule = CloneModule(BD.Program);
// Make sure functions & globals are all external so that linkage
// between the two modules will work.
for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
I->setLinkage(GlobalValue::ExternalLinkage);
for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
I->setLinkage(GlobalValue::ExternalLinkage);
DisambiguateGlobalSymbols(SafeModule);
Module *TestModule = CloneModule(SafeModule);
// Make sure global initializers exist only in the safe module (CBE->.so)
for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
I->setInitializer(0); // Delete the initializer to make it external
// Remove the Test functions from the Safe module
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(TNOF && "Function doesn't exist in module!");
DeleteFunctionBody(TNOF); // Function is now external in this module!
}
// Remove the Safe functions from the Test module
for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
bool funcFound = false;
for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
F != Fe; ++F)
if (I->getName() == (*F)->getName()) funcFound = true;
if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
DeleteFunctionBody(I);
}
// This is only applicable if we are debugging the JIT:
// Find all external functions in the Safe modules that are actually used
// (called or taken address of), and make them call the JIT wrapper instead
if (BD.isExecutingJIT()) {
// Must delete `main' from Safe module if it has it
for (Module::iterator I=SafeModule->begin(), E=SafeModule->end();I!=E;++I)
if (I->getName() == "main") DeleteFunctionBody(I);
// Add an external function "getPointerToNamedFunction" that JIT provides
// Prototype: void *getPointerToNamedFunction(const char* Name)
std::vector<const Type*> Params;
Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
Params, false /* isVarArg */);
const std::string ResolverFunctionName = "getPointerToNamedFunction";
Function *resolverFunc = new Function(resolverTy,
GlobalValue::ExternalLinkage,
ResolverFunctionName,
SafeModule);
// Use the function we just added to get addresses of functions we need
// Iterate over the global declarations in the Safe module
for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
if (F->isExternal() && F->use_begin() != F->use_end() &&
F->getName() != ResolverFunctionName) {
// If it has a non-zero use list,
// 1. Add a string constant with its name to the global file
// The correct type is `const [ NUM x sbyte ]' where NUM is length of
// function name + 1
const std::string &Name = F->getName();
GlobalVariable *funcName =
new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
true /* isConstant */,
GlobalValue::InternalLinkage,
ConstantArray::get(Name),
Name + "_name",
SafeModule);
// 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
// sbyte* so it matches the signature of the resolver function.
Constant *Zero = Constant::getNullValue(Type::LongTy);
std::vector<Constant*> GEPargs;
GEPargs.push_back(Zero);
GEPargs.push_back(Zero);
// 3. Replace all uses of `func' with calls to resolver by:
// (a) Iterating through the list of uses of this function
// (b) Insert a cast instruction in front of each use
// (c) Replace use of old call with new call
// Insert code at the beginning of the function
for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {
if (Instruction* Inst = dyn_cast<Instruction>(*i)) {
// GetElementPtr *funcName, ulong 0, ulong 0
Value *GEP =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
GEPargs);
std::vector<Value*> ResolverArgs;
ResolverArgs.push_back(GEP);
// call resolver(GetElementPtr...)
CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
"resolver", Inst);
// cast the result from the resolver to correctly-typed function
CastInst *castResolver =
new CastInst(resolve, PointerType::get(F->getFunctionType()),
"", Inst);
// actually use the resolved function
Inst->replaceUsesOfWith(F, castResolver);
//BasicBlock::iterator ii(Inst);
//ReplaceInstWithValue(Inst->getParent()->getInstList(),
// ii, ResolverResult);
}
}
}
}
}
DEBUG(std::cerr << "Safe module:\n");
for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
if (!I->isExternal()) DEBUG(std::cerr << "\t" << I->getName() << "\n");
for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
if (!I->isExternal()) DEBUG(std::cerr << "\t" << I->getName() << "\n");
DEBUG(std::cerr << "Test module:\n");
for (Module::iterator I =TestModule->begin(),E = TestModule->end(); I!=E;++I)
if (!I->isExternal()) DEBUG(std::cerr << "\t" << I->getName() << "\n");
for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
if (!I->isExternal()) DEBUG(std::cerr << "\t" << I->getName() << "\n");
// Write out the bytecode to be sent to CBE
std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
if (verifyModule(*SafeModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Make a shared library
std::string SharedObject;
BD.compileSharedObject(SafeModuleBC, SharedObject);
// Remove all functions from the Test module EXCEPT for the ones specified in
// Funcs. We know which ones these are because they are non-external in
// ToOptimize, but external in ToNotOptimize.
//
for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
if (!I->isExternal()) {
Function *TNOF = SafeModule->getFunction(I->getName(),
I->getFunctionType());
assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
if (!TNOF->isExternal())
DeleteFunctionBody(I);
}
std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
if (verifyModule(*TestModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
delete SafeModule;
delete TestModule;
// Run the code generator on the `Test' code, loading the shared library.
// The function returns whether or not the new output differs from reference.
int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
if (KeepFiles) {
std::cout << "You can reproduce the problem with the command line: \n"
<< "lli (or llc) -load " << SharedObject << " " << TestModuleBC
<< "\n";
} else {
removeFile(TestModuleBC);
removeFile(SafeModuleBC);
removeFile(SharedObject);
}
return Result;
}
namespace {
struct Disambiguator {
std::set<std::string> SymbolNames;
std::set<GlobalValue*> Symbols;
uint64_t uniqueCounter;
bool externalOnly;
public:
Disambiguator() : uniqueCounter(0), externalOnly(true) {}
void setExternalOnly(bool value) { externalOnly = value; }
void add(GlobalValue &V) {
// If we're only processing externals and this isn't external, bail
if (externalOnly && !V.isExternal()) return;
// If we're already processed this symbol, don't add it again
if (Symbols.count(&V) != 0) return;
std::string SymName = V.getName();
// If the symbol starts with a '.', replace it with 'x'
// This solves the problem of not being able to find symbols in an .so
// file when those symbol names start with '.'
if (SymName[0] == '.') {
SymName[0] = 'x';
V.setName(SymName);
}
if (SymbolNames.count(SymName) == 0) {
DEBUG(std::cerr << "Disambiguator: adding " << SymName
<< ", no conflicts.\n");
SymbolNames.insert(SymName);
} else {
// Mangle name before adding
std::string newName;
do {
newName = SymName + "_" + utostr(uniqueCounter);
if (SymbolNames.count(newName) == 0) break;
else ++uniqueCounter;
} while (1);
//while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
<< ", adding: " << newName << "\n");
V.setName(newName);
SymbolNames.insert(newName);
}
Symbols.insert(&V);
}
};
}
void ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {
// First, try not to cause collisions by minimizing chances of renaming an
// already-external symbol, so take in external globals and functions as-is.
Disambiguator D;
DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
// Now just rename functions and globals as necessary, keeping what's already
// in the set unique.
D.setExternalOnly(false);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
}
bool BugDriver::debugCodeGenerator() {
// See if we can pin down which functions are being miscompiled...
//First, build a list of all of the non-external functions in the program.
std::vector<Function*> MisCodegenFunctions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
MisCodegenFunctions.push_back(I);
// If we are executing the JIT, we *must* keep the function `main' in the
// module that is passed in, and not the shared library. However, we still
// want to be able to debug the `main' function alone. Thus, we create a new
// function `main' which just calls the old one.
if (isExecutingJIT()) {
// Get the `main' function
Function *oldMain = Program->getNamedFunction("main");
// Rename it
oldMain->setName("old_main");
// Create a NEW `main' function with same type
Function *newMain = new Function(oldMain->getFunctionType(),
GlobalValue::InternalLinkage,
"main", Program);
// Call the old main function and return its result
BasicBlock *BB = new BasicBlock("entry", newMain);
std::vector<Value*> args;
for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)
args.push_back(I);
CallInst *call = new CallInst(oldMain, args);
BB->getInstList().push_back(call);
// if the type of old function wasn't void, return value of call
ReturnInst *ret;
if (oldMain->getReturnType() != Type::VoidTy) {
ret = new ReturnInst(call);
} else {
ret = new ReturnInst();
}
// Add the return instruction to the BasicBlock
BB->getInstList().push_back(ret);
}
// Do the reduction...
ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);
std::cout << "\n*** The following functions are being miscompiled: ";
PrintFunctionList(MisCodegenFunctions);
std::cout << "\n";
// Output a bunch of bytecode files for the user...
ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
return false;
}
<commit_msg>Implemented cleanups as suggested by Chris: * Use Module::getNamedFunction() to delete "main" instead of using a loop * Compare function pointers instead of function names to determine equivalence * Simplified creation of a 2-element vector containing zeroes * Manually performed LICM on code * Added an abort() in case a function we're considering occurs in something that is not an instruction * Use DEBUG() around code sections instead of just in a statement in a loop, because GCC's DCE may not be good enough to completely remove it in a release build * Print out a command that can be directly copied-and-pasted to re-execute * Instead of just checking if a symbol begins with a dot and fixing it accordingly, use Mangler and fix all the problems (invalid chars in C symbol names) entirely * The new `main' function has external linkage<commit_after>//===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
//
// This file implements program code generation debugging support.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "SystemUtils.h"
#include "ListReducer.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalValue.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/Statistic.h"
#include "Support/StringExtras.h"
#include <algorithm>
#include <set>
class ReduceMisCodegenFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix) {
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepSuffix;
return NoFailure;
}
bool TestFuncs(const std::vector<Function*> &CodegenTest,
bool KeepFiles = false);
void DisambiguateGlobalSymbols(Module *M);
};
bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
bool KeepFiles)
{
DEBUG(std::cerr << "Test functions are:\n");
for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();
I != E; ++I)
DEBUG(std::cerr << "\t" << (*I)->getName() << "\n");
// Clone the module for the two halves of the program we want.
Module *SafeModule = CloneModule(BD.Program);
// Make sure functions & globals are all external so that linkage
// between the two modules will work.
for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)
I->setLinkage(GlobalValue::ExternalLinkage);
for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)
I->setLinkage(GlobalValue::ExternalLinkage);
DisambiguateGlobalSymbols(SafeModule);
Module *TestModule = CloneModule(SafeModule);
// Make sure global initializers exist only in the safe module (CBE->.so)
for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)
I->setInitializer(0); // Delete the initializer to make it external
// Remove the Test functions from the Safe module
for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),
Funcs[i]->getFunctionType());
assert(TNOF && "Function doesn't exist in module!");
DeleteFunctionBody(TNOF); // Function is now external in this module!
}
// Remove the Safe functions from the Test module
for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {
bool funcFound = false;
for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();
F != Fe; ++F)
if (I->getName() == (*F)->getName()) funcFound = true;
if (!funcFound && !(BD.isExecutingJIT() && I->getName() == "main"))
DeleteFunctionBody(I);
}
// This is only applicable if we are debugging the JIT:
// Find all external functions in the Safe modules that are actually used
// (called or taken address of), and make them call the JIT wrapper instead
if (BD.isExecutingJIT()) {
// Must delete `main' from Safe module if it has it
Function *safeMain = SafeModule->getNamedFunction("main");
DeleteFunctionBody(safeMain);
// Add an external function "getPointerToNamedFunction" that JIT provides
// Prototype: void *getPointerToNamedFunction(const char* Name)
std::vector<const Type*> Params;
Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
Params, false /* isVarArg */);
Function *resolverFunc = new Function(resolverTy,
GlobalValue::ExternalLinkage,
"getPointerToNamedFunction",
SafeModule);
// Use the function we just added to get addresses of functions we need
// Iterate over the global declarations in the Safe module
for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
if (F->isExternal() && !F->use_empty() && &(*F) != resolverFunc) {
// If it has a non-zero use list,
// 1. Add a string constant with its name to the global file
// The correct type is `const [ NUM x sbyte ]' where NUM is length of
// function name + 1
const std::string &Name = F->getName();
GlobalVariable *funcName =
new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
true /* isConstant */,
GlobalValue::InternalLinkage,
ConstantArray::get(Name),
Name + "_name",
SafeModule);
// 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
// sbyte* so it matches the signature of the resolver function.
std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));
// 3. Replace all uses of `func' with calls to resolver by:
// (a) Iterating through the list of uses of this function
// (b) Insert a cast instruction in front of each use
// (c) Replace use of old call with new call
// GetElementPtr *funcName, ulong 0, ulong 0
Value *GEP =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
GEPargs);
std::vector<Value*> ResolverArgs;
ResolverArgs.push_back(GEP);
// Insert code at the beginning of the function
for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {
if (Instruction* Inst = dyn_cast<Instruction>(*i)) {
// call resolver(GetElementPtr...)
CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
"resolver", Inst);
// cast the result from the resolver to correctly-typed function
CastInst *castResolver =
new CastInst(resolve, PointerType::get(F->getFunctionType()),
"", Inst);
// actually use the resolved function
Inst->replaceUsesOfWith(F, castResolver);
} else {
// FIXME: need to take care of cases where a function is used that
// is not an instruction, e.g. global variable initializer...
std::cerr << "Non-instruction is using an external function!\n";
abort();
}
}
}
}
}
DEBUG(std::cerr << "Safe module:\n";
typedef Module::iterator MI;
typedef Module::giterator MGI;
for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
std::cerr << "Test module:\n";
for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
);
// Write out the bytecode to be sent to CBE
std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
if (verifyModule(*SafeModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Make a shared library
std::string SharedObject;
BD.compileSharedObject(SafeModuleBC, SharedObject);
// Remove all functions from the Test module EXCEPT for the ones specified in
// Funcs. We know which ones these are because they are non-external in
// ToOptimize, but external in ToNotOptimize.
//
for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
if (!I->isExternal()) {
Function *TNOF = SafeModule->getFunction(I->getName(),
I->getFunctionType());
assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
if (!TNOF->isExternal())
DeleteFunctionBody(I);
}
std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
if (verifyModule(*TestModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
delete SafeModule;
delete TestModule;
// Run the code generator on the `Test' code, loading the shared library.
// The function returns whether or not the new output differs from reference.
int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
if (KeepFiles) {
std::cout << "You can reproduce the problem with the command line: \n"
<< (BD.isExecutingJIT() ? "lli" : "llc")
<< " -load " << SharedObject << " " << TestModuleBC
<< "\n";
} else {
removeFile(TestModuleBC);
removeFile(SafeModuleBC);
removeFile(SharedObject);
}
return Result;
}
namespace {
struct Disambiguator {
std::set<std::string> SymbolNames;
std::set<GlobalValue*> Symbols;
uint64_t uniqueCounter;
bool externalOnly;
public:
Disambiguator() : uniqueCounter(0), externalOnly(true) {}
void setExternalOnly(bool value) { externalOnly = value; }
void add(GlobalValue &V) {
// If we're only processing externals and this isn't external, bail
if (externalOnly && !V.isExternal()) return;
// If we're already processed this symbol, don't add it again
if (Symbols.count(&V) != 0) return;
std::string SymName = V.getName();
// Use the Mangler facility to make symbol names that will be valid in
// shared objects.
SymName = Mangler::makeNameProper(SymName);
V.setName(SymName);
if (SymbolNames.count(SymName) == 0) {
DEBUG(std::cerr << "Disambiguator: adding " << SymName
<< ", no conflicts.\n");
SymbolNames.insert(SymName);
} else {
// Mangle name before adding
std::string newName;
do {
newName = SymName + "_" + utostr(uniqueCounter);
if (SymbolNames.count(newName) == 0) break;
else ++uniqueCounter;
} while (1);
//while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
<< ", adding: " << newName << "\n");
V.setName(newName);
SymbolNames.insert(newName);
}
Symbols.insert(&V);
}
};
}
void ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {
// First, try not to cause collisions by minimizing chances of renaming an
// already-external symbol, so take in external globals and functions as-is.
Disambiguator D;
DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
// Now just rename functions and globals as necessary, keeping what's already
// in the set unique.
D.setExternalOnly(false);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
}
bool BugDriver::debugCodeGenerator() {
// See if we can pin down which functions are being miscompiled...
//First, build a list of all of the non-external functions in the program.
std::vector<Function*> MisCodegenFunctions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
MisCodegenFunctions.push_back(I);
// If we are executing the JIT, we *must* keep the function `main' in the
// module that is passed in, and not the shared library. However, we still
// want to be able to debug the `main' function alone. Thus, we create a new
// function `main' which just calls the old one.
if (isExecutingJIT()) {
// Get the `main' function
Function *oldMain = Program->getNamedFunction("main");
// Rename it
oldMain->setName("old_main");
// Create a NEW `main' function with same type
Function *newMain = new Function(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
"main", Program);
// Call the old main function and return its result
BasicBlock *BB = new BasicBlock("entry", newMain);
std::vector<Value*> args;
for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)
args.push_back(I);
CallInst *call = new CallInst(oldMain, args);
BB->getInstList().push_back(call);
// if the type of old function wasn't void, return value of call
ReturnInst *ret;
if (oldMain->getReturnType() != Type::VoidTy) {
ret = new ReturnInst(call);
} else {
ret = new ReturnInst();
}
// Add the return instruction to the BasicBlock
BB->getInstList().push_back(ret);
}
// Do the reduction...
ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);
std::cout << "\n*** The following functions are being miscompiled: ";
PrintFunctionList(MisCodegenFunctions);
std::cout << "\n";
// Output a bunch of bytecode files for the user...
ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
return false;
}
<|endoftext|>
|
<commit_before>#include "vtkMultiProcessController.h"
#include "vtkDoubleArray.h"
#include "vtkCharArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkOutputPort.h"
#include "vtkDebugLeaks.h"
#include "vtkActor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkInputPort.h"
#include "vtkPolyDataMapper.h"
#include "vtkParallelFactory.h"
#include "vtkRTAnalyticSource.h"
#include "vtkContourFilter.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkDebugLeaks.h"
#include "vtkRegressionTestImage.h"
static const int scMsgLength = 10;
struct GenericCommunicatorArgs_tmp
{
int* retVal;
int argc;
char** argv;
};
static void UpdateXFreq(void* arg)
{
vtkRTAnalyticSource* id = reinterpret_cast<vtkRTAnalyticSource*>(arg);
id->SetXFreq(id->GetXFreq()+20);
}
static void DeleteAnArg(void*)
{
return;
}
void Process1(vtkMultiProcessController *contr, void *arg)
{
vtkCommunicator* comm = contr->GetCommunicator();
int i;
// Test receiving all supported types of arrays
vtkIntArray* ia = vtkIntArray::New();
if (!comm->Receive(ia, 1, 11))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ia->GetNumberOfTuples(); i++)
{
if (ia->GetValue(i) != i)
{
cerr << "Server error: Corrupt integer array." << endl;
}
}
ia->Delete();
vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();
if (!comm->Receive(ula, 1, 22))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ula->GetNumberOfTuples(); i++)
{
if (ula->GetValue(i) != static_cast<unsigned long>(i))
{
cerr << "Server error: Corrupt unsigned long array." << endl;
}
}
ula->Delete();
vtkCharArray* ca = vtkCharArray::New();
if (!comm->Receive(ca, 1, 33))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ca->GetNumberOfTuples(); i++)
{
if (ca->GetValue(i) != static_cast<char>(i))
{
cerr << "Server error: Corrupt char array." << endl;
}
}
ca->Delete();
vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();
if (!comm->Receive(uca, 1, 44))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<uca->GetNumberOfTuples(); i++)
{
if (uca->GetValue(i) != static_cast<unsigned char>(i))
{
cerr << "Server error: Corrupt unsigned char array." << endl;
}
}
uca->Delete();
vtkFloatArray* fa = vtkFloatArray::New();
if (!comm->Receive(fa, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<fa->GetNumberOfTuples(); i++)
{
if (fa->GetValue(i) != static_cast<float>(i))
{
cerr << "Server error: Corrupt float array." << endl;
}
}
fa->Delete();
vtkDoubleArray* da = vtkDoubleArray::New();
if (!comm->Receive(da, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<da->GetNumberOfTuples(); i++)
{
if (da->GetValue(i) != static_cast<double>(i))
{
cerr << "Server error: Corrupt double array." << endl;
}
}
da->Delete();
vtkIdTypeArray* ita = vtkIdTypeArray::New();
if (!comm->Receive(ita, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ita->GetNumberOfTuples(); i++)
{
if (ita->GetValue(i) != static_cast<vtkIdType>(i))
{
cerr << "Server error: Corrupt vtkIdType array." << endl;
}
}
ita->Delete();
vtkOutputPort* op = vtkOutputPort::New();
op->SetController(contr);
op->SetTag(45);
float extent = 20;
vtkRTAnalyticSource* id = vtkRTAnalyticSource::New();
id->SetWholeExtent (-extent, extent, -extent, extent, -extent, extent);
id->SetCenter(0, 0, 0);
id->SetStandardDeviation( 0.5 );
id->SetMaximum( 255.0 );
id->SetXFreq( 60 );
id->SetXMag( 10 );
id->SetYFreq( 30 );
id->SetYMag( 18 );
id->SetZFreq( 40 );
id->SetZMag( 5 );
id->GetOutput()->SetSpacing(2.0/extent,2.0/extent,2.0/extent);
op->SetInput(id->GetOutput());
op->PipelineFlagOn();
op->SetParameterMethod(UpdateXFreq, id);
op->SetParameterMethodArgDelete(DeleteAnArg);
op->WaitForUpdate();
id->Delete();
op->Delete();
}
void Process2(vtkMultiProcessController *contr, void *arg)
{
GenericCommunicatorArgs_tmp* args =
reinterpret_cast<GenericCommunicatorArgs_tmp*>(arg);
vtkCommunicator* comm = contr->GetCommunicator();
int i;
// Test sending all supported types of arrays
int datai[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datai[i] = i;
}
vtkIntArray* ia = vtkIntArray::New();
ia->SetArray(datai, 10, 1);
if (!comm->Send(ia, 0, 11))
{
cerr << "Client error: Error sending data." << endl;
}
ia->Delete();
unsigned long dataul[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
dataul[i] = static_cast<unsigned long>(i);
}
vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();
ula->SetArray(dataul, 10, 1);
if (!comm->Send(ula, 0, 22))
{
cerr << "Client error: Error sending data." << endl;
}
ula->Delete();
char datac[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datac[i] = static_cast<char>(i);
}
vtkCharArray* ca = vtkCharArray::New();
ca->SetArray(datac, 10, 1);
if (!comm->Send(ca, 0, 33))
{
cerr << "Client error: Error sending data." << endl;
}
ca->Delete();
unsigned char datauc[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datauc[i] = static_cast<unsigned char>(i);
}
vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();
uca->SetArray(datauc, 10, 1);
if (!comm->Send(uca, 0, 44))
{
cerr << "Client error: Error sending data." << endl;
}
uca->Delete();
float dataf[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
dataf[i] = static_cast<float>(i);
}
vtkFloatArray* fa = vtkFloatArray::New();
fa->SetArray(dataf, 10, 1);
if (!comm->Send(fa, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
fa->Delete();
double datad[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datad[i] = static_cast<double>(i);
}
vtkDoubleArray* da = vtkDoubleArray::New();
da->SetArray(datad, 10, 1);
if (!comm->Send(da, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
da->Delete();
vtkIdType datait[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datait[i] = static_cast<vtkIdType>(i);
}
vtkIdTypeArray* ita = vtkIdTypeArray::New();
ita->SetArray(datait, 10, 1);
if (!comm->Send(ita, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
ita->Delete();
// Test the ports
vtkInputPort* ip = vtkInputPort::New();
ip->SetController(contr);
ip->SetTag(45);
ip->SetRemoteProcessId(0);
// Get polydata
ip->GetImageDataOutput()->Update();
vtkContourFilter* cf = vtkContourFilter::New();
cf->SetInput(ip->GetImageDataOutput());
cf->SetNumberOfContours(1);
cf->SetValue(0, 220);
vtkPolyDataMapper* pmapper = vtkPolyDataMapper::New();
pmapper->SetInput(cf->GetOutput());
cf->Delete();
vtkActor* pactor = vtkActor::New();
pactor->SetMapper(pmapper);
pmapper->UnRegister(0);
vtkRenderer* ren = vtkRenderer::New();
ren->AddActor(pactor);
pactor->UnRegister(0);
vtkRenderWindow* renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren);
ren->UnRegister(0);
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
iren->Initialize();
renWin->Render();
renWin->Render();
*(args->retVal) =
vtkRegressionTester::Test(args->argc, args->argv, renWin, 10);
if ( *(args->retVal) == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
iren->Delete();
contr->TriggerRMI(0, vtkMultiProcessController::BREAK_RMI_TAG);
ip->Delete();
renWin->Delete();
}
int main(int argc, char** argv)
{
vtkDebugLeaks::PromptUserOff();
vtkMultiProcessController* contr = vtkMultiProcessController::New();
contr->Initialize(&argc, &argv);
vtkParallelFactory* pf = vtkParallelFactory::New();
vtkObjectFactory::RegisterFactory(pf);
pf->Delete();
// This is repeated for the sake of MPI. This one might not
// get called by the parent process, the first one might not
// get called by all others.
vtkDebugLeaks::PromptUserOff();
// When using MPI, the number of processes is determined
// by the external program which launches this application.
// However, when using threads, we need to set it ourselves.
if (contr->IsA("vtkThreadedController"))
{
// Set the number of processes to 2 for this example.
contr->SetNumberOfProcesses(2);
}
// Added for regression test.
// ----------------------------------------------
int retVal;
GenericCommunicatorArgs_tmp args;
args.retVal = &retVal;
args.argc = argc;
args.argv = argv;
// ----------------------------------------------
contr->SetMultipleMethod(0, Process1, 0);
contr->SetMultipleMethod(1, Process2, &args);
contr->MultipleMethodExecute();
contr->Finalize();
contr->Delete();
return !retVal;
}
<commit_msg>Increasing coverage.<commit_after>#include "vtkMultiProcessController.h"
#include "vtkDoubleArray.h"
#include "vtkCharArray.h"
#include "vtkIntArray.h"
#include "vtkUnsignedLongArray.h"
#include "vtkFloatArray.h"
#include "vtkIdTypeArray.h"
#include "vtkOutputPort.h"
#include "vtkDebugLeaks.h"
#include "vtkActor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkInputPort.h"
#include "vtkPolyDataMapper.h"
#include "vtkParallelFactory.h"
#include "vtkRTAnalyticSource.h"
#include "vtkContourFilter.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkDebugLeaks.h"
#include "vtkRegressionTestImage.h"
static const int scMsgLength = 10;
struct GenericCommunicatorArgs_tmp
{
int* retVal;
int argc;
char** argv;
};
static void UpdateXFreq(void* arg)
{
vtkRTAnalyticSource* id = reinterpret_cast<vtkRTAnalyticSource*>(arg);
id->SetXFreq(id->GetXFreq()+20);
}
static void DeleteAnArg(void*)
{
return;
}
void Process1(vtkMultiProcessController *contr, void *arg)
{
vtkCommunicator* comm = contr->GetCommunicator();
int i;
// Test receiving all supported types of arrays
vtkIntArray* ia = vtkIntArray::New();
if (!comm->Receive(ia, 1, 11))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ia->GetNumberOfTuples(); i++)
{
if (ia->GetValue(i) != i)
{
cerr << "Server error: Corrupt integer array." << endl;
}
}
ia->Delete();
vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();
if (!comm->Receive(ula, 1, 22))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ula->GetNumberOfTuples(); i++)
{
if (ula->GetValue(i) != static_cast<unsigned long>(i))
{
cerr << "Server error: Corrupt unsigned long array." << endl;
}
}
ula->Delete();
vtkCharArray* ca = vtkCharArray::New();
if (!comm->Receive(ca, 1, 33))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ca->GetNumberOfTuples(); i++)
{
if (ca->GetValue(i) != static_cast<char>(i))
{
cerr << "Server error: Corrupt char array." << endl;
}
}
ca->Delete();
vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();
if (!comm->Receive(uca, 1, 44))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<uca->GetNumberOfTuples(); i++)
{
if (uca->GetValue(i) != static_cast<unsigned char>(i))
{
cerr << "Server error: Corrupt unsigned char array." << endl;
}
}
uca->Delete();
vtkFloatArray* fa = vtkFloatArray::New();
if (!comm->Receive(fa, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<fa->GetNumberOfTuples(); i++)
{
if (fa->GetValue(i) != static_cast<float>(i))
{
cerr << "Server error: Corrupt float array." << endl;
}
}
fa->Delete();
vtkDoubleArray* da = vtkDoubleArray::New();
if (!comm->Receive(da, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<da->GetNumberOfTuples(); i++)
{
if (da->GetValue(i) != static_cast<double>(i))
{
cerr << "Server error: Corrupt double array." << endl;
}
}
da->Delete();
vtkIdTypeArray* ita = vtkIdTypeArray::New();
if (!comm->Receive(ita, 1, 7))
{
cerr << "Server error: Error receiving data." << endl;
}
for (i=0; i<ita->GetNumberOfTuples(); i++)
{
if (ita->GetValue(i) != static_cast<vtkIdType>(i))
{
cerr << "Server error: Corrupt vtkIdType array." << endl;
}
}
ita->Delete();
vtkOutputPort* op = vtkOutputPort::New();
op->SetController(contr);
op->SetTag(45);
float extent = 20;
vtkRTAnalyticSource* id = vtkRTAnalyticSource::New();
id->SetWholeExtent (-extent, extent, -extent, extent, -extent, extent);
id->SetCenter(0, 0, 0);
id->SetStandardDeviation( 0.5 );
id->SetMaximum( 255.0 );
id->SetXFreq( 60 );
id->SetXMag( 10 );
id->SetYFreq( 30 );
id->SetYMag( 18 );
id->SetZFreq( 40 );
id->SetZMag( 5 );
id->GetOutput()->SetSpacing(2.0/extent,2.0/extent,2.0/extent);
op->SetInput(id->GetOutput());
op->PipelineFlagOn();
op->SetParameterMethod(UpdateXFreq, id);
op->SetParameterMethodArgDelete(DeleteAnArg);
op->WaitForUpdate();
id->Delete();
op->Delete();
}
void Process2(vtkMultiProcessController *contr, void *arg)
{
GenericCommunicatorArgs_tmp* args =
reinterpret_cast<GenericCommunicatorArgs_tmp*>(arg);
vtkCommunicator* comm = contr->GetCommunicator();
int i;
// Test sending all supported types of arrays
int datai[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datai[i] = i;
}
vtkIntArray* ia = vtkIntArray::New();
ia->SetArray(datai, 10, 1);
if (!comm->Send(ia, 0, 11))
{
cerr << "Client error: Error sending data." << endl;
}
ia->Delete();
unsigned long dataul[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
dataul[i] = static_cast<unsigned long>(i);
}
vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();
ula->SetArray(dataul, 10, 1);
if (!comm->Send(ula, 0, 22))
{
cerr << "Client error: Error sending data." << endl;
}
ula->Delete();
char datac[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datac[i] = static_cast<char>(i);
}
vtkCharArray* ca = vtkCharArray::New();
ca->SetArray(datac, 10, 1);
if (!comm->Send(ca, 0, 33))
{
cerr << "Client error: Error sending data." << endl;
}
ca->Delete();
unsigned char datauc[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datauc[i] = static_cast<unsigned char>(i);
}
vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();
uca->SetArray(datauc, 10, 1);
if (!comm->Send(uca, 0, 44))
{
cerr << "Client error: Error sending data." << endl;
}
uca->Delete();
float dataf[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
dataf[i] = static_cast<float>(i);
}
vtkFloatArray* fa = vtkFloatArray::New();
fa->SetArray(dataf, 10, 1);
if (!comm->Send(fa, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
fa->Delete();
double datad[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datad[i] = static_cast<double>(i);
}
vtkDoubleArray* da = vtkDoubleArray::New();
da->SetArray(datad, 10, 1);
if (!comm->Send(da, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
da->Delete();
vtkIdType datait[scMsgLength];
for (i=0; i<scMsgLength; i++)
{
datait[i] = static_cast<vtkIdType>(i);
}
vtkIdTypeArray* ita = vtkIdTypeArray::New();
ita->SetArray(datait, 10, 1);
if (!comm->Send(ita, 0, 7))
{
cerr << "Client error: Error sending data." << endl;
}
ita->Delete();
// Test the ports
vtkInputPort* ip = vtkInputPort::New();
ip->SetController(contr);
ip->SetTag(45);
ip->SetRemoteProcessId(0);
// Get polydata
ip->GetImageDataOutput()->Update();
vtkContourFilter* cf = vtkContourFilter::New();
cf->SetInput(ip->GetImageDataOutput());
cf->SetNumberOfContours(1);
cf->SetValue(0, 220);
vtkPolyDataMapper* pmapper = vtkPolyDataMapper::New();
pmapper->SetInput(cf->GetOutput());
cf->Delete();
vtkActor* pactor = vtkActor::New();
pactor->SetMapper(pmapper);
pmapper->UnRegister(0);
vtkRenderer* ren = vtkRenderer::New();
ren->AddActor(pactor);
pactor->UnRegister(0);
vtkRenderWindow* renWin = vtkRenderWindow::New();
renWin->AddRenderer(ren);
ren->UnRegister(0);
vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
iren->Initialize();
renWin->Render();
renWin->Render();
*(args->retVal) =
vtkRegressionTester::Test(args->argc, args->argv, renWin, 10);
if ( *(args->retVal) == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
iren->Delete();
contr->TriggerRMI(0, vtkMultiProcessController::BREAK_RMI_TAG);
ip->Delete();
renWin->Delete();
}
int main(int argc, char** argv)
{
vtkDebugLeaks::PromptUserOff();
vtkMultiProcessController* contr = vtkMultiProcessController::New();
contr->Initialize(&argc, &argv);
contr->CreateOutputWindow();
vtkParallelFactory* pf = vtkParallelFactory::New();
vtkObjectFactory::RegisterFactory(pf);
pf->Delete();
// This is repeated for the sake of MPI. This one might not
// get called by the parent process, the first one might not
// get called by all others.
vtkDebugLeaks::PromptUserOff();
// When using MPI, the number of processes is determined
// by the external program which launches this application.
// However, when using threads, we need to set it ourselves.
if (contr->IsA("vtkThreadedController"))
{
// Set the number of processes to 2 for this example.
contr->SetNumberOfProcesses(2);
}
// Added for regression test.
// ----------------------------------------------
int retVal;
GenericCommunicatorArgs_tmp args;
args.retVal = &retVal;
args.argc = argc;
args.argv = argv;
// ----------------------------------------------
contr->SetMultipleMethod(0, Process1, 0);
contr->SetMultipleMethod(1, Process2, &args);
contr->MultipleMethodExecute();
contr->Finalize();
contr->Delete();
return !retVal;
}
<|endoftext|>
|
<commit_before>#include <cstring>
#include <deque>
#include <vector>
#include <iostream>
#include <string>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include <v8.h>
#include "MemoryPool.h"
using namespace v8;
/**
* A string whose characters are stored elsewhere.
*
* The argument-free constructor will return a "null string". Basically, it's
* a hack that probably behaves the way you expect. (Its memory address is
* NULL.)
*/
struct SimpleString
{
const char* s;
size_t len;
SimpleString(const char* aS, size_t aLen) : s(aS), len(aLen) {}
SimpleString() : s(NULL), len(0) {}
SimpleString(const SimpleString& rhs) : s(rhs.s), len(rhs.len) {}
inline bool isNull() const { return s == NULL; }
};
struct TSTNode
{
char ch;
TSTNode* left;
TSTNode* eq;
TSTNode* right;
const SimpleString* value; // value != NULL iff this is a leaf node
explicit TSTNode(char aCh)
: ch(aCh),
left(NULL),
eq(NULL),
right(NULL),
value(NULL) {}
~TSTNode()
{
if (this->left) delete this->left;
if (this->eq) delete this->eq;
if (this->right) delete this->right;
}
};
static const size_t NodePoolChunkSize = 65536; // 4096 is slower, according to perf.js
/**
* Ternary search tree.
*
* Every string inserted into this tree will be an external one. That means the
* caller must ensure none of those strings are freed until the TST is deleted.
*/
class TST
{
public:
void insert(const SimpleString& key, const SimpleString* value)
{
if (key.len == 0) return; // We don't store zero-length strings
this->_insert(&this->root, key.s, key.len, value);
}
bool contains(const char* s, size_t len) const
{
const TSTNode* node = this->getNode(s, len);
return node != NULL;
}
const SimpleString* get(const char* s, size_t len) const
{
const TSTNode* node = this->getNode(s, len);
if (node == NULL) {
return NULL;
} else if (node->value->isNull()) {
// Every leaf node has a value, but it might be a null string.
return NULL;
} else {
return node->value;
}
}
explicit TST() : root(NULL) {}
private:
TSTNode* root;
MemoryPool<TSTNode,NodePoolChunkSize> pool;
void _insert(TSTNode** nodeAddress, const char* s, size_t len, const SimpleString* value) {
char ch = *s;
if (*nodeAddress == NULL) {
*nodeAddress = pool.newElement(ch);
// All the nodes get deleted by the MemoryPool when we destroy the TST
}
TSTNode* node = *nodeAddress;
if (ch < node->ch) {
this->_insert(&node->left, s, len, value);
} else if (ch > node->ch) {
this->_insert(&node->right, s, len, value);
} else if (len > 1) {
this->_insert(&node->eq, &s[1], len - 1, value);
} else {
node->value = value;
}
}
const TSTNode* getNode(const char* s, size_t len) const {
if (len == 0) return NULL; // We don't store zero-length strings
return this->_getNode(this->root, s, len); // recursive search
}
const TSTNode* _getNode(const TSTNode* node, const char* s, size_t len) const {
// Assume len > 0
for (;;) {
if (node == NULL) return NULL; // No match
char ch = *s;
if (ch < node->ch) {
node = node->left;
} else if (ch > node->ch) {
node = node->right;
} else if (len > 1) {
node = node->eq;
s++;
len--;
} else if (node->value != NULL) {
return node; // match
} else {
return NULL; // end of search
}
}
}
};
class TernaryBufferTree : public node::ObjectWrap {
public:
static void Init(Handle<Object> exports);
static Persistent<Function> constructor;
inline bool contains(const char* s, size_t len) const;
const SimpleString* get(const char* s, size_t len) const;
std::vector<SimpleString> findAllMatches(const char* s, size_t len, size_t maxNgramSize);
private:
char* mem = NULL;
SimpleString* strings = NULL;
TST tree;
explicit TernaryBufferTree(const char* s, size_t len);
~TernaryBufferTree();
static void New(const FunctionCallbackInfo<Value>& args);
static void Contains(const FunctionCallbackInfo<Value>& args);
static void Get(const FunctionCallbackInfo<Value>& args);
static void FindAllMatches(const FunctionCallbackInfo<Value>& args);
};
Persistent<Function> TernaryBufferTree::constructor;
static size_t
count_char_in_str(char ch, const char* s, size_t len) {
size_t ret = 0;
while (len > 0) {
if (*s == ch) ret++;
len--;
s++;
}
return ret;
}
/**
* Insert Strings into a TST.
*
* We assume the Strings are sorted. Insert the median first, then recurse.
* That's described in "Better Insertion Orders" at
* http://www.drdobbs.com/database/ternary-search-trees/184410528?pgno=2
*
* The `tokens` passed here are in *pairs*: that is, tokens[0] is a key,
* tokens[1] is its value; tokens[2] is the next key with tokens[3] as its
* value; etc. The `begin` and `end` describe the *pairs*, not the tokens:
* when `begin == end == 1`, then the key is `tokens[2]` and the value is
* `tokens[3]`.
*/
static void
insert_many(TST& tree, SimpleString tokens[], size_t begin, size_t end)
{
if (end == begin) return;
size_t mid = (begin + end - 1) >> 1;
tree.insert(tokens[mid * 2], &tokens[mid * 2 + 1]);
if (mid > begin) insert_many(tree, tokens, begin, mid);
if (mid < end - 1) insert_many(tree, tokens, mid + 1, end);
}
TernaryBufferTree::TernaryBufferTree(const char* s, size_t len)
{
this->mem = new char[len];
memcpy(this->mem, s, len);
size_t nTokens = count_char_in_str('\n', s, len) + 1;
this->strings = new SimpleString[nTokens * 2];
SimpleString* curString = &this->strings[0];
bool foundTabThisLine = false;
curString->s = this->mem;
const char* end = this->mem + len;
for (const char* p = this->mem; p < end; p++) {
switch (*p) {
case '\n':
curString->len = p - curString->s;
curString++;
if (!foundTabThisLine) {
curString++; // There's no value
}
foundTabThisLine = false;
curString->s = &p[1]; // Start parsing the next line
break;
case '\t':
curString->len = p - curString->s;
curString++;
foundTabThisLine = true;
curString->s = &p[1]; // Start parsing the value
break;
}
}
curString->len = end - curString->s;
insert_many(this->tree, this->strings, 0, nTokens);
}
TernaryBufferTree::~TernaryBufferTree()
{
delete[] this->mem;
delete[] this->strings;
}
bool
TernaryBufferTree::contains(const char* s, size_t len) const
{
return this->tree.contains(s, len);
}
const SimpleString*
TernaryBufferTree::get(const char* s, size_t len) const
{
return this->tree.get(s, len);
}
std::vector<SimpleString>
TernaryBufferTree::findAllMatches(const char* s, size_t len, size_t maxNgramSize) {
std::vector<SimpleString> ret;
std::deque<const char*> tokenStarts;
const char* lastP = s;
const char* end = s + len;
tokenStarts.push_back(s);
while (true) {
const char* p = static_cast<const char*>(memchr(lastP, ' ', end - lastP));
if (p == NULL) p = s + len;
// Add s[tokenStarts[0],pos), s[tokenStarts[1],pos), ... for every token
// in the set
for (auto i = tokenStarts.begin(); i < tokenStarts.end(); i++) {
const char* tokenStart = *i;
if (this->tree.contains(tokenStart, p - tokenStart)) {
ret.push_back(SimpleString(tokenStart, p - tokenStart));
}
}
if (tokenStarts.size() == maxNgramSize) tokenStarts.pop_front();
if (p == s + len) break;
lastP = p + 1;
tokenStarts.push_back(lastP);
}
return ret;
}
void
TernaryBufferTree::Init(Handle<Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "TernaryBufferTree"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "contains", Contains);
NODE_SET_PROTOTYPE_METHOD(tpl, "get", Get);
NODE_SET_PROTOTYPE_METHOD(tpl, "findAllMatches", FindAllMatches);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "TernaryBufferTree"), tpl->GetFunction());
}
void
TernaryBufferTree::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
const char* s = node::Buffer::Data(args[0]);
const size_t len = node::Buffer::Length(args[0]);
TernaryBufferTree* obj = new TernaryBufferTree(s, len);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call
Local<Value> argv[1] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(1, argv));
}
}
void TernaryBufferTree::Contains(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
bool ret = false;
Local<Value> arg = args[0]; // Buffer or String
if (node::Buffer::HasInstance(arg)) {
// It's a buffer. Go char-by-char
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
ret = obj->contains(data, len);
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
ret = obj->contains(*argString, argString.length());
}
args.GetReturnValue().Set(ret);
}
void TernaryBufferTree::Get(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
const SimpleString* result;
Local<Value> arg = args[0]; // Buffer or String
if (node::Buffer::HasInstance(arg)) {
// It's a buffer. Go char-by-char
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
result = obj->get(data, len);
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
result = obj->get(*argString, argString.length());
}
if (result != NULL) {
Handle<String> ret(String::NewFromUtf8(isolate, result->s, String::NewStringType::kNormalString, result->len));
args.GetReturnValue().Set(ret);
}
}
void
TernaryBufferTree::FindAllMatches(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
std::vector<SimpleString> ret;
Handle<Array> retArray;
Local<Value> arg = args[0]; // Buffer or String
uint32_t maxNgramSize = args[1]->Uint32Value();
if (maxNgramSize == 0) maxNgramSize = 1;
if (node::Buffer::HasInstance(arg)) {
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
ret = obj->findAllMatches(data, len, maxNgramSize);
// Icky copy/paste, I know
size_t size = ret.size();
retArray = Array::New(isolate, size);
for (size_t i = 0; i < size; i++) {
retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));
}
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
ret = obj->findAllMatches(*argString, argString.length(), maxNgramSize);
// Icky copy/paste, I know
size_t size = ret.size();
retArray = Array::New(isolate, size);
for (size_t i = 0; i < size; i++) {
retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));
}
}
args.GetReturnValue().Set(retArray);
}
void
init(Handle<Object> exports, Handle<Object> module) {
TernaryBufferTree::Init(exports);
}
NODE_MODULE(binding, init);
<commit_msg>Optimize searches<commit_after>#include <cstring>
#include <deque>
#include <vector>
#include <iostream>
#include <string>
#include <node.h>
#include <node_buffer.h>
#include <node_object_wrap.h>
#include <v8.h>
#include "MemoryPool.h"
using namespace v8;
/**
* A string whose characters are stored elsewhere.
*
* The argument-free constructor will return a "null string". Basically, it's
* a hack that probably behaves the way you expect. (Its memory address is
* NULL.)
*/
struct SimpleString
{
const char* s;
size_t len;
SimpleString(const char* aS, size_t aLen) : s(aS), len(aLen) {}
SimpleString() : s(NULL), len(0) {}
SimpleString(const SimpleString& rhs) : s(rhs.s), len(rhs.len) {}
inline bool isNull() const { return s == NULL; }
};
struct TSTNode
{
char ch;
TSTNode* left;
TSTNode* eq;
TSTNode* right;
const SimpleString* value; // value != NULL iff this is a leaf node
explicit TSTNode(char aCh)
: ch(aCh),
left(NULL),
eq(NULL),
right(NULL),
value(NULL) {}
~TSTNode()
{
if (this->left) delete this->left;
if (this->eq) delete this->eq;
if (this->right) delete this->right;
}
};
static const size_t NodePoolChunkSize = 65536; // 4096 is slower, according to perf.js
/**
* Ternary search tree.
*
* Every string inserted into this tree will be an external one. That means the
* caller must ensure none of those strings are freed until the TST is deleted.
*/
class TST
{
public:
void insert(const SimpleString& key, const SimpleString* value)
{
if (key.len == 0) return; // We don't store zero-length strings
this->_insert(&this->root, key.s, key.len, value);
}
bool contains(const char* s, size_t len) const
{
const TSTNode* node = this->getNode(s, len);
return node != NULL;
}
const SimpleString* get(const char* s, size_t len) const
{
const TSTNode* node = this->getNode(s, len);
if (node == NULL) {
return NULL;
} else if (node->value->isNull()) {
// Every leaf node has a value, but it might be a null string.
return NULL;
} else {
return node->value;
}
}
explicit TST() : root(NULL) {}
private:
TSTNode* root;
MemoryPool<TSTNode,NodePoolChunkSize> pool;
void _insert(TSTNode** nodeAddress, const char* s, size_t len, const SimpleString* value) {
char ch = *s;
if (*nodeAddress == NULL) {
*nodeAddress = pool.newElement(ch);
// All the nodes get deleted by the MemoryPool when we destroy the TST
}
TSTNode* node = *nodeAddress;
if (ch < node->ch) {
this->_insert(&node->left, s, len, value);
} else if (ch > node->ch) {
this->_insert(&node->right, s, len, value);
} else if (len > 1) {
this->_insert(&node->eq, &s[1], len - 1, value);
} else {
node->value = value;
}
}
const TSTNode* getNode(const char* s, size_t len) const {
if (len == 0) return NULL; // We don't store zero-length strings
const TSTNode* node = this->root;
for (;;) {
if (node == NULL) return NULL; // No match
char ch = *s;
if (ch < node->ch) {
node = node->left;
} else if (ch > node->ch) {
node = node->right;
} else if (len > 1) {
node = node->eq;
s++;
len--;
} else if (node->value != NULL) {
return node; // match
} else {
return NULL; // end of search
}
}
}
};
class TernaryBufferTree : public node::ObjectWrap {
public:
static void Init(Handle<Object> exports);
static Persistent<Function> constructor;
inline bool contains(const char* s, size_t len) const;
const SimpleString* get(const char* s, size_t len) const;
std::vector<SimpleString> findAllMatches(const char* s, size_t len, size_t maxNgramSize);
private:
char* mem = NULL;
SimpleString* strings = NULL;
TST tree;
explicit TernaryBufferTree(const char* s, size_t len);
~TernaryBufferTree();
static void New(const FunctionCallbackInfo<Value>& args);
static void Contains(const FunctionCallbackInfo<Value>& args);
static void Get(const FunctionCallbackInfo<Value>& args);
static void FindAllMatches(const FunctionCallbackInfo<Value>& args);
};
Persistent<Function> TernaryBufferTree::constructor;
static size_t
count_char_in_str(char ch, const char* s, size_t len) {
size_t ret = 0;
while (len > 0) {
if (*s == ch) ret++;
len--;
s++;
}
return ret;
}
/**
* Insert Strings into a TST.
*
* We assume the Strings are sorted. Insert the median first, then recurse.
* That's described in "Better Insertion Orders" at
* http://www.drdobbs.com/database/ternary-search-trees/184410528?pgno=2
*
* The `tokens` passed here are in *pairs*: that is, tokens[0] is a key,
* tokens[1] is its value; tokens[2] is the next key with tokens[3] as its
* value; etc. The `begin` and `end` describe the *pairs*, not the tokens:
* when `begin == end == 1`, then the key is `tokens[2]` and the value is
* `tokens[3]`.
*/
static void
insert_many(TST& tree, SimpleString tokens[], size_t begin, size_t end)
{
if (end == begin) return;
size_t mid = (begin + end - 1) >> 1;
tree.insert(tokens[mid * 2], &tokens[mid * 2 + 1]);
if (mid > begin) insert_many(tree, tokens, begin, mid);
if (mid < end - 1) insert_many(tree, tokens, mid + 1, end);
}
TernaryBufferTree::TernaryBufferTree(const char* s, size_t len)
{
this->mem = new char[len];
memcpy(this->mem, s, len);
size_t nTokens = count_char_in_str('\n', s, len) + 1;
this->strings = new SimpleString[nTokens * 2];
SimpleString* curString = &this->strings[0];
bool foundTabThisLine = false;
curString->s = this->mem;
const char* end = this->mem + len;
for (const char* p = this->mem; p < end; p++) {
switch (*p) {
case '\n':
curString->len = p - curString->s;
curString++;
if (!foundTabThisLine) {
curString++; // There's no value
}
foundTabThisLine = false;
curString->s = &p[1]; // Start parsing the next line
break;
case '\t':
curString->len = p - curString->s;
curString++;
foundTabThisLine = true;
curString->s = &p[1]; // Start parsing the value
break;
}
}
curString->len = end - curString->s;
insert_many(this->tree, this->strings, 0, nTokens);
}
TernaryBufferTree::~TernaryBufferTree()
{
delete[] this->mem;
delete[] this->strings;
}
bool
TernaryBufferTree::contains(const char* s, size_t len) const
{
return this->tree.contains(s, len);
}
const SimpleString*
TernaryBufferTree::get(const char* s, size_t len) const
{
return this->tree.get(s, len);
}
std::vector<SimpleString>
TernaryBufferTree::findAllMatches(const char* s, size_t len, size_t maxNgramSize) {
std::vector<SimpleString> ret;
std::deque<const char*> tokenStarts;
const char* lastP = s;
const char* end = s + len;
tokenStarts.push_back(s);
while (true) {
const char* p = static_cast<const char*>(memchr(lastP, ' ', end - lastP));
if (p == NULL) p = s + len;
// Add s[tokenStarts[0],pos), s[tokenStarts[1],pos), ... for every token
// in the set
for (auto i = tokenStarts.begin(); i < tokenStarts.end(); i++) {
const char* tokenStart = *i;
if (this->tree.contains(tokenStart, p - tokenStart)) {
ret.push_back(SimpleString(tokenStart, p - tokenStart));
}
}
if (tokenStarts.size() == maxNgramSize) tokenStarts.pop_front();
if (p == s + len) break;
lastP = p + 1;
tokenStarts.push_back(lastP);
}
return ret;
}
void
TernaryBufferTree::Init(Handle<Object> exports) {
Isolate* isolate = Isolate::GetCurrent();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "TernaryBufferTree"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "contains", Contains);
NODE_SET_PROTOTYPE_METHOD(tpl, "get", Get);
NODE_SET_PROTOTYPE_METHOD(tpl, "findAllMatches", FindAllMatches);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "TernaryBufferTree"), tpl->GetFunction());
}
void
TernaryBufferTree::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
const char* s = node::Buffer::Data(args[0]);
const size_t len = node::Buffer::Length(args[0]);
TernaryBufferTree* obj = new TernaryBufferTree(s, len);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call
Local<Value> argv[1] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
args.GetReturnValue().Set(cons->NewInstance(1, argv));
}
}
void TernaryBufferTree::Contains(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
bool ret = false;
Local<Value> arg = args[0]; // Buffer or String
if (node::Buffer::HasInstance(arg)) {
// It's a buffer. Go char-by-char
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
ret = obj->contains(data, len);
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
ret = obj->contains(*argString, argString.length());
}
args.GetReturnValue().Set(ret);
}
void TernaryBufferTree::Get(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
const SimpleString* result;
Local<Value> arg = args[0]; // Buffer or String
if (node::Buffer::HasInstance(arg)) {
// It's a buffer. Go char-by-char
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
result = obj->get(data, len);
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
result = obj->get(*argString, argString.length());
}
if (result != NULL) {
Handle<String> ret(String::NewFromUtf8(isolate, result->s, String::NewStringType::kNormalString, result->len));
args.GetReturnValue().Set(ret);
}
}
void
TernaryBufferTree::FindAllMatches(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());
std::vector<SimpleString> ret;
Handle<Array> retArray;
Local<Value> arg = args[0]; // Buffer or String
uint32_t maxNgramSize = args[1]->Uint32Value();
if (maxNgramSize == 0) maxNgramSize = 1;
if (node::Buffer::HasInstance(arg)) {
const char* data(node::Buffer::Data(arg));
const size_t len(node::Buffer::Length(arg));
ret = obj->findAllMatches(data, len, maxNgramSize);
// Icky copy/paste, I know
size_t size = ret.size();
retArray = Array::New(isolate, size);
for (size_t i = 0; i < size; i++) {
retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));
}
} else {
// We can convert it to utf-8. On failure, it's just an empty String.
String::Utf8Value argString(arg);
ret = obj->findAllMatches(*argString, argString.length(), maxNgramSize);
// Icky copy/paste, I know
size_t size = ret.size();
retArray = Array::New(isolate, size);
for (size_t i = 0; i < size; i++) {
retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));
}
}
args.GetReturnValue().Set(retArray);
}
void
init(Handle<Object> exports, Handle<Object> module) {
TernaryBufferTree::Init(exports);
}
NODE_MODULE(binding, init);
<|endoftext|>
|
<commit_before>// Filename: mayaSavePview.cxx
// Created by: drose (27Oct03)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "mayaSavePview.h"
#include <maya/MString.h>
#include <maya/MFnPlugin.h>
#include <maya/MFileIO.h>
#include <stdlib.h>
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
MayaSavePview::
MayaSavePview() {
}
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::doIt
// Access: Public, Virtual
// Description: Called when the plugin command is invoked.
////////////////////////////////////////////////////////////////////
MStatus MayaSavePview::
doIt(const MArgList &) {
MStatus result;
// First, make sure the current buffer is saved.
result = MFileIO::save(false);
if (result != MS::kSuccess) {
return result;
}
MString filename = MFileIO::currentFile();
MString command = MString("pview \"") + filename + MString("\"");
int command_result = system(command.asChar());
if (command_result != 0) {
return MS::kFailure;
}
return MS::kSuccess;
}
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::creator
// Access: Public, Static
// Description: This is used to create a new instance of the plugin.
////////////////////////////////////////////////////////////////////
void *MayaSavePview::
creator() {
return new MayaSavePview;
}
////////////////////////////////////////////////////////////////////
// Function: initializePlugin
// Description: Called by Maya when the plugin is loaded.
////////////////////////////////////////////////////////////////////
EXPCL_MISC MStatus
initializePlugin(MObject obj) {
MFnPlugin plugin(obj, "VR Studio", "1.0");
MStatus status;
status = plugin.registerCommand("savePview", MayaSavePview::creator);
if (!status) {
status.perror("registerCommand");
}
return status;
}
////////////////////////////////////////////////////////////////////
// Function: uninitializePlugin
// Description: Called by Maya when the plugin is unloaded.
////////////////////////////////////////////////////////////////////
EXPCL_MISC MStatus
uninitializePlugin(MObject obj) {
MFnPlugin plugin(obj);
MStatus status;
status = plugin.deregisterCommand("savePview");
if (!status) {
status.perror("deregisterCommand");
}
return status;
}
<commit_msg>call it pview, and use the -c option<commit_after>// Filename: mayaSavePview.cxx
// Created by: drose (27Oct03)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "mayaSavePview.h"
#include <maya/MString.h>
#include <maya/MFnPlugin.h>
#include <maya/MFileIO.h>
#include <stdlib.h>
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::Constructor
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
MayaSavePview::
MayaSavePview() {
}
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::doIt
// Access: Public, Virtual
// Description: Called when the plugin command is invoked.
////////////////////////////////////////////////////////////////////
MStatus MayaSavePview::
doIt(const MArgList &) {
MStatus result;
// First, make sure the current buffer is saved.
result = MFileIO::save(false);
if (result != MS::kSuccess) {
return result;
}
MString filename = MFileIO::currentFile();
MString command = MString("pview -c \"") + filename + MString("\"");
int command_result = system(command.asChar());
if (command_result != 0) {
return MS::kFailure;
}
return MS::kSuccess;
}
////////////////////////////////////////////////////////////////////
// Function: MayaSavePview::creator
// Access: Public, Static
// Description: This is used to create a new instance of the plugin.
////////////////////////////////////////////////////////////////////
void *MayaSavePview::
creator() {
return new MayaSavePview;
}
////////////////////////////////////////////////////////////////////
// Function: initializePlugin
// Description: Called by Maya when the plugin is loaded.
////////////////////////////////////////////////////////////////////
EXPCL_MISC MStatus
initializePlugin(MObject obj) {
MFnPlugin plugin(obj, "VR Studio", "1.0");
MStatus status;
status = plugin.registerCommand("pview", MayaSavePview::creator);
if (!status) {
status.perror("registerCommand");
}
return status;
}
////////////////////////////////////////////////////////////////////
// Function: uninitializePlugin
// Description: Called by Maya when the plugin is unloaded.
////////////////////////////////////////////////////////////////////
EXPCL_MISC MStatus
uninitializePlugin(MObject obj) {
MFnPlugin plugin(obj);
MStatus status;
status = plugin.deregisterCommand("pview");
if (!status) {
status.perror("deregisterCommand");
}
return status;
}
<|endoftext|>
|
<commit_before>#include "easyjobserver.h"
#include <votca/csg/nblist.h>
#include <qmnblist.h>
#include <votca/tools/histogramnew.h>
EasyJObserver::EasyJObserver()
{}
EasyJObserver::~EasyJObserver()
{}
void EasyJObserver::Initialize(QMTopology &qmtop, Property &opts)
{
_qmtop = &qmtop;
_kT = opts.get("calc_rates.thermal_energy").as<double>();
_E = opts.get("calc_rates.e_field").as<vec>();
cout << "E = " << _E << endl;
}
void EasyJObserver::setNNnames(string nnnames){
Tokenizer tok(nnnames, " ;");
Tokenizer::iterator itok = tok.begin();
for (; itok!= tok.end(); ++itok){
_nnnames.push_back(*itok);
}
}
void EasyJObserver::BeginCG(Topology *top, Topology *top_atom)
{
_qmtop->Initialize(*top);
}
void EasyJObserver::EndCG()
{
HistogramNew histo;
histo.Initialize(*(std::min_element( _Js.begin(), _Js.end() )),*(std::max_element( _Js.begin(), _Js.end() ) ) , int(_Js.size() / 10 ));
histo.ProcessRange(_Js.begin(),_Js.end());
cout << histo <<endl;
}
/// evaluate current conformation
void EasyJObserver::EvalConfiguration(Topology *top, Topology *top_atom)
{
_qmtop->Update(*top);
QMNBList &nblist = _qmtop->nblist();
BeadList list1;
Topology *toptmp = dynamic_cast<Topology*>(_qmtop);
list1.Generate(*toptmp, "*");
nblist.setCutoff(_cutoff);
nblist.Generate(list1);
for(QMNBList::iterator iter = nblist.begin();
iter!=nblist.end();++iter) {
CrgUnit *crg1 = (*iter)->first;
CrgUnit *crg2 = (*iter)->second;
if(MatchNNnames(crg1, crg2)){
vector <double> Js = _qmtop->GetJCalc().GetJ(*crg1, *crg2);
//cout << crg1->GetId() << " " << crg2->GetId() << " ";
for(int i=0; i<Js.size(); ++i)
{
_Js.push_back(Js[i]);
}
(*iter)->setJ(Js[0]);
}
}
CalcRates(nblist);
MakeRatesSIUnits(nblist);
print_nbs_to_file(nblist);
cout<<"Falks test\n";
StateSaver _saver(*_qmtop);
string outfilename = "falks.dat";
_saver.Open(outfilename,true);
_saver.Write_QMBeads(_qmtop);
}
bool EasyJObserver::MatchNNnames(CrgUnit *crg1, CrgUnit* crg2){
vector <string>::iterator its = _nnnames.begin();
string namecrg = crg1->GetType()->GetName()+string(":")+crg2->GetType()->GetName();
for ( ; its!= _nnnames.end(); ++its){
if(wildcmp(its->c_str(), namecrg.c_str()) ){
return true;
}
}
return false;
}
void EasyJObserver::CalcRates(QMNBList &nblist){
for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)
{
double rate = 0.0;
double Jeff = (*iter)->j();
//cout << "Jeff = " << Jeff << endl;
CrgUnit *crg1 = (*iter)->first;
CrgUnit *crg2 = (*iter)->second;
if(MatchNNnames(crg1, crg2))
{
double prefactor = 1.0;
/// reorganization energy in eV as given in list_charges.xml
double reorg = 0.5 * (crg1->GetType()->GetReorg()+crg2->GetType()->GetReorg());
/// free energy difference due to electric field, i.e. E*r_ij
double dG_field = -_E * ((*iter)->r()) * RA * Ang;
/// free energy difference due to different energy levels of molecules
double dG_en = crg2->GetNRG() - crg1->GetNRG();
/// electrostatics are taken into account in qmtopology and are contained in NRG
/// total free energy difference
double dG = dG_field + dG_en;
/// Marcus rate
rate = prefactor * sqrt(PI/(reorg * _kT)) * Jeff * Jeff *
exp (-(dG + reorg)*(dG + reorg)/(4*_kT*reorg));
//cout << "Rate: " << rate << endl;
//cout << "dG_field = " << dG_field << endl;
}
(*iter)->setRate(rate);
}
}
void EasyJObserver::MakeRatesSIUnits(QMNBList &nblist){
for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)
{
(*iter)->rate() *= 1/hbar;
}
}
void EasyJObserver::print_nbs_to_file(QMNBList &nblist){
ofstream out_nbl;
out_nbl.open("nbl_votca.res");
if(out_nbl!=0){
out_nbl << "Neighbours, J(0), J_eff, rate, r_ij, abs(r_ij) [Bohr]" << endl;
QMNBList::iterator iter;
for ( iter = nblist.begin(); iter != nblist.end() ; ++iter){
out_nbl << "(" << (*iter)->first->GetId() << "," << (*iter)->second->GetId() << "): ";
out_nbl << (*iter)->j() << " " << abs((*iter)->j()) << " " << (*iter)->rate() << " ";
out_nbl << (*iter)->r().getX() << " " << (*iter)->r().getY() << " " << (*iter)->r().getZ() << " ";
out_nbl << " " << abs((*iter)->r()) << endl;
}
}
out_nbl.close();
}<commit_msg>added function make_kmc_graph<commit_after>#include "easyjobserver.h"
#include <votca/csg/nblist.h>
#include <qmnblist.h>
#include <votca/tools/histogramnew.h>
#include <kmc/vertex.h>
EasyJObserver::EasyJObserver()
{}
EasyJObserver::~EasyJObserver()
{}
void EasyJObserver::Initialize(QMTopology &qmtop, Property &opts)
{
_qmtop = &qmtop;
_kT = opts.get("calc_rates.thermal_energy").as<double>();
_E = opts.get("calc_rates.e_field").as<vec>();
cout << "E = " << _E << endl;
}
void EasyJObserver::setNNnames(string nnnames){
Tokenizer tok(nnnames, " ;");
Tokenizer::iterator itok = tok.begin();
for (; itok!= tok.end(); ++itok){
_nnnames.push_back(*itok);
}
}
void EasyJObserver::BeginCG(Topology *top, Topology *top_atom)
{
_qmtop->Initialize(*top);
}
void EasyJObserver::EndCG()
{
HistogramNew histo;
histo.Initialize(*(std::min_element( _Js.begin(), _Js.end() )),*(std::max_element( _Js.begin(), _Js.end() ) ) , int(_Js.size() / 10 ));
histo.ProcessRange(_Js.begin(),_Js.end());
cout << histo <<endl;
}
/// evaluate current conformation
void EasyJObserver::EvalConfiguration(Topology *top, Topology *top_atom)
{
_qmtop->Update(*top);
QMNBList &nblist = _qmtop->nblist();
BeadList list1;
Topology *toptmp = dynamic_cast<Topology*>(_qmtop);
list1.Generate(*toptmp, "*");
nblist.setCutoff(_cutoff);
nblist.Generate(list1);
for(QMNBList::iterator iter = nblist.begin();
iter!=nblist.end();++iter) {
CrgUnit *crg1 = (*iter)->first;
CrgUnit *crg2 = (*iter)->second;
if(MatchNNnames(crg1, crg2)){
vector <double> Js = _qmtop->GetJCalc().GetJ(*crg1, *crg2);
//cout << crg1->GetId() << " " << crg2->GetId() << " ";
for(int i=0; i<Js.size(); ++i)
{
_Js.push_back(Js[i]);
}
(*iter)->setJ(Js[0]);
}
}
CalcRates(nblist);
MakeRatesSIUnits(nblist);
print_nbs_to_file(nblist);
graph kmc_grid;
make_kmc_graph(&kmc_grid,nblist);
cout<<"Falks test\n";
StateSaver _saver(*_qmtop);
string outfilename = "falks.dat";
_saver.Open(outfilename,true);
_saver.Write_QMBeads(_qmtop);
}
bool EasyJObserver::MatchNNnames(CrgUnit *crg1, CrgUnit* crg2){
vector <string>::iterator its = _nnnames.begin();
string namecrg = crg1->GetType()->GetName()+string(":")+crg2->GetType()->GetName();
for ( ; its!= _nnnames.end(); ++its){
if(wildcmp(its->c_str(), namecrg.c_str()) ){
return true;
}
}
return false;
}
void EasyJObserver::CalcRates(QMNBList &nblist){
for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)
{
double rate_12, rate_21 = 0.0;
double Jeff = (*iter)->j();
//cout << "Jeff = " << Jeff << endl;
CrgUnit *crg1 = (*iter)->first;
CrgUnit *crg2 = (*iter)->second;
if(MatchNNnames(crg1, crg2))
{
double prefactor = 1.0;
/// reorganization energy in eV as given in list_charges.xml
double reorg = 0.5 * (crg1->GetType()->GetReorg()+crg2->GetType()->GetReorg());
/// free energy difference due to electric field, i.e. E*r_ij
double dG_field = -_E * ((*iter)->r()) * RA * Ang;
/// free energy difference due to different energy levels of molecules
double dG_en = crg2->GetNRG() - crg1->GetNRG();
/// electrostatics are taken into account in qmtopology and are contained in NRG
/// total free energy difference
double dG = dG_field + dG_en;
/// Marcus rate from first to second
rate_12 = prefactor * sqrt(PI/(reorg * _kT)) * Jeff * Jeff *
exp (-(dG + reorg)*(dG + reorg)/(4*_kT*reorg));
/// Marcus rate from second to first (dG_field -> -dG_field)
dG = -dG_field + dG_en;
rate_21 = prefactor * sqrt(PI/(reorg * _kT)) * Jeff * Jeff *
exp (-(dG + reorg)*(dG + reorg)/(4*_kT*reorg));
}
(*iter)->setRate12(rate_12);
(*iter)->setRate21(rate_21);
}
}
void EasyJObserver::MakeRatesSIUnits(QMNBList &nblist){
for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)
{
(*iter)->rate12() *= 1/hbar;
(*iter)->rate21() *= 1/hbar;
}
}
void EasyJObserver::print_nbs_to_file(QMNBList &nblist){
ofstream out_nbl;
out_nbl.open("nbl_votca.res");
if(out_nbl!=0){
out_nbl << "Neighbours, J(0), J_eff, rate, r_ij, abs(r_ij) [Bohr]" << endl;
QMNBList::iterator iter;
for ( iter = nblist.begin(); iter != nblist.end() ; ++iter){
out_nbl << "(" << (*iter)->first->GetId() << "," << (*iter)->second->GetId() << "): ";
out_nbl << (*iter)->j() << " " << abs((*iter)->j()) << " " << (*iter)->rate12() << " ";
out_nbl << (*iter)->r().getX() << " " << (*iter)->r().getY() << " " << (*iter)->r().getZ() << " ";
out_nbl << " " << abs((*iter)->r()) << endl;
}
}
out_nbl.close();
}
void EasyJObserver::make_kmc_graph(graph *a, QMNBList &nblist){
cout << "[make_kmc_graph]: Building KMC Graph...";
/// assign constants
a->SetField(_E);
/// set vertices equal to centers of mass
BeadContainer::iterator it;
for(it=_qmtop->Beads().begin(); it!=_qmtop->Beads().end(); ++it){
a->AddVertex((*it)->getPos(),_E); /// TO DO: remove necessity for E-field at this point
}
/// set edges, two edges 1->2 and 2->1 are created per neighboring pair
for(QMNBList::iterator iter = nblist.begin(); iter!=nblist.end();++iter){
a->AddEdge((*iter)->first->GetId(), (*iter)->second->GetId(), (*iter)->rate12(),(*iter)->r());
a->AddEdge((*iter)->second->GetId(), (*iter)->first->GetId(), (*iter)->rate21(),-(*iter)->r());
}
cout << " Done." << endl;
}<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.3 2000/01/19 00:56:59 roddey
* Changes to get rid of dependence on old utils standard streams and to
* get rid of the fgLibLocation stuff.
*
* Revision 1.2 2000/01/12 00:16:22 roddey
* Changes to deal with multiply nested, relative pathed, entities and to deal
* with the new URL class changes.
*
* Revision 1.1.1.1 1999/11/09 01:04:55 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:11 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(PLATFORMUTILS_HPP)
#define PLATFORMUTILS_HPP
#include <util/XML4CDefs.hpp>
#include <util/XMLException.hpp>
#include <util/XMLUni.hpp>
class XMLMsgLoader;
class XMLNetAccessor;
class XMLTransService;
//
// Generate an exception for platform utitilities to throw when something
// goes awry.
//
const XMLCh gXMLPlatformUtilsException_Name[] =
{
chLatin_X, chLatin_M, chLatin_L, chLatin_P, chLatin_l, chLatin_a
, chLatin_t, chLatin_f, chLatin_o, chLatin_r, chLatin_m, chLatin_E
, chLatin_x, chLatin_c, chLatin_e, chLatin_p, chLatin_t, chLatin_i
, chLatin_o, chLatin_n, chNull
};
MakeXML4CException(XMLPlatformUtilsException, XMLUTIL_EXPORT)
class XMLUTIL_EXPORT XMLPlatformUtils
{
public :
// -----------------------------------------------------------------------
// Public types
// -----------------------------------------------------------------------
enum PanicReasons
{
Panic_NoTransService
, Panic_NoDefTranscoder
, Panic_CantFindLib
, Panic_UnknownMsgDomain
, Panic_CantLoadMsgDomain
, PanicReasons_Count
};
// -----------------------------------------------------------------------
// Public, static data
//
// fgNetAccessor
// This is the network access implementation. This is provided by
// the per-platform driver, so each platform can choose what actual
// implementation it wants to use.
//
// fgTransService
// This is the transcoding service. This is provided by the per
// platform driver, so each platform can choose what implemenation
// it wants to use.
// -----------------------------------------------------------------------
static XMLNetAccessor* fgNetAccessor;
static XMLTransService* fgTransService;
// -----------------------------------------------------------------------
// Initialization method. This must be called first in any client code.
// -----------------------------------------------------------------------
static void Initialize();
// -----------------------------------------------------------------------
// The panic mechanism. If, during init, we cannot even get far enough
// along to get transcoding up or get message loading working, we call
// this.
//
// Each platform can implement it however they want. This method is
// expected to display something meaningful and end the process. The
// enum indicates why its being called, to allow the per-platform code
// to display something more specific if desired.
// -----------------------------------------------------------------------
static void panic
(
const PanicReasons reason
);
// -----------------------------------------------------------------------
// File methods
// -----------------------------------------------------------------------
static unsigned int curFilePos(FileHandle theFile);
static void closeFile(FileHandle theFile);
static unsigned int fileSize(FileHandle theFile);
static FileHandle openFile(const char* const fileName);
static FileHandle openFile(const XMLCh* const fileName);
static FileHandle openStdInHandle();
static unsigned int readFileBuffer
(
FileHandle theFile
, const unsigned int toRead
, XMLByte* const toFill
);
static void resetFile(FileHandle theFile);
// -----------------------------------------------------------------------
// File system methods
// -----------------------------------------------------------------------
static XMLCh* getFullPath(const XMLCh* const srcPath);
static bool isRelative(const XMLCh* const toCheck);
static XMLCh* weavePaths
(
const XMLCh* const basePath
, const XMLCh* const relativePath
);
// -----------------------------------------------------------------------
// Timing methods
// -----------------------------------------------------------------------
static unsigned long getCurrentMillis();
// -----------------------------------------------------------------------
// Mutex methods
// -----------------------------------------------------------------------
static void closeMutex(void* const mtxHandle);
static void lockMutex(void* const mtxHandle);
static void* makeMutex();
static void unlockMutex(void* const mtxHandle);
// -----------------------------------------------------------------------
// External message support
// -----------------------------------------------------------------------
static XMLMsgLoader* loadMsgSet(const XMLCh* const msgDomain);
// -----------------------------------------------------------------------
// Miscellaneous synchronization methods
// -----------------------------------------------------------------------
static void* compareAndSwap
(
void** toFill
, const void* const newValue
, const void* const toCompare
);
// -----------------------------------------------------------------------
// Atomic Increment and Decrement
//
// The function return value is positive if the result of the operation
// was positive. Zero if the result of the operation was zero. Negative
// if the result of the operation was negative. Except for the zero
// case, the value returned may differ from the actual result of the
// operation - only the sign and zero/nonzero state is guaranteed to be
// correct.
// -----------------------------------------------------------------------
static int atomicIncrement(int& location);
static int atomicDecrement(int& location);
private :
// -----------------------------------------------------------------------
// Private static methods. These are provided by the per-platform
// implementation files.
// -----------------------------------------------------------------------
static XMLMsgLoader* loadAMsgSet(const XMLCh* const msgDomain);
static XMLNetAccessor* makeNetAccessor();
static XMLTransService* makeTransService();
static void platformInit();
// -----------------------------------------------------------------------
// Private static data members
//
// fgInitFlag
// This is used to avoid multiple inits if the client code calls us
// more than once. They aren't supposed to, but some have trouble
// keeping up if they are COM objects and such.
// -----------------------------------------------------------------------
static bool fgInitFlag;
};
#endif
<commit_msg>Added two more 'panic' values, which were requested by folks who needed to report a couple more panic situations.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.4 2000/01/25 21:34:23 roddey
* Added two more 'panic' values, which were requested by folks who needed
* to report a couple more panic situations.
*
* Revision 1.3 2000/01/19 00:56:59 roddey
* Changes to get rid of dependence on old utils standard streams and to
* get rid of the fgLibLocation stuff.
*
* Revision 1.2 2000/01/12 00:16:22 roddey
* Changes to deal with multiply nested, relative pathed, entities and to deal
* with the new URL class changes.
*
* Revision 1.1.1.1 1999/11/09 01:04:55 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:11 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(PLATFORMUTILS_HPP)
#define PLATFORMUTILS_HPP
#include <util/XML4CDefs.hpp>
#include <util/XMLException.hpp>
#include <util/XMLUni.hpp>
class XMLMsgLoader;
class XMLNetAccessor;
class XMLTransService;
//
// Generate an exception for platform utitilities to throw when something
// goes awry.
//
const XMLCh gXMLPlatformUtilsException_Name[] =
{
chLatin_X, chLatin_M, chLatin_L, chLatin_P, chLatin_l, chLatin_a
, chLatin_t, chLatin_f, chLatin_o, chLatin_r, chLatin_m, chLatin_E
, chLatin_x, chLatin_c, chLatin_e, chLatin_p, chLatin_t, chLatin_i
, chLatin_o, chLatin_n, chNull
};
MakeXML4CException(XMLPlatformUtilsException, XMLUTIL_EXPORT)
class XMLUTIL_EXPORT XMLPlatformUtils
{
public :
// -----------------------------------------------------------------------
// Public types
// -----------------------------------------------------------------------
enum PanicReasons
{
Panic_NoTransService
, Panic_NoDefTranscoder
, Panic_CantFindLib
, Panic_UnknownMsgDomain
, Panic_CantLoadMsgDomain
, Panic_SynchronizationErr
, Panic_SystemInit
, PanicReasons_Count
};
// -----------------------------------------------------------------------
// Public, static data
//
// fgNetAccessor
// This is the network access implementation. This is provided by
// the per-platform driver, so each platform can choose what actual
// implementation it wants to use.
//
// fgTransService
// This is the transcoding service. This is provided by the per
// platform driver, so each platform can choose what implemenation
// it wants to use.
// -----------------------------------------------------------------------
static XMLNetAccessor* fgNetAccessor;
static XMLTransService* fgTransService;
// -----------------------------------------------------------------------
// Initialization method. This must be called first in any client code.
// -----------------------------------------------------------------------
static void Initialize();
// -----------------------------------------------------------------------
// The panic mechanism. If, during init, we cannot even get far enough
// along to get transcoding up or get message loading working, we call
// this.
//
// Each platform can implement it however they want. This method is
// expected to display something meaningful and end the process. The
// enum indicates why its being called, to allow the per-platform code
// to display something more specific if desired.
// -----------------------------------------------------------------------
static void panic
(
const PanicReasons reason
);
// -----------------------------------------------------------------------
// File methods
// -----------------------------------------------------------------------
static unsigned int curFilePos(FileHandle theFile);
static void closeFile(FileHandle theFile);
static unsigned int fileSize(FileHandle theFile);
static FileHandle openFile(const char* const fileName);
static FileHandle openFile(const XMLCh* const fileName);
static FileHandle openStdInHandle();
static unsigned int readFileBuffer
(
FileHandle theFile
, const unsigned int toRead
, XMLByte* const toFill
);
static void resetFile(FileHandle theFile);
// -----------------------------------------------------------------------
// File system methods
// -----------------------------------------------------------------------
static XMLCh* getFullPath(const XMLCh* const srcPath);
static bool isRelative(const XMLCh* const toCheck);
static XMLCh* weavePaths
(
const XMLCh* const basePath
, const XMLCh* const relativePath
);
// -----------------------------------------------------------------------
// Timing methods
// -----------------------------------------------------------------------
static unsigned long getCurrentMillis();
// -----------------------------------------------------------------------
// Mutex methods
// -----------------------------------------------------------------------
static void closeMutex(void* const mtxHandle);
static void lockMutex(void* const mtxHandle);
static void* makeMutex();
static void unlockMutex(void* const mtxHandle);
// -----------------------------------------------------------------------
// External message support
// -----------------------------------------------------------------------
static XMLMsgLoader* loadMsgSet(const XMLCh* const msgDomain);
// -----------------------------------------------------------------------
// Miscellaneous synchronization methods
// -----------------------------------------------------------------------
static void* compareAndSwap
(
void** toFill
, const void* const newValue
, const void* const toCompare
);
// -----------------------------------------------------------------------
// Atomic Increment and Decrement
//
// The function return value is positive if the result of the operation
// was positive. Zero if the result of the operation was zero. Negative
// if the result of the operation was negative. Except for the zero
// case, the value returned may differ from the actual result of the
// operation - only the sign and zero/nonzero state is guaranteed to be
// correct.
// -----------------------------------------------------------------------
static int atomicIncrement(int& location);
static int atomicDecrement(int& location);
private :
// -----------------------------------------------------------------------
// Private static methods. These are provided by the per-platform
// implementation files.
// -----------------------------------------------------------------------
static XMLMsgLoader* loadAMsgSet(const XMLCh* const msgDomain);
static XMLNetAccessor* makeNetAccessor();
static XMLTransService* makeTransService();
static void platformInit();
// -----------------------------------------------------------------------
// Private static data members
//
// fgInitFlag
// This is used to avoid multiple inits if the client code calls us
// more than once. They aren't supposed to, but some have trouble
// keeping up if they are COM objects and such.
// -----------------------------------------------------------------------
static bool fgInitFlag;
};
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <thread>
#include <cfloat>
#include <GLFW/glfw3.h>
#include "compiler.h"
#include "TCPServer.hpp"
#include "data.hpp"
float lastDeviceUpdateTime = 0;
float UpdateIntervalSeconds = 1;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
// glfw callbacks
static void error_callback(int error, const char* description)
{
fprintf(stderr, "GFWL Error: %s\n", description);
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
#pragma GCC diagnostic pop
#ifdef _WINDOWS
#include <tchar.h>
int wmain(int argc, _TCHAR* argv[]) {
#else
int main(int argc, char** argv) {
#endif
// defaults
unsigned int port = 60601;
// command line params
if (argc >= 2) {
port = atoi(argv[1]);
} else {
std::cout << "Serving at default port: " << port << std::endl;
std::cout << "call 'input-logger xxxxxx' to specify the port manually." << std::endl;
}
// glfw window setup
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Joystick Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
while (!glfwWindowShouldClose(window))
{
}
// setup networking
boost::asio::io_service io_service;
TCPServer server(io_service, port);
// run!
bool running = true;
while (running)
{
for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++)
{
if (glfwJoystickPresent(i)) {
int count;
const float* axis = glfwGetJoystickAxes(i, &count);
for (int j = 0; j < count; j++) {
std::cout << "stick: " << i << ", axis: " << j << ": " << axis[j];
}
}
}
// deschedule this thread to save some resources...
// time passed to the function is lower bound
std::this_thread::sleep_for(std::chrono::milliseconds(1));
running = running &&
!glfwWindowShouldClose(window)
&& !(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
return 0;
}
<commit_msg>polling works, builds with xcode<commit_after>#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <chrono>
#include <thread>
#include <cfloat>
#include <GLFW/glfw3.h>
#include "compiler.h"
#include "TCPServer.hpp"
#include "data.hpp"
float lastDeviceUpdateTime = 0;
float UpdateIntervalSeconds = 1;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
// glfw callbacks
static void error_callback(int error, const char* description)
{
fprintf(stderr, "GFWL Error: %s\n", description);
}
static void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
#pragma GCC diagnostic pop
#ifdef _WINDOWS
#include <tchar.h>
int wmain(int argc, _TCHAR* argv[]) {
#else
int main(int argc, char** argv) {
#endif
// defaults
unsigned int port = 60601;
// command line params
if (argc >= 2) {
port = atoi(argv[1]);
} else {
std::cout << "Serving at default port: " << port << std::endl;
std::cout << "call 'input-logger xxxxxx' to specify the port manually." << std::endl;
}
// glfw window setup
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if (!glfwInit())
exit(EXIT_FAILURE);
window = glfwCreateWindow(640, 480, "Joystick Test", NULL, NULL);
if (!window)
{
glfwTerminate();
exit(EXIT_FAILURE);
}
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
std::cout << "setting up server..." << std::endl;
// setup networking
boost::asio::io_service io_service;
TCPServer server(io_service, port);
// run!
bool running = true;
while (running)
{
for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++)
{
if (glfwJoystickPresent(i)) {
int count;
const float* axis = glfwGetJoystickAxes(i, &count);
for (int j = 0; j < count; j++) {
std::cout << "stick: " << i << ", axis: " << j << ": " << axis[j] << std:: endl;
}
}
}
// deschedule this thread to save some resources...
// time passed to the function is lower bound
std::this_thread::sleep_for(std::chrono::milliseconds(1));
running = running &&
!glfwWindowShouldClose(window)
&& !(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
exit(EXIT_SUCCESS);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* SimpleTimer.cpp
*
* SimpleTimer - A timer library for Arduino.
* Author: mromani@ottotecnica.com
* Copyright (c) 2010 OTTOTECNICA Italy
*
* Callback function parameters added & compiler warnings
* removed by Bill Knight <billk@rosw.com> 20March2017
*
* 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
*/
#include "Blynk/BlynkTimer.h"
// Select time function:
//static inline unsigned long elapsed() { return micros(); }
static inline unsigned long elapsed() { return millis(); }
SimpleTimer::SimpleTimer()
: numTimers (-1)
{
}
void SimpleTimer::init() {
unsigned long current_millis = elapsed();
for (int i = 0; i < MAX_TIMERS; i++) {
memset(&timer[i], 0, sizeof (timer_t));
timer[i].prev_millis = current_millis;
}
numTimers = 0;
}
void SimpleTimer::run() {
int i;
unsigned long current_millis;
// get current time
current_millis = elapsed();
for (i = 0; i < MAX_TIMERS; i++) {
timer[i].toBeCalled = DEFCALL_DONTRUN;
// no callback == no timer, i.e. jump over empty slots
if (timer[i].callback != NULL) {
// is it time to process this timer ?
// see http://arduino.cc/forum/index.php/topic,124048.msg932592.html#msg932592
if ((current_millis - timer[i].prev_millis) >= timer[i].delay) {
// update time
timer[i].prev_millis += timer[i].delay;
// check if the timer callback has to be executed
if (timer[i].enabled) {
// "run forever" timers must always be executed
if (timer[i].maxNumRuns == RUN_FOREVER) {
timer[i].toBeCalled = DEFCALL_RUNONLY;
}
// other timers get executed the specified number of times
else if (timer[i].numRuns < timer[i].maxNumRuns) {
timer[i].toBeCalled = DEFCALL_RUNONLY;
timer[i].numRuns++;
// after the last run, delete the timer
if (timer[i].numRuns >= timer[i].maxNumRuns) {
timer[i].toBeCalled = DEFCALL_RUNANDDEL;
}
}
}
}
}
}
for (i = 0; i < MAX_TIMERS; i++) {
if (timer[i].toBeCalled == DEFCALL_DONTRUN)
continue;
if (timer[i].hasParam)
(*(timer_callback_p)timer[i].callback)(timer[i].param);
else
(*(timer_callback)timer[i].callback)();
if (timer[i].toBeCalled == DEFCALL_RUNANDDEL)
deleteTimer(i);
}
}
// find the first available slot
// return -1 if none found
int SimpleTimer::findFirstFreeSlot() {
// all slots are used
if (numTimers >= MAX_TIMERS) {
return -1;
}
// return the first slot with no callback (i.e. free)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback == NULL) {
return i;
}
}
// no free slots found
return -1;
}
int SimpleTimer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n) {
int freeTimer;
if (numTimers < 0) {
init();
}
freeTimer = findFirstFreeSlot();
if (freeTimer < 0) {
return -1;
}
if (f == NULL) {
return -1;
}
timer[freeTimer].delay = d;
timer[freeTimer].callback = f;
timer[freeTimer].param = p;
timer[freeTimer].hasParam = h;
timer[freeTimer].maxNumRuns = n;
timer[freeTimer].enabled = true;
timer[freeTimer].prev_millis = elapsed();
numTimers++;
return freeTimer;
}
int SimpleTimer::setTimer(unsigned long d, timer_callback f, unsigned n) {
return setupTimer(d, (void *)f, NULL, false, n);
}
int SimpleTimer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n) {
return setupTimer(d, (void *)f, p, true, n);
}
int SimpleTimer::setInterval(unsigned long d, timer_callback f) {
return setupTimer(d, (void *)f, NULL, false, RUN_FOREVER);
}
int SimpleTimer::setInterval(unsigned long d, timer_callback_p f, void* p) {
return setupTimer(d, (void *)f, p, true, RUN_FOREVER);
}
int SimpleTimer::setTimeout(unsigned long d, timer_callback f) {
return setupTimer(d, (void *)f, NULL, false, RUN_ONCE);
}
int SimpleTimer::setTimeout(unsigned long d, timer_callback_p f, void* p) {
return setupTimer(d, (void *)f, p, true, RUN_ONCE);
}
bool SimpleTimer::changeInterval(unsigned numTimer, unsigned long d) {
if (numTimer >= MAX_TIMERS) {
return false;
}
// Updates interval of existing specified timer
if (timer[numTimer].callback != NULL) {
timer[numTimer].delay = d;
timer[numTimer].prev_millis = elapsed();
return true;
}
// false return for non-used numTimer, no callback
return false;
}
void SimpleTimer::deleteTimer(unsigned timerId) {
if (timerId >= MAX_TIMERS) {
return;
}
// nothing to delete if no timers are in use
if (numTimers == 0) {
return;
}
// don't decrease the number of timers if the
// specified slot is already empty
if (timer[timerId].callback != NULL) {
memset(&timer[timerId], 0, sizeof (timer_t));
timer[timerId].prev_millis = elapsed();
// update number of timers
numTimers--;
}
}
// function contributed by code@rowansimms.com
void SimpleTimer::restartTimer(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].prev_millis = elapsed();
}
bool SimpleTimer::isEnabled(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return false;
}
return timer[numTimer].enabled;
}
void SimpleTimer::enable(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = true;
}
void SimpleTimer::disable(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = false;
}
void SimpleTimer::enableAll() {
// Enable all timers with a callback assigned (used)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback != NULL) {
timer[i].enabled = true;
}
}
}
void SimpleTimer::disableAll() {
// Disable all timers with a callback assigned (used)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback != NULL) {
timer[i].enabled = false;
}
}
}
void SimpleTimer::toggle(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = !timer[numTimer].enabled;
}
unsigned SimpleTimer::getNumTimers() {
return numTimers;
}
<commit_msg>Added if statements for disable/enable-all (#323)<commit_after>/*
* SimpleTimer.cpp
*
* SimpleTimer - A timer library for Arduino.
* Author: mromani@ottotecnica.com
* Copyright (c) 2010 OTTOTECNICA Italy
*
* Callback function parameters added & compiler warnings
* removed by Bill Knight <billk@rosw.com> 20March2017
*
* 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
*/
#include "Blynk/BlynkTimer.h"
// Select time function:
//static inline unsigned long elapsed() { return micros(); }
static inline unsigned long elapsed() { return millis(); }
SimpleTimer::SimpleTimer()
: numTimers (-1)
{
}
void SimpleTimer::init() {
unsigned long current_millis = elapsed();
for (int i = 0; i < MAX_TIMERS; i++) {
memset(&timer[i], 0, sizeof (timer_t));
timer[i].prev_millis = current_millis;
}
numTimers = 0;
}
void SimpleTimer::run() {
int i;
unsigned long current_millis;
// get current time
current_millis = elapsed();
for (i = 0; i < MAX_TIMERS; i++) {
timer[i].toBeCalled = DEFCALL_DONTRUN;
// no callback == no timer, i.e. jump over empty slots
if (timer[i].callback != NULL) {
// is it time to process this timer ?
// see http://arduino.cc/forum/index.php/topic,124048.msg932592.html#msg932592
if ((current_millis - timer[i].prev_millis) >= timer[i].delay) {
// update time
timer[i].prev_millis += timer[i].delay;
// check if the timer callback has to be executed
if (timer[i].enabled) {
// "run forever" timers must always be executed
if (timer[i].maxNumRuns == RUN_FOREVER) {
timer[i].toBeCalled = DEFCALL_RUNONLY;
}
// other timers get executed the specified number of times
else if (timer[i].numRuns < timer[i].maxNumRuns) {
timer[i].toBeCalled = DEFCALL_RUNONLY;
timer[i].numRuns++;
// after the last run, delete the timer
if (timer[i].numRuns >= timer[i].maxNumRuns) {
timer[i].toBeCalled = DEFCALL_RUNANDDEL;
}
}
}
}
}
}
for (i = 0; i < MAX_TIMERS; i++) {
if (timer[i].toBeCalled == DEFCALL_DONTRUN)
continue;
if (timer[i].hasParam)
(*(timer_callback_p)timer[i].callback)(timer[i].param);
else
(*(timer_callback)timer[i].callback)();
if (timer[i].toBeCalled == DEFCALL_RUNANDDEL)
deleteTimer(i);
}
}
// find the first available slot
// return -1 if none found
int SimpleTimer::findFirstFreeSlot() {
// all slots are used
if (numTimers >= MAX_TIMERS) {
return -1;
}
// return the first slot with no callback (i.e. free)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback == NULL) {
return i;
}
}
// no free slots found
return -1;
}
int SimpleTimer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n) {
int freeTimer;
if (numTimers < 0) {
init();
}
freeTimer = findFirstFreeSlot();
if (freeTimer < 0) {
return -1;
}
if (f == NULL) {
return -1;
}
timer[freeTimer].delay = d;
timer[freeTimer].callback = f;
timer[freeTimer].param = p;
timer[freeTimer].hasParam = h;
timer[freeTimer].maxNumRuns = n;
timer[freeTimer].enabled = true;
timer[freeTimer].prev_millis = elapsed();
numTimers++;
return freeTimer;
}
int SimpleTimer::setTimer(unsigned long d, timer_callback f, unsigned n) {
return setupTimer(d, (void *)f, NULL, false, n);
}
int SimpleTimer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n) {
return setupTimer(d, (void *)f, p, true, n);
}
int SimpleTimer::setInterval(unsigned long d, timer_callback f) {
return setupTimer(d, (void *)f, NULL, false, RUN_FOREVER);
}
int SimpleTimer::setInterval(unsigned long d, timer_callback_p f, void* p) {
return setupTimer(d, (void *)f, p, true, RUN_FOREVER);
}
int SimpleTimer::setTimeout(unsigned long d, timer_callback f) {
return setupTimer(d, (void *)f, NULL, false, RUN_ONCE);
}
int SimpleTimer::setTimeout(unsigned long d, timer_callback_p f, void* p) {
return setupTimer(d, (void *)f, p, true, RUN_ONCE);
}
bool SimpleTimer::changeInterval(unsigned numTimer, unsigned long d) {
if (numTimer >= MAX_TIMERS) {
return false;
}
// Updates interval of existing specified timer
if (timer[numTimer].callback != NULL) {
timer[numTimer].delay = d;
timer[numTimer].prev_millis = elapsed();
return true;
}
// false return for non-used numTimer, no callback
return false;
}
void SimpleTimer::deleteTimer(unsigned timerId) {
if (timerId >= MAX_TIMERS) {
return;
}
// nothing to delete if no timers are in use
if (numTimers == 0) {
return;
}
// don't decrease the number of timers if the
// specified slot is already empty
if (timer[timerId].callback != NULL) {
memset(&timer[timerId], 0, sizeof (timer_t));
timer[timerId].prev_millis = elapsed();
// update number of timers
numTimers--;
}
}
// function contributed by code@rowansimms.com
void SimpleTimer::restartTimer(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].prev_millis = elapsed();
}
bool SimpleTimer::isEnabled(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return false;
}
return timer[numTimer].enabled;
}
void SimpleTimer::enable(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = true;
}
void SimpleTimer::disable(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = false;
}
void SimpleTimer::enableAll() {
// Enable all timers with a callback assigned (used)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback != NULL && numRuns[i] == RUN_FOREVER) {
timer[i].enabled = true;
}
}
}
void SimpleTimer::disableAll() {
// Disable all timers with a callback assigned (used)
for (int i = 0; i < MAX_TIMERS; i++) {
if (timer[i].callback != NULL && numRuns[i] == RUN_FOREVER) {
timer[i].enabled = false;
}
}
}
void SimpleTimer::toggle(unsigned numTimer) {
if (numTimer >= MAX_TIMERS) {
return;
}
timer[numTimer].enabled = !timer[numTimer].enabled;
}
unsigned SimpleTimer::getNumTimers() {
return numTimers;
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <optional>
#include <stack>
#include "VoronoiUtils.h"
#include "linearAlg2D.h"
#include "SVG.h"
namespace arachne
{
Point VoronoiUtils::p(const vd_t::vertex_type* node)
{
return Point(node->x() + 0, node->y() + 0); // gets rid of negative zero
}
bool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments, coord_t snap_dist)
{
if (cell.contains_point())
{
return shorterThen(p - getSourcePoint(cell, points, segments), snap_dist);
}
else
{
const Segment& segment = getSourceSegment(cell, points, segments);
return shorterThen(p - segment.from(), snap_dist) || shorterThen(p - segment.to(), snap_dist);
}
}
coord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
if (cell.contains_point())
{
return vSize(p - getSourcePoint(cell, points, segments));
}
else
{
const Segment& segment = getSourceSegment(cell, points, segments);
return sqrt(LinearAlg2D::getDist2FromLineSegment(segment.from(), p, segment.to()));
}
}
Point VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_point());
switch (cell.source_category())
{
case boost::polygon::SOURCE_CATEGORY_SINGLE_POINT:
return points[cell.source_index()];
break;
case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()].to();
break;
case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()].from();
break;
default:
assert(false && "getSourcePoint should only be called on point cells!\n");
break;
}
return points[cell.source_index()];
}
PolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_point());
assert(cell.source_category() != boost::polygon::SOURCE_CATEGORY_SINGLE_POINT);
switch (cell.source_category())
{
case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:
{
assert(cell.source_index() - points.size() < segments.size());
PolygonsPointIndex ret = segments[cell.source_index() - points.size()];
++ret;
return ret;
break;
}
case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:
{
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()];
break;
}
default:
assert(false && "getSourcePoint should only be called on point cells!\n");
break;
}
PolygonsPointIndex ret = segments[cell.source_index() - points.size()];
return ++ret;
}
const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_segment());
return segments[cell.source_index() - points.size()];
}
std::vector<Point> VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, float transitioning_angle)
{
std::vector<Point> discretized;
// x is distance of point projected on the segment ab
// xx is point projected on the segment ab
const Point a = segment.from();
const Point b = segment.to();
const Point ab = b - a;
const Point as = s - a;
const Point ae = e - a;
const coord_t ab_size = vSize(ab);
const coord_t sx = dot(as, ab) / ab_size;
const coord_t ex = dot(ae, ab) / ab_size;
const coord_t sxex = ex - sx;
const Point ap = p - a;
const coord_t px = dot(ap, ab) / ab_size;
const Point pxx = LinearAlg2D::getClosestOnLine(p, a, b);
const Point ppxx = pxx - p;
const coord_t d = vSize(ppxx);
const PointMatrix rot = PointMatrix(turn90CCW(ppxx));
if (d == 0)
{
discretized.emplace_back(s);
discretized.emplace_back(e);
return discretized;
}
const float marking_bound = atan(transitioning_angle * 0.5);
coord_t msx = - marking_bound * d; // projected marking_start
coord_t mex = marking_bound * d; // projected marking_end
const coord_t marking_start_end_h = msx * msx / (2 * d) + d / 2;
Point marking_start = rot.unapply(Point(msx, marking_start_end_h)) + pxx;
Point marking_end = rot.unapply(Point(mex, marking_start_end_h)) + pxx;
const int dir = (sx > ex) ? -1 : 1;
if (dir < 0)
{
std::swap(marking_start, marking_end);
std::swap(msx, mex);
}
bool add_marking_start = msx * dir > (sx - px) * dir && msx * dir < (ex - px) * dir;
bool add_marking_end = mex * dir > (sx - px) * dir && mex * dir < (ex - px) * dir;
const Point apex = rot.unapply(Point(0, d / 2)) + pxx;
bool add_apex = (sx - px) * dir < 0 && (ex - px) * dir > 0;
assert(!(add_marking_start && add_marking_end) || add_apex);
const coord_t step_count = static_cast<coord_t>(static_cast<float>(std::abs(ex - sx)) / approximate_step_size + 0.5);
discretized.emplace_back(s);
for (coord_t step = 1; step < step_count; step++)
{
const coord_t x = sx + sxex * step / step_count - px;
const coord_t y = x * x / (2 * d) + d / 2;
if (add_marking_start && msx * dir < x * dir)
{
discretized.emplace_back(marking_start);
add_marking_start = false;
}
if (add_apex && x * dir > 0)
{
discretized.emplace_back(apex);
add_apex = false; // only add the apex just before the
}
if (add_marking_end && mex * dir < x * dir)
{
discretized.emplace_back(marking_end);
add_marking_end = false;
}
const Point result = rot.unapply(Point(x, y)) + pxx;
discretized.emplace_back(result);
}
if (add_apex)
{
discretized.emplace_back(apex);
}
if (add_marking_end)
{
discretized.emplace_back(marking_end);
}
discretized.emplace_back(e);
return discretized;
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
void VoronoiUtils::discretize(
const Point& point,
const Segment& segment,
const coord_t max_dist,
std::vector<Point>* discretization) {
// Apply the linear transformation to move start point of the segment to
// the point with coordinates (0, 0) and the direction of the segment to
// coincide the positive direction of the x-axis.
Point segm_vec = segment.to() - segment.from();
coord_t sqr_segment_length = vSize2(segm_vec);
// Compute x-coordinates of the endpoints of the edge
// in the transformed space.
coord_t projection_start = sqr_segment_length *
get_point_projection((*discretization)[0], segment);
coord_t projection_end = sqr_segment_length *
get_point_projection((*discretization)[1], segment);
// Compute parabola parameters in the transformed space.
// Parabola has next representation:
// f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y).
Point point_vec = point - segment.from();
coord_t rot_x = dot(segm_vec, point_vec);
coord_t rot_y = cross(segm_vec, point_vec);
// Save the last point.
Point last_point = (*discretization)[1];
discretization->pop_back();
// Use stack to avoid recursion.
std::stack<coord_t> point_stack;
point_stack.push(projection_end);
Point cur(projection_start, parabola_y(projection_start, rot_x, rot_y));
// Adjust max_dist parameter in the transformed space.
const coord_t max_dist_transformed = max_dist * max_dist * sqr_segment_length;
while (!point_stack.empty()) {
Point new_(point_stack.top(), parabola_y(point_stack.top(), rot_x, rot_y));
Point new_vec = new_ - cur;
// Compute coordinates of the point of the parabola that is
// furthest from the current line segment.
coord_t mid_x = new_vec.Y * rot_y / new_vec.X + rot_x;
coord_t mid_y = parabola_y(mid_x, rot_x, rot_y);
Point mid_vec = Point(mid_x, mid_y) - cur;
// Compute maximum distance between the given parabolic arc
// and line segment that discretize it.
__int128 dist = cross(mid_vec, new_vec);
dist = dist * dist / vSize2(new_vec); // TODO overflows!!!
if (dist <= max_dist_transformed) {
// Distance between parabola and line segment is less than max_dist.
point_stack.pop();
coord_t inter_x = (segm_vec.X * new_.X - segm_vec.Y * new_.Y) /
sqr_segment_length + segment.from().X;
coord_t inter_y = (segm_vec.X * new_.Y + segm_vec.Y * new_.X) /
sqr_segment_length + segment.from().Y;
discretization->push_back(Point(inter_x, inter_y));
cur = new_;
} else {
point_stack.push(mid_x);
}
}
// Update last point.
discretization->back() = last_point;
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
coord_t VoronoiUtils::parabola_y(coord_t x, coord_t a, coord_t b) {
return ((x - a) * (x - a) + b * b) / (b + b);
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
double VoronoiUtils::get_point_projection(
const Point& point, const Segment& segment) {
Point segment_vec = segment.to() - segment.from();
Point point_vec = point - segment.from();
coord_t sqr_segment_length = vSize2(segment_vec);
coord_t vec_dot = dot(segment_vec, point_vec);
return static_cast<double>(vec_dot) / sqr_segment_length;
}
}//namespace arachne
<commit_msg>Brackets on new line<commit_after>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include <optional>
#include <stack>
#include "VoronoiUtils.h"
#include "linearAlg2D.h"
#include "SVG.h"
namespace arachne
{
Point VoronoiUtils::p(const vd_t::vertex_type* node)
{
return Point(node->x() + 0, node->y() + 0); // gets rid of negative zero
}
bool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments, coord_t snap_dist)
{
if (cell.contains_point())
{
return shorterThen(p - getSourcePoint(cell, points, segments), snap_dist);
}
else
{
const Segment& segment = getSourceSegment(cell, points, segments);
return shorterThen(p - segment.from(), snap_dist) || shorterThen(p - segment.to(), snap_dist);
}
}
coord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
if (cell.contains_point())
{
return vSize(p - getSourcePoint(cell, points, segments));
}
else
{
const Segment& segment = getSourceSegment(cell, points, segments);
return sqrt(LinearAlg2D::getDist2FromLineSegment(segment.from(), p, segment.to()));
}
}
Point VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_point());
switch (cell.source_category())
{
case boost::polygon::SOURCE_CATEGORY_SINGLE_POINT:
return points[cell.source_index()];
break;
case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()].to();
break;
case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()].from();
break;
default:
assert(false && "getSourcePoint should only be called on point cells!\n");
break;
}
return points[cell.source_index()];
}
PolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_point());
assert(cell.source_category() != boost::polygon::SOURCE_CATEGORY_SINGLE_POINT);
switch (cell.source_category())
{
case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:
{
assert(cell.source_index() - points.size() < segments.size());
PolygonsPointIndex ret = segments[cell.source_index() - points.size()];
++ret;
return ret;
break;
}
case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:
{
assert(cell.source_index() - points.size() < segments.size());
return segments[cell.source_index() - points.size()];
break;
}
default:
assert(false && "getSourcePoint should only be called on point cells!\n");
break;
}
PolygonsPointIndex ret = segments[cell.source_index() - points.size()];
return ++ret;
}
const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)
{
assert(cell.contains_segment());
return segments[cell.source_index() - points.size()];
}
std::vector<Point> VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, float transitioning_angle)
{
std::vector<Point> discretized;
// x is distance of point projected on the segment ab
// xx is point projected on the segment ab
const Point a = segment.from();
const Point b = segment.to();
const Point ab = b - a;
const Point as = s - a;
const Point ae = e - a;
const coord_t ab_size = vSize(ab);
const coord_t sx = dot(as, ab) / ab_size;
const coord_t ex = dot(ae, ab) / ab_size;
const coord_t sxex = ex - sx;
const Point ap = p - a;
const coord_t px = dot(ap, ab) / ab_size;
const Point pxx = LinearAlg2D::getClosestOnLine(p, a, b);
const Point ppxx = pxx - p;
const coord_t d = vSize(ppxx);
const PointMatrix rot = PointMatrix(turn90CCW(ppxx));
if (d == 0)
{
discretized.emplace_back(s);
discretized.emplace_back(e);
return discretized;
}
const float marking_bound = atan(transitioning_angle * 0.5);
coord_t msx = - marking_bound * d; // projected marking_start
coord_t mex = marking_bound * d; // projected marking_end
const coord_t marking_start_end_h = msx * msx / (2 * d) + d / 2;
Point marking_start = rot.unapply(Point(msx, marking_start_end_h)) + pxx;
Point marking_end = rot.unapply(Point(mex, marking_start_end_h)) + pxx;
const int dir = (sx > ex) ? -1 : 1;
if (dir < 0)
{
std::swap(marking_start, marking_end);
std::swap(msx, mex);
}
bool add_marking_start = msx * dir > (sx - px) * dir && msx * dir < (ex - px) * dir;
bool add_marking_end = mex * dir > (sx - px) * dir && mex * dir < (ex - px) * dir;
const Point apex = rot.unapply(Point(0, d / 2)) + pxx;
bool add_apex = (sx - px) * dir < 0 && (ex - px) * dir > 0;
assert(!(add_marking_start && add_marking_end) || add_apex);
const coord_t step_count = static_cast<coord_t>(static_cast<float>(std::abs(ex - sx)) / approximate_step_size + 0.5);
discretized.emplace_back(s);
for (coord_t step = 1; step < step_count; step++)
{
const coord_t x = sx + sxex * step / step_count - px;
const coord_t y = x * x / (2 * d) + d / 2;
if (add_marking_start && msx * dir < x * dir)
{
discretized.emplace_back(marking_start);
add_marking_start = false;
}
if (add_apex && x * dir > 0)
{
discretized.emplace_back(apex);
add_apex = false; // only add the apex just before the
}
if (add_marking_end && mex * dir < x * dir)
{
discretized.emplace_back(marking_end);
add_marking_end = false;
}
const Point result = rot.unapply(Point(x, y)) + pxx;
discretized.emplace_back(result);
}
if (add_apex)
{
discretized.emplace_back(apex);
}
if (add_marking_end)
{
discretized.emplace_back(marking_end);
}
discretized.emplace_back(e);
return discretized;
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
void VoronoiUtils::discretize(
const Point& point,
const Segment& segment,
const coord_t max_dist,
std::vector<Point>* discretization) {
// Apply the linear transformation to move start point of the segment to
// the point with coordinates (0, 0) and the direction of the segment to
// coincide the positive direction of the x-axis.
Point segm_vec = segment.to() - segment.from();
coord_t sqr_segment_length = vSize2(segm_vec);
// Compute x-coordinates of the endpoints of the edge
// in the transformed space.
coord_t projection_start = sqr_segment_length *
get_point_projection((*discretization)[0], segment);
coord_t projection_end = sqr_segment_length *
get_point_projection((*discretization)[1], segment);
// Compute parabola parameters in the transformed space.
// Parabola has next representation:
// f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y).
Point point_vec = point - segment.from();
coord_t rot_x = dot(segm_vec, point_vec);
coord_t rot_y = cross(segm_vec, point_vec);
// Save the last point.
Point last_point = (*discretization)[1];
discretization->pop_back();
// Use stack to avoid recursion.
std::stack<coord_t> point_stack;
point_stack.push(projection_end);
Point cur(projection_start, parabola_y(projection_start, rot_x, rot_y));
// Adjust max_dist parameter in the transformed space.
const coord_t max_dist_transformed = max_dist * max_dist * sqr_segment_length;
while (!point_stack.empty())
{
Point new_(point_stack.top(), parabola_y(point_stack.top(), rot_x, rot_y));
Point new_vec = new_ - cur;
// Compute coordinates of the point of the parabola that is
// furthest from the current line segment.
coord_t mid_x = new_vec.Y * rot_y / new_vec.X + rot_x;
coord_t mid_y = parabola_y(mid_x, rot_x, rot_y);
Point mid_vec = Point(mid_x, mid_y) - cur;
// Compute maximum distance between the given parabolic arc
// and line segment that discretize it.
__int128 dist = cross(mid_vec, new_vec);
dist = dist * dist / vSize2(new_vec); // TODO overflows!!!
if (dist <= max_dist_transformed) {
// Distance between parabola and line segment is less than max_dist.
point_stack.pop();
coord_t inter_x = (segm_vec.X * new_.X - segm_vec.Y * new_.Y) /
sqr_segment_length + segment.from().X;
coord_t inter_y = (segm_vec.X * new_.Y + segm_vec.Y * new_.X) /
sqr_segment_length + segment.from().Y;
discretization->push_back(Point(inter_x, inter_y));
cur = new_;
} else {
point_stack.push(mid_x);
}
}
// Update last point.
discretization->back() = last_point;
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
coord_t VoronoiUtils::parabola_y(coord_t x, coord_t a, coord_t b)
{
return ((x - a) * (x - a) + b * b) / (b + b);
}
// adapted from boost::polygon::voronoi_visual_utils.cpp
double VoronoiUtils::get_point_projection(
const Point& point, const Segment& segment) {
Point segment_vec = segment.to() - segment.from();
Point point_vec = point - segment.from();
coord_t sqr_segment_length = vSize2(segment_vec);
coord_t vec_dot = dot(segment_vec, point_vec);
return static_cast<double>(vec_dot) / sqr_segment_length;
}
}//namespace arachne
<|endoftext|>
|
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_FUTURE_HPP_
#define _QITYPE_FUTURE_HPP_
#include <vector>
#include <qi/config.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include <qi/eventloop.hpp>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
namespace qi {
template<typename T> struct FutureType
{
typedef T type;
};
// Hold a void* for Future<void>
template<> struct FutureType<void>
{
typedef void* type;
};
template <typename T> class FutureInterface;
template <typename T> class Future;
template <typename T> class FutureSync;
template <typename T> class Promise;
namespace detail {
template <typename T> class FutureState;
}
template <typename T>
class Future {
public:
typedef typename FutureType<T>::type ValueType;
Future()
: _p(new detail::FutureState<T>())
{
}
Future(const FutureSync<T>& b)
{
*this = b;
}
inline Future<T>& operator = (const FutureSync<T>& b)
{
b._sync = false;
_p = b._p;
return *this;
}
explicit Future<T>(const ValueType& v)
{
Promise<T> promise;
promise.setValue(v);
*this = promise.future();
}
inline const ValueType &value() const { return _p->value(); }
/** Wait for future, and return a default value in case of error.
* @param defaultVal the value to return in case of Future error
* @return the future value, or \p defaultVal if hasError() is true.
*/
inline const ValueType &valueWithDefault(const ValueType& defaultVal = ValueType()) const;
inline operator const ValueType&() const { return _p->value(); }
/** Wait for future to contain a value or an error
@param msecs: Maximum time to wait in milliseconds, 0 means forever and -1 means return immediately.
@return true if future contains a value or an error, false if timeout was reached
*/
inline bool wait(int msecs = 30000) const { return _p->wait(msecs); }
inline bool isReady() const { return _p->isReady(); }
inline bool hasError(int msecs=30000) const { return _p->hasError(msecs); }
inline const std::string &error() const { return _p->error(); }
inline FutureSync<T> sync()
{
return FutureSync<T>(*this);
};
public: //Signals
typedef boost::signals2::connection Connection;
typedef typename boost::signals2::signal<void (Future<T>)>::slot_type Slot;
inline Connection connect(const Slot& s) { return _p->connect(*this, s);}
inline bool disconnect(Connection i) { return _p->disconnect(i); }
//qi::Signal<void (qi::Future<T>)> &onResult() { return _p->_onResult; }
protected:
// C4251 needs to have dll-interface to be used by clients of class 'qi::Future<T>'
boost::shared_ptr< detail::FutureState<T> > _p;
friend class Promise<T>;
friend class FutureSync<T>;
};
template<typename T> class FutureSync: public Future<T>
{
public:
// This future cannot be set, so sync starts at false
FutureSync() : _sync(false) {}
FutureSync(const Future<T>& b)
: _sync(true)
{
*this = b;
this->_p = b._p;
}
FutureSync(const FutureSync<T>& b)
: _sync(true)
{
*this = b;
this->_p = b._p;
b._sync = false;
}
explicit FutureSync<T>(const typename Future<T>::ValueType& v)
: _sync(false)
{
Promise<T> promise;
promise.setValue(v);
*this = promise.future();
}
inline FutureSync<T>& operator = (const FutureSync<T>& b)
{
this->_p = b._p;
_sync = true;
b._sync = false;
return *this;
}
inline FutureSync<T>& operator = (const Future<T>& b)
{
this->_p = b._p;
_sync = true;
return *this;
}
~FutureSync()
{
if (_sync)
this->wait();
}
Future<T> async()
{
return *this;
}
private:
mutable bool _sync;
friend class Future<T>;
};
template <typename T>
class Promise {
public:
typedef typename FutureType<T>::type ValueType;
Promise() { }
void setValue(const ValueType &value) {
_f._p->setValue(_f, value);
}
void setError(const std::string &msg) {
_f._p->setError(_f, msg);
}
void reset() {
_f._p->reset();
}
Future<T> future() { return _f; }
protected:
Future<T> _f;
};
template <typename T>
qi::Future<T> makeFutureError(const std::string &value);
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#include <qi/details/future.hxx>
#endif // _QITYPE_FUTURE_HPP_
<commit_msg>Future, FutureSync: Optimize constructors.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QITYPE_FUTURE_HPP_
#define _QITYPE_FUTURE_HPP_
#include <vector>
#include <qi/config.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/signals2.hpp>
#include <qi/eventloop.hpp>
#ifdef _MSC_VER
# pragma warning( push )
# pragma warning( disable: 4251 )
#endif
namespace qi {
template<typename T> struct FutureType
{
typedef T type;
};
// Hold a void* for Future<void>
template<> struct FutureType<void>
{
typedef void* type;
};
template <typename T> class FutureInterface;
template <typename T> class Future;
template <typename T> class FutureSync;
template <typename T> class Promise;
namespace detail {
template <typename T> class FutureState;
}
template <typename T>
class Future {
public:
typedef typename FutureType<T>::type ValueType;
Future()
: _p(new detail::FutureState<T>())
{
}
Future(const FutureSync<T>& b)
: _p(b._p)
{
b._sync = false;
}
inline Future<T>& operator = (const FutureSync<T>& b)
{
b._sync = false;
_p = b._p;
return *this;
}
explicit Future<T>(const ValueType& v)
{
Promise<T> promise;
promise.setValue(v);
*this = promise.future();
}
inline const ValueType &value() const { return _p->value(); }
/** Wait for future, and return a default value in case of error.
* @param defaultVal the value to return in case of Future error
* @return the future value, or \p defaultVal if hasError() is true.
*/
inline const ValueType &valueWithDefault(const ValueType& defaultVal = ValueType()) const;
inline operator const ValueType&() const { return _p->value(); }
/** Wait for future to contain a value or an error
@param msecs: Maximum time to wait in milliseconds, 0 means forever and -1 means return immediately.
@return true if future contains a value or an error, false if timeout was reached
*/
inline bool wait(int msecs = 30000) const { return _p->wait(msecs); }
inline bool isReady() const { return _p->isReady(); }
inline bool hasError(int msecs=30000) const { return _p->hasError(msecs); }
inline const std::string &error() const { return _p->error(); }
inline FutureSync<T> sync()
{
return FutureSync<T>(*this);
};
public: //Signals
typedef boost::signals2::connection Connection;
typedef typename boost::signals2::signal<void (Future<T>)>::slot_type Slot;
inline Connection connect(const Slot& s) { return _p->connect(*this, s);}
inline bool disconnect(Connection i) { return _p->disconnect(i); }
//qi::Signal<void (qi::Future<T>)> &onResult() { return _p->_onResult; }
protected:
// C4251 needs to have dll-interface to be used by clients of class 'qi::Future<T>'
boost::shared_ptr< detail::FutureState<T> > _p;
friend class Promise<T>;
friend class FutureSync<T>;
};
template<typename T> class FutureSync: public Future<T>
{
public:
// This future cannot be set, so sync starts at false
FutureSync() : _sync(false) {}
FutureSync(const Future<T>& b)
: Future<T>(b)
, _sync(true)
{
}
FutureSync(const FutureSync<T>& b)
: Future<T>(b)
, _sync(true)
{
b._sync = false;
}
explicit FutureSync<T>(const typename Future<T>::ValueType& v)
: _sync(false)
{
Promise<T> promise;
promise.setValue(v);
*this = promise.future();
}
inline FutureSync<T>& operator = (const FutureSync<T>& b)
{
this->_p = b._p;
_sync = true;
b._sync = false;
return *this;
}
inline FutureSync<T>& operator = (const Future<T>& b)
{
this->_p = b._p;
_sync = true;
return *this;
}
~FutureSync()
{
if (_sync)
this->wait();
}
Future<T> async()
{
return *this;
}
private:
mutable bool _sync;
friend class Future<T>;
};
template <typename T>
class Promise {
public:
typedef typename FutureType<T>::type ValueType;
Promise() { }
void setValue(const ValueType &value) {
_f._p->setValue(_f, value);
}
void setError(const std::string &msg) {
_f._p->setError(_f, msg);
}
void reset() {
_f._p->reset();
}
Future<T> future() { return _f; }
protected:
Future<T> _f;
};
template <typename T>
qi::Future<T> makeFutureError(const std::string &value);
}
#ifdef _MSC_VER
# pragma warning( pop )
#endif
#include <qi/details/future.hxx>
#endif // _QITYPE_FUTURE_HPP_
<|endoftext|>
|
<commit_before>/*
This file is part of VROOM.
Copyright (c) 2015-2017, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "./input_parser.h"
// Helper to get optional array of coordinates.
inline optional_coords_t parse_coordinates(const rapidjson::Value& object,
const char* key) {
if (object.HasMember(key) and object[key].IsArray()) {
if (object[key].Size() < 2) {
throw custom_exception("Invalid coordinates array size.");
}
return optional_coords_t({object[key][0].GetDouble(),
object[key][1].GetDouble()});
}
else {
return boost::none;
}
}
input parse(const cl_args_t& cl_args) {
BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input.";
// Set relevant wrapper to retrieve the matrix and geometry.
std::unique_ptr<routing_io<distance_t>> routing_wrapper;
if (!cl_args.use_libosrm) {
// Use osrm-routed.
routing_wrapper =
std::make_unique<routed_wrapper>(cl_args.osrm_address,
cl_args.osrm_port,
cl_args.osrm_profile);
}
else {
#if LIBOSRM
// Use libosrm.
if (cl_args.osrm_profile.empty()) {
throw custom_exception("-l flag requires -m.");
}
routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);
#else
throw custom_exception("libosrm must be installed to use -l.");
#endif
}
// Custom input object embedding jobs, vehicles and matrix.
input input_data(std::move(routing_wrapper), cl_args.geometry);
// Input json object.
rapidjson::Document json_input;
// Parsing input string to populate the input object.
if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {
std::string error_msg =
std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +
" (offset: " + std::to_string(json_input.GetErrorOffset()) + ")";
throw custom_exception(error_msg);
}
// Checks required in any case.
if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray()) {
throw custom_exception("Incorrect jobs input.");
}
if (!json_input.HasMember("vehicles")
or !json_input["vehicles"].IsArray()
or json_input["vehicles"].Empty()) {
throw custom_exception("Incorrect vehicles input.");
}
if (!json_input["vehicles"][0].IsObject()) {
throw custom_exception("Ill-formed vehicle object.");
}
if (!json_input["vehicles"][0].HasMember("id")) {
throw custom_exception("Missing mandatory vehicle id.");
}
if (json_input["vehicles"].Size() > 1) {
throw custom_exception("Multiple vehicles are not supported (yet).");
}
// Switch input type: explicit matrix or using OSRM.
if (json_input.HasMember("matrix")) {
// Load custom matrix while checking if it is square.
rapidjson::SizeType matrix_size = json_input["matrix"].Size();
matrix<distance_t> matrix_input(matrix_size);
for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {
if (json_input["matrix"][i].Size() != matrix_size) {
throw custom_exception("Input matrix is not square.");
}
for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {
if (!json_input["matrix"][i][j].IsNumber()) {
throw custom_exception("Input matrix has a non-number entry.");
}
matrix_input[i][j] = json_input["matrix"][i][j].GetUint();
}
}
//Identify the necessary columns/rows from the loaded matrix
std::vector<index_t> necessary_indices;
index_t index_counter = 0;
// Check if vehicle has start_index or end_index.
boost::optional<index_t> start_index;
if (json_input["vehicles"][0].HasMember("start_index")) {
if (!json_input["vehicles"][0]["start_index"].IsNumber()) {
throw custom_exception("Vehicle start_index is not a number.");
}
start_index = json_input["vehicles"][0]["start_index"].GetUint();
if (matrix_size <= start_index.get()) {
throw custom_exception("Vehicle start_index does not match to matrix size.");
}
}
if (start_index) {
necessary_indices.push_back( start_index.get() );
start_index = index_counter++;
}
boost::optional<index_t> end_index;
if (json_input["vehicles"][0].HasMember("end_index")) {
if (!json_input["vehicles"][0]["end_index"].IsNumber()) {
throw custom_exception("Vehicle end_index is not a number.");
}
end_index = json_input["vehicles"][0]["end_index"].GetUint();
if (matrix_size <= end_index.get()) {
throw custom_exception("Vehicle end_index does not match to matrix size.");
}
}
if (end_index) {
necessary_indices.push_back( end_index.get() );
end_index = index_counter++;
}
// Add vehicle to input
input_data.add_vehicle(json_input["vehicles"][0]["id"].GetUint(),
parse_coordinates(json_input["vehicles"][0],
"start"),
parse_coordinates(json_input["vehicles"][0],
"end"),
start_index,
end_index);
// Add the jobs
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
if (!json_input["jobs"][i].IsObject()){
throw custom_exception("Ill-formed job object.");
}
if (!json_input["jobs"][i].HasMember("id")) {
throw custom_exception("Missing mandatory job id.");
}
if (!json_input["jobs"][i]["id"].IsNumber()) {
throw custom_exception("Job id is not a number.");
}
if (!json_input["jobs"][i].HasMember("location_index")) {
throw custom_exception("Missing mandatory job location_index.");
}
if (!json_input["jobs"][i]["location_index"].IsNumber()) {
throw custom_exception("Job location_index is not a number.");
}
if (matrix_size <= json_input["jobs"][i]["location_index"].GetUint()) {
throw custom_exception("Job location_index does not match to matrix size.");
}
necessary_indices.push_back( json_input["jobs"][i]["location_index"].GetUint() );
input_data.add_job(json_input["jobs"][i]["id"].GetUint(),
parse_coordinates(json_input["jobs"][i],"location"),
index_counter++);
}
//Extract the necessary columns/rows for the algorithm.
input_data._matrix = matrix_input.get_sub_matrix( necessary_indices );
}
else {
input_data.add_vehicle(json_input["vehicles"][0]["id"].GetUint(),
parse_coordinates(json_input["vehicles"][0],
"start"),
parse_coordinates(json_input["vehicles"][0],
"end"));
// Getting jobs.
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
if (!json_input["jobs"][i].IsObject()) {
throw custom_exception("Ill-formed job object.");
}
if (!json_input["jobs"][i].HasMember("location")) {
throw custom_exception("Missing mandatory job location.");
}
if (!json_input["jobs"][i].HasMember("id")) {
throw custom_exception("Missing mandatory job id.");
}
input_data.add_job(json_input["jobs"][i]["id"].GetUint(),
parse_coordinates(json_input["jobs"][i], "location"));
}
}
if (input_data._locations.size() <= 1) {
throw custom_exception("At least two locations required!");
}
return input_data;
}
<commit_msg>Add json validity checks. #61<commit_after>/*
This file is part of VROOM.
Copyright (c) 2015-2017, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include "./input_parser.h"
// Helper to get optional array of coordinates.
inline optional_coords_t parse_coordinates(const rapidjson::Value& object,
const char* key) {
if (object.HasMember(key) and object[key].IsArray()) {
if ((object[key].Size() < 2)
or !object[key][0].IsNumber()
or !object[key][1].IsNumber()) {
throw custom_exception("Invalid " + std::string(key) + " array.");
}
return optional_coords_t({object[key][0].GetDouble(),
object[key][1].GetDouble()});
}
else {
return boost::none;
}
}
input parse(const cl_args_t& cl_args) {
BOOST_LOG_TRIVIAL(info) << "[Loading] Parsing input.";
// Set relevant wrapper to retrieve the matrix and geometry.
std::unique_ptr<routing_io<distance_t>> routing_wrapper;
if (!cl_args.use_libosrm) {
// Use osrm-routed.
routing_wrapper =
std::make_unique<routed_wrapper>(cl_args.osrm_address,
cl_args.osrm_port,
cl_args.osrm_profile);
}
else {
#if LIBOSRM
// Use libosrm.
if (cl_args.osrm_profile.empty()) {
throw custom_exception("-l flag requires -m.");
}
routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);
#else
throw custom_exception("libosrm must be installed to use -l.");
#endif
}
// Custom input object embedding jobs, vehicles and matrix.
input input_data(std::move(routing_wrapper), cl_args.geometry);
// Input json object.
rapidjson::Document json_input;
// Parsing input string to populate the input object.
if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {
std::string error_msg =
std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +
" (offset: " + std::to_string(json_input.GetErrorOffset()) + ")";
throw custom_exception(error_msg);
}
// Main Checks for valid json input.
if (!json_input.HasMember("jobs") or !json_input["jobs"].IsArray()) {
throw custom_exception("Incorrect jobs input.");
}
if (!json_input.HasMember("vehicles")
or !json_input["vehicles"].IsArray()
or json_input["vehicles"].Empty()) {
throw custom_exception("Incorrect vehicles input.");
}
if (!json_input["vehicles"][0].IsObject()) {
throw custom_exception("Ill-formed vehicle object.");
}
if (!json_input["vehicles"][0].HasMember("id")
or !json_input["vehicles"][0]["id"].IsUint()) {
throw custom_exception("Invalid vehicle id.");
}
if (json_input["vehicles"].Size() > 1) {
throw custom_exception("Multiple vehicles are not supported (yet).");
}
// Switch input type: explicit matrix or using OSRM.
if (json_input.HasMember("matrix")) {
if (!json_input["matrix"].IsArray()) {
throw custom_exception("Invalid matrix.");
}
// Load custom matrix while checking if it is square.
rapidjson::SizeType matrix_size = json_input["matrix"].Size();
matrix<distance_t> matrix_input(matrix_size);
for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {
if (!json_input["matrix"][i].IsArray()
or (json_input["matrix"][i].Size() != matrix_size)) {
throw custom_exception("Input matrix is not square.");
}
for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {
if (!json_input["matrix"][i][j].IsUint()) {
throw custom_exception("Input matrix has a non-number entry.");
}
matrix_input[i][j] = json_input["matrix"][i][j].GetUint();
}
}
//Identify the necessary columns/rows from the loaded matrix
std::vector<index_t> necessary_indices;
index_t index_counter = 0;
// Check if vehicle has start_index or end_index.
boost::optional<index_t> start_index;
if (json_input["vehicles"][0].HasMember("start_index")) {
if (!json_input["vehicles"][0]["start_index"].IsUint()) {
throw custom_exception("Vehicle start_index is not a number.");
}
start_index = json_input["vehicles"][0]["start_index"].GetUint();
if (matrix_size <= start_index.get()) {
throw custom_exception("Vehicle start_index does not match to matrix size.");
}
}
if (start_index) {
necessary_indices.push_back( start_index.get() );
start_index = index_counter++;
}
boost::optional<index_t> end_index;
if (json_input["vehicles"][0].HasMember("end_index")) {
if (!json_input["vehicles"][0]["end_index"].IsUint()) {
throw custom_exception("Vehicle end_index is not a number.");
}
end_index = json_input["vehicles"][0]["end_index"].GetUint();
if (matrix_size <= end_index.get()) {
throw custom_exception("Vehicle end_index does not match to matrix size.");
}
}
if (end_index) {
necessary_indices.push_back( end_index.get() );
end_index = index_counter++;
}
// Add vehicle to input
input_data.add_vehicle(json_input["vehicles"][0]["id"].GetUint(),
parse_coordinates(json_input["vehicles"][0],
"start"),
parse_coordinates(json_input["vehicles"][0],
"end"),
start_index,
end_index);
// Add the jobs
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
if (!json_input["jobs"][i].IsObject()) {
throw custom_exception("Ill-formed job object.");
}
if (!json_input["jobs"][i].HasMember("id")
or !json_input["jobs"][i]["id"].IsUint()) {
throw custom_exception("Invalid job id.");
}
if (!json_input["jobs"][i].HasMember("location_index")
or !json_input["jobs"][i]["location_index"].IsUint()) {
throw custom_exception("Invalid job location_index.");
}
if (matrix_size <= json_input["jobs"][i]["location_index"].GetUint()) {
throw custom_exception("Job location_index does not match to matrix size.");
}
necessary_indices.push_back( json_input["jobs"][i]["location_index"].GetUint() );
input_data.add_job(json_input["jobs"][i]["id"].GetUint(),
parse_coordinates(json_input["jobs"][i],"location"),
index_counter++);
}
//Extract the necessary columns/rows for the algorithm.
input_data._matrix = matrix_input.get_sub_matrix( necessary_indices );
}
else {
input_data.add_vehicle(json_input["vehicles"][0]["id"].GetUint(),
parse_coordinates(json_input["vehicles"][0],
"start"),
parse_coordinates(json_input["vehicles"][0],
"end"));
// Getting jobs.
for (rapidjson::SizeType i = 0; i < json_input["jobs"].Size(); ++i) {
if (!json_input["jobs"][i].IsObject()) {
throw custom_exception("Ill-formed job object.");
}
if (!json_input["jobs"][i].HasMember("location")
or !json_input["jobs"][i]["location"].IsArray()) {
throw custom_exception("Invalid job location.");
}
if (!json_input["jobs"][i].HasMember("id")
or !json_input["jobs"][i]["id"].IsUint()) {
throw custom_exception("Invalid job id.");
}
input_data.add_job(json_input["jobs"][i]["id"].GetUint(),
parse_coordinates(json_input["jobs"][i], "location"));
}
}
if (input_data._locations.size() <= 1) {
throw custom_exception("At least two locations required!");
}
return input_data;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestAreaSelections.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
// This tests vtkHardwareSelector, vtkExtractSelectedFrustum,
// vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkInteractorStyleRubberBandPick.h"
#include "vtkCallbackCommand.h"
#include "vtkHardwareSelector.h"
#include "vtkSelection.h"
#include "vtkExtractSelectedPolyDataIds.h"
#include "vtkIdTypeArray.h"
#include "vtkRenderedAreaPicker.h"
#include "vtkCamera.h"
#include "vtkImageMandelbrotSource.h"
#include "vtkImageActor.h"
#include "vtkExtractSelectedFrustum.h"
#include "vtkDataSetMapper.h"
#include "vtkSmartPointer.h"
#include "vtkDataSetReader.h"
vtkSmartPointer<vtkRenderer> renderer;
vtkSmartPointer<vtkSphereSource> SS1;
vtkSmartPointer<vtkDataSetMapper> sMap;
vtkSmartPointer<vtkPolyData> emptyPD;
#define MY_CREATE_NEW(class, variable)\
vtkSmartPointer<class> variable = vtkSmartPointer<class>::New();
static void EndPick(vtkObject *vtkNotUsed( caller ),
unsigned long vtkNotUsed(eventId),
void *, void *)
{
MY_CREATE_NEW(vtkHardwareSelector, sel);
sel->SetRenderer(renderer);
double x0 = renderer->GetPickX1();
double y0 = renderer->GetPickY1();
double x1 = renderer->GetPickX2();
double y1 = renderer->GetPickY2();
sel->SetArea(static_cast<int>(x0),static_cast<int>(y0),static_cast<int>(x1),
static_cast<int>(y1));
vtkSmartPointer<vtkSelection> res;
res.TakeReference(sel->Select());
if (!res)
{
cerr << "Selection not supported." << endl;
return;
}
/*
cerr << "x0 " << x0 << " y0 " << y0 << "\t";
cerr << "x1 " << x1 << " y1 " << y1 << endl;
vtkIdTypeArray *a = vtkIdTypeArray::New();
sel->GetSelectedIds(a);
cerr << "numhits = " << a->GetNumberOfTuples() << endl;
sel->PrintSelectedIds(a);
a->Delete();
*/
vtkSelection *cellids = res->GetChild(0);
MY_CREATE_NEW(vtkExtractSelectedPolyDataIds, extr);
if (cellids)
{
extr->SetInput(0, SS1->GetOutput());
extr->SetInput(1, cellids);
extr->Update();
sMap->SetInput(extr->GetOutput());
}
else
{
cerr << "Empty color buffer selection -" << endl;
cerr << "Check display color depth. Must be at least 24 bit." << endl;
sMap->SetInput(emptyPD);
}
}
int TestAreaSelections(int argc, char* argv[])
{
// Standard rendering classes
renderer = vtkSmartPointer<vtkRenderer>::New();
MY_CREATE_NEW(vtkRenderWindow, renWin);
renWin->AddRenderer(renderer);
MY_CREATE_NEW(vtkRenderWindowInteractor, iren);
iren->SetRenderWindow(renWin);
//set up the view
renderer->GetActiveCamera()->SetPosition( 1.5, -0.75, 7);
renderer->GetActiveCamera()->SetFocalPoint(1.5, -0.75, 0);
renderer->GetActiveCamera()->SetViewUp( 0, 1, 0);
renderer->SetBackground(0.0,0.0,0.0);
renWin->SetSize(300,300);
//use the rubber band pick interactor style
vtkRenderWindowInteractor* rwi = renWin->GetInteractor();
MY_CREATE_NEW(vtkInteractorStyleRubberBandPick, rbp);
rwi->SetInteractorStyle(rbp);
MY_CREATE_NEW(vtkRenderedAreaPicker, areaPicker);
rwi->SetPicker(areaPicker);
////////////////////////////////////////////////////////////
//Create a unstructured grid data source to test FrustumExtractor with.
MY_CREATE_NEW(vtkDataSetReader, reader);
char *cfname=vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/SampleStructGrid.vtk");
reader->SetFileName(cfname);
MY_CREATE_NEW(vtkDataSetMapper, map1);
map1->SetInput(reader->GetOutput());
MY_CREATE_NEW(vtkActor, act1);
act1->SetMapper(map1);
act1->PickableOff(); //prevents the visible cell selector from trying
renderer->AddActor(act1);
//frustum extractor works on geometry and doesn't care about pickability
MY_CREATE_NEW(vtkExtractSelectedFrustum, extractor);
extractor->SetInputConnection(reader->GetOutputPort());
extractor->PreserveTopologyOff();
extractor->SetFrustum(areaPicker->GetFrustum());
MY_CREATE_NEW(vtkDataSetMapper, eMap);
eMap->SetInput(vtkDataSet::SafeDownCast(extractor->GetOutput()));
MY_CREATE_NEW(vtkActor, eAct);
eAct->SetPosition(2,0,0);
eAct->SetMapper(eMap);
eAct->PickableOff();
renderer->AddActor(eAct);
////////////////////////////////////////////////////////////
emptyPD = vtkSmartPointer<vtkPolyData>::New();
int res = 20;
SS1 = vtkSmartPointer<vtkSphereSource>::New();
SS1->SetThetaResolution(res);
SS1->SetPhiResolution(res);
SS1->SetRadius(0.5);
SS1->SetCenter(0.5,-1.5,0);
MY_CREATE_NEW(vtkPolyDataMapper, map2);
map2->SetInput(SS1->GetOutput());
MY_CREATE_NEW(vtkActor, act2);
act2->SetMapper(map2);
act2->PickableOn(); //lets the HardwareSelector select in it
renderer->AddActor(act2);
sMap = vtkSmartPointer<vtkDataSetMapper>::New();
sMap->SetInput(SS1->GetOutput());
MY_CREATE_NEW(vtkActor, sAct);
sAct->SetMapper(sMap);
sAct->SetPosition(2,0,0);
sAct->PickableOff();
renderer->AddActor(sAct);
//pass pick events to the HardwareSelector
MY_CREATE_NEW(vtkCallbackCommand, cbc);
cbc->SetCallback(EndPick);
cbc->SetClientData(renderer);
rwi->AddObserver(vtkCommand::EndPickEvent,cbc);
////////////////////////////////////////////////////////////
//run the test
renWin->Render();
areaPicker->AreaPick(51,78,82,273,renderer);
EndPick(NULL, 0, NULL, NULL);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
delete [] cfname;
return !retVal;
}
<commit_msg>BUG: Pass the test if hardware does not support selection.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestAreaSelections.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/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 notice for more information.
=========================================================================*/
// This tests vtkHardwareSelector, vtkExtractSelectedFrustum,
// vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick.
//
// The command line arguments are:
// -I => run in interactive mode; unless this is used, the program will
// not allow interaction and exit
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkInteractorStyleRubberBandPick.h"
#include "vtkCallbackCommand.h"
#include "vtkHardwareSelector.h"
#include "vtkSelection.h"
#include "vtkExtractSelectedPolyDataIds.h"
#include "vtkIdTypeArray.h"
#include "vtkRenderedAreaPicker.h"
#include "vtkCamera.h"
#include "vtkImageMandelbrotSource.h"
#include "vtkImageActor.h"
#include "vtkExtractSelectedFrustum.h"
#include "vtkDataSetMapper.h"
#include "vtkSmartPointer.h"
#include "vtkDataSetReader.h"
vtkSmartPointer<vtkRenderer> renderer;
vtkSmartPointer<vtkSphereSource> SS1;
vtkSmartPointer<vtkDataSetMapper> sMap;
vtkSmartPointer<vtkPolyData> emptyPD;
#define MY_CREATE_NEW(class, variable)\
vtkSmartPointer<class> variable = vtkSmartPointer<class>::New();
static void EndPick(vtkObject *vtkNotUsed( caller ),
unsigned long vtkNotUsed(eventId),
void *, void *)
{
MY_CREATE_NEW(vtkHardwareSelector, sel);
sel->SetRenderer(renderer);
double x0 = renderer->GetPickX1();
double y0 = renderer->GetPickY1();
double x1 = renderer->GetPickX2();
double y1 = renderer->GetPickY2();
sel->SetArea(static_cast<int>(x0),static_cast<int>(y0),static_cast<int>(x1),
static_cast<int>(y1));
vtkSmartPointer<vtkSelection> res;
res.TakeReference(sel->Select());
if (!res)
{
cerr << "Selection not supported." << endl;
return;
}
/*
cerr << "x0 " << x0 << " y0 " << y0 << "\t";
cerr << "x1 " << x1 << " y1 " << y1 << endl;
vtkIdTypeArray *a = vtkIdTypeArray::New();
sel->GetSelectedIds(a);
cerr << "numhits = " << a->GetNumberOfTuples() << endl;
sel->PrintSelectedIds(a);
a->Delete();
*/
vtkSelection *cellids = res->GetChild(0);
MY_CREATE_NEW(vtkExtractSelectedPolyDataIds, extr);
if (cellids)
{
extr->SetInput(0, SS1->GetOutput());
extr->SetInput(1, cellids);
extr->Update();
sMap->SetInput(extr->GetOutput());
}
else
{
cerr << "Empty color buffer selection -" << endl;
cerr << "Check display color depth. Must be at least 24 bit." << endl;
sMap->SetInput(emptyPD);
}
}
int TestAreaSelections(int argc, char* argv[])
{
// Standard rendering classes
renderer = vtkSmartPointer<vtkRenderer>::New();
MY_CREATE_NEW(vtkRenderWindow, renWin);
renWin->AddRenderer(renderer);
MY_CREATE_NEW(vtkRenderWindowInteractor, iren);
iren->SetRenderWindow(renWin);
//set up the view
renderer->GetActiveCamera()->SetPosition( 1.5, -0.75, 7);
renderer->GetActiveCamera()->SetFocalPoint(1.5, -0.75, 0);
renderer->GetActiveCamera()->SetViewUp( 0, 1, 0);
renderer->SetBackground(0.0,0.0,0.0);
renWin->SetSize(300,300);
//use the rubber band pick interactor style
vtkRenderWindowInteractor* rwi = renWin->GetInteractor();
MY_CREATE_NEW(vtkInteractorStyleRubberBandPick, rbp);
rwi->SetInteractorStyle(rbp);
MY_CREATE_NEW(vtkRenderedAreaPicker, areaPicker);
rwi->SetPicker(areaPicker);
////////////////////////////////////////////////////////////
//Create a unstructured grid data source to test FrustumExtractor with.
MY_CREATE_NEW(vtkDataSetReader, reader);
char *cfname=vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/SampleStructGrid.vtk");
reader->SetFileName(cfname);
delete [] cfname;
MY_CREATE_NEW(vtkDataSetMapper, map1);
map1->SetInput(reader->GetOutput());
MY_CREATE_NEW(vtkActor, act1);
act1->SetMapper(map1);
act1->PickableOff(); //prevents the visible cell selector from trying
renderer->AddActor(act1);
//frustum extractor works on geometry and doesn't care about pickability
MY_CREATE_NEW(vtkExtractSelectedFrustum, extractor);
extractor->SetInputConnection(reader->GetOutputPort());
extractor->PreserveTopologyOff();
extractor->SetFrustum(areaPicker->GetFrustum());
MY_CREATE_NEW(vtkDataSetMapper, eMap);
eMap->SetInput(vtkDataSet::SafeDownCast(extractor->GetOutput()));
MY_CREATE_NEW(vtkActor, eAct);
eAct->SetPosition(2,0,0);
eAct->SetMapper(eMap);
eAct->PickableOff();
renderer->AddActor(eAct);
////////////////////////////////////////////////////////////
emptyPD = vtkSmartPointer<vtkPolyData>::New();
int res = 20;
SS1 = vtkSmartPointer<vtkSphereSource>::New();
SS1->SetThetaResolution(res);
SS1->SetPhiResolution(res);
SS1->SetRadius(0.5);
SS1->SetCenter(0.5,-1.5,0);
MY_CREATE_NEW(vtkPolyDataMapper, map2);
map2->SetInput(SS1->GetOutput());
MY_CREATE_NEW(vtkActor, act2);
act2->SetMapper(map2);
act2->PickableOn(); //lets the HardwareSelector select in it
renderer->AddActor(act2);
sMap = vtkSmartPointer<vtkDataSetMapper>::New();
sMap->SetInput(SS1->GetOutput());
MY_CREATE_NEW(vtkActor, sAct);
sAct->SetMapper(sMap);
sAct->SetPosition(2,0,0);
sAct->PickableOff();
renderer->AddActor(sAct);
//pass pick events to the HardwareSelector
MY_CREATE_NEW(vtkCallbackCommand, cbc);
cbc->SetCallback(EndPick);
cbc->SetClientData(renderer);
rwi->AddObserver(vtkCommand::EndPickEvent,cbc);
////////////////////////////////////////////////////////////
//run the test
renWin->Render();
int rgba[4];
renWin->GetColorBufferSizes(rgba);
if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8)
{
cout <<"Color buffer depth must be atleast 8 bit. Currently: "
<< rgba[0] << ", " << rgba[1] << ", " << rgba[2] << endl;
return 0;
}
areaPicker->AreaPick(51,78,82,273,renderer);
EndPick(NULL, 0, NULL, NULL);
renWin->Render();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
// Cleanup
return !retVal;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#define HEIGHT 50
#define WIDTH 50
#define UPDATELENGTH 150000
int board[HEIGHT][WIDTH];
int weightedarray[10] = {0,0,0,0,0,0,0,0,1};
void genBoard(int (board)[HEIGHT][WIDTH]) {
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
board[x][y] = weightedarray[rand() % 10];
}
}
}
void copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) {
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
newB[x][y] = oldB[x][y];
}
}
}
void updateBoard(int (board)[HEIGHT][WIDTH]) {
int next_board[HEIGHT][WIDTH];
copyBoard(next_board, board);
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
if ((x == 0 || x == HEIGHT) ||
(y == 0 || y == WIDTH)) {
continue;
}
int aliveN = 0;
int deadN = 0;
if (!board[x-1][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x-1][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x-1][y]) {
deadN++;
} else {
aliveN++;
}
/*
Rules
=====
1. Any live cell with fewer than two live neighbours
dies, as if caused by under-population.
2. Any live cell with two or three live neighbours lives
on to the next generation.
3. Any live cell with more than three live neighbours
dies, as if by overcrowding.
4. Any dead cell with exactly three live neighbours
becomes a live cell, as if by reproduction.
*/
if ((board[x][y] && aliveN < 2)) {
next_board[x][y] = 0;
continue;
}
if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3)))
continue;
if ((board[x][y]) && (aliveN > 3)) {
next_board[x][y] = 0;
continue;
}
if ((!board[x][y]) && (aliveN == 3)) {
next_board[x][y] = 1;
continue;
}
}
}
copyBoard(board, next_board);
}
void drawBoard(int (board)[HEIGHT][WIDTH]) {
std::cout << "\033[2J\033[1;1H";
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
if (board[x][y] == 0) {
std::cout << ".";
} else {
std::cout << "*";
}
}
std::cout << std::endl;
}
}
int main() {
genBoard(board);
while (1) {
updateBoard(board);
drawBoard(board);
usleep(UPDATELENGTH);
}
return 0;
}
<commit_msg>Changed gol weighting<commit_after>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#define HEIGHT 50
#define WIDTH 50
#define UPDATELENGTH 150000
int board[HEIGHT][WIDTH];
int weightedarray[10] = {0,0,0,0,0,0,0,1,1};
void genBoard(int (board)[HEIGHT][WIDTH]) {
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
board[x][y] = weightedarray[rand() % 10];
}
}
}
void copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) {
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
newB[x][y] = oldB[x][y];
}
}
}
void updateBoard(int (board)[HEIGHT][WIDTH]) {
int next_board[HEIGHT][WIDTH];
copyBoard(next_board, board);
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
if ((x == 0 || x == HEIGHT) ||
(y == 0 || y == WIDTH)) {
continue;
}
int aliveN = 0;
int deadN = 0;
if (!board[x-1][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y+1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y]) {
deadN++;
} else {
aliveN++;
}
if (!board[x+1][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x-1][y-1]) {
deadN++;
} else {
aliveN++;
}
if (!board[x-1][y]) {
deadN++;
} else {
aliveN++;
}
/*
Rules
=====
1. Any live cell with fewer than two live neighbours
dies, as if caused by under-population.
2. Any live cell with two or three live neighbours lives
on to the next generation.
3. Any live cell with more than three live neighbours
dies, as if by overcrowding.
4. Any dead cell with exactly three live neighbours
becomes a live cell, as if by reproduction.
*/
if ((board[x][y] && aliveN < 2)) {
next_board[x][y] = 0;
continue;
}
if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3)))
continue;
if ((board[x][y]) && (aliveN > 3)) {
next_board[x][y] = 0;
continue;
}
if ((!board[x][y]) && (aliveN == 3)) {
next_board[x][y] = 1;
continue;
}
}
}
copyBoard(board, next_board);
}
void drawBoard(int (board)[HEIGHT][WIDTH]) {
std::cout << "\033[2J\033[1;1H";
for (int x = 0; x < HEIGHT; ++x) {
for (int y = 0; y < WIDTH; ++y) {
if (board[x][y] == 0) {
std::cout << ".";
} else {
std::cout << "*";
}
}
std::cout << std::endl;
}
}
int main() {
genBoard(board);
while (1) {
updateBoard(board);
drawBoard(board);
usleep(UPDATELENGTH);
}
return 0;
}
<|endoftext|>
|
<commit_before>// @(#)root/ged:$Name: $:$Id: TStylePreview.cxx,v 1.0 2005/09/08
// Author: Denis Favre-Miville 08/09/05
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStylePreview //
// //
// This class may be used to preview the result of applying a style //
// to a canvas. The result is shown on a clone of the object, //
// in a different shown over the initial canvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStylePreview.h"
#include "TStyleManager.h"
#include <TCanvas.h>
#include <TRootEmbeddedCanvas.h>
#include <TStyle.h>
ClassImp(TStylePreview)
//______________________________________________________________________________
TStylePreview::TStylePreview(const TGWindow *p, TStyle *style,
TVirtualPad *currentPad)
: TGTransientFrame(0, p)
{
// Constructor. Create a new window and draw a clone of
// currentPad->GetCanvas() in it, using the style 'style'.
// Thanks to that method, one can have a preview of any
// style with any object.
fPad = 0;
// Create the main window.
SetWindowName("Style Manager's Preview");
SetCleanup(kNoCleanup);
DontCallClose();
// Create the trash lists to have an effective deletion of every object.
fTrashListLayout = new TList();
// Create the layouts and add them to the layout trash list.
TGLayoutHints *layoutXY = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);
fTrashListLayout->Add(layoutXY);
// Create a canvas for the preview.
fEcan = new TRootEmbeddedCanvas("TSMPreviewCanvas", this, 10, 10);
AddFrame(fEcan, layoutXY);
// Draw the preview.
Update(style, currentPad);
// Map main frame.
MapTheWindow();
// No modifications allowed in the preview.
fEcan->GetCanvas()->SetEditable(kFALSE);
fEcan->GetCanvas()->SetBit(kNoContextMenu);
}
//______________________________________________________________________________
TStylePreview::~TStylePreview()
{
// Destructor.
// Delete all the widgets created in this class.
delete fEcan;
// Delete all the layouts.
TObject *obj1;
TObject *obj2;
obj1 = fTrashListLayout->First();
while (obj1) {
obj2 = fTrashListLayout->After(obj1);
fTrashListLayout->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListLayout;
}
//______________________________________________________________________________
void TStylePreview::Update(TStyle *style, TVirtualPad *pad)
{
// Update the preview, with possibly another style and another object
// than previously.
TCanvas *c;
if (pad != fPad) {
delete fEcan->GetCanvas();
fEcan->AdoptCanvas(new TCanvas("TSMPreviewCanvas", 10, 10,
fEcan->GetCanvasWindowId()));
c = fEcan->GetCanvas();
gROOT->SetSelectedPad(c);
pad->GetCanvas()->DrawClonePad();
gROOT->SetSelectedPad(pad);
fPad = pad;
}
// Apply the 'style' to the clone of 'pad'.
c = fEcan->GetCanvas();
TStyle *tmpStyle = gStyle;
gStyle = style;
c->UseCurrentStyle();
gStyle = tmpStyle;
c->Modified();
c->Update();
}
//______________________________________________________________________________
void TStylePreview::MapTheWindow()
{
// Initialize the layout algorithm.
MapSubwindows();
TCanvas *c = fPad->GetCanvas();
UInt_t w = c->GetWindowWidth();
UInt_t h = c->GetWindowHeight() - 24;
UInt_t x = (UInt_t) c->GetWindowTopX() + 60;
UInt_t y = (UInt_t) c->GetWindowTopY() + 100;
MoveResize(x, y, w, h);
SetWMPosition(x, y);
MapWindow();
}
//______________________________________________________________________________
TCanvas *TStylePreview::GetMainCanvas()
{
// return pointer to the selected canvas.
return fEcan->GetCanvas();
}
<commit_msg>From Ilka: - fix of preview window wrong width and height when the user interface around the canvas window were activated (editor, toolbar, status bar).<commit_after>// @(#)root/ged:$Name: $:$Id: TStylePreview.cxx,v 1.0 2005/09/08
// Author: Denis Favre-Miville 08/09/05
/*************************************************************************
* Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TStylePreview //
// //
// This class may be used to preview the result of applying a style //
// to a canvas. The result is shown on a clone of the object, //
// in a different shown over the initial canvas. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TStylePreview.h"
#include "TStyleManager.h"
#include <TCanvas.h>
#include <TRootEmbeddedCanvas.h>
#include <TStyle.h>
ClassImp(TStylePreview)
//______________________________________________________________________________
TStylePreview::TStylePreview(const TGWindow *p, TStyle *style,
TVirtualPad *currentPad)
: TGTransientFrame(0, p)
{
// Constructor. Create a new window and draw a clone of
// currentPad->GetCanvas() in it, using the style 'style'.
// Thanks to that method, one can have a preview of any
// style with any object.
fPad = 0;
// Create the main window.
SetWindowName("Style Manager's Preview");
SetCleanup(kNoCleanup);
DontCallClose();
// Create the trash lists to have an effective deletion of every object.
fTrashListLayout = new TList();
// Create the layouts and add them to the layout trash list.
TGLayoutHints *layoutXY = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);
fTrashListLayout->Add(layoutXY);
// Create a canvas for the preview.
fEcan = new TRootEmbeddedCanvas("TSMPreviewCanvas", this, 10, 10);
AddFrame(fEcan, layoutXY);
// Draw the preview.
Update(style, currentPad);
// Map main frame.
MapTheWindow();
// No modifications allowed in the preview.
fEcan->GetCanvas()->SetEditable(kFALSE);
fEcan->GetCanvas()->SetBit(kNoContextMenu);
}
//______________________________________________________________________________
TStylePreview::~TStylePreview()
{
// Destructor.
// Delete all the widgets created in this class.
delete fEcan;
// Delete all the layouts.
TObject *obj1;
TObject *obj2;
obj1 = fTrashListLayout->First();
while (obj1) {
obj2 = fTrashListLayout->After(obj1);
fTrashListLayout->Remove(obj1);
delete obj1;
obj1 = obj2;
}
delete fTrashListLayout;
}
//______________________________________________________________________________
void TStylePreview::Update(TStyle *style, TVirtualPad *pad)
{
// Update the preview with possibly another style and
// another object than previously.
TCanvas *c;
if (pad != fPad) {
delete fEcan->GetCanvas();
fEcan->AdoptCanvas(new TCanvas("TSMPreviewCanvas", 10, 10,
fEcan->GetCanvasWindowId()));
c = fEcan->GetCanvas();
gROOT->SetSelectedPad(c);
pad->GetCanvas()->DrawClonePad();
gROOT->SetSelectedPad(pad);
fPad = pad;
}
// Apply the 'style' to the clone of 'pad'.
c = fEcan->GetCanvas();
TStyle *tmpStyle = gStyle;
gStyle = style;
c->UseCurrentStyle();
gStyle = tmpStyle;
c->Modified();
c->Update();
}
//______________________________________________________________________________
void TStylePreview::MapTheWindow()
{
// Initialize the layout algorithm.
MapSubwindows();
TCanvas *c = fPad->GetCanvas();
UInt_t w = c->GetWw() + 4; //4 pixels of borders
UInt_t h = c->GetWh() + 4; //4 pixels of borders
UInt_t x = (UInt_t) c->GetWindowTopX() + 60;
UInt_t y = (UInt_t) c->GetWindowTopY() + 100;
MoveResize(x, y, w, h);
SetWMPosition(x, y);
MapWindow();
}
//______________________________________________________________________________
TCanvas *TStylePreview::GetMainCanvas()
{
// Return pointer to the selected canvas.
return fEcan->GetCanvas();
}
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/gl/util.h>
#include <visionaray/math/math.h>
#include "../util.h"
namespace gl = visionaray::gl;
namespace visionaray
{
std::string gl::last_error()
{
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
#if VSNRAY_HAVE_GLEW
return std::string(reinterpret_cast<char const*>(glewGetErrorString(err)));
#endif
}
return "";
}
void gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
if (glTexStorage2D)
{
glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h);
}
else
{
glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0);
}
}
void gl::update_texture(
pixel_format_info info,
GLsizei x,
GLsizei y,
GLsizei w,
GLsizei h,
GLvoid const* pixels
)
{
glTexSubImage2D(
GL_TEXTURE_2D,
0, // TODO
x,
y,
w,
h,
info.format,
info.type,
pixels
);
}
void gl::update_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* pixels
)
{
glTexSubImage2D(
GL_TEXTURE_2D,
0, // TODO
0,
0,
w,
h,
info.format,
info.type,
pixels
);
}
void gl::draw_full_screen_quad()
{
glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glActiveTexture(GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);
glEnd();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
void gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_BLEND);
glBlendFunc(sfactor, dfactor);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glDepthMask(GL_FALSE);
glDisable(GL_LIGHTING);
draw_full_screen_quad();
glPopAttrib();
}
#if defined(VSNRAY_OPENGL_LEGACY)
void gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
recti vp = gl::viewport();
glWindowPos2i(vp[0], vp[1]);
GLfloat scalex = vp[2] / static_cast<GLfloat>(w);
GLfloat scaley = vp[3] / static_cast<GLfloat>(h);
glPixelZoom(scalex, scaley);
glEnable(GL_BLEND);
glBlendFunc(sfactor, dfactor);
glDrawPixels(w, h, format, type, pixels);
glPopAttrib();
}
#endif
recti gl::viewport()
{
GLint vp[4];
glGetIntegerv(GL_VIEWPORT, &vp[0]);
return recti(vp[0], vp[1], vp[2], vp[3]);
}
} // visionaray
<commit_msg>More OpenGLES 2.0 compatibility<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/gl/util.h>
#include <visionaray/math/math.h>
#include "../util.h"
namespace gl = visionaray::gl;
namespace visionaray
{
std::string gl::last_error()
{
GLenum err = glGetError();
if (err != GL_NO_ERROR)
{
#if VSNRAY_HAVE_GLEW
return std::string(reinterpret_cast<char const*>(glewGetErrorString(err)));
#endif
}
return "";
}
void gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
#if defined(GL_VERSION_4_2) && GL_VERSION_4_2 || defined(GL_ES_VERSION_3_0) && GL_ES_VERSION_3_0
if (glTexStorage2D)
{
glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h);
}
else
#endif
{
glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0);
}
}
void gl::update_texture(
pixel_format_info info,
GLsizei x,
GLsizei y,
GLsizei w,
GLsizei h,
GLvoid const* pixels
)
{
glTexSubImage2D(
GL_TEXTURE_2D,
0, // TODO
x,
y,
w,
h,
info.format,
info.type,
pixels
);
}
void gl::update_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* pixels
)
{
glTexSubImage2D(
GL_TEXTURE_2D,
0, // TODO
0,
0,
w,
h,
info.format,
info.type,
pixels
);
}
void gl::draw_full_screen_quad()
{
glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glActiveTexture(GL_TEXTURE0);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);
glEnd();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glPopAttrib();
}
void gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_BLEND);
glBlendFunc(sfactor, dfactor);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glDepthMask(GL_FALSE);
glDisable(GL_LIGHTING);
draw_full_screen_quad();
glPopAttrib();
}
#if defined(VSNRAY_OPENGL_LEGACY)
void gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
recti vp = gl::viewport();
glWindowPos2i(vp[0], vp[1]);
GLfloat scalex = vp[2] / static_cast<GLfloat>(w);
GLfloat scaley = vp[3] / static_cast<GLfloat>(h);
glPixelZoom(scalex, scaley);
glEnable(GL_BLEND);
glBlendFunc(sfactor, dfactor);
glDrawPixels(w, h, format, type, pixels);
glPopAttrib();
}
#endif
recti gl::viewport()
{
GLint vp[4];
glGetIntegerv(GL_VIEWPORT, &vp[0]);
return recti(vp[0], vp[1], vp[2], vp[3]);
}
} // visionaray
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* 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 "SimTKsimbody.h"
using namespace SimTK;
using namespace std;
const Real TOL = 1e-5;
#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");}
template <class T>
void assertEqual(T val1, T val2) {
ASSERT(abs(val1-val2) < TOL || abs(val1-val2)/max(abs(val1), abs(val2)) < TOL);
}
template <int N>
void assertEqual(Vec<N> val1, Vec<N> val2) {
for (int i = 0; i < N; ++i)
assertEqual(val1[i], val2[i]);
}
void testForces() {
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
// Create a triangle mesh in the shape of a pyramid, with the
// square base having area 1 (split into two triangles).
vector<Vec3> vertices;
vertices.push_back(Vec3(0, 0, 0));
vertices.push_back(Vec3(1, 0, 0));
vertices.push_back(Vec3(1, 0, 1));
vertices.push_back(Vec3(0, 0, 1));
vertices.push_back(Vec3(0.5, 1, 0.5));
vector<int> faceIndices;
int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
{2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
// Create the mobilized bodies and configure the contact model.
Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
ContactSetIndex setIndex = contacts.createContactSet();
MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); // y < 0
ElasticFoundationForce ef(forces, contacts, setIndex);
Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
ASSERT(ef.getTransitionVelocity() == vt);
State state = system.realizeTopology();
// Position the pyramid at a variety of positions and check the normal
// force.
for (Real depth = -0.1; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
system.realize(state, Stage::Dynamics);
Real f = 0;
if (depth > 0)
f = stiffness*depth;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));
}
// Now do it with a vertical velocity and see if the dissipation force is correct.
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));
system.realize(state, Stage::Dynamics);
Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);
if (f < 0)
f = 0;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
}
}
// Do it with a horizontal velocity and see if the friction force is correct.
Vector_<SpatialVec> expectedForce(matter.getNumBodies());
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
Real fh = 0;
if (depth > 0)
fh = stiffness*depth;
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));
system.realize(state, Stage::Dynamics);
const Real vrel = std::abs(v/vt);
Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)/(1+vrel*vrel))+uv*std::fabs(v));
const Vec3 totalForce = Vec3(ff, fh, 0);
expectedForce = SpatialVec(Vec3(0), Vec3(0));
Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0/3.0, 0, 1.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);
Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0/3.0, 0, 2.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);
SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);
assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);
}
}
}
int main() {
try {
testForces();
}
catch(const std::exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
<commit_msg>[master] Removed trailing spaces in Simbody/tests/TestElasticFoundationForce.cpp<commit_after>/* -------------------------------------------------------------------------- *
* Simbody(tm) *
* -------------------------------------------------------------------------- *
* This is part of the SimTK biosimulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. *
* *
* Portions copyright (c) 2008-12 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* 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 "SimTKsimbody.h"
using namespace SimTK;
using namespace std;
const Real TOL = 1e-5;
#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, "Assertion failed");}
template <class T>
void assertEqual(T val1, T val2) {
ASSERT(abs(val1-val2) < TOL || abs(val1-val2)/max(abs(val1), abs(val2)) < TOL);
}
template <int N>
void assertEqual(Vec<N> val1, Vec<N> val2) {
for (int i = 0; i < N; ++i)
assertEqual(val1[i], val2[i]);
}
void testForces() {
MultibodySystem system;
SimbodyMatterSubsystem matter(system);
GeneralContactSubsystem contacts(system);
GeneralForceSubsystem forces(system);
// Create a triangle mesh in the shape of a pyramid, with the
// square base having area 1 (split into two triangles).
vector<Vec3> vertices;
vertices.push_back(Vec3(0, 0, 0));
vertices.push_back(Vec3(1, 0, 0));
vertices.push_back(Vec3(1, 0, 1));
vertices.push_back(Vec3(0, 0, 1));
vertices.push_back(Vec3(0.5, 1, 0.5));
vector<int> faceIndices;
int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
{2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
for (int i = 0; i < 6; i++)
for (int j = 0; j < 3; j++)
faceIndices.push_back(faces[i][j]);
// Create the mobilized bodies and configure the contact model.
Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));
ContactSetIndex setIndex = contacts.createContactSet();
MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());
contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());
contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); // y < 0
ElasticFoundationForce ef(forces, contacts, setIndex);
Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;
ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);
ef.setTransitionVelocity(vt);
ASSERT(ef.getTransitionVelocity() == vt);
State state = system.realizeTopology();
// Position the pyramid at a variety of positions and check the normal
// force.
for (Real depth = -0.1; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
system.realize(state, Stage::Dynamics);
Real f = 0;
if (depth > 0)
f = stiffness*depth;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));
}
// Now do it with a vertical velocity and see if the dissipation force is correct.
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));
system.realize(state, Stage::Dynamics);
Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);
if (f < 0)
f = 0;
assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));
}
}
// Do it with a horizontal velocity and see if the friction force is correct.
Vector_<SpatialVec> expectedForce(matter.getNumBodies());
for (Real depth = -0.105; depth < 0.1; depth += 0.01) {
mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));
Real fh = 0;
if (depth > 0)
fh = stiffness*depth;
for (Real v = -1.0; v <= 1.0; v += 0.1) {
mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));
system.realize(state, Stage::Dynamics);
const Real vrel = std::abs(v/vt);
Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)/(1+vrel*vrel))+uv*std::fabs(v));
const Vec3 totalForce = Vec3(ff, fh, 0);
expectedForce = SpatialVec(Vec3(0), Vec3(0));
Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0/3.0, 0, 1.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);
Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0/3.0, 0, 2.0/3.0));
mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);
SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];
assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);
assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);
}
}
}
int main() {
try {
testForces();
}
catch(const std::exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* test1.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <LLGL/LLGL.h>
#include <memory>
#include <iostream>
#include <string>
#include <sstream>
int main()
{
try
{
// Create window
LLGL::WindowDesc windowDesc;
windowDesc.title = L"LLGL Test 1";
windowDesc.visible = true;
windowDesc.centered = true;
windowDesc.resizable = true;
windowDesc.size = { 640, 480 };
auto window = LLGL::Window::Create(windowDesc);
auto input = std::make_shared<LLGL::Input>();
window->AddListener(input);
auto timer = LLGL::Timer::Create();
int x = 100, y = 100;
window->SetPosition({ x, y });
while (window->ProcessEvents() && !input->KeyPressed(LLGL::Key::Escape))
{
timer->MeasureTime();
//std::cout << 1.0 / timer->GetDeltaTime() << std::endl;
if (input->KeyPressed(LLGL::Key::Num1))
window->Show(false);
if (input->KeyPressed(LLGL::Key::Num2))
window->Show(true);
if (input->KeyPressed(LLGL::Key::Num3))
window->SetTitle(L"FOO BAR");
if (input->KeyPressed(LLGL::Key::Num4))
window->SetTitle(L"LLGL Test 1");
if (input->KeyPressed(LLGL::Key::Num5))
window->SetSize({ 300, 300 });
auto mousePos = input->GetMousePosition();
std::wstringstream s;
s << "X = " << mousePos.x << ", Y = " << mousePos.y;
window->SetTitle(s.str());
if (input->KeyPressed(LLGL::Key::Right))
{
++x;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Left))
{
--x;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Up))
{
--y;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Down))
{
++y;
window->SetPosition({ x, y });
}
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>Commented out test section for Windows.<commit_after>/*
* test1.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include <LLGL/LLGL.h>
#include <memory>
#include <iostream>
#include <string>
#include <sstream>
int main()
{
try
{
// Create window
LLGL::WindowDesc windowDesc;
windowDesc.title = L"LLGL Test 1";
windowDesc.visible = true;
windowDesc.centered = true;
windowDesc.resizable = true;
windowDesc.size = { 640, 480 };
auto window = LLGL::Window::Create(windowDesc);
auto input = std::make_shared<LLGL::Input>();
window->AddListener(input);
auto timer = LLGL::Timer::Create();
int x = 100, y = 100;
window->SetPosition({ x, y });
while (window->ProcessEvents() && !input->KeyPressed(LLGL::Key::Escape))
{
timer->MeasureTime();
//std::cout << 1.0 / timer->GetDeltaTime() << std::endl;
if (input->KeyPressed(LLGL::Key::Num1))
window->Show(false);
if (input->KeyPressed(LLGL::Key::Num2))
window->Show(true);
if (input->KeyPressed(LLGL::Key::Num3))
window->SetTitle(L"FOO BAR");
if (input->KeyPressed(LLGL::Key::Num4))
window->SetTitle(L"LLGL Test 1");
if (input->KeyPressed(LLGL::Key::Num5))
window->SetSize({ 300, 300 });
#ifdef __APPLE__
auto mousePos = input->GetMousePosition();
std::wstringstream s;
s << "X = " << mousePos.x << ", Y = " << mousePos.y;
window->SetTitle(s.str());
#endif
if (input->KeyPressed(LLGL::Key::Right))
{
++x;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Left))
{
--x;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Up))
{
--y;
window->SetPosition({ x, y });
}
if (input->KeyPressed(LLGL::Key::Down))
{
++y;
window->SetPosition({ x, y });
}
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "commands.h"
using namespace aBuild;
namespace commands {
void build(bool verbose) {
Workspace ws(".");
checkingMissingPackages(ws);
checkingNotNeededPackages(ws);
checkingInvalidPackages(ws);
checkingRequiredPackages(ws);
Graph graph;
auto allToolchains = getAllToolchains(ws);
Toolchain toolchain = allToolchains.rbegin()->second;
std::string toolchainName = ws.accessConfigFile().getToolchain();
if (allToolchains.find(toolchainName) != allToolchains.end()) {
toolchain = allToolchains.at(toolchainName);
}
std::cout << "Using toolchain: " << toolchain.getName();
std::cout << std::endl;
std::unique_ptr<BuildAction> action { new BuildActionClang(&graph, verbose, &ws.accessConfigFile(), toolchain) };
auto linkingLibFunc = action->getLinkingLibFunc();
auto linkingExecFunc = action->getLinkingExecFunc();
auto _compileFileCppFunc = action->getCompileCppFileFunc();
auto _compileFileCppFuncDep = action->getCompileCppFileFuncDep();
auto compileFileCFunc = action->getCompileCFileFunc();
std::function<void(std::string*)> compileFileCppFunc = [&] (std::string* p){
_compileFileCppFunc(p);
_compileFileCppFuncDep(p);
};
// Create dependency tree
auto projects = ws.getAllRequiredProjects();
for (auto& e : projects) {
auto& project = e.second;
// Adding linking
if (project.getType() == "library") {
graph.addNode(&project, linkingLibFunc);
} else if (project.getType() == "executable") {
graph.addNode(&project, linkingExecFunc);
} else {
std::cout<<"invalid type: "<<project.getType()<<std::endl;
}
// Adding compile files
for (auto& f : project.getAllCppFiles()) {
graph.addNode(&f, compileFileCppFunc);
graph.addEdge(&f, &project);
}
// Adding compile files
for (auto& f : project.getAllCFiles()) {
graph.addNode(&f, compileFileCFunc);
graph.addEdge(&f, &project);
}
for (auto const& dep : project.getDependencies()) {
auto l = utils::explode(dep, "/");
auto key = l[l.size() -1];
graph.addEdge(&projects.at(key), &project);
}
for (auto const& dep : project.getOptionalDependencies()) {
auto l = utils::explode(dep, "/");
auto key = l[l.size() -1];
if (projects.find(key) != projects.end()) {
graph.addEdge(&projects.at(key), &project);
}
}
}
graph.visitAllNodes();
}
}
<commit_msg>showing flavor when building<commit_after>#include "commands.h"
using namespace aBuild;
namespace commands {
void build(bool verbose) {
Workspace ws(".");
checkingMissingPackages(ws);
checkingNotNeededPackages(ws);
checkingInvalidPackages(ws);
checkingRequiredPackages(ws);
Graph graph;
auto allToolchains = getAllToolchains(ws);
Toolchain toolchain = allToolchains.rbegin()->second;
std::string toolchainName = ws.accessConfigFile().getToolchain();
if (allToolchains.find(toolchainName) != allToolchains.end()) {
toolchain = allToolchains.at(toolchainName);
}
std::cout << "Using toolchain: " << toolchain.getName() << std::endl;
std::cout << "Using flavor: " << ws.accessConfigFile().getFlavor() << std::endl;
std::unique_ptr<BuildAction> action { new BuildActionClang(&graph, verbose, &ws.accessConfigFile(), toolchain) };
auto linkingLibFunc = action->getLinkingLibFunc();
auto linkingExecFunc = action->getLinkingExecFunc();
auto _compileFileCppFunc = action->getCompileCppFileFunc();
auto _compileFileCppFuncDep = action->getCompileCppFileFuncDep();
auto compileFileCFunc = action->getCompileCFileFunc();
std::function<void(std::string*)> compileFileCppFunc = [&] (std::string* p){
_compileFileCppFunc(p);
_compileFileCppFuncDep(p);
};
// Create dependency tree
auto projects = ws.getAllRequiredProjects();
for (auto& e : projects) {
auto& project = e.second;
// Adding linking
if (project.getType() == "library") {
graph.addNode(&project, linkingLibFunc);
} else if (project.getType() == "executable") {
graph.addNode(&project, linkingExecFunc);
} else {
std::cout<<"invalid type: "<<project.getType()<<std::endl;
}
// Adding compile files
for (auto& f : project.getAllCppFiles()) {
graph.addNode(&f, compileFileCppFunc);
graph.addEdge(&f, &project);
}
// Adding compile files
for (auto& f : project.getAllCFiles()) {
graph.addNode(&f, compileFileCFunc);
graph.addEdge(&f, &project);
}
for (auto const& dep : project.getDependencies()) {
auto l = utils::explode(dep, "/");
auto key = l[l.size() -1];
graph.addEdge(&projects.at(key), &project);
}
for (auto const& dep : project.getOptionalDependencies()) {
auto l = utils::explode(dep, "/");
auto key = l[l.size() -1];
if (projects.find(key) != projects.end()) {
graph.addEdge(&projects.at(key), &project);
}
}
}
graph.visitAllNodes();
}
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <cstdlib>
#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/drc_lcmtypes.hpp>
#include <std_msgs/Float64.h>
#include <sensor_msgs/JointState.h>
#include <geometry_msgs/Pose.h>
#include <std_srvs/Empty.h>
#include <map>
#include <string>
/**
A simple translator that listens for a robot state message on the SET_ROBOT_CONFIG channel and sets the robot's pose, joint positions,
and PID controller setpoints accordingly. If pausePhysics is set to true, the gazebo simulation will be paused after the configuration
is reset.
**/
class ConfigurationCommandHandler{
private:
std::map<std::string, ros::Publisher> setpoint_map;
ros::Publisher pose_pub;
ros::Publisher joint_pub;
ros::NodeHandle config_command_node;
ros::ServiceClient client;
bool pausePhysics;
public:
ConfigurationCommandHandler(ros::NodeHandle &node): config_command_node(node) {
pose_pub = config_command_node.advertise<geometry_msgs::Pose>("/atlas/set_pose",10);
joint_pub = config_command_node.advertise<sensor_msgs::JointState>("/atlas/configuration",10);
setpoint_map.insert(std::make_pair("l_arm_elx",config_command_node.advertise<std_msgs::Float64>("/l_arm_elx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_ely",config_command_node.advertise<std_msgs::Float64>("/l_arm_ely_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_mwx",config_command_node.advertise<std_msgs::Float64>("/l_arm_mwx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_shx",config_command_node.advertise<std_msgs::Float64>("/l_arm_shx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_usy",config_command_node.advertise<std_msgs::Float64>("/l_arm_usy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_uwy",config_command_node.advertise<std_msgs::Float64>("/l_arm_uwy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_elx",config_command_node.advertise<std_msgs::Float64>("/r_arm_elx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_ely",config_command_node.advertise<std_msgs::Float64>("/r_arm_ely_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_mwx",config_command_node.advertise<std_msgs::Float64>("/r_arm_mwx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_shx",config_command_node.advertise<std_msgs::Float64>("/r_arm_shx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_usy",config_command_node.advertise<std_msgs::Float64>("/r_arm_usy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_uwy",config_command_node.advertise<std_msgs::Float64>("/r_arm_uwy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_kny",config_command_node.advertise<std_msgs::Float64>("/l_leg_kny_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_lax",config_command_node.advertise<std_msgs::Float64>("/l_leg_lax_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_lhy",config_command_node.advertise<std_msgs::Float64>("/l_leg_lhy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_mhx",config_command_node.advertise<std_msgs::Float64>("/l_leg_mhx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_uay",config_command_node.advertise<std_msgs::Float64>("/l_leg_uay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_uhz",config_command_node.advertise<std_msgs::Float64>("/l_leg_uhz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_kny",config_command_node.advertise<std_msgs::Float64>("/r_leg_kny_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_lax",config_command_node.advertise<std_msgs::Float64>("/r_leg_lax_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_lhy",config_command_node.advertise<std_msgs::Float64>("/r_leg_lhy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_mhx",config_command_node.advertise<std_msgs::Float64>("/r_leg_mhx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_uay",config_command_node.advertise<std_msgs::Float64>("/r_leg_uay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_uhz",config_command_node.advertise<std_msgs::Float64>("/r_leg_uhz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("neck_ay",config_command_node.advertise<std_msgs::Float64>("/neck_ay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_lbz",config_command_node.advertise<std_msgs::Float64>("/back_lbz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_mby",config_command_node.advertise<std_msgs::Float64>("/back_mby_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_ubx",config_command_node.advertise<std_msgs::Float64>("/back_ubx_position_controller/command",10)));
pausePhysics = false;
client = config_command_node.serviceClient<std_srvs::Empty>("/gazebo/pause_physics");
}
~ConfigurationCommandHandler() {}
void configuration_command_callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::robot_state_t* msg)
{
// set robot pose
geometry_msgs::Pose pose_msg;
pose_msg.position = geometry_msgs::Point();
pose_msg.position.x = msg->origin_position.translation.x;
pose_msg.position.y = msg->origin_position.translation.y;
pose_msg.position.z = msg->origin_position.translation.z;
pose_msg.orientation = geometry_msgs::Quaternion();
pose_msg.orientation.x = msg->origin_position.rotation.x;
pose_msg.orientation.y = msg->origin_position.rotation.y;
pose_msg.orientation.z = msg->origin_position.rotation.z;
pose_msg.orientation.w = msg->origin_position.rotation.w;
// set robot joint config
sensor_msgs::JointState joint_msg;
for (int i=0; i<msg->num_joints; i++) {
joint_msg.name.push_back(msg->joint_name[i]);
joint_msg.position.push_back(msg->joint_position[i]);
}
if(ros::ok()) {
joint_pub.publish(joint_msg);
pose_pub.publish(pose_msg);
}
// set PID goals
std_msgs::Float64 position_command_msg;
for (int i=0; i<msg->num_joints; i++) {
// should we instead publish all joints at the same time?
position_command_msg.data = msg->joint_position[i];
if(ros::ok()) {
setpoint_map[msg->joint_name[i]].publish(position_command_msg);
}
}
// pause gazebo
if(pausePhysics && ros::ok()) {
std_srvs::Empty srv;
if (!client.call(srv)) {
ROS_ERROR("Failed to pause gazebo.");
}
}
}
};
int main(int argc,char** argv) {
ros::init(argc,argv,"config_command_publisher",ros::init_options::NoSigintHandler);
ros::NodeHandle config_command_node;
lcm::LCM listener;
if(!listener.good())
return 1;
ConfigurationCommandHandler handlerObject(config_command_node);
//LCM subscription
listener.subscribe("SET_ROBOT_CONFIG",&ConfigurationCommandHandler::configuration_command_callback,&handlerObject);
while(0 == listener.handle());
return 0;
}
<commit_msg>physics is now paused in the config command lcm2ros translator before setting the robot pose and config<commit_after>#include <ros/ros.h>
#include <cstdlib>
#include <lcm/lcm-cpp.hpp>
#include <lcmtypes/drc_lcmtypes.hpp>
#include <std_msgs/Float64.h>
#include <sensor_msgs/JointState.h>
#include <geometry_msgs/Pose.h>
#include <std_srvs/Empty.h>
#include <map>
#include <string>
/**
A simple translator that listens for a robot state message on the SET_ROBOT_CONFIG channel and sets the robot's pose, joint positions,
and PID controller setpoints accordingly. If pausePhysics is set to true, the gazebo simulation will be paused after the configuration
is reset.
**/
class ConfigurationCommandHandler{
private:
std::map<std::string, ros::Publisher> setpoint_map;
ros::Publisher pose_pub;
ros::Publisher joint_pub;
ros::NodeHandle config_command_node;
ros::ServiceClient client;
bool pausePhysics;
public:
ConfigurationCommandHandler(ros::NodeHandle &node): config_command_node(node) {
pose_pub = config_command_node.advertise<geometry_msgs::Pose>("/atlas/set_pose",10);
joint_pub = config_command_node.advertise<sensor_msgs::JointState>("/atlas/configuration",10);
setpoint_map.insert(std::make_pair("l_arm_elx",config_command_node.advertise<std_msgs::Float64>("/l_arm_elx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_ely",config_command_node.advertise<std_msgs::Float64>("/l_arm_ely_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_mwx",config_command_node.advertise<std_msgs::Float64>("/l_arm_mwx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_shx",config_command_node.advertise<std_msgs::Float64>("/l_arm_shx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_usy",config_command_node.advertise<std_msgs::Float64>("/l_arm_usy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_arm_uwy",config_command_node.advertise<std_msgs::Float64>("/l_arm_uwy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_elx",config_command_node.advertise<std_msgs::Float64>("/r_arm_elx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_ely",config_command_node.advertise<std_msgs::Float64>("/r_arm_ely_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_mwx",config_command_node.advertise<std_msgs::Float64>("/r_arm_mwx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_shx",config_command_node.advertise<std_msgs::Float64>("/r_arm_shx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_usy",config_command_node.advertise<std_msgs::Float64>("/r_arm_usy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_arm_uwy",config_command_node.advertise<std_msgs::Float64>("/r_arm_uwy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_kny",config_command_node.advertise<std_msgs::Float64>("/l_leg_kny_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_lax",config_command_node.advertise<std_msgs::Float64>("/l_leg_lax_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_lhy",config_command_node.advertise<std_msgs::Float64>("/l_leg_lhy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_mhx",config_command_node.advertise<std_msgs::Float64>("/l_leg_mhx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_uay",config_command_node.advertise<std_msgs::Float64>("/l_leg_uay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("l_leg_uhz",config_command_node.advertise<std_msgs::Float64>("/l_leg_uhz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_kny",config_command_node.advertise<std_msgs::Float64>("/r_leg_kny_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_lax",config_command_node.advertise<std_msgs::Float64>("/r_leg_lax_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_lhy",config_command_node.advertise<std_msgs::Float64>("/r_leg_lhy_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_mhx",config_command_node.advertise<std_msgs::Float64>("/r_leg_mhx_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_uay",config_command_node.advertise<std_msgs::Float64>("/r_leg_uay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("r_leg_uhz",config_command_node.advertise<std_msgs::Float64>("/r_leg_uhz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("neck_ay",config_command_node.advertise<std_msgs::Float64>("/neck_ay_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_lbz",config_command_node.advertise<std_msgs::Float64>("/back_lbz_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_mby",config_command_node.advertise<std_msgs::Float64>("/back_mby_position_controller/command",10)));
setpoint_map.insert(std::make_pair("back_ubx",config_command_node.advertise<std_msgs::Float64>("/back_ubx_position_controller/command",10)));
pausePhysics = true;
client = config_command_node.serviceClient<std_srvs::Empty>("/gazebo/pause_physics");
}
~ConfigurationCommandHandler() {}
void configuration_command_callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::robot_state_t* msg)
{
// pause gazebo
if(pausePhysics && ros::ok()) {
std_srvs::Empty srv;
if (!client.call(srv)) {
ROS_ERROR("Failed to pause gazebo.");
}
}
// set robot pose
geometry_msgs::Pose pose_msg;
pose_msg.position = geometry_msgs::Point();
pose_msg.position.x = msg->origin_position.translation.x;
pose_msg.position.y = msg->origin_position.translation.y;
pose_msg.position.z = msg->origin_position.translation.z;
pose_msg.orientation = geometry_msgs::Quaternion();
pose_msg.orientation.x = msg->origin_position.rotation.x;
pose_msg.orientation.y = msg->origin_position.rotation.y;
pose_msg.orientation.z = msg->origin_position.rotation.z;
pose_msg.orientation.w = msg->origin_position.rotation.w;
// set robot joint config
sensor_msgs::JointState joint_msg;
for (int i=0; i<msg->num_joints; i++) {
joint_msg.name.push_back(msg->joint_name[i]);
joint_msg.position.push_back(msg->joint_position[i]);
}
if(ros::ok()) {
joint_pub.publish(joint_msg);
pose_pub.publish(pose_msg);
}
// set PID goals
std_msgs::Float64 position_command_msg;
for (int i=0; i<msg->num_joints; i++) {
// should we instead publish all joints at the same time?
position_command_msg.data = msg->joint_position[i];
if(ros::ok()) {
setpoint_map[msg->joint_name[i]].publish(position_command_msg);
}
}
}
};
int main(int argc,char** argv) {
ros::init(argc,argv,"config_command_publisher",ros::init_options::NoSigintHandler);
ros::NodeHandle config_command_node;
lcm::LCM listener;
if(!listener.good())
return 1;
ConfigurationCommandHandler handlerObject(config_command_node);
//LCM subscription
listener.subscribe("SET_ROBOT_CONFIG",&ConfigurationCommandHandler::configuration_command_callback,&handlerObject);
while(0 == listener.handle());
return 0;
}
<|endoftext|>
|
<commit_before>#include "list.h"
#include "gtest/gtest.h"
#include <string>
class listTest : public testing::Test {
protected:
virtual void SetUp() {
list_1.insert(list_1.begin(), 10);
int_iter = list_1.insert(list_1.end(), 30);
int_iter = list_1.insert(int_iter, 20);
str = "a string";
}
virtual void TearDown() {}
// class constant
// setup fixtures
::list<int> list_1;
::list<int> list_2;
list<int> list_empty;
::list<std::string> list_str;
list<int>::iterator int_iter;
list<std::string>::iterator str_iter;
std::string str;
};
class listIteratorTest : public testing::Test {
// try to make friend with list_const_iterator DOES NOT WORK here
// because friendship must be made before template is resolved:
// friend class list_const_iterator<int>;
protected:
virtual void SetUp() {
head_ = new listNode<int> (0);
head_->next_ = new listNode<int> (10);
tail_ = head_->next_->next_ = new listNode<int> (20);
head_->next_->prev_ = head_;
tail_->prev_ = head_->next_;
c_iter = list_const_iterator<int> (head_);
c_iter_1 = list_const_iterator<int> (head_->next_);
iter = list_iterator<int> (head_);
iter_1 = list_iterator<int> (head_->next_);
}
virtual void TearDown() {
delete tail_;
delete head_->next_;
delete head_;
}
listNode<int>* head_;
listNode<int>* tail_;
list_const_iterator<int> c_iter;
list_const_iterator<int> c_iter_1;
list_iterator<int> iter;
list_iterator<int> iter_1;
};
// test the helper class listNodeTest
// this is a canonical example of writing testable code:
// to test private members, just write another helper class
// and make its data public
TEST(listHelperTest, ListNode) {
int element_1 = 100;
std::string element_2("Hello world");
listNode<int> node_1(element_1);
listNode<std::string> node_2(element_2);
EXPECT_EQ(element_1, node_1.element_);
EXPECT_EQ(element_2, node_2.element_);
EXPECT_EQ(nullptr, node_2.prev_);
EXPECT_EQ(nullptr, node_2.next_);
// test the move constructor for node:
listNode<int> node_3(std::move(element_1));
listNode<std::string> node_4(std::move(element_2));
EXPECT_EQ(100, node_3.element_);
EXPECT_EQ("Hello world", node_4.element_);
EXPECT_TRUE(element_2.empty());
}
TEST_F(listIteratorTest, ConstIterator) {
list_const_iterator<int> c_iter_temp = c_iter;
// testing increment and decrement of const_iterator
EXPECT_EQ(++c_iter_temp, c_iter_1);
EXPECT_EQ(--c_iter_temp, c_iter);
EXPECT_EQ(c_iter_temp++, c_iter);
EXPECT_EQ(c_iter_temp, c_iter_1);
EXPECT_EQ(c_iter_temp--, c_iter_1);
EXPECT_EQ(c_iter_temp, c_iter);
EXPECT_TRUE(c_iter_temp == c_iter);
EXPECT_TRUE(c_iter_temp != c_iter_1);
// testing access capability of const_iterator
EXPECT_EQ(0, *c_iter_temp);
EXPECT_EQ(10, *(++c_iter_temp));
EXPECT_EQ(20, *(++c_iter_temp));
EXPECT_EQ(10, *(--c_iter_temp));
// testing non-modifying capability of const_iterator:
// will not even compile:
//*c_iter_temp = 100;
}
TEST_F(listIteratorTest, Iterator) {
list_iterator<int> iter_temp = iter;
// testing increment and decrement of iterator
// which are all inherited from base
EXPECT_EQ(++iter_temp, iter_1);
EXPECT_EQ(--iter_temp, iter);
EXPECT_EQ(iter_temp++, iter);
EXPECT_EQ(iter_temp, iter_1);
EXPECT_EQ(iter_temp--, iter_1);
EXPECT_EQ(iter_temp, iter);
EXPECT_TRUE(iter_temp == iter);
EXPECT_TRUE(iter_temp != iter_1);
// testing access capability of iterator
EXPECT_EQ(0, *iter_temp);
EXPECT_EQ(10, *(++iter_temp));
EXPECT_EQ(20, *(++iter_temp));
EXPECT_EQ(10, *(--iter_temp));
// testing modifying capability of iterator:
*iter_temp = 100;
EXPECT_EQ(*iter_temp, 100);
}
TEST_F(listTest, DefaultCtor) {
EXPECT_EQ(0u, list_empty.size());
EXPECT_TRUE(list_empty.empty());
}
TEST_F(listTest, CopyCtor) {
}
TEST_F(listTest, BeginEnd) {
EXPECT_EQ(list_empty.begin(), list_empty.end());
// decrement pass begin() and increment pass end() should be ok
EXPECT_NO_FATAL_FAILURE(--list_empty.begin());
EXPECT_NO_FATAL_FAILURE(++list_empty.end());
}
TEST_F(listTest, InsertLvalue) {
// iter is pointing to tail_
list<int>::iterator iter = list_empty.begin();
// testing iterator insert (iterator, const E&)
int x = 10;
list<int>::iterator ret_iter = list_empty.insert(iter, x);
EXPECT_TRUE(--iter == ret_iter);
// iter--;
EXPECT_EQ(*ret_iter, 10);
EXPECT_EQ(list_empty.size(), 1);
EXPECT_EQ(++ret_iter, list_empty.end());
--ret_iter; // set ret_iter to point to 10
ret_iter = list_empty.insert(ret_iter, x + 10);
EXPECT_EQ(list_empty.size(), 2);
EXPECT_EQ(*ret_iter, 20);
EXPECT_EQ(*(++ret_iter), 10);
EXPECT_TRUE(++ret_iter == list_empty.end());
// insert pass begin() and pass end() should fail
// the following would not even compile:
// list_empty.insert(++list_empty.end(), 100);
// list_empty.insert(--list_empty.begin(), 100);
}
TEST_F(listTest, InsertRvalue) {
size_t old_size = list_str.size();
str_iter = list_str.insert(list_str.begin(), std::move(str));
EXPECT_EQ(*str_iter, "a string");
EXPECT_TRUE(str_iter == list_str.begin());
EXPECT_EQ(++old_size, list_str.size());
EXPECT_TRUE(str.empty());
}
TEST_F(listTest, InsertConstObject) {
// insert const object by lvalue:
const std::string const_str("const string");
const std::string CONST_STR(const_str);
size_t old_size = list_str.size();
str_iter = list_str.insert(list_str.begin(), const_str);
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*str_iter, CONST_STR);
EXPECT_EQ(const_str, CONST_STR);
// insert const objects by rvalue:
// std::move automatically degrade to a copy insert
str_iter = list_str.insert(list_str.begin(), std::move(const_str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*str_iter, CONST_STR);
EXPECT_EQ(const_str, CONST_STR);
}
TEST_F(listTest, EraseAtIter) {
int_iter = list_1.erase(list_1.begin()); // erase 10
EXPECT_EQ(list_1.size(), 2);
EXPECT_EQ(*list_1.begin(), 20);
EXPECT_EQ(*int_iter, 20);
int_iter = list_1.erase(int_iter); // erase 20
int_iter = list_1.erase(int_iter); // erase 30
// test for seg fault if erase end()
// it trigers a memory leak error right before core dump,
// which it is expected. Turned off when running memtest
//EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), "");
}
TEST_F(listTest, PushFront) {
// lvalue version
size_t old_size = list_1.size();
list_1.push_front(100);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*list_1.begin(), 100);
list_1.push_front(200);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*list_1.begin(), 200);
EXPECT_EQ(*(++list_1.begin()), 100);
EXPECT_TRUE(--(++list_1.begin()) == list_1.begin());
// rvalue version
old_size = list_str.size();
list_str.push_front(std::move(str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*list_str.begin(), "a string");
EXPECT_TRUE(str.empty());
}
TEST_F(listTest, PushBack) {
// lvalue version
size_t old_size = list_1.size();
list_1.push_back(1000);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*(--list_1.end()), 1000);
list_1.push_back(2000);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*(--list_1.end()), 2000);
EXPECT_EQ(*(--(--list_1.end())), 1000);
EXPECT_TRUE(++(--list_1.end()) == list_1.end());
// rvalue version
old_size = list_str.size();
list_str.push_back(std::move(str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*(--list_str.end()), "a string");
EXPECT_TRUE(str.empty());
}
<commit_msg>list: add tests for copy ctor<commit_after>#include "list.h"
#include "gtest/gtest.h"
#include <string>
class listTest : public testing::Test {
protected:
virtual void SetUp() {
list_1.insert(list_1.begin(), 10);
int_iter = list_1.insert(list_1.end(), 30);
int_iter = list_1.insert(int_iter, 20);
str = "a string";
}
virtual void TearDown() {}
// class constant
// setup fixtures
::list<int> list_1;
::list<int> list_2;
list<int> list_empty;
::list<std::string> list_str;
list<int>::iterator int_iter;
list<std::string>::iterator str_iter;
std::string str;
};
class listIteratorTest : public testing::Test {
// try to make friend with list_const_iterator DOES NOT WORK here
// because friendship must be made before template is resolved:
// friend class list_const_iterator<int>;
protected:
virtual void SetUp() {
head_ = new listNode<int> (0);
head_->next_ = new listNode<int> (10);
tail_ = head_->next_->next_ = new listNode<int> (20);
head_->next_->prev_ = head_;
tail_->prev_ = head_->next_;
c_iter = list_const_iterator<int> (head_);
c_iter_1 = list_const_iterator<int> (head_->next_);
iter = list_iterator<int> (head_);
iter_1 = list_iterator<int> (head_->next_);
}
virtual void TearDown() {
delete tail_;
delete head_->next_;
delete head_;
}
listNode<int>* head_;
listNode<int>* tail_;
list_const_iterator<int> c_iter;
list_const_iterator<int> c_iter_1;
list_iterator<int> iter;
list_iterator<int> iter_1;
};
// test the helper class listNodeTest
// this is a canonical example of writing testable code:
// to test private members, just write another helper class
// and make its data public
TEST(listHelperTest, ListNode) {
int element_1 = 100;
std::string element_2("Hello world");
listNode<int> node_1(element_1);
listNode<std::string> node_2(element_2);
EXPECT_EQ(element_1, node_1.element_);
EXPECT_EQ(element_2, node_2.element_);
EXPECT_EQ(nullptr, node_2.prev_);
EXPECT_EQ(nullptr, node_2.next_);
// test the move constructor for node:
listNode<int> node_3(std::move(element_1));
listNode<std::string> node_4(std::move(element_2));
EXPECT_EQ(100, node_3.element_);
EXPECT_EQ("Hello world", node_4.element_);
EXPECT_TRUE(element_2.empty());
}
TEST_F(listIteratorTest, ConstIterator) {
list_const_iterator<int> c_iter_temp = c_iter;
// testing increment and decrement of const_iterator
EXPECT_EQ(++c_iter_temp, c_iter_1);
EXPECT_EQ(--c_iter_temp, c_iter);
EXPECT_EQ(c_iter_temp++, c_iter);
EXPECT_EQ(c_iter_temp, c_iter_1);
EXPECT_EQ(c_iter_temp--, c_iter_1);
EXPECT_EQ(c_iter_temp, c_iter);
EXPECT_TRUE(c_iter_temp == c_iter);
EXPECT_TRUE(c_iter_temp != c_iter_1);
// testing access capability of const_iterator
EXPECT_EQ(0, *c_iter_temp);
EXPECT_EQ(10, *(++c_iter_temp));
EXPECT_EQ(20, *(++c_iter_temp));
EXPECT_EQ(10, *(--c_iter_temp));
// testing non-modifying capability of const_iterator:
// will not even compile:
//*c_iter_temp = 100;
}
TEST_F(listIteratorTest, Iterator) {
list_iterator<int> iter_temp = iter;
// testing increment and decrement of iterator
// which are all inherited from base
EXPECT_EQ(++iter_temp, iter_1);
EXPECT_EQ(--iter_temp, iter);
EXPECT_EQ(iter_temp++, iter);
EXPECT_EQ(iter_temp, iter_1);
EXPECT_EQ(iter_temp--, iter_1);
EXPECT_EQ(iter_temp, iter);
EXPECT_TRUE(iter_temp == iter);
EXPECT_TRUE(iter_temp != iter_1);
// testing access capability of iterator
EXPECT_EQ(0, *iter_temp);
EXPECT_EQ(10, *(++iter_temp));
EXPECT_EQ(20, *(++iter_temp));
EXPECT_EQ(10, *(--iter_temp));
// testing modifying capability of iterator:
*iter_temp = 100;
EXPECT_EQ(*iter_temp, 100);
}
TEST_F(listTest, DefaultCtor) {
EXPECT_EQ(0u, list_empty.size());
EXPECT_TRUE(list_empty.empty());
}
TEST_F(listTest, CopyCtor) {
for (int i = 0; i < 100; i++) {
list_1.push_back(i);
}
const list<int> list_temp = list_1;
EXPECT_EQ(list_temp.size(), list_1.size());
int_iter = list_1.begin();
list<int>::const_iterator temp_iter = list_temp.begin();
while(temp_iter != list_temp.end()
&& int_iter != list_1.end())
{
EXPECT_EQ(*temp_iter++, *int_iter++);
}
// edge case: empty list
list<int> list_nothing = list_empty;
EXPECT_TRUE(list_nothing.empty());
}
TEST_F(listTest, BeginEnd) {
EXPECT_EQ(list_empty.begin(), list_empty.end());
// decrement pass begin() and increment pass end() should be ok
EXPECT_NO_FATAL_FAILURE(--list_empty.begin());
EXPECT_NO_FATAL_FAILURE(++list_empty.end());
}
TEST_F(listTest, InsertLvalue) {
// iter is pointing to tail_
list<int>::iterator iter = list_empty.begin();
// testing iterator insert (iterator, const E&)
int x = 10;
list<int>::iterator ret_iter = list_empty.insert(iter, x);
EXPECT_TRUE(--iter == ret_iter);
// iter--;
EXPECT_EQ(*ret_iter, 10);
EXPECT_EQ(list_empty.size(), 1);
EXPECT_EQ(++ret_iter, list_empty.end());
--ret_iter; // set ret_iter to point to 10
ret_iter = list_empty.insert(ret_iter, x + 10);
EXPECT_EQ(list_empty.size(), 2);
EXPECT_EQ(*ret_iter, 20);
EXPECT_EQ(*(++ret_iter), 10);
EXPECT_TRUE(++ret_iter == list_empty.end());
// insert pass begin() and pass end() should fail
// the following would not even compile:
// list_empty.insert(++list_empty.end(), 100);
// list_empty.insert(--list_empty.begin(), 100);
}
TEST_F(listTest, InsertRvalue) {
size_t old_size = list_str.size();
str_iter = list_str.insert(list_str.begin(), std::move(str));
EXPECT_EQ(*str_iter, "a string");
EXPECT_TRUE(str_iter == list_str.begin());
EXPECT_EQ(++old_size, list_str.size());
EXPECT_TRUE(str.empty());
}
TEST_F(listTest, InsertConstObject) {
// insert const object by lvalue:
const std::string const_str("const string");
const std::string CONST_STR(const_str);
size_t old_size = list_str.size();
str_iter = list_str.insert(list_str.begin(), const_str);
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*str_iter, CONST_STR);
EXPECT_EQ(const_str, CONST_STR);
// insert const objects by rvalue:
// std::move automatically degrade to a copy insert
str_iter = list_str.insert(list_str.begin(), std::move(const_str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*str_iter, CONST_STR);
EXPECT_EQ(const_str, CONST_STR);
}
TEST_F(listTest, EraseAtIter) {
int_iter = list_1.erase(list_1.begin()); // erase 10
EXPECT_EQ(list_1.size(), 2);
EXPECT_EQ(*list_1.begin(), 20);
EXPECT_EQ(*int_iter, 20);
int_iter = list_1.erase(int_iter); // erase 20
int_iter = list_1.erase(int_iter); // erase 30
// test for seg fault if erase end()
// it trigers a memory leak error right before core dump,
// which it is expected. Turned off when running memtest
//EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), "");
}
TEST_F(listTest, PushFront) {
// lvalue version
size_t old_size = list_1.size();
list_1.push_front(100);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*list_1.begin(), 100);
list_1.push_front(200);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*list_1.begin(), 200);
EXPECT_EQ(*(++list_1.begin()), 100);
EXPECT_TRUE(--(++list_1.begin()) == list_1.begin());
// rvalue version
old_size = list_str.size();
list_str.push_front(std::move(str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*list_str.begin(), "a string");
EXPECT_TRUE(str.empty());
}
TEST_F(listTest, PushBack) {
// lvalue version
size_t old_size = list_1.size();
list_1.push_back(1000);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*(--list_1.end()), 1000);
list_1.push_back(2000);
EXPECT_EQ(++old_size, list_1.size());
EXPECT_EQ(*(--list_1.end()), 2000);
EXPECT_EQ(*(--(--list_1.end())), 1000);
EXPECT_TRUE(++(--list_1.end()) == list_1.end());
// rvalue version
old_size = list_str.size();
list_str.push_back(std::move(str));
EXPECT_EQ(++old_size, list_str.size());
EXPECT_EQ(*(--list_str.end()), "a string");
EXPECT_TRUE(str.empty());
}
<|endoftext|>
|
<commit_before><commit_msg>latest<commit_after><|endoftext|>
|
<commit_before>#include "AliMCAuxHandler.h"
#include "AliAnalysisManager.h"
#include <TError.h>
#include <AliLog.h>
#include <TFile.h>
#include <TClonesArray.h>
#include <TROOT.h>
#include <AliStack.h>
#include <AliMCEvent.h>
ClassImp(AliMCAuxHandler)
#if 0 // For Emacs - do not remove
;
#endif
//____________________________________________________________________
AliMCAuxHandler::AliMCAuxHandler(const char* name,
const char* what,
AliMCEventHandler* parent)
: AliMCEventHandler(name, what),
fParent(parent),
fFile(0),
fTree(0),
fDir(0),
fArray(0),
fNEvents(0),
fNEventsPerFile(0),
fNEventsInContainer(0),
fEvent(0),
fFileNumber(0),
fTreeName(""),
fFileBase("")
{
// Constructor
//
// Parameters:
// name The name
}
//____________________________________________________________________
TString*
AliMCAuxHandler::GetParentPath() const
{
if (!fParent) {
AliWarning("No parent");
return 0;
}
return fParent->GetInputPath();
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Init(Option_t* opt)
{
// Initialize the input
//
// @param opt Options
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::Init(\"%s\")", opt);
TString option(opt);
if (option.EqualTo("proof") || option.EqualTo("local")) return true;
TString t = "Tree";
TString b = "";
TClass* cl = gROOT->GetClass(GetTitle());
if (cl) {
if (cl->InheritsFrom("AliHit")) {
t += "H";
b = "Hits";
}
else if (cl->InheritsFrom("AliSDigit")) {
t += "S";
b = "SDigits";
}
else if (cl->InheritsFrom("AliDigit")) {
t += "D";
b = "Digits";
}
else
t = "";
}
if (!t.IsNull()) fTreeName = t;
if (!b.IsNull()) fFileBase = b;
fArray = new TClonesArray(GetTitle());
TTree* treeE = fParent->GetTree();
if (!treeE) {
AliError("Parent does not have an events tree");
return false;
}
// Get number of events in this directory
fNEventsPerFile = -1;
fNEvents = treeE->GetEntries();
fEvent = 0;
fFileNumber = 0;
if (!OpenFile(fFileNumber)) return false;
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::BeginEvent(Long64_t entry)
{
// Called at the beginning of an event
//
// @param entry Entry in tree
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::BeginEvent(%lld)", entry);
if (entry == -1)
fEvent++;
else
fEvent = entry;
if (fEvent >= fNEvents) {
AliWarningF("Event number out of range %d/%d", fEvent, fNEvents);
return false;
}
if (fNEventsPerFile < 0) {
TTree* treeK = fParent->TreeK();
if (!treeK) {
AliError("Parent does not have a kinematics tree");
return false;
}
TFile* fileK = treeK->GetCurrentFile();
if (!fileK) {
AliError("Kinematics tree has no associated file");
return false;
}
// Get the number of events per file
fNEventsPerFile = fileK->GetNkeys() - fileK->GetNProcessIDs();
}
return LoadEvent(fEvent);
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Notify(const char* path)
{
// Called when the input file is changed
//
// @param path New path
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::Notify(\"%s\")", path);
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::FinishEvent()
{
// Called at the end of an event
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::FinishEvent()");
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Terminate()
{
// Called at the end of a job
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::Terminate()");
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::TerminateIO()
{
// Called at the end of a sub-job
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::TerminateIO()");
return true;
}
//____________________________________________________________________
void
AliMCAuxHandler::ResetIO()
{
// Reset the I/O
//
//
AliDebug(10,"AliMCAuxHandler::ResetIO()");
TString* path = GetParentPath();
AliDebugF(10,"Got parent path %s", path ? path->Data() : "null");
if (fFile) {
delete fFile;
fFile = 0;
}
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::OpenFile(Int_t fileNo)
{
TString* path = GetParentPath();
AliDebugF(10,"Got parent path %s", path ? path->Data() : "null");
if (!path) return false;
TString ext("");
if (fileNo > 0) ext = TString::Format("%d", fileNo);
TString w(GetTitle());
if (w.EndsWith("s")) w.Chop();
TString fn = TString::Format("%s%s.%s%s.root",
path->Data(), GetName(),
fFileBase.Data(), ext.Data());
Info("Init", "Opening %s", fn.Data());
fFile = TFile::Open(fn, "READ");
if (!fFile) {
AliErrorF("Failed to open %s", fn.Data());
return false;
}
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::LoadEvent(Int_t iev)
{
// Load an event
//
// @param iev Event number
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::LoadEvent(%d)", iev);
Int_t iNew = iev / fNEventsPerFile;
if (iNew != fFileNumber) {
fFileNumber = iNew;
if (!OpenFile(fFileNumber)) return false;
}
if (!fFile) return false;
TString folder = TString::Format("Event%d", iev);
fFile->GetObject(folder, fDir);
if (!fDir) {
AliWarningF("Folder %s not found in file", folder.Data());
return false;
}
fDir->GetObject(fTreeName, fTree);
if (!fTree) {
AliWarningF("Folder %s does not contain the %s tree %s",
folder.Data(), GetTitle(), fTreeName.Data());
return false;
}
fTree->SetBranchAddress(GetName(), &fArray);
return true;
}
//____________________________________________________________________
Int_t
AliMCAuxHandler::GetNEntry() const
{
if (!fTree) return 0;
return fTree->GetEntries();
}
//____________________________________________________________________
TClonesArray*
AliMCAuxHandler::GetEntryArray(Int_t entry)
{
if (!fTree) return 0;
if (!fArray) return 0;
if (entry < 0 || entry >= fTree->GetEntries()) {
AliErrorF("Entry # %d out of bounds [0,%lld]",
entry, fTree->GetEntries());
return 0;
}
fArray->Clear();
if (fTree->GetEntry(entry) <= 0) return 0;
return fArray;
}
//____________________________________________________________________
AliMCAuxHandler*
AliMCAuxHandler::Create(const char* name, const char* what)
{
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AliMCAuxHandler::Create", "No analysis manager");
return 0;
}
AliVEventHandler* vmc = mgr->GetMCtruthEventHandler();
if (!vmc) {
::Error("AliMCAuxHandler::Create", "No MC truth handler");
return 0;
}
AliMCEventHandler* mc = dynamic_cast<AliMCEventHandler*>(vmc);
if (!mc) {
::Error("AliMCAuxHandler::Create",
"MC truth handler not a AliMCEventHandler, but %s",
vmc->ClassName());
return 0;
}
AliMCAuxHandler* ret = new AliMCAuxHandler(name, what, mc);
mc->AddSubsidiaryHandler(ret);
return ret;
}
//____________________________________________________________________
TClonesArray*
AliMCAuxHandler::GetParticleArray(AliMCAuxHandler* handler,
Int_t particle)
{
if (!handler) {
::Error("AliMCAuxHandler::GetArray", "No handler passed");
return 0;
}
AliMCEventHandler* mc = handler->GetParent();
if (!mc) {
::Error("AliMCAuxHandler::GetArray", "Handler has no parent");
return 0;
}
AliMCEvent* event = mc->MCEvent();
if (!event) {
::Error("AliMCAuxHandler::GetArray", "No MC event");
return 0;
}
AliStack* stack = event->Stack();
if (!event) {
::Error("AliMCAuxHandler::GetArray", "Event has no stack");
return 0;
}
handler->GetArray()->Clear();
TTree* tree = handler->GetTree();
if (!tree) {
::Error("AliMCAuxHandler::GetArray", "Handler has no tree");
return 0;
}
Int_t treeIdx = stack->TreeKEntry(particle);
if (treeIdx < 0 || treeIdx >= tree->GetEntries()) {
::Error("AliMCAuxHandler::GetArray",
"Index %d of %d out of bounds [0,%lld]", treeIdx, particle,
tree->GetEntries()-1);
return 0;
}
tree->GetEntry(treeIdx);
return handler->GetArray();
}
//____________________________________________________________________
//
// EOF
//
<commit_msg>Fixed check of returned pointer to AliStack object<commit_after>#include "AliMCAuxHandler.h"
#include "AliAnalysisManager.h"
#include <TError.h>
#include <AliLog.h>
#include <TFile.h>
#include <TClonesArray.h>
#include <TROOT.h>
#include <AliStack.h>
#include <AliMCEvent.h>
ClassImp(AliMCAuxHandler)
#if 0 // For Emacs - do not remove
;
#endif
//____________________________________________________________________
AliMCAuxHandler::AliMCAuxHandler(const char* name,
const char* what,
AliMCEventHandler* parent)
: AliMCEventHandler(name, what),
fParent(parent),
fFile(0),
fTree(0),
fDir(0),
fArray(0),
fNEvents(0),
fNEventsPerFile(0),
fNEventsInContainer(0),
fEvent(0),
fFileNumber(0),
fTreeName(""),
fFileBase("")
{
// Constructor
//
// Parameters:
// name The name
}
//____________________________________________________________________
TString*
AliMCAuxHandler::GetParentPath() const
{
if (!fParent) {
AliWarning("No parent");
return 0;
}
return fParent->GetInputPath();
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Init(Option_t* opt)
{
// Initialize the input
//
// @param opt Options
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::Init(\"%s\")", opt);
TString option(opt);
if (option.EqualTo("proof") || option.EqualTo("local")) return true;
TString t = "Tree";
TString b = "";
TClass* cl = gROOT->GetClass(GetTitle());
if (cl) {
if (cl->InheritsFrom("AliHit")) {
t += "H";
b = "Hits";
}
else if (cl->InheritsFrom("AliSDigit")) {
t += "S";
b = "SDigits";
}
else if (cl->InheritsFrom("AliDigit")) {
t += "D";
b = "Digits";
}
else
t = "";
}
if (!t.IsNull()) fTreeName = t;
if (!b.IsNull()) fFileBase = b;
fArray = new TClonesArray(GetTitle());
TTree* treeE = fParent->GetTree();
if (!treeE) {
AliError("Parent does not have an events tree");
return false;
}
// Get number of events in this directory
fNEventsPerFile = -1;
fNEvents = treeE->GetEntries();
fEvent = 0;
fFileNumber = 0;
if (!OpenFile(fFileNumber)) return false;
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::BeginEvent(Long64_t entry)
{
// Called at the beginning of an event
//
// @param entry Entry in tree
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::BeginEvent(%lld)", entry);
if (entry == -1)
fEvent++;
else
fEvent = entry;
if (fEvent >= fNEvents) {
AliWarningF("Event number out of range %d/%d", fEvent, fNEvents);
return false;
}
if (fNEventsPerFile < 0) {
TTree* treeK = fParent->TreeK();
if (!treeK) {
AliError("Parent does not have a kinematics tree");
return false;
}
TFile* fileK = treeK->GetCurrentFile();
if (!fileK) {
AliError("Kinematics tree has no associated file");
return false;
}
// Get the number of events per file
fNEventsPerFile = fileK->GetNkeys() - fileK->GetNProcessIDs();
}
return LoadEvent(fEvent);
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Notify(const char* path)
{
// Called when the input file is changed
//
// @param path New path
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::Notify(\"%s\")", path);
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::FinishEvent()
{
// Called at the end of an event
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::FinishEvent()");
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::Terminate()
{
// Called at the end of a job
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::Terminate()");
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::TerminateIO()
{
// Called at the end of a sub-job
//
// @return true on success
AliDebug(10,"AliMCAuxHandler::TerminateIO()");
return true;
}
//____________________________________________________________________
void
AliMCAuxHandler::ResetIO()
{
// Reset the I/O
//
//
AliDebug(10,"AliMCAuxHandler::ResetIO()");
TString* path = GetParentPath();
AliDebugF(10,"Got parent path %s", path ? path->Data() : "null");
if (fFile) {
delete fFile;
fFile = 0;
}
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::OpenFile(Int_t fileNo)
{
TString* path = GetParentPath();
AliDebugF(10,"Got parent path %s", path ? path->Data() : "null");
if (!path) return false;
TString ext("");
if (fileNo > 0) ext = TString::Format("%d", fileNo);
TString w(GetTitle());
if (w.EndsWith("s")) w.Chop();
TString fn = TString::Format("%s%s.%s%s.root",
path->Data(), GetName(),
fFileBase.Data(), ext.Data());
Info("Init", "Opening %s", fn.Data());
fFile = TFile::Open(fn, "READ");
if (!fFile) {
AliErrorF("Failed to open %s", fn.Data());
return false;
}
return true;
}
//____________________________________________________________________
Bool_t
AliMCAuxHandler::LoadEvent(Int_t iev)
{
// Load an event
//
// @param iev Event number
//
// @return true on success
AliDebugF(10,"AliMCAuxHandler::LoadEvent(%d)", iev);
Int_t iNew = iev / fNEventsPerFile;
if (iNew != fFileNumber) {
fFileNumber = iNew;
if (!OpenFile(fFileNumber)) return false;
}
if (!fFile) return false;
TString folder = TString::Format("Event%d", iev);
fFile->GetObject(folder, fDir);
if (!fDir) {
AliWarningF("Folder %s not found in file", folder.Data());
return false;
}
fDir->GetObject(fTreeName, fTree);
if (!fTree) {
AliWarningF("Folder %s does not contain the %s tree %s",
folder.Data(), GetTitle(), fTreeName.Data());
return false;
}
fTree->SetBranchAddress(GetName(), &fArray);
return true;
}
//____________________________________________________________________
Int_t
AliMCAuxHandler::GetNEntry() const
{
if (!fTree) return 0;
return fTree->GetEntries();
}
//____________________________________________________________________
TClonesArray*
AliMCAuxHandler::GetEntryArray(Int_t entry)
{
if (!fTree) return 0;
if (!fArray) return 0;
if (entry < 0 || entry >= fTree->GetEntries()) {
AliErrorF("Entry # %d out of bounds [0,%lld]",
entry, fTree->GetEntries());
return 0;
}
fArray->Clear();
if (fTree->GetEntry(entry) <= 0) return 0;
return fArray;
}
//____________________________________________________________________
AliMCAuxHandler*
AliMCAuxHandler::Create(const char* name, const char* what)
{
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AliMCAuxHandler::Create", "No analysis manager");
return 0;
}
AliVEventHandler* vmc = mgr->GetMCtruthEventHandler();
if (!vmc) {
::Error("AliMCAuxHandler::Create", "No MC truth handler");
return 0;
}
AliMCEventHandler* mc = dynamic_cast<AliMCEventHandler*>(vmc);
if (!mc) {
::Error("AliMCAuxHandler::Create",
"MC truth handler not a AliMCEventHandler, but %s",
vmc->ClassName());
return 0;
}
AliMCAuxHandler* ret = new AliMCAuxHandler(name, what, mc);
mc->AddSubsidiaryHandler(ret);
return ret;
}
//____________________________________________________________________
TClonesArray*
AliMCAuxHandler::GetParticleArray(AliMCAuxHandler* handler,
Int_t particle)
{
if (!handler) {
::Error("AliMCAuxHandler::GetArray", "No handler passed");
return 0;
}
AliMCEventHandler* mc = handler->GetParent();
if (!mc) {
::Error("AliMCAuxHandler::GetArray", "Handler has no parent");
return 0;
}
AliMCEvent* event = mc->MCEvent();
if (!event) {
::Error("AliMCAuxHandler::GetArray", "No MC event");
return 0;
}
AliStack* stack = event->Stack();
if (!stack) {
::Error("AliMCAuxHandler::GetArray", "Event has no stack");
return 0;
}
handler->GetArray()->Clear();
TTree* tree = handler->GetTree();
if (!tree) {
::Error("AliMCAuxHandler::GetArray", "Handler has no tree");
return 0;
}
Int_t treeIdx = stack->TreeKEntry(particle);
if (treeIdx < 0 || treeIdx >= tree->GetEntries()) {
::Error("AliMCAuxHandler::GetArray",
"Index %d of %d out of bounds [0,%lld]", treeIdx, particle,
tree->GetEntries()-1);
return 0;
}
tree->GetEntry(treeIdx);
return handler->GetArray();
}
//____________________________________________________________________
//
// EOF
//
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Google 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 Google Inc. 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.
*/
#include "config.h"
#include "modules/crypto/NormalizeAlgorithm.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "public/platform/WebCryptoAlgorithm.h"
#include "public/platform/WebCryptoAlgorithmParams.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/ArrayBufferView.h"
#include "wtf/HashMap.h"
#include "wtf/Uint8Array.h"
#include "wtf/Vector.h"
#include "wtf/text/StringHash.h"
namespace WebCore {
namespace {
struct AlgorithmNameMapping {
const char* const algorithmName;
WebKit::WebCryptoAlgorithmId algorithmId;
};
// Indicates that the algorithm doesn't support the specified operation.
const int UnsupportedOp = -1;
// Either UnsupportedOp, or a value from WebKit::WebCryptoAlgorithmParamsType
typedef int AlgorithmParamsForOperation;
struct OperationParamsMapping {
WebKit::WebCryptoAlgorithmId algorithmId;
AlgorithmOperation operation;
AlgorithmParamsForOperation params;
};
const AlgorithmNameMapping algorithmNameMappings[] = {
{"AES-CBC", WebKit::WebCryptoAlgorithmIdAesCbc},
{"HMAC", WebKit::WebCryptoAlgorithmIdHmac},
{"RSASSA-PKCS1-v1_5", WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5},
{"SHA-1", WebKit::WebCryptoAlgorithmIdSha1},
{"SHA-224", WebKit::WebCryptoAlgorithmIdSha224},
{"SHA-256", WebKit::WebCryptoAlgorithmIdSha256},
{"SHA-384", WebKit::WebCryptoAlgorithmIdSha384},
{"SHA-512", WebKit::WebCryptoAlgorithmIdSha512},
};
// What operations each algorithm supports, and what parameters it expects.
const OperationParamsMapping operationParamsMappings[] = {
// AES-CBC (section 18.10.)
{WebKit::WebCryptoAlgorithmIdAesCbc, Decrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, Encrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},
// HMAC (section 18.14.)
{WebKit::WebCryptoAlgorithmIdHmac, Sign, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, Verify, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
// RSASSA-PKCS1-v1_5 (section 18.4.)
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Sign, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Verify, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-1 (section 18.16.)
{WebKit::WebCryptoAlgorithmIdSha1, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-224 (section 18.16.)
{WebKit::WebCryptoAlgorithmIdSha224, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-256 (section 18.16.)
{WebKit::WebCryptoAlgorithmIdSha256, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-384 (section 18.16.)
{WebKit::WebCryptoAlgorithmIdSha384, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-512 (section 18.16.)
{WebKit::WebCryptoAlgorithmIdSha512, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
};
// This structure describes an algorithm and its supported operations.
struct AlgorithmInfo {
AlgorithmInfo()
: algorithmName(0)
{
for (size_t i = 0; i < WTF_ARRAY_LENGTH(paramsForOperation); ++i)
paramsForOperation[i] = UnsupportedOp;
}
WebKit::WebCryptoAlgorithmId algorithmId;
const char* algorithmName;
AlgorithmParamsForOperation paramsForOperation[NumberOfAlgorithmOperations];
};
// AlgorithmRegistry enumerates each of the different algorithms and its
// parameters. This describes the same information as the static tables above,
// but in a more convenient runtime form.
class AlgorithmRegistry {
public:
static const AlgorithmInfo* lookupAlgorithmByName(const String& algorithmName);
private:
AlgorithmRegistry();
// Algorithm name to ID.
typedef HashMap<String, WebKit::WebCryptoAlgorithmId, CaseFoldingHash> AlgorithmNameToIdMap;
AlgorithmNameToIdMap m_algorithmNameToId;
// Algorithm ID to information.
AlgorithmInfo m_algorithms[WebKit::NumberOfWebCryptoAlgorithmId];
};
const AlgorithmInfo* AlgorithmRegistry::lookupAlgorithmByName(const String& algorithmName)
{
DEFINE_STATIC_LOCAL(AlgorithmRegistry, registry, ());
AlgorithmNameToIdMap::const_iterator it = registry.m_algorithmNameToId.find(algorithmName);
if (it == registry.m_algorithmNameToId.end())
return 0;
return ®istry.m_algorithms[it->value];
}
AlgorithmRegistry::AlgorithmRegistry()
{
for (size_t i = 0; i < WTF_ARRAY_LENGTH(algorithmNameMappings); ++i) {
const AlgorithmNameMapping& mapping = algorithmNameMappings[i];
m_algorithmNameToId.add(mapping.algorithmName, mapping.algorithmId);
m_algorithms[mapping.algorithmId].algorithmName = mapping.algorithmName;
m_algorithms[mapping.algorithmId].algorithmId = mapping.algorithmId;
}
for (size_t i = 0; i < WTF_ARRAY_LENGTH(operationParamsMappings); ++i) {
const OperationParamsMapping& mapping = operationParamsMappings[i];
m_algorithms[mapping.algorithmId].paramsForOperation[mapping.operation] = mapping.params;
}
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesCbcParams(const Dictionary& raw)
{
RefPtr<ArrayBufferView> iv;
if (!raw.get("iv", iv) || !iv)
return nullptr;
if (iv->byteLength() != 16)
return nullptr;
return adoptPtr(new WebKit::WebCryptoAesCbcParams(static_cast<unsigned char*>(iv->baseAddress()), iv->byteLength()));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesKeyGenParams(const Dictionary& raw)
{
int32_t length;
if (!raw.get("length", length))
return nullptr;
if (length < 0 || length > 0xFFFF)
return nullptr;
return adoptPtr(new WebKit::WebCryptoAesKeyGenParams(length));
}
bool parseHash(const Dictionary& raw, WebKit::WebCryptoAlgorithm& hash)
{
Dictionary rawHash;
if (!raw.get("hash", rawHash))
return false;
TrackExceptionState es;
return normalizeAlgorithm(rawHash, Digest, hash, es);
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseHmacParams(const Dictionary& raw)
{
WebKit::WebCryptoAlgorithm hash;
if (!parseHash(raw, hash))
return nullptr;
return adoptPtr(new WebKit::WebCryptoHmacParams(hash));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaSsaParams(const Dictionary& raw)
{
WebKit::WebCryptoAlgorithm hash;
if (!parseHash(raw, hash))
return nullptr;
return adoptPtr(new WebKit::WebCryptoRsaSsaParams(hash));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaKeyGenParams(const Dictionary& raw)
{
// FIXME: This is losing precision; modulusLength is supposed to be a uint32
int32_t modulusLength;
if (!raw.get("modulusLength", modulusLength))
return nullptr;
if (modulusLength < 0)
return nullptr;
RefPtr<Uint8Array> publicExponent;
if (!raw.get("publicExponent", publicExponent) || !publicExponent)
return nullptr;
return adoptPtr(new WebKit::WebCryptoRsaKeyGenParams(modulusLength, static_cast<const unsigned char*>(publicExponent->baseAddress()), publicExponent->byteLength()));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAlgorithmParams(const Dictionary& raw, WebKit::WebCryptoAlgorithmParamsType type)
{
switch (type) {
case WebKit::WebCryptoAlgorithmParamsTypeNone:
return nullptr;
case WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams:
return parseAesCbcParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams:
return parseAesKeyGenParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeHmacParams:
return parseHmacParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams:
return parseRsaSsaParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams:
return parseRsaKeyGenParams(raw);
}
ASSERT_NOT_REACHED();
return nullptr;
}
const AlgorithmInfo* algorithmInfo(const Dictionary& raw, ExceptionState& es)
{
String algorithmName;
if (!raw.get("name", algorithmName)) {
es.throwDOMException(NotSupportedError);
return 0;
}
if (!algorithmName.containsOnlyASCII()) {
es.throwDOMException(SyntaxError);
return 0;
}
const AlgorithmInfo* info = AlgorithmRegistry::lookupAlgorithmByName(algorithmName);
if (!info) {
es.throwDOMException(NotSupportedError);
return 0;
}
return info;
}
} // namespace
// FIXME: Throw the correct exception types!
// This implementation corresponds with:
// http://www.w3.org/TR/WebCryptoAPI/#algorithm-normalizing-rules
bool normalizeAlgorithm(const Dictionary& raw, AlgorithmOperation op, WebKit::WebCryptoAlgorithm& algorithm, ExceptionState& es)
{
const AlgorithmInfo* info = algorithmInfo(raw, es);
if (!info)
return false;
if (info->paramsForOperation[op] == UnsupportedOp) {
es.throwDOMException(NotSupportedError);
return false;
}
WebKit::WebCryptoAlgorithmParamsType paramsType = static_cast<WebKit::WebCryptoAlgorithmParamsType>(info->paramsForOperation[op]);
OwnPtr<WebKit::WebCryptoAlgorithmParams> params = parseAlgorithmParams(raw, paramsType);
if (!params && paramsType != WebKit::WebCryptoAlgorithmParamsTypeNone) {
es.throwDOMException(NotSupportedError);
return false;
}
algorithm = WebKit::WebCryptoAlgorithm(info->algorithmId, info->algorithmName, params.release());
return true;
}
} // namespace WebCore
<commit_msg>Remove references to specific WebCrypto section number in code comments.<commit_after>/*
* Copyright (C) 2013 Google 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 Google Inc. 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.
*/
#include "config.h"
#include "modules/crypto/NormalizeAlgorithm.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "public/platform/WebCryptoAlgorithm.h"
#include "public/platform/WebCryptoAlgorithmParams.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/ArrayBufferView.h"
#include "wtf/HashMap.h"
#include "wtf/Uint8Array.h"
#include "wtf/Vector.h"
#include "wtf/text/StringHash.h"
namespace WebCore {
namespace {
struct AlgorithmNameMapping {
const char* const algorithmName;
WebKit::WebCryptoAlgorithmId algorithmId;
};
// Indicates that the algorithm doesn't support the specified operation.
const int UnsupportedOp = -1;
// Either UnsupportedOp, or a value from WebKit::WebCryptoAlgorithmParamsType
typedef int AlgorithmParamsForOperation;
struct OperationParamsMapping {
WebKit::WebCryptoAlgorithmId algorithmId;
AlgorithmOperation operation;
AlgorithmParamsForOperation params;
};
const AlgorithmNameMapping algorithmNameMappings[] = {
{"AES-CBC", WebKit::WebCryptoAlgorithmIdAesCbc},
{"HMAC", WebKit::WebCryptoAlgorithmIdHmac},
{"RSASSA-PKCS1-v1_5", WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5},
{"SHA-1", WebKit::WebCryptoAlgorithmIdSha1},
{"SHA-224", WebKit::WebCryptoAlgorithmIdSha224},
{"SHA-256", WebKit::WebCryptoAlgorithmIdSha256},
{"SHA-384", WebKit::WebCryptoAlgorithmIdSha384},
{"SHA-512", WebKit::WebCryptoAlgorithmIdSha512},
};
// What operations each algorithm supports, and what parameters it expects.
const OperationParamsMapping operationParamsMappings[] = {
// AES-CBC
{WebKit::WebCryptoAlgorithmIdAesCbc, Decrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, Encrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams},
{WebKit::WebCryptoAlgorithmIdAesCbc, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},
// HMAC
{WebKit::WebCryptoAlgorithmIdHmac, Sign, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, Verify, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
{WebKit::WebCryptoAlgorithmIdHmac, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},
// RSASSA-PKCS1-v1_5
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Sign, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Verify, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams},
{WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},
// SHA-*
{WebKit::WebCryptoAlgorithmIdSha1, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
{WebKit::WebCryptoAlgorithmIdSha224, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
{WebKit::WebCryptoAlgorithmIdSha256, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
{WebKit::WebCryptoAlgorithmIdSha384, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
{WebKit::WebCryptoAlgorithmIdSha512, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},
};
// This structure describes an algorithm and its supported operations.
struct AlgorithmInfo {
AlgorithmInfo()
: algorithmName(0)
{
for (size_t i = 0; i < WTF_ARRAY_LENGTH(paramsForOperation); ++i)
paramsForOperation[i] = UnsupportedOp;
}
WebKit::WebCryptoAlgorithmId algorithmId;
const char* algorithmName;
AlgorithmParamsForOperation paramsForOperation[NumberOfAlgorithmOperations];
};
// AlgorithmRegistry enumerates each of the different algorithms and its
// parameters. This describes the same information as the static tables above,
// but in a more convenient runtime form.
class AlgorithmRegistry {
public:
static const AlgorithmInfo* lookupAlgorithmByName(const String& algorithmName);
private:
AlgorithmRegistry();
// Algorithm name to ID.
typedef HashMap<String, WebKit::WebCryptoAlgorithmId, CaseFoldingHash> AlgorithmNameToIdMap;
AlgorithmNameToIdMap m_algorithmNameToId;
// Algorithm ID to information.
AlgorithmInfo m_algorithms[WebKit::NumberOfWebCryptoAlgorithmId];
};
const AlgorithmInfo* AlgorithmRegistry::lookupAlgorithmByName(const String& algorithmName)
{
DEFINE_STATIC_LOCAL(AlgorithmRegistry, registry, ());
AlgorithmNameToIdMap::const_iterator it = registry.m_algorithmNameToId.find(algorithmName);
if (it == registry.m_algorithmNameToId.end())
return 0;
return ®istry.m_algorithms[it->value];
}
AlgorithmRegistry::AlgorithmRegistry()
{
for (size_t i = 0; i < WTF_ARRAY_LENGTH(algorithmNameMappings); ++i) {
const AlgorithmNameMapping& mapping = algorithmNameMappings[i];
m_algorithmNameToId.add(mapping.algorithmName, mapping.algorithmId);
m_algorithms[mapping.algorithmId].algorithmName = mapping.algorithmName;
m_algorithms[mapping.algorithmId].algorithmId = mapping.algorithmId;
}
for (size_t i = 0; i < WTF_ARRAY_LENGTH(operationParamsMappings); ++i) {
const OperationParamsMapping& mapping = operationParamsMappings[i];
m_algorithms[mapping.algorithmId].paramsForOperation[mapping.operation] = mapping.params;
}
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesCbcParams(const Dictionary& raw)
{
RefPtr<ArrayBufferView> iv;
if (!raw.get("iv", iv) || !iv)
return nullptr;
if (iv->byteLength() != 16)
return nullptr;
return adoptPtr(new WebKit::WebCryptoAesCbcParams(static_cast<unsigned char*>(iv->baseAddress()), iv->byteLength()));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesKeyGenParams(const Dictionary& raw)
{
int32_t length;
if (!raw.get("length", length))
return nullptr;
if (length < 0 || length > 0xFFFF)
return nullptr;
return adoptPtr(new WebKit::WebCryptoAesKeyGenParams(length));
}
bool parseHash(const Dictionary& raw, WebKit::WebCryptoAlgorithm& hash)
{
Dictionary rawHash;
if (!raw.get("hash", rawHash))
return false;
TrackExceptionState es;
return normalizeAlgorithm(rawHash, Digest, hash, es);
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseHmacParams(const Dictionary& raw)
{
WebKit::WebCryptoAlgorithm hash;
if (!parseHash(raw, hash))
return nullptr;
return adoptPtr(new WebKit::WebCryptoHmacParams(hash));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaSsaParams(const Dictionary& raw)
{
WebKit::WebCryptoAlgorithm hash;
if (!parseHash(raw, hash))
return nullptr;
return adoptPtr(new WebKit::WebCryptoRsaSsaParams(hash));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaKeyGenParams(const Dictionary& raw)
{
// FIXME: This is losing precision; modulusLength is supposed to be a uint32
int32_t modulusLength;
if (!raw.get("modulusLength", modulusLength))
return nullptr;
if (modulusLength < 0)
return nullptr;
RefPtr<Uint8Array> publicExponent;
if (!raw.get("publicExponent", publicExponent) || !publicExponent)
return nullptr;
return adoptPtr(new WebKit::WebCryptoRsaKeyGenParams(modulusLength, static_cast<const unsigned char*>(publicExponent->baseAddress()), publicExponent->byteLength()));
}
PassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAlgorithmParams(const Dictionary& raw, WebKit::WebCryptoAlgorithmParamsType type)
{
switch (type) {
case WebKit::WebCryptoAlgorithmParamsTypeNone:
return nullptr;
case WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams:
return parseAesCbcParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams:
return parseAesKeyGenParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeHmacParams:
return parseHmacParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams:
return parseRsaSsaParams(raw);
case WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams:
return parseRsaKeyGenParams(raw);
}
ASSERT_NOT_REACHED();
return nullptr;
}
const AlgorithmInfo* algorithmInfo(const Dictionary& raw, ExceptionState& es)
{
String algorithmName;
if (!raw.get("name", algorithmName)) {
es.throwDOMException(NotSupportedError);
return 0;
}
if (!algorithmName.containsOnlyASCII()) {
es.throwDOMException(SyntaxError);
return 0;
}
const AlgorithmInfo* info = AlgorithmRegistry::lookupAlgorithmByName(algorithmName);
if (!info) {
es.throwDOMException(NotSupportedError);
return 0;
}
return info;
}
} // namespace
// FIXME: Throw the correct exception types!
// This implementation corresponds with:
// http://www.w3.org/TR/WebCryptoAPI/#algorithm-normalizing-rules
bool normalizeAlgorithm(const Dictionary& raw, AlgorithmOperation op, WebKit::WebCryptoAlgorithm& algorithm, ExceptionState& es)
{
const AlgorithmInfo* info = algorithmInfo(raw, es);
if (!info)
return false;
if (info->paramsForOperation[op] == UnsupportedOp) {
es.throwDOMException(NotSupportedError);
return false;
}
WebKit::WebCryptoAlgorithmParamsType paramsType = static_cast<WebKit::WebCryptoAlgorithmParamsType>(info->paramsForOperation[op]);
OwnPtr<WebKit::WebCryptoAlgorithmParams> params = parseAlgorithmParams(raw, paramsType);
if (!params && paramsType != WebKit::WebCryptoAlgorithmParamsTypeNone) {
es.throwDOMException(NotSupportedError);
return false;
}
algorithm = WebKit::WebCryptoAlgorithm(info->algorithmId, info->algorithmName, params.release());
return true;
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Framework/PoseComponent.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/OdeSolverEulerExplicit.h"
#include "SurgSim/Math/OdeSolverEulerExplicitModified.h"
#include "SurgSim/Math/OdeSolverEulerImplicit.h"
#include "SurgSim/Math/OdeSolverRungeKutta4.h"
#include "SurgSim/Math/OdeSolverLinearEulerExplicit.h"
#include "SurgSim/Math/OdeSolverLinearEulerExplicitModified.h"
#include "SurgSim/Math/OdeSolverLinearEulerImplicit.h"
#include "SurgSim/Math/OdeSolverLinearRungeKutta4.h"
#include "SurgSim/Math/OdeSolverLinearStatic.h"
#include "SurgSim/Math/OdeSolverStatic.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
namespace SurgSim
{
namespace Physics
{
DeformableRepresentation::DeformableRepresentation(const std::string& name) :
Representation(name),
SurgSim::Math::OdeEquation(),
m_numDofPerNode(0),
m_integrationScheme(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)
{
SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, SurgSim::Math::IntegrationScheme, IntegrationScheme,
getIntegrationScheme, setIntegrationScheme);
SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, std::shared_ptr<SurgSim::Collision::Representation>,
CollisionRepresentation, getCollisionRepresentation, setCollisionRepresentation);
}
DeformableRepresentation::~DeformableRepresentation()
{
}
void DeformableRepresentation::resetState()
{
Representation::resetState();
// Reminder: m_initialState is being held in OdeEquation
*m_currentState = *m_initialState;
*m_previousState = *m_initialState;
// m_newState does not need to be reset, it is a temporary variable
*m_finalState = *m_initialState;
}
void DeformableRepresentation::setInitialState(
std::shared_ptr<SurgSim::Math::OdeState> initialState)
{
// This initializes and allocates the m_initialState data member
m_initialState = initialState;
m_previousState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_currentState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_newState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_finalState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
// Set the representation number of degree of freedom
setNumDof(m_initialState->getNumDof());
SurgSim::Math::resizeVector(&m_externalGeneralizedForce, getNumDof(), true);
SurgSim::Math::resizeMatrix(&m_externalGeneralizedStiffness, getNumDof(), getNumDof(), true);
SurgSim::Math::resizeMatrix(&m_externalGeneralizedDamping, getNumDof(), getNumDof(), true);
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getCurrentState() const
{
return m_currentState;
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getPreviousState() const
{
return m_previousState;
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getFinalState() const
{
return m_finalState;
}
size_t DeformableRepresentation::getNumDofPerNode() const
{
return m_numDofPerNode;
}
void DeformableRepresentation::setIntegrationScheme(SurgSim::Math::IntegrationScheme integrationScheme)
{
SURGSIM_ASSERT(!isAwake()) << "You cannot set the integration scheme after the component has been awoken";
m_integrationScheme = integrationScheme;
}
SurgSim::Math::IntegrationScheme DeformableRepresentation::getIntegrationScheme() const
{
return m_integrationScheme;
}
const SurgSim::Math::Vector& DeformableRepresentation::getExternalGeneralizedForce() const
{
return m_externalGeneralizedForce;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedStiffness() const
{
return m_externalGeneralizedStiffness;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedDamping() const
{
return m_externalGeneralizedDamping;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getComplianceMatrix() const
{
SURGSIM_ASSERT(m_odeSolver) << "Ode solver not initialized, it should have been initialized on wake-up";
return m_odeSolver->getCompliance();
}
void DeformableRepresentation::update(double dt)
{
if (! isActive())
{
return;
}
SURGSIM_ASSERT(m_odeSolver != nullptr) <<
"Ode solver has not been set yet. Did you call beforeUpdate() ?";
SURGSIM_ASSERT(m_initialState != nullptr) <<
"Initial state has not been set yet. Did you call setInitialState() ?";
// Solve the ode
m_odeSolver->solve(dt, *m_currentState, m_newState.get());
// Back up the current state into the previous state (by swapping)
m_currentState.swap(m_previousState);
// Make the new state, the current state (by swapping)
m_currentState.swap(m_newState);
if (!m_currentState->isValid())
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated :" << std::endl
<< "position=(" << m_currentState->getPositions().transpose() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities().transpose() << ")" << std::endl;
setActive(false);
}
}
void DeformableRepresentation::afterUpdate(double dt)
{
if (! isActive())
{
return;
}
driveSceneElementPose(SurgSim::Math::RigidTransform3d::Identity());
// Back up the current state into the final state
*m_finalState = *m_currentState;
// Reset the external generalized force, stiffness and damping
m_externalGeneralizedForce.setZero();
m_externalGeneralizedStiffness.setZero();
m_externalGeneralizedDamping.setZero();
}
void DeformableRepresentation::applyCorrection(double dt,
const Eigen::VectorBlock<SurgSim::Math::Vector>& deltaVelocity)
{
if (!isActive())
{
return;
}
m_currentState->getPositions() += deltaVelocity * dt;
m_currentState->getVelocities() += deltaVelocity;
if (!m_currentState->isValid())
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated :" << std::endl
<< "position=(" << m_currentState->getPositions() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities() << ")" << std::endl;
setActive(false);
}
}
void DeformableRepresentation::deactivateAndReset(void)
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated and reset:" << std::endl
<< "position=(" << m_currentState->getPositions() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities() << ")" << std::endl;
resetState();
setActive(false);
}
void DeformableRepresentation::setCollisionRepresentation(
std::shared_ptr<SurgSim::Collision::Representation> representation)
{
if (m_collisionRepresentation != representation)
{
// If we have an old collision representation clear the dependency if it was a deformable collision
// representation
auto oldCollisionRep =
std::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation);
if (oldCollisionRep != nullptr)
{
oldCollisionRep->setDeformableRepresentation(nullptr);
}
Representation::setCollisionRepresentation(representation);
// If its a RigidCollisionRepresentation connect with this representation
auto newCollisionRep = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(representation);
if (newCollisionRep != nullptr)
{
newCollisionRep->setDeformableRepresentation(
std::static_pointer_cast<DeformableRepresentation>(getSharedPtr()));
}
}
}
bool DeformableRepresentation::doWakeUp()
{
using SurgSim::Math::OdeSolverEulerExplicit;
using SurgSim::Math::OdeSolverEulerExplicitModified;
using SurgSim::Math::OdeSolverEulerImplicit;
using SurgSim::Math::OdeSolverRungeKutta4;
using SurgSim::Math::OdeSolverStatic;
using SurgSim::Math::OdeSolverLinearEulerExplicit;
using SurgSim::Math::OdeSolverLinearEulerExplicitModified;
using SurgSim::Math::OdeSolverLinearEulerImplicit;
using SurgSim::Math::OdeSolverLinearRungeKutta4;
using SurgSim::Math::OdeSolverLinearStatic;
using SurgSim::Math::LinearSolveAndInverseDenseMatrix;
// Transform the state with the initial pose
transformState(m_initialState, getPose());
*m_previousState = *m_initialState;
*m_currentState = *m_initialState;
*m_newState = *m_initialState;
*m_finalState = *m_initialState;
// Since the pose is now embedded in the state, reset element and local pose to identity.
setLocalPose(SurgSim::Math::RigidTransform3d::Identity());
std::shared_ptr<SurgSim::Framework::SceneElement> sceneElement = getSceneElement();
if (sceneElement != nullptr)
{
sceneElement->setPose(SurgSim::Math::RigidTransform3d::Identity());
}
// Set the ode solver using the chosen integration scheme
switch (m_integrationScheme)
{
case SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerExplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerExplicitModified>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerImplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_STATIC:
m_odeSolver = std::make_shared<OdeSolverStatic>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4:
m_odeSolver = std::make_shared<OdeSolverRungeKutta4>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerExplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerExplicitModified>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerImplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC:
m_odeSolver = std::make_shared<OdeSolverLinearStatic>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4:
m_odeSolver = std::make_shared<OdeSolverLinearRungeKutta4>(this);
break;
default:
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())
<< "Ode solver (integration scheme) not initialized, the integration scheme is invalid";
return false;
}
// No assumption is made on the linear solver, we instantiate a general dense matrix solver
m_odeSolver->setLinearSolver(std::make_shared<LinearSolveAndInverseDenseMatrix>());
return true;
}
}; // namespace Physics
}; // namespace SurgSim
<commit_msg>Remove remaining uses of resizeVector and resizeMatrix<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2012-2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Framework/PoseComponent.h"
#include "SurgSim/Math/MathConvert.h"
#include "SurgSim/Math/OdeSolverEulerExplicit.h"
#include "SurgSim/Math/OdeSolverEulerExplicitModified.h"
#include "SurgSim/Math/OdeSolverEulerImplicit.h"
#include "SurgSim/Math/OdeSolverRungeKutta4.h"
#include "SurgSim/Math/OdeSolverLinearEulerExplicit.h"
#include "SurgSim/Math/OdeSolverLinearEulerExplicitModified.h"
#include "SurgSim/Math/OdeSolverLinearEulerImplicit.h"
#include "SurgSim/Math/OdeSolverLinearRungeKutta4.h"
#include "SurgSim/Math/OdeSolverLinearStatic.h"
#include "SurgSim/Math/OdeSolverStatic.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
namespace SurgSim
{
namespace Physics
{
DeformableRepresentation::DeformableRepresentation(const std::string& name) :
Representation(name),
SurgSim::Math::OdeEquation(),
m_numDofPerNode(0),
m_integrationScheme(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)
{
SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, SurgSim::Math::IntegrationScheme, IntegrationScheme,
getIntegrationScheme, setIntegrationScheme);
SURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, std::shared_ptr<SurgSim::Collision::Representation>,
CollisionRepresentation, getCollisionRepresentation, setCollisionRepresentation);
}
DeformableRepresentation::~DeformableRepresentation()
{
}
void DeformableRepresentation::resetState()
{
Representation::resetState();
// Reminder: m_initialState is being held in OdeEquation
*m_currentState = *m_initialState;
*m_previousState = *m_initialState;
// m_newState does not need to be reset, it is a temporary variable
*m_finalState = *m_initialState;
}
void DeformableRepresentation::setInitialState(
std::shared_ptr<SurgSim::Math::OdeState> initialState)
{
// This initializes and allocates the m_initialState data member
m_initialState = initialState;
m_previousState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_currentState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_newState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
m_finalState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);
// Set the representation number of degree of freedom
setNumDof(m_initialState->getNumDof());
m_externalGeneralizedForce.resize(getNumDof());
m_externalGeneralizedStiffness.resize(getNumDof(), getNumDof());
m_externalGeneralizedDamping.resize(getNumDof(), getNumDof());
m_externalGeneralizedForce.setZero();
m_externalGeneralizedStiffness.setZero();
m_externalGeneralizedDamping.setZero();
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getCurrentState() const
{
return m_currentState;
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getPreviousState() const
{
return m_previousState;
}
const std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getFinalState() const
{
return m_finalState;
}
size_t DeformableRepresentation::getNumDofPerNode() const
{
return m_numDofPerNode;
}
void DeformableRepresentation::setIntegrationScheme(SurgSim::Math::IntegrationScheme integrationScheme)
{
SURGSIM_ASSERT(!isAwake()) << "You cannot set the integration scheme after the component has been awoken";
m_integrationScheme = integrationScheme;
}
SurgSim::Math::IntegrationScheme DeformableRepresentation::getIntegrationScheme() const
{
return m_integrationScheme;
}
const SurgSim::Math::Vector& DeformableRepresentation::getExternalGeneralizedForce() const
{
return m_externalGeneralizedForce;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedStiffness() const
{
return m_externalGeneralizedStiffness;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedDamping() const
{
return m_externalGeneralizedDamping;
}
const SurgSim::Math::Matrix& DeformableRepresentation::getComplianceMatrix() const
{
SURGSIM_ASSERT(m_odeSolver) << "Ode solver not initialized, it should have been initialized on wake-up";
return m_odeSolver->getCompliance();
}
void DeformableRepresentation::update(double dt)
{
if (! isActive())
{
return;
}
SURGSIM_ASSERT(m_odeSolver != nullptr) <<
"Ode solver has not been set yet. Did you call beforeUpdate() ?";
SURGSIM_ASSERT(m_initialState != nullptr) <<
"Initial state has not been set yet. Did you call setInitialState() ?";
// Solve the ode
m_odeSolver->solve(dt, *m_currentState, m_newState.get());
// Back up the current state into the previous state (by swapping)
m_currentState.swap(m_previousState);
// Make the new state, the current state (by swapping)
m_currentState.swap(m_newState);
if (!m_currentState->isValid())
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated :" << std::endl
<< "position=(" << m_currentState->getPositions().transpose() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities().transpose() << ")" << std::endl;
setActive(false);
}
}
void DeformableRepresentation::afterUpdate(double dt)
{
if (! isActive())
{
return;
}
driveSceneElementPose(SurgSim::Math::RigidTransform3d::Identity());
// Back up the current state into the final state
*m_finalState = *m_currentState;
// Reset the external generalized force, stiffness and damping
m_externalGeneralizedForce.setZero();
m_externalGeneralizedStiffness.setZero();
m_externalGeneralizedDamping.setZero();
}
void DeformableRepresentation::applyCorrection(double dt,
const Eigen::VectorBlock<SurgSim::Math::Vector>& deltaVelocity)
{
if (!isActive())
{
return;
}
m_currentState->getPositions() += deltaVelocity * dt;
m_currentState->getVelocities() += deltaVelocity;
if (!m_currentState->isValid())
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated :" << std::endl
<< "position=(" << m_currentState->getPositions() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities() << ")" << std::endl;
setActive(false);
}
}
void DeformableRepresentation::deactivateAndReset(void)
{
SURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)
<< getName() << " deactivated and reset:" << std::endl
<< "position=(" << m_currentState->getPositions() << ")" << std::endl
<< "velocity=(" << m_currentState->getVelocities() << ")" << std::endl;
resetState();
setActive(false);
}
void DeformableRepresentation::setCollisionRepresentation(
std::shared_ptr<SurgSim::Collision::Representation> representation)
{
if (m_collisionRepresentation != representation)
{
// If we have an old collision representation clear the dependency if it was a deformable collision
// representation
auto oldCollisionRep =
std::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation);
if (oldCollisionRep != nullptr)
{
oldCollisionRep->setDeformableRepresentation(nullptr);
}
Representation::setCollisionRepresentation(representation);
// If its a RigidCollisionRepresentation connect with this representation
auto newCollisionRep = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(representation);
if (newCollisionRep != nullptr)
{
newCollisionRep->setDeformableRepresentation(
std::static_pointer_cast<DeformableRepresentation>(getSharedPtr()));
}
}
}
bool DeformableRepresentation::doWakeUp()
{
using SurgSim::Math::OdeSolverEulerExplicit;
using SurgSim::Math::OdeSolverEulerExplicitModified;
using SurgSim::Math::OdeSolverEulerImplicit;
using SurgSim::Math::OdeSolverRungeKutta4;
using SurgSim::Math::OdeSolverStatic;
using SurgSim::Math::OdeSolverLinearEulerExplicit;
using SurgSim::Math::OdeSolverLinearEulerExplicitModified;
using SurgSim::Math::OdeSolverLinearEulerImplicit;
using SurgSim::Math::OdeSolverLinearRungeKutta4;
using SurgSim::Math::OdeSolverLinearStatic;
using SurgSim::Math::LinearSolveAndInverseDenseMatrix;
// Transform the state with the initial pose
transformState(m_initialState, getPose());
*m_previousState = *m_initialState;
*m_currentState = *m_initialState;
*m_newState = *m_initialState;
*m_finalState = *m_initialState;
// Since the pose is now embedded in the state, reset element and local pose to identity.
setLocalPose(SurgSim::Math::RigidTransform3d::Identity());
std::shared_ptr<SurgSim::Framework::SceneElement> sceneElement = getSceneElement();
if (sceneElement != nullptr)
{
sceneElement->setPose(SurgSim::Math::RigidTransform3d::Identity());
}
// Set the ode solver using the chosen integration scheme
switch (m_integrationScheme)
{
case SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerExplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerExplicitModified>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverEulerImplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_STATIC:
m_odeSolver = std::make_shared<OdeSolverStatic>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4:
m_odeSolver = std::make_shared<OdeSolverRungeKutta4>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerExplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerExplicitModified>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER:
m_odeSolver = std::make_shared<OdeSolverLinearEulerImplicit>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC:
m_odeSolver = std::make_shared<OdeSolverLinearStatic>(this);
break;
case SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4:
m_odeSolver = std::make_shared<OdeSolverLinearRungeKutta4>(this);
break;
default:
SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())
<< "Ode solver (integration scheme) not initialized, the integration scheme is invalid";
return false;
}
// No assumption is made on the linear solver, we instantiate a general dense matrix solver
m_odeSolver->setLinearSolver(std::make_shared<LinearSolveAndInverseDenseMatrix>());
return true;
}
}; // namespace Physics
}; // namespace SurgSim
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMultiThreaderTest.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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkConfigure.h"
#include "itkMultiThreader.h"
int itkMultiThreaderTest(int argc, char* argv[])
{
// Choose a number of threads.
int numberOfThreads = 10;
if( argc > 1 )
{
const int nt = atoi( argv[1] );
if(nt > 1)
{
numberOfThreads = nt;
}
}
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
itk::MultiThreader::SetGlobalDefaultNumberOfThreads( numberOfThreads );
}
namespace itkMultiThreaderTestHelpers
{
void ThreadedMethod()
{
#ifdef ITK_USE_PTHREADS
// ThreadProcessIDType threadId = pthread_self();
#endif
#ifdef ITK_USE_WIN32_THREADS
// ThreadProcessIDType threadId = GetCurrentThread();
#endif
#ifdef ITK_USE_SPROC
// const ThreadProcessIDType threadId = GetCurrentThread() ??;
#endif
}
} // end of itkMultiThreaderTestHelpers
<commit_msg>ENH: Adding default return value of EXIT_SUCCESS.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkMultiThreaderTest.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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkConfigure.h"
#include "itkMultiThreader.h"
int itkMultiThreaderTest(int argc, char* argv[])
{
// Choose a number of threads.
int numberOfThreads = 10;
if( argc > 1 )
{
const int nt = atoi( argv[1] );
if(nt > 1)
{
numberOfThreads = nt;
}
}
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
itk::MultiThreader::SetGlobalDefaultNumberOfThreads( numberOfThreads );
return EXIT_SUCCESS;
}
namespace itkMultiThreaderTestHelpers
{
void ThreadedMethod()
{
#ifdef ITK_USE_PTHREADS
// ThreadProcessIDType threadId = pthread_self();
#endif
#ifdef ITK_USE_WIN32_THREADS
// ThreadProcessIDType threadId = GetCurrentThread();
#endif
#ifdef ITK_USE_SPROC
// const ThreadProcessIDType threadId = GetCurrentThread() ??;
#endif
}
} // end of itkMultiThreaderTestHelpers
<|endoftext|>
|
<commit_before>/*
* SnowPlow Arduino Tracker
*
* @description Arduino tracker for SnowPlow
* @version 0.0.1
* @author Alex Dean
* @copyright SnowPlow Analytics Ltd
* @license Apache License Version 2.0
*
* Copyright (c) 2012 SnowPlow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
#include <stdlib.h>
#include <SPI.h>
#include "SnowPlowTracker.h"
#include <Ethernet.h>
#include <EthernetClient.h>
#define LOGGING
// Initialize constants
const String SnowPlowTracker::kUserAgent = "Arduino/2.0";
const String SnowPlowTracker::kVersion = "arduino-0.1.0";
/**
* Constructor for SnowPlow class.
*
* @param aEthernet Pointer to the
* EthernetClass (initialised
* outside of this library)
* @param aMac The MAC address of the
* Arduino's WiFi or Ethernet
* Shield
* @param aAppId The SnowPlow application
* ID
**/
SnowPlowTracker::SnowPlowTracker(EthernetClass *aEthernet, const byte* aMac, const String aAppId) {
this->ethernet = aEthernet;
this->mac = (byte*)aMac;
this->appId = aAppId;
}
/**
* Initializes the SnowPlow tracker to
* talk to a collector hosted on
* CloudFront.
*
* @param aCfSubdomain The subdomain
* of the CloudFront collector
* e.g. "d3rkrsqgmqf"
*/
void SnowPlowTracker::initCf(const String aCfSubdomain) {
const String host = aCfSubdomain + String(".cloudfront.net");
this->init(host);
}
/**
* Initializes the SnowPlow tracker
* to speak to a URL-based (self-
* hosted) collector.
*
* @param aHost The hostname of the
* URL hosting the collector
* e.g. tracking.mysite.com
*/
void SnowPlowTracker::initUrl(const String aHost) {
this->init(aHost);
}
/**
* Sets the User Id for this Arduino.
* Overrides the default User Id, which
* is the Arduino's MAC address.
*
* @param @aUserId The new User Id
*/
void SnowPlowTracker::setUserId(String aUserId) {
this->userId = aUserId;
#ifdef LOGGING
Serial.print("SnowPlow User Id updated to: ");
Serial.println(this->userId);
#endif
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is an int.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue An integer value that
* you can use to provide numerical data
* about the user event
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const int aValue) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, String(aValue));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a float.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A double value that
* you can use to provide numerical data
* about the user event
* @param aValuePrecision How many digits to keep
* after the decimal sign
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const double aValue,
const int aValuePrecision) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a float.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A float value that
* you can use to provide numerical data
* about the user event
* @param aValuePrecision How many digits to keep
* after the decimal sign
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const float aValue,
const int aValuePrecision) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a String.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A String value that
* you can use to provide non-numerical data
* about the user event
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const String aValue) const {
#ifdef LOGGING
Serial.println("Tracking event!");
#endif
return SnowPlowTracker::SUCCESS;
}
/**
* Common initialization, called by
* both initCf and initUrl.
*
* @param aHost The hostname of the
* URL hosting the collector
* e.g. tracking.mysite.com
* or d3rkrsqgmqf.cloudfront.net
*/
void SnowPlowTracker::init(const String aHost) {
// Set collectorHost and userId
this->collectorHost = aHost;
this->userId = mac2String(this->mac);
// Boot the Ethernet connection
this->ethernet->begin((byte*)this->mac);
delay(1000); // Wait 1 sec
this->client = new EthernetClient();
#ifdef LOGGING
Serial.print("SnowPlowTracker initialized with collector host: ");
Serial.println(this->collectorHost);
#endif
}
/**
* Converts a MAC address byte array
* into a String. Generated String is
* of the format: "00:01:0A:2E:05:0B"
*
* @param aMac The MAC address, in bytes,
* to convert
* @return the MAC address as a String
*/
String SnowPlowTracker::mac2String(const byte* aMac) {
const int macLength = 6;
String buffer = String();
for (int i = 0; i < macLength; i++) {
buffer += String(aMac[i], HEX);
if (i < macLength - 1) {
buffer += ":";
}
}
return buffer;
}
/**
* Converts a double (or a float)
* into a String. Generated String is
* 1 or more characters long, with the
* number of digits after the decimal
* point specified by `aPrecision`.
*
* @param aDbl The double (or float) to
* convert into a String
* @return the converted String
*/
String SnowPlowTracker::double2String(const double aDouble, const int aPrecision) {
char buffer[25];
dtostrf(aDouble, 1, aPrecision, buffer);
return String(buffer);
}
/*
int SnowPlowTracker::trackEvent(const String category, const String action, const String label, const String property, const float value) const {
// TODO: fix this crap.
char rxdata[150];
int ret = 0;
int stringPos = 0;
boolean DataRx = false;
boolean RxLoop = true;
char c;
unsigned long timeout_time = 0;
unsigned long time_now = 0;
unsigned long timeout = 3000; // 3 seconds
String myDataString = ""; // Allocate for actual data sent
if (client->connect(serverName,80)) {
if (client->connected()) {
client->println("GET /i HTTP/1.1");
client->print("Host: ");
client->println(this->collectorUrl);
client->print("User-Agent: ");
client->println(kUserAgent);
client->println();
// TODO: check if we need more headers.
// Read from the nic
//
timeout_time = millis()+ timeout;
while ((timeout_time > time_now) && RxLoop) {
if (client->available()) {
if (!DataRx)
DataRx= true;
c = client->read();
rxdata[stringPos] = c;
stringPos += 1;
} else {
rxdata[stringPos] = 0;
if (DataRx) {
DataRx= false;
RxLoop = false;
ret=1;
}
}//else
time_now = millis();
}// while ((timeout_time > time_now) && RxLoop) {
client->stop();
}
}// if (client->connect(serverName,80)) {
// Return updated status code
return ret;
}
*/<commit_msg>Doco tweak<commit_after>/*
* SnowPlow Arduino Tracker
*
* @description Arduino tracker for SnowPlow
* @version 0.0.1
* @author Alex Dean
* @copyright SnowPlow Analytics Ltd
* @license Apache License Version 2.0
*
* Copyright (c) 2012 SnowPlow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
#include <stdlib.h>
#include <SPI.h>
#include "SnowPlowTracker.h"
#include <Ethernet.h>
#include <EthernetClient.h>
#define LOGGING
// Initialize constants
const String SnowPlowTracker::kUserAgent = "Arduino/2.0";
const String SnowPlowTracker::kVersion = "arduino-0.1.0";
/**
* Constructor for the SnowPlowTracker
* class.
*
* @param aEthernet Pointer to the
* EthernetClass (initialised
* outside of this library)
* @param aMac The MAC address of the
* Arduino's WiFi or Ethernet
* Shield
* @param aAppId The SnowPlow application
* ID
**/
SnowPlowTracker::SnowPlowTracker(EthernetClass *aEthernet, const byte* aMac, const String aAppId) {
this->ethernet = aEthernet;
this->mac = (byte*)aMac;
this->appId = aAppId;
}
/**
* Initializes the SnowPlow tracker to
* talk to a collector hosted on
* CloudFront.
*
* @param aCfSubdomain The subdomain
* of the CloudFront collector
* e.g. "d3rkrsqgmqf"
*/
void SnowPlowTracker::initCf(const String aCfSubdomain) {
const String host = aCfSubdomain + String(".cloudfront.net");
this->init(host);
}
/**
* Initializes the SnowPlow tracker
* to speak to a URL-based (self-
* hosted) collector.
*
* @param aHost The hostname of the
* URL hosting the collector
* e.g. tracking.mysite.com
*/
void SnowPlowTracker::initUrl(const String aHost) {
this->init(aHost);
}
/**
* Sets the User Id for this Arduino.
* Overrides the default User Id, which
* is the Arduino's MAC address.
*
* @param @aUserId The new User Id
*/
void SnowPlowTracker::setUserId(String aUserId) {
this->userId = aUserId;
#ifdef LOGGING
Serial.print("SnowPlow User Id updated to: ");
Serial.println(this->userId);
#endif
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is an int.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue An integer value that
* you can use to provide numerical data
* about the user event
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const int aValue) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, String(aValue));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a float.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A double value that
* you can use to provide numerical data
* about the user event
* @param aValuePrecision How many digits to keep
* after the decimal sign
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const double aValue,
const int aValuePrecision) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a float.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A float value that
* you can use to provide numerical data
* about the user event
* @param aValuePrecision How many digits to keep
* after the decimal sign
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const float aValue,
const int aValuePrecision) const {
// Cast aValue to String and call appropriate trackEvent
trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));
}
/**
* Tracks a structured event to a
* SnowPlow collector: version
* where the value field is a String.
*
* @param aCategory The name you supply for
* the group of objects you want to track
* @param aAction A string that is uniquely
* paired with each category, and commonly
* used to define the type of user
* interaction for the web object
* @param aLabel An optional string
* to provide additional dimensions to the
* event data
* @param aProperty An optional string
* describing the object or the action
* performed on it. This might be the
* quantity of an item added to basket
* @param aValue A String value that
* you can use to provide non-numerical data
* about the user event
* @return An integer indicating the success/failure
* of logging the event to SnowPlow
*/
int SnowPlowTracker::trackEvent(
const String aCategory,
const String aAction,
const String aLabel,
const String aProperty,
const String aValue) const {
#ifdef LOGGING
Serial.println("Tracking event!");
#endif
return SnowPlowTracker::SUCCESS;
}
/**
* Common initialization, called by
* both initCf and initUrl.
*
* @param aHost The hostname of the
* URL hosting the collector
* e.g. tracking.mysite.com
* or d3rkrsqgmqf.cloudfront.net
*/
void SnowPlowTracker::init(const String aHost) {
// Set collectorHost and userId
this->collectorHost = aHost;
this->userId = mac2String(this->mac);
// Boot the Ethernet connection
this->ethernet->begin((byte*)this->mac);
delay(1000); // Wait 1 sec
this->client = new EthernetClient();
#ifdef LOGGING
Serial.print("SnowPlowTracker initialized with collector host: ");
Serial.println(this->collectorHost);
#endif
}
/**
* Converts a MAC address byte array
* into a String. Generated String is
* of the format: "00:01:0A:2E:05:0B"
*
* @param aMac The MAC address, in bytes,
* to convert
* @return the MAC address as a String
*/
String SnowPlowTracker::mac2String(const byte* aMac) {
const int macLength = 6;
String buffer = String();
for (int i = 0; i < macLength; i++) {
buffer += String(aMac[i], HEX);
if (i < macLength - 1) {
buffer += ":";
}
}
return buffer;
}
/**
* Converts a double (or a float)
* into a String. Generated String is
* 1 or more characters long, with the
* number of digits after the decimal
* point specified by `aPrecision`.
*
* @param aDbl The double (or float) to
* convert into a String
* @return the converted String
*/
String SnowPlowTracker::double2String(const double aDouble, const int aPrecision) {
char buffer[25];
dtostrf(aDouble, 1, aPrecision, buffer);
return String(buffer);
}
/*
int SnowPlowTracker::trackEvent(const String category, const String action, const String label, const String property, const float value) const {
// TODO: fix this crap.
char rxdata[150];
int ret = 0;
int stringPos = 0;
boolean DataRx = false;
boolean RxLoop = true;
char c;
unsigned long timeout_time = 0;
unsigned long time_now = 0;
unsigned long timeout = 3000; // 3 seconds
String myDataString = ""; // Allocate for actual data sent
if (client->connect(serverName,80)) {
if (client->connected()) {
client->println("GET /i HTTP/1.1");
client->print("Host: ");
client->println(this->collectorUrl);
client->print("User-Agent: ");
client->println(kUserAgent);
client->println();
// TODO: check if we need more headers.
// Read from the nic
//
timeout_time = millis()+ timeout;
while ((timeout_time > time_now) && RxLoop) {
if (client->available()) {
if (!DataRx)
DataRx= true;
c = client->read();
rxdata[stringPos] = c;
stringPos += 1;
} else {
rxdata[stringPos] = 0;
if (DataRx) {
DataRx= false;
RxLoop = false;
ret=1;
}
}//else
time_now = millis();
}// while ((timeout_time > time_now) && RxLoop) {
client->stop();
}
}// if (client->connect(serverName,80)) {
// Return updated status code
return ret;
}
*/
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.